diff --git a/frameworks/native/backup_ext/BUILD.gn b/frameworks/native/backup_ext/BUILD.gn index ec60d87cd3bd9daefbf3ce130e531ec2dbe684c4..1a0f4628b66f24eb028f77bed42031c87760f411 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 098ebf899e4b0d25c12757f3c9deb067b8e99361..6d325e06dca001270d9b2a4513e6d6a76512b413 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 aeafebc7304d2d63b823f835ba3c4e8400a298ac..b5aedba5e124a7bda30bef2560ace07d33542117 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 cb1951b6b2ce9d77a232543d5e0220c63602de4f..0000000000000000000000000000000000000000 --- 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 82b465d25992ec1bb1576fda4de9d60a752af3be..0000000000000000000000000000000000000000 --- 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 6ce270f0c81e39a03338154d07245afb2ef25ed5..03cbc44f11928785559b10f2a2e7421b737023bb 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 4a19383c4afccd1d6e3ed156fb70f42ba47fe69c..7e2aa923737c684400905654f24c5ab4a4b37a15 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 e75dcf5f8a792c6627b77713975cc0495c2ed649..0ade1dff8f8a2c98de6281307b5ed264ef011bc8 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 d5ac5d1ab66a145c47a8d78bf9e3130bf0b4077b..8597442651bc413bc7d44eb84f3cbf05eb2ea9b5 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/interfaces/kits/ani/file_share/BUILD.gn b/interfaces/kits/ani/file_share/BUILD.gn index 772e9e2591adec8eb005bfdaf1e5bf43b24fa735..6acb23f62750469fb55eff6dad6a911af87100b4 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 caa55189da14107d7eaf4002374d6a8c09c2d072..2ab89f5a3ffe9695fdd12d6350d1e5e2e198576c 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 800b8e50f7b3da4449617ee6a0488f351c87f41f..2a12db9328fe45f5679bde90d03a7f04cc228774 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 c3545159d00f886955e9eb735f777a1e5335bde7..bd7dd815c418a03da4297634581ca1d9c4368137 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", @@ -49,6 +50,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/ets/@ohos.file.fileuri.ets b/interfaces/kits/ani/file_uri/ets/@ohos.file.fileuri.ets index 0e2afd40d0c038872e9f471288604940881990e9..cb55e760374ea9499916f0e0a8d7e9047a82587e 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 0000000000000000000000000000000000000000..6713089d8b2a8b6043aeb5ff3683e4ba7fc87d31 --- /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 ee5c314bdde9041ae7aa3dd306441c026585f728..64873b1542d09541b899a80f0480d89a39a6847b 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,8 @@ #include "file_uri_entity.h" #include "file_utils.h" #include "log.h" +#include "n_error.h" +#include "ani_util_native_ptr.h" using namespace OHOS::AppFileService; @@ -40,31 +42,54 @@ 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 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 +97,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,24 +117,23 @@ 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()); + StdSharedPtrHolder *holder + = new StdSharedPtrHolder(std::move(fileuriEntity)); 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,24 +141,21 @@ 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); - 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; } } @@ -182,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; } diff --git a/test/fuzztest/backupext_fuzzer/BUILD.gn b/test/fuzztest/backupext_fuzzer/BUILD.gn index 81a738ccaeb8f5d1d6a1d3b033f6251551ff3b07..4b68f3461e23eacdc09700e81760c9004a151e18 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 aa8aa131721fa88c64b501c21696ca0fa93d05a2..5fd0ef93d38865fb9dfc9fcbdfbb608384d17e6c 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", ]