|
| 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 | + |
| 15 | +#define FDEV_SETUP_ZVFS(fd, buf, size, rwflags, bflags) \ |
| 16 | + FDEV_SETUP_BUFIO(fd, buf, size, zvfs_read_wrap, zvfs_write_wrap, zvfs_lseek, zvfs_close, \ |
| 17 | + rwflags, bflags) |
| 18 | + |
| 19 | +int __posix_sflags(const char *mode, int *optr); |
| 20 | + |
| 21 | +/* FIXME: do not use ssize_t or off_t */ |
| 22 | +ssize_t zvfs_read(int fd, void *buf, size_t sz, const size_t *from_offset); |
| 23 | +ssize_t zvfs_write(int fd, const void *buf, size_t sz, const size_t *from_offset); |
| 24 | +off_t zvfs_lseek(int fd, off_t offset, int whence); |
| 25 | +int zvfs_close(int fd); |
| 26 | + |
| 27 | +static ssize_t zvfs_read_wrap(int fd, void *buf, size_t sz) |
| 28 | +{ |
| 29 | + return zvfs_read(fd, buf, sz, NULL); |
| 30 | +} |
| 31 | + |
| 32 | +static ssize_t zvfs_write_wrap(int fd, const void *buf, size_t sz) |
| 33 | +{ |
| 34 | + return zvfs_write(fd, buf, sz, NULL); |
| 35 | +} |
| 36 | + |
| 37 | +FILE *z_libc_file_alloc(int fd, const char *mode) |
| 38 | +{ |
| 39 | + struct __file_bufio *bf; |
| 40 | + int __maybe_unused unused; |
| 41 | + |
| 42 | + bf = calloc(1, sizeof(struct __file_bufio) + BUFSIZ); |
| 43 | + if (bf == NULL) { |
| 44 | + return NULL; |
| 45 | + } |
| 46 | + |
| 47 | + *bf = (struct __file_bufio)FDEV_SETUP_ZVFS(fd, (char *)(bf + 1), BUFSIZ, |
| 48 | + __posix_sflags(mode, &unused), __BFALL); |
| 49 | + |
| 50 | + __bufio_lock_init(&(bf->xfile.cfile.file)); |
| 51 | + |
| 52 | + return &(bf->xfile.cfile.file); |
| 53 | +} |
| 54 | + |
| 55 | +int z_libc_file_get_fd(const FILE *fp) |
| 56 | +{ |
| 57 | + const struct __file_bufio *const bf = (const struct __file_bufio *)fp; |
| 58 | + |
| 59 | + return POINTER_TO_INT(bf->ptr); |
| 60 | +} |
0 commit comments