From 5060a3eb2a4de0fbca4c2756e29539088d51acbc Mon Sep 17 00:00:00 2001 From: xuerunlong Date: Wed, 31 Jul 2024 15:11:09 +0800 Subject: [PATCH 01/44] =?UTF-8?q?=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xuerunlong --- interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp | 1 + interfaces/kits/js/src/mod_fs/properties/stat.cpp | 1 - interfaces/kits/js/src/mod_fs/properties/truncate.cpp | 1 - 3 files changed, 1 insertion(+), 2 deletions(-) diff --git a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp index 4a0dc7772..f351f3b56 100644 --- a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp @@ -1310,6 +1310,7 @@ napi_value FileNExporter::WriteArrayBuffer(napi_env env, napi_callback_info info if (!CheckUri(env, path)) { CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, bufferRef); delete asyncCallbackInfo; return nullptr; } diff --git a/interfaces/kits/js/src/mod_fs/properties/stat.cpp b/interfaces/kits/js/src/mod_fs/properties/stat.cpp index 5153e8332..08de2f1e9 100644 --- a/interfaces/kits/js/src/mod_fs/properties/stat.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/stat.cpp @@ -44,7 +44,6 @@ static tuple ParseJsFile(napi_env env, napi_value pathOrFdFromJs auto fdg = CreateUniquePtr(fd, false); if (fdg == nullptr) { HILOGE("Failed to request heap memory."); - close(fd); NError(ENOMEM).ThrowErr(env); return { false, FileInfo { false, {}, {} } }; } diff --git a/interfaces/kits/js/src/mod_fs/properties/truncate.cpp b/interfaces/kits/js/src/mod_fs/properties/truncate.cpp index 2749f259e..3e2837433 100644 --- a/interfaces/kits/js/src/mod_fs/properties/truncate.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/truncate.cpp @@ -42,7 +42,6 @@ static tuple ParseJsFile(napi_env env, napi_value pathOrFdFromJs auto fdg = CreateUniquePtr(fd, false); if (fdg == nullptr) { HILOGE("Failed to request heap memory."); - close(fd); NError(ENOMEM).ThrowErr(env); return { false, FileInfo { false, {}, {} } }; } -- Gitee From 9a4f9fad355897e599976d8594f013b1662388cd Mon Sep 17 00:00:00 2001 From: wangluyao Date: Thu, 1 Aug 2024 18:05:22 +0800 Subject: [PATCH 02/44] =?UTF-8?q?open=E6=8E=A5=E5=8F=A3=E6=89=93=E5=BC=80m?= =?UTF-8?q?eida=E9=BB=98=E8=AE=A4=E4=BD=BF=E7=94=A8datashare=E8=AE=BF?= =?UTF-8?q?=E9=97=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangluyao --- .../kits/js/src/mod_fs/properties/open.cpp | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/properties/open.cpp b/interfaces/kits/js/src/mod_fs/properties/open.cpp index 3ec0bb441..811fb8f68 100644 --- a/interfaces/kits/js/src/mod_fs/properties/open.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/open.cpp @@ -163,23 +163,22 @@ static tuple OpenByFileDataUri(Uri &uri, const string &uriStr, unsi string bundleName = uri.GetAuthority(); AppFileService::ModuleFileUri::FileUri fileUri(uriStr); string realPath = fileUri.GetRealPath(); - if ((bundleName == MEDIA || bundleName == DOCS) && access(realPath.c_str(), F_OK) != 0) { + if (bundleName == MEDIA) { int res = OpenFileByDatashare(uri.ToString(), mode); if (res < 0) { HILOGE("Failed to open file by Datashare error %{public}d", res); } return { res, uri.ToString() }; + } else if (bundleName == DOCS && access(realPath.c_str(), F_OK) != 0) { + int res = OpenFileByDatashare(uri.ToString(), mode); + if (res < 0) { + HILOGE("Failed to open file by Datashare error %{public}d", res); + } + return { ENOENT, uri.ToString() }; } int ret = OpenFileByPath(realPath, mode); if (ret < 0) { - if (bundleName == MEDIA) { - ret = OpenFileByDatashare(uriStr, mode); - if (ret < 0) { - HILOGE("Failed to open file by Datashare error %{public}d", ret); - } - } else { - HILOGE("Failed to open file for libuv error %{public}d", ret); - } + HILOGE("Failed to open file for libuv error %{public}d", ret); } return { ret, uriStr }; } -- Gitee From 525923f9d7c282ba9bb28d80ea5ddffe55fc4d8f Mon Sep 17 00:00:00 2001 From: yangli <“yangli228@huawei.com”> Date: Sat, 3 Aug 2024 14:55:37 +0800 Subject: [PATCH 03/44] =?UTF-8?q?dfs=E9=9B=B7=E8=BE=BE=E6=89=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangli <“yangli228@huawei.com”> --- bundle.json | 1 + interfaces/kits/js/BUILD.gn | 2 + interfaces/kits/js/src/common/dfs_event_dfx.h | 74 ++++++++++++++++ .../copy_listener/trans_listener.cpp | 87 +++++++++++++++---- .../properties/copy_listener/trans_listener.h | 7 +- 5 files changed, 151 insertions(+), 20 deletions(-) create mode 100644 interfaces/kits/js/src/common/dfs_event_dfx.h diff --git a/bundle.json b/bundle.json index ee3dcf798..60c317e0e 100644 --- a/bundle.json +++ b/bundle.json @@ -36,6 +36,7 @@ "dfs_service", "eventhandler", "hilog", + "hisysevent", "hitrace", "ipc", "init", diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index fa41f4cb3..5843f1bfc 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -247,6 +247,7 @@ ohos_shared_library("fs") { "ability_runtime:ability_manager", "ability_runtime:abilitykit_native", "ability_runtime:extensionkit_native", + "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", "app_file_service:fileuri_native", "bundle_framework:appexecfwk_base", @@ -255,6 +256,7 @@ ohos_shared_library("fs") { "data_share:datashare_common", "data_share:datashare_consumer", "dfs_service:distributed_file_daemon_kit_inner", + "hisysevent:libhisysevent", "hitrace:hitrace_meter", "ipc:ipc_core", "samgr:samgr_proxy", diff --git a/interfaces/kits/js/src/common/dfs_event_dfx.h b/interfaces/kits/js/src/common/dfs_event_dfx.h new file mode 100644 index 000000000..c4e3491f1 --- /dev/null +++ b/interfaces/kits/js/src/common/dfs_event_dfx.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDFILE_DFS_EVENT_DFX_H +#define DISTRIBUTEDFILE_DFS_EVENT_DFX_H + +#include "hisysevent.h" +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace RadarReporter { +using namespace OHOS::HiviewDFX; +static constexpr int DIST_DATA_MGR_SYS_ID = 0xd; +static constexpr int DFS_ID = 13; +enum BizScene : std::int32_t { + DFX_SET_DFS = 1, +}; + +enum BizStageSetPasteboard : std::int32_t { + DFX_SET_BIZ_SCENE = 1, +}; + +enum StageRes : std::int32_t { + DFX_IDLE = 0, + DFX_SUCCESS = 1, + DFX_FAILED = 2, + DFX_CANCELLED = 3, +}; + +enum BizState : std::int32_t { + DFX_BEGIN = 1, + DFX_END = 2, +}; + +enum ErrorCode : std::int32_t { + DFS_ERROR = (DIST_DATA_MGR_SYS_ID << 21) | (DFS_ID << 16), + PERPARE_COPY_SESSION_ERROR, + COPY_TO_SANDBOX_ERROR, + SEND_FILE_ERROR, +}; + +static constexpr char DOMAIN[] = "DISTDATAMGR"; +constexpr const char* EVENT_NAME = "DISTRIBUTED_DFS_BEHAVIOR"; +constexpr const char* ORG_PKG = "distributedfile"; +constexpr const char* BIZ_STATE = "BIZ_STATE"; +constexpr const char* ERROR_CODE = "ERROR_CODE"; +constexpr const char* PACKAGE_NAME = "PACKAGE_NAME"; +constexpr const char* CONCURRENT_ID = "CONCURRENT_ID"; +static constexpr HiviewDFX::HiSysEvent::EventType TYPE = HiviewDFX::HiSysEvent::EventType::BEHAVIOR; + +#define RADAR_REPORT(bizScene, bizStage, stageRes, ...) \ +({ \ + HiSysEventWrite(RadarReporter::DOMAIN, RadarReporter::EVENT_NAME, RadarReporter::TYPE, \ + "ORG_PKG", RadarReporter::ORG_PKG, "FUNC", __FUNCTION__, \ + "BIZ_SCENE", bizScene, "BIZ_STAGE", bizStage, "STAGE_RES", stageRes, \ + ##__VA_ARGS__); \ +}) +} // namespace RadarReporter +} // namespace ModuleFileIO +} // namespace MiscServices +} // namespace OHOS +#endif //DISTRIBUTEDDATAMGR_DFS_EVENT_DFX_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp index ebe7e0c38..e385473cc 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp @@ -19,20 +19,26 @@ #include #include +#include "accesstoken_kit.h" #include "ipc_skeleton.h" +#include "iremote_object.h" #include "sandbox_helper.h" #include "uri.h" #include "n_error.h" +#include "dfs_event_dfx.h" namespace OHOS { namespace FileManagement { namespace ModuleFileIO { using namespace OHOS::AppFileService; using namespace AppFileService::ModuleFileUri; +using HapTokenInfo = OHOS::Security::AccessToken::HapTokenInfo; +using AccessTokenKit = OHOS::Security::AccessToken::AccessTokenKit; const std::string NETWORK_PARA = "?networkid="; const std::string FILE_MANAGER_AUTHORITY = "docs"; const std::string MEDIA_AUTHORITY = "media"; const std::string DISTRIBUTED_PATH = "/data/storage/el2/distributedfiles/"; +std::atomic TransListener::getSequenceId_ = 0; void TransListener::RmDir(const std::string &path) { @@ -59,10 +65,54 @@ std::string TransListener::CreateDfsCopyPath() return random; } -NError TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std::string &destUri, +NError TransListener::HandleCopyFailure(CopyEvent ©Event, const Storage::DistributedFile::HmdfsInfo &info, + const std::string &disSandboxPath, const std::string ¤tId) +{ + if (info.authority != FILE_MANAGER_AUTHORITY && info.authority != MEDIA_AUTHORITY) { + RmDir(disSandboxPath); + } + auto it = softbusErr2ErrCodeTable.find(transListener->copyEvent_.errorCode); + if (it == softbusErr2ErrCodeTable.end()) { + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, + RadarReporter::SEND_FILE_ERROR, RadarReporter::CONCURRENT_ID, currentId); + return NError(EIO); + } + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, + RadarReporter::SEND_FILE_ERROR, RadarReporter::CONCURRENT_ID, currentId); + return NError(it->second); +} + +int TransListener::WaitForCopyResult(TransListener* transListener) +{ + if (transListener == nullptr) { + HILOGE("transListener is nullptr."); + return FAILED; + } + std::unique_lock lock(transListener->cvMutex_); + transListener->cv_.wait(lock, [&transListener]() { + return transListener->copyEvent_.copyResult == SUCCESS || + transListener->copyEvent_.copyResult == FAILED; + }); + return transListener->copyEvent_.copyResult; +} + +TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std::string &destUri, std::shared_ptr fileInfos, std::shared_ptr callback) { HILOGI("CopyFileFromSoftBus begin."); + std::string currentId = "GetPastData_" + std::string(getpid() + "_" + std::to_string(getSequenceId_)); + ++getSequenceId_; + HapTokenInfo hapTokenInfo; + int result = AccessTokenKit::GetHapTokenInfo(IPCSelfTokenID(), hapTokenInfo); + if (result != Security::AccessToken::AccessTokenKitRet::RET_SUCCESS) { + HILOGE("GetHapTokenInfo failed, errCode = %{public}d", result); + return NError(EIO); + } + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, + RadarReporter::BIZ_STATE, RadarReporter::DFX_BEGIN, RadarReporter::PACKAGE_NAME, hapTokenInfo.bundleName, + RadarReporter::CONCURRENT_ID, currentId); sptr transListener = new (std::nothrow) TransListener(); if (transListener == nullptr) { HILOGE("new trans listener failed"); @@ -77,34 +127,27 @@ NError TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std:: std::string disSandboxPath; auto ret = PrepareCopySession(srcUri, destUri, transListener, info, disSandboxPath); if (ret != ERRNO_NOERR) { + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, + RadarReporter::PERPARE_COPY_SESSION_ERROR, RadarReporter::CONCURRENT_ID, currentId); HILOGE("PrepareCopySession failed, ret = %{public}d.", ret); return NError(EIO); } if (fileInfos->taskSignal != nullptr) { fileInfos->taskSignal->SetFileInfoOfRemoteTask(info.sessionName, fileInfos->srcPath); } - std::unique_lock lock(transListener->cvMutex_); - transListener->cv_.wait(lock, [&transListener]() { - return transListener->copyEvent_.copyResult == SUCCESS || - transListener->copyEvent_.copyResult == FAILED; - }); - HILOGI("dfs PrepareSession Finish, result is %{public}d", transListener->copyEvent_.copyResult); - if (transListener->copyEvent_.copyResult == FAILED) { - if (info.authority != FILE_MANAGER_AUTHORITY && info.authority != MEDIA_AUTHORITY) { - RmDir(disSandboxPath); - } - auto it = softbusErr2ErrCodeTable.find(transListener->copyEvent_.errorCode); - if (it == softbusErr2ErrCodeTable.end()) { - return NError(EIO); - } - return NError(it->second); + auto copyResult = WaitForCopyResult(transListener); + if (copyResult == FAILED) { + return HandleCopyFailure(transListener->copyEvent_, info, disSandboxPath, currentId); } if (info.authority == FILE_MANAGER_AUTHORITY || info.authority == MEDIA_AUTHORITY) { HILOGW("Public or media path not copy"); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::CONCURRENT_ID, currentId); return NError(ERRNO_NOERR); } - ret = CopyToSandBox(srcUri, disSandboxPath, info.sandboxPath); + ret = CopyToSandBox(srcUri, disSandboxPath, info.sandboxPath, currentId); RmDir(disSandboxPath); if (ret != ERRNO_NOERR) { HILOGE("CopyToSandBox failed, ret = %{public}d.", ret); @@ -156,7 +199,7 @@ int32_t TransListener::PrepareCopySession(const std::string &srcUri, } int32_t TransListener::CopyToSandBox(const std::string &srcUri, const std::string &disSandboxPath, - const std::string &sandboxPath) + const std::string &sandboxPath, const std::string ¤tId) { std::error_code errCode; if (std::filesystem::exists(sandboxPath) && std::filesystem::is_directory(sandboxPath)) { @@ -165,6 +208,9 @@ int32_t TransListener::CopyToSandBox(const std::string &srcUri, const std::strin std::filesystem::copy_options::recursive | std::filesystem::copy_options::update_existing, errCode); if (errCode.value() != 0) { HILOGE("Copy dir failed: errCode: %{public}d", errCode.value()); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, + RadarReporter::COPY_TO_SANDBOX_ERROR, RadarReporter::CONCURRENT_ID, currentId); return EIO; } } else { @@ -180,10 +226,15 @@ int32_t TransListener::CopyToSandBox(const std::string &srcUri, const std::strin errCode); if (errCode.value() != 0) { HILOGE("Copy file failed: errCode: %{public}d", errCode.value()); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, + RadarReporter::COPY_TO_SANDBOX_ERROR, RadarReporter::CONCURRENT_ID, currentId); return EIO; } } HILOGI("Copy file success."); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::CONCURRENT_ID, currentId); return ERRNO_NOERR; } diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.h b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.h index 95c63d930..553864575 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.h +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.h @@ -50,13 +50,16 @@ private: static std::string CreateDfsCopyPath(); static std::string GetFileName(const std::string &path); static int32_t CopyToSandBox(const std::string &srcUri, const std::string &disSandboxPath, - const std::string &sandboxPath); + const std::string &sandboxPath, const std::string ¤tId); static int32_t PrepareCopySession(const std::string &srcUri, const std::string &destUri, TransListener* transListener, Storage::DistributedFile::HmdfsInfo &info, std::string &disSandboxPath); - + static NError HandleCopyFailure(CopyEvent ©Event, const Storage::DistributedFile::HmdfsInfo &info, + const std::string &disSandboxPath, const std::string ¤tId); + static int WaitForCopyResult(TransListener* transListener); + staiic std::atomic getSequenceId_; std::mutex cvMutex_; std::condition_variable cv_; CopyEvent copyEvent_; -- Gitee From 793ed0a80740f2915873eca6c5eb824e9fd1ba10 Mon Sep 17 00:00:00 2001 From: yangli <“yangli228@huawei.com”> Date: Sat, 3 Aug 2024 15:27:22 +0800 Subject: [PATCH 04/44] =?UTF-8?q?dfs=E9=9B=B7=E8=BE=BE=E6=89=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangli <“yangli228@huawei.com”> --- interfaces/kits/js/src/common/dfs_event_dfx.h | 6 +- .../copy_listener/trans_listener.cpp | 57 +++++++++---------- .../properties/copy_listener/trans_listener.h | 2 +- 3 files changed, 32 insertions(+), 33 deletions(-) diff --git a/interfaces/kits/js/src/common/dfs_event_dfx.h b/interfaces/kits/js/src/common/dfs_event_dfx.h index c4e3491f1..3f179b78a 100644 --- a/interfaces/kits/js/src/common/dfs_event_dfx.h +++ b/interfaces/kits/js/src/common/dfs_event_dfx.h @@ -28,7 +28,7 @@ enum BizScene : std::int32_t { DFX_SET_DFS = 1, }; -enum BizStageSetPasteboard : std::int32_t { +enum BizStageSetDfs : std::int32_t { DFX_SET_BIZ_SCENE = 1, }; @@ -46,7 +46,7 @@ enum BizState : std::int32_t { enum ErrorCode : std::int32_t { DFS_ERROR = (DIST_DATA_MGR_SYS_ID << 21) | (DFS_ID << 16), - PERPARE_COPY_SESSION_ERROR, + PREPARE_COPY_SESSION_ERROR, COPY_TO_SANDBOX_ERROR, SEND_FILE_ERROR, }; @@ -69,6 +69,6 @@ static constexpr HiviewDFX::HiSysEvent::EventType TYPE = HiviewDFX::HiSysEvent:: }) } // namespace RadarReporter } // namespace ModuleFileIO -} // namespace MiscServices +} // namespace FileManagement } // namespace OHOS #endif //DISTRIBUTEDDATAMGR_DFS_EVENT_DFX_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp index e385473cc..465d1d9ba 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp @@ -66,28 +66,28 @@ std::string TransListener::CreateDfsCopyPath() } NError TransListener::HandleCopyFailure(CopyEvent ©Event, const Storage::DistributedFile::HmdfsInfo &info, - const std::string &disSandboxPath, const std::string ¤tId) + const std::string &disSandboxPath, const std::string ¤tId) { if (info.authority != FILE_MANAGER_AUTHORITY && info.authority != MEDIA_AUTHORITY) { RmDir(disSandboxPath); } - auto it = softbusErr2ErrCodeTable.find(transListener->copyEvent_.errorCode); + auto it = softbusErr2ErrCodeTable.find(copyEvent_.errorCode); if (it == softbusErr2ErrCodeTable.end()) { - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, - RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, - RadarReporter::SEND_FILE_ERROR, RadarReporter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReporoter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_FAILED, + RadarReporoter::BIZ_STATE, RadarReporoter::DFX_END, RadarReporoter::ERROR_CODE, + RadarReporoter::SEND_FILE_ERROR, RadarReporoter::CONCURRENT_ID, currentId); return NError(EIO); } - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, - RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, - RadarReporter::SEND_FILE_ERROR, RadarReporter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_FAILED, + RadarReporoter::BIZ_STATE, RadarReporoter::DFX_END, RadarReporoter::ERROR_CODE, + RadarReporoter::SEND_FILE_ERROR, RadarReporoter::CONCURRENT_ID, currentId); return NError(it->second); } int TransListener::WaitForCopyResult(TransListener* transListener) { if (transListener == nullptr) { - HILOGE("transListener is nullptr."); + HILOGE("transListener is nullptr"); return FAILED; } std::unique_lock lock(transListener->cvMutex_); @@ -98,21 +98,21 @@ int TransListener::WaitForCopyResult(TransListener* transListener) return transListener->copyEvent_.copyResult; } -TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std::string &destUri, +NError TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std::string &destUri, std::shared_ptr fileInfos, std::shared_ptr callback) { HILOGI("CopyFileFromSoftBus begin."); - std::string currentId = "GetPastData_" + std::string(getpid() + "_" + std::to_string(getSequenceId_)); + std::string currentId = "GetPasteData_" + std::to_string(getpid()) + "_" + std::to_string(getSequenceId_); ++getSequenceId_; HapTokenInfo hapTokenInfo; - int result = AccessTokenKit::GetHapTokenInfo(IPCSelfTokenID(), hapTokenInfo); + int result = AccessTokenKit::GetHapTokenInfo(IPCSkenleton::GetSelfTokenID(), hapTokenInfo); if (result != Security::AccessToken::AccessTokenKitRet::RET_SUCCESS) { HILOGE("GetHapTokenInfo failed, errCode = %{public}d", result); return NError(EIO); } - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, - RadarReporter::BIZ_STATE, RadarReporter::DFX_BEGIN, RadarReporter::PACKAGE_NAME, hapTokenInfo.bundleName, - RadarReporter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_SUCCESS, + RadarReporoter::BIZ_STATE, RadarReporoter::DFX_BEGIN, RadarReporoter::PACKAGE_NAME, hapTokenInfo.bundleName, + RadarReporoter::CONCURRENT_ID, currentId); sptr transListener = new (std::nothrow) TransListener(); if (transListener == nullptr) { HILOGE("new trans listener failed"); @@ -127,10 +127,9 @@ TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std::string std::string disSandboxPath; auto ret = PrepareCopySession(srcUri, destUri, transListener, info, disSandboxPath); if (ret != ERRNO_NOERR) { - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, - RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, - RadarReporter::PERPARE_COPY_SESSION_ERROR, RadarReporter::CONCURRENT_ID, currentId); - HILOGE("PrepareCopySession failed, ret = %{public}d.", ret); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_FAILED, + RadarReporoter::BIZ_STATE, RadarReporoter::DFX_END, RadarReporoter::ERROR_CODE, + RadarReporoter::PREPARE_COPY_SESSION_ERROR, RadarReporoter::CONCURRENT_ID, currentId); return NError(EIO); } if (fileInfos->taskSignal != nullptr) { @@ -142,8 +141,8 @@ TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std::string } if (info.authority == FILE_MANAGER_AUTHORITY || info.authority == MEDIA_AUTHORITY) { HILOGW("Public or media path not copy"); - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, - RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_SUCCESS, + RadarReporoter::BIZ_STATE, RadarReporoter::DFX_END, RadarReporoter::CONCURRENT_ID, currentId); return NError(ERRNO_NOERR); } @@ -208,9 +207,9 @@ int32_t TransListener::CopyToSandBox(const std::string &srcUri, const std::strin std::filesystem::copy_options::recursive | std::filesystem::copy_options::update_existing, errCode); if (errCode.value() != 0) { HILOGE("Copy dir failed: errCode: %{public}d", errCode.value()); - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, - RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, - RadarReporter::COPY_TO_SANDBOX_ERROR, RadarReporter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_FAILED, + RadarReporoter::BIZ_STATE, RadarReporoter::DFX_END, RadarReporoter::ERROR_CODE, + RadarReporoter::COPY_TO_SANDBOX_ERROR, RadarReporoter::CONCURRENT_ID, currentId); return EIO; } } else { @@ -226,15 +225,15 @@ int32_t TransListener::CopyToSandBox(const std::string &srcUri, const std::strin errCode); if (errCode.value() != 0) { HILOGE("Copy file failed: errCode: %{public}d", errCode.value()); - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, - RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, - RadarReporter::COPY_TO_SANDBOX_ERROR, RadarReporter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_FAILED, + RadarReporoter::BIZ_STATE, RadarReporoter::DFX_END, RadarReporoter::ERROR_CODE, + RadarReporoter::COPY_TO_SANDBOX_ERROR, RadarReporoter::CONCURRENT_ID, currentId); return EIO; } } HILOGI("Copy file success."); - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, - RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_SUCCESS, + RadarReporoter::BIZ_STATE, RadarReporoter::DFX_END, RadarReporoter::CONCURRENT_ID, currentId); return ERRNO_NOERR; } diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.h b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.h index 553864575..d04335bee 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.h +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.h @@ -59,7 +59,7 @@ private: static NError HandleCopyFailure(CopyEvent ©Event, const Storage::DistributedFile::HmdfsInfo &info, const std::string &disSandboxPath, const std::string ¤tId); static int WaitForCopyResult(TransListener* transListener); - staiic std::atomic getSequenceId_; + static std::atomic getSequenceId_; std::mutex cvMutex_; std::condition_variable cv_; CopyEvent copyEvent_; -- Gitee From 1f7f7fc09b5c2a3d5b0018a0635dac7e43161ad7 Mon Sep 17 00:00:00 2001 From: yangli <“yangli228@huawei.com”> Date: Sat, 3 Aug 2024 15:35:20 +0800 Subject: [PATCH 05/44] =?UTF-8?q?dfs=E9=9B=B7=E8=BE=BE=E6=89=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangli <“yangli228@huawei.com”> --- interfaces/kits/js/src/common/dfs_event_dfx.h | 2 +- .../copy_listener/trans_listener.cpp | 46 +++++++++---------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/interfaces/kits/js/src/common/dfs_event_dfx.h b/interfaces/kits/js/src/common/dfs_event_dfx.h index 3f179b78a..ba3d423b2 100644 --- a/interfaces/kits/js/src/common/dfs_event_dfx.h +++ b/interfaces/kits/js/src/common/dfs_event_dfx.h @@ -71,4 +71,4 @@ static constexpr HiviewDFX::HiSysEvent::EventType TYPE = HiviewDFX::HiSysEvent:: } // namespace ModuleFileIO } // namespace FileManagement } // namespace OHOS -#endif //DISTRIBUTEDDATAMGR_DFS_EVENT_DFX_H \ No newline at end of file +#endif //DISTRIBUTEDFILE_DFS_EVENT_DFX_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp index 465d1d9ba..57e095432 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp @@ -73,14 +73,14 @@ NError TransListener::HandleCopyFailure(CopyEvent ©Event, const Storage::Dis } auto it = softbusErr2ErrCodeTable.find(copyEvent_.errorCode); if (it == softbusErr2ErrCodeTable.end()) { - RADAR_REPORT(RadarReporoter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_FAILED, - RadarReporoter::BIZ_STATE, RadarReporoter::DFX_END, RadarReporoter::ERROR_CODE, - RadarReporoter::SEND_FILE_ERROR, RadarReporoter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, + RadarReporter::SEND_FILE_ERROR, RadarReporter::CONCURRENT_ID, currentId); return NError(EIO); } - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_FAILED, - RadarReporoter::BIZ_STATE, RadarReporoter::DFX_END, RadarReporoter::ERROR_CODE, - RadarReporoter::SEND_FILE_ERROR, RadarReporoter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, + RadarReporter::SEND_FILE_ERROR, RadarReporter::CONCURRENT_ID, currentId); return NError(it->second); } @@ -105,14 +105,14 @@ NError TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std:: std::string currentId = "GetPasteData_" + std::to_string(getpid()) + "_" + std::to_string(getSequenceId_); ++getSequenceId_; HapTokenInfo hapTokenInfo; - int result = AccessTokenKit::GetHapTokenInfo(IPCSkenleton::GetSelfTokenID(), hapTokenInfo); + int result = AccessTokenKit::GetHapTokenInfo(IPCSkeleton::GetSelfTokenID(), hapTokenInfo); if (result != Security::AccessToken::AccessTokenKitRet::RET_SUCCESS) { HILOGE("GetHapTokenInfo failed, errCode = %{public}d", result); return NError(EIO); } - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_SUCCESS, - RadarReporoter::BIZ_STATE, RadarReporoter::DFX_BEGIN, RadarReporoter::PACKAGE_NAME, hapTokenInfo.bundleName, - RadarReporoter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, + RadarReporter::BIZ_STATE, RadarReporter::DFX_BEGIN, RadarReporter::PACKAGE_NAME, hapTokenInfo.bundleName, + RadarReporter::CONCURRENT_ID, currentId); sptr transListener = new (std::nothrow) TransListener(); if (transListener == nullptr) { HILOGE("new trans listener failed"); @@ -127,9 +127,9 @@ NError TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std:: std::string disSandboxPath; auto ret = PrepareCopySession(srcUri, destUri, transListener, info, disSandboxPath); if (ret != ERRNO_NOERR) { - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_FAILED, - RadarReporoter::BIZ_STATE, RadarReporoter::DFX_END, RadarReporoter::ERROR_CODE, - RadarReporoter::PREPARE_COPY_SESSION_ERROR, RadarReporoter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, + RadarReporter::PREPARE_COPY_SESSION_ERROR, RadarReporter::CONCURRENT_ID, currentId); return NError(EIO); } if (fileInfos->taskSignal != nullptr) { @@ -141,8 +141,8 @@ NError TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std:: } if (info.authority == FILE_MANAGER_AUTHORITY || info.authority == MEDIA_AUTHORITY) { HILOGW("Public or media path not copy"); - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_SUCCESS, - RadarReporoter::BIZ_STATE, RadarReporoter::DFX_END, RadarReporoter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::CONCURRENT_ID, currentId); return NError(ERRNO_NOERR); } @@ -207,9 +207,9 @@ int32_t TransListener::CopyToSandBox(const std::string &srcUri, const std::strin std::filesystem::copy_options::recursive | std::filesystem::copy_options::update_existing, errCode); if (errCode.value() != 0) { HILOGE("Copy dir failed: errCode: %{public}d", errCode.value()); - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_FAILED, - RadarReporoter::BIZ_STATE, RadarReporoter::DFX_END, RadarReporoter::ERROR_CODE, - RadarReporoter::COPY_TO_SANDBOX_ERROR, RadarReporoter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, + RadarReporter::COPY_TO_SANDBOX_ERROR, RadarReporter::CONCURRENT_ID, currentId); return EIO; } } else { @@ -225,15 +225,15 @@ int32_t TransListener::CopyToSandBox(const std::string &srcUri, const std::strin errCode); if (errCode.value() != 0) { HILOGE("Copy file failed: errCode: %{public}d", errCode.value()); - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_FAILED, - RadarReporoter::BIZ_STATE, RadarReporoter::DFX_END, RadarReporoter::ERROR_CODE, - RadarReporoter::COPY_TO_SANDBOX_ERROR, RadarReporoter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, + RadarReporter::COPY_TO_SANDBOX_ERROR, RadarReporter::CONCURRENT_ID, currentId); return EIO; } } HILOGI("Copy file success."); - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporoter::DFX_SET_BIZ_SCENE, RadarReporoter::DFX_SUCCESS, - RadarReporoter::BIZ_STATE, RadarReporoter::DFX_END, RadarReporoter::CONCURRENT_ID, currentId); + RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::CONCURRENT_ID, currentId); return ERRNO_NOERR; } -- Gitee From fc7be87a0d723ab2bb25ac56a9f88f0664e610d6 Mon Sep 17 00:00:00 2001 From: yangli <“yangli228@huawei.com”> Date: Sat, 3 Aug 2024 15:39:44 +0800 Subject: [PATCH 06/44] =?UTF-8?q?dfs=E9=9B=B7=E8=BE=BE=E6=89=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangli <“yangli228@huawei.com”> --- .../properties/copy_listener/trans_listener.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp index 57e095432..7fa5b39d2 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp @@ -71,14 +71,14 @@ NError TransListener::HandleCopyFailure(CopyEvent ©Event, const Storage::Dis if (info.authority != FILE_MANAGER_AUTHORITY && info.authority != MEDIA_AUTHORITY) { RmDir(disSandboxPath); } - auto it = softbusErr2ErrCodeTable.find(copyEvent_.errorCode); + auto it = softbusErr2ErrCodeTable.find(copyEvent.errorCode); if (it == softbusErr2ErrCodeTable.end()) { RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, RadarReporter::SEND_FILE_ERROR, RadarReporter::CONCURRENT_ID, currentId); return NError(EIO); } - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, RadarReporter::SEND_FILE_ERROR, RadarReporter::CONCURRENT_ID, currentId); return NError(it->second); @@ -110,7 +110,7 @@ NError TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std:: HILOGE("GetHapTokenInfo failed, errCode = %{public}d", result); return NError(EIO); } - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, + RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, RadarReporter::BIZ_STATE, RadarReporter::DFX_BEGIN, RadarReporter::PACKAGE_NAME, hapTokenInfo.bundleName, RadarReporter::CONCURRENT_ID, currentId); sptr transListener = new (std::nothrow) TransListener(); @@ -127,7 +127,7 @@ NError TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std:: std::string disSandboxPath; auto ret = PrepareCopySession(srcUri, destUri, transListener, info, disSandboxPath); if (ret != ERRNO_NOERR) { - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, RadarReporter::PREPARE_COPY_SESSION_ERROR, RadarReporter::CONCURRENT_ID, currentId); return NError(EIO); @@ -141,7 +141,7 @@ NError TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std:: } if (info.authority == FILE_MANAGER_AUTHORITY || info.authority == MEDIA_AUTHORITY) { HILOGW("Public or media path not copy"); - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, + RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::CONCURRENT_ID, currentId); return NError(ERRNO_NOERR); } @@ -207,7 +207,7 @@ int32_t TransListener::CopyToSandBox(const std::string &srcUri, const std::strin std::filesystem::copy_options::recursive | std::filesystem::copy_options::update_existing, errCode); if (errCode.value() != 0) { HILOGE("Copy dir failed: errCode: %{public}d", errCode.value()); - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, RadarReporter::COPY_TO_SANDBOX_ERROR, RadarReporter::CONCURRENT_ID, currentId); return EIO; @@ -225,14 +225,14 @@ int32_t TransListener::CopyToSandBox(const std::string &srcUri, const std::strin errCode); if (errCode.value() != 0) { HILOGE("Copy file failed: errCode: %{public}d", errCode.value()); - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, RadarReporter::COPY_TO_SANDBOX_ERROR, RadarReporter::CONCURRENT_ID, currentId); return EIO; } } HILOGI("Copy file success."); - RADAR_REPORT(RadarReproter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, + RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::CONCURRENT_ID, currentId); return ERRNO_NOERR; } -- Gitee From 81b0eca1d7a143834656912ce841b99a2da51989 Mon Sep 17 00:00:00 2001 From: yangli <“yangli228@huawei.com”> Date: Sat, 3 Aug 2024 16:12:29 +0800 Subject: [PATCH 07/44] =?UTF-8?q?dfs=E9=9B=B7=E8=BE=BE=E6=89=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangli <“yangli228@huawei.com”> --- interfaces/kits/js/BUILD.gn | 1 - .../properties/copy_listener/trans_listener.cpp | 12 +----------- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 5843f1bfc..c98a406bb 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -247,7 +247,6 @@ ohos_shared_library("fs") { "ability_runtime:ability_manager", "ability_runtime:abilitykit_native", "ability_runtime:extensionkit_native", - "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", "app_file_service:fileuri_native", "bundle_framework:appexecfwk_base", diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp index 7fa5b39d2..e59b704ba 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp @@ -19,9 +19,7 @@ #include #include -#include "accesstoken_kit.h" #include "ipc_skeleton.h" -#include "iremote_object.h" #include "sandbox_helper.h" #include "uri.h" #include "n_error.h" @@ -32,8 +30,6 @@ namespace FileManagement { namespace ModuleFileIO { using namespace OHOS::AppFileService; using namespace AppFileService::ModuleFileUri; -using HapTokenInfo = OHOS::Security::AccessToken::HapTokenInfo; -using AccessTokenKit = OHOS::Security::AccessToken::AccessTokenKit; const std::string NETWORK_PARA = "?networkid="; const std::string FILE_MANAGER_AUTHORITY = "docs"; const std::string MEDIA_AUTHORITY = "media"; @@ -104,14 +100,8 @@ NError TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std:: HILOGI("CopyFileFromSoftBus begin."); std::string currentId = "GetPasteData_" + std::to_string(getpid()) + "_" + std::to_string(getSequenceId_); ++getSequenceId_; - HapTokenInfo hapTokenInfo; - int result = AccessTokenKit::GetHapTokenInfo(IPCSkeleton::GetSelfTokenID(), hapTokenInfo); - if (result != Security::AccessToken::AccessTokenKitRet::RET_SUCCESS) { - HILOGE("GetHapTokenInfo failed, errCode = %{public}d", result); - return NError(EIO); - } RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, - RadarReporter::BIZ_STATE, RadarReporter::DFX_BEGIN, RadarReporter::PACKAGE_NAME, hapTokenInfo.bundleName, + RadarReporter::BIZ_STATE, RadarReporter::DFX_BEGIN, RadarReporter::PACKAGE_NAME, std::to_string(getpid()), RadarReporter::CONCURRENT_ID, currentId); sptr transListener = new (std::nothrow) TransListener(); if (transListener == nullptr) { -- Gitee From 0a81aaf9d7ec793e3f0424bcac3608b193f62687 Mon Sep 17 00:00:00 2001 From: liuhan53 Date: Sat, 3 Aug 2024 14:57:19 +0800 Subject: [PATCH 08/44] fix cj FileFS::stat error code Signed-off-by: liuhan53 --- interfaces/kits/cj/src/copy_file.cpp | 69 +++++++++++-------- interfaces/kits/cj/src/file_fs_impl.cpp | 22 ++++-- .../kits/cj/src/randomAccessFile_impl.cpp | 4 ++ interfaces/kits/cj/src/stream_impl.cpp | 3 + 4 files changed, 66 insertions(+), 32 deletions(-) diff --git a/interfaces/kits/cj/src/copy_file.cpp b/interfaces/kits/cj/src/copy_file.cpp index db5b6553a..9335526c0 100644 --- a/interfaces/kits/cj/src/copy_file.cpp +++ b/interfaces/kits/cj/src/copy_file.cpp @@ -33,32 +33,35 @@ using namespace OHOS::FileManagement::LibN; using namespace OHOS::FileManagement; using namespace OHOS::CJSystemapi::FileFs; -std::tuple ParseFile(int32_t file) +std::tuple ParseOperand(int32_t file) { - LOGI("FS_TEST:: FS_TEST::ParseFile"); + LOGI("FS_TEST:: FS_TEST::ParseOperand"); if (file < 0) { LOGE("Invalid fd"); - return { false, FileInfo { false, {}, {} } }; + return { EINVAL, FileInfo { false, {}, {} } }; } auto fdg = CreateUniquePtr(file, false); if (fdg == nullptr) { LOGE("Failed to request heap memory."); - return { false, FileInfo { false, {}, {} } }; + return { ENOMEM, FileInfo { false, {}, {} } }; } - LOGI("FS_TEST:: FS_TEST::ParseFile success"); - return { true, FileInfo { false, {}, move(fdg) } }; + LOGI("FS_TEST:: FS_TEST::ParseOperand success"); + return { SUCCESS_CODE, FileInfo { false, {}, move(fdg) } }; }; -static FileInfo ParseFile(std::string file) +std::tuple ParseOperand(std::string file) { - LOGI("FS_TEST:: ParseFile"); + LOGI("FS_TEST:: ParseOperand"); std::unique_ptr filePath = std::make_unique(file.length() + 1); + if (!filePath) { + return { ENOMEM, FileInfo { true, {}, {} } }; + } for (size_t i = 0; i < file.length(); i++) { filePath[i] = file[i]; } - LOGI("FS_TEST:: ParseFile success"); - return FileInfo { true, move(filePath), {} }; + LOGI("FS_TEST:: ParseOperand success"); + return { SUCCESS_CODE, FileInfo { true, move(filePath), {} } }; }; static int IsAllPath(FileInfo& srcFile, FileInfo& destFile) @@ -194,19 +197,27 @@ static int OpenFile(FileInfo& srcFile, FileInfo& destFile) int CopyFileImpl::CopyFile(const std::string& src, const std::string& dest, int mode) { LOGI("FS_TEST:: CopyFile::CopyFile start"); - auto srcFileInfo = ParseFile(src); - auto destFileInfo = ParseFile(dest); + auto [succSrc, srcFileInfo] = ParseOperand(src); + if (succSrc != SUCCESS_CODE) { + return succSrc; + } + auto [succDest, destFileInfo] = ParseOperand(dest); + if (succDest != SUCCESS_CODE) { + return succDest; + } return IsAllPath(srcFileInfo, destFileInfo); } int CopyFileImpl::CopyFile(const std::string& src, int32_t dest, int mode) { LOGI("FS_TEST:: CopyFile::CopyFile start"); - auto srcFileInfo = ParseFile(src); - auto [succDest, destFileInfo] = ParseFile(dest); - if (!succDest) { - LOGE("The destargument requires fd"); - return EINVAL; + auto [succSrc, srcFileInfo] = ParseOperand(src); + if (succSrc != SUCCESS_CODE) { + return succSrc; + } + auto [succDest, destFileInfo] = ParseOperand(dest); + if (succDest != SUCCESS_CODE) { + return succDest; } return OpenFile(srcFileInfo, destFileInfo); } @@ -214,11 +225,13 @@ int CopyFileImpl::CopyFile(const std::string& src, int32_t dest, int mode) int CopyFileImpl::CopyFile(int32_t src, const std::string& dest, int mode) { LOGI("FS_TEST:: CopyFile::CopyFile start"); - auto [succSrc, srcFileInfo] = ParseFile(src); - auto destFileInfo = ParseFile(dest); - if (!succSrc) { - LOGE("The destargument requires fd"); - return EINVAL; + auto [succSrc, srcFileInfo] = ParseOperand(src); + if (succSrc != SUCCESS_CODE) { + return succSrc; + } + auto [succDest, destFileInfo] = ParseOperand(dest); + if (succDest != SUCCESS_CODE) { + return succDest; } return OpenFile(srcFileInfo, destFileInfo); } @@ -226,11 +239,13 @@ int CopyFileImpl::CopyFile(int32_t src, const std::string& dest, int mode) int CopyFileImpl::CopyFile(int32_t src, int32_t dest, int mode) { LOGI("FS_TEST:: CopyFile::CopyFile start"); - auto [succSrc, srcFileInfo] = ParseFile(src); - auto [succDest, destFileInfo] = ParseFile(dest); - if (!succSrc || !succDest) { - LOGE("The destargument requires fd"); - return EINVAL; + auto [succSrc, srcFileInfo] = ParseOperand(src); + if (succSrc != SUCCESS_CODE) { + return succSrc; + } + auto [succDest, destFileInfo] = ParseOperand(dest); + if (succDest != SUCCESS_CODE) { + return succDest; } return OpenFile(srcFileInfo, destFileInfo); } diff --git a/interfaces/kits/cj/src/file_fs_impl.cpp b/interfaces/kits/cj/src/file_fs_impl.cpp index 973f49e73..466de0bc7 100644 --- a/interfaces/kits/cj/src/file_fs_impl.cpp +++ b/interfaces/kits/cj/src/file_fs_impl.cpp @@ -40,6 +40,9 @@ std::tuple ParseFile(int32_t file) std::tuple ParseFile(std::string file) { std::unique_ptr filePath = std::make_unique(file.length() + 1); + if (!filePath) { + return { ENOMEM, FileInfo { true, nullptr, {} } }; + } for (size_t i = 0; i < file.length(); i++) { filePath[i] = file[i]; } @@ -77,7 +80,10 @@ std::tuple GetUvStat(const FileInfo& fileInfo) if (state != SUCCESS_CODE) { return { state, nullptr }; } - uv_stat_t* tempBuf = new uv_stat_t(stat_req->statbuf); + uv_stat_t* tempBuf = new (std::nothrow) uv_stat_t(stat_req->statbuf); + if (!tempBuf) { + return {ENOMEM, nullptr}; + } return {SUCCESS_CODE, tempBuf}; } @@ -85,16 +91,19 @@ std::tuple ParseRandomFile(std::string file) { LOGI("FS_TEST:: RandomAccessFileImpl::ParseRandomFile"); std::unique_ptr filePath = std::make_unique(file.length() + 1); + if (!filePath) { + return { false, FileInfo { true, nullptr, {} }, ENOMEM }; + } for (size_t i = 0; i < file.length(); i++) { filePath[i] = file[i]; } OHOS::DistributedFS::FDGuard sfd; auto fdg = CreateUniquePtr(sfd, false); if (fdg == nullptr) { - return { false, FileInfo { false, nullptr, nullptr }, ENOMEM}; + return { false, FileInfo { false, nullptr, nullptr }, ENOMEM }; } LOGI("FS_TEST:: RandomAccessFileImpl::ParseRandomFile success"); - return { true, FileInfo { true, move(filePath), move(fdg) }, ERRNO_NOERR}; + return { true, FileInfo { true, move(filePath), move(fdg) }, ERRNO_NOERR }; } std::tuple GetFsAccess(const FileInfo &fileInfo) @@ -126,7 +135,7 @@ std::tuple> FileFsImpl::Stat(int32_t file) auto [fileState, fileInfo] = ParseFile(file); if (fileState != SUCCESS_CODE) { - return {GetErrorCode(ENOMEM), nullptr}; + return {GetErrorCode(fileState), nullptr}; } auto [statState, stat] = GetUvStat(fileInfo); if (statState != SUCCESS_CODE) { @@ -322,6 +331,9 @@ int FileFsImpl::Rmdir(std::string path) { std::unique_ptr scandir_req = { new (std::nothrow) uv_fs_t, CommonFunc::FsReqCleanup }; + if (!scandir_req) { + return GetErrorCode(ENOMEM); + } int ret = 0; ret = uv_fs_scandir(nullptr, scandir_req.get(), path.c_str(), 0, nullptr); if (ret < 0) { @@ -964,7 +976,7 @@ int FileFsImpl::Truncate(int32_t fd, int64_t len) { auto [fileState, fileInfo] = ParseFile(fd); if (fileState != SUCCESS_CODE) { - return GetErrorCode(EINVAL); + return GetErrorCode(fileState); } if (len < 0) { return GetErrorCode(EINVAL); diff --git a/interfaces/kits/cj/src/randomAccessFile_impl.cpp b/interfaces/kits/cj/src/randomAccessFile_impl.cpp index ace584875..65239dd45 100644 --- a/interfaces/kits/cj/src/randomAccessFile_impl.cpp +++ b/interfaces/kits/cj/src/randomAccessFile_impl.cpp @@ -84,6 +84,10 @@ void RandomAccessFileImpl::CloseSync() { std::unique_ptr close_req = { new (std::nothrow) uv_fs_t, CommonFunc::FsReqCleanup }; + if (!close_req) { + LOGE("Failed to close file with ret: %{public}d", ENOMEM); + return; + } int ret = uv_fs_close(nullptr, close_req.get(), entity_->fd.get()->GetFD(), nullptr); if (ret < 0) { LOGE("Failed to close file with ret: %{public}d", ret); diff --git a/interfaces/kits/cj/src/stream_impl.cpp b/interfaces/kits/cj/src/stream_impl.cpp index a210b5ae6..a26b4a2fc 100644 --- a/interfaces/kits/cj/src/stream_impl.cpp +++ b/interfaces/kits/cj/src/stream_impl.cpp @@ -28,6 +28,9 @@ namespace FileFs { std::tuple, size_t> DecodeString(const std::string& buffer, const std::string& encode) { std::unique_ptr buf = std::make_unique(buffer.length() + 1); + if (!buf) { + return { ENOMEM, nullptr, 0}; + } for (size_t i = 0; i < buffer.length(); i++) { buf[i] = buffer[i]; -- Gitee From c8ca39fd6f217806117565c754528c52c6fe44b6 Mon Sep 17 00:00:00 2001 From: yangli <“yangli228@huawei.com”> Date: Mon, 5 Aug 2024 18:48:52 +0800 Subject: [PATCH 09/44] =?UTF-8?q?dfs=E9=9B=B7=E8=BE=BE=E6=89=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangli <“yangli228@huawei.com”> --- .../mod_fs/properties/copy_listener/trans_listener.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp index e59b704ba..4ce58bf67 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp @@ -75,8 +75,8 @@ NError TransListener::HandleCopyFailure(CopyEvent ©Event, const Storage::Dis return NError(EIO); } RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, - RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, - RadarReporter::SEND_FILE_ERROR, RadarReporter::CONCURRENT_ID, currentId); + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, + RadarReporter::SEND_FILE_ERROR, RadarReporter::CONCURRENT_ID, currentId); return NError(it->second); } @@ -101,8 +101,8 @@ NError TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std:: std::string currentId = "GetPasteData_" + std::to_string(getpid()) + "_" + std::to_string(getSequenceId_); ++getSequenceId_; RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, - RadarReporter::BIZ_STATE, RadarReporter::DFX_BEGIN, RadarReporter::PACKAGE_NAME, std::to_string(getpid()), - RadarReporter::CONCURRENT_ID, currentId); + RadarReporter::BIZ_STATE, RadarReporter::DFX_BEGIN, RadarReporter::PACKAGE_NAME, std::to_string(getpid()), + RadarReporter::CONCURRENT_ID, currentId); sptr transListener = new (std::nothrow) TransListener(); if (transListener == nullptr) { HILOGE("new trans listener failed"); -- Gitee From fff9881be9206627e35abc2c38b312c5ff566056 Mon Sep 17 00:00:00 2001 From: yangli <“yangli228@huawei.com”> Date: Mon, 5 Aug 2024 19:12:59 +0800 Subject: [PATCH 10/44] =?UTF-8?q?dfs=E9=9B=B7=E8=BE=BE=E6=89=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangli <“yangli228@huawei.com”> --- .../js/src/mod_fs/properties/copy_listener/trans_listener.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp index 4ce58bf67..7ed06e48d 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp @@ -98,7 +98,7 @@ NError TransListener::CopyFileFromSoftBus(const std::string &srcUri, const std:: std::shared_ptr fileInfos, std::shared_ptr callback) { HILOGI("CopyFileFromSoftBus begin."); - std::string currentId = "GetPasteData_" + std::to_string(getpid()) + "_" + std::to_string(getSequenceId_); + std::string currentId = "CopyFile_" + std::to_string(getpid()) + "_" + std::to_string(getSequenceId_); ++getSequenceId_; RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_SUCCESS, RadarReporter::BIZ_STATE, RadarReporter::DFX_BEGIN, RadarReporter::PACKAGE_NAME, std::to_string(getpid()), -- Gitee From 419d7c09a907d1e6651ae8ec6b3e03c4cfd44561 Mon Sep 17 00:00:00 2001 From: dinghong Date: Sat, 27 Jul 2024 16:59:59 +0800 Subject: [PATCH 11/44] fix: file watcher Change-Id: I471adfcdd4138ce12e36d165b6ab35872f0920cc Signed-off-by: dinghong --- interfaces/kits/cj/src/file_fs_ffi.cpp | 8 +- interfaces/kits/cj/src/file_fs_impl.cpp | 7 +- interfaces/kits/cj/src/watcher_impl.cpp | 157 ++++++++++++++++-------- interfaces/kits/cj/src/watcher_impl.h | 44 ++++--- 4 files changed, 141 insertions(+), 75 deletions(-) diff --git a/interfaces/kits/cj/src/file_fs_ffi.cpp b/interfaces/kits/cj/src/file_fs_ffi.cpp index c30942825..baf176be5 100644 --- a/interfaces/kits/cj/src/file_fs_ffi.cpp +++ b/interfaces/kits/cj/src/file_fs_ffi.cpp @@ -561,12 +561,12 @@ int32_t FfiOHOSFileFsWatcherStart(int64_t id) LOGE("FfiOHOSFileFsWatcherStart instance not exist %{public}" PRId64, id); return ERR_INVALID_INSTANCE_CODE; } - LOGI("FS_TEST::FfiOHOSFileFsWatcherStart success"); - int32_t startCode = instance->StartNotify(); + int32_t startCode = FileWatcherManager::GetInstance().StartNotify(instance->data_); if (startCode != SUCCESS_CODE) { return startCode; } - instance->GetNotifyEvent(); + FileWatcherManager::GetInstance().GetNotifyEvent(instance->data_); + LOGI("FfiOHOSFileFsWatcherStart success"); return SUCCESS_CODE; } @@ -579,7 +579,7 @@ int32_t FfiOHOSFileFsWatcherStop(int64_t id) return ERR_INVALID_INSTANCE_CODE; } LOGI("FS_TEST::FfiOHOSFileFsWatcherStart success"); - return instance->StopNotify(); + return FileWatcherManager::GetInstance().StopNotify(instance->data_); } } } // namespace FileFs diff --git a/interfaces/kits/cj/src/file_fs_impl.cpp b/interfaces/kits/cj/src/file_fs_impl.cpp index 973f49e73..58078b874 100644 --- a/interfaces/kits/cj/src/file_fs_impl.cpp +++ b/interfaces/kits/cj/src/file_fs_impl.cpp @@ -1211,7 +1211,7 @@ std::tuple> FileFsImpl::CreateWatcher(std::string pat void (*callback)(CWatchEvent)) { std::shared_ptr infoArg = std::make_shared(callback); - if (!WatcherImpl::GetInstance().CheckEventValid(events)) { + if (!FileWatcherManager::GetInstance().CheckEventValid(events)) { return { GetErrorCode(EINVAL), nullptr }; } infoArg->events = events; @@ -1223,12 +1223,13 @@ std::tuple> FileFsImpl::CreateWatcher(std::string pat } watcherImpl->data_ = infoArg; - if (watcherImpl->GetNotifyId() < 0 && !watcherImpl->InitNotify()) { + if (FileWatcherManager::GetInstance().GetNotifyId() < 0 && + !FileWatcherManager::GetInstance().InitNotify()) { HILOGE("Failed to get notifyId or initnotify fail"); return { GetErrorCode(errno), nullptr }; } - bool ret = watcherImpl->AddWatcherInfo(infoArg->fileName, infoArg); + bool ret = FileWatcherManager::GetInstance().AddWatcherInfo(infoArg->fileName, infoArg); if (!ret) { HILOGE("Failed to add watcher info."); return {GetErrorCode(EINVAL), nullptr}; diff --git a/interfaces/kits/cj/src/watcher_impl.cpp b/interfaces/kits/cj/src/watcher_impl.cpp index 82a7dfadb..0e65570b4 100644 --- a/interfaces/kits/cj/src/watcher_impl.cpp +++ b/interfaces/kits/cj/src/watcher_impl.cpp @@ -14,33 +14,44 @@ */ #include "watcher_impl.h" +#include +#include +#include #include +#include "securec.h" using namespace OHOS::CJSystemapi::FileFs; namespace OHOS::CJSystemapi { using namespace std; -mutex WatcherImpl::watchMutex_; +mutex FileWatcherManager::watchMutex_; -WatcherImpl::WatcherImpl() {} +FileWatcherManager::FileWatcherManager() {} -int32_t WatcherImpl::GetNotifyId() +FileWatcherManager::~FileWatcherManager() {} + +int32_t FileWatcherManager::GetNotifyId() { return notifyFd_; } -bool WatcherImpl::InitNotify() +bool FileWatcherManager::InitNotify() { notifyFd_ = inotify_init(); if (notifyFd_ < 0) { LOGE("Failed to init notify errCode:%{public}d", errno); return false; } + eventFd_ = eventfd(0, EFD_CLOEXEC); + if (eventFd_ < 0) { + LOGE("Failed to init eventfd errCode:%{public}d", errno); + return false; + } return true; } -tuple WatcherImpl::CheckEventWatched(const string &fileName, const uint32_t &event) +tuple FileWatcherManager::CheckEventWatched(const string &fileName, const uint32_t &event) { int wd = -1; auto iter = wdFileNameMap_.find(fileName); @@ -54,12 +65,14 @@ tuple WatcherImpl::CheckEventWatched(const string &fileName, const ui return {false, wd}; } -bool WatcherImpl::AddWatcherInfo(const string &fileName, shared_ptr arg) +bool FileWatcherManager::AddWatcherInfo(const string &fileName, shared_ptr arg) { for (auto const &iter : watcherInfoSet_) { if (iter->fileName == arg->fileName && iter->events == arg->events) { - LOGE("Faile to add watcher, fileName:%{public}s the callback is same", fileName.c_str()); - return false; + if (iter->callbackId == arg->callbackId) { + LOGE("Faile to add watcher, fileName:%{public}s the callback is same", fileName.c_str()); + return false; + } } } watcherInfoSet_.insert(arg); @@ -74,7 +87,7 @@ bool CheckIncludeEvent(const uint32_t &mask, const uint32_t &event) return false; } -uint32_t WatcherImpl::RemoveWatcherInfo(shared_ptr arg) +uint32_t FileWatcherManager::RemoveWatcherInfo(shared_ptr arg) { watcherInfoSet_.erase(arg); uint32_t otherEvents = 0; @@ -86,36 +99,36 @@ uint32_t WatcherImpl::RemoveWatcherInfo(shared_ptr arg) return otherEvents; } -int32_t WatcherImpl::StartNotify() +int32_t FileWatcherManager::StartNotify(std::shared_ptr arg) { lock_guard lock(watchMutex_); if (notifyFd_ < 0) { LOGE("Failed to start notify notifyFd_:%{public}d", notifyFd_); return GetErrorCode(EIO); } - auto [isWatched, wd] = CheckEventWatched(data_->fileName, data_->events); + auto [isWatched, wd] = CheckEventWatched(arg->fileName, arg->events); if (isWatched && wd > 0) { - data_->wd = wd; + arg->wd = wd; return SUCCESS_CODE; } uint32_t watchEvents = 0; if (wd != -1) { - watchEvents = wdFileNameMap_[data_->fileName].second | data_->events; + watchEvents = wdFileNameMap_[arg->fileName].second | arg->events; } else { - watchEvents = data_->events; + watchEvents = arg->events; } - int newWd = inotify_add_watch(notifyFd_, data_->fileName.c_str(), watchEvents); + int newWd = inotify_add_watch(notifyFd_, arg->fileName.c_str(), watchEvents); if (newWd < 0) { LOGE("Failed to start notify errCode:%{public}d", errno); return GetErrorCode(errno); } - data_->wd = newWd; - wdFileNameMap_[data_->fileName].first = newWd; - wdFileNameMap_[data_->fileName].second = watchEvents; + arg->wd = newWd; + wdFileNameMap_[arg->fileName].first = newWd; + wdFileNameMap_[arg->fileName].second = watchEvents; return SUCCESS_CODE; } -int WatcherImpl::NotifyToWatchNewEvents(const string &fileName, const int &wd, const uint32_t &watchEvents) +int FileWatcherManager::NotifyToWatchNewEvents(const string &fileName, const int &wd, const uint32_t &watchEvents) { int newWd = inotify_add_watch(notifyFd_, fileName.c_str(), watchEvents); if (newWd < 0) { @@ -131,36 +144,55 @@ int WatcherImpl::NotifyToWatchNewEvents(const string &fileName, const int &wd, c return SUCCESS_CODE; } -void WatcherImpl::GetNotifyEvent() +void FileWatcherManager::ReadNotifyEvent(std::function callback) +{ + int len = 0; + int index = 0; + char buf[BUF_SIZE] = {0}; + struct inotify_event *event = nullptr; + while (((len = read(notifyFd_, &buf, sizeof(buf))) < 0) && (errno == EINTR)) {}; + while (index < len) { + event = reinterpret_cast(buf + index); + NotifyEvent(event, callback); + index += sizeof(struct inotify_event) + static_cast(event->len); + } +} + +void FileWatcherManager::GetNotifyEvent(std::shared_ptr arg) { if (run_) { return; } - run_ = true; - char buf[BUF_SIZE] = {0}; - struct inotify_event *event = nullptr; - fd_set fds; - FD_ZERO(&fds); - FD_SET(notifyFd_, &fds); - while (run_) { - if (notifyFd_ < 0) { - LOGE("Failed to run Listener Thread because notifyFd_:%{public}d", notifyFd_); - break; - } - if (select(notifyFd_ + 1, &fds, nullptr, nullptr, nullptr) > 0) { - int len = 0; - int index = 0; - while (((len = read(notifyFd_, &buf, sizeof(buf))) < 0) && (errno == EINTR)) {}; - while (index < len) { - event = reinterpret_cast(buf + index); - NotifyEvent(event); - index += static_cast(sizeof(struct inotify_event) + event->len); + auto fileListener = [this, arg]() { + run_ = true; + nfds_t nfds = 2; + struct pollfd fds[2]; + fds[0].fd = eventFd_; + fds[0].events = 0; + fds[1].fd = notifyFd_; + fds[1].events = POLLIN; + while (run_) { + int ret = poll(fds, nfds, -1); + if (ret > 0) { + if (static_cast(fds[0].revents) & POLLNVAL) { + run_ = false; + return; + } + if (static_cast(fds[1].revents) & POLLIN) { + ReadNotifyEvent(arg->watchCallback_); + } + } else if (ret < 0 && errno == EINTR) { + continue; + } else { + LOGE("Failed to poll NotifyFd, errno=%{public}d", errno); + return; } } - } + }; + std::thread(fileListener).detach(); } -void WatcherImpl::NotifyEvent(const struct inotify_event *event) +void FileWatcherManager::NotifyEvent(const struct inotify_event *event, std::function callback) { lock_guard lock(watchMutex_); string tempFileName; @@ -185,14 +217,26 @@ void WatcherImpl::NotifyEvent(const struct inotify_event *event) fileName += "/" + string(event->name); } CWatchEvent ret = { - .fileName = fileName.c_str(), + .fileName = nullptr, .event = event->mask & IN_ALL_EVENTS, .cookie = event->cookie }; - data_->watchCallback_(ret); + int len = fileName.size() + 1; + ret.fileName = (char*)malloc(len); + if (ret.fileName == nullptr) { + LOGE("Failed to create WatchEvent"); + continue; + } + int errCode = memcpy_s(ret.fileName, len, fileName.c_str(), len); + if (errCode != 0) { + LOGE("Failed to get file name"); + continue; + } + callback(ret); + free(ret.fileName); } } -int WatcherImpl::CloseNotifyFd() +int FileWatcherManager::CloseNotifyFd() { int closeRet = SUCCESS_CODE; if (watcherInfoSet_.size() == 0) { @@ -201,37 +245,46 @@ int WatcherImpl::CloseNotifyFd() LOGE("Failed to stop notify close fd errCode:%{public}d", closeRet); } notifyFd_ = -1; + closeRet = close(eventFd_); + if (closeRet != 0) { + LOGE("Failed to close eventfd errCode:%{public}d", closeRet); + } + eventFd_ = -1; run_ = false; } return closeRet; } -int32_t WatcherImpl::StopNotify() +int32_t FileWatcherManager::StopNotify(std::shared_ptr arg) { unique_lock lock(watchMutex_); if (notifyFd_ < 0) { LOGE("Failed to stop notify notifyFd_:%{public}d", notifyFd_); return EIO; } - uint32_t newEvents = RemoveWatcherInfo(data_); + uint32_t newEvents = RemoveWatcherInfo(arg); if (newEvents > 0) { - return NotifyToWatchNewEvents(data_->fileName, data_->wd, newEvents); + if (access(arg->fileName.c_str(), F_OK) == 0) { + return NotifyToWatchNewEvents(arg->fileName, arg->wd, newEvents); + } + LOGE("The Watched file does not exist, and the remaining monitored events will be invalid."); + return SUCCESS_CODE; } - if (inotify_rm_watch(notifyFd_, data_->wd) == -1) { + if (inotify_rm_watch(notifyFd_, arg->wd) == -1) { int rmErr = errno; - if (access(data_->fileName.c_str(), F_OK) == 0) { + if (access(arg->fileName.c_str(), F_OK) == 0) { LOGE("Failed to stop notify errCode:%{public}d", rmErr); - wdFileNameMap_.erase(data_->fileName); + wdFileNameMap_.erase(arg->fileName); CloseNotifyFd(); return rmErr; } } - wdFileNameMap_.erase(data_->fileName); + wdFileNameMap_.erase(arg->fileName); return CloseNotifyFd(); } -bool WatcherImpl::CheckEventValid(const uint32_t &event) +bool FileWatcherManager::CheckEventValid(const uint32_t &event) { if ((event & IN_ALL_EVENTS) == event) { return true; diff --git a/interfaces/kits/cj/src/watcher_impl.h b/interfaces/kits/cj/src/watcher_impl.h index cb51f0a60..68964fe27 100644 --- a/interfaces/kits/cj/src/watcher_impl.h +++ b/interfaces/kits/cj/src/watcher_impl.h @@ -32,7 +32,7 @@ namespace CJSystemapi { constexpr int BUF_SIZE = 1024; struct CWatchEvent { - const char* fileName; + char* fileName; uint32_t event; uint32_t cookie; }; @@ -40,31 +40,50 @@ struct WatcherInfoArg { std::string fileName = ""; uint32_t events = 0; int wd = -1; + int64_t callbackId = -1; std::function watchCallback_; explicit WatcherInfoArg(void (*callback)(CWatchEvent)) { watchCallback_ = CJLambda::Create(callback); + callbackId = reinterpret_cast(callback); } ~WatcherInfoArg() = default; }; -class WatcherImpl : public OHOS::FFI::FFIData, public Singleton { +class WatcherImpl : public OHOS::FFI::FFIData { public: std::shared_ptr data_; - WatcherImpl(); + OHOS::FFI::RuntimeType* GetRuntimeType() override { return GetClassType(); } +private: + friend class OHOS::FFI::RuntimeType; + friend class OHOS::FFI::TypeBase; + static OHOS::FFI::RuntimeType* GetClassType() + { + static OHOS::FFI::RuntimeType runtimeType = OHOS::FFI::RuntimeType::Create("WatcherImpl"); + return &runtimeType; + } +}; + +class FileWatcherManager : public Singleton { +public: + FileWatcherManager(); + ~FileWatcherManager(); + FileWatcherManager(FileWatcherManager const &) = delete; + void operator=(FileWatcherManager const &) = delete; + int32_t GetNotifyId(); bool InitNotify(); bool AddWatcherInfo(const std::string &fileName, std::shared_ptr arg); bool CheckEventValid(const uint32_t &event); - int32_t StartNotify(); - void GetNotifyEvent(); - int32_t StopNotify(); + int32_t StartNotify(std::shared_ptr arg); + void GetNotifyEvent(std::shared_ptr arg); + void ReadNotifyEvent(std::function callback); + int32_t StopNotify(std::shared_ptr arg); - OHOS::FFI::RuntimeType* GetRuntimeType() override { return GetClassType(); } private: uint32_t RemoveWatcherInfo(std::shared_ptr arg); std::tuple CheckEventWatched(const std::string &fileName, const uint32_t &event); - void NotifyEvent(const struct inotify_event *event); + void NotifyEvent(const struct inotify_event *event, std::function callback); int CloseNotifyFd(); int NotifyToWatchNewEvents(const std::string &fileName, const int &wd, const uint32_t &watchEvents); @@ -72,16 +91,9 @@ private: static std::mutex watchMutex_; bool run_ = false; int32_t notifyFd_ = -1; + int32_t eventFd_ = -1; std::unordered_set> watcherInfoSet_; std::unordered_map> wdFileNameMap_; - - friend class OHOS::FFI::RuntimeType; - friend class OHOS::FFI::TypeBase; - static OHOS::FFI::RuntimeType* GetClassType() - { - static OHOS::FFI::RuntimeType runtimeType = OHOS::FFI::RuntimeType::Create("WatcherImpl"); - return &runtimeType; - } }; } // OHOS::FileManagement::ModuleFileIO } -- Gitee From 1c69005189e7765cd7f070482ecc6cd1f2489b2c Mon Sep 17 00:00:00 2001 From: Wang Luyao Date: Thu, 8 Aug 2024 15:20:21 +0800 Subject: [PATCH 12/44] =?UTF-8?q?copy=E6=8E=A5=E5=8F=A3=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E8=BF=9B=E5=BA=A6=E6=9D=A1=E4=B8=8D=E5=88=B7=E6=96=B0=E7=9A=84?= =?UTF-8?q?=E9=97=AE=E9=A2=98&=E6=BA=90=E6=96=87=E4=BB=B6=E7=9A=84uri?= =?UTF-8?q?=E4=B8=BA=E5=AA=92=E4=BD=93=E6=97=B6=EF=BC=8C=E4=B8=8Dstat?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Wang Luyao --- .../kits/js/src/mod_fs/properties/copy.cpp | 21 +++++++++++++------ .../kits/js/src/mod_fs/properties/copy.h | 2 ++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/properties/copy.cpp b/interfaces/kits/js/src/mod_fs/properties/copy.cpp index ad4b43975..02b45c6a0 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy.cpp @@ -50,6 +50,7 @@ const std::string FILE_PREFIX_NAME = "file://"; const std::string NETWORK_PARA = "?networkid="; const string PROCEDURE_COPY_NAME = "FileFSCopy"; const std::string MEDIALIBRARY_DATA_URI = "datashare:///media"; +const std::string MEDIA = "media"; constexpr int DISMATCH = 0; constexpr int MATCH = 1; constexpr int BUF_SIZE = 1024; @@ -61,7 +62,7 @@ std::map> Copy::jsCbMap_; static int OpenSrcFile(const string &srcPth, std::shared_ptr infos, int32_t &srcFd) { Uri uri(infos->srcUri); - if (uri.GetAuthority() == "media") { + if (uri.GetAuthority() == MEDIA) { std::shared_ptr dataShareHelper = nullptr; sptr remote = new (std::nothrow) IRemoteStub(); if (!remote) { @@ -209,6 +210,13 @@ bool Copy::IsFile(const std::string &path) return (buf.st_mode & S_IFMT) == S_IFREG; } +bool Copy::IsMediaUri(const std::string &uriPath) +{ + Uri uri(uriPath); + string bundleName = uri.GetAuthority(); + return bundleName == MEDIA; +} + tuple Copy::GetFileSize(const std::string &path) { struct stat buf {}; @@ -419,7 +427,7 @@ int Copy::CopyDirFunc(const string &src, const string &dest, std::shared_ptr infos, std::shared_ptr callback) { - if (IsFile(infos->srcPath)) { + if (infos->isFile) { if (infos->srcPath == infos->destPath) { HILOGE("The src and dest is same, path = %{public}s", infos->srcPath.c_str()); return EINVAL; @@ -470,7 +478,7 @@ int Copy::SubscribeLocalListener(std::shared_ptr infos, } receiveInfo->path = infos->destPath; callback->wds.push_back({ newWd, receiveInfo }); - if (IsDirectory(infos->srcPath)) { + if (!infos->isFile) { callback->totalSize = GetDirSize(infos, infos->srcPath); return ERRNO_NOERR; } @@ -674,7 +682,7 @@ tuple Copy::HandleProgress( return { true, EINVAL, false }; } std::string fileName = receivedInfo->path; - if (event->len > 0) { // files under subdir + if (!infos->isFile) { // files under subdir fileName += "/" + string(event->name); if (!CheckFileValid(fileName, infos)) { return { true, EINVAL, false }; @@ -777,6 +785,7 @@ tuple> Copy::CreateFileInfos( infos->destPath = dstFileUri.GetPath(); infos->srcPath = GetRealPath(infos->srcPath); infos->destPath = GetRealPath(infos->destPath); + infos->isFile = IsMediaUri(infos->srcUri) || IsFile(infos->srcPath); infos->notifyTime = std::chrono::steady_clock::now() + NOTIFY_PROGRESS_DELAY; if (listener) { infos->hasListener = true; @@ -801,11 +810,11 @@ void Copy::StartNotify(std::shared_ptr infos, std::shared_ptr infos) { - if (IsFile(infos->srcPath) && IsFile(infos->destPath)) { + if (infos->isFile && IsFile(infos->destPath)) { // copyFile return CopyFile(infos->srcPath.c_str(), infos->destPath.c_str(), infos); } - if (IsDirectory(infos->srcPath) && IsDirectory(infos->destPath)) { + if (!infos->isFile && IsDirectory(infos->destPath)) { if (infos->srcPath.back() != '/') { infos->srcPath += '/'; } diff --git a/interfaces/kits/js/src/mod_fs/properties/copy.h b/interfaces/kits/js/src/mod_fs/properties/copy.h index f1dc61a37..80dac1048 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy.h +++ b/interfaces/kits/js/src/mod_fs/properties/copy.h @@ -81,6 +81,7 @@ struct FileInfos { std::string destUri; std::string srcPath; std::string destPath; + bool isFile = false; std::chrono::steady_clock::time_point notifyTime; int32_t notifyFd = -1; int32_t eventFd = -1; @@ -173,6 +174,7 @@ private: static bool IsRemoteUri(const std::string &uri); static bool IsDirectory(const std::string &path); static bool IsFile(const std::string &path); + static bool IsMediaUri(const std::string &uriPath); static std::string ConvertUriToPath(const std::string &uri); static std::string GetRealPath(const std::string& path); }; -- Gitee From 4168ddac5f90d4e4c83458865c527394daf4d10b Mon Sep 17 00:00:00 2001 From: xuerunlong Date: Thu, 8 Aug 2024 10:29:01 +0000 Subject: [PATCH 13/44] update interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp. Signed-off-by: xuerunlong --- .../kits/js/src/mod_file/class_file/file_n_exporter.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp index f351f3b56..972c56b50 100644 --- a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp @@ -1304,7 +1304,12 @@ napi_value FileNExporter::WriteArrayBuffer(napi_env env, napi_callback_info info napi_ref bufferRef = nullptr; NVal bufNapi = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("buffer"); tie(succ, buffer, bufLength) = bufNapi.ToTypedArray(); - napi_create_reference(env, bufNapi.val_, 1, &bufferRef); + napi_status status = napi_create_reference(env, bufNapi.val_, 1, &bufferRef); + if (status != napi_ok) { + UniError(EINVAL).ThrowErr(env, "Failed to create reference to buffer"); + delete asyncCallbackInfo; + return nullptr; + } string path = (uri == nullptr) ? "" : uri.get(); if (!CheckUri(env, path)) { -- Gitee From baf446be208b22f6e4622a0fceb904bf84a273fa Mon Sep 17 00:00:00 2001 From: Wang Luyao Date: Wed, 7 Aug 2024 20:58:56 +0800 Subject: [PATCH 14/44] =?UTF-8?q?=E7=AE=80=E5=8C=96securitylabl=E5=AF=B9?= =?UTF-8?q?=E6=AF=94=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Wang Luyao --- .../kits/js/src/mod_securitylabel/security_label.h | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/interfaces/kits/js/src/mod_securitylabel/security_label.h b/interfaces/kits/js/src/mod_securitylabel/security_label.h index 1b0eb61b0..02e44c000 100644 --- a/interfaces/kits/js/src/mod_securitylabel/security_label.h +++ b/interfaces/kits/js/src/mod_securitylabel/security_label.h @@ -28,6 +28,7 @@ namespace FileManagement { namespace ModuleSecurityLabel { const char XATTR_KEY[] = {"user.security"}; const std::string DEFAULT_DATA_LEVEL = "s3"; +const int DEFAULT_DATA_LENGTH = 2; const std::set DATA_LEVEL = {"s0", "s1", "s2", "s3", "s4"}; class SecurityLabel { public: @@ -42,14 +43,15 @@ public: #else auto xattrValueSize = getxattr(path.c_str(), XATTR_KEY, nullptr, 0); #endif - if (xattrValueSize == static_cast(DEFAULT_DATA_LEVEL.length())) { - std::unique_ptr xattrValue = std::make_unique((long)xattrValueSize + 1); + if (xattrValueSize == static_cast(DEFAULT_DATA_LENGTH)) { + char xattrValue[DEFAULT_DATA_LENGTH + 1]; #ifdef IOS_PLATFORM - xattrValueSize = getxattr(path.c_str(), XATTR_KEY, xattrValue.get(), xattrValueSize, 0, 0); + xattrValueSize = getxattr(path.c_str(), XATTR_KEY, xattrValue, xattrValueSize, 0, 0); #else - xattrValueSize = getxattr(path.c_str(), XATTR_KEY, xattrValue.get(), xattrValueSize); + xattrValueSize = getxattr(path.c_str(), XATTR_KEY, xattrValue, xattrValueSize); #endif - if (xattrValue[xattrValueSize - 1] > dataLevel.at(dataLevel.size() - 1)) { + xattrValue[DEFAULT_DATA_LENGTH] = '\0'; + if (std::string(xattrValue) > dataLevel) { errno = EINVAL; return false; } -- Gitee From 6ee847b8db6ac8d563f86f27118e04691c2c1d7f Mon Sep 17 00:00:00 2001 From: Wang Luyao Date: Tue, 6 Aug 2024 23:46:25 +0800 Subject: [PATCH 15/44] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=89=AB=E6=8F=8F?= =?UTF-8?q?=E6=95=B4=E6=94=B91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Wang Luyao --- .../napi/n_async/n_async_work_callback.cpp | 4 ++-- .../common/napi/n_async/n_async_work_promise.cpp | 6 +++++- .../kits/js/src/common/napi/n_async/n_ref.cpp | 4 ++-- interfaces/kits/js/src/common/napi/n_class.cpp | 2 +- interfaces/kits/js/src/common/uni_error.cpp | 16 +++++++++------- .../kits/js/src/mod_fs/class_file/file_entity.h | 4 ++-- .../kits/js/src/mod_fs/properties/copydir.cpp | 4 ++++ .../kits/js/src/mod_fs/properties/open.cpp | 3 ++- .../kits/js/src/mod_fs/properties/xattr.cpp | 2 +- .../src/n_async/n_async_work_callback.cpp | 4 ++-- .../src/n_async/n_async_work_promise.cpp | 6 +++++- utils/filemgmt_libn/src/n_async/n_ref.cpp | 4 ++-- utils/filemgmt_libn/src/n_error.cpp | 14 ++++++++------ utils/filemgmt_libn/src/n_val.cpp | 8 +++++++- 14 files changed, 52 insertions(+), 29 deletions(-) diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp index be644d529..7cf9b21fe 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp @@ -22,7 +22,7 @@ using namespace std; NAsyncWorkCallback::NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb) : NAsyncWorkFactory(env) { - ctx_ = new NAsyncContextCallback(thisPtr, cb); + ctx_ = new(std::nothrow) NAsyncContextCallback(thisPtr, cb); } static void CallbackExecute(napi_env env, void *data) @@ -71,7 +71,7 @@ static void CallbackComplete(napi_env env, napi_status status, void *data) NVal NAsyncWorkCallback::Schedule(string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) { - if (!ctx_->cb_ || !ctx_->cb_.Deref(env_).TypeIs(napi_function)) { + if (!ctx_ || !ctx_->cb_ || !ctx_->cb_.Deref(env_).TypeIs(napi_function)) { HILOGE("The callback shall be a function"); UniError(EINVAL).ThrowErr(env_); return NVal(); diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp b/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp index 978096042..1ba6a0fdb 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp @@ -22,7 +22,7 @@ using namespace std; NAsyncWorkPromise::NAsyncWorkPromise(napi_env env, NVal thisPtr) : NAsyncWorkFactory(env) { - ctx_ = new NAsyncContextPromise(thisPtr); + ctx_ = new(std::nothrow) NAsyncContextPromise(thisPtr); } static void PromiseOnExec(napi_env env, void *data) @@ -63,6 +63,10 @@ static void PromiseOnComplete(napi_env env, napi_status status, void *data) NVal NAsyncWorkPromise::Schedule(string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) { + if (ctx_ == nullptr) { + HILOGE("ctx is nullptr"); + return NVal(); + } ctx_->cbExec_ = move(cbExec); ctx_->cbComplete_ = move(cbComplete); diff --git a/interfaces/kits/js/src/common/napi/n_async/n_ref.cpp b/interfaces/kits/js/src/common/napi/n_async/n_ref.cpp index 8b78ac9c8..3509b6fdf 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_ref.cpp +++ b/interfaces/kits/js/src/common/napi/n_async/n_ref.cpp @@ -29,7 +29,7 @@ NRef::NRef(NVal val) NRef::~NRef() { - if (ref_) { + if (ref_ && env_) { napi_delete_reference(env_, ref_); } } @@ -41,7 +41,7 @@ NRef::operator bool() const NVal NRef::Deref(napi_env env) { - if (!ref_) { + if (!ref_ || !env) { return NVal(); } diff --git a/interfaces/kits/js/src/common/napi/n_class.cpp b/interfaces/kits/js/src/common/napi/n_class.cpp index cde1e0b94..191fefc0d 100644 --- a/interfaces/kits/js/src/common/napi/n_class.cpp +++ b/interfaces/kits/js/src/common/napi/n_class.cpp @@ -72,7 +72,7 @@ bool NClass::SaveClass(napi_env env, string className, napi_value exClass) napi_value NClass::InstantiateClass(napi_env env, const string& className, const vector& args) { NClass &nClass = NClass::GetInstance(); - lock_guard(nClass.exClassMapLock); + lock_guard lock(nClass.exClassMapLock); auto it = nClass.exClassMap.find(className); if (it == nClass.exClassMap.end()) { HILOGE("Class %{public}s hasn't been saved yet", className.c_str()); diff --git a/interfaces/kits/js/src/common/uni_error.cpp b/interfaces/kits/js/src/common/uni_error.cpp index 93d5e46ac..e7a81705e 100644 --- a/interfaces/kits/js/src/common/uni_error.cpp +++ b/interfaces/kits/js/src/common/uni_error.cpp @@ -103,9 +103,10 @@ napi_value UniError::GetNapiErr(napi_env env) } int32_t code; string msg; - if (errCodeTable.find(errCode) != errCodeTable.end()) { - code = errCodeTable.at(errCode).first; - msg = errCodeTable.at(errCode).second; + auto it = errCodeTable.find(errCode); + if (it != errCodeTable.end()) { + code = it->second.first; + msg = it->second.second; } else { code = errCodeTable.at(-1).first; msg = errCodeTable.at(-1).second; @@ -131,9 +132,10 @@ void UniError::ThrowErr(napi_env env) int32_t code; string msg; napi_status throwStatus = napi_ok; - if (errCodeTable.find(errno_) != errCodeTable.end()) { - code = errCodeTable.at(errno_).first; - msg = errCodeTable.at(errno_).second; + auto it = errCodeTable.find(errno_); + if (it != errCodeTable.end()) { + code = it->second.first; + msg = it->second.second; } else { code = errCodeTable.at(-1).first; msg = errCodeTable.at(-1).second; @@ -143,7 +145,7 @@ void UniError::ThrowErr(napi_env env) } else { throwStatus = napi_throw(env, GenerateBusinessError(env, code, msg)); } - + if (throwStatus != napi_ok) { HILOGE("Failed to throw an exception, %{public}d, code = %{public}s", throwStatus, msg.c_str()); } diff --git a/interfaces/kits/js/src/mod_fs/class_file/file_entity.h b/interfaces/kits/js/src/mod_fs/class_file/file_entity.h index fb3b81655..b48c796f6 100644 --- a/interfaces/kits/js/src/mod_fs/class_file/file_entity.h +++ b/interfaces/kits/js/src/mod_fs/class_file/file_entity.h @@ -30,8 +30,8 @@ namespace FileManagement { namespace ModuleFileIO { struct FileEntity { std::unique_ptr fd_ = { nullptr }; - std::string path_; - std::string uri_; + std::string path_ = ""; + std::string uri_ = ""; #ifndef WIN_PLATFORM virtual ~FileEntity() { diff --git a/interfaces/kits/js/src/mod_fs/properties/copydir.cpp b/interfaces/kits/js/src/mod_fs/properties/copydir.cpp index 6646192f9..d7743a0e9 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copydir.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copydir.cpp @@ -157,6 +157,10 @@ static int RecurCopyDir(const string &srcPath, const string &destPath, const int return ENOMEM; } int num = scandir(srcPath.c_str(), &(pNameList->namelist), FilterFunc, alphasort); + if (num < 0) { + HILOGE("scandir fail errno is %{public}d", errno); + return errno; + } pNameList->direntNum = num; for (int i = 0; i < num; i++) { diff --git a/interfaces/kits/js/src/mod_fs/properties/open.cpp b/interfaces/kits/js/src/mod_fs/properties/open.cpp index 811fb8f68..bfb5cc80b 100644 --- a/interfaces/kits/js/src/mod_fs/properties/open.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/open.cpp @@ -173,8 +173,9 @@ static tuple OpenByFileDataUri(Uri &uri, const string &uriStr, unsi int res = OpenFileByDatashare(uri.ToString(), mode); if (res < 0) { HILOGE("Failed to open file by Datashare error %{public}d", res); + return { -ENOENT, uri.ToString() }; } - return { ENOENT, uri.ToString() }; + return { res, uri.ToString() }; } int ret = OpenFileByPath(realPath, mode); if (ret < 0) { diff --git a/interfaces/kits/js/src/mod_fs/properties/xattr.cpp b/interfaces/kits/js/src/mod_fs/properties/xattr.cpp index b986d8eef..8bdeca110 100644 --- a/interfaces/kits/js/src/mod_fs/properties/xattr.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/xattr.cpp @@ -207,7 +207,7 @@ napi_value Xattr::SetAsync(napi_env env, napi_callback_info info) return nullptr; } auto cbExec = [path = path.get(), key = key.get(), value = value.get()]() -> NError { - if (setxattr(path, key, value, strnlen(value, MAX_XATTR_SIZE), 0)) { + if (setxattr(path, key, value, strnlen(value, MAX_XATTR_SIZE), 0) < 0) { HILOGE("setxattr fail, errno is %{public}d", errno); return NError(errno); } diff --git a/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp b/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp index eb10bf773..8fc3bfd09 100644 --- a/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp +++ b/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp @@ -29,7 +29,7 @@ using namespace std; NAsyncWorkCallback::NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb) : NAsyncWork(env) { - ctx_ = new NAsyncContextCallback(thisPtr, cb); + ctx_ = new(std::nothrow) NAsyncContextCallback(thisPtr, cb); } NAsyncWorkCallback::~NAsyncWorkCallback() @@ -122,7 +122,7 @@ static void CallbackComplete(napi_env env, napi_status status, void *data) NVal NAsyncWorkCallback::Schedule(string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) { - if (!ctx_->cb_ || !ctx_->cb_.Deref(env_).TypeIs(napi_function)) { + if (!ctx_ || !ctx_->cb_ || !ctx_->cb_.Deref(env_).TypeIs(napi_function)) { HILOGE("The callback should be a function"); NError(EINVAL).ThrowErr(env_); return NVal(); diff --git a/utils/filemgmt_libn/src/n_async/n_async_work_promise.cpp b/utils/filemgmt_libn/src/n_async/n_async_work_promise.cpp index 443c450ef..641debf1e 100644 --- a/utils/filemgmt_libn/src/n_async/n_async_work_promise.cpp +++ b/utils/filemgmt_libn/src/n_async/n_async_work_promise.cpp @@ -23,7 +23,7 @@ using namespace std; NAsyncWorkPromise::NAsyncWorkPromise(napi_env env, NVal thisPtr) : NAsyncWork(env) { - ctx_ = new NAsyncContextPromise(thisPtr); + ctx_ = new(std::nothrow) NAsyncContextPromise(thisPtr); } static void PromiseOnExec(napi_env env, void *data) @@ -61,6 +61,10 @@ static void PromiseOnComplete(napi_env env, napi_status status, void *data) NVal NAsyncWorkPromise::Schedule(string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) { + if (ctx_ == nullptr) { + HILOGE("ctx is nullptr"); + return NVal(); + } ctx_->cbExec_ = move(cbExec); ctx_->cbComplete_ = move(cbComplete); diff --git a/utils/filemgmt_libn/src/n_async/n_ref.cpp b/utils/filemgmt_libn/src/n_async/n_ref.cpp index bd5ebc900..d56a00ce9 100644 --- a/utils/filemgmt_libn/src/n_async/n_ref.cpp +++ b/utils/filemgmt_libn/src/n_async/n_ref.cpp @@ -30,7 +30,7 @@ NRef::NRef(NVal val) NRef::~NRef() { - if (ref_) { + if (ref_ && env_) { napi_delete_reference(env_, ref_); } } @@ -42,7 +42,7 @@ NRef::operator bool() const NVal NRef::Deref(napi_env env) { - if (!ref_) { + if (!ref_ || !env) { return NVal(); } diff --git a/utils/filemgmt_libn/src/n_error.cpp b/utils/filemgmt_libn/src/n_error.cpp index 048513bf3..cf28006ee 100644 --- a/utils/filemgmt_libn/src/n_error.cpp +++ b/utils/filemgmt_libn/src/n_error.cpp @@ -64,9 +64,10 @@ NError::NError() {} NError::NError(int errCode) { int genericCode = ConvertUVCode2ErrCode(errCode); - if (errCodeTable.find(genericCode) != errCodeTable.end()) { - errno_ = errCodeTable.at(genericCode).first; - errMsg_ = errCodeTable.at(genericCode).second; + auto it = errCodeTable.find(genericCode); + if (it != errCodeTable.end()) { + errno_ = it->second.first; + errMsg_ = it->second.second; } else { errno_ = errCodeTable.at(UNKROWN_ERR).first; errMsg_ = errCodeTable.at(UNKROWN_ERR).second + ", errno is " + to_string(abs(errCode)); @@ -98,9 +99,10 @@ napi_value NError::GetNapiErr(napi_env env, int errCode) } int32_t code = 0; string msg; - if (errCodeTable.find(errCode) != errCodeTable.end()) { - code = errCodeTable.at(errCode).first; - msg = errCodeTable.at(errCode).second; + auto it = errCodeTable.find(errCode); + if (it != errCodeTable.end()) { + code = it->second.first; + msg = it->second.second; } else { code = errCodeTable.at(UNKROWN_ERR).first; msg = errCodeTable.at(UNKROWN_ERR).second; diff --git a/utils/filemgmt_libn/src/n_val.cpp b/utils/filemgmt_libn/src/n_val.cpp index 6077fb13f..fbaa2cba0 100644 --- a/utils/filemgmt_libn/src/n_val.cpp +++ b/utils/filemgmt_libn/src/n_val.cpp @@ -75,13 +75,19 @@ tuple, size_t> NVal::ToUTF8String() const if (status != napi_ok) { return { false, nullptr, 0 }; } - + if (strLen == std::numeric_limits::max()) { + HILOGE("string is too long"); + return { false, nullptr, 0 }; + } size_t bufLen = strLen + 1; auto str = CreateUniquePtr(bufLen); if (str == nullptr) { return { false, nullptr, 0 }; } status = napi_get_value_string_utf8(env_, val_, str.get(), bufLen, &strLen); + if (str == nullptr) { + return { false, nullptr, 0 }; + } return make_tuple(status == napi_ok, move(str), strLen); } -- Gitee From acc4fe9a42cab8ba966f5a5ccd0a1a07300e9874 Mon Sep 17 00:00:00 2001 From: xia-bubai Date: Tue, 13 Aug 2024 15:17:55 +0800 Subject: [PATCH 16/44] config does not work, changed to configs Signed-off-by: xia-bubai Change-Id: I8fbe7ab7dbc8048ad58b2cc9a76a583794faf930 --- interfaces/kits/ts/streamhash/BUILD.gn | 2 +- interfaces/kits/ts/streamrw/BUILD.gn | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/interfaces/kits/ts/streamhash/BUILD.gn b/interfaces/kits/ts/streamhash/BUILD.gn index 73315c93a..23ad5eb7d 100644 --- a/interfaces/kits/ts/streamhash/BUILD.gn +++ b/interfaces/kits/ts/streamhash/BUILD.gn @@ -87,7 +87,7 @@ config("optimize-size") { } ohos_shared_library("streamhash") { - config = [ ":optimize-size" ] + configs = [ ":optimize-size" ] branch_protector_ret = "pac_ret" sanitize = { integer_overflow = true diff --git a/interfaces/kits/ts/streamrw/BUILD.gn b/interfaces/kits/ts/streamrw/BUILD.gn index 912d15771..1462c726e 100644 --- a/interfaces/kits/ts/streamrw/BUILD.gn +++ b/interfaces/kits/ts/streamrw/BUILD.gn @@ -87,7 +87,7 @@ config("optimize-size") { } ohos_shared_library("streamrw") { - config = [ ":optimize-size" ] + configs = [ ":optimize-size" ] branch_protector_ret = "pac_ret" sanitize = { integer_overflow = true -- Gitee From da6442b004b9c79199c93962d7244fa30d20da73 Mon Sep 17 00:00:00 2001 From: liuhaotian Date: Tue, 20 Aug 2024 20:29:35 +0800 Subject: [PATCH 17/44] access ext Signed-off-by: liuhaotian Change-Id: I9c39b8dd5e0a8ff60cac66982b39ee93a160b707 --- .../src/mod_fs/properties/prop_n_exporter.cpp | 204 ++++++++++++++---- 1 file changed, 161 insertions(+), 43 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp b/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp index 7fcccd97f..d60663f65 100644 --- a/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp @@ -22,10 +22,10 @@ #include #include -#include "common_func.h" #include "class_file/file_entity.h" #include "class_file/file_n_exporter.h" #include "close.h" +#include "common_func.h" #include "fdatasync.h" #include "file_utils.h" #include "filemgmt_libn.h" @@ -42,14 +42,21 @@ #include "utimes.h" #if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +#include + +#include "bundle_mgr_proxy.h" +#include "connectdfs.h" #include "copy.h" #include "copy_file.h" #include "copydir.h" #include "create_randomaccessfile.h" #include "create_stream.h" #include "create_streamrw.h" +#include "disconnectdfs.h" #include "dup.h" #include "fdopen_stream.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" #include "listfile.h" #include "lseek.h" #include "move.h" @@ -58,9 +65,8 @@ #include "read_text.h" #include "rust_file.h" #include "symlink.h" +#include "system_ability_definition.h" #include "watcher.h" -#include "connectdfs.h" -#include "disconnectdfs.h" #include "xattr.h" #endif @@ -73,17 +79,125 @@ namespace FileManagement { namespace ModuleFileIO { using namespace std; using namespace OHOS::FileManagement::LibN; +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +const string CLOUDDISK_FILE_PREFIX = "/data/storage/el2/cloud"; +const string DISTRIBUTED_FILE_PREFIX = "/data/storage/el2/distributedfiles"; +const string PACKAGE_NAME_FLAG = ""; +const string USER_ID_FLAG = ""; +const string PHYSICAL_PATH_PREFIX = "/mnt/hmdfs//account/device_view/local/data/"; +const string CLOUD_FILE_LOCATION = "user.cloud.location"; +const char POSITION_LOCAL = '1'; +const char POSITION_BOTH = '3'; +const int BASE_USER_RANGE = 200000; +#endif + +enum AccessFlag : int32_t { + DEFAULT_FLAG = -1, + LOCAL_FLAG, +}; + +struct AccessArgs { + string path; + int mode = -1; + int flag = DEFAULT_FLAG; +}; -static int AccessCore(const string &path, int mode) +static int UvAccess(const string &path, int mode) { - std::unique_ptr access_req = { - new uv_fs_t, CommonFunc::fs_req_cleanup }; + std::unique_ptr access_req = {new uv_fs_t, + CommonFunc::fs_req_cleanup}; if (!access_req) { HILOGE("Failed to request heap memory."); return ENOMEM; } - int ret = uv_fs_access(nullptr, access_req.get(), path.c_str(), mode, nullptr); - return ret; + return uv_fs_access(nullptr, access_req.get(), path.c_str(), mode, nullptr); +} + +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) +static bool IsCloudOrDistributedFilePath(const string &path) +{ + return path.find(CLOUDDISK_FILE_PREFIX) == 0 || path.find(DISTRIBUTED_FILE_PREFIX) == 0; +} + +static int GetCurrentUserId() +{ + int uid = IPCSkeleton::GetCallingUid(); + int userId = uid / BASE_USER_RANGE; + return userId; +} + +static sptr GetBundleMgrProxy() +{ + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + HILOGE("fail to get system ability mgr"); + return nullptr; + } + sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (!remoteObject) { + HILOGE("fail to get bundle manager proxy"); + return nullptr; + } + + return iface_cast(remoteObject); +} + +static string GetSelfBundleName() +{ + sptr bundleMgrProxy = GetBundleMgrProxy(); + if (!bundleMgrProxy) { + HILOGE("bundleMgrProxy is nullptr"); + return ""; + } + BundleInfo bundleInfo; + auto ret = bundleMgrProxy->GetBundleInfoForSelf(0, bundleInfo); + if (ret != 0) { + HILOGE("bundleName get fail"); + return ""; + } + return bundleInfo.name; +} + +static int HandleLocalCheck(const string &path, int mode) +{ + // check if the file of /data/storage/el2/cloud is on the local + if (path.find(CLOUDDISK_FILE_PREFIX) == 0) { + char val[2] = {'\0'}; + if (getxattr(path.c_str(), CLOUD_FILE_LOCATION.c_str(), val, sizeof(val)) < 0) { + HILOGI("get cloud file location fail, err: %{public}d", errno); + return errno; + } + if (val[0] == POSITION_LOCAL || val[0] == POSITION_BOTH) { + return 0; + } + return ENOENT; + } + // check if the distributed file of /data/storage/el2/distributedfiles is on the local, + // convert into physical path(/mnt/hmdfs//account/device_view/local/data/) and check + if (path.find(DISTRIBUTED_FILE_PREFIX) == 0) { + int userId = GetCurrentUserId(); + string bundleName = GetSelfBundleName(); + string relativePath = path.substr(DISTRIBUTED_FILE_PREFIX.length()); + string physicalPath = PHYSICAL_PATH_PREFIX + relativePath; + physicalPath.replace(physicalPath.find(USER_ID_FLAG), USER_ID_FLAG.length(), to_string(userId)); + physicalPath.replace(physicalPath.find(PACKAGE_NAME_FLAG), PACKAGE_NAME_FLAG.length(), bundleName); + + return UvAccess(path, mode); + } + + return ENOENT; +} +#endif + +static int AccessCore(const string &path, int mode, int flag = DEFAULT_FLAG) +{ +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) + if (flag == LOCAL_FLAG && IsCloudOrDistributedFilePath(path)) { + return HandleLocalCheck(path, mode); + } +#endif + return UvAccess(path, mode); } static int GetMode(NVal secondVar, bool *hasMode) @@ -101,36 +215,53 @@ static int GetMode(NVal secondVar, bool *hasMode) return -1; } -napi_value PropNExporter::AccessSync(napi_env env, napi_callback_info info) +static bool GetAccessArgs(napi_env env, const NFuncArg &funcArg, AccessArgs &args) { - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - HILOGE("Number of arguments unmatched"); - NError(EINVAL).ThrowErr(env); - return nullptr; - } - auto [succ, path, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8StringPath(); if (!succ) { HILOGE("Invalid path from JS first argument"); - NError(EINVAL).ThrowErr(env); - return nullptr; + return false; } + args.path = path.get(); bool hasMode = false; - int mode = 0; - if (funcArg.GetArgc() == NARG_CNT::TWO) { - mode = GetMode(NVal(env, funcArg[NARG_POS::SECOND]), &hasMode); + if (funcArg.GetArgc() >= NARG_CNT::TWO) { + args.mode = GetMode(NVal(env, funcArg[NARG_POS::SECOND]), &hasMode); } - if (mode < 0 && hasMode) { + if (args.mode < 0 && hasMode) { HILOGE("Invalid mode from JS second argument"); + return false; + } + args.mode = hasMode ? args.mode : 0; + + if (funcArg.GetArgc() == NARG_CNT::THREE) { + tie(succ, args.flag) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(args.flag); + if (!succ) { + HILOGE("Invalid flag from JS third argument"); + return false; + } + } + + return true; +} + +napi_value PropNExporter::AccessSync(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { + HILOGE("Number of arguments unmatched"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + + AccessArgs args; + if (!GetAccessArgs(env, funcArg, args)) { NError(EINVAL).ThrowErr(env); return nullptr; } - mode = hasMode ? mode : 0; bool isAccess = false; - int ret = AccessCore(path.get(), mode); + int ret = AccessCore(args.path, args.mode, args.flag); if (ret < 0 && (string_view(uv_err_name(ret)) != "ENOENT")) { HILOGE("Failed to access file by path"); NError(ret).ThrowErr(env); @@ -145,30 +276,17 @@ napi_value PropNExporter::AccessSync(napi_env env, napi_callback_info info) napi_value PropNExporter::Access(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { HILOGE("Number of arguments unmatched"); NError(EINVAL).ThrowErr(env); return nullptr; } - auto [succ, tmp, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8StringPath(); - if (!succ) { - HILOGE("Invalid path from JS first argument"); - NError(EINVAL).ThrowErr(env); - return nullptr; - } - - bool hasMode = false; - int mode = 0; - if (funcArg.GetArgc() == NARG_CNT::TWO) { - mode = GetMode(NVal(env, funcArg[NARG_POS::SECOND]), &hasMode); - } - if (mode < 0 && hasMode) { - HILOGE("Invalid mode from JS second argument"); + AccessArgs args; + if (!GetAccessArgs(env, funcArg, args)) { NError(EINVAL).ThrowErr(env); return nullptr; } - mode = hasMode ? mode : 0; auto result = CreateSharedPtr(); if (result == nullptr) { @@ -176,8 +294,8 @@ napi_value PropNExporter::Access(napi_env env, napi_callback_info info) NError(ENOMEM).ThrowErr(env); return nullptr; } - auto cbExec = [path = string(tmp.get()), result, mode]() -> NError { - int ret = AccessCore(path, mode); + auto cbExec = [path = args.path, result, mode = args.mode, flag = args.flag]() -> NError { + int ret = AccessCore(path, mode, flag); if (ret == 0) { result->isAccess = true; } @@ -192,7 +310,7 @@ napi_value PropNExporter::Access(napi_env env, napi_callback_info info) }; NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ONE || hasMode) { + if (funcArg.GetArgc() == NARG_CNT::ONE || NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_number)) { return NAsyncWorkPromise(env, thisVar).Schedule(PROCEDURE_ACCESS_NAME, cbExec, cbComplete).val_; } else { NVal cb(env, funcArg[NARG_POS::SECOND]); -- Gitee From 3b898d7b7ade0de23c258ef4fa7cc570a191c95f Mon Sep 17 00:00:00 2001 From: xia-bubai Date: Wed, 21 Aug 2024 18:08:41 +0800 Subject: [PATCH 18/44] =?UTF-8?q?=E5=8E=BB=E9=99=A4=E9=9A=90=E8=97=8F?= =?UTF-8?q?=E7=AC=A6=E5=8F=B7=E7=9A=84=E7=BC=96=E8=AF=91=E9=80=89=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xia-bubai --- interfaces/kits/ts/streamhash/BUILD.gn | 1 - interfaces/kits/ts/streamrw/BUILD.gn | 1 - 2 files changed, 2 deletions(-) diff --git a/interfaces/kits/ts/streamhash/BUILD.gn b/interfaces/kits/ts/streamhash/BUILD.gn index 23ad5eb7d..a27f83fe4 100644 --- a/interfaces/kits/ts/streamhash/BUILD.gn +++ b/interfaces/kits/ts/streamhash/BUILD.gn @@ -75,7 +75,6 @@ streamhash_sources = [ "native_module_streamhash.cpp" ] config("optimize-size") { cflags = [ - "-fvisibility=hidden", "-fdata-sections", "-ffunction-sections", "-Oz", diff --git a/interfaces/kits/ts/streamrw/BUILD.gn b/interfaces/kits/ts/streamrw/BUILD.gn index 1462c726e..a2eece6f1 100644 --- a/interfaces/kits/ts/streamrw/BUILD.gn +++ b/interfaces/kits/ts/streamrw/BUILD.gn @@ -75,7 +75,6 @@ streamrw_sources = [ "native_module_streamrw.cpp" ] config("optimize-size") { cflags = [ - "-fvisibility=hidden", "-fdata-sections", "-ffunction-sections", "-Oz", -- Gitee From fc5b741c1d60adb0701d7a6f82b2857b5d3b0e24 Mon Sep 17 00:00:00 2001 From: wangluyao Date: Fri, 23 Aug 2024 13:24:22 +0800 Subject: [PATCH 19/44] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=BD=8E=E6=A6=82?= =?UTF-8?q?=E7=8E=87=E5=BC=82=E6=AD=A5=E6=8E=A5=E5=8F=A3=E6=97=A0=E6=B3=95?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E5=B1=9E=E6=80=A7=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangluyao --- .../kits/js/src/mod_fs/properties/xattr.cpp | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/properties/xattr.cpp b/interfaces/kits/js/src/mod_fs/properties/xattr.cpp index 8bdeca110..ab9853feb 100644 --- a/interfaces/kits/js/src/mod_fs/properties/xattr.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/xattr.cpp @@ -158,8 +158,10 @@ napi_value Xattr::GetAsync(napi_env env, napi_callback_info info) return nullptr; } auto result = make_shared(); - auto cbExec = [path = path.get(), key = key.get(), result]() -> NError { - int ret = GetXattrCore(path, key, result); + string pathString(path.get()); + string keyString(key.get()); + auto cbExec = [path = move(pathString), key = move(keyString), result]() -> NError { + int ret = GetXattrCore(path.c_str(), key.c_str(), result); return NError(ret); }; auto cbComplete = [result](napi_env env, NError err) -> NVal { @@ -206,8 +208,11 @@ napi_value Xattr::SetAsync(napi_env env, napi_callback_info info) NError(EINVAL).ThrowErr(env); return nullptr; } - auto cbExec = [path = path.get(), key = key.get(), value = value.get()]() -> NError { - if (setxattr(path, key, value, strnlen(value, MAX_XATTR_SIZE), 0) < 0) { + string pathString(path.get()); + string keyString(key.get()); + string valueString(key.get()); + auto cbExec = [path = move(pathString), key = move(keyString), value = move(valueString)]() -> NError { + if (setxattr(path.c_str(), key.c_str(), value.c_str(), strnlen(value.c_str(), MAX_XATTR_SIZE), 0) < 0) { HILOGE("setxattr fail, errno is %{public}d", errno); return NError(errno); } @@ -222,8 +227,7 @@ napi_value Xattr::SetAsync(napi_env env, napi_callback_info info) static const std::string PROCEDURE_NAME = "SetXattr"; NVal thisVar(env, funcArg.GetThisVar()); return NAsyncWorkPromise(env, thisVar) - .Schedule(PROCEDURE_NAME, cbExec, cbComplete) - .val_; + .Schedule(PROCEDURE_NAME, cbExec, cbComplete).val_; } } // namespace ModuleFileIO } // namespace FileManagement -- Gitee From 97daf394ce3b3c1a1c07006b25059c3ac6bb0238 Mon Sep 17 00:00:00 2001 From: xuerunlong Date: Sat, 24 Aug 2024 14:53:39 +0800 Subject: [PATCH 20/44] =?UTF-8?q?=E5=88=A0=E9=99=A4=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E6=89=93=E5=8D=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xuerunlong --- .../kits/js/src/mod_fs/class_file/file_n_exporter.cpp | 6 +++--- interfaces/kits/js/src/mod_fs/properties/copy.cpp | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/class_file/file_n_exporter.cpp b/interfaces/kits/js/src/mod_fs/class_file/file_n_exporter.cpp index 4b7bf13ba..f323319c1 100644 --- a/interfaces/kits/js/src/mod_fs/class_file/file_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fs/class_file/file_n_exporter.cpp @@ -116,7 +116,7 @@ napi_value FileNExporter::GetPath(napi_env env, napi_callback_info info) } auto [realPathRes, realPath] = RealPathCore(fileEntity->path_); if (realPathRes != ERRNO_NOERR) { - HILOGE("Failed to get real path, ret: %{public}d", realPathRes); + HILOGE("Failed to get real path"); NError(realPathRes).ThrowErr(env); return nullptr; } @@ -143,7 +143,7 @@ napi_value FileNExporter::GetName(napi_env env, napi_callback_info info) } auto [realPathRes, realPath] = RealPathCore(fileEntity->path_); if (realPathRes != ERRNO_NOERR) { - HILOGE("Failed to get real path, ret: %{public}d", realPathRes); + HILOGE("Failed to get real path"); NError(realPathRes).ThrowErr(env); return nullptr; } @@ -179,7 +179,7 @@ napi_value FileNExporter::GetParent(napi_env env, napi_callback_info info) } else { auto [realPathRes, realPath] = RealPathCore(path); if (realPathRes) { - HILOGE("Failed to get real path, ret: %{public}d", realPathRes); + HILOGE("Failed to get real path"); NError(realPathRes).ThrowErr(env); return nullptr; } diff --git a/interfaces/kits/js/src/mod_fs/properties/copy.cpp b/interfaces/kits/js/src/mod_fs/properties/copy.cpp index 02b45c6a0..610664f4c 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy.cpp @@ -193,7 +193,7 @@ bool Copy::IsDirectory(const std::string &path) struct stat buf {}; int ret = stat(path.c_str(), &buf); if (ret == -1) { - HILOGE("stat failed, errno is %{public}d, path is %{public}s", errno, path.c_str()); + HILOGE("stat failed, errno is %{public}d", errno); return false; } return (buf.st_mode & S_IFMT) == S_IFDIR; @@ -231,7 +231,7 @@ tuple Copy::GetFileSize(const std::string &path) void Copy::CheckOrCreatePath(const std::string &destPath) { if (!filesystem::exists(destPath)) { - HILOGI("destPath not exist, destPath = %{public}s", destPath.c_str()); + HILOGI("destPath not exist"); auto file = open(destPath.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (file < 0) { HILOGE("Error opening file descriptor. errno = %{public}d", errno); @@ -429,7 +429,7 @@ int Copy::ExecLocal(std::shared_ptr infos, std::shared_ptrisFile) { if (infos->srcPath == infos->destPath) { - HILOGE("The src and dest is same, path = %{public}s", infos->srcPath.c_str()); + HILOGE("The src and dest is same"); return EINVAL; } CheckOrCreatePath(infos->destPath); -- Gitee From 3688a4db569cdddb55732a3606894ff98cdd1225 Mon Sep 17 00:00:00 2001 From: liuzerun Date: Thu, 29 Aug 2024 16:02:16 +0000 Subject: [PATCH 21/44] bugfix for close and setxattr Signed-off-by: liuzerun --- .../kits/js/src/mod_fs/class_file/file_entity.h | 17 +---------------- .../kits/js/src/mod_fs/properties/xattr.cpp | 2 +- 2 files changed, 2 insertions(+), 17 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/class_file/file_entity.h b/interfaces/kits/js/src/mod_fs/class_file/file_entity.h index b48c796f6..4531f36a8 100644 --- a/interfaces/kits/js/src/mod_fs/class_file/file_entity.h +++ b/interfaces/kits/js/src/mod_fs/class_file/file_entity.h @@ -33,22 +33,7 @@ struct FileEntity { std::string path_ = ""; std::string uri_ = ""; #ifndef WIN_PLATFORM - virtual ~FileEntity() - { - if (!fd_.get()) { - return; - } - int32_t fd = fd_.get()->GetFD(); - int ret = flock(fd, LOCK_UN); - if (ret == 0) { - struct stat buf; - if (fstat(fd, &buf) == 0) { - HILOGD("Unlock succeeded inode = %{public}" PRIu64, buf.st_ino); - } else { - HILOGE("Failed to get inode number, error: %{public}d", errno); - } - } - } + virtual ~FileEntity() {}; #endif }; } // namespace ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fs/properties/xattr.cpp b/interfaces/kits/js/src/mod_fs/properties/xattr.cpp index ab9853feb..2fb1961d0 100644 --- a/interfaces/kits/js/src/mod_fs/properties/xattr.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/xattr.cpp @@ -210,7 +210,7 @@ napi_value Xattr::SetAsync(napi_env env, napi_callback_info info) } string pathString(path.get()); string keyString(key.get()); - string valueString(key.get()); + string valueString(value.get()); auto cbExec = [path = move(pathString), key = move(keyString), value = move(valueString)]() -> NError { if (setxattr(path.c_str(), key.c_str(), value.c_str(), strnlen(value.c_str(), MAX_XATTR_SIZE), 0) < 0) { HILOGE("setxattr fail, errno is %{public}d", errno); -- Gitee From 5a11ff5326acf92b07b4ce31239bc29ead458ece Mon Sep 17 00:00:00 2001 From: liuzerun Date: Fri, 30 Aug 2024 03:01:38 +0000 Subject: [PATCH 22/44] del ref Signed-off-by: liuzerun --- utils/filemgmt_libn/include/n_class.h | 4 +++- utils/filemgmt_libn/src/n_class.cpp | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/utils/filemgmt_libn/include/n_class.h b/utils/filemgmt_libn/include/n_class.h index ca59dcc8b..f8f8019f4 100644 --- a/utils/filemgmt_libn/include/n_class.h +++ b/utils/filemgmt_libn/include/n_class.h @@ -38,6 +38,7 @@ public: napi_callback constructor, std::vector &&properties); static bool SaveClass(napi_env env, std::string className, napi_value exClass); + static void CleanClass(void *arg); static napi_value InstantiateClass(napi_env env, const std::string& className, const std::vector& args); template static T *GetEntityOf(napi_env env, napi_value objStat) @@ -82,11 +83,12 @@ public: } private: - NClass() = default; + NClass() : addCleanHook(false) {}; ~NClass() = default; static NClass &GetInstance(); std::map exClassMap; std::mutex exClassMapLock; + bool addCleanHook; }; } // namespace LibN } // namespace FileManagement diff --git a/utils/filemgmt_libn/src/n_class.cpp b/utils/filemgmt_libn/src/n_class.cpp index c9b8492ca..6c72fb57a 100644 --- a/utils/filemgmt_libn/src/n_class.cpp +++ b/utils/filemgmt_libn/src/n_class.cpp @@ -59,9 +59,32 @@ bool NClass::SaveClass(napi_env env, string className, napi_value exClass) HILOGE("INNER BUG. Cannot ref class constructor %{public}s because of %{public}d", className.c_str(), res); } + if (!nClass.addCleanHook) { + napi_status status = napi_add_env_cleanup_hook(env, CleanClass, env); + if (status != napi_ok) { + HILOGE("INNER BUG. Cleanup_hook registation has failed because of %{public}d", res); + } else { + nClass.addCleanHook = true; + } + } return res == napi_ok; } +void NClass::CleanClass(void *arg) +{ + napi_env env = reinterpret_cast(arg); + NClass &nClass = NClass::GetInstance(); + lock_guard(nClass.exClassMapLock); + + napi_status res; + for (auto it = nClass.exClassMap.begin(); it != nClass.exClassMap.end(); ++it) { + res = napi_delete_reference(env, it->second); + if (res != napi_ok) { + HILOGE("Cannot del ref class constructor %{public}s because of %{public}d", it->first.c_str(), res); + } + } +} + napi_value NClass::InstantiateClass(napi_env env, const string& className, const vector& args) { NClass &nClass = NClass::GetInstance(); -- Gitee From 5d032d04237aff3cf18f26ee8d29a09b1241360a Mon Sep 17 00:00:00 2001 From: kirby Date: Tue, 3 Sep 2024 11:03:14 +0800 Subject: [PATCH 23/44] fix_ffi_code_check Signed-off-by: kirby --- interfaces/kits/cj/src/copy_dir.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/interfaces/kits/cj/src/copy_dir.cpp b/interfaces/kits/cj/src/copy_dir.cpp index 878bbe4f8..ab9357e74 100644 --- a/interfaces/kits/cj/src/copy_dir.cpp +++ b/interfaces/kits/cj/src/copy_dir.cpp @@ -198,20 +198,20 @@ static CConflictFiles* VectorToCConflict(std::vector &errf break; } if (strcpy_s(result[i].srcFiles, srcFilesLen, errfiles[i].srcFiles.c_str()) != 0) { - delete result[i].srcFiles; + delete[] result[i].srcFiles; result[i].srcFiles = nullptr; break; } size_t destFilesLen = errfiles[i].destFiles.length() + 1; result[i].destFiles = new(std::nothrow) char[destFilesLen]; if (result[i].destFiles == nullptr) { - delete result[i].srcFiles; + delete[] result[i].srcFiles; result[i].srcFiles = nullptr; break; } if (strcpy_s(result[i].destFiles, destFilesLen, errfiles[i].destFiles.c_str()) != 0) { - delete result[i].srcFiles; - delete result[i].destFiles; + delete[] result[i].srcFiles; + delete[] result[i].destFiles; result[i].srcFiles = nullptr; result[i].destFiles = nullptr; @@ -221,8 +221,8 @@ static CConflictFiles* VectorToCConflict(std::vector &errf } if (temp != errfiles.size()) { for (size_t j = temp; j > 0; j--) { - delete result[j - 1].srcFiles; - delete result[j - 1].destFiles; + delete[] result[j - 1].srcFiles; + delete[] result[j - 1].destFiles; result[j - 1].srcFiles = nullptr; result[j - 1].destFiles = nullptr; -- Gitee From 5dbe120c08027e2d9cdd5ed365da317f07e0bbca Mon Sep 17 00:00:00 2001 From: zhongning5 Date: Tue, 3 Sep 2024 16:24:27 +0800 Subject: [PATCH 24/44] =?UTF-8?q?=E5=9B=9E=E9=80=80=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhongning5 --- interfaces/kits/rust/BUILD.gn | 1 - 1 file changed, 1 deletion(-) diff --git a/interfaces/kits/rust/BUILD.gn b/interfaces/kits/rust/BUILD.gn index 51d2b5296..a4cc7d698 100644 --- a/interfaces/kits/rust/BUILD.gn +++ b/interfaces/kits/rust/BUILD.gn @@ -26,6 +26,5 @@ ohos_rust_shared_ffi("rust_file") { rustflags = [ "-Zstack-protector=all" ] deps = [ "//third_party/rust/crates/libc:lib" ] external_deps = [ "hilog:hilog_rust" ] - innerapi_tags = [ "platformsdk" ] public_configs = [ ":public_config" ] } -- Gitee From e18f2d7ef74aab6f4dbd67423c3b68ba0e029ab2 Mon Sep 17 00:00:00 2001 From: liuhaotian Date: Tue, 3 Sep 2024 17:20:41 +0800 Subject: [PATCH 25/44] fix access ext Signed-off-by: liuhaotian Change-Id: I508892b40ad7a4f8f5392b9f5c6f63eb00676561 --- interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp b/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp index d60663f65..1191c3311 100644 --- a/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp @@ -183,7 +183,7 @@ static int HandleLocalCheck(const string &path, int mode) physicalPath.replace(physicalPath.find(USER_ID_FLAG), USER_ID_FLAG.length(), to_string(userId)); physicalPath.replace(physicalPath.find(PACKAGE_NAME_FLAG), PACKAGE_NAME_FLAG.length(), bundleName); - return UvAccess(path, mode); + return UvAccess(physicalPath, mode); } return ENOENT; -- Gitee From fdd0fdad94d3153ac87bc665ff1bb13015f201e2 Mon Sep 17 00:00:00 2001 From: wangluyao Date: Sat, 31 Aug 2024 17:20:49 +0800 Subject: [PATCH 26/44] =?UTF-8?q?=E6=B7=BB=E5=8A=A0exists=E7=9A=84errcode?= =?UTF-8?q?=E5=85=A5=E5=8F=82=EF=BC=8C=E9=98=B2=E6=AD=A2throw=20err?= =?UTF-8?q?=E5=87=BA=E7=8E=B0crash?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangluyao --- .../kits/js/src/mod_fs/properties/copy.cpp | 21 +++++++++++--- .../kits/js/src/mod_fs/properties/copy.h | 2 +- .../js/src/mod_fs/properties/copy_file.cpp | 2 +- .../copy_listener/trans_listener.cpp | 2 +- .../kits/js/src/mod_fs/properties/copydir.cpp | 20 ++++++++++--- .../kits/js/src/mod_fs/properties/move.cpp | 2 +- .../kits/js/src/mod_fs/properties/movedir.cpp | 29 +++++++++++++------ .../js/src/mod_fs/properties/rmdirent.cpp | 8 +++-- 8 files changed, 63 insertions(+), 23 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/properties/copy.cpp b/interfaces/kits/js/src/mod_fs/properties/copy.cpp index 610664f4c..86020f7e5 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy.cpp @@ -228,16 +228,21 @@ tuple Copy::GetFileSize(const std::string &path) return { ERRNO_NOERR, buf.st_size }; } -void Copy::CheckOrCreatePath(const std::string &destPath) +int Copy::CheckOrCreatePath(const std::string &destPath) { - if (!filesystem::exists(destPath)) { + std::error_code errCode; + if (!filesystem::exists(destPath, errCode) && errCode.value() == ERRNO_NOERR) { HILOGI("destPath not exist"); auto file = open(destPath.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (file < 0) { HILOGE("Error opening file descriptor. errno = %{public}d", errno); + return errno; } close(file); + } else if (errCode.value() != 0) { + return errCode.value(); } + return ERRNO_NOERR; } int Copy::CopyFile(const string &src, const string &dest, std::shared_ptr infos) @@ -278,12 +283,16 @@ int Copy::MakeDir(const string &path) int Copy::CopySubDir(const string &srcPath, const string &destPath, std::shared_ptr infos) { - if (!filesystem::exists(destPath)) { + std::error_code errCode; + if (!filesystem::exists(destPath, errCode) && errCode.value() == ERRNO_NOERR) { int res = MakeDir(destPath); if (res != ERRNO_NOERR) { HILOGE("Failed to mkdir"); return res; } + } else if (errCode.value() != ERRNO_NOERR) { + HILOGE("fs exists fail, errcode is %{public}d", errCode.value()); + return errCode.value(); } uint32_t watchEvents = IN_MODIFY; if (infos->notifyFd >= 0) { @@ -432,7 +441,11 @@ int Copy::ExecLocal(std::shared_ptr infos, std::shared_ptrdestPath); + int ret = CheckOrCreatePath(infos->destPath); + if (ret != ERRNO_NOERR) { + HILOGE("check or create fail, error code is %{public}d", ret); + return ret; + } } if (!infos->hasListener) { return ExecCopy(infos); diff --git a/interfaces/kits/js/src/mod_fs/properties/copy.h b/interfaces/kits/js/src/mod_fs/properties/copy.h index 80dac1048..ffaa21980 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy.h +++ b/interfaces/kits/js/src/mod_fs/properties/copy.h @@ -130,7 +130,7 @@ private: static tuple ParseJsOperand(napi_env env, NVal pathOrFdFromJsArg); static tuple GetListenerFromOptionArg(napi_env env, const NFuncArg &funcArg); static tuple GetCopySignalFromOptionArg(napi_env env, const NFuncArg &funcArg); - static void CheckOrCreatePath(const std::string &destPath); + static int CheckOrCreatePath(const std::string &destPath); static int ParseJsParam(napi_env env, NFuncArg &funcArg, std::shared_ptr &fileInfos); // operator of local listener diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_file.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_file.cpp index 5c4816668..8858f554d 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_file.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_file.cpp @@ -137,7 +137,7 @@ static NError OpenCore(FileInfo& fileInfo, const int flags, const int mode) static NError OpenFile(FileInfo& srcFile, FileInfo& destFile) { if (srcFile.isPath) { - auto openResult = OpenCore(srcFile, UV_FS_O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); + auto openResult = OpenCore(srcFile, UV_FS_O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (openResult) { return openResult; } diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp index 7ed06e48d..abe3a4750 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener.cpp @@ -47,7 +47,7 @@ void TransListener::RmDir(const std::string &path) HILOGE("Failed to remove directory, error code: %{public}d", errCode.value()); } } else { - HILOGE("pathName is not exists, error code: %{public}d", errCode.value()); + HILOGE("pathName is not exists, error code: %{public}d", errCode.value()); } } diff --git a/interfaces/kits/js/src/mod_fs/properties/copydir.cpp b/interfaces/kits/js/src/mod_fs/properties/copydir.cpp index d7743a0e9..48c4cfb91 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copydir.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copydir.cpp @@ -111,15 +111,19 @@ static void Deleter(struct NameList *arg) static int CopyFile(const string &src, const string &dest, const int mode) { filesystem::path dstPath(dest); - if (filesystem::exists(dstPath)) { + std::error_code errCode; + if (filesystem::exists(dstPath, errCode)) { int ret = (mode == DIRMODE_FILE_COPY_THROW_ERR) ? EEXIST : RemoveFile(dest); if (ret) { HILOGE("Failed to copy file due to existing destPath with throw err"); return ret; } } + if (errCode.value() != ERRNO_NOERR) { + HILOGE("fs exists fail, errcode is %{public}d", errCode.value()); + return errCode.value(); + } filesystem::path srcPath(src); - std::error_code errCode; if (!filesystem::copy_file(srcPath, dstPath, filesystem::copy_options::overwrite_existing, errCode)) { HILOGE("Failed to copy file, error code: %{public}d", errCode.value()); return errCode.value(); @@ -130,12 +134,16 @@ static int CopyFile(const string &src, const string &dest, const int mode) static int CopySubDir(const string &srcPath, const string &destPath, const int mode, vector &errfiles) { - if (!filesystem::exists(destPath)) { + std::error_code errCode; + if (!filesystem::exists(destPath, errCode) && errCode.value() == ERRNO_NOERR) { int res = MakeDir(destPath); if (res != ERRNO_NOERR) { HILOGE("Failed to mkdir"); return res; } + } else if (errCode.value() != ERRNO_NOERR) { + HILOGE("fs exists fail, errcode is %{public}d", errCode.value()); + return errCode.value(); } return RecurCopyDir(srcPath, destPath, mode, errfiles); } @@ -198,12 +206,16 @@ static int CopyDirFunc(const string &src, const string &dest, const int mode, ve } string dirName = string(src).substr(found); string destStr = dest + dirName; - if (!filesystem::exists(destStr)) { + std::error_code errCode; + if (!filesystem::exists(destStr, errCode) && errCode.value() == ERRNO_NOERR) { int res = MakeDir(destStr); if (res != ERRNO_NOERR) { HILOGE("Failed to mkdir"); return res; } + } else if (errCode.value() != ERRNO_NOERR) { + HILOGE("fs exists fail, errcode is %{public}d", errCode.value()); + return errCode.value(); } int res = RecurCopyDir(src, destStr, mode, errfiles); if (!errfiles.empty() && res == ERRNO_NOERR) { diff --git a/interfaces/kits/js/src/mod_fs/properties/move.cpp b/interfaces/kits/js/src/mod_fs/properties/move.cpp index 03b5876e5..59e7fb97f 100644 --- a/interfaces/kits/js/src/mod_fs/properties/move.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/move.cpp @@ -97,7 +97,7 @@ static int CopyAndDeleteFile(const string &src, const string &dest) #if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) filesystem::path dstPath(dest); std::error_code errCode; - if (filesystem::exists(dstPath)) { + if (filesystem::exists(dstPath, errCode)) { if (!filesystem::remove(dstPath, errCode)) { HILOGE("Failed to remove dest file, error code: %{public}d", errCode.value()); return errCode.value(); diff --git a/interfaces/kits/js/src/mod_fs/properties/movedir.cpp b/interfaces/kits/js/src/mod_fs/properties/movedir.cpp index 7e1874e51..4a6a8781c 100644 --- a/interfaces/kits/js/src/mod_fs/properties/movedir.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/movedir.cpp @@ -38,8 +38,9 @@ static int RecurMoveDir(const string &srcPath, const string &destPath, const int static tuple JudgeExistAndEmpty(const string &path) { + std::error_code errCode; filesystem::path pathName(path); - if (filesystem::exists(pathName)) { + if (filesystem::exists(pathName, errCode)) { if (filesystem::is_empty(pathName)) { return { true, true }; } @@ -51,13 +52,17 @@ static tuple JudgeExistAndEmpty(const string &path) static int RmDirectory(const string &path) { filesystem::path pathName(path); - if (filesystem::exists(pathName)) { + std::error_code errCode; + if (filesystem::exists(pathName, errCode)) { std::error_code errCode; (void)filesystem::remove_all(pathName, errCode); if (errCode.value() != 0) { HILOGE("Failed to remove directory, error code: %{public}d", errCode.value()); return errCode.value(); } + } else if (errCode.value() != ERRNO_NOERR) { + HILOGE("fs exists fail, errcode is %{public}d", errCode.value()); + return errCode.value(); } return ERRNO_NOERR; } @@ -100,7 +105,8 @@ static tuple, unique_ptr, int> ParseJsOperand(n static int CopyAndDeleteFile(const string &src, const string &dest) { filesystem::path dstPath(dest); - if (filesystem::exists(dstPath)) { + std::error_code errCode; + if (filesystem::exists(dstPath, errCode)) { int removeRes = RemovePath(dest); if (removeRes != 0) { HILOGE("Failed to remove dest file"); @@ -108,7 +114,6 @@ static int CopyAndDeleteFile(const string &src, const string &dest) } } filesystem::path srcPath(src); - std::error_code errCode; if (!filesystem::copy_file(srcPath, dstPath, filesystem::copy_options::overwrite_existing, errCode)) { HILOGE("Failed to copy file, error code: %{public}d", errCode.value()); return errCode.value(); @@ -119,8 +124,9 @@ static int CopyAndDeleteFile(const string &src, const string &dest) static int RenameFile(const string &src, const string &dest, const int mode, deque &errfiles) { filesystem::path dstPath(dest); - if (filesystem::exists(dstPath)) { - if (filesystem::is_directory(dstPath)) { + std::error_code errCode; + if (filesystem::exists(dstPath, errCode)) { + if (filesystem::is_directory(dstPath, errCode)) { errfiles.emplace_front(src, dest); return ERRNO_NOERR; } @@ -129,8 +135,10 @@ static int RenameFile(const string &src, const string &dest, const int mode, deq return ERRNO_NOERR; } } + if (errCode.value() != ERRNO_NOERR) { + HILOGE("fs exists or is_directory fail, errcode is %{public}d", errCode.value()); + } filesystem::path srcPath(src); - std::error_code errCode; filesystem::rename(srcPath, dstPath, errCode); if (errCode.value() == EXDEV) { HILOGD("Failed to rename file due to EXDEV"); @@ -150,11 +158,14 @@ static int32_t FilterFunc(const struct dirent *filename) static int RenameDir(const string &src, const string &dest, const int mode, deque &errfiles) { filesystem::path destPath(dest); - if (filesystem::exists(destPath)) { + std::error_code errCode; + if (filesystem::exists(destPath, errCode)) { return RecurMoveDir(src, dest, mode, errfiles); + } else if (errCode.value() != ERRNO_NOERR) { + HILOGE("fs exists fail, errcode is %{public}d", errCode.value()); + return errCode.value(); } filesystem::path srcPath(src); - std::error_code errCode; filesystem::rename(srcPath, destPath, errCode); if (errCode.value() == EXDEV) { HILOGD("Failed to rename file due to EXDEV"); diff --git a/interfaces/kits/js/src/mod_fs/properties/rmdirent.cpp b/interfaces/kits/js/src/mod_fs/properties/rmdirent.cpp index f5e2bbfb1..9d375c244 100755 --- a/interfaces/kits/js/src/mod_fs/properties/rmdirent.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/rmdirent.cpp @@ -39,14 +39,18 @@ static NError RmDirent(const string &fpath) std::filesystem::path strToPath(fpath); std::error_code errCode; std::uintmax_t num = std::filesystem::remove_all(strToPath, errCode); - if (errCode) { + if (errCode.value() != ERRNO_NOERR) { HILOGD("Failed to remove directory, error code: %{public}d", errCode.value()); return NError(errCode.value()); } - if (!num || std::filesystem::exists(strToPath)) { + if (!num || std::filesystem::exists(strToPath, errCode)) { HILOGE("Failed to remove directory, dirPath does not exist"); return NError(ENOENT); } + if (errCode.value() != ERRNO_NOERR) { + HILOGE("fs exists fail, error code: %{public}d", errCode.value()); + return NError(errCode.value()); + } return NError(ERRNO_NOERR); } -- Gitee From 2f3a41c907ecd2180daefa5ea9b21d471564562a Mon Sep 17 00:00:00 2001 From: Wang Luyao Date: Wed, 28 Aug 2024 20:06:09 +0800 Subject: [PATCH 27/44] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dtdd=20hap=20=E5=AE=89?= =?UTF-8?q?=E8=A3=85=E5=A4=B1=E8=B4=A5=E5=AF=BC=E8=87=B4tdd=E6=97=A0?= =?UTF-8?q?=E6=B3=95=E9=80=9A=E8=BF=87=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Wang Luyao --- .../kits/js/src/mod_fs/properties/copy.cpp | 36 +++++++++++++----- .../kits/js/src/mod_fs/properties/copy.h | 4 +- .../unittest/napi_test/openharmony_sx.p7b | Bin 4189 -> 3428 bytes 3 files changed, 29 insertions(+), 11 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/properties/copy.cpp b/interfaces/kits/js/src/mod_fs/properties/copy.cpp index 610664f4c..e138c4e6a 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy.cpp @@ -188,22 +188,26 @@ bool Copy::IsRemoteUri(const std::string &uri) return uri.find(NETWORK_PARA) != uri.npos; } -bool Copy::IsDirectory(const std::string &path) +bool Copy::IsDirectory(const std::string &path, int &errCode) { + errCode = 0; struct stat buf {}; int ret = stat(path.c_str(), &buf); if (ret == -1) { + errCode = errno; HILOGE("stat failed, errno is %{public}d", errno); return false; } return (buf.st_mode & S_IFMT) == S_IFDIR; } -bool Copy::IsFile(const std::string &path) +bool Copy::IsFile(const std::string &path, int &errCode) { + errCode = 0; struct stat buf {}; int ret = stat(path.c_str(), &buf); if (ret == -1) { + errCode = errno; HILOGI("stat failed, errno is %{public}d, ", errno); return false; } @@ -427,11 +431,19 @@ int Copy::CopyDirFunc(const string &src, const string &dest, std::shared_ptr infos, std::shared_ptr callback) { + int errCode = 0; + infos->isFile = IsMediaUri(infos->srcUri) || IsFile(infos->srcPath, errCode); + if (errCode != 0) { + return errCode; + } + if (!infos->isFile && !IsDirectory(infos->srcPath, errCode)) { + return EINVAL; + } + if (infos->srcPath == infos->destPath) { + HILOGE("The src and dest is same, path = %{public}s", infos->srcPath.c_str()); + return EINVAL; + } if (infos->isFile) { - if (infos->srcPath == infos->destPath) { - HILOGE("The src and dest is same"); - return EINVAL; - } CheckOrCreatePath(infos->destPath); } if (!infos->hasListener) { @@ -785,7 +797,6 @@ tuple> Copy::CreateFileInfos( infos->destPath = dstFileUri.GetPath(); infos->srcPath = GetRealPath(infos->srcPath); infos->destPath = GetRealPath(infos->destPath); - infos->isFile = IsMediaUri(infos->srcUri) || IsFile(infos->srcPath); infos->notifyTime = std::chrono::steady_clock::now() + NOTIFY_PROGRESS_DELAY; if (listener) { infos->hasListener = true; @@ -810,11 +821,15 @@ void Copy::StartNotify(std::shared_ptr infos, std::shared_ptr infos) { - if (infos->isFile && IsFile(infos->destPath)) { + int errCode = 0; + if (infos->isFile && IsFile(infos->destPath, errCode) && errCode == 0) { // copyFile return CopyFile(infos->srcPath.c_str(), infos->destPath.c_str(), infos); } - if (!infos->isFile && IsDirectory(infos->destPath)) { + if (errCode != 0) { + return errCode; + } + if (!infos->isFile && IsDirectory(infos->destPath, errCode) && errCode == 0) { if (infos->srcPath.back() != '/') { infos->srcPath += '/'; } @@ -824,6 +839,9 @@ int Copy::ExecCopy(std::shared_ptr infos) // copyDir return CopyDirFunc(infos->srcPath.c_str(), infos->destPath.c_str(), infos); } + if (errCode != 0) { + return errCode; + } return EINVAL; } diff --git a/interfaces/kits/js/src/mod_fs/properties/copy.h b/interfaces/kits/js/src/mod_fs/properties/copy.h index 80dac1048..52d2fc400 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy.h +++ b/interfaces/kits/js/src/mod_fs/properties/copy.h @@ -172,8 +172,8 @@ private: // operator of uri or path static bool IsValidUri(const std::string &uri); static bool IsRemoteUri(const std::string &uri); - static bool IsDirectory(const std::string &path); - static bool IsFile(const std::string &path); + static bool IsDirectory(const std::string &path, int &errCode); + static bool IsFile(const std::string &path, int &errCode); static bool IsMediaUri(const std::string &uriPath); static std::string ConvertUriToPath(const std::string &uri); static std::string GetRealPath(const std::string& path); diff --git a/interfaces/test/unittest/napi_test/openharmony_sx.p7b b/interfaces/test/unittest/napi_test/openharmony_sx.p7b index 166e7985b623f7bf896e6363761bb1a331c54db7..c69f83414e5ae8062eef7be0315ec8a490575eb8 100644 GIT binary patch literal 3428 zcmcgveN+=y7AGG-5u+$7YE>{&v0~s&NJ2tu+nLEHFu@5S5X9mnnS7DVgfPh@xLO-q zwrJJ0J*#Z}LQ&N9qq}NF_MBSRZFOz8x>ncS(~4c|a<;l!*VVRGkM7O@Rq*H^dwPyJ zCz-jwd*91_@BZ%Zod*(<`6+2LTZ}E=O9ZLH_Jjln2?-_?2p|baPf45KVib@fu}}aK z$w?0a1?>s(b#X#`b%8WWhMRmeC8LNSDJ_x83qS#o&bkjfX%`2}XGw`rNapf2F=3x0 z!teu_c!(cBH`V(nhV+C99_2dnS*rGVQyYXsZpp^O1V-!s}CpK3>oHNm0F`HF5=*Yv!nwV zgvkI&G?Cn7jtJ!nkTM_Truq3?WRwihAu=rM%cvqmQbr;iq^UR;J7g_RGR*kgJ}1HO zOOo*)L}xIWb5NbdYSNof*sAM8>nO}*LiJV@g=^y;m^C4=$5aZNYa>di(5tcd^D&q< zplG9^5>sdp7}H_~EQU72rHIFDLtwkLj)EJ^6_^EQbsoFchT~;AmYL%;*dmn%ecVy4 ziI7%ZErvJ^FjS>OV;F8NLIREkuh$ubq7JITQ%BhhHm}2~^JA#4FA9!f#KTc|4Z=DM z0l&S*5^~5D9vtXcqt|K1{5V@jnXRT~%xaHe&A76fN1Jh$!(#U_KT?KSs#qP{m!nn- z$3nFRo16PG4oKszqnt)KrnSQ5{p)J7B6?edsKH};D{Sq@XscGIiPy^Y93Jwz41uV_ zuPevkhQ6HZD8!4QI8d+jnp`Fpw_^wa>&+1Z6E{^uc*I*->~@vbM3idWrlEb1 z@nL>&GsvAVX24MlEq0a#Vo;r7P1!gJitAR#ivEZDwb&r#aNnsEpN7eN@+(wU40xgDx8o3@05dAY()@6d((N zaZV)yd>i#k0TBvt?L^VxAQ9jO@)F`E2`0ifxYWxjN589{b4a;SZS3yGf zJV*#WXcq|uLZP^LTksGVp7Io@peJUFMWW;+;DpjaT8gMjoRTR-&CnPynm2}JrVr8& zXadOM(e%uWL1>PZB!bX1FqLV zg3wP)0)T@4B=R1Y#GEkg_65isOTT&oJIG8)?b`;SU|>H)f>aTbB(6Rw{8xA9-ml=s zLt~G>HRGM#`r;*$wrs)IyJvp*=J|6MreNEPzZHFU{U{~Ox4xMD!5`c4RcYh?@V4TF zh+1}Z{5u_7zkqBmoypV0tVl8*aJ`lhn3o@W+xUr%1RS!Mtu_<)fD!GFbK zkuY^Jn9SQF#N)(cJ|Ql>zpdGP=HxH;y>=z}?sxSPfn{jTM7|{87D7q8R_sYjIO2PZ zxucLPzaYE4DSJn+&tUa0+`Y27t?MgfrR$vg+Y8%nURa)@nt$)t>$xHAE&k>&?+q`3 zujI}vPoBE;_nnI?z&Y*Tmrn1oOgt<=w_nQL*P+aa?YP&psP`Wu_i_Bua{M_yz@L#9 z)XRqE0=z%5bTh#8{?cVXu5=cfW*#CDq=3|eNYrOO!Aznc;{kb+^IsJwNkxt%F{bK? zuWFDiS$9oRdi355`Wq)4EL+emOJ5g#|FYeFYVO+2FC}gtIBgdjmSKjr&}wAsuJ)VV z^>?hD!$EqeCFc)r-F&Bh?49Y^%fdZ5&rZgh?50J$Yy1B-?Q2BU(JoXU}8S3PJA9+@I6)c1=sQ zjM=jMX8W6<^u@ULhls8>v?aQJ-A%Bjv0_#H?6#~k`JE>W<6DwB9uXXmdIxwkg*-fa zXeLjvdV|CWQWnVv^N2T}j3PdULQ^+w5Rd+KKD7-e_&j zxN)j&YU{06=I_tXzIFNdg%!7DRUJ-13=yYCa^(Nu*dxVl$O$9zCIM0ig6CdVFZmU7 z?Umo$D)H9uIHuZg@leLGvzZqcx-%+zja6T^E}r1+GX3Yw<*u=xT|PUC6RV?7(d>?r z@Fq*wblIKvYIc3JdUeK;z;iw05|i$}ao)T<+`EFf7_u|VJs&GJKKFS6ln@{s$zI^D z1EArFlyTrh9end>_kr>EZysqPi1Yn;UlD*w_l>kA-54>VX zD$bex^-lS#qYqMlCb~{r_MFe%ZT{<99~Qeh_GM|$yDiIZgJJhia-rA=^uno0t51!c zr8>agc0c`E^O4?~Q>yF8#{Kc?lRvbMq8HxHzsiR&6YgHWK?(LfJMXuRFY8P83q#YO Q=kduM?Oz{NRj;%yS5yodGJ;qY=hT9Rt&t&MF0+L*Ml z4%*$tW?&93>Qu__Hd5ZNl`Jw@fS@Jd6LJhITw71Ef44{TC*qgGk!MvTqoBVOc zV*_@E&DlMyWM^zSXJeuX`jG$dNrI<0>q5?L_Cn5Vgmn4i{aMpuy*VoK;bb

xi&H zJC*3q++&BMI6Pk59%<-udR&;3VG#!t!r`a@&VsS^&mv{0MH>wrH8EqYrK5&n^A4r~ zbuuuYu6E$)3gsLg7Y=(To9NuN8T#Xa1&vvOp?r4AZlUrWmU=sGCPS=+ru)hgYbAk= zq#QI?nek9eWk~Xf86051idf8*{y3485SP^!uM_A>K5CA*QBNZ;SnDHg_Bszj5@ayu zwsofQ1m=$Mwc%I-C+ZTOx~#7)%5e>q5q~@+uu>?9OAP5{8r{G{x~zJNv`Hk)OI{+G>wE@&Vc)x0I|>A)g2Z zp~fZ11{5)R(&4%UaC$0(P05&%cXzpwjGjPn$sf163ayITCPfqGW`sBlBLLGY#t84pY(}Z^&@DcB`#1sBg%7nKr2-WB|3T#$+vS za2W&9CSY$edH5)sN8;ubi*og~fVR8nTs)h#I_eP0AI~H`f(NZ^%QO)6Hj?SEP`2Cx zlPi@JDBdbo*W|lAzK)c>E+S={T%G_;*$8V41M~dx0=ZcSa}&Z}mzO^I3npS!Vvdg` zqheJo&nJ^nSva6R!j^n83I!ydNX7VQ!A$B}MLv_2bxqrrNVoJ>wZL9lC}ROWEy7~I za6u0gtynlMt8H3VvXq$4q{6|BDClmeS=bEQ7Syl5udHX`Ak;tsc3h~XQ2B<4Mi8_Xu!$C zqa=;dw8=mk5roAlBV#5g18#zyC=M~Qn1N;)j3F_SGZAKOb3vzj=cVft{j3009ZsJQ zM&&hvCAeT&`G|napKJ;7(WscpYnSzO4;c@-l@md?VslTiQlV51sU9DG@|Vlj9R$PF zL*Rk<{ybH2F{npMz)*E@gGxP0Njs1cpiDM~m8z{-UJ}E|C~%AHC@CG*>(J1Y1-T7O zlAXn+W3D?j?nEM^p-GJe1-FeWgF65h6>1HRnSJBRaPt83#~HK}l&c39=A~4q2UXs! zD$*7Qid4So!o=jEIb~NT*DU(&YQ8FQ8_D+bPv8FGMuj+f zXa3!7r?CU`_BS7C$SqlWajEd|Z>&}JBjDLR72BRlEB3wn_tLUEmM7P3{I)p%{!_%# z>|0+wxRnBTg5hvEDn=+2S5+#w)@m?9wnxeKAW#hdK!xlWt{STvz4dGoIVq@SMQeSO=?N#}?MgBSj?^SR@%%w3CJ z+A?!z?wq>LGVQ%-f4u+PuCF1jss)l0ZU4U zTb=b9GMTjWvH+P1ru1eqNv^0%C0fH#QDf)hd`Oh9J{m@ZS18~Gqpl;Tmm0;2!NpXO z>W#SJPT#H%r#wtGe>U+^?!cAVUz9&{ZpuBo_te~)43-Ukr}>ow+BbhYb7vc~dHAk- z@()z(U(TE|wmA1DsVA`&uW#*EOn?j=117^fDyFE$gR#p;e{=cDUQJ_j^WkH$uSbuW zTQT(bi}(P5G+}=|xbfJ_=Z^+nt2@4B6=SEiWirXxdVR7zTor`+nT?65ss4D09QgJscBW?J?_DL6xj*Btr*406x`rt!(Qab4mmket z-8OwMTGf@tM=^u>)$yvo%vwRqEC+OT(o+r@(h3Xqxw2z-`PXw zX7~?}zx1otRgM|${Hvh5xCo+tbsy^QSbX{q!pIZ*2j=qQ$kR1VL{JRv)x?5C_L)Bs z)&7e}J~!&;C-&Wojh(#k&2__;EzLjOvGuVHYn(b=F8rSF+3$X_d{h3@7jD~Jx##(h zxMiC?7iO-UxYm2BtYX8kTdQBV?-T2GVLPdx|9SGh4?IQbabF(IOaE#yW}5YX^X~fW z)7oF3ggh7nd2q`OJh-V6UKh%n(&T%>`h$rPgv`(d;h7e=ffmsFePTcbZ|x;U3up!l zd%QghRyFhy;%?e40XKEM3T+(#b&Zfo;L<)`9bqn+BX=2h-H|D?EfQ~JV;3Adb8 zf=Jl=)`qK>*4*mf{c^2t#h$S_Zsq6AU)FVhc;~CnUOct@}1wfQJGO5cmTC zMG+s+U$0dmT9szK|4-QZ$ZPorF3%eEQX=%o8|u~eWe=z39vb=P@RPqw9v;AOrHTWL zQX`%4dYpzy$Cf@e)q3UN=(5YFc4Sse+f)^ct_dwXI%Kg@6W!i?sOO|XQ~l38&}0vu Xdhz1NGa^siwrTS5cS`)zCLR1Y-~J2{ -- Gitee From fc17a4cf9c54492d76692d029374444b58a6c4b7 Mon Sep 17 00:00:00 2001 From: wangluyao Date: Sat, 7 Sep 2024 15:38:59 +0800 Subject: [PATCH 28/44] =?UTF-8?q?=E4=BD=BF=E7=94=A8shared=5Fptr=E6=99=BA?= =?UTF-8?q?=E8=83=BD=E6=8C=87=E9=92=88=E9=98=B2=E6=AD=A2=E6=8F=90=E5=89=8D?= =?UTF-8?q?=E6=9E=90=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangluyao --- interfaces/kits/js/BUILD.gn | 1 - .../kits/js/src/mod_fs/class_stream/flush.cpp | 102 ---------- .../kits/js/src/mod_fs/class_stream/flush.h | 34 ---- .../src/mod_fs/class_stream/stream_entity.h | 3 +- .../mod_fs/class_stream/stream_n_exporter.cpp | 177 ++++++++++++------ .../mod_fs/class_stream/stream_n_exporter.h | 10 + interfaces/kits/js/src/mod_fs/common_func.cpp | 3 +- interfaces/kits/js/src/mod_fs/common_func.h | 2 +- .../src/mod_fs/properties/create_stream.cpp | 16 +- .../js/src/mod_fs/properties/create_stream.h | 2 +- 10 files changed, 146 insertions(+), 204 deletions(-) delete mode 100755 interfaces/kits/js/src/mod_fs/class_stream/flush.cpp delete mode 100755 interfaces/kits/js/src/mod_fs/class_stream/flush.h diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index c98a406bb..d1e895ed6 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -214,7 +214,6 @@ ohos_shared_library("fs") { sources += [ "src/mod_fs/class_randomaccessfile/randomaccessfile_n_exporter.cpp", "src/mod_fs/class_readeriterator/readeriterator_n_exporter.cpp", - "src/mod_fs/class_stream/flush.cpp", "src/mod_fs/class_stream/stream_n_exporter.cpp", "src/mod_fs/class_tasksignal/task_signal_entity.cpp", "src/mod_fs/class_tasksignal/task_signal_n_exporter.cpp", diff --git a/interfaces/kits/js/src/mod_fs/class_stream/flush.cpp b/interfaces/kits/js/src/mod_fs/class_stream/flush.cpp deleted file mode 100755 index 105eab7ba..000000000 --- a/interfaces/kits/js/src/mod_fs/class_stream/flush.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "flush.h" - -#include -#include - -#include "class_stat/stat_entity.h" -#include "class_stat/stat_n_exporter.h" -#include "filemgmt_libhilog.h" -#include "stream_entity.h" - -namespace OHOS { -namespace FileManagement { -namespace ModuleFileIO { -using namespace std; -using namespace OHOS::FileManagement::LibN; - -napi_value Flush::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - HILOGE("Number of arguments unmatched"); - NError(EINVAL).ThrowErr(env); - return nullptr; - } - - auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { - HILOGE("Failed to get entity of Stream"); - NError(EIO).ThrowErr(env); - return nullptr; - } - - int ret = fflush(streamEntity->fp.get()); - if (ret < 0) { - HILOGE("Failed to fflush file in the stream, ret: %{public}d", ret); - NError(errno).ThrowErr(env); - return nullptr; - } - return NVal::CreateUndefined(env).val_; -} - -napi_value Flush::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { - HILOGE("Number of arguments unmatched"); - NError(EINVAL).ThrowErr(env); - return nullptr; - } - - auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { - HILOGE("Failed to get entity of Stream"); - NError(EIO).ThrowErr(env); - return nullptr; - } - - auto cbExec = [streamEntity]() -> NError { - if (!streamEntity || !streamEntity->fp) { - HILOGE("Stream has been closed in flush cbExec possibly"); - return NError(EIO); - } - int ret = fflush(streamEntity->fp.get()); - if (ret < 0) { - HILOGE("Failed to fflush file in the stream"); - return NError(errno); - } else { - return NError(ERRNO_NOERR); - } - }; - auto cbCompl = [](napi_env env, NError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ZERO) { - return NAsyncWorkPromise(env, thisVar).Schedule(PROCEDURE_STREAM_FLUSH_NAME, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::FIRST]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(PROCEDURE_STREAM_FLUSH_NAME, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace FileManagement -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_stream/flush.h b/interfaces/kits/js/src/mod_fs/class_stream/flush.h deleted file mode 100755 index aa7be7012..000000000 --- a/interfaces/kits/js/src/mod_fs/class_stream/flush.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_STREAM_FLUSH_H -#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_STREAM_FLUSH_H - -#include "filemgmt_libn.h" - -namespace OHOS { -namespace FileManagement { -namespace ModuleFileIO { -class Flush final { -public: - static napi_value Async(napi_env env, napi_callback_info info); - static napi_value Sync(napi_env env, napi_callback_info info); -}; - -const std::string PROCEDURE_STREAM_FLUSH_NAME = "FileIOStreamFlush"; -} // namespace ModuleFileIO -} // namespace FileManagement -} // namespace namespace OHOS -#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_STREAM_FLUSH_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_stream/stream_entity.h b/interfaces/kits/js/src/mod_fs/class_stream/stream_entity.h index 11cdae1dc..dc048fac1 100755 --- a/interfaces/kits/js/src/mod_fs/class_stream/stream_entity.h +++ b/interfaces/kits/js/src/mod_fs/class_stream/stream_entity.h @@ -16,11 +16,12 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_STREAM_ENTITY_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_STREAM_ENTITY_H +#include namespace OHOS { namespace FileManagement { namespace ModuleFileIO { struct StreamEntity { - std::unique_ptr fp = { nullptr, fclose }; + std::shared_ptr fp{ nullptr}; }; } // namespace ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp b/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp index d220521a9..a9bc267a7 100644 --- a/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp @@ -27,7 +27,6 @@ #include "common_func.h" #include "file_utils.h" #include "filemgmt_libhilog.h" -#include "flush.h" #include "rust_file.h" #include "stream_entity.h" @@ -36,6 +35,87 @@ namespace FileManagement { namespace ModuleFileIO { using namespace std; using namespace OHOS::FileManagement::LibN; +std::mutex StreamNExporter::mutex; +std::shared_ptr StreamNExporter::GetFilePtr(StreamEntity *streamEntity) +{ + std::lock_guard lock(mutex); + if (streamEntity) { + return streamEntity->fp; + } + return nullptr; +} + +napi_value StreamNExporter::FlushSync(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + HILOGE("Number of arguments unmatched"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + + auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + auto fp = GetFilePtr(streamEntity); + if (fp == nullptr) { + HILOGE("Failed to get entity of Stream"); + NError(EIO).ThrowErr(env); + return nullptr; + } + + int ret = fflush(fp.get()); + if (ret < 0) { + HILOGE("Failed to fflush file in the stream, ret: %{public}d", ret); + NError(errno).ThrowErr(env); + return nullptr; + } + return NVal::CreateUndefined(env).val_; +} + +napi_value StreamNExporter::Flush(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + HILOGE("Number of arguments unmatched"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + + auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + auto fp = GetFilePtr(streamEntity); + if (fp == nullptr) { + HILOGE("Failed to get entity of Stream"); + NError(EIO).ThrowErr(env); + return nullptr; + } + + auto cbExec = [fp]() -> NError { + if (!fp) { + HILOGE("Stream has been closed in flush cbExec possibly"); + return NError(EIO); + } + int ret = fflush(fp.get()); + if (ret < 0) { + HILOGE("Failed to fflush file in the stream"); + return NError(errno); + } else { + return NError(ERRNO_NOERR); + } + }; + auto cbCompl = [](napi_env env, NError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() == NARG_CNT::ZERO) { + return NAsyncWorkPromise(env, thisVar).Schedule(PROCEDURE_STREAM_FLUSH_NAME, cbExec, cbCompl).val_; + } else { + NVal cb(env, funcArg[NARG_POS::FIRST]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(PROCEDURE_STREAM_FLUSH_NAME, cbExec, cbCompl).val_; + } +} napi_value StreamNExporter::ReadSync(napi_env env, napi_callback_info cbInfo) { @@ -47,13 +127,13 @@ napi_value StreamNExporter::ReadSync(napi_env env, napi_callback_info cbInfo) } auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { + + auto fp = GetFilePtr(streamEntity); + if (fp == nullptr) { HILOGE("Failed to get entity of Stream"); NError(EIO).ThrowErr(env); return nullptr; } - FILE *filp = nullptr; - filp = streamEntity->fp.get(); auto [succ, buf, len, offset] = CommonFunc::GetReadArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); @@ -63,7 +143,7 @@ napi_value StreamNExporter::ReadSync(napi_env env, napi_callback_info cbInfo) } if (offset >= 0) { - int ret = fseek(filp, static_cast(offset), SEEK_SET); + int ret = fseek(fp.get(), static_cast(offset), SEEK_SET); if (ret < 0) { HILOGE("Failed to set the offset location of the file stream pointer, ret: %{public}d", ret); NError(errno).ThrowErr(env); @@ -71,8 +151,8 @@ napi_value StreamNExporter::ReadSync(napi_env env, napi_callback_info cbInfo) } } - size_t actLen = fread(buf, 1, len, filp); - if ((actLen != static_cast(len) && !feof(filp)) || ferror(filp)) { + size_t actLen = fread(buf, 1, len, fp.get()); + if ((actLen != static_cast(len) && !feof(fp.get())) || ferror(fp.get())) { HILOGE("Invalid buffer size and pointer, actlen: %{public}zu", actLen); NError(EIO).ThrowErr(env); return nullptr; @@ -89,16 +169,10 @@ napi_value StreamNExporter::CloseSync(napi_env env, napi_callback_info cbInfo) NError(EINVAL).ThrowErr(env); return nullptr; } - - auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { - HILOGE("Failed to get entity of Stream"); - NError(EIO).ThrowErr(env); - return nullptr; + { + std::lock_guard lock(mutex); + (void)NClass::RemoveEntityOfFinal(env, funcArg.GetThisVar()); } - streamEntity->fp.reset(); - (void)NClass::RemoveEntityOfFinal(env, funcArg.GetThisVar()); - return NVal::CreateUndefined(env).val_; } @@ -112,13 +186,12 @@ napi_value StreamNExporter::WriteSync(napi_env env, napi_callback_info cbInfo) } auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { + auto fp = GetFilePtr(streamEntity); + if (fp == nullptr) { HILOGE("Failed to get entity of Stream"); NError(EIO).ThrowErr(env); return nullptr; } - FILE *filp = nullptr; - filp = streamEntity->fp.get(); auto [succ, bufGuard, buf, len, offset] = CommonFunc::GetWriteArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); @@ -127,7 +200,7 @@ napi_value StreamNExporter::WriteSync(napi_env env, napi_callback_info cbInfo) return nullptr; } if (offset >= 0) { - int ret = fseek(filp, static_cast(offset), SEEK_SET); + int ret = fseek(fp.get(), static_cast(offset), SEEK_SET); if (ret < 0) { HILOGE("Failed to set the offset location of the file stream pointer, ret: %{public}d", ret); NError(errno).ThrowErr(env); @@ -135,7 +208,7 @@ napi_value StreamNExporter::WriteSync(napi_env env, napi_callback_info cbInfo) } } - size_t writeLen = fwrite(buf, 1, len, filp); + size_t writeLen = fwrite(buf, 1, len, fp.get()); if ((writeLen == 0) && (writeLen != len)) { HILOGE("Failed to fwrite stream"); NError(EIO).ThrowErr(env); @@ -145,7 +218,7 @@ napi_value StreamNExporter::WriteSync(napi_env env, napi_callback_info cbInfo) return NVal::CreateInt64(env, static_cast(writeLen)).val_; } -static napi_value WriteExec(napi_env env, NFuncArg &funcArg, StreamEntity *streamEntity) +static napi_value WriteExec(napi_env env, NFuncArg &funcArg, shared_ptr fp) { auto [succ, bufGuard, buf, len, offset] = CommonFunc::GetWriteArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); @@ -160,19 +233,19 @@ static napi_value WriteExec(napi_env env, NFuncArg &funcArg, StreamEntity *strea NError(ENOMEM).ThrowErr(env); return nullptr; } - auto cbExec = [arg, buf = buf, len = len, streamEntity, offset = offset]() -> NError { - if (!streamEntity || !streamEntity->fp.get()) { + auto cbExec = [arg, buf = buf, len = len, fp, offset = offset]() -> NError { + if (!fp.get()) { HILOGE("Stream has been closed in write cbExec possibly"); return NError(EIO); } if (offset >= 0) { - int ret = fseek(streamEntity->fp.get(), static_cast(offset), SEEK_SET); + int ret = fseek(fp.get(), static_cast(offset), SEEK_SET); if (ret < 0) { HILOGE("Failed to set the offset location of the file stream pointer, ret: %{public}d", ret); return NError(errno); } } - arg->actLen = fwrite(buf, 1, len, streamEntity->fp.get()); + arg->actLen = fwrite(buf, 1, len, fp.get()); if ((arg->actLen == 0) && (arg->actLen != len)) { HILOGE("Failed to fwrite stream"); return NError(EIO); @@ -186,7 +259,6 @@ static napi_value WriteExec(napi_env env, NFuncArg &funcArg, StreamEntity *strea } return { NVal::CreateInt64(env, static_cast(arg->actLen)) }; }; - NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::ONE || (funcArg.GetArgc() == NARG_CNT::TWO && !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function))) { @@ -208,15 +280,16 @@ napi_value StreamNExporter::Write(napi_env env, napi_callback_info cbInfo) } auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { - HILOGD("Failed to get entity of Stream"); + auto fp = GetFilePtr(streamEntity); + if (fp == nullptr) { + HILOGE("Failed to get entity of Stream"); NError(EIO).ThrowErr(env); return nullptr; } - return WriteExec(env, funcArg, streamEntity); + return WriteExec(env, funcArg, fp); } -static napi_value ReadExec(napi_env env, NFuncArg &funcArg, StreamEntity *streamEntity) +static napi_value ReadExec(napi_env env, NFuncArg &funcArg, shared_ptr fp) { auto [succ, buf, len, offset] = CommonFunc::GetReadArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); @@ -232,19 +305,19 @@ static napi_value ReadExec(napi_env env, NFuncArg &funcArg, StreamEntity *stream NError(ENOMEM).ThrowErr(env); return nullptr; } - auto cbExec = [arg, buf = buf, len = len, streamEntity, offset = offset]() -> NError { - if (!streamEntity || !streamEntity->fp.get()) { + auto cbExec = [arg, buf = buf, len = len, fp, offset = offset]() -> NError { + if (!fp.get()) { HILOGE("Stream has been closed in read cbExec possibly"); return NError(EIO); } if (offset >= 0) { - if (fseek(streamEntity->fp.get(), static_cast(offset), SEEK_SET) < 0) { + if (fseek(fp.get(), static_cast(offset), SEEK_SET) < 0) { HILOGE("Failed to set the offset location of the file stream pointer"); return NError(errno); } } - size_t actLen = fread(buf, 1, len, streamEntity->fp.get()); - if ((actLen != static_cast(len) && !feof(streamEntity->fp.get())) || ferror(streamEntity->fp.get())) { + size_t actLen = fread(buf, 1, len, fp.get()); + if ((actLen != static_cast(len) && !feof(fp.get())) || ferror(fp.get())) { HILOGE("Invalid buffer size and pointer, actlen: %{public}zu", actLen); return NError(EIO); } else { @@ -281,12 +354,13 @@ napi_value StreamNExporter::Read(napi_env env, napi_callback_info cbInfo) } auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { + auto fp = GetFilePtr(streamEntity); + if (fp == nullptr) { HILOGE("Failed to get entity of Stream"); NError(EIO).ThrowErr(env); return nullptr; } - return ReadExec(env, funcArg, streamEntity); + return ReadExec(env, funcArg, fp); } napi_value StreamNExporter::Close(napi_env env, napi_callback_info cbInfo) @@ -297,20 +371,15 @@ napi_value StreamNExporter::Close(napi_env env, napi_callback_info cbInfo) NError(EINVAL).ThrowErr(env); return nullptr; } - - auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { - HILOGE("Failed to get entity of Stream"); - NError(EIO).ThrowErr(env); - return nullptr; + StreamEntity* ret = nullptr; + { + std::lock_guard lock(mutex); + ret = NClass::RemoveEntityOfFinal(env, funcArg.GetThisVar()); } - - auto fp = NClass::RemoveEntityOfFinal(env, funcArg.GetThisVar()); - if (!fp) { + if (!ret) { NError(EINVAL).ThrowErr(env); return nullptr; } - auto cbExec = []() -> NError { return NError(ERRNO_NOERR); }; @@ -342,12 +411,12 @@ napi_value StreamNExporter::Seek(napi_env env, napi_callback_info cbInfo) } auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { + auto fp = GetFilePtr(streamEntity); + if (fp == nullptr) { HILOGE("Failed to get entity of Stream"); NError(EIO).ThrowErr(env); return nullptr; } - auto [succGetOffset, offset] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt64(); if (!succGetOffset) { HILOGE("Invalid offset from JS first argument"); @@ -367,14 +436,14 @@ napi_value StreamNExporter::Seek(napi_env env, napi_callback_info cbInfo) } if (offset >= 0) { - int ret = fseek(streamEntity->fp.get(), static_cast(offset), whence); + int ret = fseek(fp.get(), static_cast(offset), whence); if (ret < 0) { HILOGE("Failed to set the offset location of the file stream pointer, ret: %{public}d", ret); NError(errno).ThrowErr(env); return nullptr; } } - int64_t res = ftell(streamEntity->fp.get()); + int64_t res = ftell(fp.get()); if (res < 0) { HILOGE("Failed to tell, error:%{public}d", errno); NError(errno).ThrowErr(env); @@ -411,8 +480,8 @@ bool StreamNExporter::Export() { vector props = { NVal::DeclareNapiFunction("writeSync", WriteSync), - NVal::DeclareNapiFunction("flush", Flush::Async), - NVal::DeclareNapiFunction("flushSync", Flush::Sync), + NVal::DeclareNapiFunction("flush", Flush), + NVal::DeclareNapiFunction("flushSync", FlushSync), NVal::DeclareNapiFunction("readSync", ReadSync), NVal::DeclareNapiFunction("closeSync", CloseSync), NVal::DeclareNapiFunction("write", Write), diff --git a/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.h b/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.h index fb7f0fb3b..8b2a05bc7 100644 --- a/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.h +++ b/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.h @@ -18,12 +18,16 @@ #include "filemgmt_libn.h" +#include +#include "stream_entity.h" namespace OHOS { namespace FileManagement { namespace ModuleFileIO { using namespace OHOS::FileManagement::LibN; class StreamNExporter final : public NExporter { public: + static std::mutex mutex; + inline static const std::string className_ = "FsStream"; bool Export() override; @@ -34,11 +38,15 @@ public: static napi_value WriteSync(napi_env env, napi_callback_info cbInfo); static napi_value ReadSync(napi_env env, napi_callback_info cbInfo); static napi_value CloseSync(napi_env env, napi_callback_info cbInfo); + static napi_value FlushSync(napi_env env, napi_callback_info cbInfo); static napi_value Write(napi_env env, napi_callback_info cbInfo); static napi_value Read(napi_env env, napi_callback_info cbInfo); static napi_value Close(napi_env env, napi_callback_info cbInfo); static napi_value Seek(napi_env env, napi_callback_info cbInfo); + static napi_value Flush(napi_env env, napi_callback_info cbInfo); + + static std::shared_ptr GetFilePtr(StreamEntity *streamEntity); StreamNExporter(napi_env env, napi_value exports); ~StreamNExporter() override; @@ -65,6 +73,8 @@ struct AsyncWriteArg { const std::string PROCEDURE_STREAM_WRITE_NAME = "FileIOStreamWrite"; const std::string PROCEDURE_STREAM_READ_NAME = "FileIOStreamRead"; const std::string PROCEDURE_STREAM_CLOSE_NAME = "FileIOStreamClose"; +const std::string PROCEDURE_STREAM_FLUSH_NAME = "FileIOStreamFlush"; + } // namespace ModuleFileIO } // namespace FileManagement } // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fs/common_func.cpp b/interfaces/kits/js/src/mod_fs/common_func.cpp index 93d0e1c58..43aa39b31 100644 --- a/interfaces/kits/js/src/mod_fs/common_func.cpp +++ b/interfaces/kits/js/src/mod_fs/common_func.cpp @@ -251,7 +251,7 @@ NVal CommonFunc::InstantiateFile(napi_env env, int fd, const string &pathOrUri, return { env, objFile }; } -NVal CommonFunc::InstantiateStream(napi_env env, unique_ptr fp) +NVal CommonFunc::InstantiateStream(napi_env env, shared_ptr fp) { napi_value objStream = NClass::InstantiateClass(env, StreamNExporter::className_, {}); if (!objStream) { @@ -266,7 +266,6 @@ NVal CommonFunc::InstantiateStream(napi_env env, unique_ptrfp.swap(fp); return { env, objStream }; } diff --git a/interfaces/kits/js/src/mod_fs/common_func.h b/interfaces/kits/js/src/mod_fs/common_func.h index 2a51b3506..c99a7ee51 100644 --- a/interfaces/kits/js/src/mod_fs/common_func.h +++ b/interfaces/kits/js/src/mod_fs/common_func.h @@ -85,7 +85,7 @@ struct CommonFunc { #endif #ifndef WIN_PLATFORM static LibN::NVal InstantiateFile(napi_env env, int fd, const std::string &pathOrUri, bool isUri); - static LibN::NVal InstantiateStream(napi_env env, std::unique_ptr fp); + static LibN::NVal InstantiateStream(napi_env env, std::shared_ptr fp); #endif static std::tuple GetReadArg(napi_env env, napi_value readBuf, diff --git a/interfaces/kits/js/src/mod_fs/properties/create_stream.cpp b/interfaces/kits/js/src/mod_fs/properties/create_stream.cpp index 1440e4a5d..06b3b127a 100755 --- a/interfaces/kits/js/src/mod_fs/properties/create_stream.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/create_stream.cpp @@ -60,15 +60,14 @@ napi_value CreateStream::Sync(napi_env env, napi_callback_info info) NError(EINVAL).ThrowErr(env); return nullptr; } - - unique_ptr fp = { fopen(argPath.c_str(), argMode.c_str()), fclose }; - if (!fp) { + FILE *file = fopen(argPath.c_str(), argMode.c_str()); + if (!file) { HILOGE("Failed to fdopen file by path"); NError(errno).ThrowErr(env); return nullptr; } - - return CommonFunc::InstantiateStream(env, move(fp)).val_; + std::shared_ptr fp(file, fclose); + return CommonFunc::InstantiateStream(env, fp).val_; } napi_value CreateStream::Async(napi_env env, napi_callback_info info) @@ -93,11 +92,12 @@ napi_value CreateStream::Async(napi_env env, napi_callback_info info) return nullptr; } auto cbExec = [arg, argPath = move(argPath), argMode = move(argMode)]() -> NError { - arg->fp = { fopen(argPath.c_str(), argMode.c_str()), fclose }; - if (!arg->fp) { + FILE *file = fopen(argPath.c_str(), argMode.c_str()); + if (!file) { HILOGE("Failed to fdopen file by path"); return NError(errno); } + arg->fp = std::shared_ptr(file, fclose); return NError(ERRNO_NOERR); }; @@ -105,7 +105,7 @@ napi_value CreateStream::Async(napi_env env, napi_callback_info info) if (err) { return { env, err.GetNapiErr(env) }; } - return CommonFunc::InstantiateStream(env, move(arg->fp)); + return CommonFunc::InstantiateStream(env, arg->fp); }; NVal thisVar(env, funcArg.GetThisVar()); diff --git a/interfaces/kits/js/src/mod_fs/properties/create_stream.h b/interfaces/kits/js/src/mod_fs/properties/create_stream.h index 9e7b01493..66965860f 100755 --- a/interfaces/kits/js/src/mod_fs/properties/create_stream.h +++ b/interfaces/kits/js/src/mod_fs/properties/create_stream.h @@ -28,7 +28,7 @@ public: }; struct AsyncCreateStreamArg { - std::unique_ptr fp = { nullptr, fclose }; + std::shared_ptr fp; }; const std::string PROCEDURE_CREATESTREAM_NAME = "FileIOCreateStream"; -- Gitee From 9d325923c61b9735d700dbcc49321c708f75eaf6 Mon Sep 17 00:00:00 2001 From: guomeicen Date: Tue, 10 Sep 2024 06:58:33 +0000 Subject: [PATCH 29/44] update interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h. Signed-off-by: guomeicen --- .../kits/js/src/common/napi/n_async/n_async_work_callback.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h index 9bc6d5f3d..0f17d7720 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h @@ -23,7 +23,7 @@ namespace DistributedFS { class NAsyncWorkCallback : public NAsyncWorkFactory { public: NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb); - ~NAsyncWorkCallback() = default; + ~NAsyncWorkCallback(); NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; -- Gitee From d8b06cdc3b23d798ada44b0afcc5fa6bcb838cfd Mon Sep 17 00:00:00 2001 From: guomeicen Date: Tue, 10 Sep 2024 07:00:29 +0000 Subject: [PATCH 30/44] update interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp. Signed-off-by: guomeicen --- .../js/src/common/napi/n_async/n_async_work_callback.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp index 7cf9b21fe..0d761dea3 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp @@ -24,6 +24,13 @@ NAsyncWorkCallback::NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb) : NA { ctx_ = new(std::nothrow) NAsyncContextCallback(thisPtr, cb); } +NAsyncWorkCallback::~NAsyncWorkCallback() +{ + if(!ctx_){ + return; + } + delete ctx_; +} static void CallbackExecute(napi_env env, void *data) { -- Gitee From 1322dc058db052a150c9fa8eb2cffe36fa390cea Mon Sep 17 00:00:00 2001 From: guomeicen Date: Tue, 10 Sep 2024 08:09:18 +0000 Subject: [PATCH 31/44] update interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp. Signed-off-by: guomeicen --- .../kits/js/src/common/napi/n_async/n_async_work_callback.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp index 0d761dea3..75136db63 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp @@ -26,7 +26,7 @@ NAsyncWorkCallback::NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb) : NA } NAsyncWorkCallback::~NAsyncWorkCallback() { - if(!ctx_){ + if (!ctx_) { return; } delete ctx_; -- Gitee From 89f57613dc6f6bfae5f3b6c89a62fc7d76c9e83f Mon Sep 17 00:00:00 2001 From: guomeicen Date: Tue, 10 Sep 2024 09:00:09 +0000 Subject: [PATCH 32/44] update interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h. Signed-off-by: guomeicen --- .../kits/js/src/common/napi/n_async/n_async_work_callback.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h index 0f17d7720..1b78939eb 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h @@ -23,7 +23,7 @@ namespace DistributedFS { class NAsyncWorkCallback : public NAsyncWorkFactory { public: NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb); - ~NAsyncWorkCallback(); + ~NAsyncWorkCallback() override; NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; -- Gitee From a15beedd703c81f86ab4272da938813a227a030c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E6=B6=A6?= Date: Fri, 13 Sep 2024 09:23:05 +0000 Subject: [PATCH 33/44] update interfaces/test/unittest/BUILD.gn. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 陈润 --- interfaces/test/unittest/BUILD.gn | 1 - 1 file changed, 1 deletion(-) diff --git a/interfaces/test/unittest/BUILD.gn b/interfaces/test/unittest/BUILD.gn index b61ff4d24..95f924b84 100644 --- a/interfaces/test/unittest/BUILD.gn +++ b/interfaces/test/unittest/BUILD.gn @@ -16,7 +16,6 @@ group("unittest") { deps = [ "class_file:class_file_test", "filemgmt_libn_test:filemgmt_libn_test", - "napi_test:file_api_js_test", "remote_uri:remote_uri_test", "task_signal:task_signal_test", ] -- Gitee From d145af393b96525e7ee3184ebf649181c99eacb7 Mon Sep 17 00:00:00 2001 From: wangluyao Date: Sat, 14 Sep 2024 09:39:46 +0800 Subject: [PATCH 34/44] =?UTF-8?q?createStream=E9=81=97=E7=95=99=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E9=97=AD=E7=8E=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangluyao --- .../js/src/mod_fs/class_stream/stream_entity.h | 2 +- .../mod_fs/class_stream/stream_n_exporter.cpp | 12 ++++++++++++ .../js/src/mod_fs/properties/create_stream.cpp | 4 ++-- .../js/src/mod_fs/properties/create_stream.h | 2 +- .../js/src/mod_fs/properties/fdopen_stream.cpp | 16 ++++++++-------- .../js/src/mod_fs/properties/fdopen_stream.h | 3 ++- 6 files changed, 26 insertions(+), 13 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/class_stream/stream_entity.h b/interfaces/kits/js/src/mod_fs/class_stream/stream_entity.h index dc048fac1..e42c21e08 100755 --- a/interfaces/kits/js/src/mod_fs/class_stream/stream_entity.h +++ b/interfaces/kits/js/src/mod_fs/class_stream/stream_entity.h @@ -21,7 +21,7 @@ namespace OHOS { namespace FileManagement { namespace ModuleFileIO { struct StreamEntity { - std::shared_ptr fp{ nullptr}; + std::shared_ptr fp{ nullptr }; }; } // namespace ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp b/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp index a9bc267a7..6e218bc09 100644 --- a/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp @@ -169,6 +169,12 @@ napi_value StreamNExporter::CloseSync(napi_env env, napi_callback_info cbInfo) NError(EINVAL).ThrowErr(env); return nullptr; } + auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!streamEntity) { + HILOGE("Failed to get entity of Stream, may closed twice"); + NError(EIO).ThrowErr(env); + return nullptr; + } { std::lock_guard lock(mutex); (void)NClass::RemoveEntityOfFinal(env, funcArg.GetThisVar()); @@ -371,6 +377,12 @@ napi_value StreamNExporter::Close(napi_env env, napi_callback_info cbInfo) NError(EINVAL).ThrowErr(env); return nullptr; } + auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!streamEntity) { + HILOGE("Failed to get entity of Stream, may closed twice"); + NError(EIO).ThrowErr(env); + return nullptr; + } StreamEntity* ret = nullptr; { std::lock_guard lock(mutex); diff --git a/interfaces/kits/js/src/mod_fs/properties/create_stream.cpp b/interfaces/kits/js/src/mod_fs/properties/create_stream.cpp index 06b3b127a..7ace8cc18 100755 --- a/interfaces/kits/js/src/mod_fs/properties/create_stream.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/create_stream.cpp @@ -67,7 +67,7 @@ napi_value CreateStream::Sync(napi_env env, napi_callback_info info) return nullptr; } std::shared_ptr fp(file, fclose); - return CommonFunc::InstantiateStream(env, fp).val_; + return CommonFunc::InstantiateStream(env, move(fp)).val_; } napi_value CreateStream::Async(napi_env env, napi_callback_info info) @@ -105,7 +105,7 @@ napi_value CreateStream::Async(napi_env env, napi_callback_info info) if (err) { return { env, err.GetNapiErr(env) }; } - return CommonFunc::InstantiateStream(env, arg->fp); + return CommonFunc::InstantiateStream(env, move(arg->fp)); }; NVal thisVar(env, funcArg.GetThisVar()); diff --git a/interfaces/kits/js/src/mod_fs/properties/create_stream.h b/interfaces/kits/js/src/mod_fs/properties/create_stream.h index 66965860f..1e9d7e684 100755 --- a/interfaces/kits/js/src/mod_fs/properties/create_stream.h +++ b/interfaces/kits/js/src/mod_fs/properties/create_stream.h @@ -28,7 +28,7 @@ public: }; struct AsyncCreateStreamArg { - std::shared_ptr fp; + std::shared_ptr fp{ nullptr }; }; const std::string PROCEDURE_CREATESTREAM_NAME = "FileIOCreateStream"; diff --git a/interfaces/kits/js/src/mod_fs/properties/fdopen_stream.cpp b/interfaces/kits/js/src/mod_fs/properties/fdopen_stream.cpp index 4029464ed..1d6ababb4 100755 --- a/interfaces/kits/js/src/mod_fs/properties/fdopen_stream.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/fdopen_stream.cpp @@ -60,14 +60,13 @@ napi_value FdopenStream::Sync(napi_env env, napi_callback_info info) NError(EINVAL).ThrowErr(env); return nullptr; } - - unique_ptr fp = { fdopen(fd, mode.c_str()), fclose }; - if (!fp) { - HILOGE("Failed to fdopen file by fd:%{public}d", fd); + FILE *file = fdopen(fd, mode.c_str()); + if (!file) { + HILOGE("Failed to fdopen file by path"); NError(errno).ThrowErr(env); return nullptr; } - + std::shared_ptr fp(file, fclose); return CommonFunc::InstantiateStream(env, move(fp)).val_; } @@ -93,11 +92,12 @@ napi_value FdopenStream::Async(napi_env env, napi_callback_info info) return nullptr; } auto cbExec = [arg, fd = fd, mode = mode]() -> NError { - arg->fp = { fdopen(fd, mode.c_str()), fclose }; - if (!arg->fp) { - HILOGE("Failed to fdopen file by fd:%{public}d", fd); + FILE *file = fdopen(fd, mode.c_str()); + if (!file) { + HILOGE("Failed to fdopen file by path"); return NError(errno); } + arg->fp = std::shared_ptr(file, fclose); return NError(ERRNO_NOERR); }; diff --git a/interfaces/kits/js/src/mod_fs/properties/fdopen_stream.h b/interfaces/kits/js/src/mod_fs/properties/fdopen_stream.h index ed43f3d3b..4aaa92fda 100755 --- a/interfaces/kits/js/src/mod_fs/properties/fdopen_stream.h +++ b/interfaces/kits/js/src/mod_fs/properties/fdopen_stream.h @@ -17,6 +17,7 @@ #define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_FDOPEN_STREAM_H #include "filemgmt_libn.h" +#include namespace OHOS { namespace FileManagement { @@ -28,7 +29,7 @@ public: }; struct AsyncFdopenStreamArg { - std::unique_ptr fp = { nullptr, fclose }; + std::shared_ptr fp{ nullptr }; }; const std::string PROCEDURE_FDOPENSTREAM_NAME = "FileIOFdopenStream"; -- Gitee From 8c24cd7f28e1521026617c067c8c4a0a1b3f61ae Mon Sep 17 00:00:00 2001 From: wangluyao Date: Sat, 14 Sep 2024 06:35:20 +0000 Subject: [PATCH 35/44] update interfaces/kits/js/src/mod_fs/properties/fdopen_stream.h. Signed-off-by: wangluyao --- interfaces/kits/js/src/mod_fs/properties/fdopen_stream.h | 1 - 1 file changed, 1 deletion(-) diff --git a/interfaces/kits/js/src/mod_fs/properties/fdopen_stream.h b/interfaces/kits/js/src/mod_fs/properties/fdopen_stream.h index 4aaa92fda..0bdc3c49d 100755 --- a/interfaces/kits/js/src/mod_fs/properties/fdopen_stream.h +++ b/interfaces/kits/js/src/mod_fs/properties/fdopen_stream.h @@ -17,7 +17,6 @@ #define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_FDOPEN_STREAM_H #include "filemgmt_libn.h" -#include namespace OHOS { namespace FileManagement { -- Gitee From 283a21d6f2b3a1d610b05e2de161b3290f695539 Mon Sep 17 00:00:00 2001 From: liuzerun Date: Tue, 17 Sep 2024 03:01:39 +0000 Subject: [PATCH 36/44] fix mem_leak in Deleter Signed-off-by: liuzerun --- interfaces/kits/cj/src/copy_dir.cpp | 2 ++ interfaces/kits/cj/src/file_fs_impl.cpp | 6 ++++-- interfaces/kits/cj/src/list_file.cpp | 2 ++ interfaces/kits/js/src/mod_fs/properties/copy.cpp | 3 +++ interfaces/kits/js/src/mod_fs/properties/copydir.cpp | 3 +++ interfaces/kits/js/src/mod_fs/properties/listfile.cpp | 3 +++ interfaces/kits/js/src/mod_fs/properties/movedir.cpp | 3 +++ 7 files changed, 20 insertions(+), 2 deletions(-) diff --git a/interfaces/kits/cj/src/copy_dir.cpp b/interfaces/kits/cj/src/copy_dir.cpp index ab9357e74..f1404cfb9 100644 --- a/interfaces/kits/cj/src/copy_dir.cpp +++ b/interfaces/kits/cj/src/copy_dir.cpp @@ -64,6 +64,8 @@ static void Deleter(struct NameList *arg) } free(arg->namelist); arg->namelist = nullptr; + delete arg; + arg = nullptr; } static int CopyFile(const std::string &src, const std::string &dest, const int mode) diff --git a/interfaces/kits/cj/src/file_fs_impl.cpp b/interfaces/kits/cj/src/file_fs_impl.cpp index 0b271b8c8..e647288fb 100644 --- a/interfaces/kits/cj/src/file_fs_impl.cpp +++ b/interfaces/kits/cj/src/file_fs_impl.cpp @@ -476,11 +476,13 @@ struct NameListArg { static void Deleter(struct NameListArg *arg) { for (int i = 0; i < arg->num; i++) { - delete (arg->namelist)[i]; + free((arg->namelist)[i]); (arg->namelist)[i] = nullptr; } - delete arg->namelist; + free(arg->namelist); arg->namelist = nullptr; + delete arg; + arg = nullptr; } static int32_t FilterFunc(const struct dirent *filename) diff --git a/interfaces/kits/cj/src/list_file.cpp b/interfaces/kits/cj/src/list_file.cpp index 444e2abcc..2dc5e9bc4 100644 --- a/interfaces/kits/cj/src/list_file.cpp +++ b/interfaces/kits/cj/src/list_file.cpp @@ -203,6 +203,8 @@ static void Deleter(struct NameListArg *arg) } free(arg->namelist); arg->namelist = nullptr; + delete arg; + arg = nullptr; } static int FilterFileRes(const string &path, vector &dirents) diff --git a/interfaces/kits/js/src/mod_fs/properties/copy.cpp b/interfaces/kits/js/src/mod_fs/properties/copy.cpp index 2cf1da8bb..fa2b36bc7 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy.cpp @@ -345,6 +345,9 @@ static void Deleter(struct NameList *arg) (arg->namelist)[i] = nullptr; } free(arg->namelist); + arg->namelist = nullptr; + delete arg; + arg = nullptr; } std::string Copy::GetRealPath(const std::string& path) diff --git a/interfaces/kits/js/src/mod_fs/properties/copydir.cpp b/interfaces/kits/js/src/mod_fs/properties/copydir.cpp index 48c4cfb91..6444c2e6e 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copydir.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copydir.cpp @@ -106,6 +106,9 @@ static void Deleter(struct NameList *arg) (arg->namelist)[i] = nullptr; } free(arg->namelist); + arg->namelist = nullptr; + delete arg; + arg = nullptr; } static int CopyFile(const string &src, const string &dest, const int mode) diff --git a/interfaces/kits/js/src/mod_fs/properties/listfile.cpp b/interfaces/kits/js/src/mod_fs/properties/listfile.cpp index 777297995..46afa981f 100755 --- a/interfaces/kits/js/src/mod_fs/properties/listfile.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/listfile.cpp @@ -258,6 +258,9 @@ static void Deleter(struct NameListArg *arg) (arg->namelist)[i] = nullptr; } free(arg->namelist); + arg->namelist = nullptr; + delete arg; + arg = nullptr; } static int FilterFileRes(const string &path, vector &dirents) diff --git a/interfaces/kits/js/src/mod_fs/properties/movedir.cpp b/interfaces/kits/js/src/mod_fs/properties/movedir.cpp index 4a6a8781c..dd438202a 100644 --- a/interfaces/kits/js/src/mod_fs/properties/movedir.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/movedir.cpp @@ -194,6 +194,9 @@ static void Deleter(struct NameListArg *arg) (arg->namelist)[i] = nullptr; } free(arg->namelist); + arg->namelist = nullptr; + delete arg; + arg = nullptr; } static int RecurMoveDir(const string &srcPath, const string &destPath, const int mode, -- Gitee From 4ae6913ae23261d77c932168b361e5a5ada2ee43 Mon Sep 17 00:00:00 2001 From: liuzerun Date: Tue, 17 Sep 2024 04:02:46 +0000 Subject: [PATCH 37/44] add map clear Signed-off-by: liuzerun --- utils/filemgmt_libn/src/n_class.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/utils/filemgmt_libn/src/n_class.cpp b/utils/filemgmt_libn/src/n_class.cpp index 6c72fb57a..8d94c3625 100644 --- a/utils/filemgmt_libn/src/n_class.cpp +++ b/utils/filemgmt_libn/src/n_class.cpp @@ -83,6 +83,7 @@ void NClass::CleanClass(void *arg) HILOGE("Cannot del ref class constructor %{public}s because of %{public}d", it->first.c_str(), res); } } + nClass.exClassMap.clear(); } napi_value NClass::InstantiateClass(napi_env env, const string& className, const vector& args) -- Gitee From d10df7377914d538245b4e7434ca015ca73536bf Mon Sep 17 00:00:00 2001 From: guomeicen Date: Mon, 23 Sep 2024 17:37:29 +0800 Subject: [PATCH 38/44] file_api:fix declaration cbinfo definition info Signed-off-by: guomeicen --- .../kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp b/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp index 6e218bc09..6ef97b7d2 100644 --- a/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp @@ -45,9 +45,9 @@ std::shared_ptr StreamNExporter::GetFilePtr(StreamEntity *streamEntity) return nullptr; } -napi_value StreamNExporter::FlushSync(napi_env env, napi_callback_info info) +napi_value StreamNExporter::FlushSync(napi_env env, napi_callback_info cbinfo) { - NFuncArg funcArg(env, info); + NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ZERO)) { HILOGE("Number of arguments unmatched"); NError(EINVAL).ThrowErr(env); @@ -71,9 +71,9 @@ napi_value StreamNExporter::FlushSync(napi_env env, napi_callback_info info) return NVal::CreateUndefined(env).val_; } -napi_value StreamNExporter::Flush(napi_env env, napi_callback_info info) +napi_value StreamNExporter::Flush(napi_env env, napi_callback_info cbinfo) { - NFuncArg funcArg(env, info); + NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { HILOGE("Number of arguments unmatched"); NError(EINVAL).ThrowErr(env); -- Gitee From bec5f8223e880f5f7c8a3b1521bf3210adf20c49 Mon Sep 17 00:00:00 2001 From: guomeicen Date: Tue, 24 Sep 2024 09:18:13 +0000 Subject: [PATCH 39/44] update interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp. Signed-off-by: guomeicen --- .../kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp b/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp index 6ef97b7d2..a166a05f1 100644 --- a/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fs/class_stream/stream_n_exporter.cpp @@ -45,9 +45,9 @@ std::shared_ptr StreamNExporter::GetFilePtr(StreamEntity *streamEntity) return nullptr; } -napi_value StreamNExporter::FlushSync(napi_env env, napi_callback_info cbinfo) +napi_value StreamNExporter::FlushSync(napi_env env, napi_callback_info cbInfo) { - NFuncArg funcArg(env, cbinfo); + NFuncArg funcArg(env, cbInfo); if (!funcArg.InitArgs(NARG_CNT::ZERO)) { HILOGE("Number of arguments unmatched"); NError(EINVAL).ThrowErr(env); @@ -71,9 +71,9 @@ napi_value StreamNExporter::FlushSync(napi_env env, napi_callback_info cbinfo) return NVal::CreateUndefined(env).val_; } -napi_value StreamNExporter::Flush(napi_env env, napi_callback_info cbinfo) +napi_value StreamNExporter::Flush(napi_env env, napi_callback_info cbInfo) { - NFuncArg funcArg(env, cbinfo); + NFuncArg funcArg(env, cbInfo); if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { HILOGE("Number of arguments unmatched"); NError(EINVAL).ThrowErr(env); -- Gitee From 5fed8f5f0b7665abf6d89bf318fb4d25924eae68 Mon Sep 17 00:00:00 2001 From: l30052632 Date: Sat, 21 Sep 2024 09:57:25 +0800 Subject: [PATCH 40/44] file_api:add errCode for filesystem Signed-off-by: l30052632 --- .../kits/js/src/mod_fs/properties/copydir.cpp | 9 +++++---- interfaces/kits/js/src/mod_fs/properties/move.cpp | 3 ++- .../kits/js/src/mod_fs/properties/movedir.cpp | 14 ++++++++------ 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/properties/copydir.cpp b/interfaces/kits/js/src/mod_fs/properties/copydir.cpp index 6444c2e6e..e61809848 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copydir.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copydir.cpp @@ -48,13 +48,14 @@ static tuple, unique_ptr, int> ParseAndCheckJsO const NFuncArg &funcArg) { auto [resGetFirstArg, src, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8StringPath(); - if (!resGetFirstArg || !filesystem::is_directory(filesystem::status(src.get()))) { - HILOGE("Invalid src"); + std::error_code errCode; + if (!resGetFirstArg || !filesystem::is_directory(filesystem::status(src.get(), errCode))) { + HILOGE("Invalid src, errCode = %{public}d", errCode.value()); return { false, nullptr, nullptr, 0 }; } auto [resGetSecondArg, dest, unused] = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8StringPath(); - if (!resGetSecondArg || !filesystem::is_directory(filesystem::status(dest.get()))) { - HILOGE("Invalid dest"); + if (!resGetSecondArg || !filesystem::is_directory(filesystem::status(dest.get(), errCode))) { + HILOGE("Invalid dest, errCode = %{public}d", errCode.value()); return { false, nullptr, nullptr, 0 }; } if (!AllowToCopy(src.get(), dest.get())) { diff --git a/interfaces/kits/js/src/mod_fs/properties/move.cpp b/interfaces/kits/js/src/mod_fs/properties/move.cpp index 59e7fb97f..f75481d88 100644 --- a/interfaces/kits/js/src/mod_fs/properties/move.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/move.cpp @@ -37,7 +37,8 @@ using namespace OHOS::FileManagement::LibN; #ifdef __MUSL__ static bool CheckDir(const string &path) { - if (!filesystem::is_directory(filesystem::status(path))) { + std::error_code errCode; + if (!filesystem::is_directory(filesystem::status(path, errCode))) { return false; } return true; diff --git a/interfaces/kits/js/src/mod_fs/properties/movedir.cpp b/interfaces/kits/js/src/mod_fs/properties/movedir.cpp index dd438202a..ecb833420 100644 --- a/interfaces/kits/js/src/mod_fs/properties/movedir.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/movedir.cpp @@ -41,7 +41,7 @@ static tuple JudgeExistAndEmpty(const string &path) std::error_code errCode; filesystem::path pathName(path); if (filesystem::exists(pathName, errCode)) { - if (filesystem::is_empty(pathName)) { + if (filesystem::is_empty(pathName, errCode)) { return { true, true }; } return { true, false }; @@ -81,13 +81,14 @@ static int RemovePath(const string& pathStr) static tuple, unique_ptr, int> ParseJsOperand(napi_env env, const NFuncArg& funcArg) { auto [resGetFirstArg, src, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8StringPath(); - if (!resGetFirstArg || !filesystem::is_directory(filesystem::status(src.get()))) { - HILOGE("Invalid src"); + std::error_code errCode; + if (!resGetFirstArg || !filesystem::is_directory(filesystem::status(src.get(), errCode))) { + HILOGE("Invalid src, errCode = %{public}d", errCode.value()); return { false, nullptr, nullptr, 0 }; } auto [resGetSecondArg, dest, unused] = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8StringPath(); - if (!resGetSecondArg || !filesystem::is_directory(filesystem::status(dest.get()))) { - HILOGE("Invalid dest"); + if (!resGetSecondArg || !filesystem::is_directory(filesystem::status(dest.get(), errCode))) { + HILOGE("Invalid dest,errCode = %{public}d", errCode.value()); return { false, nullptr, nullptr, 0 }; } int mode = 0; @@ -203,7 +204,8 @@ static int RecurMoveDir(const string &srcPath, const string &destPath, const int deque &errfiles) { filesystem::path dpath(destPath); - if (!filesystem::is_directory(dpath)) { + std::error_code errCode; + if (!filesystem::is_directory(dpath, errCode)) { errfiles.emplace_front(srcPath, destPath); return ERRNO_NOERR; } -- Gitee From cd6dde7ba616797e3b7a0be94710a7609c6812a4 Mon Sep 17 00:00:00 2001 From: liuzerun Date: Thu, 26 Sep 2024 13:39:01 +0000 Subject: [PATCH 41/44] fixup for copydir Signed-off-by: liuzerun --- .../kits/js/src/mod_fs/properties/copydir.cpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/properties/copydir.cpp b/interfaces/kits/js/src/mod_fs/properties/copydir.cpp index 6444c2e6e..d3c7d9633 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copydir.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copydir.cpp @@ -35,10 +35,23 @@ using namespace OHOS::FileManagement::LibN; static int RecurCopyDir(const string &srcPath, const string &destPath, const int mode, vector &errfiles); +static bool EndWithSlash(const string &src) +{ + return src.back() == '/'; +} + static bool AllowToCopy(const string &src, const string &dest) { - if (dest.find(src) == 0 || filesystem::path(src).parent_path() == dest) { - HILOGE("Failed to copy file"); + if (src == dest) { + HILOGE("Failed to copy file, the same path"); + return false; + } + if (EndWithSlash(src) ? dest.find(src) == 0 : dest.find(src + "/") == 0) { + HILOGE("Failed to copy file, dest is under src"); + return false; + } + if (filesystem::path(src).parent_path() == dest) { + HILOGE("Failed to copy file, src's parent path is dest"); return false; } return true; -- Gitee From d9f6056b7fa6608060001ea3c09534c503f6a135 Mon Sep 17 00:00:00 2001 From: l30052632 Date: Sun, 29 Sep 2024 17:49:51 +0800 Subject: [PATCH 42/44] zr set fd -2 before close Signed-off-by: l30052632 --- .../kits/js/src/mod_fs/class_watcher/watcher_entity.cpp | 7 +++++-- utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp | 5 ++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/watcher_entity.cpp b/interfaces/kits/js/src/mod_fs/class_watcher/watcher_entity.cpp index 384c0ae20..379b7bf2c 100644 --- a/interfaces/kits/js/src/mod_fs/class_watcher/watcher_entity.cpp +++ b/interfaces/kits/js/src/mod_fs/class_watcher/watcher_entity.cpp @@ -117,8 +117,12 @@ int FileWatcher::NotifyToWatchNewEvents(const string &fileName, const int &wd, c int FileWatcher::CloseNotifyFd() { int closeRet = ERRNO_NOERR; + int fd = notifyFd_; + if (watcherInfoSet_.size() == 0) { - closeRet = close(notifyFd_); + run_ = false; + notifyFd_ = -1; + closeRet = close(fd); if (closeRet != 0) { HILOGE("Failed to stop notify close fd errCode:%{public}d", errno); } @@ -128,7 +132,6 @@ int FileWatcher::CloseNotifyFd() HILOGE("Failed to close eventfd errCode:%{public}d", errno); } eventFd_ = -1; - run_ = false; } return closeRet; diff --git a/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp b/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp index 8fc3bfd09..74cf5a5e2 100644 --- a/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp +++ b/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp @@ -214,8 +214,11 @@ void NAsyncWorkCallback::ThreadSafeSchedule(NContextCBComplete cbComplete) work->data = static_cast(workArgs.get()); int ret = uv_queue_work( - loop, work.get(), [](uv_work_t *work) {}, + loop, work.get(), [](uv_work_t *work) { + HILOGI("Enter, %{public}zu", (size_t)work); + }, [](uv_work_t *work, int status) { + HILOGI("AsyncWork Enter, %{public}zu", (size_t)work); auto workArgs = static_cast(work->data); AfterWorkCallback(workArgs->ptr->env_, napi_ok, workArgs->ptr->ctx_, workArgs->cb); delete workArgs; -- Gitee From e6db4a763bf884999b139b1b10b9ef476631e990 Mon Sep 17 00:00:00 2001 From: runrunya Date: Mon, 7 Oct 2024 09:12:32 +0800 Subject: [PATCH 43/44] remove IsAllPath Signed-off-by: runrunya --- .../js/src/mod_fs/properties/copy_file.cpp | 46 ++----------------- 1 file changed, 4 insertions(+), 42 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_file.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_file.cpp index 8858f554d..7446d8454 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_file.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_file.cpp @@ -33,33 +33,6 @@ namespace ModuleFileIO { using namespace std; using namespace OHOS::FileManagement::LibN; -static NError IsAllPath(FileInfo& srcFile, FileInfo& destFile) -{ -#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) - filesystem::path srcPath(string(srcFile.path.get())); - filesystem::path dstPath(string(destFile.path.get())); - error_code errCode; - if (!filesystem::copy_file(srcPath, dstPath, filesystem::copy_options::overwrite_existing, errCode)) { - HILOGE("Failed to copy file, error code: %{public}d", errCode.value()); - return NError(errCode.value()); - } -#else - std::unique_ptr copyfile_req = { - new (nothrow) uv_fs_t, CommonFunc::fs_req_cleanup }; - if (!copyfile_req) { - HILOGE("Failed to request heap memory."); - return NError(ENOMEM); - } - int ret = uv_fs_copyfile(nullptr, copyfile_req.get(), srcFile.path.get(), destFile.path.get(), - UV_FS_COPYFILE_FICLONE, nullptr); - if (ret < 0) { - HILOGE("Failed to copy file when all parameters are paths"); - return NError(ret); - } -#endif - return NError(ERRNO_NOERR); -} - static NError SendFileCore(FileInfo& srcFdg, FileInfo& destFdg, struct stat& statbf) { std::unique_ptr sendfile_req = { @@ -229,18 +202,10 @@ napi_value CopyFile::Sync(napi_env env, napi_callback_info info) return nullptr; } - if (src.isPath && dest.isPath) { - auto err = IsAllPath(src, dest); - if (err) { - err.ThrowErr(env); - return nullptr; - } - } else { - auto err = OpenFile(src, dest); - if (err) { - err.ThrowErr(env); - return nullptr; - } + auto err = OpenFile(src, dest); + if (err) { + err.ThrowErr(env); + return nullptr; } return NVal::CreateUndefined(env).val_; } @@ -276,9 +241,6 @@ napi_value CopyFile::Async(napi_env env, napi_callback_info info) return nullptr; } auto cbExec = [para]() -> NError { - if (para->src_.isPath && para->dest_.isPath) { - return IsAllPath(para->src_, para->dest_); - } return OpenFile(para->src_, para->dest_); }; -- Gitee From 2d209f67621a941d6162ab4bcaa6cb2c23566f6b Mon Sep 17 00:00:00 2001 From: liuhan53 Date: Tue, 8 Oct 2024 16:07:52 +0800 Subject: [PATCH 44/44] fix cj open&list leak Signed-off-by: liuhan53 --- interfaces/kits/cj/src/file_impl.cpp | 8 ++++---- interfaces/kits/cj/src/list_file.cpp | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/interfaces/kits/cj/src/file_impl.cpp b/interfaces/kits/cj/src/file_impl.cpp index f60a1580d..56b2b3627 100644 --- a/interfaces/kits/cj/src/file_impl.cpp +++ b/interfaces/kits/cj/src/file_impl.cpp @@ -211,9 +211,9 @@ std::tuple> FileEntity::Open(const char* path, int64_t return { ENOMEM, nullptr}; } auto fileUri = FFIData::Create(std::move(fileEntity->fd_), fileEntity->path_, fileEntity->uri_); + delete(fileEntity); + fileEntity = nullptr; if (!fileUri) { - delete(fileEntity); - fileEntity = nullptr; return {ENOMEM, nullptr}; } return {SUCCESS_CODE, fileUri}; @@ -229,9 +229,9 @@ std::tuple> FileEntity::Open(const char* path, int64_t return { ENOMEM, nullptr}; } auto filePath = FFIData::Create(std::move(file->fd_), file->path_, file->uri_); + delete(file); + file = nullptr; if (!filePath) { - delete(file); - file = nullptr; return {ENOMEM, nullptr}; } return {SUCCESS_CODE, filePath}; diff --git a/interfaces/kits/cj/src/list_file.cpp b/interfaces/kits/cj/src/list_file.cpp index 2dc5e9bc4..1942675db 100644 --- a/interfaces/kits/cj/src/list_file.cpp +++ b/interfaces/kits/cj/src/list_file.cpp @@ -269,7 +269,7 @@ static char** VectorToCArrString(vector &vec) break; } if (strcpy_s(result[i], vec[i].length() + 1, vec[i].c_str()) != 0) { - free(result[i]); + delete[] result[i]; result[i] = nullptr; break; } @@ -277,7 +277,7 @@ static char** VectorToCArrString(vector &vec) } if (temp != vec.size()) { for (size_t j = temp; j > 0; j--) { - free(result[j - 1]); + delete[] result[j - 1]; result[j - 1] = nullptr; } delete[] result; -- Gitee