From 2ea171698a7316fc8811eac5b201fee6ca31afd9 Mon Sep 17 00:00:00 2001 From: wuyunxun Date: Sat, 12 Apr 2025 19:59:28 +0800 Subject: [PATCH 1/3] =?UTF-8?q?BackupExtensionAbility=E6=8E=A5=E5=8F=A3IDL?= =?UTF-8?q?=E5=8C=96=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wuyunxun Change-Id: Icb7d49ee1a51df83713594defb7b6e5f38e039cf --- frameworks/native/backup_ext/BUILD.gn | 2 + frameworks/native/backup_ext/ani/BUILD.gn | 62 +++---- ...hos.application.BackupExtensionAbility.ets | 12 +- .../ani/include/ext_backup_loader.h | 38 ----- .../backup_ext/ani/src/ext_backup_loader.cpp | 48 ------ .../backup_ext/{ani => }/include/ani_utils.h | 153 ++---------------- .../{ani => }/include/ext_backup_ani.h | 10 +- .../native/backup_ext/src/ext_backup.cpp | 5 +- .../{ani => }/src/ext_backup_ani.cpp | 34 +++- test/fuzztest/backupext_fuzzer/BUILD.gn | 2 + tests/unittests/backup_ext/BUILD.gn | 6 + 11 files changed, 83 insertions(+), 289 deletions(-) delete mode 100644 frameworks/native/backup_ext/ani/include/ext_backup_loader.h delete mode 100644 frameworks/native/backup_ext/ani/src/ext_backup_loader.cpp rename frameworks/native/backup_ext/{ani => }/include/ani_utils.h (59%) rename frameworks/native/backup_ext/{ani => }/include/ext_backup_ani.h (90%) rename frameworks/native/backup_ext/{ani => }/src/ext_backup_ani.cpp (78%) diff --git a/frameworks/native/backup_ext/BUILD.gn b/frameworks/native/backup_ext/BUILD.gn index ec60d87cd..1a0f4628b 100644 --- a/frameworks/native/backup_ext/BUILD.gn +++ b/frameworks/native/backup_ext/BUILD.gn @@ -28,6 +28,7 @@ ohos_shared_library("backup_extension_ability_native") { sources = [ "src/ext_backup.cpp", + "src/ext_backup_ani.cpp", "src/ext_backup_context.cpp", "src/ext_backup_context_js.cpp", "src/ext_backup_js.cpp", @@ -76,6 +77,7 @@ ohos_shared_library("backup_extension_ability_native") { "ipc:ipc_core", "ipc:ipc_napi", "napi:ace_napi", + "runtime_core:ani", "samgr:samgr_proxy", ] diff --git a/frameworks/native/backup_ext/ani/BUILD.gn b/frameworks/native/backup_ext/ani/BUILD.gn index 098ebf899..6d325e06d 100644 --- a/frameworks/native/backup_ext/ani/BUILD.gn +++ b/frameworks/native/backup_ext/ani/BUILD.gn @@ -13,50 +13,28 @@ import("//build/config/components/ets_frontend/ets2abc_config.gni") import("//build/ohos.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") -group("backup_ext_ani_package") { - deps = [ ":backup_ext_ani" ] -} - -ohos_shared_library("backup_ext_ani") { - sanitize = { - integer_overflow = true - ubsan = true - boundary_sanitize = true - cfi = true - cfi_cross_dso = true - debug = false +if (support_jsapi) { + group("backup_ext_ani_package") { + deps = [ + ":backup_ext_abc_etc", + ] } - sources = [ "src/ext_backup_ani.cpp" ] - - include_dirs = [ - "include", - "../include", - ] - - deps = [ "${path_backup}/utils:backup_utils" ] - - external_deps = [ - "ability_base:want", - "ability_runtime:ability_context_native", - "ability_runtime:abilitykit_native", - "ability_runtime:app_context", - "ability_runtime:appkit_native", - "ability_runtime:extensionkit_native", - "ability_runtime:runtime", - "access_token:libaccesstoken_sdk", - "bundle_framework:appexecfwk_core", - "c_utils:utils", - "hilog:libhilog", - "hitrace:hitrace_meter", - "ipc:ipc_core", - "runtime_core:ani", - "samgr:samgr_proxy", - ] + generate_static_abc("backup_ext_abc") { + base_url = "./ets" + files = [ "./ets/@ohos.application.BackupExtensionAbility.ets" ] + dst_file = "$target_out_dir/backup_ext.abc" + out_puts = [ "$target_out_dir/backup_ext.abc" ] + is_boot_abc = "True" + device_dst_file = "/system/framework/backup_ext.abc" + } - subsystem_name = "filemanagement" - part_name = "app_file_service" - output_extension = "so" + ohos_prebuilt_etc("backup_ext_abc_etc") { + source = "$target_out_dir/backup_ext.abc" + module_install_dir = "framework" + subsystem_name = "filemanagement" + part_name = "app_file_service" + deps = [ ":backup_ext_abc" ] + } } diff --git a/frameworks/native/backup_ext/ani/ets/@ohos.application.BackupExtensionAbility.ets b/frameworks/native/backup_ext/ani/ets/@ohos.application.BackupExtensionAbility.ets index aeafebc73..b5aedba5e 100644 --- a/frameworks/native/backup_ext/ani/ets/@ohos.application.BackupExtensionAbility.ets +++ b/frameworks/native/backup_ext/ani/ets/@ohos.application.BackupExtensionAbility.ets @@ -15,16 +15,16 @@ export interface BundleVersion { - public code: number; - public name: string; + code: number; + name: string; } -class BundleVersionInner extends BundleVersion { +export class BundleVersionInner implements BundleVersion { public code: number; public name: string; } -export default class BackupExtensionAbility { - onBackup(): void; - onRestore(bundleVersion: BundleVersion): void; +export default abstract class BackupExtensionAbility { + abstract onBackup(): void; + abstract onRestore(bundleVersion: BundleVersion): void; } \ No newline at end of file diff --git a/frameworks/native/backup_ext/ani/include/ext_backup_loader.h b/frameworks/native/backup_ext/ani/include/ext_backup_loader.h deleted file mode 100644 index cb1951b6b..000000000 --- a/frameworks/native/backup_ext/ani/include/ext_backup_loader.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2025 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 OHOS_FILEMGMT_BACKUP_EXT_BACKUP_LOADER_H -#define OHOS_FILEMGMT_BACKUP_EXT_BACKUP_LOADER_H - -#include "extension_module_loader.h" - -namespace OHOS::FileManagement::Backup { -class ExtBackupLoader : public AbilityRuntime::ExtensionModuleLoader, public Singleton { - DECLARE_SINGLETON(ExtBackupLoader); - -public: - /** - * @brief Create Extension. - * - * @param runtime The runtime. - * @return The Extension instance. - */ - AbilityRuntime::Extension *Create(const std::unique_ptr &runtime) const override; - - virtual std::map GetParams() override; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_EXT_BACKUP_LOADER_H \ No newline at end of file diff --git a/frameworks/native/backup_ext/ani/src/ext_backup_loader.cpp b/frameworks/native/backup_ext/ani/src/ext_backup_loader.cpp deleted file mode 100644 index 82b465d25..000000000 --- a/frameworks/native/backup_ext/ani/src/ext_backup_loader.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2025 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 "ext_backup_loader.h" - -#include "ext_backup_ani.h" -#include "filemgmt_libhilog.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -ExtBackupLoader::ExtBackupLoader() = default; -ExtBackupLoader::~ExtBackupLoader() = default; - -AbilityRuntime::Extension *ExtBackupLoader::Create(const unique_ptr &runtime) const -{ - HILOGI("Create as an BackupExtensionAbility(Loader)"); - return ExtBackupAni::Create(runtime); -} - -map ExtBackupLoader::GetParams() -{ - HILOGI("Register as an extension ability"); - return { - // Type 即为 Extension 类型,定义在 ExtensionAbilityType 这一枚举类中。具体位置见 extension_ability_info.h - {"type", "9"}, - {"name", "BackupExtensionAbility"}, - }; -} - -extern "C" __attribute__((visibility("default"))) void *OHOS_EXTENSION_GetExtensionModule() -{ - HILOGI("Load as a library"); - return &ExtBackupLoader::GetInstance(); -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_ext/ani/include/ani_utils.h b/frameworks/native/backup_ext/include/ani_utils.h similarity index 59% rename from frameworks/native/backup_ext/ani/include/ani_utils.h rename to frameworks/native/backup_ext/include/ani_utils.h index 6ce270f0c..03cbc44f1 100644 --- a/frameworks/native/backup_ext/ani/include/ani_utils.h +++ b/frameworks/native/backup_ext/include/ani_utils.h @@ -190,31 +190,31 @@ private: }; template <> -bool UnionAccessor::IsInstanceOfType() +inline bool UnionAccessor::IsInstanceOfType() { return IsInstanceOf("Lstd/core/Boolean;"); } template <> -bool UnionAccessor::IsInstanceOfType() +inline bool UnionAccessor::IsInstanceOfType() { return IsInstanceOf("Lstd/core/Int;"); } template <> -bool UnionAccessor::IsInstanceOfType() +inline bool UnionAccessor::IsInstanceOfType() { return IsInstanceOf("Lstd/core/Double;"); } template <> -bool UnionAccessor::IsInstanceOfType() +inline bool UnionAccessor::IsInstanceOfType() { return IsInstanceOf("Lstd/core/String;"); } template <> -bool UnionAccessor::TryConvert(bool &value) +inline bool UnionAccessor::TryConvert(bool &value) { if (!IsInstanceOfType()) { return false; @@ -230,7 +230,7 @@ bool UnionAccessor::TryConvert(bool &value) } template <> -bool UnionAccessor::TryConvert(int &value) +inline bool UnionAccessor::TryConvert(int &value) { if (!IsInstanceOfType()) { return false; @@ -246,7 +246,7 @@ bool UnionAccessor::TryConvert(int &value) } template <> -bool UnionAccessor::TryConvert(double &value) +inline bool UnionAccessor::TryConvert(double &value) { if (!IsInstanceOfType()) { return false; @@ -262,7 +262,7 @@ bool UnionAccessor::TryConvert(double &value) } template <> -bool UnionAccessor::TryConvert(std::string &value) +inline bool UnionAccessor::TryConvert(std::string &value) { if (!IsInstanceOfType()) { return false; @@ -272,120 +272,6 @@ bool UnionAccessor::TryConvert(std::string &value) return true; } -template <> -bool UnionAccessor::TryConvertArray(std::vector &value) -{ - ani_double length; - if (ANI_OK != env_->Object_GetPropertyByName_Double(obj_, "length", &length)) { - std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; - return false; - } - for (int i = 0; i < int(length); i++) { - ani_ref ref; - if (ANI_OK != env_->Object_CallMethodByName_Ref(obj_, "$_get", "I:Lstd/core/Object;", &ref, (ani_int)i)) { - std::cerr << "Object_GetPropertyByName_Ref failed" << std::endl; - return false; - } - ani_boolean val; - if (ANI_OK != env_->Object_CallMethodByName_Boolean(static_cast(ref), "unboxed", nullptr, &val)) { - std::cerr << "Object_CallMethodByName_Double unbox failed" << std::endl; - return false; - } - value.push_back(static_cast(val)); - } - return true; -} - -template <> -bool UnionAccessor::TryConvertArray(std::vector &value) -{ - ani_double length; - if (ANI_OK != env_->Object_GetPropertyByName_Double(obj_, "length", &length)) { - std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; - return false; - } - for (int i = 0; i < int(length); i++) { - ani_ref ref; - if (ANI_OK != env_->Object_CallMethodByName_Ref(obj_, "$_get", "I:Lstd/core/Object;", &ref, (ani_int)i)) { - std::cerr << "Object_GetPropertyByName_Ref failed" << std::endl; - return false; - } - ani_int intValue; - if (ANI_OK != env_->Object_CallMethodByName_Int(static_cast(ref), "unboxed", nullptr, &intValue)) { - std::cerr << "Object_CallMethodByName_Double unbox failed" << std::endl; - return false; - } - value.push_back(static_cast(intValue)); - } - return true; -} - -template <> -bool UnionAccessor::TryConvertArray(std::vector &value) -{ - ani_double length; - if (ANI_OK != env_->Object_GetPropertyByName_Double(obj_, "length", &length)) { - std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; - return false; - } - for (int i = 0; i < int(length); i++) { - ani_ref ref; - if (ANI_OK != env_->Object_CallMethodByName_Ref(obj_, "$_get", "I:Lstd/core/Object;", &ref, (ani_int)i)) { - std::cerr << "Object_GetPropertyByName_Ref failed" << std::endl; - return false; - } - ani_double val; - if (ANI_OK != env_->Object_CallMethodByName_Double(static_cast(ref), "unboxed", nullptr, &val)) { - std::cerr << "Object_CallMethodByName_Double unbox failed" << std::endl; - return false; - } - value.push_back(static_cast(val)); - } - return true; -} - -template <> -bool UnionAccessor::TryConvertArray(std::vector &value) -{ - std::cout << "TryConvertArray std::vector" << std::endl; - ani_ref buffer; - if (ANI_OK != env_->Object_GetFieldByName_Ref(obj_, "buffer", &buffer)) { - std::cout << "Object_GetFieldByName_Ref failed" << std::endl; - return false; - } - void *data; - size_t length; - if (ANI_OK != env_->ArrayBuffer_GetInfo(static_cast(buffer), &data, &length)) { - std::cerr << "ArrayBuffer_GetInfo failed" << std::endl; - return false; - } - std::cout << "Length of buffer is " << length << std::endl; - for (size_t i = 0; i < length; i++) { - value.push_back(static_cast(data)[i]); - } - return true; -} - -template <> -bool UnionAccessor::TryConvertArray(std::vector &value) -{ - ani_double length; - if (ANI_OK != env_->Object_GetPropertyByName_Double(obj_, "length", &length)) { - std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; - return false; - } - - for (int i = 0; i < int(length); i++) { - ani_ref ref; - if (ANI_OK != env_->Object_CallMethodByName_Ref(obj_, "$_get", "I:Lstd/core/Object;", &ref, (ani_int)i)) { - std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; - return false; - } - value.push_back(AniStringUtils::ToStd(env_, static_cast(ref))); - } - return true; -} - class OptionalAccessor { public: OptionalAccessor(ani_env *env, ani_object &obj) : env_(env), obj_(obj) {} @@ -406,7 +292,7 @@ private: }; template <> -std::optional OptionalAccessor::Convert() +inline std::optional OptionalAccessor::Convert() { if (IsUndefined()) { return std::nullopt; @@ -421,25 +307,4 @@ std::optional OptionalAccessor::Convert() return value; } -template <> -std::optional OptionalAccessor::Convert() -{ - if (IsUndefined()) { - return std::nullopt; - } - - ani_size strSize; - env_->String_GetUTF8Size(static_cast(obj_), &strSize); - - std::vector buffer(strSize + 1); - char *utf8_buffer = buffer.data(); - - ani_size bytes_written = 0; - env_->String_GetUTF8(static_cast(obj_), utf8_buffer, strSize + 1, &bytes_written); - - utf8_buffer[bytes_written] = '\0'; - std::string content = std::string(utf8_buffer); - return content; -} - #endif diff --git a/frameworks/native/backup_ext/ani/include/ext_backup_ani.h b/frameworks/native/backup_ext/include/ext_backup_ani.h similarity index 90% rename from frameworks/native/backup_ext/ani/include/ext_backup_ani.h rename to frameworks/native/backup_ext/include/ext_backup_ani.h index 4a19383c4..7e2aa9237 100644 --- a/frameworks/native/backup_ext/ani/include/ext_backup_ani.h +++ b/frameworks/native/backup_ext/include/ext_backup_ani.h @@ -16,15 +16,14 @@ #ifndef EXT_BACKUP_ANI_H #define EXT_BACKUP_ANI_H -#include "ani_utils.h" #include "ext_backup_context.h" -#include "extension_base.h" +#include "ext_backup.h" #include "runtime.h" #include "sts_runtime.h" namespace OHOS::FileManagement::Backup { -class ExtBackupAni : public AbilityRuntime::ExtensionBase { +class ExtBackupAni : public ExtBackup { public: void Init(const std::shared_ptr &record, const std::shared_ptr &application, @@ -35,10 +34,10 @@ public: static ExtBackupAni *Create(const std::unique_ptr &runtime); ErrCode OnBackup(std::function callback, - std::function callbackEx); + std::function callbackEx) override; ErrCode OnRestore(std::function callback, - std::function callbackEx); + std::function callbackEx) override; public: explicit ExtBackupAni(AbilityRuntime::Runtime &runtime); @@ -50,7 +49,6 @@ private: private: AbilityRuntime::STSRuntime &stsRuntime_; - ani_env *env_; std::unique_ptr etsObj_; }; diff --git a/frameworks/native/backup_ext/src/ext_backup.cpp b/frameworks/native/backup_ext/src/ext_backup.cpp index e75dcf5f8..0ade1dff8 100644 --- a/frameworks/native/backup_ext/src/ext_backup.cpp +++ b/frameworks/native/backup_ext/src/ext_backup.cpp @@ -31,6 +31,7 @@ #include "b_json/b_json_cached_entity.h" #include "b_json/b_json_entity_extension_config.h" #include "b_resources/b_constants.h" +#include "ext_backup_ani.h" #include "ext_backup_js.h" #include "ext_extension.h" #include "filemgmt_libhilog.h" @@ -75,7 +76,9 @@ ExtBackup *ExtBackup::Create(const unique_ptr &runtime) case AbilityRuntime::Runtime::Language::JS: HILOGD("Create as BackupExtensionAbility(JS)"); return ExtBackupJs::Create(runtime); - + case AbilityRuntime::Runtime::Language::STS: + HILOGD("Create as BackupExtensionAbility(STS)"); + return ExtBackupAni::Create(runtime); default: HILOGD("Create as BackupExtensionAbility(base)"); return new ExtBackup(); diff --git a/frameworks/native/backup_ext/ani/src/ext_backup_ani.cpp b/frameworks/native/backup_ext/src/ext_backup_ani.cpp similarity index 78% rename from frameworks/native/backup_ext/ani/src/ext_backup_ani.cpp rename to frameworks/native/backup_ext/src/ext_backup_ani.cpp index d5ac5d1ab..859744265 100644 --- a/frameworks/native/backup_ext/ani/src/ext_backup_ani.cpp +++ b/frameworks/native/backup_ext/src/ext_backup_ani.cpp @@ -14,6 +14,8 @@ */ #include "ext_backup_ani.h" + +#include "ani_utils.h" #include "b_error/b_error.h" #include "b_error/b_excep_utils.h" #include "filemgmt_libhilog.h" @@ -25,7 +27,6 @@ ExtBackupAni::ExtBackupAni(AbilityRuntime::Runtime &runtime) : stsRuntime_(static_cast(runtime)) { HILOGI("Create as an BackupExtensionAbility"); - env_ = stsRuntime_.GetAniEnv(); } ExtBackupAni::~ExtBackupAni() @@ -74,24 +75,49 @@ void ExtBackupAni::Init(const std::shared_ptr &r ErrCode ExtBackupAni::CallEtsOnBackup() { - if (ANI_OK != env_->Object_CallMethodByName_Void(etsObj_->aniObj, "onBackup", nullptr)) { + ani_vm *vm = nullptr; + if (ANI_OK != stsRuntime_.GetAniEnv()->GetVM(&vm)) { + return EINVAL; + } + ani_env *env = nullptr; + ani_options aniArgs {0, nullptr}; + if (ANI_OK != vm->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &env)) { + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + return EINVAL; + } + } + if (ANI_OK != env->Object_CallMethodByName_Void(etsObj_->aniObj, "onBackup", nullptr)) { HILOGE("Failed to call the method: onBackup"); return EINVAL; } + vm->DetachCurrentThread(); return ERR_OK; } ErrCode ExtBackupAni::CallEtsOnRestore() { - ani_object bundleVersionObj = AniObjectUtils::Create(env_, "LBundleVersionInner;"); + ani_vm *vm = nullptr; + if (ANI_OK != stsRuntime_.GetAniEnv()->GetVM(&vm)) { + return EINVAL; + } + ani_env *env = nullptr; + ani_options aniArgs {0, nullptr}; + if (ANI_OK != vm->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &env)) { + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + return EINVAL; + } + } + const std::string className = "L@ohos/application/BackupExtensionAbility/BundleVersionInner;"; + ani_object bundleVersionObj = AniObjectUtils::Create(env, className.c_str()); if (nullptr == bundleVersionObj) { HILOGE("Failed to Create the BundleVersionInner"); return EINVAL; } - if (ANI_OK != env_->Object_CallMethodByName_Void(etsObj_->aniObj, "onRestore", nullptr, bundleVersionObj)) { + if (ANI_OK != env->Object_CallMethodByName_Void(etsObj_->aniObj, "onRestore", nullptr, bundleVersionObj)) { HILOGE("Failed to call the method: onRestore"); return EINVAL; } + vm->DetachCurrentThread(); return ERR_OK; } diff --git a/test/fuzztest/backupext_fuzzer/BUILD.gn b/test/fuzztest/backupext_fuzzer/BUILD.gn index 81a738cca..4b68f3461 100644 --- a/test/fuzztest/backupext_fuzzer/BUILD.gn +++ b/test/fuzztest/backupext_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("BackupExtFuzzTest") { ] sources = [ "${path_backup}/frameworks/native/backup_ext/src/ext_backup.cpp", + "${path_backup}/frameworks/native/backup_ext/src/ext_backup_ani.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_backup_context.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_backup_context_js.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_backup_js.cpp", @@ -70,6 +71,7 @@ ohos_fuzztest("BackupExtFuzzTest") { "ipc:ipc_napi", "jsoncpp:jsoncpp", "napi:ace_napi", + "runtime_core:ani", ] defines = [ diff --git a/tests/unittests/backup_ext/BUILD.gn b/tests/unittests/backup_ext/BUILD.gn index aa8aa1317..5fd0ef93d 100644 --- a/tests/unittests/backup_ext/BUILD.gn +++ b/tests/unittests/backup_ext/BUILD.gn @@ -134,6 +134,7 @@ ohos_unittest("tar_file_test") { sources = [ "${path_backup}/frameworks/native/backup_ext/src/ext_backup.cpp", + "${path_backup}/frameworks/native/backup_ext/src/ext_backup_ani.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_backup_context.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_backup_context_js.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_backup_js.cpp", @@ -187,6 +188,7 @@ ohos_unittest("tar_file_test") { "ipc:ipc_core", "ipc:ipc_napi", "napi:ace_napi", + "runtime_core:ani", "samgr:samgr_proxy", ] @@ -209,6 +211,7 @@ ohos_unittest("untar_file_sup_test") { sources = [ "${path_backup}/frameworks/native/backup_ext/src/ext_backup.cpp", + "${path_backup}/frameworks/native/backup_ext/src/ext_backup_ani.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_backup_context.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_backup_context_js.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_backup_js.cpp", @@ -264,6 +267,7 @@ ohos_unittest("untar_file_sup_test") { "ipc:ipc_core", "ipc:ipc_napi", "napi:ace_napi", + "runtime_core:ani", "samgr:samgr_proxy", ] @@ -285,6 +289,7 @@ ohos_unittest("untar_file_test") { sources = [ "${path_backup}/frameworks/native/backup_ext/src/ext_backup.cpp", + "${path_backup}/frameworks/native/backup_ext/src/ext_backup_ani.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_backup_context.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_backup_context_js.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_backup_js.cpp", @@ -338,6 +343,7 @@ ohos_unittest("untar_file_test") { "ipc:ipc_core", "ipc:ipc_napi", "napi:ace_napi", + "runtime_core:ani", "samgr:samgr_proxy", ] -- Gitee From 05549d2565c5793ce6eb5a7c1aac888d53925bf3 Mon Sep 17 00:00:00 2001 From: xying6 Date: Wed, 16 Apr 2025 16:40:19 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfileuri=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xying6 Change-Id: Iae97fd76aa18277c3108c8ea82b107ed5c953b2f --- interfaces/kits/ani/file_share/BUILD.gn | 1 + .../ani/file_share/ets/@ohos.fileshare.ets | 13 ++-- .../ani/file_share/src/ani_file_share.cpp | 57 +++++++++++----- interfaces/kits/ani/file_uri/BUILD.gn | 1 + .../kits/ani/file_uri/src/ani_file_uri.cpp | 67 ++++++++++--------- 5 files changed, 84 insertions(+), 55 deletions(-) diff --git a/interfaces/kits/ani/file_share/BUILD.gn b/interfaces/kits/ani/file_share/BUILD.gn index 772e9e259..6acb23f62 100644 --- a/interfaces/kits/ani/file_share/BUILD.gn +++ b/interfaces/kits/ani/file_share/BUILD.gn @@ -56,6 +56,7 @@ ohos_shared_library("fileshare_ani") { "hilog:libhilog", "init:libbegetutil", "ipc:ipc_core", + "napi:ace_napi", "runtime_core:ani", ] part_name = "app_file_service" diff --git a/interfaces/kits/ani/file_share/ets/@ohos.fileshare.ets b/interfaces/kits/ani/file_share/ets/@ohos.fileshare.ets index caa55189d..2ab89f5a3 100644 --- a/interfaces/kits/ani/file_share/ets/@ohos.fileshare.ets +++ b/interfaces/kits/ani/file_share/ets/@ohos.fileshare.ets @@ -16,34 +16,35 @@ import type { AsyncCallback } from '@ohos.base'; import { BusinessError } from '@ohos.base'; import type wantConstant from '@ohos.app.ability.wantConstant'; +import hilog from '@ohos.hilog' export namespace fileShare { loadLibrary("fileshare_ani") export function grantUriPermission(uri: string, bundleName: string, flag: wantConstant.Flags, callback: AsyncCallback): void { - console.log("Start grantUriPermission in callback main thread."); + hilog.info(0x0000, 'grantUriPermission', "Start grantUriPermission in callback main thread."); let p1 = taskpool.execute(grantUriPermissionSync, uri, bundleName, flag); p1.then((err: NullishType) => { let error: BusinessError; callback(error, undefined); }); p1.catch((err: NullishType) => { - console.log("grantUriPermission catch in callback thread."); - let error: BusinessError; + hilog.info(0x0000, 'grantUriPermission', "grantUriPermission catch in callback thread."); + let error = err as BusinessError; callback(error, undefined); }); } export function grantUriPermission(uri: string, bundleName: string, flag: wantConstant.Flags): Promise { - console.log("Start grantUriPermission in promise main thread"); + hilog.info(0x0000, 'grantUriPermission', "Start grantUriPermission in promise main thread"); let p = new Promise((resolve: (value: undefined) => void, reject: (error: Object) => void): void => { let p1 = taskpool.execute(grantUriPermissionSync, uri, bundleName, flag); p1.then((e: NullishType): void => { resolve(undefined); }); p1.catch((e: Error): void => { - console.log("grantUriPermission catch in promise thread."); + hilog.info(0x0000, 'grantUriPermission', "grantUriPermission catch in promise thread."); reject(e); }); }); @@ -51,7 +52,7 @@ export namespace fileShare { } export function grantUriPermissionSync(uri: string, bundleName: string, flag: wantConstant.Flags):int { - console.log("Start grantUriPermissionSync in thread."); + hilog.info(0x0000, 'grantUriPermission', "Start grantUriPermissionSync in thread."); grantUriPermissionInner(uri, bundleName, flag); return 0; } diff --git a/interfaces/kits/ani/file_share/src/ani_file_share.cpp b/interfaces/kits/ani/file_share/src/ani_file_share.cpp index 800b8e50f..2a12db932 100644 --- a/interfaces/kits/ani/file_share/src/ani_file_share.cpp +++ b/interfaces/kits/ani/file_share/src/ani_file_share.cpp @@ -23,6 +23,7 @@ #include "datashare_values_bucket.h" #include "ipc_skeleton.h" #include "log.h" +#include "n_error.h" #include "remote_uri.h" #include "tokenid_kit.h" #include "uri.h" @@ -31,6 +32,7 @@ using namespace OHOS::DataShare; using namespace OHOS::DistributedFS::ModuleRemoteUri; +using namespace OHOS::FileManagement::LibN; namespace OHOS { namespace AppFileService { @@ -62,24 +64,41 @@ static ani_int ParseEnumToInt(ani_env *env, ani_enum_item enumItem) return intValue; } -static ani_error CreateAniError(ani_env *env, std::string&& errMsg) +static void ThrowBusinessError(ani_env *env, int errCode, std::string&& errMsg) { - static const char *errorClsName = "Lescompat/Error;"; + LOGD("Begin ThrowBusinessError."); + static const char *errorClsName = "L@ohos/base/BusinessError;"; ani_class cls {}; if (ANI_OK != env->FindClass(errorClsName, &cls)) { - LOGE("%{public}s: Not found namespace %{public}s.", __func__, errorClsName); - return nullptr; + LOGE("find class BusinessError %{public}s failed", errorClsName); + return; } ani_method ctor; - if (ANI_OK != env->Class_FindMethod(cls, "", "Lstd/core/String;:V", &ctor)) { - LOGE("%{public}s: Not found in %{public}s.", __func__, errorClsName); - return nullptr; + if (ANI_OK != env->Class_FindMethod(cls, "", ":V", &ctor)) { + LOGE("find method BusinessError.constructor failed"); + return; } - ani_string error_msg; - env->String_NewUTF8(errMsg.c_str(), 17U, &error_msg); ani_object errorObject; - env->Object_New(cls, ctor, &errorObject, error_msg); - return static_cast(errorObject); + if (ANI_OK != env->Object_New(cls, ctor, &errorObject)) { + LOGE("create BusinessError object failed"); + return; + } + ani_double aniErrCode = static_cast(errCode); + ani_string errMsgStr; + if (ANI_OK != env->String_NewUTF8(errMsg.c_str(), errMsg.size(), &errMsgStr)) { + LOGE("convert errMsg to ani_string failed"); + return; + } + if (ANI_OK != env->Object_SetFieldByName_Double(errorObject, "code", aniErrCode)) { + LOGE("set error code failed"); + return; + } + if (ANI_OK != env->Object_SetPropertyByName_Ref(errorObject, "message", errMsgStr)) { + LOGE("set error message failed"); + return; + } + env->ThrowError(static_cast(errorObject)); + return; } static bool IsSystemApp() @@ -234,8 +253,7 @@ static void GrantUriPermission(ani_env *env, ani_string uri, ani_string bundleNa LOGD("Enter GrantUriPermission."); if (!IsSystemApp()) { LOGE("%{public}s: GrantUriPermission is not System App!", __func__); - ani_error error = CreateAniError(env, "GrantUriPermission is not System App!"); - env->ThrowError(error); + ThrowBusinessError(env, E_PERMISSION_SYS, "FileShare::GrantUriPermission is not System App!"); return; } @@ -243,8 +261,7 @@ static void GrantUriPermission(ani_env *env, ani_string uri, ani_string bundleNa std::string uriStr = ParseObjToStr(env, uri); if (!CheckValidPublicUri(uriStr)) { LOGE("%{public}s: GrantUriPermission uri is not valid!", __func__); - ani_error error = CreateAniError(env, "GrantUriPermission uri is not valid!"); - env->ThrowError(error); + ThrowBusinessError(env, EINVAL, "GrantUriPermission uri is not valid!"); return; } uriPermInfo.uri = uriStr; @@ -254,8 +271,7 @@ static void GrantUriPermission(ani_env *env, ani_string uri, ani_string bundleNa ani_int wantConstantFlag = ParseEnumToInt(env, static_cast(enumIndex)); if (wantConstantFlag < 0) { LOGE("%{public}s: GrantUriPermission ParseEnumToInt Faild!", __func__); - ani_error error = CreateAniError(env, "GrantUriPermission ParseEnumToInt Faild!"); - env->ThrowError(error); + ThrowBusinessError(env, EINVAL, "GrantUriPermission is not System App!"); return; } uriPermInfo.flag = wantConstantFlag; @@ -264,7 +280,12 @@ static void GrantUriPermission(ani_env *env, ani_string uri, ani_string bundleNa uriStr.c_str(), bundleNameStr.c_str(), wantConstantFlag, uriPermInfo.mode.c_str()); int ret = DoGrantUriPermission(uriPermInfo); - LOGD("DoGrantUriPermission ret: %{public}d.", ret); + if (ret < 0) { + LOGE("FileShare::GrantUriPermission DoGrantUriPermission failed with %{public}d", ret); + ThrowBusinessError(env, -ret, "GrantUriPermission failed"); + return; + } + LOGD("FileShare::GrantUriPermission DoGrantUriPermission successfully!"); } } // namespace ModuleFileShare } // namespace AppFileService diff --git a/interfaces/kits/ani/file_uri/BUILD.gn b/interfaces/kits/ani/file_uri/BUILD.gn index c3545159d..7fad45cea 100644 --- a/interfaces/kits/ani/file_uri/BUILD.gn +++ b/interfaces/kits/ani/file_uri/BUILD.gn @@ -49,6 +49,7 @@ ohos_shared_library("fileuri_ani") { "file_api:filemgmt_libn", "hilog:libhilog", "ipc:ipc_core", + "napi:ace_napi", "runtime_core:ani", "samgr:samgr_proxy", ] diff --git a/interfaces/kits/ani/file_uri/src/ani_file_uri.cpp b/interfaces/kits/ani/file_uri/src/ani_file_uri.cpp index ee5c314bd..e7f181117 100644 --- a/interfaces/kits/ani/file_uri/src/ani_file_uri.cpp +++ b/interfaces/kits/ani/file_uri/src/ani_file_uri.cpp @@ -20,6 +20,7 @@ #include "file_uri_entity.h" #include "file_utils.h" #include "log.h" +#include "n_error.h" using namespace OHOS::AppFileService; @@ -47,24 +48,41 @@ static ModuleFileUri::FileUriEntity *unwrapp(ani_env *env, ani_object object) return reinterpret_cast(fileuriEntity_); } -static ani_error CreateAniError(ani_env *env, std::string&& errMsg) +static void ThrowBusinessError(ani_env *env, int errCode, std::string&& errMsg) { - static const char *errorClsName = "Lescompat/Error;"; + LOGD("Begin ThrowBusinessError."); + static const char *errorClsName = "L@ohos/base/BusinessError;"; ani_class cls {}; if (ANI_OK != env->FindClass(errorClsName, &cls)) { - LOGE("Not found %{public}s.", errorClsName); - return nullptr; + LOGE("find class BusinessError %{public}s failed", errorClsName); + return; } ani_method ctor; - if (ANI_OK != env->Class_FindMethod(cls, "", "Lstd/core/String;:V", &ctor)) { - LOGE("Not found method in %{public}s.", errorClsName); - return nullptr; + if (ANI_OK != env->Class_FindMethod(cls, "", ":V", &ctor)) { + LOGE("find method BusinessError.constructor failed"); + return; } - ani_string error_msg; - env->String_NewUTF8(errMsg.c_str(), 17U, &error_msg); ani_object errorObject; - env->Object_New(cls, ctor, &errorObject, error_msg); - return static_cast(errorObject); + if (ANI_OK != env->Object_New(cls, ctor, &errorObject)) { + LOGE("create BusinessError object failed"); + return; + } + ani_double aniErrCode = static_cast(errCode); + ani_string errMsgStr; + if (ANI_OK != env->String_NewUTF8(errMsg.c_str(), errMsg.size(), &errMsgStr)) { + LOGE("convert errMsg to ani_string failed"); + return; + } + if (ANI_OK != env->Object_SetFieldByName_Double(errorObject, "code", aniErrCode)) { + LOGE("set error code failed"); + return; + } + if (ANI_OK != env->Object_SetPropertyByName_Ref(errorObject, "message", errMsgStr)) { + LOGE("set error message failed"); + return; + } + env->ThrowError(static_cast(errorObject)); + return; } static ani_string GetUriFromPath(ani_env *env, ani_string stringObj) @@ -72,18 +90,11 @@ static ani_string GetUriFromPath(ani_env *env, ani_string stringObj) LOGD("Enter GetUriFromPath"); ani_string uriObj = nullptr; std::string path = ParseObjToStr(env, stringObj); - if (path == "") { - LOGE("GetUriFromPath get path parameter failed!"); - ani_error err = CreateAniError(env, "GetUriFromPath get path parameter failed!"); - env->ThrowError(err); - return uriObj; - } std::string uri = CommonFunc::GetUriFromPath(path); if (uri == "") { LOGE("CommonFunc::GetUriFromPath failed!"); - ani_error err = CreateAniError(env, "GetUriFromPath failed!"); - env->ThrowError(err); + ThrowBusinessError(env, OHOS::FileManagement::LibN::E_PARAMS, "CommonFunc::GetUriFromPath failed!"); return uriObj; } LOGD("GetUriFromPath uri: %{public}s", uri.c_str()); @@ -99,15 +110,13 @@ void FileUriConstructor(ani_env *env, ani_object obj, ani_string stringObj) std::string path = ParseObjToStr(env, stringObj); if (path == "") { LOGE("FileUriConstructor get path parameter failed!"); - ani_error err = CreateAniError(env, "GetUriFromPath get path parameter failed!"); - env->ThrowError(err); + ThrowBusinessError(env, EINVAL, "Failed to get path"); return; } auto fileuriEntity = OHOS::FileManagement::CreateUniquePtr(path); if (fileuriEntity == nullptr) { LOGE("Failed to request heap memory."); - ani_error err = CreateAniError(env, "Failed to request heap memory."); - env->ThrowError(err); + ThrowBusinessError(env, ENOMEM, "Failed to request heap memory."); return; } LOGD("FileUriConstructor fileuriEntity: %{public}p.", fileuriEntity.get()); @@ -115,8 +124,7 @@ void FileUriConstructor(ani_env *env, ani_object obj, ani_string stringObj) ani_namespace ns; if (env->FindNamespace("L@ohos/file/fileuri/fileUri;", &ns) != ANI_OK) { LOGE("Namespace L@ohos/file/fileuri/fileUri not found."); - ani_error err = CreateAniError(env, "Namespace L@ohos/file/fileuri/fileUri not found."); - env->ThrowError(err); + ThrowBusinessError(env, EPERM, "Namespace L@ohos/file/fileuri/fileUri not found."); return; }; @@ -124,23 +132,20 @@ void FileUriConstructor(ani_env *env, ani_object obj, ani_string stringObj) static const char *className = "LFileUri;"; if (env->Namespace_FindClass(ns, className, &cls) != ANI_OK) { LOGE("Not found class LFileUri in Namespace L@ohos/file/fileuri/fileUri."); - ani_error err = CreateAniError(env, "Class LFileUri not found."); - env->ThrowError(err); + ThrowBusinessError(env, EPERM, "Class LFileUri not found."); return; } ani_method acquireObj; if (ANI_OK != env->Class_FindMethod(cls, "acquireFileUriEntity", "J:V", &acquireObj)) { LOGE("Not found method acquireFileUriEntity in class LFileUri."); - ani_error err = CreateAniError(env, "Method acquireFileUriEntity not found."); - env->ThrowError(err); + ThrowBusinessError(env, EPERM, "Method acquireFileUriEntity not found."); return; } if (ANI_OK != env->Object_CallMethod_Void(obj, acquireObj, reinterpret_cast(fileuriEntity.get()))) { LOGE("Call method acquireFileUriEntity failed."); - ani_error err = CreateAniError(env, "Call method acquireFileUriEntity failed."); - env->ThrowError(err); + ThrowBusinessError(env, EPERM, "Call method acquireFileUriEntity failed."); return; } } -- Gitee From 978e53d63abfa11417dd4902391ccb3c522b6dc5 Mon Sep 17 00:00:00 2001 From: xushunjie Date: Sun, 27 Apr 2025 17:31:44 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fileuri=20nativeptr=20=E6=94=B9=E9=80=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: Ib1d82b27a04dea1220618587e4d62f5145142dd0 --- interfaces/kits/ani/file_uri/BUILD.gn | 1 + .../ani/file_uri/ets/@ohos.file.fileuri.ets | 43 ++++++ .../file_uri/include/ani_util_native_ptr.h | 144 ++++++++++++++++++ .../kits/ani/file_uri/src/ani_file_uri.cpp | 30 +++- 4 files changed, 211 insertions(+), 7 deletions(-) create mode 100644 interfaces/kits/ani/file_uri/include/ani_util_native_ptr.h diff --git a/interfaces/kits/ani/file_uri/BUILD.gn b/interfaces/kits/ani/file_uri/BUILD.gn index 7fad45cea..bd7dd815c 100644 --- a/interfaces/kits/ani/file_uri/BUILD.gn +++ b/interfaces/kits/ani/file_uri/BUILD.gn @@ -32,6 +32,7 @@ ohos_shared_library("fileuri_ani") { ] include_dirs = [ + "include", "../../../common/include", "../../js/file_uri", "${app_file_service_path}/interfaces/innerkits/native/file_uri/include", diff --git a/interfaces/kits/ani/file_uri/ets/@ohos.file.fileuri.ets b/interfaces/kits/ani/file_uri/ets/@ohos.file.fileuri.ets index 0e2afd40d..cb55e7603 100644 --- a/interfaces/kits/ani/file_uri/ets/@ohos.file.fileuri.ets +++ b/interfaces/kits/ani/file_uri/ets/@ohos.file.fileuri.ets @@ -15,6 +15,42 @@ import uri from '@ohos.uri'; +class Cleaner { + static callback(cleaner: Cleaner): void { + console.println("enter Cleaner.callback"); + cleaner.clean() + } + + constructor(targetPtr: long) { + this.targetPtr = targetPtr + } + + native clean(): void + + private targetPtr: long = 0 +}; + +class FinalizationAgent { + constructor(obj: T, ptr: long) { + this.register(obj, ptr); + } + + register(obj: T, ptr: long): void { + this.unregisterToken = {}; + this.cleaner = new Cleaner(ptr); + finalizer.register(obj, this.cleaner!, this.unregisterToken); + } + + unregister(): void { + finalizer.unregister(this.unregisterToken); + } + + private cleaner: Cleaner | null = null; + private unregisterToken: object; +} + +let finalizer = new FinalizationRegistry(Cleaner.callback) + export default namespace fileUri { loadLibrary("fileuri_ani") @@ -27,7 +63,14 @@ export default namespace fileUri { private fileUriEntity_: long = 0; private acquireFileUriEntity(fileUriEntity: long) { this.fileUriEntity_ = fileUriEntity; + this.fzAgent = new FinalizationAgent(this, this.fileUriEntity_); } + + unregisterCleaner(): void { + this.fzAgent.unregister(); + } + + private fzAgent: FinalizationAgent; }; export native function getUriFromPath(path: string): string; } diff --git a/interfaces/kits/ani/file_uri/include/ani_util_native_ptr.h b/interfaces/kits/ani/file_uri/include/ani_util_native_ptr.h new file mode 100644 index 000000000..6713089d8 --- /dev/null +++ b/interfaces/kits/ani/file_uri/include/ani_util_native_ptr.h @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2025 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 ANI_UTIL_OBJECT_H +#define ANI_UTIL_OBJECT_H + +#include +#include + +#include +#include + +class NativeObject { +public: + virtual ~NativeObject() = default; +}; + + +template +class StdSharedPtrHolder : public NativeObject { +public: + StdSharedPtrHolder(const std::shared_ptr &sptr) : sptr_(sptr) + { + } + + std::shared_ptr Get() + { + return sptr_; + } + + std::shared_ptr GetOrDefault() + { + if (!sptr_) { + sptr_ = std::make_shared(); + } + return sptr_; + } + +private: + std::shared_ptr sptr_; +}; + + +template +class OhSharedPtrHolder : public NativeObject { +public: + OhSharedPtrHolder(const OHOS::sptr &sptr) : sptr_(sptr) + { + } + + OHOS::sptr Get() + { + return sptr_; + } + + OHOS::sptr GetOrDefault() + { + if (!sptr_) { + sptr_ = OHOS::sptr::MakeSptr(); + } + return sptr_; + } + +private: + OHOS::sptr sptr_; +}; + + +class NativePtrWrapper { +public: + NativePtrWrapper(ani_env *env, ani_object object, const char* propName = "nativePtr") + : env_(env), obj_(object), propName_(propName) + { + } + + template + ani_status Wrap(T* nativePtr) + { + return env_->Object_SetFieldByName_Long(obj_, propName_.c_str(), reinterpret_cast(nativePtr)); + } + + template + T* Unwrap() + { + ani_long nativePtr; + if (ANI_OK != env_->Object_GetFieldByName_Long(obj_, propName_.c_str(), &nativePtr)) { + return nullptr; + } + return reinterpret_cast(nativePtr); + } + +private: + ani_env *env_ = nullptr; + ani_object obj_ = nullptr; + std::string propName_; +}; + + +class NativePtrCleaner { +public: + static void Clean([[maybe_unused]] ani_env *env, [[maybe_unused]] ani_object object) + { + ani_long ptr = 0; + if (ANI_OK != env->Object_GetFieldByName_Long(object, "targetPtr", &ptr)){ + return; + } + delete reinterpret_cast(ptr); + } + + NativePtrCleaner(ani_env *env) + : env_(env) + { + } + + ani_status Bind(ani_class cls) + { + std::array methods = { + ani_native_function { "clean", nullptr, reinterpret_cast(NativePtrCleaner::Clean) }, + }; + + if (ANI_OK != env_->Class_BindNativeMethods(cls, methods.data(), methods.size())) { + return (ani_status)ANI_ERROR; + }; + + return ANI_OK; + } + +private: + ani_env *env_ = nullptr; +}; + +#endif diff --git a/interfaces/kits/ani/file_uri/src/ani_file_uri.cpp b/interfaces/kits/ani/file_uri/src/ani_file_uri.cpp index e7f181117..64873b154 100644 --- a/interfaces/kits/ani/file_uri/src/ani_file_uri.cpp +++ b/interfaces/kits/ani/file_uri/src/ani_file_uri.cpp @@ -21,6 +21,7 @@ #include "file_utils.h" #include "log.h" #include "n_error.h" +#include "ani_util_native_ptr.h" using namespace OHOS::AppFileService; @@ -41,11 +42,17 @@ static std::string ParseObjToStr(ani_env *env, ani_string stringObj) static ModuleFileUri::FileUriEntity *unwrapp(ani_env *env, ani_object object) { - ani_long fileuriEntity_; - if (ANI_OK != env->Object_GetFieldByName_Long(object, "fileUriEntity_", &fileuriEntity_)) { + ani_long fileUriEntityHolder_; + if (ANI_OK != env->Object_GetFieldByName_Long(object, "fileUriEntity_", &fileUriEntityHolder_)) { + LOGE("Get fileuriEntityHolder_ failed"); return nullptr; } - return reinterpret_cast(fileuriEntity_); + auto fileUriHolder = reinterpret_cast *>(fileUriEntityHolder_); + if (!fileUriHolder) { + LOGE("Get fileuriEntityHolder by long ptr failed"); + return nullptr; + } + return reinterpret_cast(fileUriHolder->Get().get()); } static void ThrowBusinessError(ani_env *env, int errCode, std::string&& errMsg) @@ -120,6 +127,8 @@ void FileUriConstructor(ani_env *env, ani_object obj, ani_string stringObj) return; } LOGD("FileUriConstructor fileuriEntity: %{public}p.", fileuriEntity.get()); + StdSharedPtrHolder *holder + = new StdSharedPtrHolder(std::move(fileuriEntity)); ani_namespace ns; if (env->FindNamespace("L@ohos/file/fileuri/fileUri;", &ns) != ANI_OK) { @@ -143,10 +152,10 @@ void FileUriConstructor(ani_env *env, ani_object obj, ani_string stringObj) return; } - if (ANI_OK != env->Object_CallMethod_Void(obj, acquireObj, reinterpret_cast(fileuriEntity.get()))) { - LOGE("Call method acquireFileUriEntity failed."); - ThrowBusinessError(env, EPERM, "Call method acquireFileUriEntity failed."); - return; + if (ANI_OK != env->Object_CallMethod_Void(obj, acquireObj, reinterpret_cast(holder))) { + LOGE("Call method acquireFileUriEntity failed."); + ThrowBusinessError(env, EPERM, "Call method acquireFileUriEntity failed."); + return; } } @@ -187,6 +196,13 @@ ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) return ANI_ERROR; }; + ani_class cleanerCls; + if (ANI_OK != env->FindClass("L@ohos/file/fileuri/Cleaner;", &cleanerCls)) { + LOGE("Not found class @ohos/file/fileuri/Cleaner;."); + return ANI_NOT_FOUND; + } + NativePtrCleaner(env).Bind(cleanerCls); + *result = ANI_VERSION_1; return ANI_OK; } -- Gitee