]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/solid/fs.rs
Rollup merge of #97015 - nrc:read-buf-cursor, r=Mark-Simulacrum
[rust.git] / library / std / src / sys / solid / fs.rs
1 use super::{abi, error};
2 use crate::{
3     ffi::{CStr, CString, OsStr, OsString},
4     fmt,
5     io::{self, BorrowedCursor, IoSlice, IoSliceMut, SeekFrom},
6     mem::MaybeUninit,
7     os::raw::{c_int, c_short},
8     os::solid::ffi::OsStrExt,
9     path::{Path, PathBuf},
10     sync::Arc,
11     sys::time::SystemTime,
12     sys::unsupported,
13 };
14
15 pub use crate::sys_common::fs::try_exists;
16
17 /// A file descriptor.
18 #[derive(Clone, Copy)]
19 #[rustc_layout_scalar_valid_range_start(0)]
20 // libstd/os/raw/mod.rs assures me that every libstd-supported platform has a
21 // 32-bit c_int. Below is -2, in two's complement, but that only works out
22 // because c_int is 32 bits.
23 #[rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FE)]
24 struct FileDesc {
25     fd: c_int,
26 }
27
28 impl FileDesc {
29     #[inline]
30     fn new(fd: c_int) -> FileDesc {
31         assert_ne!(fd, -1i32);
32         // Safety: we just asserted that the value is in the valid range and
33         // isn't `-1` (the only value bigger than `0xFF_FF_FF_FE` unsigned)
34         unsafe { FileDesc { fd } }
35     }
36
37     #[inline]
38     fn raw(&self) -> c_int {
39         self.fd
40     }
41 }
42
43 pub struct File {
44     fd: FileDesc,
45 }
46
47 #[derive(Clone)]
48 pub struct FileAttr {
49     stat: abi::stat,
50 }
51
52 // all DirEntry's will have a reference to this struct
53 struct InnerReadDir {
54     dirp: abi::S_DIR,
55     root: PathBuf,
56 }
57
58 pub struct ReadDir {
59     inner: Arc<InnerReadDir>,
60 }
61
62 pub struct DirEntry {
63     entry: abi::dirent,
64     inner: Arc<InnerReadDir>,
65 }
66
67 #[derive(Clone, Debug)]
68 pub struct OpenOptions {
69     // generic
70     read: bool,
71     write: bool,
72     append: bool,
73     truncate: bool,
74     create: bool,
75     create_new: bool,
76     // system-specific
77     custom_flags: i32,
78 }
79
80 #[derive(Copy, Clone, Debug, Default)]
81 pub struct FileTimes {}
82
83 #[derive(Clone, PartialEq, Eq, Debug)]
84 pub struct FilePermissions(c_short);
85
86 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
87 pub struct FileType(c_short);
88
89 #[derive(Debug)]
90 pub struct DirBuilder {}
91
92 impl FileAttr {
93     pub fn size(&self) -> u64 {
94         self.stat.st_size as u64
95     }
96
97     pub fn perm(&self) -> FilePermissions {
98         FilePermissions(self.stat.st_mode)
99     }
100
101     pub fn file_type(&self) -> FileType {
102         FileType(self.stat.st_mode)
103     }
104
105     pub fn modified(&self) -> io::Result<SystemTime> {
106         Ok(SystemTime::from_time_t(self.stat.st_mtime))
107     }
108
109     pub fn accessed(&self) -> io::Result<SystemTime> {
110         Ok(SystemTime::from_time_t(self.stat.st_atime))
111     }
112
113     pub fn created(&self) -> io::Result<SystemTime> {
114         Ok(SystemTime::from_time_t(self.stat.st_ctime))
115     }
116 }
117
118 impl FilePermissions {
119     pub fn readonly(&self) -> bool {
120         (self.0 & abi::S_IWRITE) == 0
121     }
122
123     pub fn set_readonly(&mut self, readonly: bool) {
124         if readonly {
125             self.0 &= !abi::S_IWRITE;
126         } else {
127             self.0 |= abi::S_IWRITE;
128         }
129     }
130 }
131
132 impl FileTimes {
133     pub fn set_accessed(&mut self, _t: SystemTime) {}
134     pub fn set_modified(&mut self, _t: SystemTime) {}
135 }
136
137 impl FileType {
138     pub fn is_dir(&self) -> bool {
139         self.is(abi::S_IFDIR)
140     }
141     pub fn is_file(&self) -> bool {
142         self.is(abi::S_IFREG)
143     }
144     pub fn is_symlink(&self) -> bool {
145         false
146     }
147
148     pub fn is(&self, mode: c_short) -> bool {
149         self.0 & abi::S_IFMT == mode
150     }
151 }
152
153 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
154     unsafe {
155         let mut dir = MaybeUninit::uninit();
156         error::SolidError::err_if_negative(abi::SOLID_FS_OpenDir(
157             cstr(p)?.as_ptr(),
158             dir.as_mut_ptr(),
159         ))
160         .map_err(|e| e.as_io_error())?;
161         let inner = Arc::new(InnerReadDir { dirp: dir.assume_init(), root: p.to_owned() });
162         Ok(ReadDir { inner })
163     }
164 }
165
166 impl fmt::Debug for ReadDir {
167     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168         // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
169         // Thus the result will be e g 'ReadDir("/home")'
170         fmt::Debug::fmt(&*self.inner.root, f)
171     }
172 }
173
174 impl Iterator for ReadDir {
175     type Item = io::Result<DirEntry>;
176
177     fn next(&mut self) -> Option<io::Result<DirEntry>> {
178         unsafe {
179             let mut out_dirent = MaybeUninit::uninit();
180             error::SolidError::err_if_negative(abi::SOLID_FS_ReadDir(
181                 self.inner.dirp,
182                 out_dirent.as_mut_ptr(),
183             ))
184             .ok()?;
185             Some(Ok(DirEntry { entry: out_dirent.assume_init(), inner: Arc::clone(&self.inner) }))
186         }
187     }
188 }
189
190 impl Drop for InnerReadDir {
191     fn drop(&mut self) {
192         unsafe { abi::SOLID_FS_CloseDir(self.dirp) };
193     }
194 }
195
196 impl DirEntry {
197     pub fn path(&self) -> PathBuf {
198         self.inner.root.join(OsStr::from_bytes(
199             unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }.to_bytes(),
200         ))
201     }
202
203     pub fn file_name(&self) -> OsString {
204         OsStr::from_bytes(unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }.to_bytes())
205             .to_os_string()
206     }
207
208     pub fn metadata(&self) -> io::Result<FileAttr> {
209         lstat(&self.path())
210     }
211
212     pub fn file_type(&self) -> io::Result<FileType> {
213         match self.entry.d_type {
214             abi::DT_CHR => Ok(FileType(abi::S_IFCHR)),
215             abi::DT_FIFO => Ok(FileType(abi::S_IFIFO)),
216             abi::DT_REG => Ok(FileType(abi::S_IFREG)),
217             abi::DT_DIR => Ok(FileType(abi::S_IFDIR)),
218             abi::DT_BLK => Ok(FileType(abi::S_IFBLK)),
219             _ => lstat(&self.path()).map(|m| m.file_type()),
220         }
221     }
222 }
223
224 impl OpenOptions {
225     pub fn new() -> OpenOptions {
226         OpenOptions {
227             // generic
228             read: false,
229             write: false,
230             append: false,
231             truncate: false,
232             create: false,
233             create_new: false,
234             // system-specific
235             custom_flags: 0,
236         }
237     }
238
239     pub fn read(&mut self, read: bool) {
240         self.read = read;
241     }
242     pub fn write(&mut self, write: bool) {
243         self.write = write;
244     }
245     pub fn append(&mut self, append: bool) {
246         self.append = append;
247     }
248     pub fn truncate(&mut self, truncate: bool) {
249         self.truncate = truncate;
250     }
251     pub fn create(&mut self, create: bool) {
252         self.create = create;
253     }
254     pub fn create_new(&mut self, create_new: bool) {
255         self.create_new = create_new;
256     }
257
258     pub fn custom_flags(&mut self, flags: i32) {
259         self.custom_flags = flags;
260     }
261     pub fn mode(&mut self, _mode: u32) {}
262
263     fn get_access_mode(&self) -> io::Result<c_int> {
264         match (self.read, self.write, self.append) {
265             (true, false, false) => Ok(abi::O_RDONLY),
266             (false, true, false) => Ok(abi::O_WRONLY),
267             (true, true, false) => Ok(abi::O_RDWR),
268             (false, _, true) => Ok(abi::O_WRONLY | abi::O_APPEND),
269             (true, _, true) => Ok(abi::O_RDWR | abi::O_APPEND),
270             (false, false, false) => Err(io::Error::from_raw_os_error(libc::EINVAL)),
271         }
272     }
273
274     fn get_creation_mode(&self) -> io::Result<c_int> {
275         match (self.write, self.append) {
276             (true, false) => {}
277             (false, false) => {
278                 if self.truncate || self.create || self.create_new {
279                     return Err(io::Error::from_raw_os_error(libc::EINVAL));
280                 }
281             }
282             (_, true) => {
283                 if self.truncate && !self.create_new {
284                     return Err(io::Error::from_raw_os_error(libc::EINVAL));
285                 }
286             }
287         }
288
289         Ok(match (self.create, self.truncate, self.create_new) {
290             (false, false, false) => 0,
291             (true, false, false) => abi::O_CREAT,
292             (false, true, false) => abi::O_TRUNC,
293             (true, true, false) => abi::O_CREAT | abi::O_TRUNC,
294             (_, _, true) => abi::O_CREAT | abi::O_EXCL,
295         })
296     }
297 }
298
299 fn cstr(path: &Path) -> io::Result<CString> {
300     let path = path.as_os_str().as_bytes();
301
302     if !path.starts_with(br"\") {
303         // Relative paths aren't supported
304         return Err(crate::io::const_io_error!(
305             crate::io::ErrorKind::Unsupported,
306             "relative path is not supported on this platform",
307         ));
308     }
309
310     // Apply the thread-safety wrapper
311     const SAFE_PREFIX: &[u8] = br"\TS";
312     let wrapped_path = [SAFE_PREFIX, &path, &[0]].concat();
313
314     CString::from_vec_with_nul(wrapped_path).map_err(|_| {
315         crate::io::const_io_error!(
316             io::ErrorKind::InvalidInput,
317             "path provided contains a nul byte",
318         )
319     })
320 }
321
322 impl File {
323     pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
324         let flags = opts.get_access_mode()?
325             | opts.get_creation_mode()?
326             | (opts.custom_flags as c_int & !abi::O_ACCMODE);
327         unsafe {
328             let mut fd = MaybeUninit::uninit();
329             error::SolidError::err_if_negative(abi::SOLID_FS_Open(
330                 fd.as_mut_ptr(),
331                 cstr(path)?.as_ptr(),
332                 flags,
333             ))
334             .map_err(|e| e.as_io_error())?;
335             Ok(File { fd: FileDesc::new(fd.assume_init()) })
336         }
337     }
338
339     pub fn file_attr(&self) -> io::Result<FileAttr> {
340         unsupported()
341     }
342
343     pub fn fsync(&self) -> io::Result<()> {
344         self.flush()
345     }
346
347     pub fn datasync(&self) -> io::Result<()> {
348         self.flush()
349     }
350
351     pub fn truncate(&self, _size: u64) -> io::Result<()> {
352         unsupported()
353     }
354
355     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
356         unsafe {
357             let mut out_num_bytes = MaybeUninit::uninit();
358             error::SolidError::err_if_negative(abi::SOLID_FS_Read(
359                 self.fd.raw(),
360                 buf.as_mut_ptr(),
361                 buf.len(),
362                 out_num_bytes.as_mut_ptr(),
363             ))
364             .map_err(|e| e.as_io_error())?;
365             Ok(out_num_bytes.assume_init())
366         }
367     }
368
369     pub fn read_buf(&self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> {
370         unsafe {
371             let len = cursor.capacity();
372             let mut out_num_bytes = MaybeUninit::uninit();
373             error::SolidError::err_if_negative(abi::SOLID_FS_Read(
374                 self.fd.raw(),
375                 cursor.as_mut().as_mut_ptr() as *mut u8,
376                 len,
377                 out_num_bytes.as_mut_ptr(),
378             ))
379             .map_err(|e| e.as_io_error())?;
380
381             // Safety: `out_num_bytes` is filled by the successful call to
382             // `SOLID_FS_Read`
383             let num_bytes_read = out_num_bytes.assume_init();
384
385             // Safety: `num_bytes_read` bytes were written to the unfilled
386             // portion of the buffer
387             cursor.advance(num_bytes_read);
388
389             Ok(())
390         }
391     }
392
393     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
394         crate::io::default_read_vectored(|buf| self.read(buf), bufs)
395     }
396
397     pub fn is_read_vectored(&self) -> bool {
398         false
399     }
400
401     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
402         unsafe {
403             let mut out_num_bytes = MaybeUninit::uninit();
404             error::SolidError::err_if_negative(abi::SOLID_FS_Write(
405                 self.fd.raw(),
406                 buf.as_ptr(),
407                 buf.len(),
408                 out_num_bytes.as_mut_ptr(),
409             ))
410             .map_err(|e| e.as_io_error())?;
411             Ok(out_num_bytes.assume_init())
412         }
413     }
414
415     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
416         crate::io::default_write_vectored(|buf| self.write(buf), bufs)
417     }
418
419     pub fn is_write_vectored(&self) -> bool {
420         false
421     }
422
423     pub fn flush(&self) -> io::Result<()> {
424         error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Sync(self.fd.raw()) })
425             .map_err(|e| e.as_io_error())?;
426         Ok(())
427     }
428
429     pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
430         let (whence, pos) = match pos {
431             // Casting to `i64` is fine, too large values will end up as
432             // negative which will cause an error in `SOLID_FS_Lseek`.
433             SeekFrom::Start(off) => (abi::SEEK_SET, off as i64),
434             SeekFrom::End(off) => (abi::SEEK_END, off),
435             SeekFrom::Current(off) => (abi::SEEK_CUR, off),
436         };
437         error::SolidError::err_if_negative(unsafe {
438             abi::SOLID_FS_Lseek(self.fd.raw(), pos, whence)
439         })
440         .map_err(|e| e.as_io_error())?;
441
442         // Get the new offset
443         unsafe {
444             let mut out_offset = MaybeUninit::uninit();
445             error::SolidError::err_if_negative(abi::SOLID_FS_Ftell(
446                 self.fd.raw(),
447                 out_offset.as_mut_ptr(),
448             ))
449             .map_err(|e| e.as_io_error())?;
450             Ok(out_offset.assume_init() as u64)
451         }
452     }
453
454     pub fn duplicate(&self) -> io::Result<File> {
455         unsupported()
456     }
457
458     pub fn set_permissions(&self, _perm: FilePermissions) -> io::Result<()> {
459         unsupported()
460     }
461
462     pub fn set_times(&self, _times: FileTimes) -> io::Result<()> {
463         unsupported()
464     }
465 }
466
467 impl Drop for File {
468     fn drop(&mut self) {
469         unsafe { abi::SOLID_FS_Close(self.fd.raw()) };
470     }
471 }
472
473 impl DirBuilder {
474     pub fn new() -> DirBuilder {
475         DirBuilder {}
476     }
477
478     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
479         error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Mkdir(cstr(p)?.as_ptr()) })
480             .map_err(|e| e.as_io_error())?;
481         Ok(())
482     }
483 }
484
485 impl fmt::Debug for File {
486     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487         f.debug_struct("File").field("fd", &self.fd.raw()).finish()
488     }
489 }
490
491 pub fn unlink(p: &Path) -> io::Result<()> {
492     if stat(p)?.file_type().is_dir() {
493         Err(io::const_io_error!(io::ErrorKind::IsADirectory, "is a directory"))
494     } else {
495         error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Unlink(cstr(p)?.as_ptr()) })
496             .map_err(|e| e.as_io_error())?;
497         Ok(())
498     }
499 }
500
501 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
502     error::SolidError::err_if_negative(unsafe {
503         abi::SOLID_FS_Rename(cstr(old)?.as_ptr(), cstr(new)?.as_ptr())
504     })
505     .map_err(|e| e.as_io_error())?;
506     Ok(())
507 }
508
509 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
510     error::SolidError::err_if_negative(unsafe {
511         abi::SOLID_FS_Chmod(cstr(p)?.as_ptr(), perm.0.into())
512     })
513     .map_err(|e| e.as_io_error())?;
514     Ok(())
515 }
516
517 pub fn rmdir(p: &Path) -> io::Result<()> {
518     if stat(p)?.file_type().is_dir() {
519         error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Unlink(cstr(p)?.as_ptr()) })
520             .map_err(|e| e.as_io_error())?;
521         Ok(())
522     } else {
523         Err(io::const_io_error!(io::ErrorKind::NotADirectory, "not a directory"))
524     }
525 }
526
527 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
528     for child in readdir(path)? {
529         let child = child?;
530         let child_type = child.file_type()?;
531         if child_type.is_dir() {
532             remove_dir_all(&child.path())?;
533         } else {
534             unlink(&child.path())?;
535         }
536     }
537     rmdir(path)
538 }
539
540 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
541     // This target doesn't support symlinks
542     stat(p)?;
543     Err(io::const_io_error!(io::ErrorKind::InvalidInput, "not a symbolic link"))
544 }
545
546 pub fn symlink(_original: &Path, _link: &Path) -> io::Result<()> {
547     // This target doesn't support symlinks
548     unsupported()
549 }
550
551 pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> {
552     // This target doesn't support symlinks
553     unsupported()
554 }
555
556 pub fn stat(p: &Path) -> io::Result<FileAttr> {
557     // This target doesn't support symlinks
558     lstat(p)
559 }
560
561 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
562     unsafe {
563         let mut out_stat = MaybeUninit::uninit();
564         error::SolidError::err_if_negative(abi::SOLID_FS_Stat(
565             cstr(p)?.as_ptr(),
566             out_stat.as_mut_ptr(),
567         ))
568         .map_err(|e| e.as_io_error())?;
569         Ok(FileAttr { stat: out_stat.assume_init() })
570     }
571 }
572
573 pub fn canonicalize(_p: &Path) -> io::Result<PathBuf> {
574     unsupported()
575 }
576
577 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
578     use crate::fs::File;
579
580     let mut reader = File::open(from)?;
581     let mut writer = File::create(to)?;
582
583     io::copy(&mut reader, &mut writer)
584 }