diff --git a/bundle.json b/bundle.json index d7c79de2a53329715e457cb6aa3f10b0756c7cd1..e8b3be68694eb2492eeaae594120799a49d493d7 100644 --- a/bundle.json +++ b/bundle.json @@ -37,6 +37,7 @@ "ipc", "init", "napi", + "runtime_core", "safwk", "samgr", "storage_service", @@ -67,8 +68,11 @@ "//foundation/filemanagement/app_file_service/interfaces/kits/js:fileshare", "//foundation/filemanagement/app_file_service/interfaces/kits/js:fileuri", "//foundation/filemanagement/app_file_service/interfaces/kits/js:backup", + "//foundation/filemanagement/app_file_service/interfaces/kits/ani/file_share:fileshare_ani_package", + "//foundation/filemanagement/app_file_service/interfaces/kits/ani/file_uri:fileuri_ani_package", "//foundation/filemanagement/app_file_service/interfaces/kits/ndk/fileuri/src:ohfileuri", - "//foundation/filemanagement/app_file_service/interfaces/kits/ndk/fileshare/src:ohfileshare" + "//foundation/filemanagement/app_file_service/interfaces/kits/ndk/fileshare/src:ohfileshare", + "//foundation/filemanagement/app_file_service/frameworks/native/backup_ext/ani:backup_ext_ani_package" ], "service_group": [ "//foundation/filemanagement/app_file_service:tgt_backup_extension", diff --git a/frameworks/native/backup_ext/ani/BUILD.gn b/frameworks/native/backup_ext/ani/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..098ebf899e4b0d25c12757f3c9deb067b8e99361 --- /dev/null +++ b/frameworks/native/backup_ext/ani/BUILD.gn @@ -0,0 +1,62 @@ +# 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. + +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 + } + + 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", + ] + + subsystem_name = "filemanagement" + part_name = "app_file_service" + output_extension = "so" +} diff --git a/frameworks/native/backup_ext/ani/ets/@ohos.application.BackupExtensionAbility.ets b/frameworks/native/backup_ext/ani/ets/@ohos.application.BackupExtensionAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..aeafebc7304d2d63b823f835ba3c4e8400a298ac --- /dev/null +++ b/frameworks/native/backup_ext/ani/ets/@ohos.application.BackupExtensionAbility.ets @@ -0,0 +1,30 @@ +/* + * 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. + */ + + +export interface BundleVersion { + public code: number; + public name: string; +} + +class BundleVersionInner extends BundleVersion { + public code: number; + public name: string; +} + +export default class BackupExtensionAbility { + onBackup(): void; + onRestore(bundleVersion: BundleVersion): void; +} \ No newline at end of file diff --git a/frameworks/native/backup_ext/ani/include/ani_utils.h b/frameworks/native/backup_ext/ani/include/ani_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..6ce270f0c81e39a03338154d07245afb2ef25ed5 --- /dev/null +++ b/frameworks/native/backup_ext/ani/include/ani_utils.h @@ -0,0 +1,445 @@ +/* + * 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_UTILS_H +#define ANI_UTILS_H + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +class AniObjectUtils { +public: + static ani_object Create(ani_env *env, const char *nsName, const char *clsName, ...) + { + ani_object nullobj {}; + + ani_namespace ns; + if (ANI_OK != env->FindNamespace(nsName, &ns)) { + std::cerr << "[ANI] Not found namespace " << nsName << std::endl; + return nullobj; + } + + ani_class cls; + if (ANI_OK != env->Namespace_FindClass(ns, clsName, &cls)) { + std::cerr << "[ANI] Not found class " << clsName << std::endl; + return nullobj; + } + + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, "", nullptr, &ctor)) { + std::cerr << "[ANI] Not found for class " << clsName << std::endl; + return nullobj; + } + + std::cerr << "[ANI] AniObjectUtils Object_New_V " << clsName << std::endl; + ani_object obj; + va_list args; + va_start(args, clsName); + ani_status status = env->Object_New_V(cls, ctor, &obj, args); + va_end(args); + if (ANI_OK != status) { + std::cerr << "[ANI] Failed to Object_New for class " << cls << std::endl; + return nullobj; + } + return obj; + } + + static ani_object Create(ani_env *env, const char *clsName, ...) + { + ani_object nullobj {}; + + ani_class cls; + if (ANI_OK != env->FindClass(clsName, &cls)) { + std::cerr << "[ANI] Not found class " << clsName << std::endl; + return nullobj; + } + + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, "", nullptr, &ctor)) { + std::cerr << "[ANI] Not found for class " << clsName << std::endl; + return nullobj; + } + + ani_object obj; + va_list args; + va_start(args, clsName); + ani_status status = env->Object_New_V(cls, ctor, &obj, args); + va_end(args); + if (ANI_OK != status) { + std::cerr << "[ANI] Failed to Object_New for class " << cls << std::endl; + return nullobj; + } + return obj; + } + + static ani_object Create(ani_env *env, ani_class cls, ...) + { + ani_object nullobj {}; + + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, "", nullptr, &ctor)) { + std::cerr << "[ANI] Not found for class" << std::endl; + return nullobj; + } + + ani_object obj; + va_list args; + va_start(args, cls); + ani_status status = env->Object_New_V(cls, ctor, &obj, args); + va_end(args); + if (ANI_OK != status) { + std::cerr << "[ANI] Failed to Object_New for class " << cls << std::endl; + return nullobj; + } + return obj; + } + + template + static ani_status Wrap(ani_env *env, ani_object object, T *nativePtr, const char *propName = "nativePtr") + { + return env->Object_SetFieldByName_Long(object, propName, reinterpret_cast(nativePtr)); + } + + template + static T *Unwrap(ani_env *env, ani_object object, const char *propName = "nativePtr") + { + ani_long nativePtr; + if (ANI_OK != env->Object_GetFieldByName_Long(object, propName, &nativePtr)) { + return nullptr; + } + return reinterpret_cast(nativePtr); + } +}; + +class AniStringUtils { +public: + static std::string ToStd(ani_env *env, ani_string ani_str) + { + ani_size strSize; + env->String_GetUTF8Size(ani_str, &strSize); + + std::vector buffer(strSize + 1); // +1 for null terminator + char *utf8_buffer = buffer.data(); + + // String_GetUTF8 Supportted by https://gitee.com/openharmony/arkcompiler_runtime_core/pulls/3416 + ani_size bytes_written = 0; + env->String_GetUTF8(ani_str, utf8_buffer, strSize + 1, &bytes_written); + + utf8_buffer[bytes_written] = '\0'; + std::string content = std::string(utf8_buffer); + return content; + } + + static ani_string ToAni(ani_env *env, const std::string &str) + { + ani_string aniStr = nullptr; + if (ANI_OK != env->String_NewUTF8(str.data(), str.size(), &aniStr)) { + std::cerr << "[ANI] Unsupported ANI_VERSION_1" << std::endl; + return nullptr; + } + return aniStr; + } +}; + +class UnionAccessor { +public: + UnionAccessor(ani_env *env, ani_object &obj) : env_(env), obj_(obj) {} + + bool IsInstanceOf(const std::string &cls_name) + { + ani_class cls; + env_->FindClass(cls_name.c_str(), &cls); + + ani_boolean ret; + env_->Object_InstanceOf(obj_, cls, &ret); + return ret; + } + + template + bool IsInstanceOfType(); + + template + bool TryConvert(T &value); + + template + bool TryConvertArray(std::vector &value); + +private: + ani_env *env_; + ani_object obj_; +}; + +template <> +bool UnionAccessor::IsInstanceOfType() +{ + return IsInstanceOf("Lstd/core/Boolean;"); +} + +template <> +bool UnionAccessor::IsInstanceOfType() +{ + return IsInstanceOf("Lstd/core/Int;"); +} + +template <> +bool UnionAccessor::IsInstanceOfType() +{ + return IsInstanceOf("Lstd/core/Double;"); +} + +template <> +bool UnionAccessor::IsInstanceOfType() +{ + return IsInstanceOf("Lstd/core/String;"); +} + +template <> +bool UnionAccessor::TryConvert(bool &value) +{ + if (!IsInstanceOfType()) { + return false; + } + + ani_boolean aniValue; + auto ret = env_->Object_CallMethodByName_Boolean(obj_, "unboxed", nullptr, &aniValue); + if (ret != ANI_OK) { + return false; + } + value = static_cast(aniValue); + return true; +} + +template <> +bool UnionAccessor::TryConvert(int &value) +{ + if (!IsInstanceOfType()) { + return false; + } + + ani_int aniValue; + auto ret = env_->Object_CallMethodByName_Int(obj_, "unboxed", nullptr, &aniValue); + if (ret != ANI_OK) { + return false; + } + value = static_cast(aniValue); + return true; +} + +template <> +bool UnionAccessor::TryConvert(double &value) +{ + if (!IsInstanceOfType()) { + return false; + } + + ani_double aniValue; + auto ret = env_->Object_CallMethodByName_Double(obj_, "unboxed", nullptr, &aniValue); + if (ret != ANI_OK) { + return false; + } + value = static_cast(aniValue); + return true; +} + +template <> +bool UnionAccessor::TryConvert(std::string &value) +{ + if (!IsInstanceOfType()) { + return false; + } + + value = AniStringUtils::ToStd(env_, static_cast(obj_)); + 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) {} + + bool IsUndefined() + { + ani_boolean isUndefined; + env_->Reference_IsUndefined(obj_, &isUndefined); + return isUndefined; + } + + template + std::optional Convert(); + +private: + ani_env *env_; + ani_object obj_; +}; + +template <> +std::optional OptionalAccessor::Convert() +{ + if (IsUndefined()) { + return std::nullopt; + } + + ani_double aniValue; + auto ret = env_->Object_CallMethodByName_Double(obj_, "doubleValue", nullptr, &aniValue); + if (ret != ANI_OK) { + return std::nullopt; + } + auto value = static_cast(aniValue); + 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/ani/include/ext_backup_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..4a19383c4afccd1d6e3ed156fb70f42ba47fe69c --- /dev/null +++ b/frameworks/native/backup_ext/ani/include/ext_backup_ani.h @@ -0,0 +1,59 @@ +/* + * 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 EXT_BACKUP_ANI_H +#define EXT_BACKUP_ANI_H + +#include "ani_utils.h" +#include "ext_backup_context.h" +#include "extension_base.h" +#include "runtime.h" +#include "sts_runtime.h" + +namespace OHOS::FileManagement::Backup { + +class ExtBackupAni : public AbilityRuntime::ExtensionBase { +public: + void Init(const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) override; + +public: + static ExtBackupAni *Create(const std::unique_ptr &runtime); + + ErrCode OnBackup(std::function callback, + std::function callbackEx); + + ErrCode OnRestore(std::function callback, + std::function callbackEx); + +public: + explicit ExtBackupAni(AbilityRuntime::Runtime &runtime); + virtual ~ExtBackupAni() override; + +private: + ErrCode CallEtsOnBackup(); + ErrCode CallEtsOnRestore(); + +private: + AbilityRuntime::STSRuntime &stsRuntime_; + ani_env *env_; + std::unique_ptr etsObj_; +}; + +} // namespace OHOS::FileManagement::Backup + +#endif // EXT_BACKUP_ANI_H \ 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 new file mode 100644 index 0000000000000000000000000000000000000000..cb1951b6b2ce9d77a232543d5e0220c63602de4f --- /dev/null +++ b/frameworks/native/backup_ext/ani/include/ext_backup_loader.h @@ -0,0 +1,38 @@ +/* + * 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_ani.cpp b/frameworks/native/backup_ext/ani/src/ext_backup_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d5ac5d1ab66a145c47a8d78bf9e3130bf0b4077b --- /dev/null +++ b/frameworks/native/backup_ext/ani/src/ext_backup_ani.cpp @@ -0,0 +1,122 @@ +/* + * 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_ani.h" +#include "b_error/b_error.h" +#include "b_error/b_excep_utils.h" +#include "filemgmt_libhilog.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +ExtBackupAni::ExtBackupAni(AbilityRuntime::Runtime &runtime) + : stsRuntime_(static_cast(runtime)) +{ + HILOGI("Create as an BackupExtensionAbility"); + env_ = stsRuntime_.GetAniEnv(); +} + +ExtBackupAni::~ExtBackupAni() +{ + HILOGI("ExtBackupAni::~ExtBackupAni."); +} + +void ExtBackupAni::Init(const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) +{ + HILOGI("Init the BackupExtensionAbility"); + try { + if (record == nullptr) { + HILOGE("record null"); + return; + } + Extension::Init(record, application, handler, token); + if (Extension::abilityInfo_ == nullptr || Extension::abilityInfo_->srcEntrance.empty()) { + HILOGE("BackupExtensionAbility Init abilityInfo error"); + return; + } + std::string srcPath(Extension::abilityInfo_->moduleName + "/"); + srcPath.append(Extension::abilityInfo_->srcEntrance); + auto pos = srcPath.rfind("."); + if (pos != std::string::npos) { + srcPath.erase(pos); + srcPath.append(".abc"); + } + std::string moduleName(Extension::abilityInfo_->moduleName); + moduleName.append("::").append(abilityInfo_->name); + etsObj_ = stsRuntime_.LoadModule(moduleName, srcPath, abilityInfo_->hapPath, + abilityInfo_->compileMode == AppExecFwk::CompileMode::ES_MODULE, false, + abilityInfo_->srcEntrance); + if (etsObj_ == nullptr) { + HILOGE("Failed to get etsObj"); + return; + } + } catch (const BError &e) { + HILOGE("%{public}s", e.what()); + } catch (const exception &e) { + HILOGE("%{public}s", e.what()); + } +} + +ErrCode ExtBackupAni::CallEtsOnBackup() +{ + if (ANI_OK != env_->Object_CallMethodByName_Void(etsObj_->aniObj, "onBackup", nullptr)) { + HILOGE("Failed to call the method: onBackup"); + return EINVAL; + } + return ERR_OK; +} + +ErrCode ExtBackupAni::CallEtsOnRestore() +{ + ani_object bundleVersionObj = AniObjectUtils::Create(env_, "LBundleVersionInner;"); + if (nullptr == bundleVersionObj) { + HILOGE("Failed to Create the BundleVersionInner"); + return EINVAL; + } + if (ANI_OK != env_->Object_CallMethodByName_Void(etsObj_->aniObj, "onRestore", nullptr, bundleVersionObj)) { + HILOGE("Failed to call the method: onRestore"); + return EINVAL; + } + return ERR_OK; +} + +ExtBackupAni *ExtBackupAni::Create(const std::unique_ptr &runtime) +{ + HILOGI("Create as an BackupExtensionAbility"); + return new ExtBackupAni(*runtime); +} + +ErrCode ExtBackupAni::OnBackup(function callback, + std::function callbackEx) +{ + HILOGI("ExtBackupAni OnBackup"); + BExcepUltils::BAssert(etsObj_, BError::Codes::EXT_BROKEN_FRAMEWORK, + "The app does not provide the onBackup interface."); + return CallEtsOnBackup(); +} + +ErrCode ExtBackupAni::OnRestore(std::function callback, + std::function callbackEx) +{ + HILOGI("ExtBackupAni OnRestore"); + BExcepUltils::BAssert(etsObj_, BError::Codes::EXT_BROKEN_FRAMEWORK, + "The app does not provide the OnRestore interface."); + return CallEtsOnRestore(); +} + +} // namespace OHOS::FileManagement::Backup \ 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 new file mode 100644 index 0000000000000000000000000000000000000000..82b465d25992ec1bb1576fda4de9d60a752af3be --- /dev/null +++ b/frameworks/native/backup_ext/ani/src/ext_backup_loader.cpp @@ -0,0 +1,48 @@ +/* + * 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/interfaces/kits/ani/file_share/BUILD.gn b/interfaces/kits/ani/file_share/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..772e9e2591adec8eb005bfdaf1e5bf43b24fa735 --- /dev/null +++ b/interfaces/kits/ani/file_share/BUILD.gn @@ -0,0 +1,88 @@ +# 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. + +import("//build/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//foundation/filemanagement/app_file_service/app_file_service.gni") + +ohos_shared_library("fileshare_ani") { + branch_protector_ret = "pac_ret" + sanitize = { + boundary_sanitize = true + ubsan = true + cfi = true + cfi_cross_dso = true + debug = false + } + + cflags_cc = [ "-Wno-unused-function" ] + sources = [ "src/ani_file_share.cpp" ] + + include_dirs = [ + "include", + "../../../common/include", + "${app_file_service_path}/interfaces/innerkits/native/file_share/include", + ] + + deps = + [ "${app_file_service_path}/interfaces/innerkits/native:fileuri_native" ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:abilitykit_native", + "ability_runtime:extensionkit_native", + "ability_runtime:uri_permission_mgr", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "data_share:datashare_common", + "data_share:datashare_consumer", + "file_api:filemgmt_libhilog", + "file_api:filemgmt_libn", + "file_api:remote_uri_native", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "runtime_core:ani", + ] + part_name = "app_file_service" + subsystem_name = "filemanagement" + output_extension = "so" +} + +generate_static_abc("fileshare_abc") { + base_url = "./ets" + files = [ "./ets/@ohos.fileshare.ets" ] + dst_file = "$target_out_dir/fileshare.abc" + out_puts = [ "$target_out_dir/fileshare.abc" ] + is_boot_abc = "True" + device_dst_file = "/system/framework/fileshare.abc" +} + +ohos_prebuilt_etc("fileshare_abc_etc") { + source = "$target_out_dir/fileshare.abc" + module_install_dir = "framework" + subsystem_name = "filemanagement" + part_name = "app_file_service" + deps = [ ":fileshare_abc" ] +} + +group("fileshare_ani_package") { + deps = [ + ":fileshare_abc_etc", + ":fileshare_ani", + ] +} diff --git a/interfaces/kits/ani/file_share/ets/@ohos.fileshare.ets b/interfaces/kits/ani/file_share/ets/@ohos.fileshare.ets new file mode 100644 index 0000000000000000000000000000000000000000..caa55189da14107d7eaf4002374d6a8c09c2d072 --- /dev/null +++ b/interfaces/kits/ani/file_share/ets/@ohos.fileshare.ets @@ -0,0 +1,59 @@ +/* + * 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. + */ + +import type { AsyncCallback } from '@ohos.base'; +import { BusinessError } from '@ohos.base'; +import type wantConstant from '@ohos.app.ability.wantConstant'; + +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."); + 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; + callback(error, undefined); + }); + } + + export function grantUriPermission(uri: string, bundleName: string, flag: wantConstant.Flags): Promise { + console.log("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."); + reject(e); + }); + }); + return p; + } + + export function grantUriPermissionSync(uri: string, bundleName: string, flag: wantConstant.Flags):int { + console.log("Start grantUriPermissionSync in thread."); + grantUriPermissionInner(uri, bundleName, flag); + return 0; + } + native function grantUriPermissionInner(uri: string, bundleName: string, flag: wantConstant.Flags):void; +} diff --git a/interfaces/kits/ani/file_share/include/ani_file_share.h b/interfaces/kits/ani/file_share/include/ani_file_share.h new file mode 100644 index 0000000000000000000000000000000000000000..86e1ac8f1588a60a46d7b177452cf099436f7bf6 --- /dev/null +++ b/interfaces/kits/ani/file_share/include/ani_file_share.h @@ -0,0 +1,69 @@ + /* + * 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_FILE_SHARE_H +#define ANI_FILE_SHARE_H + +#include +#include "iremote_broker.h" + +namespace OHOS { +namespace AppFileService { +namespace ModuleFileShare { + +const std::string MEDIA_GRANT_URI_PERMISSION = + "datashare:///media/bundle_permission_insert_operation/bundle_permission_insert_operation"; +const std::string MEDIALIBRARY_DATA_URI = "datashare:///media"; +const std::string MEDIA_FILEMODE_READONLY = "r"; +const std::string GRANT_URI_NAME = "file_share_grant_uri_permission"; +const std::string MEDIA_API_VERSION_10 = "?api_version=10"; +const std::string PERMISSION_BUNDLE_NAME = "bundle_name"; +const std::string PERMISSION_FILE_ID = "file_id"; +const std::string PERMISSION_MODE = "mode"; +const std::string MEDIA_AUTHORITY = "media"; +const std::string FILE_SCHEME = "file"; +const std::string PERMISSION_TABLE_TYPE = "table_type"; +const std::string FILE_MANAGER_AUTHORITY = "docs"; +const std::string MEDIA_FILE_URI_PHOTO_PREFEX = "file://media/Photo/"; +const std::string MEDIA_FILE_URI_AUDIO_PREFEX = "file://media/Audio/"; +const std::string MEDIA_FILE_URI_VIDEO_PREFEX = "file://media/video/"; +const std::string MEDIA_FILE_URI_IMAGE_PREFEX = "file://media/image/"; +const std::string MEDIA_FILE_URI_FILE_PREFEX = "file://media/file/"; +const std::string MEDIA_FILE_URI_Audio_PREFEX = "file://media/audio/"; + +class FileShareGrantToken : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.fileshare.grantUriPermission"); + + FileShareGrantToken() = default; + virtual ~FileShareGrantToken() noexcept = default; +}; + +enum MediaFileTable { + FILE_TABLE = 0, + PHOTO_TABLE = 1, + AUDIO_TABLE = 2, +}; + +struct UriPermissionInfo { + unsigned int flag; + std::string mode; + std::string bundleName; + std::string uri; +}; + +} // namespace ModuleFileShare +} // namespace AppFileService +} // namespace OHOS +#endif // ANI_FILE_SHARE_H diff --git a/interfaces/kits/ani/file_share/src/ani_file_share.cpp b/interfaces/kits/ani/file_share/src/ani_file_share.cpp new file mode 100644 index 0000000000000000000000000000000000000000..800b8e50f7b3da4449617ee6a0488f351c87f41f --- /dev/null +++ b/interfaces/kits/ani/file_share/src/ani_file_share.cpp @@ -0,0 +1,299 @@ + /* + * 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 "ani_file_share.h" + +#include +#include +#include +#include "ability.h" +#include "datashare_helper.h" +#include "datashare_values_bucket.h" +#include "ipc_skeleton.h" +#include "log.h" +#include "remote_uri.h" +#include "tokenid_kit.h" +#include "uri.h" +#include "uri_permission_manager_client.h" +#include "want.h" + +using namespace OHOS::DataShare; +using namespace OHOS::DistributedFS::ModuleRemoteUri; + +namespace OHOS { +namespace AppFileService { +namespace ModuleFileShare { + +static std::string ParseObjToStr(ani_env *env, ani_string stringObj) +{ + ani_size strSize; + env->String_GetUTF8Size(stringObj, &strSize); + std::vector buffer(strSize + 1); + char* utf8Buffer = buffer.data(); + + ani_size byteswritten = 0; + env->String_GetUTF8(stringObj, utf8Buffer, strSize + 1, &byteswritten); + + utf8Buffer[byteswritten] = '\0'; + std::string path = std::string(utf8Buffer); + return path; +} + +static ani_int ParseEnumToInt(ani_env *env, ani_enum_item enumItem) +{ + ani_int intValue = -1; + if (ANI_OK != env->EnumItem_GetValue_Int(enumItem, &intValue)) { + LOGE("%{public}s: EnumItem_GetValue_Int FAILD.", __func__); + return -1; + } + LOGD("%{public}s: Enum Value: %{public}d.", __func__, intValue); + return intValue; +} + +static ani_error CreateAniError(ani_env *env, std::string&& errMsg) +{ + static const char *errorClsName = "Lescompat/Error;"; + ani_class cls {}; + if (ANI_OK != env->FindClass(errorClsName, &cls)) { + LOGE("%{public}s: Not found namespace %{public}s.", __func__, errorClsName); + return nullptr; + } + 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; + } + 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); +} + +static bool IsSystemApp() +{ + uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID(); + return OHOS::Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId); +} + +static int32_t GetIdFromUri(string uri) +{ + std::replace(uri.begin(), uri.end(), '/', ' '); + std::stringstream ss(uri); + std::string tmp; + int fileId = -1; + ss >> tmp >> tmp >> tmp >> fileId; + return fileId; +} + +static bool CheckValidPublicUri(const std::string &inputUri) +{ + Uri uri(inputUri); + std::string scheme = uri.GetScheme(); + if (scheme != FILE_SCHEME) { + return false; + } + + std::string authority = uri.GetAuthority(); + if (authority != MEDIA_AUTHORITY && authority != FILE_MANAGER_AUTHORITY) { + return false; + } + + return true; +} + +static std::string GetModeFromFlag(unsigned int flag) +{ + std::string mode = ""; + if (flag & OHOS::AAFwk::Want::FLAG_AUTH_READ_URI_PERMISSION) { + mode += "r"; + } + if (flag & OHOS::AAFwk::Want::FLAG_AUTH_WRITE_URI_PERMISSION) { + mode += "w"; + } + return mode; +} + +static int32_t GetMediaTypeAndApiFromUri(const std::string &uri, bool &isApi10) +{ + if (uri.find(MEDIA_FILE_URI_PHOTO_PREFEX) == 0) { + isApi10 = true; + return MediaFileTable::PHOTO_TABLE; + } else if (uri.find(MEDIA_FILE_URI_VIDEO_PREFEX) == 0 || + uri.find(MEDIA_FILE_URI_IMAGE_PREFEX) == 0) { + return MediaFileTable::PHOTO_TABLE; + } else if (uri.find(MEDIA_FILE_URI_AUDIO_PREFEX) == 0) { + isApi10 = true; + return MediaFileTable::AUDIO_TABLE; + } else if (uri.find(MEDIA_FILE_URI_Audio_PREFEX) == 0) { + return MediaFileTable::AUDIO_TABLE; + } else if (uri.find(MEDIA_FILE_URI_FILE_PREFEX) == 0) { + return MediaFileTable::FILE_TABLE; + } + + return MediaFileTable::FILE_TABLE; +} + +static int InitValuesBucket(const UriPermissionInfo &uriPermInfo, Uri &uri, bool &isApi10, + DataShareValuesBucket &valuesBucket) +{ + int32_t fileId = GetIdFromUri(uriPermInfo.uri); + if (fileId == -1) { + LOGE("%{public}s: get fileId parameter failed!", __func__); + return -EINVAL; + } + + int32_t filesType = GetMediaTypeAndApiFromUri(uri.ToString(), isApi10); + valuesBucket.Put(PERMISSION_FILE_ID, fileId); + valuesBucket.Put(PERMISSION_BUNDLE_NAME, uriPermInfo.bundleName); + valuesBucket.Put(PERMISSION_MODE, uriPermInfo.mode); + valuesBucket.Put(PERMISSION_TABLE_TYPE, filesType); + return 0; +} + +static int InsertByDatashare(const DataShareValuesBucket &valuesBucket, bool isApi10) +{ + int ret = -1; + std::shared_ptr dataShareHelper = nullptr; + sptr remote = new IRemoteStub(); + if (remote == nullptr) { + LOGE("%{public}s: get remoteObject failed!", __func__); + return -ret; + } + + dataShareHelper = DataShare::DataShareHelper::Creator(remote->AsObject(), MEDIALIBRARY_DATA_URI); + if (!dataShareHelper) { + LOGE("%{public}s: connect to datashare failed!", __func__); + return ret; + } + string uriStr = MEDIA_GRANT_URI_PERMISSION; + if (isApi10) { + uriStr += MEDIA_API_VERSION_10; + } + + Uri uri(uriStr); + ret = dataShareHelper->Insert(uri, valuesBucket); + if (ret < 0) { + LOGE("%{public}s: insert failed with error code %{public}d!", __func__, ret); + return ret; + } + return ret; +} + +static int GrantInMediaLibrary(const UriPermissionInfo &uriPermInfo, Uri &uri) +{ + bool isApi10 = false; + DataShareValuesBucket valuesBucket; + int ret = InitValuesBucket(uriPermInfo, uri, isApi10, valuesBucket); + if (ret < 0) { + LOGE("%{public}s: InitValuesBucket failed!", __func__); + return ret; + } + + ret = InsertByDatashare(valuesBucket, isApi10); + if (ret < 0) { + LOGE("%{public}s: InsertByDatashare failed!", __func__); + return ret; + } + return 0; +} + +static int DoGrantUriPermission(const UriPermissionInfo &uriPermInfo) +{ + Uri uri(uriPermInfo.uri); + std::string authority = uri.GetAuthority(); + std::string path = uri.GetPath(); + if (authority == MEDIA_AUTHORITY && path.find(".") == string::npos) { + return GrantInMediaLibrary(uriPermInfo, uri); + } else { + auto& uriPermissionClient = OHOS::AAFwk::UriPermissionManagerClient::GetInstance(); + int ret = uriPermissionClient.GrantUriPermission(uri, uriPermInfo.flag, uriPermInfo.bundleName); + if (ret != 0) { + LOGD("%{public}s: uriPermissionClient.GrantUriPermission by uri permission client failed!", __func__); + return GrantInMediaLibrary(uriPermInfo, uri); + } + } + + return 0; +} + +static void GrantUriPermission(ani_env *env, ani_string uri, ani_string bundleName, ani_object enumIndex) +{ + 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); + return; + } + + UriPermissionInfo uriPermInfo; + 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); + return; + } + uriPermInfo.uri = uriStr; + std::string bundleNameStr = ParseObjToStr(env, bundleName); + uriPermInfo.bundleName = bundleNameStr; + + 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); + return; + } + uriPermInfo.flag = wantConstantFlag; + uriPermInfo.mode = GetModeFromFlag(wantConstantFlag); + LOGD("GrantUriPermission uri: %{public}s, bundleName: %{public}s, flag: %{public}d, mode: %{public}s", + uriStr.c_str(), bundleNameStr.c_str(), wantConstantFlag, uriPermInfo.mode.c_str()); + + int ret = DoGrantUriPermission(uriPermInfo); + LOGD("DoGrantUriPermission ret: %{public}d.", ret); +} +} // namespace ModuleFileShare +} // namespace AppFileService +} // namespace OHOS + +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) +{ + LOGD("Enter ANI_Constructor."); + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + LOGE("Unsupported ANI_VERSION_1"); + return ANI_ERROR; + } + + static const char *nsName = "L@ohos/fileshare/fileShare;"; + ani_namespace ns; + if (ANI_OK != env->FindNamespace(nsName, &ns)) { + LOGE("Not found namespace %{public}s.", nsName); + return ANI_NOT_FOUND; + } + std::array nsMethods = { + ani_native_function {"grantUriPermissionInner", nullptr, + reinterpret_cast(OHOS::AppFileService::ModuleFileShare::GrantUriPermission)}, + }; + if (ANI_OK != env->Namespace_BindNativeFunctions(ns, nsMethods.data(), nsMethods.size())) { + LOGE("Cannot bind native methods to namespace %{public}s.", nsName); + return ANI_ERROR; + }; + + *result = ANI_VERSION_1; + return ANI_OK; +} diff --git a/interfaces/kits/ani/file_uri/BUILD.gn b/interfaces/kits/ani/file_uri/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c3545159d00f886955e9eb735f777a1e5335bde7 --- /dev/null +++ b/interfaces/kits/ani/file_uri/BUILD.gn @@ -0,0 +1,82 @@ +# 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. + +import("//build/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//foundation/filemanagement/app_file_service/app_file_service.gni") + +ohos_shared_library("fileuri_ani") { + branch_protector_ret = "pac_ret" + sanitize = { + boundary_sanitize = true + ubsan = true + cfi = true + cfi_cross_dso = true + debug = false + } + + cflags_cc = [ "-Wno-unused-function" ] + sources = [ + "../../../common/src/common_func.cpp", + "src/ani_file_uri.cpp", + ] + + include_dirs = [ + "../../../common/include", + "../../js/file_uri", + "${app_file_service_path}/interfaces/innerkits/native/file_uri/include", + ] + + deps = + [ "${app_file_service_path}/interfaces/innerkits/native:fileuri_native" ] + + external_deps = [ + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "file_api:filemgmt_libhilog", + "file_api:filemgmt_libn", + "hilog:libhilog", + "ipc:ipc_core", + "runtime_core:ani", + "samgr:samgr_proxy", + ] + part_name = "app_file_service" + subsystem_name = "filemanagement" + output_extension = "so" +} + +generate_static_abc("fileuri_abc") { + base_url = "./ets" + files = [ "./ets/@ohos.file.fileuri.ets" ] + dst_file = "$target_out_dir/fileuri.abc" + out_puts = [ "$target_out_dir/fileuri.abc" ] + is_boot_abc = "True" + device_dst_file = "/system/framework/fileuri.abc" +} + +ohos_prebuilt_etc("fileuri_abc_etc") { + source = "$target_out_dir/fileuri.abc" + module_install_dir = "framework" + subsystem_name = "filemanagement" + part_name = "app_file_service" + deps = [ ":fileuri_abc" ] +} + +group("fileuri_ani_package") { + deps = [ + ":fileuri_abc_etc", + ":fileuri_ani", + ] +} diff --git a/interfaces/kits/ani/file_uri/ets/@ohos.file.fileuri.ets b/interfaces/kits/ani/file_uri/ets/@ohos.file.fileuri.ets new file mode 100644 index 0000000000000000000000000000000000000000..0e2afd40d0c038872e9f471288604940881990e9 --- /dev/null +++ b/interfaces/kits/ani/file_uri/ets/@ohos.file.fileuri.ets @@ -0,0 +1,33 @@ +/* + * 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. + */ + +import uri from '@ohos.uri'; + +export default namespace fileUri { + loadLibrary("fileuri_ani") + + export class FileUri { + native constructor(uriOrPath: string); + getFileUriEntity():long { + return this.fileUriEntity_; + } + + private fileUriEntity_: long = 0; + private acquireFileUriEntity(fileUriEntity: long) { + this.fileUriEntity_ = fileUriEntity; + } + }; + export native function getUriFromPath(path: string): string; +} diff --git a/interfaces/kits/ani/file_uri/src/ani_file_uri.cpp b/interfaces/kits/ani/file_uri/src/ani_file_uri.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee5c314bdde9041ae7aa3dd306441c026585f728 --- /dev/null +++ b/interfaces/kits/ani/file_uri/src/ani_file_uri.cpp @@ -0,0 +1,187 @@ + /* + * 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 +#include +#include +#include "common_func.h" +#include "file_uri_entity.h" +#include "file_utils.h" +#include "log.h" + +using namespace OHOS::AppFileService; + +static std::string ParseObjToStr(ani_env *env, ani_string stringObj) +{ + ani_size strSize; + env->String_GetUTF8Size(stringObj, &strSize); + std::vector buffer(strSize + 1); + char* utf8Buffer = buffer.data(); + + ani_size byteswritten = 0; + env->String_GetUTF8(stringObj, utf8Buffer, strSize + 1, &byteswritten); + + utf8Buffer[byteswritten] = '\0'; + std::string path = std::string(utf8Buffer); + return path; +} + +static ModuleFileUri::FileUriEntity *unwrapp(ani_env *env, ani_object object) +{ + ani_long fileuriEntity_; + if (ANI_OK != env->Object_GetFieldByName_Long(object, "fileUriEntity_", &fileuriEntity_)) { + return nullptr; + } + return reinterpret_cast(fileuriEntity_); +} + +static ani_error CreateAniError(ani_env *env, std::string&& errMsg) +{ + static const char *errorClsName = "Lescompat/Error;"; + ani_class cls {}; + if (ANI_OK != env->FindClass(errorClsName, &cls)) { + LOGE("Not found %{public}s.", errorClsName); + return nullptr; + } + 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; + } + 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); +} + +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); + return uriObj; + } + LOGD("GetUriFromPath uri: %{public}s", uri.c_str()); + + env->String_NewUTF8(uri.c_str(), uri.size(), &uriObj); + + return uriObj; +} + +void FileUriConstructor(ani_env *env, ani_object obj, ani_string stringObj) +{ + LOGD("Enter FileUriConstructor"); + 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); + 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); + return; + } + LOGD("FileUriConstructor fileuriEntity: %{public}p.", fileuriEntity.get()); + + 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); + return; + }; + + ani_class cls; + 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); + 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); + 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; + } +} + +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) +{ + LOGD("Enter ANI_Constructor."); + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + LOGE("Unsupported ANI_VERSION_1"); + return ANI_ERROR; + } + + static const char *nsName = "L@ohos/file/fileuri/fileUri;"; + ani_namespace ns; + if (ANI_OK != env->FindNamespace(nsName, &ns)) { + LOGE("Not found namespace %{public}s.", nsName); + return ANI_NOT_FOUND; + } + std::array nsMethods = { + ani_native_function {"getUriFromPath", nullptr, reinterpret_cast(GetUriFromPath)}, + }; + if (ANI_OK != env->Namespace_BindNativeFunctions(ns, nsMethods.data(), nsMethods.size())) { + LOGE("Cannot bind native methods to namespace %{public}s.", nsName); + return ANI_ERROR; + }; + + static const char *className = "LFileUri;"; + ani_class fileUriClass; + if (ANI_OK != env->Namespace_FindClass(ns, className, &fileUriClass)) { + LOGE("Not found class %{public}s in %{public}s.", nsName, nsName); + return ANI_NOT_FOUND; + } + std::array classMethods = { + ani_native_function {"", "Lstd/core/String;:V", reinterpret_cast(FileUriConstructor)}, + }; + if (ANI_OK != env->Class_BindNativeMethods(fileUriClass, classMethods.data(), classMethods.size())) { + LOGE("Cannot bind native methods to class %{public}s.", className); + return ANI_ERROR; + }; + + *result = ANI_VERSION_1; + return ANI_OK; +}