axlibc/
fs.rs

1use core::ffi::{c_char, c_int};
2
3use arceos_posix_api::{
4    sys_fstat, sys_getcwd, sys_lseek, sys_lstat, sys_open, sys_rename, sys_stat,
5};
6
7use crate::{ctypes, utils::e};
8
9/// Open a file by `filename` and insert it into the file descriptor table.
10///
11/// Return its index in the file table (`fd`). Return `EMFILE` if it already
12/// has the maximum number of files open.
13#[unsafe(no_mangle)]
14pub unsafe extern "C" fn ax_open(
15    filename: *const c_char,
16    flags: c_int,
17    mode: ctypes::mode_t,
18) -> c_int {
19    e(sys_open(filename, flags, mode))
20}
21
22/// Set the position of the file indicated by `fd`.
23///
24/// Return its position after seek.
25#[unsafe(no_mangle)]
26pub unsafe extern "C" fn lseek(fd: c_int, offset: ctypes::off_t, whence: c_int) -> ctypes::off_t {
27    e(sys_lseek(fd, offset, whence) as _) as _
28}
29
30/// Get the file metadata by `path` and write into `buf`.
31///
32/// Return 0 if success.
33#[unsafe(no_mangle)]
34pub unsafe extern "C" fn stat(path: *const c_char, buf: *mut ctypes::stat) -> c_int {
35    e(sys_stat(path, buf))
36}
37
38/// Get file metadata by `fd` and write into `buf`.
39///
40/// Return 0 if success.
41#[unsafe(no_mangle)]
42pub unsafe extern "C" fn fstat(fd: c_int, buf: *mut ctypes::stat) -> c_int {
43    e(sys_fstat(fd, buf))
44}
45
46/// Get the metadata of the symbolic link and write into `buf`.
47///
48/// Return 0 if success.
49#[unsafe(no_mangle)]
50pub unsafe extern "C" fn lstat(path: *const c_char, buf: *mut ctypes::stat) -> c_int {
51    e(sys_lstat(path, buf) as _)
52}
53
54/// Get the path of the current directory.
55#[unsafe(no_mangle)]
56pub unsafe extern "C" fn getcwd(buf: *mut c_char, size: usize) -> *mut c_char {
57    sys_getcwd(buf, size)
58}
59
60/// Rename `old` to `new`
61/// If new exists, it is first removed.
62///
63/// Return 0 if the operation succeeds, otherwise return -1.
64#[unsafe(no_mangle)]
65pub unsafe extern "C" fn rename(old: *const c_char, new: *const c_char) -> c_int {
66    e(sys_rename(old, new))
67}