]> git.proxmox.com Git - rustc.git/blob - src/libstd/sys/vxworks/fs.rs
New upstream version 1.46.0+dfsg1
[rustc.git] / src / libstd / sys / vxworks / fs.rs
1 // copies from linuxx
2 use crate::ffi::{CStr, CString, OsStr, OsString};
3 use crate::fmt;
4 use crate::io::{self, Error, ErrorKind, IoSlice, IoSliceMut, SeekFrom};
5 use crate::mem;
6 use crate::path::{Path, PathBuf};
7 use crate::ptr;
8 use crate::sync::Arc;
9 use crate::sys::fd::FileDesc;
10 use crate::sys::time::SystemTime;
11 use crate::sys::vxworks::ext::ffi::OsStrExt;
12 use crate::sys::vxworks::ext::ffi::OsStringExt;
13 use crate::sys::{cvt, cvt_r};
14 use crate::sys_common::{AsInner, FromInner};
15 use libc::{self, c_int, mode_t, off_t, stat64};
16 use libc::{dirent, ftruncate, lseek, open, readdir_r as readdir64_r};
17 pub struct File(FileDesc);
18
19 #[derive(Clone)]
20 pub struct FileAttr {
21 stat: stat64,
22 }
23
24 // all DirEntry's will have a reference to this struct
25 struct InnerReadDir {
26 dirp: Dir,
27 root: PathBuf,
28 }
29
30 #[derive(Clone)]
31 pub struct ReadDir {
32 inner: Arc<InnerReadDir>,
33 end_of_stream: bool,
34 }
35
36 struct Dir(*mut libc::DIR);
37
38 unsafe impl Send for Dir {}
39 unsafe impl Sync for Dir {}
40
41 pub struct DirEntry {
42 entry: dirent,
43 dir: ReadDir,
44 }
45
46 #[derive(Clone, Debug)]
47 pub struct OpenOptions {
48 // generic
49 read: bool,
50 write: bool,
51 append: bool,
52 truncate: bool,
53 create: bool,
54 create_new: bool,
55 // system-specific
56 custom_flags: i32,
57 mode: mode_t,
58 }
59
60 #[derive(Clone, PartialEq, Eq, Debug)]
61 pub struct FilePermissions {
62 mode: mode_t,
63 }
64
65 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
66 pub struct FileType {
67 mode: mode_t,
68 }
69
70 #[derive(Debug)]
71 pub struct DirBuilder {
72 mode: mode_t,
73 }
74
75 impl FileAttr {
76 pub fn size(&self) -> u64 {
77 self.stat.st_size as u64
78 }
79 pub fn perm(&self) -> FilePermissions {
80 FilePermissions { mode: (self.stat.st_mode as mode_t) }
81 }
82
83 pub fn file_type(&self) -> FileType {
84 FileType { mode: self.stat.st_mode as mode_t }
85 }
86
87 pub fn modified(&self) -> io::Result<SystemTime> {
88 Ok(SystemTime::from(libc::timespec {
89 tv_sec: self.stat.st_mtime as libc::time_t,
90 tv_nsec: 0, // hack 2.0;
91 }))
92 }
93
94 pub fn accessed(&self) -> io::Result<SystemTime> {
95 Ok(SystemTime::from(libc::timespec {
96 tv_sec: self.stat.st_atime as libc::time_t,
97 tv_nsec: 0, // hack - a proper fix would be better
98 }))
99 }
100
101 pub fn created(&self) -> io::Result<SystemTime> {
102 Err(io::Error::new(
103 io::ErrorKind::Other,
104 "creation time is not available on this platform currently",
105 ))
106 }
107 }
108
109 impl AsInner<stat64> for FileAttr {
110 fn as_inner(&self) -> &stat64 {
111 &self.stat
112 }
113 }
114
115 impl FilePermissions {
116 pub fn readonly(&self) -> bool {
117 // check if any class (owner, group, others) has write permission
118 self.mode & 0o222 == 0
119 }
120
121 pub fn set_readonly(&mut self, readonly: bool) {
122 if readonly {
123 // remove write permission for all classes; equivalent to `chmod a-w <file>`
124 self.mode &= !0o222;
125 } else {
126 // add write permission for all classes; equivalent to `chmod a+w <file>`
127 self.mode |= 0o222;
128 }
129 }
130 pub fn mode(&self) -> u32 {
131 self.mode as u32
132 }
133 }
134
135 impl FileType {
136 pub fn is_dir(&self) -> bool {
137 self.is(libc::S_IFDIR)
138 }
139 pub fn is_file(&self) -> bool {
140 self.is(libc::S_IFREG)
141 }
142 pub fn is_symlink(&self) -> bool {
143 self.is(libc::S_IFLNK)
144 }
145
146 pub fn is(&self, mode: mode_t) -> bool {
147 self.mode & libc::S_IFMT == mode
148 }
149 }
150
151 impl FromInner<u32> for FilePermissions {
152 fn from_inner(mode: u32) -> FilePermissions {
153 FilePermissions { mode: mode as mode_t }
154 }
155 }
156
157 impl fmt::Debug for ReadDir {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
160 // Thus the result will be e g 'ReadDir("/home")'
161 fmt::Debug::fmt(&*self.inner.root, f)
162 }
163 }
164
165 impl Iterator for ReadDir {
166 type Item = io::Result<DirEntry>;
167 fn next(&mut self) -> Option<io::Result<DirEntry>> {
168 if self.end_of_stream {
169 return None;
170 }
171
172 unsafe {
173 let mut ret = DirEntry { entry: mem::zeroed(), dir: self.clone() };
174 let mut entry_ptr = ptr::null_mut();
175 loop {
176 if readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 {
177 if entry_ptr.is_null() {
178 // We encountered an error (which will be returned in this iteration), but
179 // we also reached the end of the directory stream. The `end_of_stream`
180 // flag is enabled to make sure that we return `None` in the next iteration
181 // (instead of looping forever)
182 self.end_of_stream = true;
183 }
184 return Some(Err(Error::last_os_error()));
185 }
186 if entry_ptr.is_null() {
187 return None;
188 }
189 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
190 return Some(Ok(ret));
191 }
192 }
193 }
194 }
195 }
196
197 impl Drop for Dir {
198 fn drop(&mut self) {
199 let r = unsafe { libc::closedir(self.0) };
200 debug_assert_eq!(r, 0);
201 }
202 }
203
204 impl DirEntry {
205 pub fn path(&self) -> PathBuf {
206 use crate::sys::vxworks::ext::ffi::OsStrExt;
207 self.dir.inner.root.join(OsStr::from_bytes(self.name_bytes()))
208 }
209
210 pub fn file_name(&self) -> OsString {
211 OsStr::from_bytes(self.name_bytes()).to_os_string()
212 }
213
214 pub fn metadata(&self) -> io::Result<FileAttr> {
215 lstat(&self.path())
216 }
217
218 pub fn file_type(&self) -> io::Result<FileType> {
219 lstat(&self.path()).map(|m| m.file_type())
220 }
221
222 pub fn ino(&self) -> u64 {
223 self.entry.d_ino as u64
224 }
225
226 fn name_bytes(&self) -> &[u8] {
227 unsafe {
228 //&*self.name
229 CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes()
230 }
231 }
232 }
233
234 impl OpenOptions {
235 pub fn new() -> OpenOptions {
236 OpenOptions {
237 // generic
238 read: false,
239 write: false,
240 append: false,
241 truncate: false,
242 create: false,
243 create_new: false,
244 // system-specific
245 custom_flags: 0,
246 mode: 0o666,
247 }
248 }
249
250 pub fn read(&mut self, read: bool) {
251 self.read = read;
252 }
253 pub fn write(&mut self, write: bool) {
254 self.write = write;
255 }
256 pub fn append(&mut self, append: bool) {
257 self.append = append;
258 }
259 pub fn truncate(&mut self, truncate: bool) {
260 self.truncate = truncate;
261 }
262 pub fn create(&mut self, create: bool) {
263 self.create = create;
264 }
265 pub fn create_new(&mut self, create_new: bool) {
266 self.create_new = create_new;
267 }
268 pub fn mode(&mut self, mode: u32) {
269 self.mode = mode as mode_t;
270 }
271
272 fn get_access_mode(&self) -> io::Result<c_int> {
273 match (self.read, self.write, self.append) {
274 (true, false, false) => Ok(libc::O_RDONLY),
275 (false, true, false) => Ok(libc::O_WRONLY),
276 (true, true, false) => Ok(libc::O_RDWR),
277 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
278 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
279 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
280 }
281 }
282
283 fn get_creation_mode(&self) -> io::Result<c_int> {
284 match (self.write, self.append) {
285 (true, false) => {}
286 (false, false) => {
287 if self.truncate || self.create || self.create_new {
288 return Err(Error::from_raw_os_error(libc::EINVAL));
289 }
290 }
291 (_, true) => {
292 if self.truncate && !self.create_new {
293 return Err(Error::from_raw_os_error(libc::EINVAL));
294 }
295 }
296 }
297
298 Ok(match (self.create, self.truncate, self.create_new) {
299 (false, false, false) => 0,
300 (true, false, false) => libc::O_CREAT,
301 (false, true, false) => libc::O_TRUNC,
302 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
303 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
304 })
305 }
306 }
307
308 impl File {
309 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
310 let path = cstr(path)?;
311 File::open_c(&path, opts)
312 }
313
314 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
315 let flags = libc::O_CLOEXEC
316 | opts.get_access_mode()?
317 | opts.get_creation_mode()?
318 | (opts.custom_flags as c_int & !libc::O_ACCMODE);
319 let fd = cvt_r(|| unsafe { open(path.as_ptr(), flags, opts.mode as c_int) })?;
320 Ok(File(FileDesc::new(fd)))
321 }
322
323 pub fn file_attr(&self) -> io::Result<FileAttr> {
324 let mut stat: stat64 = unsafe { mem::zeroed() };
325 cvt(unsafe { ::libc::fstat(self.0.raw(), &mut stat) })?;
326 Ok(FileAttr { stat: stat })
327 }
328
329 pub fn fsync(&self) -> io::Result<()> {
330 cvt_r(|| unsafe { libc::fsync(self.0.raw()) })?;
331 Ok(())
332 }
333
334 pub fn datasync(&self) -> io::Result<()> {
335 cvt_r(|| unsafe { os_datasync(self.0.raw()) })?;
336 return Ok(());
337 unsafe fn os_datasync(fd: c_int) -> c_int {
338 libc::fsync(fd)
339 } //not supported
340 }
341
342 pub fn truncate(&self, size: u64) -> io::Result<()> {
343 return cvt_r(|| unsafe { ftruncate(self.0.raw(), size as off_t) }).map(drop);
344 }
345
346 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
347 self.0.read(buf)
348 }
349
350 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
351 self.0.read_vectored(bufs)
352 }
353
354 #[inline]
355 pub fn is_read_vectored(&self) -> bool {
356 self.0.is_read_vectored()
357 }
358
359 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
360 self.0.read_at(buf, offset)
361 }
362
363 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
364 self.0.write(buf)
365 }
366
367 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
368 self.0.write_vectored(bufs)
369 }
370
371 #[inline]
372 pub fn is_write_vectored(&self) -> bool {
373 self.0.is_write_vectored()
374 }
375
376 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
377 self.0.write_at(buf, offset)
378 }
379
380 pub fn flush(&self) -> io::Result<()> {
381 Ok(())
382 }
383
384 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
385 let (whence, pos) = match pos {
386 // Casting to `i64` is fine, too large values will end up as
387 // negative which will cause an error in `"lseek64"`.
388 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
389 SeekFrom::End(off) => (libc::SEEK_END, off),
390 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
391 };
392 let n = cvt(unsafe { lseek(self.0.raw(), pos, whence) })?;
393 Ok(n as u64)
394 }
395
396 pub fn duplicate(&self) -> io::Result<File> {
397 self.0.duplicate().map(File)
398 }
399
400 pub fn fd(&self) -> &FileDesc {
401 &self.0
402 }
403
404 pub fn into_fd(self) -> FileDesc {
405 self.0
406 }
407
408 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
409 cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?;
410 Ok(())
411 }
412
413 pub fn diverge(&self) -> ! {
414 panic!()
415 }
416 }
417
418 impl DirBuilder {
419 pub fn new() -> DirBuilder {
420 DirBuilder { mode: 0o777 }
421 }
422
423 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
424 let p = cstr(p)?;
425 cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
426 Ok(())
427 }
428
429 pub fn set_mode(&mut self, mode: u32) {
430 self.mode = mode as mode_t;
431 }
432 }
433
434 fn cstr(path: &Path) -> io::Result<CString> {
435 use crate::sys::vxworks::ext::ffi::OsStrExt;
436 Ok(CString::new(path.as_os_str().as_bytes())?)
437 }
438
439 impl FromInner<c_int> for File {
440 fn from_inner(fd: c_int) -> File {
441 File(FileDesc::new(fd))
442 }
443 }
444
445 impl fmt::Debug for File {
446 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
447 fn get_path(fd: c_int) -> Option<PathBuf> {
448 let mut buf = vec![0; libc::PATH_MAX as usize];
449 let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) };
450 if n == -1 {
451 return None;
452 }
453 let l = buf.iter().position(|&c| c == 0).unwrap();
454 buf.truncate(l as usize);
455 Some(PathBuf::from(OsString::from_vec(buf)))
456 }
457 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
458 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
459 if mode == -1 {
460 return None;
461 }
462 match mode & libc::O_ACCMODE {
463 libc::O_RDONLY => Some((true, false)),
464 libc::O_RDWR => Some((true, true)),
465 libc::O_WRONLY => Some((false, true)),
466 _ => None,
467 }
468 }
469
470 let fd = self.0.raw();
471 let mut b = f.debug_struct("File");
472 b.field("fd", &fd);
473 if let Some(path) = get_path(fd) {
474 b.field("path", &path);
475 }
476 if let Some((read, write)) = get_mode(fd) {
477 b.field("read", &read).field("write", &write);
478 }
479 b.finish()
480 }
481 }
482
483 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
484 let root = p.to_path_buf();
485 let p = cstr(p)?;
486 unsafe {
487 let ptr = libc::opendir(p.as_ptr());
488 if ptr.is_null() {
489 Err(Error::last_os_error())
490 } else {
491 let inner = InnerReadDir { dirp: Dir(ptr), root };
492 Ok(ReadDir { inner: Arc::new(inner), end_of_stream: false })
493 }
494 }
495 }
496
497 pub fn unlink(p: &Path) -> io::Result<()> {
498 let p = cstr(p)?;
499 cvt(unsafe { libc::unlink(p.as_ptr()) })?;
500 Ok(())
501 }
502
503 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
504 let old = cstr(old)?;
505 let new = cstr(new)?;
506 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
507 Ok(())
508 }
509
510 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
511 let p = cstr(p)?;
512 cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
513 Ok(())
514 }
515
516 pub fn rmdir(p: &Path) -> io::Result<()> {
517 let p = cstr(p)?;
518 cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
519 Ok(())
520 }
521
522 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
523 let filetype = lstat(path)?.file_type();
524 if filetype.is_symlink() { unlink(path) } else { remove_dir_all_recursive(path) }
525 }
526
527 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
528 for child in readdir(path)? {
529 let child = child?;
530 if child.file_type()?.is_dir() {
531 remove_dir_all_recursive(&child.path())?;
532 } else {
533 unlink(&child.path())?;
534 }
535 }
536 rmdir(path)
537 }
538
539 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
540 let c_path = cstr(p)?;
541 let p = c_path.as_ptr();
542
543 let mut buf = Vec::with_capacity(256);
544
545 loop {
546 let buf_read =
547 cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize;
548
549 unsafe {
550 buf.set_len(buf_read);
551 }
552
553 if buf_read != buf.capacity() {
554 buf.shrink_to_fit();
555
556 return Ok(PathBuf::from(OsString::from_vec(buf)));
557 }
558
559 // Trigger the internal buffer resizing logic of `Vec` by requiring
560 // more space than the current capacity. The length is guaranteed to be
561 // the same as the capacity due to the if statement above.
562 buf.reserve(1);
563 }
564 }
565
566 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
567 let src = cstr(src)?;
568 let dst = cstr(dst)?;
569 cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
570 Ok(())
571 }
572
573 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
574 let src = cstr(src)?;
575 let dst = cstr(dst)?;
576 cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
577 Ok(())
578 }
579
580 pub fn stat(p: &Path) -> io::Result<FileAttr> {
581 let p = cstr(p)?;
582 let mut stat: stat64 = unsafe { mem::zeroed() };
583 cvt(unsafe { libc::stat(p.as_ptr(), &mut stat as *mut _ as *mut _) })?;
584 Ok(FileAttr { stat })
585 }
586
587 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
588 let p = cstr(p)?;
589 let mut stat: stat64 = unsafe { mem::zeroed() };
590 cvt(unsafe { ::libc::lstat(p.as_ptr(), &mut stat as *mut _ as *mut _) })?;
591 Ok(FileAttr { stat })
592 }
593
594 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
595 use crate::sys::vxworks::ext::ffi::OsStrExt;
596 let path = CString::new(p.as_os_str().as_bytes())?;
597 let buf;
598 unsafe {
599 let r = libc::realpath(path.as_ptr(), ptr::null_mut());
600 if r.is_null() {
601 return Err(io::Error::last_os_error());
602 }
603 buf = CStr::from_ptr(r).to_bytes().to_vec();
604 libc::free(r as *mut _);
605 }
606 Ok(PathBuf::from(OsString::from_vec(buf)))
607 }
608
609 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
610 use crate::fs::File;
611 if !from.is_file() {
612 return Err(Error::new(
613 ErrorKind::InvalidInput,
614 "the source path is not an existing regular file",
615 ));
616 }
617
618 let mut reader = File::open(from)?;
619 let mut writer = File::create(to)?;
620 let perm = reader.metadata()?.permissions();
621
622 let ret = io::copy(&mut reader, &mut writer)?;
623 writer.set_permissions(perm)?;
624 Ok(ret)
625 }