diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index d4f31e1b4b592a26f3daed0ee78a25f8fc8df42a..9334220be9d28e01972e60ed84bec52d044d4e8a 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -625,6 +625,7 @@ group("ani_file_api") { ":ani_fs_class", ":ani_hash_class", ":ani_securitylabel_class", + ":ohos_file_fs_abc", ] } @@ -669,7 +670,7 @@ ohos_shared_library("ani_fs_class") { "src/mod_fs/properties/copy_listener", ] sources = [ - "src/common/ani_helper/bind_function.cpp", + "src/common/ani_helper/error_handler.cpp", "src/common/ani_helper/type_converter.cpp", "src/common/file_helper/fd_guard.cpp", "src/mod_fs/ani/bind_function_class.cpp", @@ -707,7 +708,7 @@ ohos_shared_library("ani_fs_class") { "src/mod_fs/properties/write_core.cpp", ] deps = [ - ":ani_fs_abc_etc", + ":ohos_file_fs_abc_etc", "${file_api_path}/interfaces/kits/native:remote_uri_native", "${file_api_path}/interfaces/kits/rust:rust_file", "${utils_path}/filemgmt_libfs:filemgmt_libfs", @@ -752,24 +753,24 @@ ohos_shared_library("ani_fs_class") { cfi_cross_dso = true debug = false } + output_extension = "so" subsystem_name = "filemanagement" part_name = "file_api" } -generate_static_abc("ani_fs_abc") { - arktsconfig = "src/mod_fs/ani/arktsconfig.json" - dst_file = "$target_out_dir/ani_fs.abc" - out_puts = [ "$target_out_dir/ani_fs.abc" ] +generate_static_abc("ohos_file_fs_abc") { + base_url = "./src/mod_fs/ani/ets" + files = [ "./src/mod_fs/ani/ets/@ohos.file.fs.ets" ] is_boot_abc = "True" - device_dst_file = "/system/framework/ani_fs.abc" + device_dst_file = "/system/framework/ohos_file_fs_abc.abc" } -ohos_prebuilt_etc("ani_fs_abc_etc") { - source = "$target_out_dir/ani_fs.abc" +ohos_prebuilt_etc("ohos_file_fs_abc_etc") { + source = "$target_out_dir/ohos_file_fs_abc.abc" module_install_dir = "framework" subsystem_name = "filemanagement" part_name = "file_api" - deps = [ ":ani_fs_abc" ] + deps = [ ":ohos_file_fs_abc" ] } ohos_shared_library("ani_hash_class") { @@ -779,7 +780,7 @@ ohos_shared_library("ani_hash_class") { "src/mod_hash/ani", ] sources = [ - "src/common/ani_helper/bind_function.cpp", + "src/common/ani_helper/error_handler.cpp", "src/common/ani_helper/type_converter.cpp", "src/common/file_helper/fd_guard.cpp", "src/common/file_helper/hash_file.cpp", @@ -790,7 +791,7 @@ ohos_shared_library("ani_hash_class") { ] deps = [ - ":ani_hash_abc_etc", + ":ohos_file_hash_abc_etc", "${file_api_path}/interfaces/kits/rust:rust_file", "${utils_path}/filemgmt_libfs:filemgmt_libfs", "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", @@ -822,24 +823,24 @@ ohos_shared_library("ani_hash_class") { cfi_cross_dso = true debug = false } + output_extension = "so" subsystem_name = "filemanagement" part_name = "file_api" } -generate_static_abc("ani_hash_abc") { - arktsconfig = "src/mod_hash/ani/arktsconfig.json" - dst_file = "$target_out_dir/ani_hash.abc" - out_puts = [ "$target_out_dir/ani_hash.abc" ] +generate_static_abc("ohos_file_hash_abc") { + base_url = "./src/mod_hash/ani/ets" + files = [ "./src/mod_hash/ani/ets/@ohos.file.hash.ets" ] is_boot_abc = "True" - device_dst_file = "/system/framework/ani_hash.abc" + device_dst_file = "/system/framework/ohos_file_hash_abc.abc" } -ohos_prebuilt_etc("ani_hash_abc_etc") { - source = "$target_out_dir/ani_hash.abc" +ohos_prebuilt_etc("ohos_file_hash_abc_etc") { + source = "$target_out_dir/ohos_file_hash_abc.abc" module_install_dir = "framework" subsystem_name = "filemanagement" part_name = "file_api" - deps = [ ":ani_hash_abc" ] + deps = [ ":ohos_file_hash_abc" ] } ohos_shared_library("ani_securitylabel_class") { @@ -849,7 +850,7 @@ ohos_shared_library("ani_securitylabel_class") { "src/mod_securitylabel", ] sources = [ - "src/common/ani_helper/bind_function.cpp", + "src/common/ani_helper/error_handler.cpp", "src/common/ani_helper/type_converter.cpp", "src/common/file_helper/fd_guard.cpp", "src/mod_fs/fs_utils.cpp", @@ -859,7 +860,7 @@ ohos_shared_library("ani_securitylabel_class") { ] deps = [ - ":ani_securitylabel_abc_etc", + ":ohos_file_securityLabel_abc_etc", "${file_api_path}/interfaces/kits/rust:rust_file", "${utils_path}/filemgmt_libfs:filemgmt_libfs", "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", @@ -890,22 +891,22 @@ ohos_shared_library("ani_securitylabel_class") { cfi_cross_dso = true debug = false } + output_extension = "so" subsystem_name = "filemanagement" part_name = "file_api" } -generate_static_abc("ani_securitylabel_abc") { - arktsconfig = "src/mod_securitylabel/ani/arktsconfig.json" - dst_file = "$target_out_dir/ani_securitylabel.abc" - out_puts = [ "$target_out_dir/ani_securitylabel.abc" ] +generate_static_abc("ohos_file_securityLabel_abc") { + base_url = "./src/mod_securitylabel/ani/ets" + files = [ "./src/mod_securitylabel/ani/ets/@ohos.file.securityLabel.ets" ] is_boot_abc = "True" - device_dst_file = "/system/framework/ani_securitylabel.abc" + device_dst_file = "/system/framework/ohos_file_securityLabel_abc.abc" } -ohos_prebuilt_etc("ani_securitylabel_abc_etc") { - source = "$target_out_dir/ani_securitylabel.abc" +ohos_prebuilt_etc("ohos_file_securityLabel_abc_etc") { + source = "$target_out_dir/ohos_file_securityLabel_abc.abc" module_install_dir = "framework" subsystem_name = "filemanagement" part_name = "file_api" - deps = [ ":ani_securitylabel_abc" ] + deps = [ ":ohos_file_securityLabel_abc" ] } diff --git a/interfaces/kits/js/src/common/ani_helper/bind_function.cpp b/interfaces/kits/js/src/common/ani_helper/bind_function.cpp deleted file mode 100644 index 1f1b29049682f4324a74bad775a785f64895559a..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/src/common/ani_helper/bind_function.cpp +++ /dev/null @@ -1,78 +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 "bind_function.h" -#include "filemgmt_libhilog.h" - -namespace OHOS { -namespace FileManagement { -namespace ModuleFileIO { -namespace ANI { -ANI_EXPORT ani_status BindClass(ani_vm *vm, const char *className, const std::vector &methods) -{ - if (vm == nullptr) { - HILOGE("ani_vm is null!"); - return ANI_ERROR; - } - - ani_env *env; - if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { - HILOGE("Unsupported ANI_VERSION_1!"); - return ANI_OUT_OF_REF; - } - - ani_class cls; - if (ANI_OK != env->FindClass(className, &cls)) { - HILOGE("Not found '%{private}s'", className); - return ANI_INVALID_ARGS; - } - - if (ANI_OK != env->Class_BindNativeMethods(cls, methods.data(), methods.size())) { - HILOGE("Cannot bind native methods to '%{private}s'", className); - return ANI_INVALID_TYPE; - }; - return ANI_OK; -} - -ANI_EXPORT ani_status BindNamespace( - ani_vm *vm, const char *namespaceStr, const std::vector &functions) -{ - if (vm == nullptr) { - HILOGE("ani_vm is null!"); - return ANI_ERROR; - } - - ani_env *env; - if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { - HILOGE("Unsupported ANI_VERSION_1 Fail!!!"); - return ANI_OUT_OF_REF; - } - - ani_namespace ns; - if (ANI_OK != env->FindNamespace(namespaceStr, &ns)) { - HILOGE("Not found '%{private}s'", namespaceStr); - return ANI_INVALID_ARGS; - } - - if (ANI_OK != env->Namespace_BindNativeFunctions(ns, functions.data(), functions.size())) { - HILOGE("Cannot bind native methods to '%{private}s'", namespaceStr); - return ANI_INVALID_TYPE; - }; - return ANI_OK; -} -} // namespace ANI -} // namespace ModuleFileIO -} // namespace FileManagement -} // namespace OHOS diff --git a/interfaces/kits/js/src/common/ani_helper/bind_function.h b/interfaces/kits/js/src/common/ani_helper/bind_function.h index 7d41c65547f5cd604471391807846d35d97e7e98..3c951b25125364260b1879851df4f1b832e9b233 100644 --- a/interfaces/kits/js/src/common/ani_helper/bind_function.h +++ b/interfaces/kits/js/src/common/ani_helper/bind_function.h @@ -25,27 +25,28 @@ namespace FileManagement { namespace ModuleFileIO { namespace ANI { -ANI_EXPORT ani_status BindClass(ani_vm *vm, const char *className, const std::vector &methods); -ANI_EXPORT ani_status BindNamespace( - ani_vm *vm, const char *namespaceStr, const std::vector &functions); - template ANI_EXPORT ani_status BindClass(ani_env *env, const char *className, const std::array &methods) { if (env == nullptr) { - HILOGE("ani_env is null!"); - return ANI_ERROR; + HILOGE("Invalid parameter env"); + return ANI_INVALID_ARGS; } - + + if (className == nullptr) { + HILOGE("Invalid parameter className"); + return ANI_INVALID_ARGS; + } + ani_class cls; if (ANI_OK != env->FindClass(className, &cls)) { HILOGE("Cannot find class '%{private}s'", className); - return ANI_INVALID_ARGS; + return ANI_NOT_FOUND; } if (ANI_OK != env->Class_BindNativeMethods(cls, methods.data(), methods.size())) { HILOGE("Cannot bind native methods to '%{private}s'", className); - return ANI_INVALID_TYPE; + return ANI_ERROR; }; return ANI_OK; } @@ -55,19 +56,24 @@ ANI_EXPORT ani_status BindNamespace( ani_env *env, const char *namespaceStr, const std::array &methods) { if (env == nullptr) { - HILOGE("ani_env is null!"); - return ANI_ERROR; + HILOGE("Invalid parameter env"); + return ANI_INVALID_ARGS; + } + + if (namespaceStr == nullptr) { + HILOGE("Invalid parameter namespaceStr"); + return ANI_INVALID_ARGS; } ani_namespace ns; if (ANI_OK != env->FindNamespace(namespaceStr, &ns)) { - HILOGE("Not found '%{private}s'", namespaceStr); - return ANI_INVALID_ARGS; + HILOGE("Cannot find namespace '%{private}s'", namespaceStr); + return ANI_NOT_FOUND; } if (ANI_OK != env->Namespace_BindNativeFunctions(ns, methods.data(), methods.size())) { HILOGE("Cannot bind native methods to '%{private}s'", namespaceStr); - return ANI_INVALID_TYPE; + return ANI_ERROR; }; return ANI_OK; } diff --git a/interfaces/kits/js/src/common/ani_helper/error_handler.cpp b/interfaces/kits/js/src/common/ani_helper/error_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a9e87cb828a602ae4995180c6b59a41a66c8dfb7 --- /dev/null +++ b/interfaces/kits/js/src/common/ani_helper/error_handler.cpp @@ -0,0 +1,27 @@ +/* + * 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 "error_handler.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI { + +ani_status ErrorHandler::Throw(ani_env *env, int32_t code, const std::string &errMsg) +{ + const char *className = "L@ohos/base/BusinessError;"; + const char *name = "BusinessError"; + return Throw(env, className, name, code, errMsg); +} + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI \ No newline at end of file diff --git a/interfaces/kits/js/src/common/ani_helper/error_handler.h b/interfaces/kits/js/src/common/ani_helper/error_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..59c41c11436572d555aab35aa47ee003427564ef --- /dev/null +++ b/interfaces/kits/js/src/common/ani_helper/error_handler.h @@ -0,0 +1,140 @@ +/* + * 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 FILEMANAGEMENT_ANI_ERROR_HANDLER_H +#define FILEMANAGEMENT_ANI_ERROR_HANDLER_H + +#include +#include +#include +#include "ani_helper.h" +#include "filemgmt_libhilog.h" +#include "fs_error.h" +#include "type_converter.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI { + +class ErrorHandler { +public: + static ani_status Throw(ani_env *env, int32_t code, const std::string &errMsg); + + static ani_status Throw(ani_env *env, int32_t code) + { + if (env == nullptr) { + HILOGE("Invalid parameter env"); + return ANI_INVALID_ARGS; + } + FsError err(code); + return Throw(env, std::move(err)); + } + + static ani_status Throw(ani_env *env, const FsError &err) + { + if (env == nullptr) { + HILOGE("Invalid parameter env"); + return ANI_INVALID_ARGS; + } + auto code = err.GetErrNo(); + const auto &errMsg = err.GetErrMsg(); + return Throw(env, code, errMsg); + } + +private: + static ani_status Throw( + ani_env *env, const char *className, const char *name, int32_t code, const std::string &errMsg) + { + if (env == nullptr) { + HILOGE("Invalid parameter env"); + return ANI_INVALID_ARGS; + } + + if (className == nullptr) { + HILOGE("Invalid parameter className"); + return ANI_INVALID_ARGS; + } + + if (name == nullptr) { + HILOGE("Invalid parameter name"); + return ANI_INVALID_ARGS; + } + + auto [status, err] = CreateErrorObj(env, className, name, code, errMsg); + + if (status != ANI_OK) { + HILOGE("Create error object failed!"); + return status; + } + + status = env->ThrowError(err); + if (status != ANI_OK) { + HILOGE("Throw ani error object failed!"); + return status; + } + return ANI_OK; + } + + static std::tuple CreateErrorObj( + ani_env *env, const char *className, const char *name, int32_t code, const std::string &errMsg) + { + ani_class cls; + if (ANI_OK != env->FindClass(className, &cls)) { + HILOGE("Cannot find class '%{private}s'", className); + return { ANI_NOT_FOUND, nullptr }; + } + + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, "", ":V", &ctor)) { + HILOGE("Cannot find constructor for class '%{private}s'", className); + return { ANI_NOT_FOUND, nullptr }; + } + + auto [succ, message] = TypeConverter::ToAniString(env, errMsg); + if (!succ) { + HILOGE("Convert errMsg to ani string failed"); + return { ANI_ERROR, nullptr }; + } + + ani_object obj; + if (ANI_OK != env->Object_New(cls, ctor, &obj, static_cast(code), message)) { + HILOGE("Cannot create ani error object"); + return { ANI_ERROR, nullptr }; + } + + ani_status status = ANI_ERROR; + status = AniHelper::SetFieldValue(env, cls, obj, "name", name); + if (status != ANI_OK) { + HILOGE("Set field 'name' value failed"); + return { status, nullptr }; + } + + status = AniHelper::SetFieldValue(env, cls, obj, "message", errMsg); + if (status != ANI_OK) { + HILOGE("Set field 'message' value failed"); + return { status, nullptr }; + } + + status = AniHelper::SetFieldValue(env, cls, obj, "code", static_cast(code)); + if (status != ANI_OK) { + HILOGE("Set field 'code' value failed"); + return { status, nullptr }; + } + ani_error err = static_cast(obj); + return { ANI_OK, std::move(err) }; + } +}; + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI + +#endif // FILEMANAGEMENT_ANI_ERROR_HANDLER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/ani_helper/type_converter.cpp b/interfaces/kits/js/src/common/ani_helper/type_converter.cpp index 2f23db6e90d47bf40eec9b5a6d297823300963bf..e618699674ad19375fb59c8391765074e448a6d9 100644 --- a/interfaces/kits/js/src/common/ani_helper/type_converter.cpp +++ b/interfaces/kits/js/src/common/ani_helper/type_converter.cpp @@ -15,6 +15,7 @@ #include "type_converter.h" +#include #include #include @@ -27,6 +28,9 @@ namespace OHOS::FileManagement::ModuleFileIO::ANI { std::tuple TypeConverter::ToUTF8String(ani_env *env, const ani_string &path) { + if (env == nullptr) { + return { false, EMPTY_STRING }; + } ani_size sz {}; std::string result; auto status = env->String_GetUTF8Size(path, &sz); @@ -42,40 +46,61 @@ std::tuple TypeConverter::ToUTF8String(ani_env *env, const an return { true, std::move(result) }; } -std::tuple> TypeConverter::ToOptionalInt32(ani_env *env, const ani_object &intOp) +std::tuple> TypeConverter::ToOptionalInt32(ani_env *env, const ani_object &value) { + if (env == nullptr) { + return { false, {} }; + } ani_boolean isUndefined; - env->Reference_IsUndefined(intOp, &isUndefined); + env->Reference_IsUndefined(value, &isUndefined); if (isUndefined) { return { true, std::nullopt }; } - ani_int result; - if (ANI_OK != env->Object_CallMethodByName_Int(intOp, "intValue", nullptr, &result)) { - return { false, {} }; + ani_double doubleValue; + if (ANI_OK == env->Object_CallMethodByName_Double(value, "doubleValue", nullptr, &doubleValue)) { + return { true, std::make_optional(static_cast(doubleValue)) }; } - return { true, std::make_optional(result) }; + ani_int intValue; + if (ANI_OK == env->Object_CallMethodByName_Int(value, "intValue", nullptr, &intValue)) { + return { true, std::make_optional(intValue) }; + } + + return { false, {} }; } -std::tuple> TypeConverter::ToOptionalInt64(ani_env *env, const ani_object &longOp) +std::tuple> TypeConverter::ToOptionalInt64(ani_env *env, const ani_object &value) { + if (env == nullptr) { + return { false, {} }; + } + ani_boolean isUndefined; - env->Reference_IsUndefined(longOp, &isUndefined); + env->Reference_IsUndefined(value, &isUndefined); if (isUndefined) { return { true, std::nullopt }; } - ani_long result; - if (ANI_OK != env->Object_CallMethodByName_Long(longOp, "longValue", nullptr, &result)) { - return { false, {} }; + ani_double doubleValue; + if (ANI_OK == env->Object_CallMethodByName_Double(value, "doubleValue", nullptr, &doubleValue)) { + return { true, std::make_optional(static_cast(doubleValue)) }; } - return { true, std::make_optional(result) }; + ani_long longValue; + if (ANI_OK == env->Object_CallMethodByName_Long(value, "longValue", nullptr, &longValue)) { + return { true, std::make_optional(longValue) }; + } + + return { false, {} }; } std::tuple TypeConverter::ToAniString(ani_env *env, std::string str) { + if (env == nullptr) { + return { false, {} }; + } + ani_string result; if (ANI_OK != env->String_NewUTF8(str.c_str(), str.size(), &result)) { return { false, {} }; @@ -85,6 +110,10 @@ std::tuple TypeConverter::ToAniString(ani_env *env, std::strin std::tuple TypeConverter::ToAniString(ani_env *env, const char *str) { + if (env == nullptr) { + return { false, {} }; + } + size_t length = std::strlen(str); ani_string result; if (ANI_OK != env->String_NewUTF8(str, length, &result)) { @@ -109,13 +138,47 @@ std::tuple> TypeConverter::EnumToInt32(ani_env *env return { true, std::make_optional(result) }; } -std::tuple TypeConverter::ToFileInfo(ani_env *env, const ani_object &pathOrFd) +static std::tuple ParseFd(ani_env *env, const ani_object &pathOrFd) { - ani_class stringClass; - env->FindClass("Lstd/core/String;", &stringClass); + ani_boolean isFd = false; + + ani_class DoubleClass; + env->FindClass("Lstd/core/Double;", &DoubleClass); + env->Object_InstanceOf(pathOrFd, DoubleClass, &isFd); + if (isFd) { + ani_double doubleValue; + if (ANI_OK != env->Object_CallMethodByName_Double(pathOrFd, "doubleValue", nullptr, &doubleValue)) { + HILOGE("Parse file path failed"); + return { false, 0 }; + } + int32_t fd = static_cast(doubleValue); + return { true, fd }; + } ani_class IntClass; env->FindClass("Lstd/core/Int;", &IntClass); + env->Object_InstanceOf(pathOrFd, IntClass, &isFd); + if (isFd) { + ani_int fd; + if (ANI_OK != env->Object_CallMethodByName_Int(pathOrFd, "intValue", nullptr, &fd)) { + HILOGE("Parse file path failed"); + return { false, 0 }; + } + return { true, fd }; + } + + return { false, 0 }; +} + +std::tuple TypeConverter::ToFileInfo(ani_env *env, const ani_object &pathOrFd) +{ + if (env == nullptr) { + HILOGE("Invalid parameter env"); + return { false, FileInfo { false, {}, {} } }; + } + + ani_class stringClass; + env->FindClass("Lstd/core/String;", &stringClass); ani_boolean isPath = false; env->Object_InstanceOf(pathOrFd, stringClass, &isPath); @@ -135,14 +198,8 @@ std::tuple TypeConverter::ToFileInfo(ani_env *env, const ani_obj return { true, FileInfo { true, move(chars), {} } }; } - ani_boolean isFd = false; - env->Object_InstanceOf(pathOrFd, IntClass, &isFd); + auto [isFd, fd] = ParseFd(env, pathOrFd); if (isFd) { - ani_int fd; - if (ANI_OK != env->Object_CallMethodByName_Int(pathOrFd, "intValue", nullptr, &fd)) { - HILOGE("Parse file path failed"); - return { false, FileInfo { false, {}, {} } }; - } auto fdg = CreateUniquePtr(fd, false); if (fdg == nullptr) { HILOGE("Failed to request heap memory."); @@ -150,11 +207,16 @@ std::tuple TypeConverter::ToFileInfo(ani_env *env, const ani_obj } return { true, FileInfo { false, {}, move(fdg) } }; } + return { false, FileInfo { false, {}, {} } }; } std::tuple TypeConverter::ToArrayBuffer(ani_env *env, ani_arraybuffer &buffer) { + if (env == nullptr) { + return { false, ArrayBuffer { nullptr, 0 } }; + } + void *buf = nullptr; ani_size length = 0; @@ -167,6 +229,10 @@ std::tuple TypeConverter::ToArrayBuffer(ani_env *env, ani_arr std::tuple TypeConverter::ToAniStringList( ani_env *env, const std::string strList[], const uint32_t length) { + if (env == nullptr) { + return { false, nullptr }; + } + ani_array_ref result = nullptr; ani_class itemCls = nullptr; if (env->FindClass("Lstd/core/String;", &itemCls) != ANI_OK) { diff --git a/interfaces/kits/js/src/common/ani_helper/type_converter.h b/interfaces/kits/js/src/common/ani_helper/type_converter.h index ff8463a76337848ec362dc1540c46b2607eaf37f..24bdd736a736c1c26e1deadc3d1dc351573e2817 100644 --- a/interfaces/kits/js/src/common/ani_helper/type_converter.h +++ b/interfaces/kits/js/src/common/ani_helper/type_converter.h @@ -30,8 +30,8 @@ inline const std::string EMPTY_STRING = ""; class TypeConverter { public: static std::tuple ToUTF8String(ani_env *env, const ani_string &path); - static std::tuple> ToOptionalInt32(ani_env *env, const ani_object &intOp); - static std::tuple> ToOptionalInt64(ani_env *env, const ani_object &longOp); + static std::tuple> ToOptionalInt32(ani_env *env, const ani_object &value); + static std::tuple> ToOptionalInt64(ani_env *env, const ani_object &value); static std::tuple ToAniString(ani_env *env, std::string str); static std::tuple ToAniString(ani_env *env, const char *str); static std::tuple> EnumToInt32(ani_env *env, const ani_enum_item &enumOp); diff --git a/interfaces/kits/js/src/mod_fs/ani/arktsconfig.json b/interfaces/kits/js/src/mod_fs/ani/arktsconfig.json deleted file mode 100644 index 748c905719d84a6a72f1c14cfa8a4afdaabc2f56..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/src/mod_fs/ani/arktsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ - -{ - "compilerOptions": { - "package": "", - "baseUrl": ".", - "outDir": "./dist", - "paths": { - "std": [ - "../../../../../../../../../arkcompiler/runtime_core/static_core/plugins/ets/stdlib/std" - ], - "escompat": [ - "../../../../../../../../../arkcompiler/runtime_core/static_core/plugins/ets/stdlib/escompat" - ] - } - }, - "include": [ - "*.ets" - ] -} diff --git a/interfaces/kits/js/src/mod_fs/ani/bind_function_class.cpp b/interfaces/kits/js/src/mod_fs/ani/bind_function_class.cpp index 779bd453b99928081a448c410be2d99ad182fe7f..065495c9ade9c4c775ce494fa218d0c382077459 100644 --- a/interfaces/kits/js/src/mod_fs/ani/bind_function_class.cpp +++ b/interfaces/kits/js/src/mod_fs/ani/bind_function_class.cpp @@ -39,7 +39,7 @@ using namespace OHOS::FileManagement::ModuleFileIO::ANI; static ani_status BindFileMethods(ani_env *env) { - static const char *className = "Lfile_fs_class/FileInner;"; + static const char *className = "L@ohos/file/fs/FileInner;"; std::array methods = { ani_native_function { "getParent", nullptr, reinterpret_cast(FileAni::GetParent) }, @@ -53,7 +53,7 @@ static ani_status BindFileMethods(ani_env *env) static ani_status BindStatClassMethods(ani_env *env) { - static const char *className = "Lfile_fs_class/StatInner;"; + static const char *className = "L@ohos/file/fs/StatInner;"; std::array methods = { ani_native_function { "isBlockDevice", ":Z", reinterpret_cast(StatAni::IsBlockDevice) }, @@ -70,15 +70,15 @@ static ani_status BindStatClassMethods(ani_env *env) static ani_status BindStaticMethods(ani_env *env) { - static const char *className = "Lfile_fs_class/fileIo;"; + static const char *className = "L@ohos/file/fs/FileIoImpl;"; std::array methods = { ani_native_function { "closeSync", nullptr, reinterpret_cast(CloseAni::CloseSync) }, ani_native_function { "copyFileSync", nullptr, reinterpret_cast(CopyFileAni::CopyFileSync) }, ani_native_function { "doAccessSync", nullptr, reinterpret_cast(AccessAni::AccessSync3) }, ani_native_function { "listFileSync", nullptr, reinterpret_cast(ListFileAni::ListFileSync) }, - ani_native_function { "mkdirSync", "Lstd/core/String;:I", reinterpret_cast(MkdirkAni::MkdirSync0) }, - ani_native_function { "mkdirSync", "Lstd/core/String;Z:I", reinterpret_cast(MkdirkAni::MkdirSync1) }, + ani_native_function { "mkdirSync", "Lstd/core/String;:V", reinterpret_cast(MkdirkAni::MkdirSync0) }, + ani_native_function { "mkdirSync", "Lstd/core/String;Z:V", reinterpret_cast(MkdirkAni::MkdirSync1) }, ani_native_function { "moveFileSync", nullptr, reinterpret_cast(MoveAni::MoveFileSync) }, ani_native_function { "openSync", nullptr, reinterpret_cast(OpenAni::OpenSync) }, ani_native_function { "readSync", nullptr, reinterpret_cast(ReadAni::ReadSync) }, @@ -94,17 +94,26 @@ static ani_status BindStaticMethods(ani_env *env) ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) { + if (vm == nullptr) { + HILOGE("Invalid parameter vm"); + return ANI_INVALID_ARGS; + } + + if (result == nullptr) { + HILOGE("Invalid parameter result"); + return ANI_INVALID_ARGS; + } + ani_env *env; - ani_status status = ANI_ERROR; - status = vm->GetEnv(ANI_VERSION_1, &env); + ani_status status = vm->GetEnv(ANI_VERSION_1, &env); if (status != ANI_OK) { - HILOGE("Unsupported ANI_VERSION_1"); - return status; + HILOGE("Invalid ani version!"); + return ANI_INVALID_VERSION; } status = BindStaticMethods(env); if (status != ANI_OK) { - HILOGE("Cannot bind native static methods for fileio!"); + HILOGE("Cannot bind native static methods for BindStaticMethods!"); return status; }; @@ -120,11 +129,6 @@ ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) return status; }; - if (result == nullptr) { - HILOGE("result is null!"); - return ANI_ERROR; - } - *result = ANI_VERSION_1; return ANI_OK; } diff --git a/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets b/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets new file mode 100644 index 0000000000000000000000000000000000000000..67eb95add30a0cd803f0542ae46c90f870189651 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets @@ -0,0 +1,662 @@ +/* + * 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 { BusinessError, AsyncCallback } from '@ohos.base'; + +function access(path: string, mode?: AccessModeType): Promise { + return new Promise((resolve: (result: boolean) => void, reject: (e: BusinessError) => void) => { + if (mode === undefined) { + let promise = taskpool.execute((path: string): boolean => { + return FileIoImpl.doAccessSync(path); + }, path); + promise.then((ret: NullishType) => { + let result = ret as boolean; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + } else { + let promise = taskpool.execute((path: string, mode: AccessModeType): boolean => { + return FileIoImpl.doAccessSync(path, mode); + }, path, mode); + promise.then((ret: NullishType) => { + let result = ret as boolean; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + } + }); +} + +function access(path: string, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string): boolean => { + return FileIoImpl.doAccessSync(path); + }, path); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as boolean; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, false); + }); +} + +function access(path: string, mode: AccessModeType, flag: AccessFlagType): Promise { + return new Promise((resolve: (result: boolean) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute(FileIoImpl.doAccessSync, path, mode, flag); + promise.then((ret: NullishType): void => { + let result = ret as boolean; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }) +} + +function accessSync(path: string, mode?: AccessModeType): boolean { + return FileIoImpl.doAccessSync(path, mode); +} + +function accessSync(path: string, mode: AccessModeType, flag: AccessFlagType): boolean { + return FileIoImpl.doAccessSync(path, mode, flag); +} + +function close(file: number | File): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((file: number | File): undefined => FileIoImpl.closeSync(file), file); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function close(file: number | File, callback: AsyncCallback): void { + let promise = taskpool.execute((file: number | File): undefined => FileIoImpl.closeSync(file), file); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function closeSync(file: number | File): void { + return FileIoImpl.closeSync(file) +} + +function mkdirSync(path: string): void { + return FileIoImpl.mkdirSync(path) +} + +function mkdirSync(path: string, recursion: boolean): void { + return FileIoImpl.mkdirSync(path, recursion) +} + +function mkdirSync1(path: string): undefined { + FileIoImpl.mkdirSync(path); + return undefined; +} + +function mkdirSync2(path: string, recursion: boolean): undefined { + FileIoImpl.mkdirSync(path, recursion); + return undefined; +} + +function mkdir(path: string): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((path: string): undefined => mkdirSync1(path), path); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e as BusinessError); + }); + }); +} + +function mkdir(path: string, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string): undefined => mkdirSync1(path), path); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function mkdir(path: string, recursion: boolean): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((path: string, recursion: boolean): undefined => + mkdirSync2(path, recursion), path, recursion); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: NullishType): void => { + reject(e as BusinessError); + }); + }); +} + +function mkdir(path: string, recursion: boolean, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string, recursion: boolean): undefined => + mkdirSync2(path, recursion), path, recursion); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function moveFileSync(src: string, dest: string, mode?: number): void { + return FileIoImpl.moveFileSync(src, dest, mode); +} + +function openSync(path: string, mode?: number): File { + return FileIoImpl.openSync(path, mode); +} + +function open(path: String, mode?: number): Promise { + return new Promise((resolve: (result: File) => void, reject: (e: BusinessError) => void) => { + if (mode === undefined) { + let promise = taskpool.execute(FileIoImpl.openSync, path); + promise.then((ret: NullishType): void => { + let file = ret as File; + resolve(file); + }).catch((e: BusinessError): void => { + reject(e); + }); + } else { + let promise = taskpool.execute(FileIoImpl.openSync, path, mode); + promise.then((ret: NullishType): void => { + let file = ret as File; + resolve(file); + }).catch((e: BusinessError): void => { + reject(e); + }); + } + }); +} + +function open(path: String, mode: number, callback: AsyncCallback): void { + let promise = taskpool.execute(FileIoImpl.openSync, path, mode); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let file = ret as File; + callback(e, file); + }).catch((e: BusinessError): void => { + let f: File = new FileInner(0); + callback(e, f); + }); +} + +function open(path: String, callback: AsyncCallback): void { + let promise = taskpool.execute(FileIoImpl.openSync, path); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let file = ret as File; + callback(e, file); + }).catch((e: BusinessError): void => { + let f: File = new FileInner(0); + callback(e, f); + }); +} + +function writeSync(fd: number, buffer: string | ArrayBuffer, options?: WriteOptions): number { + return FileIoImpl.writeSync(fd, buffer, options); +} + +function write(fd: number, buffer: string | ArrayBuffer, options?: WriteOptions): Promise { + return new Promise((resolve: (result: number) => void, reject: (e: BusinessError) => void) => { + if (options === undefined) { + let promise = taskpool.execute(FileIoImpl.writeSync, fd, buffer, options); + promise.then((ret: NullishType): void => { + let result = ret as number + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + } else { + let promise = taskpool.execute(FileIoImpl.writeSync, fd, buffer, options); + promise.then((ret: NullishType): void => { + let result = ret as number + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + } + }); +} + +function write(fd: number, buffer: string | ArrayBuffer, options: WriteOptions, + callback: AsyncCallback): void { + let promise = taskpool.execute(FileIoImpl.writeSync, fd, buffer, options); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); +} + +function write(fd: number, buffer: string | ArrayBuffer, callback: AsyncCallback): void { + let promise = taskpool.execute(FileIoImpl.writeSync, fd, buffer); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); +} + +function readSync(fd: number, buffer: ArrayBuffer, options?: ReadOptions): number { + return FileIoImpl.readSync(fd, buffer, options) +} + +function read(fd: number, buffer: ArrayBuffer, options?: ReadOptions): Promise { + return new Promise((resolve: (result: number) => void, reject: (e: BusinessError) => void) => { + if (options === undefined) { + let promise = taskpool.execute((fd: number, buffer: ArrayBuffer): number => { + return FileIoImpl.readSync(fd, buffer); + }, fd, buffer); + promise.then((ret: NullishType) => { + let result = ret as number; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + } else { + let promise = taskpool.execute((fd: number, buffer: ArrayBuffer, options: ReadOptions): number => { + return FileIoImpl.readSync(fd, buffer, options) + }, fd, buffer, options); + promise.then((ret: NullishType) => { + let result = ret as number; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + } + }); +} + +function read(fd: number, buffer: ArrayBuffer, callback: AsyncCallback): void { + let promise = taskpool.execute(FileIoImpl.readSync, fd, buffer); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); +} + +function read(fd: number, buffer: ArrayBuffer, options: ReadOptions, callback: AsyncCallback): void { + let promise = taskpool.execute(FileIoImpl.readSync, fd, buffer, options); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as number; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, 0); + }); +} + +function rmdirSync(path: string): void { + return FileIoImpl.rmdirSync(path) +} + +function truncateSync(file: string | number, len?: number): void { + return FileIoImpl.truncateSync(file, len) +} + +function unlinkSync(path: string): void { + return FileIoImpl.unlinkSync(path) +} + +function unlink(path: string): Promise { + return new Promise((resolve: (result: undefined) => void, + reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((path: string): undefined => unlinkSync(path), path); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function unlink(path: string, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string): undefined => unlinkSync(path), path); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + +function readText(filePath: string, options?: ReadTextOptions): Promise { + return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void) => { + if (options === undefined) { + let promise = taskpool.execute(FileIoImpl.readTextSync, filePath); + promise.then((ret: NullishType): void => { + let r = ret as string; + resolve(r); + }).catch((e: BusinessError): void => { + reject(e); + }); + } else { + let promise = taskpool.execute(FileIoImpl.readTextSync, filePath, options); + promise.then((ret: NullishType): void => { + let r = ret as string; + resolve(r); + }).catch((e: BusinessError): void => { + reject(e); + }); + } + }); +} + +function readText(filePath: string, callback: AsyncCallback): void { + let promise = taskpool.execute(FileIoImpl.readTextSync, filePath); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let r = ret as string; + callback(e, r); + }).catch((e: BusinessError): void => { + callback(e, ""); + }); +} + +function readText(filePath: string, options: ReadTextOptions, callback: AsyncCallback): void { + let promise = taskpool.execute(FileIoImpl.readTextSync, filePath, options); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let r = ret as string; + callback(e, r); + }).catch((e: BusinessError): void => { + callback(e, ""); + }); +} + +function readTextSync(filePath: string, options?: ReadTextOptions): string { + return FileIoImpl.readTextSync(filePath, options); +} + +function listFile(path: string, options?: ListFileOptions): Promise { + return new Promise((resolve: (result: string[]) => void, reject: (e: BusinessError) => void) => { + if (options === undefined) { + let promise = taskpool.execute(FileIoImpl.listFileSync, path); + promise.then((ret: NullishType): void => { + let r = ret as string[]; + resolve(r); + }).catch((e: BusinessError): void => { + reject(e); + }); + } else { + let promise = taskpool.execute(FileIoImpl.listFileSync, path, options); + promise.then((ret: NullishType): void => { + let r = ret as string[]; + resolve(r); + }).catch((e: BusinessError): void => { + reject(e); + }); + } + }); +} + +function listFile(path: string, callback: AsyncCallback): void { + let promise = taskpool.execute(FileIoImpl.listFileSync, path); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let r = ret as string[]; + callback(e, r); + }).catch((e: BusinessError): void => { + callback(e, []); + }); +} + +function listFile(path: string, options: ListFileOptions, callback: AsyncCallback): void { + let promise = taskpool.execute(FileIoImpl.listFileSync, path, options); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let r = ret as string[]; + callback(e, r); + }).catch((e: BusinessError): void => { + callback(e, []); + }); +} + +function listFileSync(path: string, options?: ListFileOptions): string[] { + return FileIoImpl.listFileSync(path, options); +} + +function copyFileSync(src: string | number, dest: string | number, mode?: number): void { + return FileIoImpl.copyFileSync(src, dest, mode) +} + +function statSync(file: string | number): Stat { + return FileIoImpl.statSync(file) +} + +function stat(file: string | number): Promise { + return new Promise((resolve: (result: Stat) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute(FileIoImpl.statSync, file); + promise.then((ret: NullishType): void => { + let r = ret as Stat; + resolve(r); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} + +function stat(file: string | number, callback: AsyncCallback): void { + let p = taskpool.execute(FileIoImpl.statSync, file); + p.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let r = ret as Stat; + callback(e, r); + }).catch((e: BusinessError): void => { + callback(e, new StatInner(0)); + }); +} + +export interface Filter { + suffix?: Array; + displayName?: Array; + mimeType?: Array; + fileSizeOver?: number; + lastModifiedAfter?: number; + excludeMedia?: boolean; +} + +export interface ListFileOptions { + recursion?: boolean; + listNum?: number; + filter?: Filter; +} + +export interface ReadOptions { + offset?: number; + length?: number; +} + +export interface ReadTextOptions extends ReadOptions { + encoding?: string; +} + +export interface WriteOptions { + offset?: number; + length?: number; + encoding?: string; +} + +enum AccessModeType { + EXIST = 0, + WRITE = 2, + READ = 4, + READ_WRITE = 6, +} + +enum AccessFlagType { + LOCAL = 0, +} + +export interface File { + fd: number; + path: String; + name: String; + + getParent(): String; + lock(exclusive?: boolean): void; + tryLock(exclusive?: boolean): void; + unlock(): void; +} + +class FileInner implements File { + fd: number = -1; + path: String = ""; + name: String = ""; + + private nativePtr: long = 0; + + constructor(ptr: long) { + if (this.nativePtr === 0) { + this.nativePtr = ptr; + } + } + + native getParent(): String; + native lock(exclusive?: boolean): void; + native tryLock(exclusive?: boolean): void; + native unlock(): void; + +} + +enum LocationType { + LOCAL = 1, + CLOUD = 2 +} + +export interface Stat { + ino: bigint; + mode: number; + uid: number; + gid: number; + size: number; + atime: number; + mtime: number; + ctime: number; + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + location: LocationType; + + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isDirectory(): boolean; + isFIFO(): boolean; + isFile(): boolean; + isSocket(): boolean; + isSymbolicLink(): boolean; +} + +class StatInner implements Stat { + ino: bigint = 0n; + mode: number; + uid: number; + gid: number; + size: number; + atime: number; + mtime: number; + ctime: number; + atimeNs: bigint = 0n; + mtimeNs: bigint = 0n; + ctimeNs: bigint = 0n; + location: LocationType = LocationType.LOCAL; + + private nativeStat: long = 0; + + constructor(stat: long) { + if (this.nativeStat === 0) { + this.nativeStat = stat; + } + } + + native isBlockDevice(): boolean; + native isCharacterDevice(): boolean; + native isDirectory(): boolean; + native isFIFO(): boolean; + native isFile(): boolean; + native isSocket(): boolean; + native isSymbolicLink(): boolean; +} + +class FileIoImpl { + + static { + loadLibrary("ani_fs_class"); + } + + static native doAccessSync(path: string, mode?: AccessModeType, flag?: AccessFlagType): boolean; + + static native closeSync(file: number | File): void; + + static native copyFileSync(src: string | number, dest: string | number, mode?: number): void; + + static native listFileSync(path: string, options?: ListFileOptions): string[]; + + static native mkdirSync(path: string): void; + + static native mkdirSync(path: string, recursion: boolean): void; + + static native moveFileSync(src: String, dest: String, mode?: number): void; + + static native openSync(path: String, mode?: number): File; + + static native readSync(fd: number, buffer: ArrayBuffer, options?: ReadOptions): number; + + static native readTextSync(filePath: string, options?: ReadTextOptions): string; + + static native rmdirSync(path: string): void; + + static native statSync(file: string | number): Stat; + + static native truncateSync(file: string | number, len?: number): void; + + static native unlinkSync(path: string): void; + + static native writeSync(fd: number, buffer: string | ArrayBuffer, options?: WriteOptions): number; + +} diff --git a/interfaces/kits/js/src/mod_fs/ani/file_fs_class.ets b/interfaces/kits/js/src/mod_fs/ani/file_fs_class.ets deleted file mode 100644 index dde54350e2cfab73b1e5b71ab19a0ab310f1444e..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/src/mod_fs/ani/file_fs_class.ets +++ /dev/null @@ -1,742 +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. - */ - -export default fileIo; - -export class BusinessError { - code: number = 0; - data?: T; -} - -export type AsyncCallback = (err: BusinessError, data?: T) => void; - -export interface Filter { - suffix?: Array; - displayName?: Array; - mimeType?: Array; - fileSizeOver?: number; - lastModifiedAfter?: number; - excludeMedia?: boolean; -} - -export interface ListFileOptions { - recursion?: boolean; - listNum?: number; - filter?: Filter; -} - -export interface ReadOptions { - offset?: number; - length?: number; -} - -export interface ReadTextOptions extends ReadOptions { - encoding?: string; -} - -export interface WriteOptions { - offset?: long; - length?: long; - encoding?: string; -} - -enum AccessModeType { - EXIST = 0, - WRITE = 2, - READ = 4, - READ_WRITE = 6, -} - -enum AccessFlagType { - LOCAL = 0, -} - -interface File { - fd: int; - path: String; - name: String; - - getParent(): String; - lock(exclusive?: boolean): void; - tryLock(exclusive?: boolean): void; - unlock(): void; -} - -class FileInner implements File { - fd: int = -1; - path: String = ""; - name: String = ""; - - private nativePtr: long = 0; - - constructor(ptr: long) { - if (this.nativePtr == 0) { - this.nativePtr = ptr; - } - } - - native getParent(): String; - native lock(exclusive?: boolean): void; - native tryLock(exclusive?: boolean): void; - native unlock(): void; - -} - -enum LocationType { - LOCAL = 1, - CLOUD = 2 -} - -interface Stat { - ino: bigint; - mode: number; - uid: number; - gid: number; - size: number; - atime: number; - mtime: number; - ctime: number; - atimeNs: bigint; - mtimeNs: bigint; - ctimeNs: bigint; - location: LocationType; - - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isDirectory(): boolean; - isFIFO(): boolean; - isFile(): boolean; - isSocket(): boolean; - isSymbolicLink(): boolean; -} - -class StatInner implements Stat { - ino: bigint = 0n; - mode: number; - uid: number; - gid: number; - size: number; - atime: number; - mtime: number; - ctime: number; - atimeNs: bigint = 0n; - mtimeNs: bigint = 0n; - ctimeNs: bigint = 0n; - location: LocationType = LocationType.LOCAL; - - private nativeStat: long = 0; - - constructor(stat: long) { - if (this.nativeStat == 0) { - this.nativeStat = stat; - } - } - - native isBlockDevice(): boolean; - native isCharacterDevice(): boolean; - native isDirectory(): boolean; - native isFIFO(): boolean; - native isFile(): boolean; - native isSocket(): boolean; - native isSymbolicLink(): boolean; -} - -type FdOrFile = int | File; -type PathOrFd = string | int; -type BufferType = string | ArrayBuffer; - -class fileIo { - - static { - loadLibrary("ani_fs_class.z"); - } - - static native doAccessSync(path: string, mode?: AccessModeType, flag?: AccessFlagType): boolean; - - static accessSync(path: string, mode?: AccessModeType): boolean { - return fileIo.doAccessSync(path, mode); - } - - static accessSync(path: string, mode: AccessModeType, flag: AccessFlagType): boolean { - return fileIo.doAccessSync(path, mode, flag); - } - - static accessSync1(path: string): boolean { - return fileIo.accessSync(path); - } - - static accessSync2(path: string, mode: AccessModeType): boolean { - return fileIo.accessSync(path, mode); - } - - static accessSync3(path: string, mode: AccessModeType, flag: AccessFlagType): boolean { - return fileIo.accessSync(path, mode, flag); - } - - static access(path: string, mode?: AccessModeType): Promise { - return new Promise((resolve: (result: boolean) => void, reject: (e: BusinessError) => void) => { - if (mode === undefined) { - let promise = taskpool.execute(fileIo.accessSync1, path); // 这里调用同步方法 - promise.then((ret: NullishType) => { - if (ret === null || ret === undefined) { // 异常处理 - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - let result = ret as boolean; - resolve(result); // 正常结果 - } - }); - } else { - let promise = taskpool.execute(fileIo.accessSync2, path, mode); // 这里调用同步方法 - promise.then((ret: NullishType) => { - if (ret === null || ret === undefined) { // 异常处理 - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - let result = ret as boolean; - resolve(result); // 正常结果 - } - }); - } - }); - } - - static access(path: string, mode: AccessModeType, flag: AccessFlagType): Promise { - return new Promise((resolve: (result: boolean) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(fileIo.accessSync3, path, mode, flag); // 这里调用同步方法 - promise.then((ret: NullishType) => { - if (ret === null || ret === undefined) { // 异常处理 - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - let result = ret as boolean; - resolve(result); // 正常结果 - } - }); - }) - } - - static access(path: string, callback: AsyncCallback): void { - let promise = taskpool.execute(fileIo.accessSync1, path); // 这里调用同步方法 - promise.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { // 异常处理 - err.code = -1; - callback(err, undefined); - } else { - err.code = 0; - let result = ret as boolean; - callback(err, result); // 正常结果 - } - }); - } - - static native closeSync(file: FdOrFile): int; - - static native copyFileSync(src: PathOrFd, dest: PathOrFd, mode?: int): void; - - static native listFileSync(path: string, options?: ListFileOptions): string[]; - - static listFileSync1(path: string): string[] { - return fileIo.listFileSync(path); - } - static listFileSync2(path: string, options: ListFileOptions): string[] { - return fileIo.listFileSync(path, options); - } - - static listFile(path: string): Promise { - return new Promise((resolve: (result: string[]) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(fileIo.listFileSync1, path); - promise.then((ret: NullishType) => { - if (ret === null || ret === undefined) { - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - let r = ret as string[]; - resolve(r); - } - }); - }); - } - - static listFile(path: string, options: ListFileOptions): Promise { - return new Promise((resolve: (result: string[]) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(fileIo.listFileSync2, path, options); - promise.then((ret: NullishType) => { - if (ret === null || ret === undefined) { - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - let r = ret as string[]; - resolve(r); - } - }); - }); - } - - static listFile(path: string, callback: AsyncCallback): void { - let p1 = taskpool.execute(fileIo.listFileSync1, path); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - err.code = -1; - callback(err, undefined); - } else { - err.code = 0; - let r = ret as string[]; - callback(err, r); - } - }); - } - - static listFile(path: string, options: ListFileOptions, callback: AsyncCallback): void { - let p1 = taskpool.execute(fileIo.listFileSync2, path, options); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - err.code = -1; - callback(err, undefined); - } else { - err.code = 0; - let r = ret as string[]; - callback(err, r); - } - }); - } - - static native mkdirSync(path: string): int; - - static native mkdirSync(path: string, recursion: boolean): int; - - static mkdir(path: string): Promise { - return new Promise((resolve: (result: int) => void, reject: (e: BusinessError) => void) => { - const mkdirSyncWrapper = (path: string) => fileIo.mkdirSync(path); - let promise = taskpool.execute(mkdirSyncWrapper, path); // 这里调用同步方法 - promise.then((ret: NullishType) => { - let result = ret as int - if (ret === null || ret === undefined) { // 异常处理 - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - resolve(result); // 正常结果 - } - }); - }); - } - - static mkdir(path: string, callback: AsyncCallback): void { - const mkdirSyncWrapper = (path: string) => fileIo.mkdirSync(path); - let p1 = taskpool.execute(mkdirSyncWrapper, path); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - console.println("-------- err code = -1 -------------"); - err.code = -1 - callback(err, undefined) - } else { - console.println("-------- err code = 0 -------------"); - err.code = 0 - let r = ret as int; - callback(err, r); - } - }); - } - - static mkdir(path: string, recursion: boolean): Promise { - return new Promise((resolve: (result: int) => void, reject: (e: BusinessError) => void) => { - const mkdirSyncWrapper = (path: string, recursion: boolean) => fileIo.mkdirSync(path, recursion); - let promise = taskpool.execute(mkdirSyncWrapper, path, recursion); // 这里调用同步方法 - promise.then((ret: NullishType) => { - let result = ret as int - if (ret === null || ret === undefined) { // 异常处理 - console.println("-------- err code = -1 -------------"); - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - console.println("-------- err code = 0 -------------"); - resolve(result); // 正常结果 - } - }); - }); - } - - static mkdir(path: string, recursion: boolean, callback: AsyncCallback): void { - const mkdirSyncWrapper = (path: string, recursion: boolean,) => fileIo.mkdirSync(path, recursion); - let p1 = taskpool.execute(mkdirSyncWrapper, path, recursion); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - console.println("-------- err code = -1 -------------"); - err.code = -1 - callback(err, undefined) - } else { - console.println("-------- err code = 0 -------------"); - err.code = 0 - let r = ret as int; - callback(err, r); - } - }); - } - - static native moveFileSync(src: String, dest: String, mode?: int): void; - - static native openSync(path: String, mode?: int): File; - - static openSync1(path: String, mode: int): File { - return fileIo.openSync(path, mode); - } - static openSync2(path: String): File { - return fileIo.openSync(path); - } - - static open(path: String, mode: int): Promise { - return new Promise((resolve: (result: File) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(fileIo.openSync1, path, mode); - promise.then((ret: NullishType) => { - if (ret === null || ret === undefined) { - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - let r = ret as File; - resolve(r); - } - }); - }); - } - - static open(path: String): Promise { - return new Promise((resolve: (result: File) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(fileIo.openSync2, path); - promise.then((ret: NullishType) => { - if (ret === null || ret === undefined) { - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - let r = ret as File; - resolve(r); - } - }); - }); - } - - static open(path: String, mode: int, callback: AsyncCallback): void { - let p1 = taskpool.execute(fileIo.openSync1, path, mode); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - console.println("-------- err code = -1 -------------"); - err.code = -1; - callback(err, undefined); - } else { - console.println("-------- err code = 0 -------------"); - err.code = 0; - let r = ret as File; - callback(err, r); - } - }); - } - - static open(path: String, callback: AsyncCallback): void { - let p1 = taskpool.execute(fileIo.openSync2, path); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - console.println("-------- err code = -1 -------------"); - err.code = -1; - callback(err, undefined); - } else { - console.println("-------- err code = 0 -------------"); - err.code = 0; - let r = ret as File; - callback(err, r); - } - }); - } - - static native readSync(fd: int, buffer: ArrayBuffer, options?: ReadOptions): long; - - static readSync1(fd: int, buffer: ArrayBuffer): long { - return fileIo.readSync(fd, buffer); - } - static readSync2(fd: int, buffer: ArrayBuffer, options: ReadOptions): long { - return fileIo.readSync(fd, buffer, options); - } - - static read(fd: int, buffer: ArrayBuffer): Promise { - return new Promise((resolve: (result: long) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(fileIo.readSync1, fd, buffer); - promise.then((ret: NullishType) => { - if (ret === null || ret === undefined) { - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - let r = ret as long; - resolve(r); - } - }); - }); - } - - static read(fd: int, buffer: ArrayBuffer, options: ReadOptions): Promise { - return new Promise((resolve: (result: long) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(fileIo.readSync2, fd, buffer, options); - promise.then((ret: NullishType) => { - if (ret === null || ret === undefined) { - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - let r = ret as long; - resolve(r); - } - }); - }); - } - - static read(fd: int, buffer: ArrayBuffer, callback: AsyncCallback): void { - let p1 = taskpool.execute(fileIo.readSync1, fd, buffer); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - console.println("-------- err code = -1 -------------"); - err.code = -1; - callback(err, undefined); - } else { - console.println("-------- err code = 0 -------------"); - err.code = 0; - let r = ret as long; - callback(err, r); - } - }); - } - - static read(fd: int, buffer: ArrayBuffer, options: ReadOptions, callback: AsyncCallback): void { - let p1 = taskpool.execute(fileIo.readSync2, fd, buffer, options); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - console.println("-------- err code = -1 -------------"); - err.code = -1; - callback(err, undefined); - } else { - console.println("-------- err code = 0 -------------"); - err.code = 0; - let r = ret as long; - callback(err, r); - } - }); - } - - static native readTextSync(filePath: string, options?: ReadTextOptions): string; - - static readTextSync1(filePath: string): string { - return fileIo.readTextSync(filePath); - } - static readTextSync2(filePath: string, options: ReadTextOptions): string { - return fileIo.readTextSync(filePath, options); - } - - static readText(filePath: string): Promise { - return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(fileIo.readTextSync1, filePath); - promise.then((ret: NullishType) => { - if (ret === null || ret === undefined) { // 异常处理 - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - let r = ret as string; - resolve(r); // 正常结果 - } - }); - }); - } - - static readText(filePath: string, options: ReadTextOptions): Promise { - return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(fileIo.readTextSync2, filePath, options); - promise.then((ret: NullishType) => { - if (ret === null || ret === undefined) { // 异常处理 - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - let r = ret as string; - resolve(r); // 正常结果 - } - }); - }); - } - - static readText(filePath: string, callback: AsyncCallback): void { - let p1 = taskpool.execute(fileIo.readTextSync1, filePath); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - console.println("-------- err code = -1 -------------"); - err.code = -1; - callback(err, undefined); - } else { - console.println("-------- err code = 0 -------------"); - err.code = 0; - let r = ret as string; - callback(err, r); - } - }); - } - - static readText(filePath: string, options: ReadTextOptions, callback: AsyncCallback): void { - let p1 = taskpool.execute(fileIo.readTextSync2, filePath, options); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - console.println("-------- err code = -1 -------------"); - err.code = -1; - callback(err, undefined); - } else { - console.println("-------- err code = 0 -------------"); - err.code = 0; - let r = ret as string; - callback(err, r); - } - }); - } - - static native rmdirSync(path: string): void; - - static native statSync(file: PathOrFd): Stat; - - static native truncateSync(file: PathOrFd, len?: long): void; - - static native unlinkSync(path: string): int; - - static unlink(path: string): Promise { - return new Promise((resolve: (result: int) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(fileIo.unlinkSync, path); // 这里调用同步方法 - promise.then((ret: NullishType) => { - let result = ret as int - if (ret === null || ret === undefined) { // 异常处理 - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - resolve(result); // 正常结果 - } - }); - }); - } - - static unlink(path: string, callback: AsyncCallback): void { - let p1 = taskpool.execute(fileIo.unlinkSync, path); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - console.println("-------- err code = -1 -------------"); - err.code = -1 - callback(err, undefined) - } else { - console.println("-------- err code = 0 -------------"); - err.code = 0 - let r = ret as int; - callback(err, r); - } - }); - } - - static native writeSync(fd: int, buffer: BufferType, options?: WriteOptions): long; - - static writeSync1(fd: int, buffer: BufferType, options: WriteOptions): long { - return fileIo.writeSync(fd, buffer, options); - } - static writeSync2(fd: int, buffer: BufferType): long { - return fileIo.writeSync(fd, buffer); - } - - static write(fd: int, buffer: BufferType, options: WriteOptions): Promise { - return new Promise((resolve: (result: long) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(fileIo.writeSync1, fd, buffer, options); - promise.then((ret: NullishType) => { - let result = ret as long - if (ret === null || ret === undefined) { - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - resolve(result); - } - }); - }); - } - - static write(fd: int, buffer: BufferType): Promise { - return new Promise((resolve: (result: long) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(fileIo.writeSync2, fd, buffer); - promise.then((ret: NullishType) => { - let result = ret as long - if (ret === null || ret === undefined) { - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - resolve(result); - } - }); - }); - } - - static write(fd: int, buffer: BufferType, options: WriteOptions, callback: AsyncCallback): void { - let p1 = taskpool.execute(fileIo.writeSync1, fd, buffer, options); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - console.println("-------- err code = -1 -------------"); - err.code = -1 - callback(err, undefined) - } else { - console.println("-------- err code = 0 -------------"); - err.code = 0 - let r = ret as long; - callback(err, r); - } - }); - } - - static write(fd: int, buffer: BufferType, callback: AsyncCallback): void { - let p1 = taskpool.execute(fileIo.writeSync2, fd, buffer); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - console.println("-------- err code = -1 -------------"); - err.code = -1 - callback(err, undefined) - } else { - console.println("-------- err code = 0 -------------"); - err.code = 0 - let r = ret as long; - callback(err, r); - } - }); - } -} diff --git a/interfaces/kits/js/src/mod_fs/class_file/ani/file_ani.cpp b/interfaces/kits/js/src/mod_fs/class_file/ani/file_ani.cpp index c404e0a622c9e71e7823c095b4a36a6bedec2148..5dc1136590656cda875c8d1ee80b73597af47b27 100644 --- a/interfaces/kits/js/src/mod_fs/class_file/ani/file_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/class_file/ani/file_ani.cpp @@ -15,7 +15,7 @@ #include "file_ani.h" -#include +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "fs_file.h" #include "type_converter.h" @@ -45,17 +45,21 @@ ani_string FileAni::GetParent(ani_env *env, [[maybe_unused]] ani_object object) auto fsFile = Unwrap(env, object); if (fsFile == nullptr) { HILOGE("Cannot unwrap fsfile!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); return {}; } auto ret = fsFile->GetParent(); if (!ret.IsSuccess()) { HILOGE("Cannot get file parent!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return {}; } auto value = ret.GetData().value(); auto [succ, parent] = TypeConverter::ToAniString(env, value); if (!succ) { HILOGE("Cannot convert file parent to ani string!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); return {}; } return parent; @@ -72,11 +76,14 @@ void FileAni::Lock(ani_env *env, [[maybe_unused]] ani_object object, ani_object auto fsFile = Unwrap(env, object); if (fsFile == nullptr) { HILOGE("Cannot unwrap fsfile!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); return; } auto ret = fsFile->Lock(exc); if (!ret.IsSuccess()) { HILOGE("Lock file failed!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return; } } @@ -92,11 +99,14 @@ void FileAni::TryLock(ani_env *env, [[maybe_unused]] ani_object object, ani_obje auto fsFile = Unwrap(env, object); if (fsFile == nullptr) { HILOGE("Cannot unwrap fsfile!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); return; } auto ret = fsFile->TryLock(exc); if (!ret.IsSuccess()) { HILOGE("TryLock file failed!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return; } } @@ -106,11 +116,14 @@ void FileAni::UnLock(ani_env *env, [[maybe_unused]] ani_object object) auto fsFile = Unwrap(env, object); if (fsFile == nullptr) { HILOGE("Cannot unwrap fsfile!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); return; } auto ret = fsFile->UnLock(); if (!ret.IsSuccess()) { HILOGE("UnLock file failed!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return; } } diff --git a/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_ani.cpp b/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_ani.cpp index dd4f6bdc65611d53d9cac3213c3987652f2d20ef..beb411ed2a9c7459ae14bac8aaa86a6d39288c96 100644 --- a/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_ani.cpp @@ -15,9 +15,7 @@ #include "stat_ani.h" -#include -#include - +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "stat_core.h" #include "type_converter.h" @@ -109,7 +107,8 @@ static ani_status SetProperties(ani_env *env, const ani_class &cls, ani_object & { "size", ani_double(static_cast(fsStat->GetSize())) }, { "atime", ani_double(static_cast(fsStat->GetAtime())) }, { "mtime", ani_double(static_cast(fsStat->GetMtime())) }, - { "ctime", ani_double(static_cast(fsStat->GetCtime())) } }; + { "ctime", ani_double(static_cast(fsStat->GetCtime())) }, + }; for (auto iter : numProperties) { ret = SetNumProperty(env, cls, statObject, iter.first, iter.second); if (ret != ANI_OK) { @@ -122,7 +121,8 @@ static ani_status SetProperties(ani_env *env, const ani_class &cls, ani_object & { "ino", ani_double(static_cast(fsStat->GetIno())) }, { "atimeNs", ani_double(static_cast(fsStat->GetAtimeNs())) }, { "mtimeNs", ani_double(static_cast(fsStat->GetMtimeNs())) }, - { "ctimeNs", ani_double(static_cast(fsStat->GetCtimeNs())) } }; + { "ctimeNs", ani_double(static_cast(fsStat->GetCtimeNs())) }, + }; for (auto iter : bigIntProperties) { ret = SetBigIntProperty(env, cls, statObject, iter.first, iter.second); if (ret != ANI_OK) { @@ -131,11 +131,13 @@ static ani_status SetProperties(ani_env *env, const ani_class &cls, ani_object & } } +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) if ((ret = SetEnumLocation(env, cls, statObject, "location", static_cast(fsStat->GetLocation()))) != ANI_OK) { HILOGE("Object_CallMethod_Void Fail location, err: %{private}d", ret); return ret; } +#endif return ANI_OK; } @@ -143,7 +145,7 @@ static ani_status SetProperties(ani_env *env, const ani_class &cls, ani_object & static tuple Wrap(ani_env *env, FsStat *fsStat) { ani_object statObject = {}; - static const char *className = "Lfile_fs_class/StatInner;"; + static const char *className = "L@ohos/file/fs/StatInner;"; ani_class cls; ani_status ret; @@ -187,12 +189,15 @@ ani_object StatAni::StatSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani auto [succPath, fileInfo] = TypeConverter::ToFileInfo(env, file); if (!succPath) { HILOGE("The first argument requires filepath/fd"); + ErrorHandler::Throw(env, EINVAL); return {}; } auto ret = StatCore::DoStat(fileInfo); if (!ret.IsSuccess()) { HILOGE("DoStat failed!"); + const FsError &err = ret.GetError(); + ErrorHandler::Throw(env, err); return {}; } @@ -202,8 +207,10 @@ ani_object StatAni::StatSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani delete fsStat; fsStat = nullptr; HILOGE("Wrap stat object failed!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); return {}; } + return statObject; } @@ -211,6 +218,7 @@ ani_boolean StatAni::IsBlockDevice(ani_env *env, [[maybe_unused]] ani_object obj { auto fsStat = Unwrap(env, object); if (fsStat == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); return ANI_FALSE; } @@ -222,6 +230,7 @@ ani_boolean StatAni::IsCharacterDevice(ani_env *env, [[maybe_unused]] ani_object { auto fsStat = Unwrap(env, object); if (fsStat == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); return ANI_FALSE; } @@ -233,6 +242,7 @@ ani_boolean StatAni::IsDirectory(ani_env *env, [[maybe_unused]] ani_object objec { auto fsStat = Unwrap(env, object); if (fsStat == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); return ANI_FALSE; } @@ -244,6 +254,7 @@ ani_boolean StatAni::IsFIFO(ani_env *env, [[maybe_unused]] ani_object object) { auto fsStat = Unwrap(env, object); if (fsStat == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); return ANI_FALSE; } @@ -255,6 +266,7 @@ ani_boolean StatAni::IsFile(ani_env *env, [[maybe_unused]] ani_object object) { auto fsStat = Unwrap(env, object); if (fsStat == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); return ANI_FALSE; } @@ -266,6 +278,7 @@ ani_boolean StatAni::IsSocket(ani_env *env, [[maybe_unused]] ani_object object) { auto fsStat = Unwrap(env, object); if (fsStat == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); return ANI_FALSE; } @@ -277,6 +290,7 @@ ani_boolean StatAni::IsSymbolicLink(ani_env *env, [[maybe_unused]] ani_object ob { auto fsStat = Unwrap(env, object); if (fsStat == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); return ANI_FALSE; } diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/access_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/access_ani.cpp index e98af682d33ba2c196c4d9178d34f1820a9a7383..329e116231db924a7a676180d4d20c25f63f8eca 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/access_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/access_ani.cpp @@ -16,6 +16,7 @@ #include "access_ani.h" #include "access_core.h" +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "type_converter.h" @@ -80,12 +81,14 @@ ani_boolean AccessAni::AccessSync3( auto [succPath, pathStr] = TypeConverter::ToUTF8String(env, path); if (!succPath) { HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); return ret; } auto [succMode, modeOp] = TypeConverter::EnumToInt32(env, mode); if (!succMode) { HILOGE("Invalid mode"); + ErrorHandler::Throw(env, EINVAL); return ret; } auto modeType = OptToAccessModeType(modeOp); @@ -93,6 +96,7 @@ ani_boolean AccessAni::AccessSync3( auto [succFlag, flagOpt] = TypeConverter::EnumToInt32(env, flag); if (!succFlag) { HILOGE("Invalid flag"); + ErrorHandler::Throw(env, EINVAL); return ret; } auto flagType = OptToAccessFlagType(flagOpt); @@ -106,6 +110,8 @@ ani_boolean AccessAni::AccessSync3( if (!fsRet.IsSuccess()) { HILOGE("DoAccess failed"); + const auto &err = fsRet.GetError(); + ErrorHandler::Throw(env, err); return false; } return fsRet.GetData().value(); diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/close_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/close_ani.cpp index e4d1fe4e2c65b3503f6ad5325ba195cd500b149d..f49ccf2f256d3f877b6970f70c7c27e698fcd57e 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/close_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/close_ani.cpp @@ -18,6 +18,7 @@ #include #include "close_core.h" +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "type_converter.h" @@ -29,9 +30,9 @@ namespace ANI { using namespace std; using namespace OHOS::FileManagement::ModuleFileIO; -tuple AnalyzerFdUnion(ani_env *env, ani_object obj) +tuple ParseFd(ani_env *env, ani_object obj) { - int result = -1; + int32_t result = -1; ani_class IntClass; env->FindClass("Lstd/core/Double;", &IntClass); ani_boolean isInt; @@ -42,40 +43,43 @@ tuple AnalyzerFdUnion(ani_env *env, ani_object obj) HILOGE("Get fd value failed"); return { false, result }; } - result = static_cast(fd); + result = static_cast(fd); return { true, result }; } ani_class FileClass; - env->FindClass("Lfile_fs_class/FileInner;", &FileClass); + env->FindClass("L@ohos/file/fs/FileInner;", &FileClass); ani_boolean isFile; env->Object_InstanceOf(obj, FileClass, &isFile); if (isFile) { - ani_int fd; - if (ANI_OK != env->Object_GetPropertyByName_Int(obj, "fd", &fd)) { + ani_double fd; + if (ANI_OK != env->Object_GetPropertyByName_Double(obj, "fd", &fd)) { HILOGE("Get fd in class file failed"); return { false, result }; } - result = static_cast(fd); + result = static_cast(fd); return { true, result }; } + HILOGE("Invalid fd type"); return { false, result }; } -ani_int CloseAni::CloseSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_object obj) +void CloseAni::CloseSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_object obj) { - auto [succ, fd] = AnalyzerFdUnion(env, obj); + auto [succ, fd] = ParseFd(env, obj); if (!succ) { - HILOGE("Invalid arguments"); - return -1; + HILOGE("Parse fd argument failed"); + ErrorHandler::Throw(env, EINVAL); + return; } auto ret = CloseCore::DoClose(fd); if (!ret.IsSuccess()) { HILOGE("Close %d failed", fd); - return -1; + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; } - return 0; } } // namespace ANI diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/close_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/close_ani.h index 7c6202f65bf88f07422b5983e284d66e0425d331..cd2715ebeeafc532cce408b4d358d34d8e17adfa 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/close_ani.h +++ b/interfaces/kits/js/src/mod_fs/properties/ani/close_ani.h @@ -25,7 +25,7 @@ namespace ANI { class CloseAni final { public: - static ani_int CloseSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_object obj); + static void CloseSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_object obj); }; } // namespace ANI diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/copy_file_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/copy_file_ani.cpp index 161378a5736390ba992e8f11a8740f7ea930ed69..51e30f4de0053763d7b6c0d812c6c4d1b1eaf554 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/copy_file_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/copy_file_ani.cpp @@ -16,6 +16,7 @@ #include "copy_file_ani.h" #include "copy_file_core.h" +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "type_converter.h" @@ -33,18 +34,22 @@ void CopyFileAni::CopyFileSync( auto [succDest, destFile] = TypeConverter::ToFileInfo(env, dest); if (!succSrc || !succDest) { HILOGE("The first/second argument requires filepath/fd"); + ErrorHandler::Throw(env, EINVAL); return; } auto [succMode, optMode] = TypeConverter::ToOptionalInt32(env, mode); if (!succMode) { HILOGE("Failed to convert mode to int32"); + ErrorHandler::Throw(env, EINVAL); return; } auto ret = CopyFileCore::DoCopyFile(srcFile, destFile, optMode); if (!ret.IsSuccess()) { HILOGE("DoCopyFile failed!"); + const FsError &err = ret.GetError(); + ErrorHandler::Throw(env, err); return; } } diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/listfile_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/listfile_ani.cpp index 514d8d69ced021732b91edcb4ffffc49947e7d2d..8540848a3f65a064ee14969ddb619248aeb6c414 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/listfile_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/listfile_ani.cpp @@ -15,6 +15,7 @@ #include "listfile_ani.h" +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "listfile_core.h" #include "type_converter.h" @@ -35,12 +36,12 @@ tuple ParseBooleanParam(ani_env *env, ani_object obj, string tag) return { false, false }; } env->Reference_IsUndefined(bool_ref, &isUndefined); - if (!isUndefined) { + if (isUndefined) { return { true, false }; } ani_boolean bool_ref_res; - if (ANI_OK != - env->Object_CallMethodByName_Boolean(static_cast(bool_ref), "unboxed", ":Z", &bool_ref_res)) { + if (ANI_OK != env->Object_CallMethodByName_Boolean( + static_cast(bool_ref), "unboxed", ":Z", &bool_ref_res)) { return { false, false }; } return { true, static_cast(bool_ref_res) }; @@ -59,8 +60,8 @@ tuple ParseIntParam(ani_env *env, ani_object obj, string tag) return { true, result }; } ani_int result_ref_res; - if (ANI_OK != - env->Object_CallMethodByName_Int(static_cast(result_ref), "intValue", nullptr, &result_ref_res)) { + if (ANI_OK != env->Object_CallMethodByName_Int( + static_cast(result_ref), "intValue", nullptr, &result_ref_res)) { result = -1; return { false, result }; } @@ -89,7 +90,7 @@ tuple> ParseDoubleParam(ani_env *env, ani_object obj, str return { true, make_optional(result) }; } -tuple>> AnalyzerArrayString(ani_env *env, ani_object obj, string tag) +tuple>> ParseArrayString(ani_env *env, ani_object obj, string tag) { ani_boolean isUndefined; ani_ref result_ref; @@ -103,14 +104,14 @@ tuple>> AnalyzerArrayString(ani_env *env, ani_obje } ani_double length; - if (ANI_OK != env->Object_GetPropertyByName_Double(static_cast(result_ref), "length", &length) || - length == 0) { + if (ANI_OK != env->Object_GetPropertyByName_Double( + static_cast(result_ref), "length", &length) || length == 0) { return { false, nullopt }; } for (int i = 0; i < int(length); i++) { ani_ref stringEntryRef; - if (ANI_OK != env->Object_CallMethodByName_Ref(static_cast(result_ref), "$_get", - "I:Lstd/core/Object;", &stringEntryRef, (ani_int)i)) { + if (ANI_OK != env->Object_CallMethodByName_Ref( + static_cast(result_ref), "$_get", "I:Lstd/core/Object;", &stringEntryRef, (ani_int)i)) { return { false, nullopt }; } auto [succ, tmp] = TypeConverter::ToUTF8String(env, static_cast(stringEntryRef)); @@ -122,7 +123,7 @@ tuple>> AnalyzerArrayString(ani_env *env, ani_obje return { true, make_optional>(move(strings)) }; } -tuple> AnalyzeFilter(ani_env *env, ani_object obj) +tuple> ParseFilter(ani_env *env, ani_object obj) { FsFileFilter filter; @@ -140,14 +141,14 @@ tuple> AnalyzeFilter(ani_env *env, ani_object obj) } filter.SetFileSizeOver(lastModifiedAfter); - auto [succSuffix, suffix] = AnalyzerArrayString(env, obj, "suffix"); + auto [succSuffix, suffix] = ParseArrayString(env, obj, "suffix"); if (!succSuffix) { HILOGE("Illegal option.suffix parameter"); return { false, move(filter) }; } filter.SetSuffix(move(suffix)); - auto [succDisplayName, displayName] = AnalyzerArrayString(env, obj, "displayName"); + auto [succDisplayName, displayName] = ParseArrayString(env, obj, "displayName"); if (!succDisplayName) { HILOGE("Illegal option.displayName parameter"); return { false, move(filter) }; @@ -157,7 +158,7 @@ tuple> AnalyzeFilter(ani_env *env, ani_object obj) return { true, move(filter) }; } -tuple> AnalyzeArgs(ani_env *env, ani_object obj) +tuple> ParseArgs(ani_env *env, ani_object obj) { FsListFileOptions result; ani_boolean isUndefined; @@ -189,7 +190,7 @@ tuple> AnalyzeArgs(ani_env *env, ani_object ob if (isUndefined) { return { true, make_optional(result) }; } - auto [succFilter, filterFilterClass] = AnalyzeFilter(env, static_cast(filter_ref)); + auto [succFilter, filterFilterClass] = ParseFilter(env, static_cast(filter_ref)); if (!succFilter) { HILOGE("Invalid filter"); return { false, nullopt }; @@ -204,18 +205,22 @@ ani_array_ref ListFileAni::ListFileSync(ani_env *env, [[maybe_unused]] ani_class auto [succPath, srcPath] = TypeConverter::ToUTF8String(env, path); if (!succPath) { HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); return nullptr; } - auto [succOpt, opt] = AnalyzeArgs(env, obj); + auto [succOpt, opt] = ParseArgs(env, obj); if (!succOpt) { HILOGE("Invalid options Arguments"); + ErrorHandler::Throw(env, EINVAL); return nullptr; } auto ret = ListFileCore::DoListFile(srcPath, opt); if (!ret.IsSuccess()) { HILOGE("DoListFile failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return nullptr; } @@ -223,7 +228,8 @@ ani_array_ref ListFileAni::ListFileSync(ani_env *env, [[maybe_unused]] ani_class const std::string *strArray = fileList.data(); auto [succ, result] = TypeConverter::ToAniStringList(env, strArray, fileList.size()); if (!succ) { - HILOGE("list file result value to ani_string list failed"); + HILOGE("Convert list file result to ani string array failed"); + ErrorHandler::Throw(env, UNKNOWN_ERR); return nullptr; } return result; diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/mkdir_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/mkdir_ani.cpp index 12251930bd6e502d144f470aabe70eb8174b61a3..a5cd88374fc3bf4e0af4e4eba32427439116a59f 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/mkdir_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/mkdir_ani.cpp @@ -15,6 +15,7 @@ #include "mkdir_ani.h" +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "mkdir_core.h" #include "type_converter.h" @@ -24,34 +25,38 @@ namespace FileManagement { namespace ModuleFileIO { namespace ANI { -ani_int MkdirkAni::MkdirSync0(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path) +void MkdirkAni::MkdirSync0(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path) { auto [succ, pathStr] = TypeConverter::ToUTF8String(env, path); if (!succ) { HILOGE("Invalid path"); - return -1; + ErrorHandler::Throw(env, EINVAL); + return; } auto ret = MkdirCore::DoMkdir(pathStr); if (!ret.IsSuccess()) { HILOGE("Mkdir failed"); - return -1; + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; } - return 0; } -ani_int MkdirkAni::MkdirSync1(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_boolean recursion) +void MkdirkAni::MkdirSync1(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_boolean recursion) { auto [succ, pathStr] = ANI::TypeConverter::ToUTF8String(env, path); if (!succ) { HILOGE("Invalid path"); - return -1; + ErrorHandler::Throw(env, EINVAL); + return; } auto ret = MkdirCore::DoMkdir(pathStr, recursion); if (!ret.IsSuccess()) { HILOGE("DoMkdir failed"); - return -1; + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; } - return 0; } } // namespace ANI diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/mkdir_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/mkdir_ani.h index fa342d959ac8df83655847961eb7cecbf2cf8b74..8ed780e9619e99f3390c2db0493d9063a9b37e33 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/mkdir_ani.h +++ b/interfaces/kits/js/src/mod_fs/properties/ani/mkdir_ani.h @@ -25,8 +25,8 @@ namespace ANI { class MkdirkAni final { public: - static ani_int MkdirSync0(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path); - static ani_int MkdirSync1(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_boolean recursion); + static void MkdirSync0(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path); + static void MkdirSync1(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_boolean recursion); }; } // namespace ANI diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/move_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/move_ani.cpp index 0b5c597a7ae73d84ec68515bdf4139577c937607..3243554f5f9611e115048faacc029838fde49961 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/move_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/move_ani.cpp @@ -15,6 +15,7 @@ #include "move_ani.h" +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "move_core.h" #include "type_converter.h" @@ -30,21 +31,26 @@ void MoveAni::MoveFileSync( auto [succSrc, srcPath] = TypeConverter::ToUTF8String(env, src); if (!succSrc) { HILOGE("Invalid src"); + ErrorHandler::Throw(env, EINVAL); return; } auto [succDest, destPath] = TypeConverter::ToUTF8String(env, dest); if (!succDest) { HILOGE("Invalid dest"); + ErrorHandler::Throw(env, EINVAL); return; } auto [succMode, modeOp] = TypeConverter::ToOptionalInt32(env, mode); if (!succMode) { HILOGE("Invalid mode"); + ErrorHandler::Throw(env, EINVAL); return; } auto ret = MoveCore::DoMove(srcPath, destPath, modeOp); if (!ret.IsSuccess()) { HILOGE("Move failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return; } } diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/open_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/open_ani.cpp index 82eaf6156295199dbdd1be3dd21b7436199ee20b..bb76bd0865d037c3f779c972200157326809b26f 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/open_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/open_ani.cpp @@ -16,6 +16,7 @@ #include "open_ani.h" #include "ani_helper.h" +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "open_core.h" #include "type_converter.h" @@ -28,58 +29,58 @@ using namespace OHOS::FileManagement::ModuleFileIO; static ani_object Wrap(ani_env *env, const FsFile *file) { - static const char *className = "Lfile_fs_class/FileInner;"; + static const char *className = "L@ohos/file/fs/FileInner;"; ani_class cls; if (ANI_OK != env->FindClass(className, &cls)) { HILOGE("Cannot find class %s", className); - return {}; + return nullptr; } ani_method ctor; if (ANI_OK != env->Class_FindMethod(cls, "", "J:V", &ctor)) { HILOGE("Cannot find constructor method for class %s", className); - return {}; + return nullptr; } ani_long ptr = static_cast(reinterpret_cast(file)); ani_object obj; if (ANI_OK != env->Object_New(cls, ctor, &obj, ptr)) { HILOGE("New %s obj Failed!", className); - return {}; + return nullptr; } const auto &fdRet = file->GetFD(); if (!fdRet.IsSuccess()) { HILOGE("GetFD Failed!"); - return {}; + return nullptr; } const auto &fd = fdRet.GetData().value(); - if (ANI_OK != AniHelper::SetPropertyValue(env, cls, obj, "fd", fd)) { + if (ANI_OK != AniHelper::SetPropertyValue(env, cls, obj, "fd", static_cast(fd))) { HILOGE("Set fd field value failed!"); - return {}; + return nullptr; } const auto &pathRet = file->GetPath(); if (!pathRet.IsSuccess()) { HILOGE("GetPath Failed!"); - return {}; + return nullptr; } const auto &path = pathRet.GetData().value(); if (ANI_OK != AniHelper::SetPropertyValue(env, cls, obj, "path", path)) { HILOGE("Set path field value failed!"); - return {}; + return nullptr; } const auto &nameRet = file->GetName(); if (!pathRet.IsSuccess()) { HILOGE("GetPath Failed!"); - return {}; + return nullptr; } const auto &name = nameRet.GetData().value(); if (ANI_OK != AniHelper::SetPropertyValue(env, cls, obj, "name", name)) { HILOGE("Set name field value failed!"); - return {}; + return nullptr; } return obj; } @@ -89,21 +90,30 @@ ani_object OpenAni::OpenSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani auto [succPath, filePath] = TypeConverter::ToUTF8String(env, path); if (!succPath) { HILOGE("Invalid path"); - return {}; + ErrorHandler::Throw(env, EINVAL); + return nullptr; } auto [succMode, modeOp] = TypeConverter::ToOptionalInt32(env, mode); if (!succMode) { HILOGE("Invalid mode"); - return {}; + ErrorHandler::Throw(env, EINVAL); + return nullptr; } FsResult ret = OpenCore::DoOpen(filePath, modeOp); if (!ret.IsSuccess()) { HILOGE("Open failed"); - return {}; + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return nullptr; } const FsFile *file = ret.GetData().value(); - return Wrap(env, move(file)); + auto result = Wrap(env, move(file)); + if (result == nullptr) { + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + return result; } } // namespace ANI } // namespace ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/read_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/read_ani.cpp index 330d75c34ef8bd69e09d18591eb4e69f755dc6ed..fa5ce2334a35ed1d5973284dea9a9e1eafd42d22 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/read_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/read_ani.cpp @@ -17,6 +17,7 @@ #include #include "ani_helper.h" +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "read_core.h" #include "type_converter.h" @@ -51,26 +52,30 @@ static tuple> ToReadOptions(ani_env *env, ani_object return { true, make_optional(move(options)) }; } -ani_long ReadAni::ReadSync( - ani_env *env, [[maybe_unused]] ani_class clazz, ani_int fd, ani_arraybuffer buffer, ani_object options) +ani_double ReadAni::ReadSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_double fd, ani_arraybuffer buffer, ani_object options) { auto [succBuf, arrayBuffer] = TypeConverter::ToArrayBuffer(env, buffer); if (!succBuf) { HILOGE("Failed to resolve arrayBuffer!"); + ErrorHandler::Throw(env, EINVAL); return -1; } auto [succOp, op] = ToReadOptions(env, options); if (!succOp) { HILOGE("Failed to resolve options!"); + ErrorHandler::Throw(env, EINVAL); return -1; } - auto ret = ReadCore::DoRead(fd, arrayBuffer, op); + auto ret = ReadCore::DoRead(static_cast(fd), arrayBuffer, op); if (!ret.IsSuccess()) { HILOGE("Read file content failed!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return -1; } - return ret.GetData().value(); + return static_cast(ret.GetData().value()); } } // namespace OHOS::FileManagement::ModuleFileIO::ANI \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/read_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/read_ani.h index 027fd5407cec75482baa18fd188c222e1cd7fa00..ceec384b48be270170bf14f877680608ad65f1a8 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/read_ani.h +++ b/interfaces/kits/js/src/mod_fs/properties/ani/read_ani.h @@ -22,8 +22,8 @@ namespace OHOS::FileManagement::ModuleFileIO::ANI { class ReadAni final { public: - static ani_long ReadSync( - ani_env *env, [[maybe_unused]] ani_class clazz, ani_int fd, ani_arraybuffer buffer, ani_object options); + static ani_double ReadSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_double fd, ani_arraybuffer buffer, ani_object options); }; } // namespace OHOS::FileManagement::ModuleFileIO::ANI #endif // INTERFACES_KITS_JS_SRC_MOD_FS_READ_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/read_text_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/read_text_ani.cpp index 2c1c64d8af4f9b6bad14dc2f527a84589b1185f3..dc733c606ba1779568b5d76350ab0c3f8753bfa7 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/read_text_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/read_text_ani.cpp @@ -17,6 +17,7 @@ #include #include "ani_helper.h" +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "read_text_core.h" #include "type_converter.h" @@ -69,19 +70,23 @@ ani_string ReadTextAni::ReadTextSync( { auto [succOpt, options] = ToReadTextOptions(env, obj); if (!succOpt) { - HILOGE("Ivalid options"); + HILOGE("Invalid options"); + ErrorHandler::Throw(env, EINVAL); return nullptr; } auto [succPath, path] = TypeConverter::ToUTF8String(env, filePath); if (!succPath) { HILOGE("Invalid Path"); + ErrorHandler::Throw(env, EINVAL); return nullptr; } auto ret = ReadTextCore::DoReadText(path, options); if (!ret.IsSuccess()) { HILOGE("DoReadText failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return nullptr; } @@ -89,7 +94,8 @@ ani_string ReadTextAni::ReadTextSync( string res = std::get<0>(resText); auto [succ, result] = TypeConverter::ToAniString(env, res); if (!succ) { - HILOGE("Create ani_string error"); + HILOGE("Convert result to ani string failed"); + ErrorHandler::Throw(env, UNKNOWN_ERR); return nullptr; } return result; diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/rmdir_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/rmdir_ani.cpp index 42e4c5cf7faa3bc920ba514404ef5127c16e1437..04a4cfa6b2fd2ab944f40b5eb02c1e02b630f4e3 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/rmdir_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/rmdir_ani.cpp @@ -15,6 +15,7 @@ #include "rmdir_ani.h" +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "rmdir_core.h" #include "type_converter.h" @@ -30,11 +31,14 @@ void RmdirAni::RmdirSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_str auto [succPath, pathStr] = TypeConverter::ToUTF8String(env, path); if (!succPath) { HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); return; } auto ret = RmdirentCore::DoRmdirent(pathStr); if (!ret.IsSuccess()) { HILOGE("DoRmdirent failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return; } } diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/truncate_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/truncate_ani.cpp index f2231a37a6b6e6e57b777668a1e59d9dc31dedfd..6176d45e123c92a84e679d4b6ccce0bc7f6fc9e3 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/truncate_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/truncate_ani.cpp @@ -15,6 +15,7 @@ #include "truncate_ani.h" +#include "error_handler.h" #include "file_utils.h" #include "filemgmt_libhilog.h" #include "truncate_core.h" @@ -30,18 +31,22 @@ void TruncateAni::TruncateSync(ani_env *env, [[maybe_unused]] ani_class clazz, a auto [succ, fileinfo] = TypeConverter::ToFileInfo(env, file); if (!succ) { HILOGE("Invalid fd/path"); + ErrorHandler::Throw(env, EINVAL); return; } auto [succLen, len] = TypeConverter::ToOptionalInt64(env, length); if (!succLen) { HILOGE("Invalid truncate length"); + ErrorHandler::Throw(env, EINVAL); return; } auto ret = TruncateCore::DoTruncate(fileinfo, len); if (!ret.IsSuccess()) { HILOGE("Truncate failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return; } } diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/unlink_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/unlink_ani.cpp index 7c8e7a8fdabc3c179fd1a0f266c0c7473270e724..91a929d134e2b5443fe840fc16441cedf4e45f5e 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/unlink_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/unlink_ani.cpp @@ -15,6 +15,7 @@ #include "unlink_ani.h" +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "type_converter.h" #include "unlink_core.h" @@ -24,19 +25,21 @@ namespace FileManagement { namespace ModuleFileIO { namespace ANI { -ani_int UnlinkAni::UnlinkSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path) +void UnlinkAni::UnlinkSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path) { auto [succ, pathStr] = TypeConverter::ToUTF8String(env, path); if (!succ) { HILOGE("Invalid path"); - return -1; + ErrorHandler::Throw(env, EINVAL); + return; } auto ret = UnlinkCore::DoUnlink(pathStr); if (!ret.IsSuccess()) { HILOGE("Unlink failed"); - return -1; + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; } - return 0; } } // namespace ANI diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/unlink_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/unlink_ani.h index 83bb1722ec333bb5699264441ed03c591ecf1202..817b258000b9f13b5dbbc8f498b00cc74e7dc1e0 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/unlink_ani.h +++ b/interfaces/kits/js/src/mod_fs/properties/ani/unlink_ani.h @@ -25,7 +25,7 @@ namespace ANI { class UnlinkAni final { public: - static ani_int UnlinkSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path); + static void UnlinkSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path); }; } // namespace ANI diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/write_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/write_ani.cpp index 0f6248f6ce2feb88fb36fefc525ee9a7d19c5922..a87254108e209a06388e25516bac32315abe795e 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/write_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/write_ani.cpp @@ -17,6 +17,7 @@ #include #include "ani_helper.h" +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "type_converter.h" #include "write_core.h" @@ -88,12 +89,13 @@ static std::tuple ParseArrayBuffer(ani_env *env, const an return { true, std::move(result) }; } -ani_long WriteAni::WriteSync( - ani_env *env, [[maybe_unused]] ani_class clazz, ani_int fd, ani_object buf, ani_object options) +ani_double WriteAni::WriteSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_double fd, ani_object buf, ani_object options) { auto [succOp, op] = ToWriteOptions(env, options); if (!succOp) { HILOGE("Failed to resolve options!"); + ErrorHandler::Throw(env, EINVAL); return -1; } @@ -102,14 +104,17 @@ ani_long WriteAni::WriteSync( auto [succBuf, buffer] = TypeConverter::ToUTF8String(env, stringBuffer); if (!succBuf) { HILOGE("Failed to resolve stringBuffer!"); + ErrorHandler::Throw(env, EINVAL); return -1; } - auto ret = WriteCore::DoWrite(fd, buffer, op); + auto ret = WriteCore::DoWrite(static_cast(fd), buffer, op); if (!ret.IsSuccess()) { HILOGE("write buffer failed!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return -1; } - return ret.GetData().value(); + return static_cast(ret.GetData().value()); } auto [isArrayBuffer, arrayBuffer] = ParseArrayBuffer(env, buf); @@ -117,16 +122,20 @@ ani_long WriteAni::WriteSync( auto [succBuf, buffer] = TypeConverter::ToArrayBuffer(env, arrayBuffer); if (!succBuf) { HILOGE("Failed to resolve arrayBuffer!"); + ErrorHandler::Throw(env, EINVAL); return -1; } - auto ret = WriteCore::DoWrite(fd, buffer, op); + auto ret = WriteCore::DoWrite(static_cast(fd), buffer, op); if (!ret.IsSuccess()) { HILOGE("write buffer failed!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return -1; } - return ret.GetData().value(); + return static_cast(ret.GetData().value()); } HILOGE("Unsupported buffer type!"); + ErrorHandler::Throw(env, EINVAL); return -1; } } // namespace ANI diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/write_ani.h b/interfaces/kits/js/src/mod_fs/properties/ani/write_ani.h index 24d6be843e787ced51ba74d2daba249b7b7f345f..aeb6e2c4c841a9b2cd5f95958fed92ac0c383c37 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/write_ani.h +++ b/interfaces/kits/js/src/mod_fs/properties/ani/write_ani.h @@ -25,8 +25,8 @@ namespace ANI { class WriteAni final { public: - static ani_long WriteSync( - ani_env *env, [[maybe_unused]] ani_class clazz, ani_int fd, ani_object buf, ani_object options); + static ani_double WriteSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_double fd, ani_object buf, ani_object options); }; } // namespace ANI } // namespace ModuleFileIO diff --git a/interfaces/kits/js/src/mod_hash/ani/arktsconfig.json b/interfaces/kits/js/src/mod_hash/ani/arktsconfig.json deleted file mode 100644 index ae12d05b6be6cd0eb77adb251ee4c798879bef53..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/src/mod_hash/ani/arktsconfig.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "compilerOptions": { - "package": "", - "baseUrl": ".", - "outDir": "./dist", - "paths": { - "std": [ - "../../../../../../../../../arkcompiler/runtime_core/static_core/plugins/ets/stdlib/std" - ], - "escompat": [ - "../../../../../../../../../arkcompiler/runtime_core/static_core/plugins/ets/stdlib/escompat" - ] - } - }, - "include": [ - "*.ets" - ] -} diff --git a/interfaces/kits/js/src/mod_hash/ani/bind_function_class.cpp b/interfaces/kits/js/src/mod_hash/ani/bind_function_class.cpp index 8b51760ddd030d7e5ae9db0b05afca3c03791a15..52ee635891b5765649a72e907fe31b8f97fa41d2 100644 --- a/interfaces/kits/js/src/mod_hash/ani/bind_function_class.cpp +++ b/interfaces/kits/js/src/mod_hash/ani/bind_function_class.cpp @@ -19,14 +19,41 @@ using namespace OHOS::FileManagement::ModuleFileIO::ANI; -ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) +static ani_status BindStaticMethods(ani_env *env) { - static const char *className = "Lfile_hash_class/hash;"; - std::vector functions = { + static const char *className = "L@ohos/file/hash/hashImpl;"; + std::array methods = { ani_native_function { "hashSync", "Lstd/core/String;Lstd/core/String;:Lstd/core/String;", reinterpret_cast(HashAni::HashSync) }, }; + return BindClass(env, className, methods); +} + +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) +{ + if (vm == nullptr) { + HILOGE("Invalid parameter vm"); + return ANI_INVALID_ARGS; + } + + if (result == nullptr) { + HILOGE("Invalid parameter result"); + return ANI_INVALID_ARGS; + } + + ani_env *env; + ani_status status = vm->GetEnv(ANI_VERSION_1, &env); + if (status != ANI_OK) { + HILOGE("Invalid ani version!"); + return ANI_INVALID_VERSION; + } + + status = BindStaticMethods(env); + if (status != ANI_OK) { + HILOGE("Cannot bind native static methods for hash!"); + return status; + }; *result = ANI_VERSION_1; - return BindClass(vm, className, functions); + return ANI_OK; } diff --git a/interfaces/kits/js/src/mod_hash/ani/file_hash_class.ets b/interfaces/kits/js/src/mod_hash/ani/ets/@ohos.file.hash.ets similarity index 38% rename from interfaces/kits/js/src/mod_hash/ani/file_hash_class.ets rename to interfaces/kits/js/src/mod_hash/ani/ets/@ohos.file.hash.ets index c8808e36e7d4d54e350dbcecd66cbacd1e776c77..1e68269ace6dabdd99484162185d1f95525d2682 100644 --- a/interfaces/kits/js/src/mod_hash/ani/file_hash_class.ets +++ b/interfaces/kits/js/src/mod_hash/ani/ets/@ohos.file.hash.ets @@ -13,51 +13,41 @@ * limitations under the License. */ -export default hash; +import { BusinessError, AsyncCallback } from '@ohos.base'; -export class BusinessError { - code: number = 0; - data?: T; +function hashSync(path: string, algorithm: string): string { + return HashImpl.hashSync(path, algorithm); } -export type AsyncCallback = (err: BusinessError, data?: T) => void; +function hash(path: string, algorithm: string): Promise { + return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void) => { + let promise = taskpool.execute(HashImpl.hashSync, path, algorithm); + promise.then((ret: NullishType): void => { + let res = ret as string; + resolve(res); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); +} -class hash { +function hash(path: string, algorithm: string, callback: AsyncCallback): void { + let promise = taskpool.execute(HashImpl.hashSync, path, algorithm); + promise.then((ret: NullishType) => { + let e = new BusinessError(); + e.code = 0; + let res = ret as string; + callback(e, res); + }).catch((e: BusinessError): void => { + callback(e, ""); + }); +} + +class HashImpl { static { - loadLibrary("ani_hash_class.z"); + loadLibrary("ani_hash_class"); } static native hashSync(path: string, algorithm: string): string; - - static hash(path: string, algorithm: string): Promise { - return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(hash.hashSync, path, algorithm); - promise.then((ret: NullishType) => { - if (ret === null || ret === undefined) { - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - let r = ret as string; - resolve(r); - } - }); - }); - } - - static hash(path: string, algorithm: string, callback: AsyncCallback): void { - let p1 = taskpool.execute(hash.hashSync, path, algorithm); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - err.code = -1 - callback(err, undefined) - } else { - err.code = 0 - let r = ret as string; - callback(err, r); - } - }); - } } diff --git a/interfaces/kits/js/src/mod_hash/ani/hash_ani.cpp b/interfaces/kits/js/src/mod_hash/ani/hash_ani.cpp index c8bffc53cda38ffbf7bfe8372585b1fbd0aec403..6acb4389cdaba7a384403d9e61541fbe9dd6e214 100644 --- a/interfaces/kits/js/src/mod_hash/ani/hash_ani.cpp +++ b/interfaces/kits/js/src/mod_hash/ani/hash_ani.cpp @@ -15,6 +15,7 @@ #include "hash_ani.h" +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "hash_core.h" #include "type_converter.h" @@ -32,25 +33,30 @@ ani_string HashAni::HashSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani auto [succPath, srcPath] = TypeConverter::ToUTF8String(env, path); if (!succPath) { HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); return nullptr; } auto [succAlg, algType] = TypeConverter::ToUTF8String(env, algorithm); if (!succAlg) { HILOGE("Invalid algorithm"); + ErrorHandler::Throw(env, EINVAL); return nullptr; } auto ret = HashCore::DoHash(srcPath, algType); if (!ret.IsSuccess()) { HILOGE("DoHash failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return nullptr; } const auto &res = ret.GetData().value(); auto [succ, result] = TypeConverter::ToAniString(env, res); if (!succ) { - HILOGE("Convert hash value to ani_string failed"); + HILOGE("Convert hash value to ani string failed"); + ErrorHandler::Throw(env, UNKNOWN_ERR); return nullptr; } return result; diff --git a/interfaces/kits/js/src/mod_securitylabel/ani/arktsconfig.json b/interfaces/kits/js/src/mod_securitylabel/ani/arktsconfig.json deleted file mode 100644 index ae12d05b6be6cd0eb77adb251ee4c798879bef53..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/src/mod_securitylabel/ani/arktsconfig.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "compilerOptions": { - "package": "", - "baseUrl": ".", - "outDir": "./dist", - "paths": { - "std": [ - "../../../../../../../../../arkcompiler/runtime_core/static_core/plugins/ets/stdlib/std" - ], - "escompat": [ - "../../../../../../../../../arkcompiler/runtime_core/static_core/plugins/ets/stdlib/escompat" - ] - } - }, - "include": [ - "*.ets" - ] -} diff --git a/interfaces/kits/js/src/mod_securitylabel/ani/bind_function_class.cpp b/interfaces/kits/js/src/mod_securitylabel/ani/bind_function_class.cpp index 19e735c51bc727944f74f974824645049f861193..9dfe0fb3ff27cb1896ae8304e28ef3176e6baae0 100644 --- a/interfaces/kits/js/src/mod_securitylabel/ani/bind_function_class.cpp +++ b/interfaces/kits/js/src/mod_securitylabel/ani/bind_function_class.cpp @@ -19,15 +19,41 @@ using namespace OHOS::FileManagement::ModuleFileIO::ANI; +static ani_status BindStaticMethods(ani_env *env) +{ + static const char *className = "L@ohos/file/securityLabel/securitylabelImpl;"; + std::array methods = { + ani_native_function { "setSecurityLabelSync", "Lstd/core/String;Lstd/core/String;:V", + reinterpret_cast(SecurityLabelAni::SetSecurityLabelSync) }, + }; + return BindClass(env, className, methods); +} + ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) { - *result = ANI_VERSION_1; + if (vm == nullptr) { + HILOGE("Invalid parameter vm"); + return ANI_INVALID_ARGS; + } - static const char *className = "Lfile_securitylabel_class/securitylabel;"; - std::vector functions = { - ani_native_function { "setSecurityLabelSync", "Lstd/core/String;Lstd/core/String;:I", - reinterpret_cast(SecurityLabelAni::SetSecurityLabelSync) }, + if (result == nullptr) { + HILOGE("Invalid parameter result"); + return ANI_INVALID_ARGS; + } + + ani_env *env; + ani_status status = vm->GetEnv(ANI_VERSION_1, &env); + if (status != ANI_OK) { + HILOGE("Invalid ani version!"); + return ANI_INVALID_VERSION; + } + + status = BindStaticMethods(env); + if (status != ANI_OK) { + HILOGE("Cannot bind native static methods for securitylabel!"); + return status; }; - return BindClass(vm, className, functions); + *result = ANI_VERSION_1; + return ANI_OK; } diff --git a/interfaces/kits/js/src/mod_securitylabel/ani/file_securitylabel_class.ets b/interfaces/kits/js/src/mod_securitylabel/ani/ets/@ohos.file.securityLabel.ets similarity index 37% rename from interfaces/kits/js/src/mod_securitylabel/ani/file_securitylabel_class.ets rename to interfaces/kits/js/src/mod_securitylabel/ani/ets/@ohos.file.securityLabel.ets index 3e851ba67dd14643209f0afd8b95f63c8ca03ae4..28c002c7e3d732a7e139c6e7f909ec65a82d3192 100644 --- a/interfaces/kits/js/src/mod_securitylabel/ani/file_securitylabel_class.ets +++ b/interfaces/kits/js/src/mod_securitylabel/ani/ets/@ohos.file.securityLabel.ets @@ -13,53 +13,41 @@ * limitations under the License. */ -export default securitylabel; +import { BusinessError, AsyncCallback } from '@ohos.base'; -export class BusinessError { - code: number = 0; - data?: T; +type DataLevel = 's0' | 's1' | 's2' | 's3' | 's4'; + +function setSecurityLabel(path: string, type: DataLevel): Promise { + return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute((path: string, type: DataLevel): void => SecurityLabelImpl.setSecurityLabelSync(path, type), path, type); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); } -export type AsyncCallback = (err: BusinessError, data?: T) => void; +function setSecurityLabel(path: string, type: DataLevel, callback: AsyncCallback): void { + let promise = taskpool.execute((path: string, type: DataLevel): void => SecurityLabelImpl.setSecurityLabelSync(path, type), path, type); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} -type DataLevel = 's0' | 's1' | 's2' | 's3' | 's4'; +function setSecurityLabelSync(path: string, type: DataLevel): void { + return SecurityLabelImpl.setSecurityLabelSync(path, type); +} -class securitylabel { +class SecurityLabelImpl { static { - loadLibrary("ani_securitylabel_class.z"); + loadLibrary("ani_securitylabel_class"); } - static native setSecurityLabelSync(path: string, type: DataLevel): int; - - static setSecurityLabel(path: string, type: DataLevel): Promise { - return new Promise((resolve: (result: int) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(securitylabel.setSecurityLabelSync, path, type); - promise.then((ret: NullishType) => { - if (ret === null || ret === undefined) { - let err = new BusinessError(); - err.code = -1; - reject(err); - } else { - let r = ret as int; - resolve(r); - } - }); - }); - } - - static setSecurityLabel(path: string, type: DataLevel, callback: AsyncCallback): void { - let p1 = taskpool.execute(securitylabel.setSecurityLabelSync, path, type); - p1.then((ret: NullishType) => { - let err = new BusinessError(); - if (ret === null || ret === undefined) { - err.code = -1 - callback(err, undefined) - } else { - err.code = 0 - let r = ret as int; - callback(err, r); - } - }); - } + static native setSecurityLabelSync(path: string, type: DataLevel): void; } diff --git a/interfaces/kits/js/src/mod_securitylabel/ani/securitylabel_ani.cpp b/interfaces/kits/js/src/mod_securitylabel/ani/securitylabel_ani.cpp index 35f28cc7afa66a1a62b103feec1340b65554156e..6c44deb69a515dcf5bf600643ea84b7886101809 100644 --- a/interfaces/kits/js/src/mod_securitylabel/ani/securitylabel_ani.cpp +++ b/interfaces/kits/js/src/mod_securitylabel/ani/securitylabel_ani.cpp @@ -15,6 +15,7 @@ #include "securitylabel_ani.h" +#include "error_handler.h" #include "filemgmt_libhilog.h" #include "securitylabel_core.h" #include "type_converter.h" @@ -28,28 +29,30 @@ using namespace std; using namespace OHOS::FileManagement::ModuleFileIO; using namespace OHOS::FileManagement::ModuleSecurityLabel; -ani_int SecurityLabelAni::SetSecurityLabelSync( +void SecurityLabelAni::SetSecurityLabelSync( ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_string level) { auto [succPath, srcPath] = TypeConverter::ToUTF8String(env, path); if (!succPath) { HILOGE("Invalid path"); - return -1; + ErrorHandler::Throw(env, EINVAL); + return; } auto [succLevel, dataLevel] = TypeConverter::ToUTF8String(env, level); if (!succLevel) { HILOGE("Invalid dataLevel"); - return -1; + ErrorHandler::Throw(env, EINVAL); + return; } auto ret = DoSetSecurityLabel(srcPath, dataLevel); if (!ret.IsSuccess()) { HILOGE("Set securitylabel failed"); - return -1; + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; } - - return 0; } } // namespace ANI diff --git a/interfaces/kits/js/src/mod_securitylabel/ani/securitylabel_ani.h b/interfaces/kits/js/src/mod_securitylabel/ani/securitylabel_ani.h index b99fa8bc1647b5e18c19a7272a0f627fa2149a25..025d65308f449d033b6d132ac9d0ac2845407103 100644 --- a/interfaces/kits/js/src/mod_securitylabel/ani/securitylabel_ani.h +++ b/interfaces/kits/js/src/mod_securitylabel/ani/securitylabel_ani.h @@ -25,8 +25,7 @@ namespace ANI { class SecurityLabelAni final { public: - static ani_int SetSecurityLabelSync( - ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_string level); + static void SetSecurityLabelSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_string level); }; } // namespace ANI