wasmer_wasix/syscalls/wasi/
path_rename.rs1use std::path::PathBuf;
2
3use anyhow::Context;
4
5use super::*;
6use crate::syscalls::*;
7
8#[instrument(level = "trace", skip_all, fields(%old_fd, %new_fd, old_path = field::Empty, new_path = field::Empty), ret)]
24pub fn path_rename<M: MemorySize>(
25 mut ctx: FunctionEnvMut<'_, WasiEnv>,
26 old_fd: WasiFd,
27 old_path: WasmPtr<u8, M>,
28 old_path_len: M::Offset,
29 new_fd: WasiFd,
30 new_path: WasmPtr<u8, M>,
31 new_path_len: M::Offset,
32) -> Result<Errno, WasiError> {
33 WasiEnv::do_pending_operations(&mut ctx)?;
34
35 let env = ctx.data();
36 let (memory, mut state, inodes) = unsafe { env.get_memory_and_wasi_state_and_inodes(&ctx, 0) };
37 let source_str = unsafe { get_input_str_ok!(&memory, old_path, old_path_len) };
38 Span::current().record("old_path", source_str.as_str());
39 let target_str = unsafe { get_input_str_ok!(&memory, new_path, new_path_len) };
40 Span::current().record("new_path", target_str.as_str());
41
42 let ret = path_rename_internal(&mut ctx, old_fd, &source_str, new_fd, &target_str)?;
43 let env = ctx.data();
44
45 if ret == Errno::Success {
46 #[cfg(feature = "journal")]
47 if env.enable_journal {
48 JournalEffector::save_path_rename(&mut ctx, old_fd, source_str, new_fd, target_str)
49 .map_err(|err| {
50 tracing::error!("failed to save path rename event - {}", err);
51 WasiError::Exit(ExitCode::from(Errno::Fault))
52 })?;
53 }
54 }
55 Ok(ret)
56}
57
58pub fn path_rename_internal(
59 ctx: &mut FunctionEnvMut<'_, WasiEnv>,
60 source_fd: WasiFd,
61 source_path: &str,
62 target_fd: WasiFd,
63 target_path: &str,
64) -> Result<Errno, WasiError> {
65 let env = ctx.data();
66 let (memory, mut state, inodes) = unsafe { env.get_memory_and_wasi_state_and_inodes(&ctx, 0) };
67
68 {
69 let source_fd = wasi_try_ok!(state.fs.get_fd(source_fd));
70 if !source_fd.inner.rights.contains(Rights::PATH_RENAME_SOURCE) {
71 return Ok(Errno::Access);
72 }
73 let target_fd = wasi_try_ok!(state.fs.get_fd(target_fd));
74 if !target_fd.inner.rights.contains(Rights::PATH_RENAME_TARGET) {
75 return Ok(Errno::Access);
76 }
77 }
78
79 wasi_try_ok!(
81 state
82 .fs
83 .get_inode_at_path(inodes, source_fd, source_path, true)
84 );
85 let _ = state
87 .fs
88 .get_inode_at_path(inodes, target_fd, target_path, true);
89 let (source_parent_inode, source_entry_name) = wasi_try_ok!(state.fs.get_parent_inode_at_path(
90 inodes,
91 source_fd,
92 Path::new(source_path),
93 true
94 ));
95 let (target_parent_inode, target_entry_name) = wasi_try_ok!(state.fs.get_parent_inode_at_path(
96 inodes,
97 target_fd,
98 Path::new(target_path),
99 true
100 ));
101 let host_adjusted_source_path = {
102 let guard = source_parent_inode.read();
103 match guard.deref() {
104 Kind::Dir { path, .. } => path.join(&source_entry_name),
105 Kind::Root { .. } => return Ok(Errno::Notcapable),
106 Kind::Socket { .. }
107 | Kind::PipeTx { .. }
108 | Kind::PipeRx { .. }
109 | Kind::DuplexPipe { .. }
110 | Kind::EventNotifications { .. }
111 | Kind::Epoll { .. } => return Ok(Errno::Inval),
112 Kind::Symlink { .. } | Kind::File { .. } | Kind::Buffer { .. } => {
113 debug!("fatal internal logic error: parent of inode is not a directory");
114 return Ok(Errno::Inval);
115 }
116 }
117 };
118 let mut need_create = true;
119 let host_adjusted_target_path = {
120 let guard = target_parent_inode.read();
121 match guard.deref() {
122 Kind::Dir { entries, path, .. } => {
123 if entries.contains_key(&target_entry_name) {
124 need_create = false;
125 }
126 path.join(&target_entry_name)
127 }
128 Kind::Root { .. } => return Ok(Errno::Notcapable),
129 Kind::Socket { .. }
130 | Kind::PipeTx { .. }
131 | Kind::PipeRx { .. }
132 | Kind::DuplexPipe { .. }
133 | Kind::EventNotifications { .. }
134 | Kind::Epoll { .. } => return Ok(Errno::Inval),
135 Kind::Symlink { .. } | Kind::File { .. } | Kind::Buffer { .. } => {
136 debug!("fatal internal logic error: parent of inode is not a directory");
137 return Ok(Errno::Inval);
138 }
139 }
140 };
141
142 let source_entry = {
143 let mut guard = source_parent_inode.write();
144 match guard.deref_mut() {
145 Kind::Dir { entries, .. } => {
146 wasi_try_ok!(entries.remove(&source_entry_name).ok_or(Errno::Noent))
147 }
148 Kind::Root { .. } => return Ok(Errno::Notcapable),
149 Kind::Socket { .. }
150 | Kind::PipeRx { .. }
151 | Kind::PipeTx { .. }
152 | Kind::DuplexPipe { .. }
153 | Kind::EventNotifications { .. }
154 | Kind::Epoll { .. } => {
155 return Ok(Errno::Inval);
156 }
157 Kind::Symlink { .. } | Kind::File { .. } | Kind::Buffer { .. } => {
158 debug!("fatal internal logic error: parent of inode is not a directory");
159 return Ok(Errno::Inval);
160 }
161 }
162 };
163
164 {
165 let mut guard = source_entry.write();
166 match guard.deref_mut() {
167 Kind::File { path, .. } => {
168 let result = {
169 let path_clone = path.clone();
170 drop(guard);
171 let state = state;
172 let host_adjusted_target_path = host_adjusted_target_path.clone();
173 __asyncify_light(env, None, async move {
174 state
175 .fs_rename(path_clone, &host_adjusted_target_path)
176 .await
177 })?
178 };
179 if let Err(e) = result {
181 let mut guard = source_parent_inode.write();
182 if let Kind::Dir { entries, .. } = guard.deref_mut() {
183 entries.insert(source_entry_name, source_entry);
184 return Ok(e);
185 }
186 } else {
187 let mut guard = source_entry.write();
188 if let Kind::File { path, .. } = guard.deref_mut() {
189 *path = host_adjusted_target_path.clone();
190 } else {
191 unreachable!()
192 }
193 }
194 }
195 Kind::Dir { path, .. } => {
196 let cloned_path = path.clone();
197 let res = {
198 let state = state;
199 let host_adjusted_target_path = host_adjusted_target_path.clone();
200 __asyncify_light(env, None, async move {
201 state
202 .fs_rename(cloned_path, &host_adjusted_target_path)
203 .await
204 })?
205 };
206 if let Err(e) = res {
207 return Ok(e);
208 }
209 {
210 let source_dir_path = path.clone();
211 drop(guard);
212 rename_inode_tree(&source_entry, &source_dir_path, &host_adjusted_target_path);
213 }
214 }
215 Kind::Symlink {
216 base_po_dir,
217 path_to_symlink,
218 relative_path,
219 } => {
220 let is_ephemeral = state
221 .fs
222 .ephemeral_symlink_at(host_adjusted_source_path.as_path())
223 .is_some();
224 let res = {
225 let state = state;
226 let from = host_adjusted_source_path.clone();
227 let to = host_adjusted_target_path.clone();
228 __asyncify_light(env, None, async move { state.fs_rename(from, to).await })?
229 };
230 match (res, is_ephemeral) {
231 (Ok(()), _) | (Err(Errno::Noent), true) => {}
232 (Err(e), _) => {
233 let mut guard = source_parent_inode.write();
234 if let Kind::Dir { entries, .. } = guard.deref_mut() {
235 entries.insert(source_entry_name, source_entry.clone());
236 return Ok(e);
237 }
238 }
239 }
240
241 let (new_base_po_dir, new_path_to_symlink) =
242 wasi_try_ok!(state.fs.path_into_pre_open_and_relative_path_owned(
243 host_adjusted_target_path.as_path()
244 ));
245 *base_po_dir = new_base_po_dir;
246 *path_to_symlink = new_path_to_symlink.clone();
247 if is_ephemeral {
248 state.fs.move_ephemeral_symlink(
249 host_adjusted_source_path.as_path(),
250 host_adjusted_target_path.as_path(),
251 new_base_po_dir,
252 new_path_to_symlink,
253 relative_path.clone(),
254 );
255 }
256 }
257 Kind::Buffer { .. }
258 | Kind::Socket { .. }
259 | Kind::PipeTx { .. }
260 | Kind::PipeRx { .. }
261 | Kind::DuplexPipe { .. }
262 | Kind::Epoll { .. }
263 | Kind::EventNotifications { .. } => {}
264 Kind::Root { .. } => unreachable!("The root can not be moved"),
265 }
266 }
267
268 let source_size = source_entry.stat.read().unwrap().st_size;
269
270 if need_create {
271 let mut guard = target_parent_inode.write();
272 if let Kind::Dir { entries, .. } = guard.deref_mut() {
273 let result = entries.insert(target_entry_name.clone(), source_entry);
274 assert!(
275 result.is_none(),
276 "fatal error: race condition on filesystem detected or internal logic error"
277 );
278 }
279 }
280
281 let target_inode = state
283 .fs
284 .get_inode_at_path(inodes, target_fd, target_path, true)
285 .expect("Expected target inode to exist, and it's too late to safely fail");
286 *target_inode.name.write().unwrap() = target_entry_name.into();
287 target_inode.stat.write().unwrap().st_size = source_size;
288
289 state
292 .fs
293 .unregister_ephemeral_symlink(host_adjusted_target_path.as_path());
294
295 Ok(Errno::Success)
296}
297
298fn rename_inode_tree(inode: &InodeGuard, source_dir_path: &Path, target_dir_path: &Path) {
299 let children;
300
301 let mut guard = inode.write();
302 match guard.deref_mut() {
303 Kind::File { path, .. } => {
304 *path = adjust_path(path, source_dir_path, target_dir_path);
305 return;
306 }
307 Kind::Dir { path, entries, .. } => {
308 *path = adjust_path(path, source_dir_path, target_dir_path);
309 children = entries.values().cloned().collect::<Vec<_>>();
310 }
311 _ => return,
312 }
313 drop(guard);
314
315 for child in children {
316 rename_inode_tree(&child, source_dir_path, target_dir_path);
317 }
318}
319
320fn adjust_path(path: &Path, source_dir_path: &Path, target_dir_path: &Path) -> PathBuf {
321 let relative_path = path
322 .strip_prefix(source_dir_path)
323 .with_context(|| format!("Expected path {path:?} to be a subpath of {source_dir_path:?}"))
324 .expect("Fatal filesystem error");
325 target_dir_path.join(relative_path)
326}