]> git.proxmox.com Git - wasi-libc.git/blob - libc-bottom-half/cloudlibc/src/libc/dirent/fdopendir.c
Remove __wasilibc_unmodified_upstream markers from libc-bottom-half.
[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 // TODO: Remove the cast on `dirp->buffer` once the witx is updated with char8 support.
29 __wasi_fd_readdir(fd, (uint8_t *)dirp->buffer, DIRENT_DEFAULT_BUFFER_SIZE,
30 __WASI_DIRCOOKIE_START, &dirp->buffer_used);
31 if (error != 0) {
32 free(dirp->buffer);
33 free(dirp);
34 errno = errno_fixup_directory(fd, error);
35 return NULL;
36 }
37
38 // Initialize other members.
39 dirp->fd = fd;
40 dirp->cookie = __WASI_DIRCOOKIE_START;
41 dirp->buffer_processed = 0;
42 dirp->buffer_size = DIRENT_DEFAULT_BUFFER_SIZE;
43 dirp->dirent = NULL;
44 dirp->dirent_size = 1;
45 return dirp;
46 }