1 /*
2 * Copyright (c) 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "file_instantiator.h"
17
18 #include "file_entity.h"
19 #include "file_utils.h"
20 #include "filemgmt_libhilog.h"
21
22 namespace OHOS {
23 namespace FileManagement {
24 namespace ModuleFileIO {
25 using namespace std;
26 using namespace OHOS::DistributedFS;
27
InstantiateFile(int fd,string pathOrUri,bool isUri)28 FsResult<FsFile *> FileInstantiator::InstantiateFile(int fd, string pathOrUri, bool isUri)
29 {
30 FsResult<FsFile *> result = FsFile::Constructor();
31 if (!result.IsSuccess()) {
32 HILOGE("Failed to instantiate class");
33 int ret = close(fd);
34 if (ret < 0) {
35 HILOGE("Failed to close fd");
36 }
37 return FsResult<FsFile *>::Error(EIO);
38 }
39
40 const FsFile *objFile = result.GetData().value();
41 if (!objFile) {
42 HILOGE("Failed to get fsFile");
43 int ret = close(fd);
44 if (ret < 0) {
45 HILOGE("Failed to close fd");
46 }
47 return FsResult<FsFile *>::Error(EIO);
48 }
49
50 auto *fileEntity = objFile->GetFileEntity();
51 if (!fileEntity) {
52 HILOGE("Failed to get fileEntity");
53 int ret = close(fd);
54 if (ret < 0) {
55 HILOGE("Failed to close fd");
56 }
57 delete objFile;
58 objFile = nullptr;
59 return FsResult<FsFile *>::Error(EIO);
60 }
61
62 auto fdg = CreateUniquePtr<DistributedFS::FDGuard>(fd, false);
63 if (fdg == nullptr) {
64 HILOGE("Failed to request heap memory.");
65 close(fd);
66 delete objFile;
67 objFile = nullptr;
68 return FsResult<FsFile *>::Error(ENOMEM);
69 }
70 fileEntity->fd_.swap(fdg);
71 if (isUri) {
72 fileEntity->path_ = "";
73 fileEntity->uri_ = pathOrUri;
74 } else {
75 fileEntity->path_ = pathOrUri;
76 fileEntity->uri_ = "";
77 }
78 return result;
79 }
80
81 } // namespace ModuleFileIO
82 } // namespace FileManagement
83 } // namespace OHOS