wasmer_wasix/syscalls/wasix/
chdir.rs

1use super::*;
2use crate::syscalls::*;
3
4/// ### `chdir()`
5/// Sets the current working directory
6#[instrument(level = "trace", skip_all, fields(name = field::Empty), ret)]
7pub fn chdir<M: MemorySize>(
8    mut ctx: FunctionEnvMut<'_, WasiEnv>,
9    path: WasmPtr<u8, M>,
10    path_len: M::Offset,
11) -> Result<Errno, WasiError> {
12    WasiEnv::do_pending_operations(&mut ctx)?;
13
14    let env = ctx.data();
15    let (memory, mut state) = unsafe { env.get_memory_and_wasi_state(&ctx, 0) };
16    let path = unsafe { get_input_str_ok!(&memory, path, path_len) };
17    Span::current().record("path", path.as_str());
18
19    wasi_try_ok!(chdir_internal(ctx.data(), &path));
20    let env = ctx.data();
21
22    #[cfg(feature = "journal")]
23    if env.enable_journal {
24        JournalEffector::save_chdir(&mut ctx, path).map_err(|err| {
25            tracing::error!("failed to chdir event - {}", err);
26            WasiError::Exit(ExitCode::from(Errno::Fault))
27        })?;
28    }
29
30    Ok(Errno::Success)
31}
32
33pub fn chdir_internal(env: &WasiEnv, path: &str) -> Result<(), Errno> {
34    let state = &env.state;
35
36    // Check if the directory exists
37    if state.fs.root_fs.read_dir(Path::new(path)).is_err() {
38        return Err(Errno::Noent);
39    }
40
41    state.fs.set_current_dir(path);
42    Ok(())
43}