diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index f12c564b2047596887bfb10de8de7cc37a27becb..11ad29a3fdcc62613fb3193cb1ead3551e3a1cf6 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -624,10 +624,11 @@ group("build_kits_js") { group("ani_file_api") { deps = [ - ":ani_fs_class", - ":ani_hash_class", - ":ani_securitylabel_class", - ":ohos_file_fs_abc", + ":ani_file_environment", + ":ani_file_fs", + ":ani_file_hash", + ":ani_file_securitylabel", + ":ani_file_statvfs", ] } @@ -658,7 +659,7 @@ config("ani_config") { ] } -ohos_shared_library("ani_fs_class") { +ohos_shared_library("ani_file_fs") { public_configs = [ ":ani_config" ] include_dirs = [ "include/ipc", @@ -682,6 +683,7 @@ ohos_shared_library("ani_fs_class") { "src/mod_fs/properties/copy_listener", ] sources = [ + "src/common/ani_helper/ani_signature.cpp", "src/common/ani_helper/error_handler.cpp", "src/common/ani_helper/type_converter.cpp", "src/common/file_helper/fd_guard.cpp", @@ -807,6 +809,7 @@ ohos_shared_library("ani_fs_class") { "ipc:ipc_core", "libuv:uv", "runtime_core:ani", + "runtime_core:ani_helpers", "runtime_core:libarkruntime", "samgr:samgr_proxy", ] @@ -852,13 +855,14 @@ ohos_prebuilt_etc("ohos_file_fs_abc_etc") { deps = [ ":ohos_file_fs_abc" ] } -ohos_shared_library("ani_hash_class") { +ohos_shared_library("ani_file_hash") { public_configs = [ ":ani_config" ] include_dirs = [ "src/mod_hash", "src/mod_hash/ani", ] sources = [ + "src/common/ani_helper/ani_signature.cpp", "src/common/ani_helper/error_handler.cpp", "src/common/ani_helper/type_converter.cpp", "src/common/file_helper/fd_guard.cpp", @@ -880,6 +884,7 @@ ohos_shared_library("ani_hash_class") { "libuv:uv", "openssl:libcrypto_shared", "runtime_core:ani", + "runtime_core:ani_helpers", "runtime_core:libarkruntime", ] use_exceptions = true @@ -922,13 +927,14 @@ ohos_prebuilt_etc("ohos_file_hash_abc_etc") { deps = [ ":ohos_file_hash_abc" ] } -ohos_shared_library("ani_securitylabel_class") { +ohos_shared_library("ani_file_securitylabel") { public_configs = [ ":ani_config" ] include_dirs = [ "src/mod_securitylabel/ani", "src/mod_securitylabel", ] sources = [ + "src/common/ani_helper/ani_signature.cpp", "src/common/ani_helper/error_handler.cpp", "src/common/ani_helper/type_converter.cpp", "src/common/file_helper/fd_guard.cpp", @@ -948,6 +954,7 @@ ohos_shared_library("ani_securitylabel_class") { "hilog:libhilog", "libuv:uv", "runtime_core:ani", + "runtime_core:ani_helpers", "runtime_core:libarkruntime", ] use_exceptions = true @@ -989,3 +996,140 @@ ohos_prebuilt_etc("ohos_file_securityLabel_abc_etc") { part_name = "file_api" deps = [ ":ohos_file_securityLabel_abc" ] } + +ohos_shared_library("ani_file_environment") { + public_configs = [ ":ani_config" ] + include_dirs = [ + "src/mod_environment/ani", + "src/mod_environment", + ] + sources = [ + "src/common/ani_helper/ani_signature.cpp", + "src/common/ani_helper/error_handler.cpp", + "src/common/ani_helper/type_converter.cpp", + "src/common/file_helper/fd_guard.cpp", + "src/mod_environment/ani/bind_function_class.cpp", + "src/mod_environment/ani/environment_ani.cpp", + "src/mod_environment/environment_core.cpp", + "src/mod_fs/fs_utils.cpp", + ] + + deps = [ + ":ohos_file_environment_abc_etc", + "${file_api_path}/interfaces/kits/rust:rust_file", + "${utils_path}/filemgmt_libfs:filemgmt_libfs", + "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", + ] + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "libuv:uv", + "openssl:libcrypto_shared", + "os_account:os_account_innerkits", + "runtime_core:ani", + "runtime_core:ani_helpers", + "runtime_core:libarkruntime", + ] + use_exceptions = true + + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + output_extension = "so" + subsystem_name = "filemanagement" + part_name = "file_api" +} + +generate_static_abc("ohos_file_environment_abc") { + base_url = "./src/mod_environment/ani/ets" + files = [ "./src/mod_environment/ani/ets/@ohos.file.environment.ets" ] + is_boot_abc = "True" + device_dst_file = "/system/framework/ohos_file_environment_abc.abc" +} + +ohos_prebuilt_etc("ohos_file_environment_abc_etc") { + source = "$target_out_dir/ohos_file_environment_abc.abc" + module_install_dir = "framework" + subsystem_name = "filemanagement" + part_name = "file_api" + deps = [ ":ohos_file_environment_abc" ] +} + +ohos_shared_library("ani_file_statvfs") { + public_configs = [ ":ani_config" ] + include_dirs = [ + "src/mod_statvfs/ani", + "src/mod_statvfs", + ] + sources = [ + "src/common/ani_helper/ani_signature.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", + "src/mod_statvfs/ani/bind_function_class.cpp", + "src/mod_statvfs/ani/statvfs_ani.cpp", + "src/mod_statvfs/statvfs_core.cpp", + ] + + deps = [ + ":ohos_file_statvfs_abc_etc", + "${file_api_path}/interfaces/kits/rust:rust_file", + "${utils_path}/filemgmt_libfs:filemgmt_libfs", + "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", + ] + external_deps = [ + "hilog:libhilog", + "libuv:uv", + "runtime_core:ani", + "runtime_core:ani_helpers", + "runtime_core:libarkruntime", + ] + use_exceptions = true + cflags = [ + "-fvisibility=hidden", + "-fdata-sections", + "-ffunction-sections", + "-Oz", + ] + cflags_cc = [ + "-fvisibility-inlines-hidden", + "-Oz", + ] + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + output_extension = "so" + subsystem_name = "filemanagement" + part_name = "file_api" +} + +generate_static_abc("ohos_file_statvfs_abc") { + base_url = "./src/mod_statvfs/ani/ets" + files = [ "./src/mod_statvfs/ani/ets/@ohos.file.statvfs.ets" ] + is_boot_abc = "True" + device_dst_file = "/system/framework/ohos_file_statvfs_abc.abc" +} + +ohos_prebuilt_etc("ohos_file_statvfs_abc_etc") { + source = "$target_out_dir/ohos_file_statvfs_abc.abc" + module_install_dir = "framework" + subsystem_name = "filemanagement" + part_name = "file_api" + deps = [ ":ohos_file_statvfs_abc" ] +} diff --git a/interfaces/kits/js/src/common/ani_helper/ani_helper.h b/interfaces/kits/js/src/common/ani_helper/ani_helper.h index 11083ff86ac94f879ef36b9e50d3234c5beda0fd..654b3b9c257bbbd4e10098f58da8f7071344adda 100644 --- a/interfaces/kits/js/src/common/ani_helper/ani_helper.h +++ b/interfaces/kits/js/src/common/ani_helper/ani_helper.h @@ -22,6 +22,7 @@ #include +#include "ani_signature.h" #include "event_handler.h" #include "event_runner.h" #include "file_utils.h" @@ -30,6 +31,7 @@ namespace OHOS::FileManagement::ModuleFileIO::ANI { using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; static thread_local shared_ptr mainHandler; @@ -107,8 +109,10 @@ public: if (isUndefined) { return { true, nullopt }; } + static const string longValueSig = Builder::BuildSignatureDescriptor({}, BasicTypes::longType); ani_long value; - status = env->Object_CallMethodByName_Long(static_cast(property), "longValue", ":J", &value); + status = env->Object_CallMethodByName_Long( + static_cast(property), "longValue", longValueSig.c_str(), &value); if (status != ANI_OK) { return { false, nullopt }; } @@ -147,8 +151,7 @@ public: return env; } - ani_option interopEnabled { "--interop=enable", nullptr }; - ani_options aniArgs { 1, &interopEnabled }; + ani_options aniArgs { 0, nullptr }; auto status = vm->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &env); if (status != ANI_OK) { status = vm->GetEnv(ANI_VERSION_1, &env); @@ -156,10 +159,7 @@ public: HILOGE("vm GetEnv, err: %{private}d", status); return nullptr; } - - return env; } - return env; } diff --git a/interfaces/kits/js/src/common/ani_helper/ani_signature.cpp b/interfaces/kits/js/src/common/ani_helper/ani_signature.cpp new file mode 100644 index 0000000000000000000000000000000000000000..87ee3dfe32090a7ff846dd0c7092f252b133542d --- /dev/null +++ b/interfaces/kits/js/src/common/ani_helper/ani_signature.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ani_signature.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature { +// BasicTypes +const Type BasicTypes::undefinedType = Builder::BuildUndefined(); +const Type BasicTypes::nullType = Builder::BuildNull(); +const Type BasicTypes::booleanType = Builder::BuildBoolean(); +const Type BasicTypes::byteType = Builder::BuildByte(); +const Type BasicTypes::charType = Builder::BuildChar(); +const Type BasicTypes::shortType = Builder::BuildShort(); +const Type BasicTypes::intType = Builder::BuildInt(); +const Type BasicTypes::longType = Builder::BuildLong(); +const Type BasicTypes::floatType = Builder::BuildFloat(); +const Type BasicTypes::doubleType = Builder::BuildDouble(); +// BoxedTypes::Boolean +const Type BoxedTypes::Boolean::classType = Builder::BuildClass("std.core.Boolean"); +const string BoxedTypes::Boolean::classDesc = BoxedTypes::Double::classType.Descriptor(); +const string BoxedTypes::Boolean::unboxedDesc = "unboxed"; +const string BoxedTypes::Boolean::unboxedSig = Builder::BuildSignatureDescriptor({}, BasicTypes::booleanType); +// BoxedTypes::Int +const Type BoxedTypes::Int::classType = Builder::BuildClass("std.core.Int"); +const string BoxedTypes::Int::classDesc = BoxedTypes::Int::classType.Descriptor(); +// BoxedTypes::Double +const Type BoxedTypes::Double::classType = Builder::BuildClass("std.core.Double"); +const string BoxedTypes::Double::classDesc = BoxedTypes::Double::classType.Descriptor(); +// BaseType +const string BaseType::ctorDesc = Builder::BuildConstructorName(); +const string BaseType::ctorSig0 = Builder::BuildSignatureDescriptor({}); +// BuiltInTypes::Object +const Type BuiltInTypes::Object::classType = Builder::BuildClass("std.core.Object"); +const string BuiltInTypes::Object::classDesc = BuiltInTypes::Object::classType.Descriptor(); +// BuiltInTypes::String +const Type BuiltInTypes::String::classType = Builder::BuildClass("std.core.String"); +const string BuiltInTypes::String::classDesc = BuiltInTypes::String::classType.Descriptor(); +// BuiltInTypes::Array +const Type BuiltInTypes::Array::classType = Builder::BuildClass("escompat.Array"); +const string BuiltInTypes::Array::classDesc = BuiltInTypes::Array::classType.Descriptor(); +const string BuiltInTypes::Array::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::intType }); +const string BuiltInTypes::Array::getterDesc = "$_get"; +const string BuiltInTypes::Array::setterDesc = "$_set"; +const string BuiltInTypes::Array::objectGetterSig = + Builder::BuildSignatureDescriptor({ BasicTypes::intType }, BuiltInTypes::objectType); +const string BuiltInTypes::Array::objectSetterSig = + Builder::BuildSignatureDescriptor({ BasicTypes::intType, BuiltInTypes::objectType }); +// BuiltInTypes::ArrayBuffer +const Type BuiltInTypes::ArrayBuffer::classType = Builder::BuildClass("escompat.ArrayBuffer"); +const string BuiltInTypes::ArrayBuffer::classDesc = BuiltInTypes::ArrayBuffer::classType.Descriptor(); +// BuiltInTypes::BigInt +const Type BuiltInTypes::BigInt::classType = Builder::BuildClass("escompat.BigInt"); +const string BuiltInTypes::BigInt::classDesc = BuiltInTypes::BigInt::classType.Descriptor(); +const string BuiltInTypes::BigInt::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::doubleType }); +// BuiltInTypes::BusinessError +const Type BuiltInTypes::BusinessError::classType = Builder::BuildClass("@ohos.base.BusinessError"); +const string BuiltInTypes::BusinessError::classDesc = BuiltInTypes::BusinessError::classType.Descriptor(); +// FS::ConflictFilesInner +const Type FS::ConflictFilesInner::classType = Builder::BuildClass("@ohos.file.fs.ConflictFilesInner"); +const string FS::ConflictFilesInner::classDesc = FS::ConflictFilesInner::classType.Descriptor(); +const string FS::ConflictFilesInner::ctorSig = + Builder::BuildSignatureDescriptor({ BuiltInTypes::stringType, BuiltInTypes::stringType }); +// FS::FileInner +const Type FS::FileInner::classType = Builder::BuildClass("@ohos.file.fs.fileIo.FileInner"); +const string FS::FileInner::classDesc = FS::FileInner::classType.Descriptor(); +const string FS::FileInner::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::ProgressInner +const Type FS::ProgressInner::classType = Builder::BuildClass("@ohos.file.fs.fileIo.ProgressInner"); +const string FS::ProgressInner::classDesc = FS::ProgressInner::classType.Descriptor(); +const string FS::ProgressInner::ctorSig = + Builder::BuildSignatureDescriptor({ BasicTypes::doubleType, BasicTypes::doubleType }); +// FS::RandomAccessFileInner +const Type FS::RandomAccessFileInner::classType = Builder::BuildClass("@ohos.file.fs.fileIo.RandomAccessFileInner"); +const string FS::RandomAccessFileInner::classDesc = FS::RandomAccessFileInner::classType.Descriptor(); +const string FS::RandomAccessFileInner::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::ReaderIteratorInner +const Type FS::ReaderIteratorInner::classType = Builder::BuildClass("@ohos.file.fs.fileIo.ReaderIteratorInner"); +const string FS::ReaderIteratorInner::classDesc = FS::ReaderIteratorInner::classType.Descriptor(); +const string FS::ReaderIteratorInner::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::ReaderIteratorResultInner +const Type FS::ReaderIteratorResultInner::classType = + Builder::BuildClass("@ohos.file.fs.fileIo.ReaderIteratorResultInner"); +const string FS::ReaderIteratorResultInner::classDesc = FS::ReaderIteratorResultInner::classType.Descriptor(); +const string FS::ReaderIteratorResultInner::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::StatInner +const Type FS::StatInner::classType = Builder::BuildClass("@ohos.file.fs.fileIo.StatInner"); +const string FS::StatInner::classDesc = FS::StatInner::classType.Descriptor(); +const string FS::StatInner::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::StreamInner +const Type FS::StreamInner::classType = Builder::BuildClass("@ohos.file.fs.fileIo.StreamInner"); +const string FS::StreamInner::classDesc = FS::StreamInner::classType.Descriptor(); +const string FS::StreamInner::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::TaskSignal +const Type FS::TaskSignal::classType = Builder::BuildClass("@ohos.file.fs.fileIo.TaskSignal"); +const string FS::TaskSignal::classDesc = FS::TaskSignal::classType.Descriptor(); +const string FS::TaskSignal::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::WatcherInner +const Type FS::WatcherInner::classType = Builder::BuildClass("@ohos.file.fs.fileIo.WatcherInner"); +const string FS::WatcherInner::classDesc = FS::WatcherInner::classType.Descriptor(); +const string FS::WatcherInner::ctorSig = Builder::BuildSignatureDescriptor({ BasicTypes::longType }); +// FS::WatchEventInner +const Type FS::WatchEventInner::classType = Builder::BuildClass("@ohos.file.fs.WatchEventInner"); +const string FS::WatchEventInner::classDesc = FS::WatchEventInner::classType.Descriptor(); +const string FS::WatchEventInner::ctorSig = + Builder::BuildSignatureDescriptor({ BuiltInTypes::stringType, BasicTypes::doubleType, BasicTypes::doubleType }); +// Impl::EnvironmentImpl +const Type Impl::EnvironmentImpl::classType = Builder::BuildClass("@ohos.file.environment.EnvironmentImpl"); +const string Impl::EnvironmentImpl::classDesc = Impl::EnvironmentImpl::classType.Descriptor(); +// Impl::FileIoImpl +const Type Impl::FileIoImpl::classType = Builder::BuildClass("@ohos.file.fs.FileIoImpl"); +const string Impl::FileIoImpl::classDesc = Impl::FileIoImpl::classType.Descriptor(); +// Impl::HashImpl +const Type Impl::HashImpl::classType = Builder::BuildClass("@ohos.file.hash.HashImpl"); +const string Impl::HashImpl::classDesc = Impl::HashImpl::classType.Descriptor(); +// Impl::SecurityLabelImpl +const Type Impl::SecurityLabelImpl::classType = Builder::BuildClass("@ohos.file.securityLabel.SecurityLabelImpl"); +const string Impl::SecurityLabelImpl::classDesc = Impl::SecurityLabelImpl::classType.Descriptor(); +// Impl::StatvfsImpl +const Type Impl::StatvfsImpl::classType = Builder::BuildClass("@ohos.file.statvfs.StatvfsImpl"); +const string Impl::StatvfsImpl::classDesc = Impl::StatvfsImpl::classType.Descriptor(); + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature \ No newline at end of file diff --git a/interfaces/kits/js/src/common/ani_helper/ani_signature.h b/interfaces/kits/js/src/common/ani_helper/ani_signature.h new file mode 100644 index 0000000000000000000000000000000000000000..c05470dc09694c075f7eb1eded41dadb52f42070 --- /dev/null +++ b/interfaces/kits/js/src/common/ani_helper/ani_signature.h @@ -0,0 +1,212 @@ +/* + * 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 INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_ANI_SIGNATURE_H +#define INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_ANI_SIGNATURE_H + +#pragma once + +#include +#include + +namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature { +using namespace std; +using namespace arkts::ani_signature; + +struct BasicTypes { + static const Type undefinedType; + static const Type nullType; + static const Type booleanType; + static const Type byteType; + static const Type charType; + static const Type shortType; + static const Type intType; + static const Type longType; + static const Type floatType; + static const Type doubleType; +}; + +struct BaseType { + static const string ctorDesc; + static const string ctorSig0; +}; + +namespace BoxedTypes { + +struct Boolean : public BaseType { + static const Type classType; + static const string classDesc; + static const string unboxedDesc; + static const string unboxedSig; +}; + +struct Int : public BaseType { + static const Type classType; + static const string classDesc; +}; + +struct Double : public BaseType { + static const Type classType; + static const string classDesc; +}; + +} // namespace BoxedTypes + +namespace BuiltInTypes { + +struct Object : public BaseType { + static const Type classType; + static const string classDesc; +}; + +inline const Type &objectType = BuiltInTypes::Object::classType; + +struct String : public BaseType { + static const Type classType; + static const string classDesc; +}; + +inline const Type &stringType = BuiltInTypes::String::classType; + +struct Array : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; + static const string getterDesc; + static const string setterDesc; + static const string objectGetterSig; + static const string objectSetterSig; +}; + +struct ArrayBuffer : public BaseType { + static const Type classType; + static const string classDesc; +}; + +struct BigInt : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct BusinessError : public BaseType { + static const Type classType; + static const string classDesc; +}; + +}; // namespace BuiltInTypes + +namespace FS { + +struct ConflictFilesInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct FileInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct ProgressInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct RandomAccessFileInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct ReaderIteratorInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct ReaderIteratorResultInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct StatInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct StreamInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct TaskSignal : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct WatcherInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +struct WatchEventInner : public BaseType { + static const Type classType; + static const string classDesc; + static const string ctorSig; +}; + +} // namespace FS + +namespace Impl { + +struct EnvironmentImpl : public BaseType { + static const Type classType; + static const string classDesc; +}; + +struct FileIoImpl : public BaseType { + static const Type classType; + static const string classDesc; +}; + +struct HashImpl : public BaseType { + static const Type classType; + static const string classDesc; +}; + +struct SecurityLabelImpl : public BaseType { + static const Type classType; + static const string classDesc; +}; + +struct StatvfsImpl : public BaseType { + static const Type classType; + static const string classDesc; +}; + +} // namespace Impl + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature + +#endif // INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_ANI_SIGNATURE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/ani_helper/error_handler.cpp b/interfaces/kits/js/src/common/ani_helper/error_handler.cpp index d300bb8c2d06ceb9e7d2727f5784a0c43ab88ee6..c56a4dc0d26aaacdb2c42811d411d47d4341421d 100644 --- a/interfaces/kits/js/src/common/ani_helper/error_handler.cpp +++ b/interfaces/kits/js/src/common/ani_helper/error_handler.cpp @@ -20,8 +20,8 @@ namespace OHOS::FileManagement::ModuleFileIO::ANI { ani_status ErrorHandler::Throw( ani_env *env, int32_t code, const std::string &errMsg, const std::optional &errData) { - const char *className = "L@ohos/base/BusinessError;"; - return Throw(env, className, code, errMsg, errData); + auto classDesc = BuiltInTypes::BusinessError::classDesc.c_str(); + return Throw(env, classDesc, code, errMsg, errData); } } // 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 index cab44cc1ca34c21392affa2009f29f8d98d43103..2138f075dbe1e380b84568929445c692e9b99298 100644 --- a/interfaces/kits/js/src/common/ani_helper/error_handler.h +++ b/interfaces/kits/js/src/common/ani_helper/error_handler.h @@ -20,11 +20,13 @@ #include #include #include "ani_helper.h" +#include "ani_signature.h" #include "filemgmt_libhilog.h" #include "fs_error.h" #include "type_converter.h" namespace OHOS::FileManagement::ModuleFileIO::ANI { +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; class ErrorHandler { public: @@ -90,8 +92,10 @@ private: return { ANI_NOT_FOUND, nullptr }; } + auto ctorDesc = BaseType::ctorDesc.c_str(); + auto ctorSig = BaseType::ctorSig0.c_str(); ani_method ctor; - if (ANI_OK != env->Class_FindMethod(cls, "", ":V", &ctor)) { + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { HILOGE("Cannot find constructor for class '%{private}s'", className); return { ANI_NOT_FOUND, nullptr }; } 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 bfa635e0e40742fc0906f8935608de95e5cb2c81..2e995d41efb31f07f13c69934656af66eaf60f5c 100644 --- a/interfaces/kits/js/src/common/ani_helper/type_converter.cpp +++ b/interfaces/kits/js/src/common/ani_helper/type_converter.cpp @@ -21,10 +21,12 @@ #include +#include "ani_signature.h" #include "file_utils.h" #include "filemgmt_libhilog.h" namespace OHOS::FileManagement::ModuleFileIO::ANI { +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; std::tuple TypeConverter::ToUTF8String(ani_env *env, const ani_string &path) { @@ -155,9 +157,10 @@ static std::tuple ParseFd(ani_env *env, const ani_object &pathOrF { ani_boolean isFd = false; - ani_class DoubleClass; - env->FindClass("Lstd/core/Double;", &DoubleClass); - env->Object_InstanceOf(pathOrFd, DoubleClass, &isFd); + auto doubleClassDesc = BoxedTypes::Double::classDesc.c_str(); + ani_class doubleClass; + env->FindClass(doubleClassDesc, &doubleClass); + env->Object_InstanceOf(pathOrFd, doubleClass, &isFd); if (isFd) { ani_double doubleValue; if (ANI_OK != env->Object_CallMethodByName_Double(pathOrFd, "doubleValue", nullptr, &doubleValue)) { @@ -168,9 +171,10 @@ static std::tuple ParseFd(ani_env *env, const ani_object &pathOrF return { true, fd }; } - ani_class IntClass; - env->FindClass("Lstd/core/Int;", &IntClass); - env->Object_InstanceOf(pathOrFd, IntClass, &isFd); + auto intClassDesc = BoxedTypes::Int::classDesc.c_str(); + ani_class intClass; + env->FindClass(intClassDesc, &intClass); + env->Object_InstanceOf(pathOrFd, intClass, &isFd); if (isFd) { ani_int fd; if (ANI_OK != env->Object_CallMethodByName_Int(pathOrFd, "intValue", nullptr, &fd)) { @@ -190,8 +194,9 @@ std::tuple TypeConverter::ToFileInfo(ani_env *env, const ani_obj return { false, FileInfo { false, {}, {} } }; } + auto stringClassDesc = BuiltInTypes::String::classDesc.c_str(); ani_class stringClass; - env->FindClass("Lstd/core/String;", &stringClass); + env->FindClass(stringClassDesc, &stringClass); ani_boolean isPath = false; env->Object_InstanceOf(pathOrFd, stringClass, &isPath); @@ -246,12 +251,13 @@ std::tuple TypeConverter::ToAniStringList( return { false, nullptr }; } + auto classDesc = BuiltInTypes::String::classDesc.c_str(); ani_array_ref result = nullptr; - ani_class itemCls = nullptr; - if (env->FindClass("Lstd/core/String;", &itemCls) != ANI_OK) { + ani_class cls = nullptr; + if (env->FindClass(classDesc, &cls) != ANI_OK) { return { false, result }; } - if (env->Array_New_Ref(itemCls, length, nullptr, &result) != ANI_OK) { + if (env->Array_New_Ref(cls, length, nullptr, &result) != ANI_OK) { return { false, result }; } for (uint32_t i = 0; i < length; i++) { diff --git a/interfaces/kits/js/src/mod_environment/ani/bind_function_class.cpp b/interfaces/kits/js/src/mod_environment/ani/bind_function_class.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dfda601139d779543f2420a01958bbc6a024dcdd --- /dev/null +++ b/interfaces/kits/js/src/mod_environment/ani/bind_function_class.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "ani_signature.h" +#include "bind_function.h" +#include "environment_ani.h" + +using namespace OHOS::FileManagement::ModuleFileIO::ANI; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +static ani_status BindStaticMethods(ani_env *env) +{ + auto classDesc = Impl::EnvironmentImpl::classDesc.c_str(); + std::array methods = { + ani_native_function { + "getStorageDataDirSync", nullptr, reinterpret_cast(EnvironmentAni::GetStorageDataDirSync) }, + ani_native_function { + "getUserDataDirSync", nullptr, reinterpret_cast(EnvironmentAni::GetUserDataDirSync) }, + ani_native_function { + "getUserDownloadDirSync", nullptr, reinterpret_cast(EnvironmentAni::GetUserDownloadDirSync) }, + ani_native_function { + "getUserDesktopDirSync", nullptr, reinterpret_cast(EnvironmentAni::GetUserDesktopDirSync) }, + ani_native_function { + "getUserDocumentDirSync", nullptr, reinterpret_cast(EnvironmentAni::GetUserDocumentDirSync) }, + ani_native_function { + "getExternalStorageDirSync", nullptr, reinterpret_cast(EnvironmentAni::GetExternalStorageDirSync) }, + ani_native_function { + "getUserHomeDirSync", nullptr, reinterpret_cast(EnvironmentAni::GetUserHomeDirSync) }, + }; + return BindClass(env, classDesc, 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 environment!"); + return status; + }; + + *result = ANI_VERSION_1; + return ANI_OK; +} diff --git a/interfaces/kits/js/src/mod_environment/ani/environment_ani.cpp b/interfaces/kits/js/src/mod_environment/ani/environment_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da95c9a2a437b7ead16e513c40be8817e756e2cb --- /dev/null +++ b/interfaces/kits/js/src/mod_environment/ani/environment_ani.cpp @@ -0,0 +1,175 @@ +/* + * 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 "environment_ani.h" + +#include "environment_core.h" +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleEnvironment; + +ani_string EnvironmentAni::GetStorageDataDirSync(ani_env *env, [[maybe_unused]] ani_class clazz) +{ + auto ret = DoGetStorageDataDir(); + if (!ret.IsSuccess()) { + HILOGE("Get storage data dir failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return nullptr; + } + + string res = ret.GetData().value(); + auto [succ, result] = TypeConverter::ToAniString(env, res); + if (!succ) { + HILOGE("Create ani_string error"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + return result; +} + +ani_string EnvironmentAni::GetUserDataDirSync(ani_env *env, [[maybe_unused]] ani_class clazz) +{ + auto ret = DoGetUserDataDir(); + if (!ret.IsSuccess()) { + HILOGE("Get user data dir failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return nullptr; + } + + string res = ret.GetData().value(); + auto [succ, result] = TypeConverter::ToAniString(env, res); + if (!succ) { + HILOGE("Create ani_string error"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + return result; +} + +ani_string EnvironmentAni::GetUserDownloadDirSync(ani_env *env, [[maybe_unused]] ani_class clazz) +{ + auto ret = DoGetUserDownloadDir(); + if (!ret.IsSuccess()) { + HILOGE("Get user download dir failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return nullptr; + } + + string res = ret.GetData().value(); + auto [succ, result] = TypeConverter::ToAniString(env, res); + if (!succ) { + HILOGE("Create ani_string error"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + return result; +} + +ani_string EnvironmentAni::GetUserDesktopDirSync(ani_env *env, [[maybe_unused]] ani_class clazz) +{ + auto ret = DoGetUserDesktopDir(); + if (!ret.IsSuccess()) { + HILOGE("Get user desktop dir failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return nullptr; + } + + string res = ret.GetData().value(); + auto [succ, result] = TypeConverter::ToAniString(env, res); + if (!succ) { + HILOGE("Create ani_string error"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + return result; +} + +ani_string EnvironmentAni::GetUserDocumentDirSync(ani_env *env, [[maybe_unused]] ani_class clazz) +{ + auto ret = DoGetUserDocumentDir(); + if (!ret.IsSuccess()) { + HILOGE("Get user document dir failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return nullptr; + } + + string res = ret.GetData().value(); + auto [succ, result] = TypeConverter::ToAniString(env, res); + if (!succ) { + HILOGE("Create ani_string error"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + return result; +} + +ani_string EnvironmentAni::GetExternalStorageDirSync(ani_env *env, [[maybe_unused]] ani_class clazz) +{ + auto ret = DoGetExternalStorageDir(); + if (!ret.IsSuccess()) { + HILOGE("Get external storage dir failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return nullptr; + } + + string res = ret.GetData().value(); + auto [succ, result] = TypeConverter::ToAniString(env, res); + if (!succ) { + HILOGE("Create ani_string error"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + return result; +} + +ani_string EnvironmentAni::GetUserHomeDirSync(ani_env *env, [[maybe_unused]] ani_class clazz) +{ + auto ret = DoGetUserHomeDir(); + if (!ret.IsSuccess()) { + HILOGE("Get user home dir failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return nullptr; + } + + string res = ret.GetData().value(); + auto [succ, result] = TypeConverter::ToAniString(env, res); + if (!succ) { + HILOGE("Create ani_string error"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + return result; +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_environment/ani/environment_ani.h b/interfaces/kits/js/src/mod_environment/ani/environment_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..d14a78c69e7e04672328d47ab1dad8b0b69afce2 --- /dev/null +++ b/interfaces/kits/js/src/mod_environment/ani/environment_ani.h @@ -0,0 +1,42 @@ +/* + * 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 INTERFACES_KITS_JS_SRC_MOD_ENVIRONMENT_ANI_ENVIRONMENT_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_ENVIRONMENT_ANI_ENVIRONMENT_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class EnvironmentAni final { +public: + static ani_string GetStorageDataDirSync(ani_env *env, [[maybe_unused]] ani_class clazz); + static ani_string GetUserDataDirSync(ani_env *env, [[maybe_unused]] ani_class clazz); + static ani_string GetUserDownloadDirSync(ani_env *env, [[maybe_unused]] ani_class clazz); + static ani_string GetUserDesktopDirSync(ani_env *env, [[maybe_unused]] ani_class clazz); + static ani_string GetUserDocumentDirSync(ani_env *env, [[maybe_unused]] ani_class clazz); + static ani_string GetExternalStorageDirSync(ani_env *env, [[maybe_unused]] ani_class clazz); + static ani_string GetUserHomeDirSync(ani_env *env, [[maybe_unused]] ani_class clazz); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_ENVIRONMENT_ANI_ENVIRONMENT_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_environment/ani/ets/@ohos.file.environment.ets b/interfaces/kits/js/src/mod_environment/ani/ets/@ohos.file.environment.ets new file mode 100644 index 0000000000000000000000000000000000000000..9ccc27495eee2897f9289fcad6b5e1222704da59 --- /dev/null +++ b/interfaces/kits/js/src/mod_environment/ani/ets/@ohos.file.environment.ets @@ -0,0 +1,103 @@ +/* + * 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'; + +namespace Environment { + export function getStorageDataDir(): Promise { + return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute(EnvironmentImpl.getStorageDataDirSync); + promise.then((ret: NullishType): void => { + let result = ret as string; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); + } + + export function getStorageDataDir(callback: AsyncCallback): void { + let promise = taskpool.execute(EnvironmentImpl.getStorageDataDirSync); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as string; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, ""); + }); + } + + export function getUserDataDir(): Promise { + return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute(EnvironmentImpl.getUserDataDirSync); + promise.then((ret: NullishType): void => { + let result = ret as string; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); + } + export function getUserDataDir(callback: AsyncCallback): void { + let promise = taskpool.execute(EnvironmentImpl.getUserDataDirSync); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + let result = ret as string; + callback(e, result); + }).catch((e: BusinessError): void => { + callback(e, ""); + }); + } + + export function getUserDownloadDir(): string { + return EnvironmentImpl.getUserDownloadDirSync(); + } + + export function getUserDesktopDir(): string { + return EnvironmentImpl.getUserDesktopDirSync(); + } + + export function getUserDocumentDir(): string { + return EnvironmentImpl.getUserDocumentDirSync(); + } + + export function getExternalStorageDir(): string { + return EnvironmentImpl.getExternalStorageDirSync(); + } + + export function getUserHomeDir(): string { + return EnvironmentImpl.getUserHomeDirSync(); + } + +} + +export default Environment; + +class EnvironmentImpl { + + static { + loadLibrary("ani_file_environment"); + } + + static native getStorageDataDirSync(): string; + static native getUserDataDirSync(): string; + static native getUserDownloadDirSync(): string; + static native getUserDesktopDirSync(): string; + static native getUserDocumentDirSync(): string; + static native getExternalStorageDirSync(): string; + static native getUserHomeDirSync(): string; +} \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_environment/environment_core.cpp b/interfaces/kits/js/src/mod_environment/environment_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f13e9b942752fe1ed5ae7b7259bb51e6277a28c0 --- /dev/null +++ b/interfaces/kits/js/src/mod_environment/environment_core.cpp @@ -0,0 +1,204 @@ +/* + * 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 "environment_core.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "account_error_no.h" +#include "filemgmt_libhilog.h" +#include "ipc_skeleton.h" +#include "os_account_manager.h" +#include "parameter.h" +#include "tokenid_kit.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleEnvironment { +namespace { +const std::string STORAGE_DATA_PATH = "/data"; +const std::string PC_STORAGE_PATH = "/storage/Users/"; +const std::string EXTERNAL_STORAGE_PATH = "/storage/External"; +const std::string USER_APP_DATA_PATH = "/appdata"; +const std::string READ_WRITE_DOWNLOAD_PERMISSION = "ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY"; +const std::string READ_WRITE_DESKTOP_PERMISSION = "ohos.permission.READ_WRITE_DESKTOP_DIRECTORY"; +const std::string READ_WRITE_DOCUMENTS_PERMISSION = "ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY"; +const std::string FILE_ACCESS_MANAGER_PERMISSION = "ohos.permission.FILE_ACCESS_MANAGER"; +const std::string DOWNLOAD_PATH = "/Download"; +const std::string DESKTOP_PATH = "/Desktop"; +const std::string DOCUMENTS_PATH = "/Documents"; +const std::string DEFAULT_USERNAME = "currentUser"; +const char *FILE_MANAMER_FULL_MOUNT_ENABLE_PARAMETER = "const.filemanager.full_mount.enable"; +static bool IsSystemApp() +{ + uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID(); + return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId); +} + +static bool CheckCallingPermission(const std::string &permission) +{ + Security::AccessToken::AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + int res = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission); + if (res != Security::AccessToken::PermissionState::PERMISSION_GRANTED) { + HILOGE("ModuleUserDirectory::CheckCallingPermission have no fileAccess permission"); + return false; + } + return true; +} + +static std::string GetUserName() +{ + std::string userName; + ErrCode errCode = OHOS::AccountSA::OsAccountManager::GetOsAccountShortName(userName); + if (errCode != ERR_OK || userName.empty()) { + HILOGE("Get userName Failed"); + } + userName = DEFAULT_USERNAME; + return userName; +} + +static std::string GetPublicPath(const std::string &directoryName) +{ + return PC_STORAGE_PATH + GetUserName() + directoryName; +} + +static bool CheckFileManagerFullMountEnable() +{ + char value[] = "false"; + int retSystem = GetParameter(FILE_MANAMER_FULL_MOUNT_ENABLE_PARAMETER, "false", value, sizeof(value)); + if (retSystem > 0 && !std::strcmp(value, "true")) { + return true; + } + HILOGE("Not supporting all mounts"); + return false; +} + +static int CheckInvalidAccess(const std::string &permission) +{ + if (!CheckFileManagerFullMountEnable()) { + HILOGE("Capability not supported"); + return E_DEVICENOTSUPPORT; + } + if (permission == FILE_ACCESS_MANAGER_PERMISSION) { + if (!IsSystemApp()) { + return E_PERMISSION_SYS; + } + } + if (!CheckCallingPermission(permission)) { + HILOGE("No Permission"); + return E_PERMISSION; + } + return ERRNO_NOERR; +} +} + +FsResult DoGetStorageDataDir() +{ + if (!IsSystemApp()) { + return FsResult::Error(E_PERMISSION_SYS); + } + return FsResult::Success(std::move(STORAGE_DATA_PATH)); +} + +int GetUserId() +{ + return 0; +} + +FsResult DoGetUserDataDir() +{ + if (!IsSystemApp()) { + return FsResult::Error(E_PERMISSION_SYS); + } + + auto userDataPath = std::make_shared(); + (*userDataPath).append("/storage/media/").append(std::to_string(GetUserId())).append("/local"); + return FsResult::Success(std::move(*userDataPath)); +} + +FsResult DoGetUserDownloadDir() +{ + if (!CheckFileManagerFullMountEnable()) { + HILOGE("Capability not supported"); + return FsResult::Error(E_DEVICENOTSUPPORT); + } + + static std::string downloadPath = GetPublicPath(DOWNLOAD_PATH); + if (downloadPath.empty()) { + HILOGE("Unknown error"); + return FsResult::Error(E_UNKNOWN_ERROR); + } + return FsResult::Success(std::move(downloadPath)); +} + +FsResult DoGetUserDesktopDir() +{ + if (!CheckFileManagerFullMountEnable()) { + HILOGE("Capability not supported"); + return FsResult::Error(E_DEVICENOTSUPPORT); + } + + static std::string desktopPath = GetPublicPath(DESKTOP_PATH); + if (desktopPath.empty()) { + HILOGE("Unknown error"); + return FsResult::Error(E_UNKNOWN_ERROR); + } + return FsResult::Success(std::move(desktopPath)); +} + +FsResult DoGetUserDocumentDir() +{ + if (!CheckFileManagerFullMountEnable()) { + HILOGE("Capability not supported"); + return FsResult::Error(E_DEVICENOTSUPPORT); + } + + static std::string documentsPath = GetPublicPath(DOCUMENTS_PATH); + if (documentsPath.empty()) { + HILOGE("Unknown error"); + return FsResult::Error(E_UNKNOWN_ERROR); + } + return FsResult::Success(std::move(documentsPath)); +} + +FsResult DoGetExternalStorageDir() +{ + auto res = CheckInvalidAccess(FILE_ACCESS_MANAGER_PERMISSION); + if (res) { + return FsResult::Error(res); + } + return FsResult::Success(std::move(EXTERNAL_STORAGE_PATH)); +} + +FsResult DoGetUserHomeDir() +{ + auto res = CheckInvalidAccess(FILE_ACCESS_MANAGER_PERMISSION); + if (res) { + return FsResult::Error(res); + } + + static std::string userName = GetUserName(); + if (userName.empty()) { + HILOGE("Unknown error"); + return FsResult::Error(E_UNKNOWN_ERROR); + } + std::string result = PC_STORAGE_PATH + userName; + return FsResult::Success(std::move(result)); +} +} // namespace ModuleEnvironment +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_environment/environment_core.h b/interfaces/kits/js/src/mod_environment/environment_core.h new file mode 100644 index 0000000000000000000000000000000000000000..0962c1f4ab1b3c2e576d44d67071e87613951dba --- /dev/null +++ b/interfaces/kits/js/src/mod_environment/environment_core.h @@ -0,0 +1,36 @@ +/* + * 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 INTERFACES_KITS_JS_SRC_MOD_ENVIRONMENT_ENVIRONMENT_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_ENVIRONMENT_ENVIRONMENT_CORE_H + +#include "filemgmt_libfs.h" +#include "fs_utils.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleEnvironment { +using namespace ModuleFileIO; +FsResult DoGetStorageDataDir(); +FsResult DoGetUserDataDir(); +FsResult DoGetUserDownloadDir(); +FsResult DoGetUserDesktopDir(); +FsResult DoGetUserDocumentDir(); +FsResult DoGetExternalStorageDir(); +FsResult DoGetUserHomeDir(); +} // namespace ModuleEnvironment +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_ENVIRONMENT_ENVIRONMENT_CORE_H \ No newline at end of file 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 6f1f375328c4fb8c0cb00e795943389d99d4fa14..10e86d4ba2a557e12d3ea4ee639121eadafe26ba 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 @@ -18,6 +18,7 @@ #include #include "access_ani.h" +#include "ani_signature.h" #include "bind_function.h" #include "close_ani.h" #include "connectdfs_ani.h" @@ -61,10 +62,11 @@ #include "xattr_ani.h" using namespace OHOS::FileManagement::ModuleFileIO::ANI; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; static ani_status BindRafFileMethods(ani_env *env) { - static const char *className = "L@ohos/file/fs/RandomAccessFileInner;"; + auto classDesc = FS::RandomAccessFileInner::classDesc.c_str(); std::array methods = { ani_native_function { @@ -72,26 +74,29 @@ static ani_status BindRafFileMethods(ani_env *env) ani_native_function { "close", nullptr, reinterpret_cast(RandomAccessFileAni::Close) }, ani_native_function { "writeSync0", nullptr, reinterpret_cast(RandomAccessFileAni::WriteSync) }, ani_native_function { "readSync0", nullptr, reinterpret_cast(RandomAccessFileAni::ReadSync) }, + ani_native_function { "getReadStream", nullptr, reinterpret_cast(RandomAccessFileAni::GetReadStream) }, + ani_native_function { + "getWriteStream", nullptr, reinterpret_cast(RandomAccessFileAni::GetWriteStream) }, }; - return BindClass(env, className, methods); + return BindClass(env, classDesc, methods); } static ani_status BindWatcherClassMethods(ani_env *env) { - static const char *className = "L@ohos/file/fs/WatcherInner;"; + auto classDesc = FS::WatcherInner::classDesc.c_str(); std::array methods = { ani_native_function { "start", nullptr, reinterpret_cast(FsWatcherAni::Start) }, ani_native_function { "stop", nullptr, reinterpret_cast(FsWatcherAni::Stop) }, }; - return BindClass(env, className, methods); + return BindClass(env, classDesc, methods); } static ani_status BindFileMethods(ani_env *env) { - static const char *className = "L@ohos/file/fs/FileInner;"; + auto classDesc = FS::FileInner::classDesc.c_str(); std::array methods = { ani_native_function { "getParent", nullptr, reinterpret_cast(FileAni::GetParent) }, @@ -100,40 +105,40 @@ static ani_status BindFileMethods(ani_env *env) ani_native_function { "unlock", nullptr, reinterpret_cast(FileAni::UnLock) }, }; - return BindClass(env, className, methods); + return BindClass(env, classDesc, methods); } static ani_status BindReaderIteratorMethods(ani_env *env) { - static const char *className = "L@ohos/file/fs/ReaderIteratorInner;"; + auto classDesc = FS::ReaderIteratorInner::classDesc.c_str(); std::array methods = { ani_native_function { "next", nullptr, reinterpret_cast(ReaderIteratorAni::Next) }, }; - return BindClass(env, className, methods); + return BindClass(env, classDesc, methods); } static ani_status BindStatClassMethods(ani_env *env) { - static const char *className = "L@ohos/file/fs/StatInner;"; + auto classDesc = FS::StatInner::classDesc.c_str(); std::array methods = { - ani_native_function { "isBlockDevice", ":Z", reinterpret_cast(StatAni::IsBlockDevice) }, - ani_native_function { "isCharacterDevice", ":Z", reinterpret_cast(StatAni::IsCharacterDevice) }, - ani_native_function { "isDirectory", ":Z", reinterpret_cast(StatAni::IsDirectory) }, - ani_native_function { "isFIFO", ":Z", reinterpret_cast(StatAni::IsFIFO) }, - ani_native_function { "isFile", ":Z", reinterpret_cast(StatAni::IsFile) }, - ani_native_function { "isSocket", ":Z", reinterpret_cast(StatAni::IsSocket) }, - ani_native_function { "isSymbolicLink", ":Z", reinterpret_cast(StatAni::IsSymbolicLink) }, + ani_native_function { "isBlockDevice", nullptr, reinterpret_cast(StatAni::IsBlockDevice) }, + ani_native_function { "isCharacterDevice", nullptr, reinterpret_cast(StatAni::IsCharacterDevice) }, + ani_native_function { "isDirectory", nullptr, reinterpret_cast(StatAni::IsDirectory) }, + ani_native_function { "isFIFO", nullptr, reinterpret_cast(StatAni::IsFIFO) }, + ani_native_function { "isFile", nullptr, reinterpret_cast(StatAni::IsFile) }, + ani_native_function { "isSocket", nullptr, reinterpret_cast(StatAni::IsSocket) }, + ani_native_function { "isSymbolicLink", nullptr, reinterpret_cast(StatAni::IsSymbolicLink) }, }; - return BindClass(env, className, methods); + return BindClass(env, classDesc, methods); } static ani_status BindStreamMethods(ani_env *env) { - static const char *className = "L@ohos/file/fs/StreamInner;"; + auto classDesc = FS::StreamInner::classDesc.c_str(); std::array methods = { ani_native_function { "closeSync", nullptr, reinterpret_cast(StreamAni::Close) }, @@ -143,24 +148,28 @@ static ani_status BindStreamMethods(ani_env *env) ani_native_function { "seek", nullptr, reinterpret_cast(StreamAni::Seek) }, }; - return BindClass(env, className, methods); + return BindClass(env, classDesc, methods); } static ani_status BindTaskSignalClassMethods(ani_env *env) { - static const char *className = "L@ohos/file/fs/TaskSignal;"; + auto classDesc = FS::TaskSignal::classDesc.c_str(); std::array methods = { - ani_native_function { "cancel", ":V", reinterpret_cast(TaskSignalAni::Cancel) }, + ani_native_function { "cancel", nullptr, reinterpret_cast(TaskSignalAni::Cancel) }, ani_native_function { "onCancelNative", nullptr, reinterpret_cast(TaskSignalAni::OnCancel) }, }; - return BindClass(env, className, methods); + return BindClass(env, classDesc, methods); } +const static string mkdirCtorSig0 = Builder::BuildSignatureDescriptor({ BuiltInTypes::stringType }); +const static string mkdirCtorSig1 = + Builder::BuildSignatureDescriptor({ BuiltInTypes::stringType, BasicTypes::booleanType }); + static ani_status BindStaticMethods(ani_env *env) { - static const char *className = "L@ohos/file/fs/FileIoImpl;"; + auto classDesc = Impl::FileIoImpl::classDesc.c_str(); std::array methods = { ani_native_function { "closeSync", nullptr, reinterpret_cast(CloseAni::CloseSync) }, @@ -184,8 +193,8 @@ static ani_status BindStaticMethods(ani_env *env) ani_native_function { "listFileSync", nullptr, reinterpret_cast(ListFileAni::ListFileSync) }, ani_native_function { "lseekSync", nullptr, reinterpret_cast(LseekAni::LseekSync) }, ani_native_function { "lstatSync", nullptr, reinterpret_cast(LstatAni::LstatSync) }, - 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 { "mkdirSync", mkdirCtorSig0.c_str(), reinterpret_cast(MkdirkAni::MkdirSync0) }, + ani_native_function { "mkdirSync", mkdirCtorSig1.c_str(), reinterpret_cast(MkdirkAni::MkdirSync1) }, ani_native_function { "mkdtempSync", nullptr, reinterpret_cast(MkdtempAni::MkdtempSync) }, ani_native_function { "movedirSync", nullptr, reinterpret_cast(MoveDirAni::MoveDirSync) }, ani_native_function { "moveFileSync", nullptr, reinterpret_cast(MoveAni::MoveFileSync) }, @@ -203,7 +212,7 @@ static ani_status BindStaticMethods(ani_env *env) ani_native_function { "utimes", nullptr, reinterpret_cast(UtimesAni::Utimes) }, ani_native_function { "writeSync", nullptr, reinterpret_cast(WriteAni::WriteSync) }, }; - return BindClass(env, className, methods); + return BindClass(env, classDesc, methods); } ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) 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 index c43cc008cb540a14348e36bb9cd2c3af60062c32..e93183d838f3c8df2b3416fad471eba2d390fd49 100644 --- 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 @@ -28,31 +28,18 @@ namespace fileIo { export const NOFOLLOW = 0o400000; export const SYNC = 0o4010000; } -} 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); - }); - } + let promise = taskpool.execute((path: string, mode?: AccessModeType): boolean => { + return FileIoImpl.doAccessSync(path, mode); + }, path, mode); + promise.then((ret: NullishType): void => { + let result = ret as boolean; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); }); } @@ -72,7 +59,9 @@ function access(path: string, callback: AsyncCallback): void { 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); + let promise = taskpool.execute((path: string, mode: AccessModeType, flag: AccessFlagType): boolean => { + return FileIoImpl.doAccessSync(path, mode, flag); + }, path, mode, flag); promise.then((ret: NullishType): void => { let result = ret as boolean; resolve(result); @@ -145,7 +134,9 @@ function getxattrSync(path: string, key: string): string { function getxattr(path: string, key: string): Promise { return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void): void => { - let promise = taskpool.execute(FileIoImpl.getxattrSync, path, key); + let promise = taskpool.execute((path: string, key: string): string => { + return FileIoImpl.getxattrSync(path, key); + }, path, key); promise.then((ret: NullishType): void => { let result = ret as string; resolve(result); @@ -164,25 +155,15 @@ function copyDirSync(src: string, dest: string, mode?: number): void { } function copyDir(src: string, dest: string, mode?: number): Promise { - return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError>) => void): void => { - if (mode === undefined) { - let promise = taskpool.execute((src: string, dest: string): undefined => - FileIoImpl.copyDirSync(src, dest), src, dest); - promise.then((ret: NullishType): void => { - resolve(undefined); - }).catch((e: BusinessError>): void => { - reject(e); - }); - } else { - let promise = taskpool.execute((src: string, dest: string, mode: number): undefined => - FileIoImpl.copyDirSync(src, dest, mode), src, dest, mode); - promise.then((ret: NullishType): void => { - resolve(undefined); - }).catch((e: BusinessError>): void => { - reject(e); - }); - } - + return new Promise((resolve: (result: undefined) => void, + reject: (e: BusinessError>) => void): void => { + let promise = taskpool.execute((src: string, dest: string, mode?: number): undefined => + FileIoImpl.copyDirSync(src, dest, mode), src, dest, mode); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError>): void => { + reject(e); + }); }); } @@ -330,25 +311,14 @@ function moveDirSync(src: string, dest: string, mode?: number): void { function moveDir(src: string, dest: string, mode?: number): Promise { return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError>) => void): void => { - if (mode === undefined) { - let promise = taskpool.execute((src: string, dest: string): undefined => { - return FileIoImpl.movedirSync(src, dest); - }, src, dest); - promise.then((ret: NullishType): void => { - resolve(undefined); - }).catch((e: BusinessError>): void => { - reject(e); - }); - } else { - let promise = taskpool.execute((src: string, dest: string, mode: number): undefined => { - return FileIoImpl.movedirSync(src, dest, mode); - }, src, dest, mode); - promise.then((ret: NullishType): void => { - resolve(undefined); - }).catch((e: BusinessError>): void => { - reject(e); - }); - } + let promise = taskpool.execute((src: string, dest: string, mode?: number): undefined => { + return FileIoImpl.movedirSync(src, dest, mode); + }, src, dest, mode); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError>): void => { + reject(e); + }); }) } @@ -407,7 +377,9 @@ function mkdtempSync(prefix: string): string { function mkdtemp(prefix: string): Promise { return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void): void => { - let promise = taskpool.execute(FileIoImpl.mkdtempSync, prefix); + let promise = taskpool.execute((prefix: string): string => { + return FileIoImpl.mkdtempSync(prefix); + }, prefix); promise.then((ret: NullishType): void => { let result = ret as string; resolve(result); @@ -418,7 +390,9 @@ function mkdtemp(prefix: string): Promise { } function mkdtemp(prefix: string, callback: AsyncCallback): void { - let promise = taskpool.execute(FileIoImpl.mkdtempSync, prefix); + let promise = taskpool.execute((prefix: string): string => { + return FileIoImpl.mkdtempSync(prefix); + }, prefix); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -435,25 +409,14 @@ function moveFileSync(src: string, dest: string, mode?: number): void { function moveFile(src: string, dest: string, mode?: number): Promise { return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { - if (mode === undefined) { - let promise = taskpool.execute((src: string, dest: string): undefined => { - return FileIoImpl.moveFileSync(src, dest); - }, src, dest); - promise.then((ret: NullishType): void => { - resolve(undefined); - }).catch((e: BusinessError): void => { - reject(e); - }); - } else { - let promise = taskpool.execute((src: string, dest: string, mode: number): undefined => { - return FileIoImpl.moveFileSync(src, dest, mode); - }, src, dest, mode); - promise.then((ret: NullishType): void => { - resolve(undefined); - }).catch((e: BusinessError): void => { - reject(e); - }); - } + let promise = taskpool.execute((src: string, dest: string, mode?: number): undefined => { + return FileIoImpl.moveFileSync(src, dest, mode); + }, src, dest, mode); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); }); } @@ -489,28 +452,22 @@ function openSync(path: string, mode?: number): File { 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); - }); - } + let promise = taskpool.execute((path: String, mode?: number): File => { + return FileIoImpl.openSync(path, mode); + },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); + let promise = taskpool.execute((path: String, mode: number): File => { + return FileIoImpl.openSync(path, mode); + }, path, mode); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -523,7 +480,9 @@ function open(path: String, mode: number, callback: AsyncCallback): } function open(path: String, callback: AsyncCallback): void { - let promise = taskpool.execute(FileIoImpl.openSync, path); + let promise = taskpool.execute((path: String): File => { + return FileIoImpl.openSync(path); + }, path); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -541,29 +500,23 @@ function writeSync(fd: number, buffer: string | ArrayBuffer, options?: WriteOpti 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); - }); - } + let promise = taskpool.execute((fd: number, buffer: string | ArrayBuffer, options?: WriteOptions): number => { + return FileIoImpl.writeSync(fd, buffer, options); + }, 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); + let promise = taskpool.execute((fd: number, buffer: string | ArrayBuffer, options: WriteOptions): number => { + return FileIoImpl.writeSync(fd, buffer, options); + }, fd, buffer, options); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -575,7 +528,9 @@ function write(fd: number, buffer: string | ArrayBuffer, options: WriteOptions, } function write(fd: number, buffer: string | ArrayBuffer, callback: AsyncCallback): void { - let promise = taskpool.execute(FileIoImpl.writeSync, fd, buffer); + let promise = taskpool.execute((fd: number, buffer: string | ArrayBuffer): number => { + return FileIoImpl.writeSync(fd, buffer); + }, fd, buffer); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -592,32 +547,22 @@ function readSync(fd: number, buffer: ArrayBuffer, options?: ReadOptions): numbe 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); - }); - } + 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); + let promise = taskpool.execute((fd: number, buffer: ArrayBuffer): number => { + return FileIoImpl.readSync(fd, buffer); + }, fd, buffer); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -629,7 +574,9 @@ function read(fd: number, buffer: ArrayBuffer, callback: AsyncCallback): void { - let promise = taskpool.execute(FileIoImpl.readSync, fd, buffer, options); + let promise = taskpool.execute((fd: number, buffer: ArrayBuffer, options: ReadOptions): number => { + return FileIoImpl.readSync(fd, buffer, options); + }, fd, buffer, options); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -645,29 +592,24 @@ function readLinesSync(filePath: string, options?: Options): ReaderIterator { } function readLines(filePath: string, options?: Options): Promise { - return new Promise((resolve: (result: ReaderIterator) => void, reject: (e: BusinessError) => void) => { - if (options === undefined) { - let promise = taskpool.execute(FileIoImpl.readlinesSync, filePath); - promise.then((ret: NullishType): void => { - let it = ret as ReaderIterator; - resolve(it); - }).catch((e: BusinessError): void => { - reject(e); - }); - } else { - let promise = taskpool.execute(FileIoImpl.readlinesSync, filePath, options); - promise.then((ret: NullishType): void => { - let it = ret as ReaderIterator; - resolve(it); - }).catch((e: BusinessError): void => { - reject(e); - }); - } + return new Promise((resolve: (result: ReaderIterator) => void, + reject: (e: BusinessError) => void) => { + let promise = taskpool.execute((filePath: string, options?: Options): ReaderIterator => { + return FileIoImpl.readlinesSync(filePath, options); + }, filePath, options); + promise.then((ret: NullishType): void => { + let it = ret as ReaderIterator; + resolve(it); + }).catch((e: BusinessError): void => { + reject(e); + }); }); } function readLines(filePath: string, callback: AsyncCallback): void { - let promise = taskpool.execute(FileIoImpl.readlinesSync, filePath); + let promise = taskpool.execute((filePath: string): ReaderIterator => { + return FileIoImpl.readlinesSync(filePath); + }, filePath); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -680,7 +622,9 @@ function readLines(filePath: string, callback: AsyncCallback): v } function readLines(filePath: string, options: Options, callback: AsyncCallback): void { - let promise = taskpool.execute(FileIoImpl.readlinesSync, filePath, options); + let promise = taskpool.execute((filePath: string, options: Options): ReaderIterator => { + return FileIoImpl.readlinesSync(filePath, options); + }, filePath, options); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -725,25 +669,14 @@ function truncateSync(file: string | number, len?: number): void { function truncate(file: string | number, len?: number): Promise { return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { - if (len === undefined) { - let promise = taskpool.execute((file: string | number): undefined => { - return FileIoImpl.truncateSync(file); - }, file); - promise.then((ret: NullishType): void => { - resolve(undefined); - }).catch((e: BusinessError): void => { - reject(e); - }); - } else { - let promise = taskpool.execute((file: string | number, len: number): undefined => { - return FileIoImpl.truncateSync(file, len); - }, file, len); - promise.then((ret: NullishType): void => { - resolve(undefined); - }).catch((e: BusinessError): void => { - reject(e); - }); - } + let promise = taskpool.execute((file: string | number, len?: number): undefined => { + return FileIoImpl.truncateSync(file, len); + }, file, len); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); }) } @@ -802,28 +735,22 @@ function unlink(path: string, callback: AsyncCallback): void { 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); - }); - } + let promise = taskpool.execute((filePath: string, options?: ReadTextOptions): string => { + return FileIoImpl.readTextSync(filePath, options); + }, 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); + let promise = taskpool.execute((filePath: string): string => { + return FileIoImpl.readTextSync(filePath); + }, filePath); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -835,7 +762,9 @@ function readText(filePath: string, callback: AsyncCallback): void { } function readText(filePath: string, options: ReadTextOptions, callback: AsyncCallback): void { - let promise = taskpool.execute(FileIoImpl.readTextSync, filePath, options); + let promise = taskpool.execute((filePath: string, options: ReadTextOptions): string => { + return FileIoImpl.readTextSync(filePath, options); + }, filePath, options); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -852,28 +781,22 @@ function readTextSync(filePath: string, options?: ReadTextOptions): string { 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); - }); - } + let promise = taskpool.execute((path: string, options?: ListFileOptions): string[] => { + return FileIoImpl.listFileSync(path, options); + }, 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); + let promise = taskpool.execute((path: string): string[] => { + return FileIoImpl.listFileSync(path); + }, path); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -885,7 +808,9 @@ function listFile(path: string, callback: AsyncCallback): void { } function listFile(path: string, options: ListFileOptions, callback: AsyncCallback): void { - let promise = taskpool.execute(FileIoImpl.listFileSync, path, options); + let promise = taskpool.execute((path: string, options: ListFileOptions): string[] => { + return FileIoImpl.listFileSync(path, options); + }, path, options); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -910,7 +835,9 @@ function statSync(file: string | number): Stat { function stat(file: string | number): Promise { return new Promise((resolve: (result: Stat) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(FileIoImpl.statSync, file); + let promise = taskpool.execute((file: string | number): Stat => { + return FileIoImpl.statSync(file); + }, file); promise.then((ret: NullishType): void => { let r = ret as Stat; resolve(r); @@ -921,7 +848,9 @@ function stat(file: string | number): Promise { } function stat(file: string | number, callback: AsyncCallback): void { - let p = taskpool.execute(FileIoImpl.statSync, file); + let p = taskpool.execute((file: string | number): Stat => { + return FileIoImpl.statSync(file); + }, file); p.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -949,6 +878,19 @@ function fsync(fd: number): Promise { }); } +function fsync(fd: number, callback: AsyncCallback): void { + let promise = taskpool.execute((fd: number): undefined => { + return FileIoImpl.fsyncSync(fd); + }, fd); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + function symlinkSync(target: string, srcPath: string): void { return FileIoImpl.symlinkSync(target, srcPath); } @@ -982,6 +924,20 @@ function rename(oldPath: string, newPath: string): Promise { }); }); } + +function rename(oldPath: string, newPath: string, callback: AsyncCallback): void { + let promise = taskpool.execute((oldPath: string, newPath: string): undefined => { + return FileIoImpl.renameSync(oldPath, newPath); + }, oldPath, newPath); + promise.then((ret: NullishType): void => { + let e = new BusinessError(); + e.code = 0; + callback(e, undefined); + }).catch((e: BusinessError): void => { + callback(e, undefined); + }); +} + function createRandomAccessFileSync(file: string | File, mode?: number, options?: RandomAccessFileOptions): RandomAccessFile { return FileIoImpl.createRandomAccessFileSync(file, mode, options); @@ -991,27 +947,10 @@ function createRandomAccessFile(file: string | File, mode?: number, options?: RandomAccessFileOptions): Promise { return new Promise((resolve: (result: RandomAccessFile) => void, reject: (e: BusinessError) => void) => { - if (mode === undefined) { - let promise = taskpool.execute(FileIoImpl.createRandomAccessFileSync, file); - promise.then((ret: NullishType): void => { - let raffile = ret as RandomAccessFileInner; - resolve(raffile); - }).catch((e: BusinessError): void => { - reject(e); - }); - return; - } - if (mode !== undefined && options === undefined) { - let promise = taskpool.execute(FileIoImpl.createRandomAccessFileSync, file, mode); - promise.then((ret: NullishType): void => { - let raffile = ret as RandomAccessFileInner; - resolve(raffile); - }).catch((e: BusinessError): void => { - reject(e); - }); - return; - } - let promise = taskpool.execute(FileIoImpl.createRandomAccessFileSync, file, mode, options); + let promise = taskpool.execute((file: string | File, mode?: number, + options?: RandomAccessFileOptions): RandomAccessFile => { + return FileIoImpl.createRandomAccessFileSync(file, mode, options); + }, file, mode, options); promise.then((ret: NullishType): void => { let raffile = ret as RandomAccessFileInner; resolve(raffile); @@ -1020,9 +959,12 @@ function createRandomAccessFile(file: string | File, mode?: number, }); }); } + function fdopenStream(fd: number, mode: string): Promise { return new Promise((resolve: (result: Stream) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(FileIoImpl.fdopenStreamSync, fd, mode); + let promise = taskpool.execute((fd: number, mode: string): Stream => { + return FileIoImpl.fdopenStreamSync(fd, mode); + }, fd, mode); promise.then((ret: NullishType): void => { let stream = ret as Stream; resolve(stream); @@ -1049,7 +991,9 @@ function setxattr(path: string, key: string, value: string): Promise { } function createRandomAccessFile(file: string | File, callback: AsyncCallback): void { - let promise = taskpool.execute(FileIoImpl.createRandomAccessFileSync, file); + let promise = taskpool.execute((file: string | File): RandomAccessFile => { + return FileIoImpl.createRandomAccessFileSync(file); + }, file); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -1063,7 +1007,9 @@ function createRandomAccessFile(file: string | File, callback: AsyncCallback): void { - let promise = taskpool.execute(FileIoImpl.createRandomAccessFileSync, file, mode); + let promise = taskpool.execute((file: string | File, mode: number): RandomAccessFile => { + return FileIoImpl.createRandomAccessFileSync(file, mode); + }, file, mode); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -1076,7 +1022,9 @@ function createRandomAccessFile(file: string | File, mode: number, } function fdopenStream(fd: number, mode: string, callback: AsyncCallback): void { - let promise = taskpool.execute(FileIoImpl.fdopenStreamSync, fd, mode); + let promise = taskpool.execute((fd: number, mode: string): Stream => { + return FileIoImpl.fdopenStreamSync(fd, mode); + }, fd, mode); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -1094,7 +1042,9 @@ function fdopenStreamSync(fd: number, mode: string): Stream { function createStream(path: string, mode: string): Promise { return new Promise((resolve: (result: Stream) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(FileIoImpl.createStreamSync, path, mode); + let promise = taskpool.execute((path: string, mode: string): Stream => { + return FileIoImpl.createStreamSync(path, mode); + }, path, mode); promise.then((ret: NullishType): void => { let stream = ret as Stream; resolve(stream); @@ -1105,7 +1055,9 @@ function createStream(path: string, mode: string): Promise { } function createStream(path: string, mode: string, callback: AsyncCallback): void { - let promise = taskpool.execute(FileIoImpl.createStreamSync, path, mode); + let promise = taskpool.execute((path: string, mode: string): Stream => { + return FileIoImpl.createStreamSync(path, mode); + }, path, mode); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -1156,7 +1108,9 @@ function lstatSync(path: string): Stat { function lstat(path: string): Promise { return new Promise((resolve: (result: Stat) => void, reject: (e: BusinessError) => void) => { - let promise = taskpool.execute(FileIoImpl.lstatSync, path); + let promise = taskpool.execute((path: string): Stat => { + return FileIoImpl.lstatSync(path); + }, path); promise.then((ret: NullishType): void => { if (ret === null || ret === undefined) { let e = new BusinessError(); @@ -1173,7 +1127,9 @@ function lstat(path: string): Promise { } function lstat(path: string, callback: AsyncCallback): void { - let p = taskpool.execute(FileIoImpl.lstatSync, path); + let p = taskpool.execute((path: string): Stat => { + return FileIoImpl.lstatSync(path); + }, path); p.then((ret: NullishType): void => { let e = new BusinessError(); if (ret === null || ret === undefined) { @@ -1191,45 +1147,25 @@ function lstat(path: string, callback: AsyncCallback): void { } function copyFile(src: string | number, dest: string | number, mode?: number): Promise { return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { - if (mode === undefined) { - let promise = taskpool.execute((src: string | number, dest: string | number): undefined => - FileIoImpl.copyFileSync(src, dest), src, dest); - promise.then((ret: NullishType): void => { - resolve(undefined); - }).catch((e: BusinessError): void => { - reject(e); - }); - } else { - let promise = taskpool.execute((src: string | number, dest: string | number, mode: number): undefined => - FileIoImpl.copyFileSync(src, dest, mode), src, dest, mode); - promise.then((ret: NullishType): void => { - resolve(undefined); - }).catch((e: BusinessError): void => { - reject(e); - }); - } + let promise = taskpool.execute((src: string | number, dest: string | number, mode?: number): undefined => + FileIoImpl.copyFileSync(src, dest, mode), src, dest, mode); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); }); } function copy(srcUri: string, destUri: string, options?: CopyOptions): Promise { return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { - if (options === undefined) { - let promise = taskpool.execute((srcUri: string, destUri: string): undefined => - FileIoImpl.copySync(srcUri, destUri), srcUri, destUri); - promise.then((ret: NullishType): void => { - resolve(undefined); - }).catch((e: BusinessError): void => { - reject(e); - }); - } else { - let promise = taskpool.execute((srcUri: string, destUri: string, options: CopyOptions): undefined => - FileIoImpl.copySync(srcUri, destUri, options), srcUri, destUri, options); - promise.then((ret: NullishType): void => { - resolve(undefined); - }).catch((e: BusinessError): void => { - reject(e); - }); - } + let promise = taskpool.execute((srcUri: string, destUri: string, options?: CopyOptions): undefined => + FileIoImpl.copySync(srcUri, destUri, options), srcUri, destUri, options); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); }); } @@ -1285,21 +1221,6 @@ function lseek(fd: number, offset: number, whence?: WhenceType): number { return FileIoImpl.lseekSync(fd, offset, whence); } -export interface ConflictFiles { - srcFile: string; - destFile: string; -} - -class ConflictFilesInner implements ConflictFiles { - srcFile: string = ""; - destFile: string = ""; - - constructor(src: string, dest: string) { - this.srcFile = src; - this.destFile = dest; - } -} - export interface Filter { suffix?: Array; displayName?: Array; @@ -1309,35 +1230,6 @@ export interface Filter { 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 Options { - encoding?: string; -} - -export interface WriteOptions extends Options { - offset?: number; - length?: number; -} - -export interface RandomAccessFileOptions { - start?: number; - end?: number; -} - export interface Progress { processedSize: number; totalSize: number; @@ -1347,7 +1239,7 @@ export interface DfsListeners { onStatus(networkId: string, status: number): void; } -class ProgressInner implements Progress { +export class ProgressInner implements Progress { processedSize: number; totalSize: number; @@ -1382,14 +1274,14 @@ export interface CopyOptions { copySignal?: TaskSignal; } -enum AccessModeType { +export enum AccessModeType { EXIST = 0, WRITE = 2, READ = 4, READ_WRITE = 6, } -enum AccessFlagType { +export enum AccessFlagType { LOCAL = 0, } @@ -1407,9 +1299,11 @@ export interface RandomAccessFile { read(buffer: ArrayBuffer, callback: AsyncCallback): void; read(buffer: ArrayBuffer, options: ReadOptions, callback: AsyncCallback): void; readSync(buffer: ArrayBuffer, options?: ReadOptions): number; + getReadStream(): ReadStream; + getWriteStream(): WriteStream; } -class RandomAccessFileInner implements RandomAccessFile { +export class RandomAccessFileInner implements RandomAccessFile { fd: number = -1; filePointer: number = -1; @@ -1440,28 +1334,22 @@ class RandomAccessFileInner implements RandomAccessFile { write(buffer: ArrayBuffer | string, options?: WriteOptions): Promise { return new Promise((resolve: (result: number) => void, reject: (e: BusinessError) => void) => { - if (options === undefined) { - let promise = taskpool.execute(this.writeSync, 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(this.writeSync, buffer, options); - promise.then((ret: NullishType): void => { - let result = ret as number - resolve(result); - }).catch((e: BusinessError): void => { - reject(e); - }); - } + let promise = taskpool.execute((buffer: ArrayBuffer | string, options?: WriteOptions): number => { + return this.writeSync(buffer, options); + }, buffer, options); + promise.then((ret: NullishType): void => { + let result = ret as number + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); }); } write(buffer: ArrayBuffer | string, options: WriteOptions, callback: AsyncCallback): void { - let promise = taskpool.execute(this.writeSync, buffer, options); + let promise = taskpool.execute((buffer: ArrayBuffer | string, options: WriteOptions): number => { + return this.writeSync(buffer, options); + }, buffer, options); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -1473,7 +1361,9 @@ class RandomAccessFileInner implements RandomAccessFile { } write(buffer: ArrayBuffer | string, callback: AsyncCallback): void { - let promise = taskpool.execute(this.writeSync, buffer); + let promise = taskpool.execute((buffer: ArrayBuffer | string): number => { + return this.writeSync(buffer); + }, buffer); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -1494,28 +1384,22 @@ class RandomAccessFileInner implements RandomAccessFile { read(buffer: ArrayBuffer, options?: ReadOptions): Promise { return new Promise((resolve: (result: number) => void, reject: (e: BusinessError) => void) => { - if (options === undefined) { - let promise = taskpool.execute(this.readSync, buffer); - promise.then((ret: NullishType): void => { - let result = ret as number; - resolve(result); - }).catch((e: BusinessError): void => { - reject(e); - }); - } else { - let promise = taskpool.execute(this.readSync, buffer, options); - promise.then((ret: NullishType): void => { - let result = ret as number; - resolve(result); - }).catch((e: BusinessError): void => { - reject(e); - }); - } + let promise = taskpool.execute((buffer: ArrayBuffer, options?: ReadOptions): number => { + return this.readSync(buffer, options); + }, buffer, options); + promise.then((ret: NullishType): void => { + let result = ret as number; + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); }); } read(buffer: ArrayBuffer, options: ReadOptions, callback: AsyncCallback): void { - let promise = taskpool.execute(this.readSync, buffer, options); + let promise = taskpool.execute((buffer: ArrayBuffer, options: ReadOptions): number => { + return this.readSync(buffer, options); + }, buffer, options); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -1527,7 +1411,9 @@ class RandomAccessFileInner implements RandomAccessFile { } read(buffer: ArrayBuffer, callback: AsyncCallback): void { - let promise = taskpool.execute(this.readSync, buffer); + let promise = taskpool.execute((buffer: ArrayBuffer): number => { + return this.readSync(buffer); + }, buffer); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -1537,6 +1423,9 @@ class RandomAccessFileInner implements RandomAccessFile { callback(e, 0); }); } + + native getReadStream(): ReadStream; + native getWriteStream(): WriteStream; } export interface File { @@ -1552,7 +1441,7 @@ export interface File { unlock(): void; } -class FileInner implements File { +export class FileInner implements File { fd: number = -1; path: String = ""; name: String = ""; @@ -1570,25 +1459,14 @@ class FileInner implements File { lock(exclusive?: boolean): Promise { return new Promise((resolve: (result: undefined) => void, reject: (e: BusinessError) => void): void => { - if (exclusive === undefined) { - let promise = taskpool.execute((): undefined => { - return this.lockSync(); - }); - promise.then((ret: NullishType): void => { - resolve(undefined); - }).catch((e: BusinessError): void => { - reject(e); - }); - } else { - let promise = taskpool.execute((exclusive: boolean): undefined => { - return this.lockSync(exclusive); - }, exclusive); - promise.then((ret: NullishType): void => { - resolve(undefined); - }).catch((e: BusinessError): void => { - reject(e); - }); - } + let promise = taskpool.execute((exclusive?: boolean): undefined => { + return this.lockSync(exclusive); + }, exclusive); + promise.then((ret: NullishType): void => { + resolve(undefined); + }).catch((e: BusinessError): void => { + reject(e); + }); }); } @@ -1623,17 +1501,13 @@ class FileInner implements File { } -enum LocationType { +export enum LocationType { LOCAL = 1, CLOUD = 2 } -export interface ReaderIteratorResult { - done: boolean; - value: string; -} -class ReaderIteratorResultInner implements ReaderIteratorResult { +export class ReaderIteratorResultInner implements ReaderIteratorResult { private nativePtr: long = 0; constructor(ptr: long) { @@ -1650,7 +1524,7 @@ export interface ReaderIterator { next(): ReaderIteratorResult; } -class ReaderIteratorInner implements ReaderIterator { +export class ReaderIteratorInner implements ReaderIterator { private nativePtr: long = 0; constructor(ptr: long) { @@ -1685,7 +1559,7 @@ export interface Stat { isSymbolicLink(): boolean; } -class StatInner implements Stat { +export class StatInner implements Stat { ino: bigint = 0n; mode: number; uid: number; @@ -1734,7 +1608,7 @@ export interface Stream { seek(offset: number, whence?: number): number; } -class StreamInner implements Stream { +export class StreamInner implements Stream { private nativePtr: long = 0; constructor(ptr: long) { @@ -1793,28 +1667,22 @@ class StreamInner implements Stream { write(buffer: ArrayBuffer | string, options?: WriteOptions): Promise { return new Promise((resolve: (result: number) => void, reject: (e: BusinessError) => void) => { - if (options === undefined) { - let promise = taskpool.execute(this.writeSync, buffer); - promise.then((ret: NullishType): void => { - let result = ret as number - resolve(result); - }).catch((e: BusinessError): void => { - reject(e); - }); - } else { - let promise = taskpool.execute(this.writeSync, buffer, options); - promise.then((ret: NullishType): void => { - let result = ret as number - resolve(result); - }).catch((e: BusinessError): void => { - reject(e); - }); - } + let promise = taskpool.execute((buffer: ArrayBuffer | string, options?: WriteOptions): number => { + return this.writeSync(buffer, options); + }, buffer, options); + promise.then((ret: NullishType): void => { + let result = ret as number + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); }); } write(buffer: ArrayBuffer | string, callback: AsyncCallback): void { - let promise = taskpool.execute(this.writeSync, buffer); + let promise = taskpool.execute((buffer: ArrayBuffer | string): number => { + return this.writeSync(buffer); + }, buffer); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -1826,7 +1694,9 @@ class StreamInner implements Stream { } write(buffer: ArrayBuffer | string, options: WriteOptions, callback: AsyncCallback): void { - let promise = taskpool.execute(this.writeSync, buffer, options); + let promise = taskpool.execute((buffer: ArrayBuffer | string, options: WriteOptions): number => { + return this.writeSync(buffer, options); + }, buffer, options); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -1841,28 +1711,22 @@ class StreamInner implements Stream { read(buffer: ArrayBuffer, options?: ReadOptions): Promise { return new Promise((resolve: (result: number) => void, reject: (e: BusinessError) => void) => { - if (options === undefined) { - let promise = taskpool.execute(this.readSync, buffer); - promise.then((ret: NullishType): void => { - let result = ret as number - resolve(result); - }).catch((e: BusinessError): void => { - reject(e); - }); - } else { - let promise = taskpool.execute(this.readSync, buffer, options); - promise.then((ret: NullishType): void => { - let result = ret as number - resolve(result); - }).catch((e: BusinessError): void => { - reject(e); - }); - } + let promise = taskpool.execute((buffer: ArrayBuffer, options?: ReadOptions): number => { + return this.readSync(buffer, options); + }, buffer, options); + promise.then((ret: NullishType): void => { + let result = ret as number + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); }); } read(buffer: ArrayBuffer, callback: AsyncCallback): void { - let promise = taskpool.execute(this.readSync, buffer); + let promise = taskpool.execute((buffer: ArrayBuffer): number => { + return this.readSync(buffer); + }, buffer); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -1874,7 +1738,9 @@ class StreamInner implements Stream { } read(buffer: ArrayBuffer, options: ReadOptions, callback: AsyncCallback): void { - let promise = taskpool.execute(this.readSync, buffer, options); + let promise = taskpool.execute((buffer: ArrayBuffer, options: ReadOptions): number => { + return this.readSync(buffer, options); + }, buffer, options); promise.then((ret: NullishType): void => { let e = new BusinessError(); e.code = 0; @@ -1889,16 +1755,6 @@ class StreamInner implements Stream { native seek(offset: number, whence?: number): number; } -export interface ReadStreamOptions { - start?: number; - end?: number; -} - -export interface WriteStreamOptions { - mode?: number; - start?: number; -} - export class ReadStream extends stream.Readable { private pathInner: string; private bytesReadInner: number; @@ -2058,7 +1914,8 @@ export class WriteStream extends stream.Writable { return modeStr; } } -enum WhenceType { + +export enum WhenceType { SEEK_SET = 0, SEEK_CUR = 1, SEEK_END = 2 @@ -2083,6 +1940,23 @@ class WatcherInner implements Watcher { native stop(): void; } +} // namespace fileIo + +export interface ConflictFiles { + srcFile: string; + destFile: string; +} + +class ConflictFilesInner implements ConflictFiles { + srcFile: string = ""; + destFile: string = ""; + + constructor(src: string, dest: string) { + this.srcFile = src; + this.destFile = dest; + } +} + export interface WatchEvent { fileName: string; event: number; @@ -2090,7 +1964,7 @@ export interface WatchEvent { } class WatchEventInner implements WatchEvent { - fileName: string; + fileName: string = ''; event: number; cookie: number; @@ -2104,17 +1978,86 @@ class WatchEventInner implements WatchEvent { export type WatchEventListener = (event: WatchEvent) => void; -class FileIoImpl { +export interface Options { + encoding?: string; +} + +export interface ReadOptions { + offset?: number; + length?: number; +} + +export interface ReadTextOptions extends ReadOptions { + encoding?: string; +} + +export interface WriteOptions extends Options { + offset?: number; + length?: number; +} + +export interface RandomAccessFileOptions { + start?: number; + end?: number; +} + +export interface ListFileOptions { + recursion?: boolean; + listNum?: number; + filter?: Filter; +} + +export interface WriteStreamOptions { + mode?: number; + start?: number; +} + +export interface ReadStreamOptions { + start?: number; + end?: number; +} + +export class ReadStreamOptionsInner implements ReadStreamOptions { + constructor() {} + start?: number; + end?: number; +} + +export class WriteStreamOptionsInner implements WriteStreamOptions { + constructor() {} + mode?: number; + start?: number; +} + +export interface ReaderIteratorResult { + done: boolean; + value: string; +} + +export interface Filter { + suffix?: Array; + displayName?: Array; + mimeType?: Array; + fileSizeOver?: number; + lastModifiedAfter?: number; + excludeMedia?: boolean; +} + +type TaskSignal = fileIo.TaskSignal; +type DfsListeners = fileIo.DfsListeners; + + +export class FileIoImpl { static { - loadLibrary("ani_fs_class"); + loadLibrary("ani_file_fs"); } - static native doAccessSync(path: string, mode?: AccessModeType, flag?: AccessFlagType): boolean; + static native doAccessSync(path: string, mode?: fileIo.AccessModeType, flag?: fileIo.AccessFlagType): boolean; - static native closeSync(file: number | File): void; + static native closeSync(file: number | fileIo.File): void; - static native copySync(srcUri: string, destUri: string, options?: CopyOptions): void; + static native copySync(srcUri: string, destUri: string, options?: fileIo.CopyOptions): void; static native connectDfs(networkId: string, listeners: DfsListeners): void; @@ -2128,19 +2071,19 @@ class FileIoImpl { static native getxattrSync(path: string, key: string): string; - static native createStreamSync(path: string, mode: string): Stream; - - static native createWatcherSync(path: string, events: number, listener: WatchEventListener): Watcher; - - static native fdopenStreamSync(fd: number, mode: string): Stream; + static native createStreamSync(path: string, mode: string): fileIo.Stream; - static native dup(fd: number): File; + static native createWatcherSync(path: string, events: number, listener: WatchEventListener): fileIo.Watcher; + + static native fdopenStreamSync(fd: number, mode: string): fileIo.Stream; + + static native dup(fd: number): fileIo.File; static native listFileSync(path: string, options?: ListFileOptions): string[]; - static native lstatSync(path: string): Stat; - - static native lseekSync(fd: number, offset: number, whence?: WhenceType): number; + static native lstatSync(path: string): fileIo.Stat; + + static native lseekSync(fd: number, offset: number, whence?: fileIo.WhenceType): number; static native mkdirSync(path: string): void; @@ -2152,10 +2095,10 @@ class FileIoImpl { static native moveFileSync(src: String, dest: String, mode?: number): void; - static native openSync(path: String, mode?: number): File; - - static native readlinesSync(filePath: string, options?: Options): ReaderIterator; + static native openSync(path: String, mode?: number): fileIo.File; + static native readlinesSync(filePath: string, options?: Options): fileIo.ReaderIterator; + static native readSync(fd: number, buffer: ArrayBuffer, options?: ReadOptions): number; static native readTextSync(filePath: string, options?: ReadTextOptions): string; @@ -2164,7 +2107,7 @@ class FileIoImpl { static native setxattrSync(path: string, key: string, value: string): void; - static native statSync(file: string | number): Stat; + static native statSync(file: string | number): fileIo.Stat; static native truncateSync(file: string | number, len?: number): void; @@ -2176,8 +2119,8 @@ class FileIoImpl { static native renameSync(oldPath: string, newPath: string): void; - static native createRandomAccessFileSync(file: string | File, mode?: number, - options?: RandomAccessFileOptions): RandomAccessFile; + static native createRandomAccessFileSync(file: string | fileIo.File, mode?: number, + options?: RandomAccessFileOptions): fileIo.RandomAccessFile; static native symlinkSync(target: string, srcPath: string): void; diff --git a/interfaces/kits/js/src/mod_fs/class_file/ani/file_wrapper.cpp b/interfaces/kits/js/src/mod_fs/class_file/ani/file_wrapper.cpp index 047f033a5bf60d0b18b3dd57db9e5bc21fb752ff..fcbf8aab9ea4ca9007252a1e0feec0a6971502cc 100644 --- a/interfaces/kits/js/src/mod_fs/class_file/ani/file_wrapper.cpp +++ b/interfaces/kits/js/src/mod_fs/class_file/ani/file_wrapper.cpp @@ -15,6 +15,7 @@ #include "file_wrapper.h" +#include "ani_signature.h" #include "error_handler.h" #include "filemgmt_libhilog.h" #include "fs_file.h" @@ -24,8 +25,9 @@ namespace OHOS { namespace FileManagement { namespace ModuleFileIO { namespace ANI { -using namespace OHOS::FileManagement::ModuleFileIO; using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; FsFile *FileWrapper::Unwrap(ani_env *env, ani_object object) { @@ -40,61 +42,79 @@ FsFile *FileWrapper::Unwrap(ani_env *env, ani_object object) return file; } -ani_object FileWrapper::Wrap(ani_env *env, const FsFile *file) +static bool SetFileProperties(ani_env *env, ani_class cls, ani_object obj, const FsFile *file) { - 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 nullptr; - } - ani_method ctor; - if (ANI_OK != env->Class_FindMethod(cls, "", "J:V", &ctor)) { - HILOGE("Cannot find constructor method for class %s", className); - 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 nullptr; - } - const auto &fdRet = file->GetFD(); if (!fdRet.IsSuccess()) { HILOGE("GetFD Failed!"); - return nullptr; + return false; } const auto &fd = fdRet.GetData().value(); if (ANI_OK != AniHelper::SetPropertyValue(env, cls, obj, "fd", static_cast(fd))) { HILOGE("Set fd field value failed!"); - return nullptr; + return false; } const auto &pathRet = file->GetPath(); if (!pathRet.IsSuccess()) { HILOGE("GetPath Failed!"); - return nullptr; + return false; } const auto &path = pathRet.GetData().value(); if (ANI_OK != AniHelper::SetPropertyValue(env, cls, obj, "path", path)) { HILOGE("Set path field value failed!"); - return nullptr; + return false; } const auto &nameRet = file->GetName(); if (!pathRet.IsSuccess()) { HILOGE("GetPath Failed!"); - return nullptr; + return false; } const auto &name = nameRet.GetData().value(); if (ANI_OK != AniHelper::SetPropertyValue(env, cls, obj, "name", name)) { HILOGE("Set name field value failed!"); + return false; + } + return true; +} + +ani_object FileWrapper::Wrap(ani_env *env, const FsFile *file) +{ + if (file == nullptr) { + HILOGE("FsFile pointer is null!"); + return nullptr; + } + + auto classDesc = FS::FileInner::classDesc.c_str(); + ani_class cls; + if (ANI_OK != env->FindClass(classDesc, &cls)) { + HILOGE("Cannot find class %s", classDesc); + return nullptr; + } + + auto ctorDesc = FS::FileInner::ctorDesc.c_str(); + auto ctorSig = FS::FileInner::ctorSig.c_str(); + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { + HILOGE("Cannot find constructor method for class %s", classDesc); 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!", classDesc); + return nullptr; + } + + if (!SetFileProperties(env, cls, obj, file)) { + return nullptr; + } + return obj; } diff --git a/interfaces/kits/js/src/mod_fs/class_file/fs_file.cpp b/interfaces/kits/js/src/mod_fs/class_file/fs_file.cpp index ae55f850400086afcda55fb50d7e702bf45b68ed..35744bb89e6b7b94144e88477f60c4b4b733de4d 100644 --- a/interfaces/kits/js/src/mod_fs/class_file/fs_file.cpp +++ b/interfaces/kits/js/src/mod_fs/class_file/fs_file.cpp @@ -40,6 +40,16 @@ static tuple> RealPa return { ret, move(realpath_req) }; } +bool FsFile::RemoveEntity() +{ + if (!fileEntity) { + HILOGE("Failed to get file entity"); + return false; + } + fileEntity = nullptr; + return true; +} + FsResult FsFile::GetFD() const { if (!fileEntity) { diff --git a/interfaces/kits/js/src/mod_fs/class_file/fs_file.h b/interfaces/kits/js/src/mod_fs/class_file/fs_file.h index dbdd471bf7d664f5e0ec948b94733751f3694a95..73c41d4d07fb55e8b8f1823c00aeb2f452ce2238 100644 --- a/interfaces/kits/js/src/mod_fs/class_file/fs_file.h +++ b/interfaces/kits/js/src/mod_fs/class_file/fs_file.h @@ -62,6 +62,7 @@ public: #endif static FsResult Constructor(); FsResult GetFD() const; + bool RemoveEntity(); private: unique_ptr fileEntity; diff --git a/interfaces/kits/js/src/mod_fs/class_randomaccessfile/ani/randomaccessfile_ani.cpp b/interfaces/kits/js/src/mod_fs/class_randomaccessfile/ani/randomaccessfile_ani.cpp index 36f30dad896fd81b72a4be4e7e80c0d242281c88..335092ba87a051121bc840045913417e126f72c9 100644 --- a/interfaces/kits/js/src/mod_fs/class_randomaccessfile/ani/randomaccessfile_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/class_randomaccessfile/ani/randomaccessfile_ani.cpp @@ -16,6 +16,7 @@ #include "randomaccessfile_ani.h" #include "ani_helper.h" +#include "ani_signature.h" #include "error_handler.h" #include "filemgmt_libhilog.h" #include "fs_randomaccessfile.h" @@ -25,8 +26,13 @@ namespace OHOS { namespace FileManagement { namespace ModuleFileIO { namespace ANI { -using namespace OHOS::FileManagement::ModuleFileIO; using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +const int BUF_SIZE = 1024; +const string READ_STREAM_CLASS = "ReadStream"; +const string WRITE_STREAM_CLASS = "WriteStream"; static FsRandomAccessFile *Unwrap(ani_env *env, ani_object object) { @@ -101,7 +107,8 @@ static tuple> ToWriteOptions(ani_env *env, ani_obje static tuple ParseStringBuffer(ani_env *env, const ani_object &buf) { ani_class cls; - env->FindClass("Lstd/core/String;", &cls); + auto classDesc = BuiltInTypes::String::classDesc.c_str(); + env->FindClass(classDesc, &cls); ani_boolean isString; env->Object_InstanceOf(buf, cls, &isString); @@ -115,7 +122,8 @@ static tuple ParseStringBuffer(ani_env *env, const ani_object static tuple ParseArrayBuffer(ani_env *env, const ani_object &buf) { ani_class cls; - env->FindClass("Lescompat/ArrayBuffer;", &cls); + auto classDesc = BuiltInTypes::ArrayBuffer::classDesc.c_str(); + env->FindClass(classDesc, &cls); ani_boolean isArrayBuffer; env->Object_InstanceOf(buf, cls, &isArrayBuffer); @@ -160,8 +168,8 @@ void RandomAccessFileAni::Close(ani_env *env, [[maybe_unused]] ani_object object } } -ani_double RandomAccessFileAni::WriteSync(ani_env *env, [[maybe_unused]] ani_object object, - ani_object buf, ani_object options) +ani_double RandomAccessFileAni::WriteSync( + ani_env *env, [[maybe_unused]] ani_object object, ani_object buf, ani_object options) { auto rafFile = Unwrap(env, object); if (rafFile == nullptr) { @@ -215,8 +223,8 @@ ani_double RandomAccessFileAni::WriteSync(ani_env *env, [[maybe_unused]] ani_obj return -1; } -ani_double RandomAccessFileAni::ReadSync(ani_env *env, [[maybe_unused]] ani_object object, - ani_arraybuffer buf, ani_object options) +ani_double RandomAccessFileAni::ReadSync( + ani_env *env, [[maybe_unused]] ani_object object, ani_arraybuffer buf, ani_object options) { auto rafFile = Unwrap(env, object); if (rafFile == nullptr) { @@ -239,7 +247,7 @@ ani_double RandomAccessFileAni::ReadSync(ani_env *env, [[maybe_unused]] ani_obje return -1; } - auto ret = rafFile-> ReadSync(arrayBuffer, op); + auto ret = rafFile->ReadSync(arrayBuffer, op); if (!ret.IsSuccess()) { HILOGE("Read file content failed!"); const auto &err = ret.GetError(); @@ -249,6 +257,231 @@ ani_double RandomAccessFileAni::ReadSync(ani_env *env, [[maybe_unused]] ani_obje return static_cast(ret.GetData().value()); } +static ani_string GetFilePath(ani_env *env, const int fd) +{ + auto dstFd = dup(fd); + if (dstFd < 0) { + HILOGE("Failed to get valid fd, fail reason: %{public}s, fd: %{public}d", strerror(errno), fd); + return nullptr; + } + + string path = "/proc/self/fd/" + to_string(dstFd); + auto buf = CreateUniquePtr(BUF_SIZE); + int readLinkRes = readlink(path.c_str(), buf.get(), BUF_SIZE); + if (readLinkRes < 0) { + close(dstFd); + return nullptr; + } + + close(dstFd); + auto [succ, filePath] = TypeConverter::ToAniString(env, string(buf.get())); + if (!succ) { + return nullptr; + } + return move(filePath); +} + +static ani_object CreateReadStreamOptions(ani_env *env, int64_t start, int64_t end) +{ + static const char *className = "L@ohos/file/fs/ReadStreamOptionsInner;"; + ani_class cls; + if (ANI_OK != env->FindClass(className, &cls)) { + HILOGE("Cannot find class %s", className); + return nullptr; + } + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, "", ":V", &ctor)) { + HILOGE("Cannot find constructor method for class %s", className); + return nullptr; + } + ani_object obj; + if (ANI_OK != env->Object_New(cls, ctor, &obj)) { + HILOGE("New %s obj Failed", className); + return nullptr; + } + + ani_field startField = nullptr; + ani_field endField = nullptr; + if (ANI_OK != env->Class_FindField(cls, "start", &startField)) { + HILOGE("Cannot find start in class %s", className); + return nullptr; + } + if (ANI_OK != env->Class_FindField(cls, "end", &endField)) { + HILOGE("Cannot find end in class %s", className); + return nullptr; + } + + if (start >= 0) { + env->Object_SetField_Int(obj, startField, start); + } + if (end >= 0) { + env->Object_SetField_Int(obj, endField, end); + } + if (obj == nullptr) { + HILOGE("CreateReadStreamOptions is nullptr"); + } + + return move(obj); +} + +static ani_object CreateWriteStreamOptions(ani_env *env, int64_t start, int flags) +{ + static const char *className = "L@ohos/file/fs/WriteStreamOptionsInner;"; + ani_class cls; + if (ANI_OK != env->FindClass(className, &cls)) { + HILOGE("Cannot find class %s", className); + return nullptr; + } + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, "", ":V", &ctor)) { + HILOGE("Cannot find constructor method for class %s", className); + return nullptr; + } + ani_object obj; + if (ANI_OK != env->Object_New(cls, ctor, &obj)) { + HILOGE("New %s obj Failed", className); + return nullptr; + } + + ani_field modeField = nullptr; + ani_field startField = nullptr; + if (ANI_OK != env->Class_FindField(cls, "mode", &modeField)) { + HILOGE("Cannot find mode in class %s", className); + return nullptr; + } + if (ANI_OK != env->Class_FindField(cls, "start", &startField)) { + HILOGE("Cannot find start in class %s", className); + return nullptr; + } + + env->Object_SetField_Int(obj, modeField, flags); + if (start >= 0) { + env->Object_SetField_Int(obj, startField, start); + } + + return move(obj); +} + +static ani_object CreateReadStream(ani_env *env, ani_string filePath, ani_object options) +{ + static const char *className = "L@ohos/file/fs/fileIo/ReadStream;"; + ani_class cls; + if (ANI_OK != env->FindClass(className, &cls)) { + HILOGE("Cannot find class %s", className); + return nullptr; + } + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, "", "Lstd/core/String;L@ohos/file/fs/ReadStreamOptions;:V", &ctor)) { + HILOGE("Cannot find constructor method for class %s", className); + return nullptr; + } + ani_object obj; + if (ANI_OK != env->Object_New(cls, ctor, &obj, filePath, options)) { + HILOGE("New %s obj Failed", className); + return nullptr; + } + + return move(obj); +} + +static ani_object CreateWriteStream(ani_env *env, ani_string filePath, ani_object options) +{ + static const char *className = "L@ohos/file/fs/fileIo/WriteStream;"; + ani_class cls; + if (ANI_OK != env->FindClass(className, &cls)) { + HILOGE("Cannot find class %s", className); + return nullptr; + } + ani_method ctor; + if (ANI_OK != + env->Class_FindMethod(cls, "", "Lstd/core/String;L@ohos/file/fs/WriteStreamOptions;:V", &ctor)) { + HILOGE("Cannot find constructor method for class %s", className); + return nullptr; + } + ani_object obj; + if (ANI_OK != env->Object_New(cls, ctor, &obj, filePath, options)) { + HILOGE("New %s obj Failed", className); + return nullptr; + } + + return move(obj); +} + +static ani_object CreateStream(ani_env *env, const string &streamName, RandomAccessFileEntity *rafEntity, int flags) +{ + ani_string filePath = GetFilePath(env, rafEntity->fd.get()->GetFD()); + if (!filePath) { + HILOGE("Get file path failed, errno=%{public}d", errno); + ErrorHandler::Throw(env, errno); + return nullptr; + } + + if (streamName == READ_STREAM_CLASS) { + ani_object obj = CreateReadStreamOptions(env, rafEntity->start, rafEntity->end); + return CreateReadStream(env, filePath, obj); + } + if (streamName == WRITE_STREAM_CLASS) { + ani_object obj = CreateWriteStreamOptions(env, rafEntity->start, flags); + return CreateWriteStream(env, filePath, obj); + } + + return nullptr; +} + +ani_object RandomAccessFileAni::GetReadStream(ani_env *env, [[maybe_unused]] ani_object object) +{ + auto rafFile = Unwrap(env, object); + if (rafFile == nullptr) { + HILOGE("Cannot unwrap rafFile!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + + auto entity = rafFile->GetRAFEntity(); + if (!entity) { + HILOGE("Get RandomAccessFileEntity failed!"); + ErrorHandler::Throw(env, EIO); + return nullptr; + } + + int flags = fcntl(entity->fd.get()->GetFD(), F_GETFL); + unsigned int uflags = static_cast(flags); + if (((uflags & O_ACCMODE) != O_RDONLY) && ((uflags & O_ACCMODE) != O_RDWR)) { + HILOGE("Failed to check Permission"); + ErrorHandler::Throw(env, EACCES); + return nullptr; + } + + return CreateStream(env, READ_STREAM_CLASS, entity, flags); +} + +ani_object RandomAccessFileAni::GetWriteStream(ani_env *env, [[maybe_unused]] ani_object object) +{ + auto rafFile = Unwrap(env, object); + if (rafFile == nullptr) { + HILOGE("Cannot unwrap rafFile!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return nullptr; + } + + auto entity = rafFile->GetRAFEntity(); + if (!entity) { + HILOGE("Get RandomAccessFileEntity failed!"); + ErrorHandler::Throw(env, EIO); + return nullptr; + } + + int flags = fcntl(entity->fd.get()->GetFD(), F_GETFL); + unsigned int uflags = static_cast(flags); + if (((uflags & O_ACCMODE) != O_RDONLY) && ((uflags & O_ACCMODE) != O_RDWR)) { + HILOGE("Failed to check Permission"); + ErrorHandler::Throw(env, EACCES); + return nullptr; + } + + return CreateStream(env, READ_STREAM_CLASS, entity, flags); +} + } // namespace ANI } // namespace ModuleFileIO } // namespace FileManagement diff --git a/interfaces/kits/js/src/mod_fs/class_randomaccessfile/ani/randomaccessfile_ani.h b/interfaces/kits/js/src/mod_fs/class_randomaccessfile/ani/randomaccessfile_ani.h index 7fc783bd5e2c902aa87a9f3d7270d318e3d79829..d1a29d8ec514fddcc0b2745b0c4509f38f1fa51c 100644 --- a/interfaces/kits/js/src/mod_fs/class_randomaccessfile/ani/randomaccessfile_ani.h +++ b/interfaces/kits/js/src/mod_fs/class_randomaccessfile/ani/randomaccessfile_ani.h @@ -28,11 +28,13 @@ public: static void SetFilePointer(ani_env *env, [[maybe_unused]] ani_object object, ani_double fp); static void Close(ani_env *env, [[maybe_unused]] ani_object object); static ani_double WriteSync(ani_env *env, [[maybe_unused]] ani_object object, ani_object buf, ani_object options); - static ani_double ReadSync(ani_env *env, [[maybe_unused]] ani_object object, - ani_arraybuffer buf, ani_object options); + static ani_double ReadSync( + ani_env *env, [[maybe_unused]] ani_object object, ani_arraybuffer buf, ani_object options); + static ani_object GetReadStream(ani_env *env, [[maybe_unused]] ani_object object); + static ani_object GetWriteStream(ani_env *env, [[maybe_unused]] ani_object object); }; } // namespace ANI } // namespace ModuleFileIO } // namespace FileManagement } // namespace OHOS -#endif //INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_RANDOMACCESSFILE_ANI_RANDOMACCESSFILE_ANI_H \ No newline at end of file +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_RANDOMACCESSFILE_ANI_RANDOMACCESSFILE_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_readeriterator/ani/reader_iterator_ani.cpp b/interfaces/kits/js/src/mod_fs/class_readeriterator/ani/reader_iterator_ani.cpp index b5f8b55b93c91b0b2b2c1b9a046cdc2968dab24f..eb3f82c0eb47bbdf8f2c1f46dfda580084f8b33c 100644 --- a/interfaces/kits/js/src/mod_fs/class_readeriterator/ani/reader_iterator_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/class_readeriterator/ani/reader_iterator_ani.cpp @@ -15,6 +15,7 @@ #include "reader_iterator_ani.h" +#include "ani_signature.h" #include "error_handler.h" #include "filemgmt_libhilog.h" #include "reader_iterator_result_ani.h" @@ -24,27 +25,36 @@ namespace OHOS { namespace FileManagement { namespace ModuleFileIO { namespace ANI { -using namespace OHOS::FileManagement::ModuleFileIO; using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; ani_object ReaderIteratorAni::Wrap(ani_env *env, const FsReaderIterator *it) { - static const char *className = "L@ohos/file/fs/ReaderIteratorInner;"; + if (it == nullptr) { + HILOGE("FsReaderIterator pointer is null!"); + return nullptr; + } + auto classDesc = FS::ReaderIteratorInner::classDesc.c_str(); ani_class cls; - if (ANI_OK != env->FindClass(className, &cls)) { - HILOGE("Cannot find class %s", className); + if (ANI_OK != env->FindClass(classDesc, &cls)) { + HILOGE("Cannot find class %s", classDesc); return nullptr; } + + auto ctorDesc = FS::ReaderIteratorInner::ctorDesc.c_str(); + auto ctorSig = FS::ReaderIteratorInner::ctorSig.c_str(); ani_method ctor; - if (ANI_OK != env->Class_FindMethod(cls, "", "J:V", &ctor)) { - HILOGE("Cannot find constructor method for class %s", className); + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { + HILOGE("Cannot find constructor method for class %s", classDesc); return nullptr; } + ani_long ptr = static_cast(reinterpret_cast(it)); ani_object obj; if (ANI_OK != env->Object_New(cls, ctor, &obj, ptr)) { - HILOGE("New %s obj Failed!", className); + HILOGE("New %s obj Failed!", classDesc); return nullptr; } @@ -69,7 +79,7 @@ ani_object ReaderIteratorAni::Next(ani_env *env, [[maybe_unused]] ani_object obj auto fsReaderIterator = Unwrap(env, object); if (fsReaderIterator == nullptr) { ErrorHandler::Throw(env, UNKNOWN_ERR); - return ANI_FALSE; + return nullptr; } auto ret = fsReaderIterator->Next(); @@ -77,7 +87,7 @@ ani_object ReaderIteratorAni::Next(ani_env *env, [[maybe_unused]] ani_object obj HILOGE("Cannot get readeriterator next!"); const auto &err = ret.GetError(); ErrorHandler::Throw(env, err); - return {}; + return nullptr; } auto nextRet = ret.GetData().value(); auto result = ReaderIteratorResultAni::Wrap(env, &nextRet); diff --git a/interfaces/kits/js/src/mod_fs/class_readeriterator/ani/reader_iterator_result_ani.cpp b/interfaces/kits/js/src/mod_fs/class_readeriterator/ani/reader_iterator_result_ani.cpp index 0ea8f121b13ffdf8bf88536279e737b91519685b..b8efe806e026de0b7c54f2b29aab3d76007120ac 100644 --- a/interfaces/kits/js/src/mod_fs/class_readeriterator/ani/reader_iterator_result_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/class_readeriterator/ani/reader_iterator_result_ani.cpp @@ -15,6 +15,7 @@ #include "reader_iterator_result_ani.h" +#include "ani_signature.h" #include "error_handler.h" #include "filemgmt_libhilog.h" #include "type_converter.h" @@ -23,27 +24,36 @@ namespace OHOS { namespace FileManagement { namespace ModuleFileIO { namespace ANI { -using namespace OHOS::FileManagement::ModuleFileIO; using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; ani_object ReaderIteratorResultAni::Wrap(ani_env *env, const ReaderIteratorResult *result) { - static const char *className = "L@ohos/file/fs/ReaderIteratorResultInner;"; + if (result == nullptr) { + HILOGE("ReaderIteratorResult pointer is null!"); + return nullptr; + } + auto classDesc = FS::ReaderIteratorResultInner::classDesc.c_str(); ani_class cls; - if (ANI_OK != env->FindClass(className, &cls)) { - HILOGE("Cannot find class %s", className); + if (ANI_OK != env->FindClass(classDesc, &cls)) { + HILOGE("Cannot find class %s", classDesc); return nullptr; } + + auto ctorDesc = FS::ReaderIteratorResultInner::ctorDesc.c_str(); + auto ctorSig = FS::ReaderIteratorResultInner::ctorSig.c_str(); ani_method ctor; - if (ANI_OK != env->Class_FindMethod(cls, "", "J:V", &ctor)) { - HILOGE("Cannot find constructor method for class %s", className); + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { + HILOGE("Cannot find constructor method for class %s", classDesc); return nullptr; } + ani_long ptr = static_cast(reinterpret_cast(result)); ani_object obj; if (ANI_OK != env->Object_New(cls, ctor, &obj, ptr)) { - HILOGE("New %s obj Failed!", className); + HILOGE("New %s obj Failed!", classDesc); return nullptr; } diff --git a/interfaces/kits/js/src/mod_fs/class_stat/ani/lstat_ani.cpp b/interfaces/kits/js/src/mod_fs/class_stat/ani/lstat_ani.cpp index f4379ac5fe8dd63c2d8b1449d3f9563e3a09599d..deb3052c516c6db994ae074a6ba0dfc0375d9aa0 100644 --- a/interfaces/kits/js/src/mod_fs/class_stat/ani/lstat_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/class_stat/ani/lstat_ani.cpp @@ -49,15 +49,15 @@ ani_object LstatAni::LstatSync(ani_env *env, [[maybe_unused]] ani_class clazz, a } auto fsStat = ret.GetData().value(); - auto [status, statObject] = StatWrapper::Wrap(env, fsStat); - if (status != ANI_OK) { + auto statObject = StatWrapper::Wrap(env, fsStat); + if (statObject == nullptr) { delete fsStat; fsStat = nullptr; HILOGE("Wrap stat object failed!"); ErrorHandler::Throw(env, UNKNOWN_ERR); return {}; } - + return statObject; } } // namespace ANI 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 95b92f9583c75bd005a8636f27f7358cef352404..de57367dac0ce3a7b45e197b77c96080c1c393ef 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 @@ -34,7 +34,7 @@ ani_object StatAni::StatSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani if (!succPath) { HILOGE("The first argument requires filepath/fd"); ErrorHandler::Throw(env, EINVAL); - return {}; + return nullptr; } auto ret = StatCore::DoStat(fileInfo); @@ -42,17 +42,17 @@ ani_object StatAni::StatSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani HILOGE("DoStat failed!"); const FsError &err = ret.GetError(); ErrorHandler::Throw(env, err); - return {}; + return nullptr; } auto fsStat = ret.GetData().value(); - auto [status, statObject] = StatWrapper::Wrap(env, fsStat); - if (status != ANI_OK) { + auto statObject = StatWrapper::Wrap(env, fsStat); + if (statObject == nullptr) { delete fsStat; fsStat = nullptr; HILOGE("Wrap stat object failed!"); ErrorHandler::Throw(env, UNKNOWN_ERR); - return {}; + return nullptr; } return statObject; diff --git a/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_wrapper.cpp b/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_wrapper.cpp index 02a9bca9fc8b1a7d4bac48c492a1e73069ccb491..7545be6454b6718d5ac25e6d8e9bd558365cd4b8 100644 --- a/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_wrapper.cpp +++ b/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_wrapper.cpp @@ -17,7 +17,9 @@ #include #include +#include +#include "ani_signature.h" #include "error_handler.h" #include "filemgmt_libhilog.h" #include "type_converter.h" @@ -28,6 +30,7 @@ namespace ModuleFileIO { namespace ANI { using namespace std; using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; static ani_status SetNumProperty( ani_env *env, const ani_class &cls, ani_object &object, const char *name, ani_double &value) @@ -46,17 +49,19 @@ static ani_status SetBigIntProperty( ani_env *env, const ani_class &statCls, ani_object &statObject, const char *name, ani_double &value) { ani_object object = {}; - static const char *className = "Lescompat/BigInt;"; + auto classDesc = BuiltInTypes::BigInt::classDesc.c_str(); ani_class cls; ani_status ret; - if ((ret = env->FindClass(className, &cls)) != ANI_OK) { - HILOGE("Not found %{private}s, err: %{private}d", className, ret); + if ((ret = env->FindClass(classDesc, &cls)) != ANI_OK) { + HILOGE("Not found %{private}s, err: %{private}d", classDesc, ret); return ret; } + auto ctorDesc = BuiltInTypes::BigInt::ctorDesc.c_str(); + auto ctorSig = BuiltInTypes::BigInt::ctorSig.c_str(); ani_method ctor; - if ((ret = env->Class_FindMethod(cls, "", "D:V", &ctor)) != ANI_OK) { + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { HILOGE("Not found ctor, err: %{private}d", ret); return ret; } @@ -98,45 +103,62 @@ static ani_status SetEnumLocation( return env->Object_CallMethod_Void(object, setter, GetLocationEnumIndex(value)); } +const static string MODE_SETTER = Builder::BuildSetterName("mode"); +const static string UID_SETTER = Builder::BuildSetterName("uid"); +const static string GID_SETTER = Builder::BuildSetterName("gid"); +const static string SIZE_SETTER = Builder::BuildSetterName("size"); +const static string ATIME_SETTER = Builder::BuildSetterName("atime"); +const static string MTIME_SETTER = Builder::BuildSetterName("mtime"); +const static string CTIME_SETTER = Builder::BuildSetterName("ctime"); +const static string INO_SETTER = Builder::BuildSetterName("ino"); +const static string ATIME_NS_SETTER = Builder::BuildSetterName("atimeNs"); +const static string MTIME_NS_SETTER = Builder::BuildSetterName("mtimeNs"); +const static string CTIME_NS_SETTER = Builder::BuildSetterName("ctimeNs"); +const static string LOCATION_SETTER = Builder::BuildSetterName("location"); + static ani_status SetProperties(ani_env *env, const ani_class &cls, ani_object &statObject, FsStat *fsStat) { ani_status ret; - vector> numProperties = { - { "mode", ani_double(static_cast(fsStat->GetMode())) }, - { "uid", ani_double(static_cast(fsStat->GetUid())) }, - { "gid", ani_double(static_cast(fsStat->GetGid())) }, - { "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())) }, + vector> numProperties = { + { MODE_SETTER, ani_double(static_cast(fsStat->GetMode())) }, + { UID_SETTER, ani_double(static_cast(fsStat->GetUid())) }, + { GID_SETTER, ani_double(static_cast(fsStat->GetGid())) }, + { SIZE_SETTER, ani_double(static_cast(fsStat->GetSize())) }, + { ATIME_SETTER, ani_double(static_cast(fsStat->GetAtime())) }, + { MTIME_SETTER, ani_double(static_cast(fsStat->GetMtime())) }, + { CTIME_SETTER, ani_double(static_cast(fsStat->GetCtime())) }, }; for (auto iter : numProperties) { - ret = SetNumProperty(env, cls, statObject, iter.first, iter.second); + auto key = iter.first.data(); + auto value = iter.second; + ret = SetNumProperty(env, cls, statObject, key, value); if (ret != ANI_OK) { - HILOGE("Object_CallMethod_Void Fail %{private}s, err: %{private}d", iter.first, ret); + HILOGE("Object_CallMethod_Void Fail %{private}s, err: %{private}d", key, ret); return ret; } } - vector> bigIntProperties = { - { "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())) }, + vector> bigIntProperties = { + { INO_SETTER, ani_double(static_cast(fsStat->GetIno())) }, + { ATIME_NS_SETTER, ani_double(static_cast(fsStat->GetAtimeNs())) }, + { MTIME_NS_SETTER, ani_double(static_cast(fsStat->GetMtimeNs())) }, + { CTIME_NS_SETTER, ani_double(static_cast(fsStat->GetCtimeNs())) }, }; for (auto iter : bigIntProperties) { - ret = SetBigIntProperty(env, cls, statObject, iter.first, iter.second); + auto key = iter.first.data(); + auto value = iter.second; + ret = SetBigIntProperty(env, cls, statObject, key, value); if (ret != ANI_OK) { - HILOGE("Object_CallMethod_Void Fail %{private}s, err: %{private}d", iter.first, ret); + HILOGE("Object_CallMethod_Void Fail %{private}s, err: %{private}d", key, ret); return ret; } } #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); + auto key = LOCATION_SETTER.c_str(); + if ((ret = SetEnumLocation(env, cls, statObject, key, static_cast(fsStat->GetLocation()))) != ANI_OK) { + HILOGE("Object_CallMethod_Void Fail %{private}s, err: %{private}d", key, ret); return ret; } #endif @@ -144,38 +166,44 @@ static ani_status SetProperties(ani_env *env, const ani_class &cls, ani_object & return ANI_OK; } -tuple StatWrapper::Wrap(ani_env *env, FsStat *fsStat) +ani_object StatWrapper::Wrap(ani_env *env, FsStat *fsStat) { + if (fsStat == nullptr) { + HILOGE("FsStat pointer is null!"); + return nullptr; + } + auto classDesc = FS::StatInner::classDesc.c_str(); ani_object statObject = {}; - static const char *className = "L@ohos/file/fs/StatInner;"; ani_class cls; ani_status ret; - if ((ret = env->FindClass(className, &cls)) != ANI_OK) { - HILOGE("Not found %{private}s, err: %{private}d", className, ret); - return { ret, statObject }; + if ((ret = env->FindClass(classDesc, &cls)) != ANI_OK) { + HILOGE("Not found %{private}s, err: %{private}d", classDesc, ret); + return nullptr; } + auto ctorDesc = FS::StatInner::ctorDesc.c_str(); + auto ctorSig = FS::StatInner::ctorSig.c_str(); ani_method ctor; - if ((ret = env->Class_FindMethod(cls, "", "J:V", &ctor)) != ANI_OK) { + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { HILOGE("Not found ctor, err: %{private}d", ret); - return { ret, statObject }; + return nullptr; } if ((ret = env->Object_New(cls, ctor, &statObject, reinterpret_cast(fsStat))) != ANI_OK) { HILOGE("New StatInner Fail, err: %{private}d", ret); - return { ret, statObject }; + return nullptr; } if ((ret = SetProperties(env, cls, statObject, fsStat)) != ANI_OK) { HILOGE("SetProperties Fail, err: %{private}d", ret); - return { ret, statObject }; + return nullptr; } - return { ANI_OK, statObject }; + return statObject; } -FsStat* StatWrapper::Unwrap(ani_env *env, ani_object object) +FsStat *StatWrapper::Unwrap(ani_env *env, ani_object object) { ani_long fsStat; auto ret = env->Object_GetFieldByName_Long(object, "nativeStat", &fsStat); diff --git a/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_wrapper.h b/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_wrapper.h index 77bbcbe6ff1b46fe0a35f564914b5a82c8395271..e84e1e5eb6561a31c7c2c5d14991531b2c8c0743 100644 --- a/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_wrapper.h +++ b/interfaces/kits/js/src/mod_fs/class_stat/ani/stat_wrapper.h @@ -28,8 +28,8 @@ using namespace std; class StatWrapper final { public: - static tuple Wrap(ani_env *env, FsStat *fsStat); - static FsStat* Unwrap(ani_env *env, ani_object object); + static ani_object Wrap(ani_env *env, FsStat *fsStat); + static FsStat *Unwrap(ani_env *env, ani_object object); }; } // namespace ANI } // namespace ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fs/class_stream/ani/stream_ani.cpp b/interfaces/kits/js/src/mod_fs/class_stream/ani/stream_ani.cpp index 92cfc402cca1232fbdaaa8a9d4aa88cdd79c79b0..a1d694187cd62d43d21440ff4b8f111de4314e13 100644 --- a/interfaces/kits/js/src/mod_fs/class_stream/ani/stream_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/class_stream/ani/stream_ani.cpp @@ -19,6 +19,7 @@ #include #include "ani_helper.h" +#include "ani_signature.h" #include "error_handler.h" #include "filemgmt_libhilog.h" #include "fs_stream.h" @@ -29,8 +30,9 @@ namespace OHOS { namespace FileManagement { namespace ModuleFileIO { namespace ANI { -using namespace OHOS::FileManagement::ModuleFileIO; using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; static tuple> ToReadOptions(ani_env *env, ani_object obj) { @@ -91,8 +93,9 @@ static tuple> ToWriteOptions(ani_env *env, ani_obje static std::tuple ParseStringBuffer(ani_env *env, const ani_object &buf) { + auto classDesc = BuiltInTypes::String::classDesc.c_str(); ani_class cls; - env->FindClass("Lstd/core/String;", &cls); + env->FindClass(classDesc, &cls); ani_boolean isString; env->Object_InstanceOf(buf, cls, &isString); @@ -105,8 +108,9 @@ static std::tuple ParseStringBuffer(ani_env *env, const ani_ob static std::tuple ParseArrayBuffer(ani_env *env, const ani_object &buf) { + auto classDesc = BuiltInTypes::ArrayBuffer::classDesc.c_str(); ani_class cls; - env->FindClass("Lescompat/ArrayBuffer;", &cls); + env->FindClass(classDesc, &cls); ani_boolean isArrayBuffer; env->Object_InstanceOf(buf, cls, &isArrayBuffer); diff --git a/interfaces/kits/js/src/mod_fs/class_stream/ani/stream_wrapper.cpp b/interfaces/kits/js/src/mod_fs/class_stream/ani/stream_wrapper.cpp index 31ff9ec263797ba2f333c5a252a4b5a4daba373e..c882f9dda1125661faf91bfa8ff19036b57404c2 100644 --- a/interfaces/kits/js/src/mod_fs/class_stream/ani/stream_wrapper.cpp +++ b/interfaces/kits/js/src/mod_fs/class_stream/ani/stream_wrapper.cpp @@ -18,6 +18,7 @@ #include #include "ani_helper.h" +#include "ani_signature.h" #include "filemgmt_libhilog.h" #include "type_converter.h" @@ -25,8 +26,9 @@ namespace OHOS { namespace FileManagement { namespace ModuleFileIO { namespace ANI { -using namespace OHOS::FileManagement::ModuleFileIO; using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; FsStream *StreamWrapper::Unwrap(ani_env *env, ani_object object) { @@ -43,21 +45,27 @@ FsStream *StreamWrapper::Unwrap(ani_env *env, ani_object object) ani_object StreamWrapper::Wrap(ani_env *env, const FsStream *stream) { - static const char *className = "L@ohos/file/fs/StreamInner;"; + if (stream == nullptr) { + HILOGE("FsStream pointer is null!"); + return nullptr; + } + auto classDesc = FS::StreamInner::classDesc.c_str(); ani_class cls; - if (ANI_OK != env->FindClass(className, &cls)) { - HILOGE("Cannot find class %s", className); + if (ANI_OK != env->FindClass(classDesc, &cls)) { + HILOGE("Cannot find class %s", classDesc); return nullptr; } + auto ctorDesc = FS::StreamInner::ctorDesc.c_str(); + auto ctorSig = FS::StreamInner::ctorSig.c_str(); ani_method ctor; - if (ANI_OK != env->Class_FindMethod(cls, "", "J:V", &ctor)) { - HILOGE("Cannot find constructor method for class %s", className); + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { + HILOGE("Cannot find constructor method for class %s", classDesc); return nullptr; } ani_long ptr = static_cast(reinterpret_cast(stream)); ani_object obj; if (ANI_OK != env->Object_New(cls, ctor, &obj, ptr)) { - HILOGE("New %s obj Failed!", className); + HILOGE("New %s obj Failed!", classDesc); return nullptr; } diff --git a/interfaces/kits/js/src/mod_fs/class_stream/fs_stream.cpp b/interfaces/kits/js/src/mod_fs/class_stream/fs_stream.cpp index 2a39e3506b6513e805093e64852349d00fe4fe98..00a493ed2767ee19c5128f27ae62b8df9fcf6eff 100644 --- a/interfaces/kits/js/src/mod_fs/class_stream/fs_stream.cpp +++ b/interfaces/kits/js/src/mod_fs/class_stream/fs_stream.cpp @@ -29,7 +29,7 @@ using namespace std; std::shared_ptr FsStream::GetFilePtr() { std::lock_guard lock(mtx); - if (!streamEntity->fp) { + if (!streamEntity) { return nullptr; } return streamEntity->fp; diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/ani/fs_watcher_wrapper.cpp b/interfaces/kits/js/src/mod_fs/class_watcher/ani/fs_watcher_wrapper.cpp index ca5212e4b0f86d6794671c490b31d7b846fc23c9..79d6fb1dcec57fd9324c82ccf1a20d4c88309431 100644 --- a/interfaces/kits/js/src/mod_fs/class_watcher/ani/fs_watcher_wrapper.cpp +++ b/interfaces/kits/js/src/mod_fs/class_watcher/ani/fs_watcher_wrapper.cpp @@ -15,14 +15,16 @@ #include "fs_watcher_wrapper.h" +#include "ani_signature.h" #include "filemgmt_libhilog.h" namespace OHOS { namespace FileManagement { namespace ModuleFileIO { namespace ANI { -using namespace OHOS::FileManagement::ModuleFileIO; using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; FsWatcher *FsWatcherWrapper::Unwrap(ani_env *env, ani_object object) { @@ -39,21 +41,27 @@ FsWatcher *FsWatcherWrapper::Unwrap(ani_env *env, ani_object object) ani_object FsWatcherWrapper::Wrap(ani_env *env, const FsWatcher *watcher) { - static const char *className = "L@ohos/file/fs/WatcherInner;"; + if (watcher == nullptr) { + HILOGE("FsWatcher pointer is null!"); + return nullptr; + } + auto classDesc = FS::WatcherInner::classDesc.c_str(); ani_class cls; - if (ANI_OK != env->FindClass(className, &cls)) { - HILOGE("Cannot find class %s", className); + if (ANI_OK != env->FindClass(classDesc, &cls)) { + HILOGE("Cannot find class %s", classDesc); return nullptr; } + auto ctorDesc = FS::WatcherInner::ctorDesc.c_str(); + auto ctorSig = FS::WatcherInner::ctorSig.c_str(); ani_method ctor; - if (ANI_OK != env->Class_FindMethod(cls, "", "J:V", &ctor)) { - HILOGE("Cannot find constructor method for class %s", className); + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { + HILOGE("Cannot find constructor method for class %s", classDesc); return nullptr; } ani_long ptr = static_cast(reinterpret_cast(watcher)); ani_object obj; if (ANI_OK != env->Object_New(cls, ctor, &obj, ptr)) { - HILOGE("New %s obj Failed!", className); + HILOGE("New %s obj Failed!", classDesc); return nullptr; } return obj; diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/ani/watch_event_wrapper.cpp b/interfaces/kits/js/src/mod_fs/class_watcher/ani/watch_event_wrapper.cpp index 154ccd4cbf90cab562c23aa8bdc00f56f3c4c2da..1712f7f1f1ea44307b90f50ccd03e9311824c496 100644 --- a/interfaces/kits/js/src/mod_fs/class_watcher/ani/watch_event_wrapper.cpp +++ b/interfaces/kits/js/src/mod_fs/class_watcher/ani/watch_event_wrapper.cpp @@ -15,6 +15,7 @@ #include "watch_event_wrapper.h" +#include "ani_signature.h" #include "filemgmt_libhilog.h" #include "type_converter.h" @@ -22,20 +23,23 @@ namespace OHOS { namespace FileManagement { namespace ModuleFileIO { namespace ANI { -using namespace OHOS::FileManagement::ModuleFileIO; using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; ani_object WatchEventWrapper::Wrap(ani_env *env, const WatchEvent &evt) { - static const char *className = "L@ohos/file/fs/WatchEventInner;"; + auto classDesc = FS::WatchEventInner::classDesc.c_str(); ani_class cls; - if (ANI_OK != env->FindClass(className, &cls)) { - HILOGE("Cannot find class %s", className); + if (ANI_OK != env->FindClass(classDesc, &cls)) { + HILOGE("Cannot find class %s", classDesc); return nullptr; } + auto ctorDesc = FS::WatchEventInner::ctorDesc.c_str(); + auto ctorSig = FS::WatchEventInner::ctorSig.c_str(); ani_method ctor; - if (ANI_OK != env->Class_FindMethod(cls, "", "Lstd/core/String;DD:V", &ctor)) { - HILOGE("Cannot find constructor method for class %s", className); + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { + HILOGE("Cannot find constructor method for class %s", classDesc); return nullptr; } @@ -50,7 +54,7 @@ ani_object WatchEventWrapper::Wrap(ani_env *env, const WatchEvent &evt) ani_object obj; if (ANI_OK != env->Object_New(cls, ctor, &obj, fileName, event, cookie)) { - HILOGE("Create %s obj failed!", className); + HILOGE("Create %s obj failed!", classDesc); return nullptr; } return obj; 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 f49ccf2f256d3f877b6970f70c7c27e698fcd57e..3fc2f5b13e62736580622e407aa2a4724636be7b 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 @@ -17,9 +17,11 @@ #include +#include "ani_signature.h" #include "close_core.h" #include "error_handler.h" #include "filemgmt_libhilog.h" +#include "file_wrapper.h" #include "type_converter.h" namespace OHOS { @@ -29,57 +31,64 @@ namespace ANI { using namespace std; using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; -tuple ParseFd(ani_env *env, ani_object obj) +tuple ParseFdOrFile(ani_env *env, ani_object obj) { int32_t result = -1; - ani_class IntClass; - env->FindClass("Lstd/core/Double;", &IntClass); - ani_boolean isInt; - env->Object_InstanceOf(obj, IntClass, &isInt); - if (isInt) { + auto doubleClassDesc = BoxedTypes::Double::classDesc.c_str(); + ani_class doubleClass; + env->FindClass(doubleClassDesc, &doubleClass); + ani_boolean isDouble; + env->Object_InstanceOf(obj, doubleClass, &isDouble); + if (isDouble) { ani_int fd; if (ANI_OK != env->Object_CallMethodByName_Int(obj, "intValue", nullptr, &fd)) { HILOGE("Get fd value failed"); - return { false, result }; + return { false, result, nullptr }; } result = static_cast(fd); - return { true, result }; + return { true, result, nullptr }; } - ani_class FileClass; - env->FindClass("L@ohos/file/fs/FileInner;", &FileClass); - ani_boolean isFile; - env->Object_InstanceOf(obj, FileClass, &isFile); - if (isFile) { - 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); - return { true, result }; + FsFile *file = FileWrapper::Unwrap(env, obj); + if (file != nullptr) { + return { true, -1, file }; } - HILOGE("Invalid fd type"); - return { false, result }; + + HILOGE("Cannot unwrap fsfile!"); + ErrorHandler::Throw(env, UNKNOWN_ERR); + return { false, -1, nullptr }; } void CloseAni::CloseSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_object obj) { - auto [succ, fd] = ParseFd(env, obj); + auto [succ, fd, file] = ParseFdOrFile(env, obj); if (!succ) { HILOGE("Parse fd argument failed"); ErrorHandler::Throw(env, EINVAL); return; } - auto ret = CloseCore::DoClose(fd); + if (file == nullptr) { + auto ret = CloseCore::DoClose(fd); + if (!ret.IsSuccess()) { + HILOGE("Close %d failed", fd); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return; + } + return; + } + + auto ret = CloseCore::DoClose(file); if (!ret.IsSuccess()) { HILOGE("Close %d failed", fd); const auto &err = ret.GetError(); ErrorHandler::Throw(env, err); return; } + return; } } // namespace ANI diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp index 1f9b713c328cf0f9e8fef23f1eef5d2f60fc0116..e086c5ee1f53cae4857b4f4e45f2a36547eb1db7 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp @@ -16,6 +16,7 @@ #include "copy_ani.h" #include "ani_helper.h" +#include "ani_signature.h" #include "copy_core.h" #include "error_handler.h" #include "file_utils.h" @@ -28,6 +29,7 @@ namespace ModuleFileIO { namespace ANI { using namespace std; using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; static void SetProgressListenerCb(ani_env *env, ani_ref &callback, CopyOptions &opts) { @@ -37,7 +39,7 @@ static void SetProgressListenerCb(ani_env *env, ani_ref &callback, CopyOptions & opts.listenerCb = [vm, &callback](uint64_t progressSize, uint64_t totalSize) -> void { ani_status ret; ani_object progress = {}; - static const char *className = "L@ohos/file/fs/ProgressInner;"; + auto classDesc = FS::ProgressInner::classDesc.c_str(); ani_class cls; auto env = AniHelper::GetThreadEnv(vm); @@ -47,22 +49,25 @@ static void SetProgressListenerCb(ani_env *env, ani_ref &callback, CopyOptions & } if (progressSize > MAX_VALUE || totalSize > MAX_VALUE) { - HILOGE("progressSize or totalSize exceed MAX_VALUE: %{private}llu %{private}llu", progressSize, totalSize); + HILOGE("progressSize or totalSize exceed MAX_VALUE: %{private}" PRIu64 " %{private}" PRIu64, progressSize, + totalSize); } - if ((ret = env->FindClass(className, &cls)) != ANI_OK) { - HILOGE("Not found %{private}s, err: %{private}d", className, ret); + if ((ret = env->FindClass(classDesc, &cls)) != ANI_OK) { + HILOGE("Not found %{private}s, err: %{private}d", classDesc, ret); return; } + auto ctorDesc = FS::ProgressInner::ctorDesc.c_str(); + auto ctorSig = FS::ProgressInner::ctorSig.c_str(); ani_method ctor; - if ((ret = env->Class_FindMethod(cls, "", "DD:V", &ctor)) != ANI_OK) { + if ((ret = env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) != ANI_OK) { HILOGE("Not found ctor, err: %{private}d", ret); return; } if ((ret = env->Object_New(cls, ctor, &progress, ani_double(static_cast(progressSize)), - ani_double(static_cast(totalSize)))) != ANI_OK) { + ani_double(static_cast(totalSize)))) != ANI_OK) { HILOGE("New ProgressInner Fail, err: %{private}d", ret); return; } @@ -88,7 +93,7 @@ static bool SetTaskSignal(ani_env *env, ani_ref ©Signal, CopyOptions &opts) } ret = env->Object_SetFieldByName_Long(static_cast(copySignal), "nativeTaskSignal", - reinterpret_cast(taskSignalEntityCore.get())); + reinterpret_cast(taskSignalEntityCore.get())); if (ret != ANI_OK) { HILOGE("Object set nativeTaskSignal err: %{private}d", ret); return false; diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/copy_dir_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/copy_dir_ani.cpp index 200573ca167c91357855954228d43cad07955fdc..13804c8ad3d433a93a3ca1589bd387e7fd3010bf 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/copy_dir_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/copy_dir_ani.cpp @@ -16,6 +16,7 @@ #include "copy_dir_ani.h" #include +#include "ani_signature.h" #include "copy_dir_core.h" #include "error_handler.h" #include "filemgmt_libhilog.h" @@ -27,20 +28,23 @@ namespace ModuleFileIO { namespace ANI { using namespace std; using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; static tuple ToConflictFiles(ani_env *env, const ConflictFiles &files) { - static const char *className = "L@ohos/file/fs/ConflictFilesInner;"; + auto classDesc = FS::ConflictFilesInner::classDesc.c_str(); ani_class cls; ani_status ret; - if ((ret = env->FindClass(className, &cls)) != ANI_OK) { - HILOGE("Cannot find class %{private}s, err: %{private}d", className, ret); + if ((ret = env->FindClass(classDesc, &cls)) != ANI_OK) { + HILOGE("Cannot find class %{private}s, err: %{private}d", classDesc, ret); return { false, nullptr }; } + auto ctorDesc = FS::ConflictFilesInner::ctorDesc.c_str(); + auto ctorSig = FS::ConflictFilesInner::ctorSig.c_str(); ani_method ctor; - if ((ret = env->Class_FindMethod(cls, "", "Lstd/core/String;Lstd/core/String;:V", &ctor)) != ANI_OK) { - HILOGE("Cannot find class %{private}s constructor method, err: %{private}d", className, ret); + if ((ret = env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) != ANI_OK) { + HILOGE("Cannot find class %{private}s constructor method, err: %{private}d", classDesc, ret); return { false, nullptr }; } @@ -71,18 +75,20 @@ static tuple> ToConflictFilesArray( if (!errFiles.has_value()) { return { true, nullopt }; } - static const char *className = "Lescompat/Array;"; + auto classDesc = BuiltInTypes::Array::classDesc.c_str(); ani_class cls = nullptr; ani_status ret; - if ((ret = env->FindClass(className, &cls)) != ANI_OK) { - HILOGE("Cannot find class %{private}s, err: %{private}d", className, ret); + if ((ret = env->FindClass(classDesc, &cls)) != ANI_OK) { + HILOGE("Cannot find class %{private}s, err: %{private}d", classDesc, ret); return { false, nullopt }; } + auto ctorDesc = BuiltInTypes::Array::ctorDesc.c_str(); + auto ctorSig = BuiltInTypes::Array::ctorSig.c_str(); ani_method ctor; - if ((ret = env->Class_FindMethod(cls, "", "I:V", &ctor)) != ANI_OK) { - HILOGE("Cannot find class %{private}s constructor method, err: %{private}d", className, ret); + if ((ret = env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) != ANI_OK) { + HILOGE("Cannot find class %{private}s constructor method, err: %{private}d", classDesc, ret); return { false, nullopt }; } @@ -93,6 +99,8 @@ static tuple> ToConflictFilesArray( return { false, nullopt }; } + auto setterDesc = BuiltInTypes::Array::setterDesc.c_str(); + auto setterSig = BuiltInTypes::Array::objectSetterSig.c_str(); ani_size index = 0; for (const auto &errFile : files) { auto [succ, fileObj] = ToConflictFiles(env, errFile); @@ -100,7 +108,7 @@ static tuple> ToConflictFilesArray( return { false, nullopt }; } - if ((ret = env->Object_CallMethodByName_Void(arr, "$_set", "ILstd/core/Object;:V", index, fileObj)) != ANI_OK) { + if ((ret = env->Object_CallMethodByName_Void(arr, setterDesc, setterSig, index, fileObj)) != ANI_OK) { HILOGE("Add element to Array failed, err: %{private}d", ret); return { false, nullopt }; } @@ -150,6 +158,7 @@ void CopyDirAni::CopyDirSync( return; } } + } // namespace ANI } // namespace ModuleFileIO } // namespace FileManagement diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/create_randomaccessfile_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/create_randomaccessfile_ani.cpp index 3b72266483578e7be989880e7260df0654d1b4cd..17fe296a3fc95112d2b9d1c8441e8cb45ea05f7b 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/create_randomaccessfile_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/create_randomaccessfile_ani.cpp @@ -16,6 +16,7 @@ #include "create_randomaccessfile_ani.h" #include "ani_helper.h" +#include "ani_signature.h" #include "create_randomaccessfile_core.h" #include "error_handler.h" #include "filemgmt_libhilog.h" @@ -25,44 +26,57 @@ namespace OHOS { namespace FileManagement { namespace ModuleFileIO { namespace ANI { - using namespace std; using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; static ani_object Wrap(ani_env *env, const FsRandomAccessFile *rafFile) { - static const char *className = "L@ohos/file/fs/RandomAccessFileInner;"; + if (rafFile == nullptr) { + HILOGE("FsRandomAccessFile pointer is null!"); + return nullptr; + } + + auto classDesc = FS::RandomAccessFileInner::classDesc.c_str(); ani_class cls; - if (ANI_OK != env->FindClass(className, &cls)) { - HILOGE("Cannot find class %s", className); + if (ANI_OK != env->FindClass(classDesc, &cls)) { + HILOGE("Cannot find class %s", classDesc); return nullptr; } + + auto ctorDesc = FS::RandomAccessFileInner::ctorDesc.c_str(); + auto ctorSig = FS::RandomAccessFileInner::ctorSig.c_str(); ani_method ctor; - if (ANI_OK != env->Class_FindMethod(cls, "", "J:V", &ctor)) { - HILOGE("Cannot find constructor method for class %s", className); + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { + HILOGE("Cannot find constructor method for class %s", classDesc); return nullptr; } + ani_long ptr = static_cast(reinterpret_cast(rafFile)); ani_object obj; if (ANI_OK != env->Object_New(cls, ctor, &obj, ptr)) { - HILOGE("New %s obj Failed!", className); + HILOGE("New %s obj Failed!", classDesc); return nullptr; } + const auto &fdRet = rafFile->GetFD(); if (!fdRet.IsSuccess()) { HILOGE("GetFD Failed!"); return nullptr; } + const auto &fd = fdRet.GetData().value(); if (ANI_OK != AniHelper::SetPropertyValue(env, cls, obj, "fd", static_cast(fd))) { HILOGE("Set fd field value failed!"); return nullptr; } + const auto &fpRet = rafFile->GetFPointer(); if (!fpRet.IsSuccess()) { HILOGE("GetFPointer Failed!"); return nullptr; } + const auto &fp = fpRet.GetData().value(); if (ANI_OK != AniHelper::SetPropertyValue(env, cls, obj, "filePointer", static_cast(fp))) { HILOGE("Set fp field value failed!"); @@ -73,16 +87,18 @@ static ani_object Wrap(ani_env *env, const FsRandomAccessFile *rafFile) static tuple JudgeFile(ani_env *env, ani_object obj) { + auto stringTypeDesc = BuiltInTypes::String::classDesc.c_str(); ani_class stringClass; - env->FindClass("Lstd/core/String;", &stringClass); + env->FindClass(stringTypeDesc, &stringClass); ani_boolean isString = false; env->Object_InstanceOf(obj, stringClass, &isString); if (isString) { return { true, true }; } + auto fileClassDesc = FS::FileInner::classDesc.c_str(); ani_class fileClass; - env->FindClass("L@ohos/file/fs/FileInner;", &fileClass); + env->FindClass(fileClassDesc, &fileClass); ani_boolean isFile = false; env->Object_InstanceOf(obj, fileClass, &isFile); if (isFile) { @@ -118,8 +134,8 @@ static tuple> ToRafOptions(ani_env *env, return { true, make_optional(move(options)) }; } -static ani_object CreateRandomAccessFileByString(ani_env *env, ani_object file, ani_object mode, - optional op) +static ani_object CreateRandomAccessFileByString( + ani_env *env, ani_object file, ani_object mode, optional op) { auto [succPath, path] = TypeConverter::ToUTF8String(env, static_cast(file)); if (!succPath) { @@ -142,14 +158,16 @@ static ani_object CreateRandomAccessFileByString(ani_env *env, ani_object file, const FsRandomAccessFile *refFile = ret.GetData().value(); auto result = Wrap(env, move(refFile)); if (result == nullptr) { + delete refFile; + refFile = nullptr; ErrorHandler::Throw(env, UNKNOWN_ERR); return nullptr; } return result; } -ani_object CreateRandomAccessFileAni::CreateRandomAccessFileSync(ani_env *env, [[maybe_unused]] ani_class clazz, - ani_object file, ani_object mode, ani_object options) +ani_object CreateRandomAccessFileAni::CreateRandomAccessFileSync( + ani_env *env, [[maybe_unused]] ani_class clazz, ani_object file, ani_object mode, ani_object options) { auto [succOp, op] = ToRafOptions(env, options); if (!succOp) { @@ -185,6 +203,8 @@ ani_object CreateRandomAccessFileAni::CreateRandomAccessFileSync(ani_env *env, [ const FsRandomAccessFile *refFile = ret.GetData().value(); auto result = Wrap(env, move(refFile)); if (result == nullptr) { + delete refFile; + refFile = nullptr; ErrorHandler::Throw(env, UNKNOWN_ERR); return nullptr; } diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/create_stream_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/create_stream_ani.cpp index b8fd35e59b2a16b0ba877b96c815d090b6b07d74..d819834047a9994f0c30a857d5c15eedbb853d77 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/create_stream_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/create_stream_ani.cpp @@ -57,6 +57,8 @@ ani_object CreateStreamAni::CreateStreamSync( const FsStream *stream = ret.GetData().value(); auto result = StreamWrapper::Wrap(env, move(stream)); if (result == nullptr) { + delete stream; + stream = nullptr; ErrorHandler::Throw(env, UNKNOWN_ERR); return nullptr; } 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 8540848a3f65a064ee14969ddb619248aeb6c414..2e81571906504e9d8b65602bd2f10025eeb28173 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 "ani_signature.h" #include "error_handler.h" #include "filemgmt_libhilog.h" #include "listfile_core.h" @@ -27,6 +28,7 @@ namespace ANI { using namespace std; using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; tuple ParseBooleanParam(ani_env *env, ani_object obj, string tag) { @@ -39,9 +41,11 @@ tuple ParseBooleanParam(ani_env *env, ani_object obj, string tag) if (isUndefined) { return { true, false }; } + auto unboxedDesc = BoxedTypes::Boolean::unboxedDesc.c_str(); + auto unboxedSig = BoxedTypes::Boolean::unboxedSig.c_str(); ani_boolean bool_ref_res; if (ANI_OK != env->Object_CallMethodByName_Boolean( - static_cast(bool_ref), "unboxed", ":Z", &bool_ref_res)) { + static_cast(bool_ref), unboxedDesc, unboxedSig, &bool_ref_res)) { return { false, false }; } return { true, static_cast(bool_ref_res) }; @@ -108,10 +112,12 @@ tuple>> ParseArrayString(ani_env *env, ani_object static_cast(result_ref), "length", &length) || length == 0) { return { false, nullopt }; } + auto getterDesc = BuiltInTypes::Array::getterDesc.c_str(); + auto getterSig = BuiltInTypes::Array::objectGetterSig.c_str(); 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)) { + static_cast(result_ref), getterDesc, getterSig, &stringEntryRef, (ani_int)i)) { return { false, nullopt }; } auto [succ, tmp] = TypeConverter::ToUTF8String(env, static_cast(stringEntryRef)); diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/movedir_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/movedir_ani.cpp index e1239cfcac238550f114da14ecc43e078262efec..33bfb77cfeb053b95b2a4b6499ec36202ff7e9a2 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/movedir_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/movedir_ani.cpp @@ -16,6 +16,7 @@ #include "movedir_ani.h" #include +#include "ani_signature.h" #include "error_handler.h" #include "filemgmt_libhilog.h" #include "movedir_core.h" @@ -25,20 +26,23 @@ namespace OHOS { namespace FileManagement { namespace ModuleFileIO { namespace ANI { +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; static tuple ToConflictFiles(ani_env *env, const ErrFiles &files) { - static const char *className = "L@ohos/file/fs/ConflictFilesInner;"; + auto classDesc = FS::ConflictFilesInner::classDesc.c_str(); ani_class cls; ani_status ret; - if ((ret = env->FindClass(className, &cls)) != ANI_OK) { - HILOGE("Cannot find class %{private}s, err: %{private}d", className, ret); + if ((ret = env->FindClass(classDesc, &cls)) != ANI_OK) { + HILOGE("Cannot find class %{private}s, err: %{private}d", classDesc, ret); return { false, nullptr }; } + auto ctorDesc = FS::ConflictFilesInner::ctorDesc.c_str(); + auto ctorSig = FS::ConflictFilesInner::ctorSig.c_str(); ani_method ctor; - if ((ret = env->Class_FindMethod(cls, "", "Lstd/core/String;Lstd/core/String;:V", &ctor)) != ANI_OK) { - HILOGE("Cannot find class %{private}s constructor method, err: %{private}d", className, ret); + if ((ret = env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) != ANI_OK) { + HILOGE("Cannot find class %{private}s constructor method, err: %{private}d", classDesc, ret); return { false, nullptr }; } @@ -69,18 +73,20 @@ static tuple> ToConflictFilesArray( if (!errFiles.has_value()) { return { true, nullopt }; } - static const char *className = "Lescompat/Array;"; + auto classDesc = BuiltInTypes::Array::classDesc.c_str(); ani_class cls = nullptr; ani_status ret; - if ((ret = env->FindClass(className, &cls)) != ANI_OK) { - HILOGE("Cannot find class %{private}s, err: %{private}d", className, ret); + if ((ret = env->FindClass(classDesc, &cls)) != ANI_OK) { + HILOGE("Cannot find class %{private}s, err: %{private}d", classDesc, ret); return { false, nullopt }; } + auto ctorDesc = BuiltInTypes::Array::ctorDesc.c_str(); + auto ctorSig = BuiltInTypes::Array::ctorSig.c_str(); ani_method ctor; - if ((ret = env->Class_FindMethod(cls, "", "I:V", &ctor)) != ANI_OK) { - HILOGE("Cannot find class %{private}s constructor method, err: %{private}d", className, ret); + if ((ret = env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) != ANI_OK) { + HILOGE("Cannot find class %{private}s constructor method, err: %{private}d", classDesc, ret); return { false, nullopt }; } @@ -91,6 +97,8 @@ static tuple> ToConflictFilesArray( return { false, nullopt }; } + auto setterDesc = BuiltInTypes::Array::setterDesc.c_str(); + auto setterSig = BuiltInTypes::Array::objectSetterSig.c_str(); ani_size index = 0; for (const auto &errFile : files) { auto [succ, fileObj] = ToConflictFiles(env, errFile); @@ -98,7 +106,7 @@ static tuple> ToConflictFilesArray( return { false, nullopt }; } - if ((ret = env->Object_CallMethodByName_Void(arr, "$_set", "ILstd/core/Object;:V", index, fileObj)) != ANI_OK) { + if ((ret = env->Object_CallMethodByName_Void(arr, setterDesc, setterSig, index, fileObj)) != ANI_OK) { HILOGE("Add element to Array failed, err: %{private}d", ret); return { false, nullopt }; } @@ -140,6 +148,7 @@ void MoveDirAni::MoveDirSync( return; } } + } // namespace ANI } // namespace ModuleFileIO } // namespace FileManagement 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 68538e0be0086639a7bac8fb7ad2318ab4a6d96e..eceb4b1bd75ca202f1d1cd5d351cf924d782057c 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 @@ -53,6 +53,8 @@ ani_object OpenAni::OpenSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani const FsFile *file = ret.GetData().value(); auto result = FileWrapper::Wrap(env, move(file)); if (result == nullptr) { + delete file; + file = nullptr; ErrorHandler::Throw(env, UNKNOWN_ERR); return nullptr; } 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 7e2fe63ffbc7b70ec7f3a8440f09e9b28a1d32fe..05689d3d79dd010dc42ea4374d4648e08a78b358 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 @@ -91,8 +91,8 @@ ani_string ReadTextAni::ReadTextSync( } const auto &resText = ret.GetData().value(); - string res = std::get<0>(resText); - size_t size = std::get<1>(resText); + string res = std::get<0>(resText); // get buffer + size_t size = std::get<1>(resText); // get buffer length auto [succ, result] = TypeConverter::ToAniString(env, res, size); if (!succ) { HILOGE("Convert result to ani string failed"); diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/watcher_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/watcher_ani.cpp index 04e281ab0f3ab54333cb3b01773603ab58ea85cb..f0641c93f26ae01b8445ad23e2947e524c9c3110 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/watcher_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/watcher_ani.cpp @@ -66,6 +66,8 @@ ani_object WatcherAni::CreateWatcherSync( const FsWatcher *watcher = ret.GetData().value(); auto result = FsWatcherWrapper::Wrap(env, move(watcher)); if (result == nullptr) { + delete watcher; + watcher = nullptr; ErrorHandler::Throw(env, UNKNOWN_ERR); return nullptr; } 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 a87254108e209a06388e25516bac32315abe795e..f20a83917d86ca6b514c7b49fe818bd92c661ae4 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 "ani_signature.h" #include "error_handler.h" #include "filemgmt_libhilog.h" #include "type_converter.h" @@ -28,6 +29,7 @@ namespace ModuleFileIO { namespace ANI { using namespace std; using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; static tuple> ToWriteOptions(ani_env *env, ani_object obj) { @@ -63,8 +65,9 @@ static tuple> ToWriteOptions(ani_env *env, ani_obje static std::tuple ParseStringBuffer(ani_env *env, const ani_object &buf) { + auto classDesc = BuiltInTypes::String::classDesc.c_str(); ani_class cls; - env->FindClass("Lstd/core/String;", &cls); + env->FindClass(classDesc, &cls); ani_boolean isString; env->Object_InstanceOf(buf, cls, &isString); @@ -77,8 +80,9 @@ static std::tuple ParseStringBuffer(ani_env *env, const ani_ob static std::tuple ParseArrayBuffer(ani_env *env, const ani_object &buf) { + auto classDesc = BuiltInTypes::ArrayBuffer::classDesc.c_str(); ani_class cls; - env->FindClass("Lescompat/ArrayBuffer;", &cls); + env->FindClass(classDesc, &cls); ani_boolean isArrayBuffer; env->Object_InstanceOf(buf, cls, &isArrayBuffer); diff --git a/interfaces/kits/js/src/mod_fs/properties/close_core.cpp b/interfaces/kits/js/src/mod_fs/properties/close_core.cpp index 9ac7a784072edf1cec1c148bf8f5c2319064bd50..51f4b68ad1aafcfda4f5be5ab7c291f96bfda7d5 100644 --- a/interfaces/kits/js/src/mod_fs/properties/close_core.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/close_core.cpp @@ -60,4 +60,22 @@ FsResult CloseCore::DoClose(const int32_t &fd) } return FsResult::Success(); } + +FsResult CloseCore::DoClose(FsFile *file) +{ + auto ret = file->GetFD(); + if (!ret.IsSuccess()) { + return FsResult::Error(EINVAL); + } + auto err = CloseFd(ret.GetData().value()); + if (err) { + return FsResult::Error(err); + } + + bool succ = file->RemoveEntity(); + if (!succ) { + return FsResult::Error(EINVAL); + } + return FsResult::Success(); +} } // namespace OHOS::FileManagement::ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fs/properties/close_core.h b/interfaces/kits/js/src/mod_fs/properties/close_core.h index 1bbdd1c3194b641e5d26a5f02ca94f479aeaeab8..3b54ca4c5717cc310e7c94997dce9fe23e1571aa 100644 --- a/interfaces/kits/js/src/mod_fs/properties/close_core.h +++ b/interfaces/kits/js/src/mod_fs/properties/close_core.h @@ -17,6 +17,7 @@ #define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_CLOSE_CORE_H #include "filemgmt_libfs.h" +#include "fs_file.h" #include "fs_utils.h" #include "fs_result.h" @@ -25,6 +26,7 @@ namespace OHOS::FileManagement::ModuleFileIO { class CloseCore final { public: static FsResult DoClose(const int32_t &fd); + static FsResult DoClose(FsFile *file); }; const std::string PROCEDURE_CLOSE_NAME = "FileIOClose"; 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 d93492ac71a06f730371028b6bbe0f76f5a01e55..9edb9abefa382ab207f90b9c032d56c684df9034 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 @@ -14,19 +14,20 @@ */ #include +#include "ani_signature.h" #include "bind_function.h" #include "hash_ani.h" using namespace OHOS::FileManagement::ModuleFileIO::ANI; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; static ani_status BindStaticMethods(ani_env *env) { - static const char *className = "L@ohos/file/hash/HashImpl;"; + auto classDesc = Impl::HashImpl::classDesc.c_str(); std::array methods = { - ani_native_function { "hashSync", "Lstd/core/String;Lstd/core/String;:Lstd/core/String;", - reinterpret_cast(HashAni::HashSync) }, + ani_native_function { "hashSync", nullptr, reinterpret_cast(HashAni::HashSync) }, }; - return BindClass(env, className, methods); + return BindClass(env, classDesc, methods); } ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) diff --git a/interfaces/kits/js/src/mod_hash/ani/ets/@ohos.file.hash.ets b/interfaces/kits/js/src/mod_hash/ani/ets/@ohos.file.hash.ets index 3c4fd40dcd7028c67d7ef84e3438cda5a921514c..dfa16ab00530db92e6dc328c889cb035d50080d4 100644 --- a/interfaces/kits/js/src/mod_hash/ani/ets/@ohos.file.hash.ets +++ b/interfaces/kits/js/src/mod_hash/ani/ets/@ohos.file.hash.ets @@ -86,7 +86,7 @@ export default namespace hash { class HashImpl { static { - loadLibrary("ani_hash_class"); + loadLibrary("ani_file_hash"); } static native hashSync(path: string, algorithm: string): string; 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 5bb0f2650cfb3291dd34e0fce1f212a4d9bc25e7..947e460b65992a5ec8c5042a6dd205d03ef42c56 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 @@ -14,21 +14,23 @@ */ #include +#include "ani_signature.h" #include "bind_function.h" #include "securitylabel_ani.h" using namespace OHOS::FileManagement::ModuleFileIO::ANI; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; static ani_status BindStaticMethods(ani_env *env) { - static const char *className = "L@ohos/file/securityLabel/SecurityLabelImpl;"; + auto classDesc = Impl::SecurityLabelImpl::classDesc.c_str(); std::array methods = { - ani_native_function { "setSecurityLabelSync", "Lstd/core/String;Lstd/core/String;:V", - reinterpret_cast(SecurityLabelAni::SetSecurityLabelSync) }, - ani_native_function { "getSecurityLabelSync", "Lstd/core/String;:Lstd/core/String;", - reinterpret_cast(SecurityLabelAni::GetSecurityLabelSync) }, + ani_native_function { + "setSecurityLabelSync", nullptr, reinterpret_cast(SecurityLabelAni::SetSecurityLabelSync) }, + ani_native_function { + "getSecurityLabelSync", nullptr, reinterpret_cast(SecurityLabelAni::GetSecurityLabelSync) }, }; - return BindClass(env, className, methods); + return BindClass(env, classDesc, methods); } ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) diff --git a/interfaces/kits/js/src/mod_securitylabel/ani/ets/@ohos.file.securityLabel.ets b/interfaces/kits/js/src/mod_securitylabel/ani/ets/@ohos.file.securityLabel.ets index b4268c6118846a602353c671ca9f86575dfea30e..06e659dc275ae1890e009c02fc830bd8e766dbea 100644 --- a/interfaces/kits/js/src/mod_securitylabel/ani/ets/@ohos.file.securityLabel.ets +++ b/interfaces/kits/js/src/mod_securitylabel/ani/ets/@ohos.file.securityLabel.ets @@ -78,7 +78,7 @@ export default securityLabel; class SecurityLabelImpl { static { - loadLibrary("ani_securitylabel_class"); + loadLibrary("ani_file_securitylabel"); } static native setSecurityLabelSync(path: string, type: securityLabel.DataLevel): void; diff --git a/interfaces/kits/js/src/mod_statvfs/ani/bind_function_class.cpp b/interfaces/kits/js/src/mod_statvfs/ani/bind_function_class.cpp new file mode 100644 index 0000000000000000000000000000000000000000..33782a3d10d71c8cde2bfce292e4caddfb0637ff --- /dev/null +++ b/interfaces/kits/js/src/mod_statvfs/ani/bind_function_class.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "ani_signature.h" +#include "bind_function.h" +#include "statvfs_ani.h" + +using namespace OHOS::FileManagement::ModuleFileIO::ANI; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +static ani_status BindStaticMethods(ani_env *env) +{ + auto classDesc = Impl::StatvfsImpl::classDesc.c_str(); + + std::array methods = { + ani_native_function { "getFreeSizeSync", nullptr, reinterpret_cast(StatvfsAni::GetFreeSizeSync) }, + ani_native_function { "getTotalSizeSync", nullptr, reinterpret_cast(StatvfsAni::GetTotalSizeSync) }, + }; + return BindClass(env, classDesc, 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; + } + + if ((status = BindStaticMethods(env)) != ANI_OK) { + HILOGE("Cannot bind native static methods for statvfs!"); + return status; + }; + + *result = ANI_VERSION_1; + return ANI_OK; +} \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_statvfs/ani/ets/@ohos.file.statvfs.ets b/interfaces/kits/js/src/mod_statvfs/ani/ets/@ohos.file.statvfs.ets new file mode 100644 index 0000000000000000000000000000000000000000..831bc046d4a4836e2a9652147f047c8e00a7f76d --- /dev/null +++ b/interfaces/kits/js/src/mod_statvfs/ani/ets/@ohos.file.statvfs.ets @@ -0,0 +1,86 @@ +/* + * 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'; + +namespace statfs { + export function getFreeSizeSync(path: string): number { + return StatvfsImpl.getFreeSizeSync(path); + } + + export function getFreeSize(path: string): Promise { + return new Promise((resolve: (result: number) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute(StatvfsImpl.getFreeSizeSync, path); + promise.then((ret: NullishType): void => { + let result = ret as number + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); + } + + export function getFreeSize(path: string, callback: AsyncCallback): void { + let promise = taskpool.execute(StatvfsImpl.getFreeSizeSync, path); + 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); + }); + } + + export function getTotalSizeSync(path: string): number { + return StatvfsImpl.getTotalSizeSync(path); + } + + export function getTotalSize(path: string): Promise { + return new Promise((resolve: (result: number) => void, reject: (e: BusinessError) => void): void => { + let promise = taskpool.execute(StatvfsImpl.getTotalSizeSync, path); + promise.then((ret: NullishType): void => { + let result = ret as number + resolve(result); + }).catch((e: BusinessError): void => { + reject(e); + }); + }); + } + + export function getTotalSize(path: string, callback: AsyncCallback): void { + let promise = taskpool.execute(StatvfsImpl.getTotalSizeSync, path); + 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); + }); + } +} + +export default statfs; + +class StatvfsImpl { + + static { + loadLibrary("ani_file_statvfs"); + } + + static native getFreeSizeSync(path: string): number; + static native getTotalSizeSync(path: string): number; +} \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_statvfs/ani/statvfs_ani.cpp b/interfaces/kits/js/src/mod_statvfs/ani/statvfs_ani.cpp new file mode 100644 index 0000000000000000000000000000000000000000..337b78f84341de0d691d1a3b49b3ebb827069bbd --- /dev/null +++ b/interfaces/kits/js/src/mod_statvfs/ani/statvfs_ani.cpp @@ -0,0 +1,75 @@ +/* + * 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 "statvfs_ani.h" + +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "statvfs_core.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleStatvfs; + +ani_double StatvfsAni::GetFreeSizeSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path) +{ + auto [succPath, srcPath] = TypeConverter::ToUTF8String(env, path); + if (!succPath) { + HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); + return 0; + } + + auto ret = StatvfsCore::DoGetFreeSize(srcPath); + if (!ret.IsSuccess()) { + HILOGE("Get freesize failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return 0; + } + + return static_cast(ret.GetData().value()); +} + +ani_double StatvfsAni::GetTotalSizeSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path) +{ + auto [succPath, srcPath] = TypeConverter::ToUTF8String(env, path); + if (!succPath) { + HILOGE("Invalid path"); + ErrorHandler::Throw(env, EINVAL); + return 0; + } + + auto ret = StatvfsCore::DoGetTotalSize(srcPath); + if (!ret.IsSuccess()) { + HILOGE("Get totalsize failed"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); + return 0; + } + + return static_cast(ret.GetData().value()); +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_statvfs/ani/statvfs_ani.h b/interfaces/kits/js/src/mod_statvfs/ani/statvfs_ani.h new file mode 100644 index 0000000000000000000000000000000000000000..1eaf5081fdaf1c43002634d1e70e7face2f3673a --- /dev/null +++ b/interfaces/kits/js/src/mod_statvfs/ani/statvfs_ani.h @@ -0,0 +1,37 @@ +/* + * 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 INTERFACES_KITS_JS_SRC_MOD_STATVFS_ANI_STATVFS_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_STATVFS_ANI_STATVFS_ANI_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class StatvfsAni final { +public: + static ani_double GetFreeSizeSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path); + static ani_double GetTotalSizeSync(ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_KITS_JS_SRC_MOD_STATVFS_ANI_STATVFS_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_statvfs/statvfs_core.cpp b/interfaces/kits/js/src/mod_statvfs/statvfs_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a9aa9db682784dcadb84e1510f6cca574ff90bf --- /dev/null +++ b/interfaces/kits/js/src/mod_statvfs/statvfs_core.cpp @@ -0,0 +1,52 @@ +/* + * 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 "statvfs_core.h" + +#include +#include "filemgmt_libhilog.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleStatvfs { +using namespace std; + +FsResult StatvfsCore::DoGetFreeSize(const string &path) +{ + struct statvfs diskInfo; + int ret = statvfs(path.c_str(), &diskInfo); + if (ret != 0) { + return FsResult::Error(errno); + } + unsigned long long freeSize = static_cast(diskInfo.f_bsize) * + static_cast(diskInfo.f_bfree); + return FsResult::Success(static_cast(freeSize)); +} + +FsResult StatvfsCore::DoGetTotalSize(const string &path) +{ + struct statvfs diskInfo; + int ret = statvfs(path.c_str(), &diskInfo); + if (ret != 0) { + return FsResult::Error(errno); + } + unsigned long long totalSize = static_cast(diskInfo.f_bsize) * + static_cast(diskInfo.f_blocks); + return FsResult::Success(static_cast(totalSize)); +} + +} // namespace ModuleStatfs +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_statvfs/statvfs_core.h b/interfaces/kits/js/src/mod_statvfs/statvfs_core.h new file mode 100644 index 0000000000000000000000000000000000000000..24817f3eb8a6cdb91c7604b74ba28eea33e711e1 --- /dev/null +++ b/interfaces/kits/js/src/mod_statvfs/statvfs_core.h @@ -0,0 +1,35 @@ +/* + * 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 INTERFACES_KITS_JS_SRC_MOD_STATVFS_STATVFS_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_STATVFS_STATVFS_CORE_H + +#include "filemgmt_libfs.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleStatvfs { +using namespace ModuleFileIO; + +class StatvfsCore final { +public: + static FsResult DoGetFreeSize(const string &path); + static FsResult DoGetTotalSize(const string &path); +}; + +} // namespace ModuleStatvfs +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_STATVFS_STATVFS_CORE_H \ No newline at end of file