]> git.proxmox.com Git - wasi-libc.git/blob - libc-bottom-half/cloudlibc/src/libc/dirent/fdopendir.c
Wasi snapshot preview1 (#140)
[wasi-libc.git] / libc-bottom-half / cloudlibc / src / libc / dirent / fdopendir.c
1 // Copyright (c) 2015-2016 Nuxi, https://nuxi.nl/
2 //
3 // SPDX-License-Identifier: BSD-2-Clause
4
5 #include <common/errno.h>
6
7 #include <wasi/api.h>
8 #include <dirent.h>
9 #include <errno.h>
10 #include <stdlib.h>
11
12 #include "dirent_impl.h"
13
14 DIR *fdopendir(int fd) {
15 // Allocate new directory object and read buffer.
16 DIR *dirp = malloc(sizeof(*dirp));
17 if (dirp == NULL)
18 return NULL;
19 dirp->buffer = malloc(DIRENT_DEFAULT_BUFFER_SIZE);
20 if (dirp->buffer == NULL) {
21 free(dirp);
22 return NULL;
23 }
24
25 // Ensure that this is really a directory by already loading the first
26 // chunk of data.
27 __wasi_errno_t error =
28 #ifdef __wasilibc_unmodified_upstream
29 __wasi_file_readdir(fd, dirp->buffer, DIRENT_DEFAULT_BUFFER_SIZE,
30 #else
31 // TODO: Remove the cast on `dirp->buffer` once the witx is updated with char8 support.
32 __wasi_fd_readdir(fd, (uint8_t *)dirp->buffer, DIRENT_DEFAULT_BUFFER_SIZE,
33 #endif
34 __WASI_DIRCOOKIE_START, &dirp->buffer_used);
35 if (error != 0) {
36 free(dirp->buffer);
37 free(dirp);
38 errno = errno_fixup_directory(fd, error);
39 return NULL;
40 }
41
42 // Initialize other members.
43 dirp->fd = fd;
44 dirp->cookie = __WASI_DIRCOOKIE_START;
45 dirp->buffer_processed = 0;
46 dirp->buffer_size = DIRENT_DEFAULT_BUFFER_SIZE;
47 dirp->dirent = NULL;
48 dirp->dirent_size = 1;
49 return dirp;
50 }