1 /*
2 * Copyright 2024 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <cutils/log.h>
18 #include <lib/zxio/zxio.h>
19 #include <services/service_connector.h>
20 #include <string.h>
21
22 #include "os_dirent.h"
23
24 struct os_dir {
~os_diros_dir25 ~os_dir() {
26 if (dir_iterator_init_) {
27 zxio_dirent_iterator_destroy(&iterator_);
28 }
29 if (zxio_init_) {
30 zxio_close(&io_storage_.io, /*should_wait=*/true);
31 }
32 }
33
34 // Always consumes |dir_channel|
Initos_dir35 bool Init(zx_handle_t dir_channel) {
36 zx_status_t status = zxio_create(dir_channel, &io_storage_);
37 if (status != ZX_OK) {
38 ALOGE("zxio_create failed: %d", status);
39 return false;
40 }
41
42 zxio_init_ = true;
43
44 status = zxio_dirent_iterator_init(&iterator_, &io_storage_.io);
45 if (status != ZX_OK) {
46 ALOGE("zxio_dirent_iterator_init failed: %d", status);
47 return false;
48 }
49
50 dir_iterator_init_ = true;
51 return true;
52 }
53
Nextos_dir54 bool Next(struct os_dirent* entry) {
55 // dirent is an in-out parameter.
56 // name must be initialized to point to a buffer of at least ZXIO_MAX_FILENAME bytes.
57 static_assert(sizeof(entry->d_name) >= ZXIO_MAX_FILENAME);
58 zxio_dirent_t dirent = {.name = entry->d_name};
59
60 zx_status_t status = zxio_dirent_iterator_next(&iterator_, &dirent);
61 if (status != ZX_OK) {
62 if (status != ZX_ERR_NOT_FOUND) ALOGE("zxio_dirent_iterator_next failed: %d", status);
63 return false;
64 }
65
66 entry->d_ino = dirent.has.id ? dirent.id : OS_INO_UNKNOWN;
67 entry->d_name[dirent.name_length] = '\0';
68
69 return true;
70 }
71
72 private:
73 bool zxio_init_ = false;
74 bool dir_iterator_init_ = false;
75 zxio_storage_t io_storage_;
76 zxio_dirent_iterator_t iterator_;
77 };
78
os_opendir(const char * path)79 os_dir_t* os_opendir(const char* path) {
80 zx_handle_t dir_channel = GetConnectToServiceFunction()(path);
81 if (dir_channel == ZX_HANDLE_INVALID) {
82 ALOGE("fuchsia_open(%s) failed", path);
83 return nullptr;
84 }
85
86 auto dir = new os_dir();
87
88 if (!dir->Init(dir_channel)) {
89 delete dir;
90 return nullptr;
91 }
92
93 return dir;
94 }
95
os_closedir(os_dir_t * dir)96 int os_closedir(os_dir_t* dir) {
97 delete dir;
98 return 0;
99 }
100
os_readdir(os_dir_t * dir)101 struct os_dirent* os_readdir(os_dir_t* dir) {
102 static struct os_dirent dirent = {};
103 return reinterpret_cast<os_dirent*>(dir->Next(&dirent)) ? &dirent : nullptr;
104 }
105