|
| 1 | +/* |
| 2 | + * Copyright (c) 2024 Tenstorrent AI ULC |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +#include "stdio-bufio.h" |
| 8 | + |
| 9 | +#include <stddef.h> |
| 10 | +#include <stdio.h> |
| 11 | +#include <stdlib.h> |
| 12 | + |
| 13 | +#include <zephyr/sys/fdtable.h> |
| 14 | +#include <zephyr/toolchain.h> |
| 15 | + |
| 16 | +BUILD_ASSERT(CONFIG_ZVFS_LIBC_FILE_SIZE == sizeof(struct __file_bufio), |
| 17 | + "CONFIG_ZVFS_LIBC_FILE_SIZE must match size of FILE object"); |
| 18 | +BUILD_ASSERT(CONFIG_ZVFS_LIBC_FILE_ALIGN == __alignof(struct __file_bufio), |
| 19 | + "CONFIG_ZVFS_LIBC_FILE_SIZE must match alignment of FILE object"); |
| 20 | + |
| 21 | +#define FDEV_SETUP_ZVFS(fd, buf, size, rwflags, bflags) \ |
| 22 | + FDEV_SETUP_BUFIO(fd, buf, size, zvfs_read_wrap, zvfs_write_wrap, zvfs_lseek, zvfs_close, \ |
| 23 | + rwflags, bflags) |
| 24 | + |
| 25 | +int __posix_sflags(const char *mode, int *optr); |
| 26 | + |
| 27 | +/* FIXME: do not use ssize_t or off_t */ |
| 28 | +ssize_t zvfs_read(int fd, void *buf, size_t sz, const size_t *from_offset); |
| 29 | +ssize_t zvfs_write(int fd, const void *buf, size_t sz, const size_t *from_offset); |
| 30 | +off_t zvfs_lseek(int fd, off_t offset, int whence); |
| 31 | +int zvfs_close(int fd); |
| 32 | + |
| 33 | +static ssize_t zvfs_read_wrap(int fd, void *buf, size_t sz) |
| 34 | +{ |
| 35 | + return zvfs_read(fd, buf, sz, NULL); |
| 36 | +} |
| 37 | + |
| 38 | +static ssize_t zvfs_write_wrap(int fd, const void *buf, size_t sz) |
| 39 | +{ |
| 40 | + return zvfs_write(fd, buf, sz, NULL); |
| 41 | +} |
| 42 | + |
| 43 | +void zvfs_libc_file_alloc_cb(int fd, const char *mode, FILE *fp) |
| 44 | +{ |
| 45 | + struct __file_bufio *const bf = (struct __file_bufio *)fp; |
| 46 | + int __maybe_unused unused; |
| 47 | + |
| 48 | + *bf = (struct __file_bufio)FDEV_SETUP_ZVFS(fd, (char *)(bf + 1), BUFSIZ, |
| 49 | + __posix_sflags(mode, &unused), __BFALL); |
| 50 | + |
| 51 | + __bufio_lock_init(&(bf->xfile.cfile.file)); |
| 52 | +} |
| 53 | + |
| 54 | +int zvfs_libc_file_get_fd(FILE *fp) |
| 55 | +{ |
| 56 | + const struct __file_bufio *const bf = (const struct __file_bufio *)fp; |
| 57 | + |
| 58 | + return POINTER_TO_INT(bf->ptr); |
| 59 | +} |
0 commit comments