Debian Codegraph @

debian/rust-vendor/nix/test/test_fcntl.rs

raw
1 #[cfg(not(target_os = "redox"))]
2 use nix::errno::*;
3 #[cfg(not(target_os = "redox"))]
4 use nix::fcntl::{open, readlink, OFlag};
5 #[cfg(not(target_os = "redox"))]
6 use nix::fcntl::{openat, readlinkat, renameat};
7
8 #[cfg(target_os = "linux")]
9 use nix::fcntl::{openat2, OpenHow, ResolveFlag};
10
11 #[cfg(all(
12 target_os = "linux",
13 target_env = "gnu",
14 any(
15 target_arch = "x86_64",
16 target_arch = "powerpc",
17 target_arch = "s390x"
18 )
19 ))]
20 use nix::fcntl::{renameat2, RenameFlags};
21 #[cfg(not(target_os = "redox"))]
22 use nix::sys::stat::Mode;
23 #[cfg(not(target_os = "redox"))]
24 use nix::unistd::read;
25 #[cfg(not(target_os = "redox"))]
26 use std::fs::File;
27 #[cfg(not(target_os = "redox"))]
28 use std::io::prelude::*;
29 #[cfg(not(target_os = "redox"))]
30 use std::os::unix::fs;
31 #[cfg(not(target_os = "redox"))]
32 use tempfile::NamedTempFile;
33
34 #[test]
35 #[cfg(not(target_os = "redox"))]
36 // QEMU does not handle openat well enough to satisfy this test
37 // https://gitlab.com/qemu-project/qemu/-/issues/829
38 #[cfg_attr(qemu, ignore)]
39 fn test_openat() {
40 const CONTENTS: &[u8] = b"abcd";
41 let mut tmp = NamedTempFile::new().unwrap();
42 tmp.write_all(CONTENTS).unwrap();
43
44 let dirfd =
45 open(tmp.path().parent().unwrap(), OFlag::empty(), Mode::empty())
46 .unwrap();
47 let fd = openat(
48 dirfd,
49 tmp.path().file_name().unwrap(),
50 OFlag::O_RDONLY,
51 Mode::empty(),
52 )
53 .unwrap();
54
55 let mut buf = [0u8; 1024];
56 assert_eq!(4, read(&fd, &mut buf).unwrap());
57 assert_eq!(CONTENTS, &buf[0..4]);
58 }
59
60 #[test]
61 #[cfg(target_os = "linux")]
62 // QEMU does not handle openat well enough to satisfy this test
63 // https://gitlab.com/qemu-project/qemu/-/issues/829
64 #[cfg_attr(qemu, ignore)]
65 fn test_openat2() {
66 const CONTENTS: &[u8] = b"abcd";
67 let mut tmp = NamedTempFile::new().unwrap();
68 tmp.write_all(CONTENTS).unwrap();
69
70 let dirfd =
71 open(tmp.path().parent().unwrap(), OFlag::empty(), Mode::empty())
72 .unwrap();
73
74 let fd = openat2(
75 dirfd,
76 tmp.path().file_name().unwrap(),
77 OpenHow::new()
78 .flags(OFlag::O_RDONLY)
79 .mode(Mode::empty())
80 .resolve(ResolveFlag::RESOLVE_BENEATH),
81 )
82 .unwrap();
83
84 let mut buf = [0u8; 1024];
85 assert_eq!(4, read(&fd, &mut buf).unwrap());
86 assert_eq!(CONTENTS, &buf[0..4]);
87 }
88
89 #[test]
90 #[cfg(target_os = "linux")]
91 // QEMU does not handle openat well enough to satisfy this test
92 // https://gitlab.com/qemu-project/qemu/-/issues/829
93 #[cfg_attr(qemu, ignore)]
94 fn test_openat2_forbidden() {
95 let mut tmp = NamedTempFile::new().unwrap();
96 tmp.write_all(b"let me out").unwrap();
97
98 let dirfd =
99 open(tmp.path().parent().unwrap(), OFlag::empty(), Mode::empty())
100 .unwrap();
101
102 let escape_attempt =
103 tmp.path().parent().unwrap().join("../../../hello.txt");
104
105 let res = openat2(
106 dirfd,
107 &escape_attempt,
108 OpenHow::new()
109 .flags(OFlag::O_RDONLY)
110 .resolve(ResolveFlag::RESOLVE_BENEATH),
111 );
112 assert_eq!(res.unwrap_err(), Errno::EXDEV);
113 }
114
115 #[test]
116 #[cfg(not(target_os = "redox"))]
117 fn test_renameat() {
118 let old_dir = tempfile::tempdir().unwrap();
119 let old_dirfd =
120 open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap();
121 let old_path = old_dir.path().join("old");
122 File::create(old_path).unwrap();
123 let new_dir = tempfile::tempdir().unwrap();
124 let new_dirfd =
125 open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap();
126 renameat(&old_dirfd, "old", &new_dirfd, "new").unwrap();
127 assert_eq!(
128 renameat(&old_dirfd, "old", &new_dirfd, "new").unwrap_err(),
129 Errno::ENOENT
130 );
131 assert!(new_dir.path().join("new").exists());
132 }
133
134 #[test]
135 #[cfg(all(
136 target_os = "linux",
137 target_env = "gnu",
138 any(
139 target_arch = "x86_64",
140 target_arch = "powerpc",
141 target_arch = "s390x"
142 )
143 ))]
144 fn test_renameat2_behaves_like_renameat_with_no_flags() {
145 let old_dir = tempfile::tempdir().unwrap();
146 let old_dirfd =
147 open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap();
148 let old_path = old_dir.path().join("old");
149 File::create(old_path).unwrap();
150 let new_dir = tempfile::tempdir().unwrap();
151 let new_dirfd =
152 open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap();
153 renameat2(&old_dirfd, "old", &new_dirfd, "new", RenameFlags::empty())
154 .unwrap();
155 assert_eq!(
156 renameat2(&old_dirfd, "old", &new_dirfd, "new", RenameFlags::empty())
157 .unwrap_err(),
158 Errno::ENOENT
159 );
160 assert!(new_dir.path().join("new").exists());
161 }
162
163 #[test]
164 #[cfg(all(
165 target_os = "linux",
166 target_env = "gnu",
167 any(
168 target_arch = "x86_64",
169 target_arch = "powerpc",
170 target_arch = "s390x"
171 )
172 ))]
173 fn test_renameat2_exchange() {
174 let old_dir = tempfile::tempdir().unwrap();
175 let old_dirfd =
176 open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap();
177 let old_path = old_dir.path().join("old");
178 {
179 let mut old_f = File::create(&old_path).unwrap();
180 old_f.write_all(b"old").unwrap();
181 }
182 let new_dir = tempfile::tempdir().unwrap();
183 let new_dirfd =
184 open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap();
185 let new_path = new_dir.path().join("new");
186 {
187 let mut new_f = File::create(&new_path).unwrap();
188 new_f.write_all(b"new").unwrap();
189 }
190 renameat2(
191 &old_dirfd,
192 "old",
193 &new_dirfd,
194 "new",
195 RenameFlags::RENAME_EXCHANGE,
196 )
197 .unwrap();
198 let mut buf = String::new();
199 let mut new_f = File::open(&new_path).unwrap();
200 new_f.read_to_string(&mut buf).unwrap();
201 assert_eq!(buf, "old");
202 buf = "".to_string();
203 let mut old_f = File::open(&old_path).unwrap();
204 old_f.read_to_string(&mut buf).unwrap();
205 assert_eq!(buf, "new");
206 }
207
208 #[test]
209 #[cfg(all(
210 target_os = "linux",
211 target_env = "gnu",
212 any(
213 target_arch = "x86_64",
214 target_arch = "powerpc",
215 target_arch = "s390x"
216 )
217 ))]
218 fn test_renameat2_noreplace() {
219 let old_dir = tempfile::tempdir().unwrap();
220 let old_dirfd =
221 open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap();
222 let old_path = old_dir.path().join("old");
223 File::create(old_path).unwrap();
224 let new_dir = tempfile::tempdir().unwrap();
225 let new_dirfd =
226 open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap();
227 let new_path = new_dir.path().join("new");
228 File::create(new_path).unwrap();
229 assert_eq!(
230 renameat2(
231 &old_dirfd,
232 "old",
233 &new_dirfd,
234 "new",
235 RenameFlags::RENAME_NOREPLACE
236 )
237 .unwrap_err(),
238 Errno::EEXIST
239 );
240 assert!(new_dir.path().join("new").exists());
241 assert!(old_dir.path().join("old").exists());
242 }
243
244 #[test]
245 #[cfg(not(target_os = "redox"))]
246 fn test_readlink() {
247 let tempdir = tempfile::tempdir().unwrap();
248 let src = tempdir.path().join("a");
249 let dst = tempdir.path().join("b");
250 println!("a: {:?}, b: {:?}", src, dst);
251 fs::symlink(src.as_path(), dst.as_path()).unwrap();
252 let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap();
253 let expected_dir = src.to_str().unwrap();
254
255 assert_eq!(readlink(&dst).unwrap().to_str().unwrap(), expected_dir);
256 assert_eq!(
257 readlinkat(dirfd, "b").unwrap().to_str().unwrap(),
258 expected_dir
259 );
260 }
261
262 /// This test creates a temporary file containing the contents
263 /// 'foobarbaz' and uses the `copy_file_range` call to transfer
264 /// 3 bytes at offset 3 (`bar`) to another empty file at offset 0. The
265 /// resulting file is read and should contain the contents `bar`.
266 /// The from_offset should be updated by the call to reflect
267 /// the 3 bytes read (6).
268 #[cfg(any(
269 linux_android,
270 // Not available until FreeBSD 13.0
271 all(target_os = "freebsd", fbsd14),
272 ))]
273 #[test]
274 // QEMU does not support copy_file_range. Skip under qemu
275 #[cfg_attr(qemu, ignore)]
276 fn test_copy_file_range() {
277 use nix::fcntl::copy_file_range;
278
279 const CONTENTS: &[u8] = b"foobarbaz";
280
281 let mut tmp1 = tempfile::tempfile().unwrap();
282 let mut tmp2 = tempfile::tempfile().unwrap();
283
284 tmp1.write_all(CONTENTS).unwrap();
285 tmp1.flush().unwrap();
286
287 let mut from_offset: i64 = 3;
288 copy_file_range(&tmp1, Some(&mut from_offset), &tmp2, None, 3).unwrap();
289
290 let mut res: String = String::new();
291 tmp2.rewind().unwrap();
292 tmp2.read_to_string(&mut res).unwrap();
293
294 assert_eq!(res, String::from("bar"));
295 assert_eq!(from_offset, 6);
296 }
297
298 #[cfg(linux_android)]
299 mod linux_android {
300 use libc::loff_t;
301 use std::io::prelude::*;
302 use std::io::IoSlice;
303
304 use nix::fcntl::*;
305 use nix::unistd::{pipe, read, write};
306
307 use tempfile::tempfile;
308 #[cfg(target_os = "linux")]
309 use tempfile::NamedTempFile;
310
311 use crate::*;
312
313 #[test]
314 fn test_splice() {
315 const CONTENTS: &[u8] = b"abcdef123456";
316 let mut tmp = tempfile().unwrap();
317 tmp.write_all(CONTENTS).unwrap();
318
319 let (rd, wr) = pipe().unwrap();
320 let mut offset: loff_t = 5;
321 let res =
322 splice(tmp, Some(&mut offset), wr, None, 2, SpliceFFlags::empty())
323 .unwrap();
324
325 assert_eq!(2, res);
326
327 let mut buf = [0u8; 1024];
328 assert_eq!(2, read(&rd, &mut buf).unwrap());
329 assert_eq!(b"f1", &buf[0..2]);
330 assert_eq!(7, offset);
331 }
332
333 #[test]
334 fn test_tee() {
335 let (rd1, wr1) = pipe().unwrap();
336 let (rd2, wr2) = pipe().unwrap();
337
338 write(wr1, b"abc").unwrap();
339 let res = tee(rd1.try_clone().unwrap(), wr2, 2, SpliceFFlags::empty())
340 .unwrap();
341
342 assert_eq!(2, res);
343
344 let mut buf = [0u8; 1024];
345
346 // Check the tee'd bytes are at rd2.
347 assert_eq!(2, read(&rd2, &mut buf).unwrap());
348 assert_eq!(b"ab", &buf[0..2]);
349
350 // Check all the bytes are still at rd1.
351 assert_eq!(3, read(&rd1, &mut buf).unwrap());
352 assert_eq!(b"abc", &buf[0..3]);
353 }
354
355 #[test]
356 fn test_vmsplice() {
357 let (rd, wr) = pipe().unwrap();
358
359 let buf1 = b"abcdef";
360 let buf2 = b"defghi";
361 let iovecs = [IoSlice::new(&buf1[0..3]), IoSlice::new(&buf2[0..3])];
362
363 let res = vmsplice(wr, &iovecs[..], SpliceFFlags::empty()).unwrap();
364
365 assert_eq!(6, res);
366
367 // Check the bytes can be read at rd.
368 let mut buf = [0u8; 32];
369 assert_eq!(6, read(&rd, &mut buf).unwrap());
370 assert_eq!(b"abcdef", &buf[0..6]);
371 }
372
373 #[cfg(target_os = "linux")]
374 #[test]
375 fn test_fallocate() {
376 let tmp = NamedTempFile::new().unwrap();
377
378 fallocate(&tmp, FallocateFlags::empty(), 0, 100).unwrap();
379
380 // Check if we read exactly 100 bytes
381 let mut buf = [0u8; 200];
382 assert_eq!(100, read(&tmp, &mut buf).unwrap());
383 }
384
385 // The tests below are disabled for the listed targets
386 // due to OFD locks not being available in the kernel/libc
387 // versions used in the CI environment, probably because
388 // they run under QEMU.
389
390 #[test]
391 #[cfg(all(target_os = "linux", not(target_env = "musl")))]
392 #[cfg_attr(target_env = "uclibc", ignore)] // uclibc doesn't support OFD locks, but the test should still compile
393 fn test_ofd_write_lock() {
394 use nix::sys::stat::fstat;
395 use std::mem;
396
397 let tmp = NamedTempFile::new().unwrap();
398
399 let statfs = nix::sys::statfs::fstatfs(tmp.as_file()).unwrap();
400 if statfs.filesystem_type() == nix::sys::statfs::OVERLAYFS_SUPER_MAGIC {
401 // OverlayFS is a union file system. It returns one inode value in
402 // stat(2), but a different one shows up in /proc/locks. So we must
403 // skip the test.
404 skip!("/proc/locks does not work on overlayfs");
405 }
406 let inode = fstat(&tmp).expect("fstat failed").st_ino as usize;
407
408 let mut flock: libc::flock = unsafe {
409 mem::zeroed() // required for Linux/mips
410 };
411 flock.l_type = libc::F_WRLCK as libc::c_short;
412 flock.l_whence = libc::SEEK_SET as libc::c_short;
413 flock.l_start = 0;
414 flock.l_len = 0;
415 flock.l_pid = 0;
416 fcntl(&tmp, FcntlArg::F_OFD_SETLKW(&flock)).expect("write lock failed");
417 assert_eq!(
418 Some(("OFDLCK".to_string(), "WRITE".to_string())),
419 lock_info(inode)
420 );
421
422 flock.l_type = libc::F_UNLCK as libc::c_short;
423 fcntl(&tmp, FcntlArg::F_OFD_SETLKW(&flock))
424 .expect("write unlock failed");
425 assert_eq!(None, lock_info(inode));
426 }
427
428 #[test]
429 #[cfg(all(target_os = "linux", not(target_env = "musl")))]
430 #[cfg_attr(target_env = "uclibc", ignore)] // uclibc doesn't support OFD locks, but the test should still compile
431 fn test_ofd_read_lock() {
432 use nix::sys::stat::fstat;
433 use std::mem;
434
435 let tmp = NamedTempFile::new().unwrap();
436
437 let statfs = nix::sys::statfs::fstatfs(tmp.as_file()).unwrap();
438 if statfs.filesystem_type() == nix::sys::statfs::OVERLAYFS_SUPER_MAGIC {
439 // OverlayFS is a union file system. It returns one inode value in
440 // stat(2), but a different one shows up in /proc/locks. So we must
441 // skip the test.
442 skip!("/proc/locks does not work on overlayfs");
443 }
444 let inode = fstat(&tmp).expect("fstat failed").st_ino as usize;
445
446 let mut flock: libc::flock = unsafe {
447 mem::zeroed() // required for Linux/mips
448 };
449 flock.l_type = libc::F_RDLCK as libc::c_short;
450 flock.l_whence = libc::SEEK_SET as libc::c_short;
451 flock.l_start = 0;
452 flock.l_len = 0;
453 flock.l_pid = 0;
454 fcntl(&tmp, FcntlArg::F_OFD_SETLKW(&flock)).expect("read lock failed");
455 assert_eq!(
456 Some(("OFDLCK".to_string(), "READ".to_string())),
457 lock_info(inode)
458 );
459
460 flock.l_type = libc::F_UNLCK as libc::c_short;
461 fcntl(&tmp, FcntlArg::F_OFD_SETLKW(&flock))
462 .expect("read unlock failed");
463 assert_eq!(None, lock_info(inode));
464 }
465
466 #[cfg(all(target_os = "linux", not(target_env = "musl")))]
467 fn lock_info(inode: usize) -> Option<(String, String)> {
468 use std::{fs::File, io::BufReader};
469
470 let file = File::open("/proc/locks").expect("open /proc/locks failed");
471 let buf = BufReader::new(file);
472
473 for line in buf.lines() {
474 let line = line.unwrap();
475 let parts: Vec<_> = line.split_whitespace().collect();
476 let lock_type = parts[1];
477 let lock_access = parts[3];
478 let ino_parts: Vec<_> = parts[5].split(':').collect();
479 let ino: usize = ino_parts[2].parse().unwrap();
480 if ino == inode {
481 return Some((lock_type.to_string(), lock_access.to_string()));
482 }
483 }
484 None
485 }
486 }
487
488 #[cfg(any(
489 linux_android,
490 target_os = "emscripten",
491 target_os = "fuchsia",
492 target_os = "wasi",
493 target_env = "uclibc",
494 target_os = "freebsd"
495 ))]
496 mod test_posix_fadvise {
497 use nix::errno::Errno;
498 use nix::fcntl::*;
499 use nix::unistd::pipe;
500 use tempfile::NamedTempFile;
501
502 #[test]
503 fn test_success() {
504 let tmp = NamedTempFile::new().unwrap();
505 posix_fadvise(&tmp, 0, 100, PosixFadviseAdvice::POSIX_FADV_WILLNEED)
506 .expect("posix_fadvise failed");
507 }
508
509 #[test]
510 fn test_errno() {
511 let (rd, _wr) = pipe().unwrap();
512 let res =
513 posix_fadvise(&rd, 0, 100, PosixFadviseAdvice::POSIX_FADV_WILLNEED);
514 assert_eq!(res, Err(Errno::ESPIPE));
515 }
516 }
517
518 #[cfg(any(
519 linux_android,
520 freebsdlike,
521 target_os = "emscripten",
522 target_os = "fuchsia",
523 target_os = "wasi",
524 ))]
525 mod test_posix_fallocate {
526
527 use nix::errno::Errno;
528 use nix::fcntl::*;
529 use nix::unistd::pipe;
530 use std::io::Read;
531 use tempfile::NamedTempFile;
532
533 #[test]
534 fn success() {
535 const LEN: usize = 100;
536 let mut tmp = NamedTempFile::new().unwrap();
537 let res = posix_fallocate(&tmp, 0, LEN as libc::off_t);
538 match res {
539 Ok(_) => {
540 let mut data = [1u8; LEN];
541 assert_eq!(tmp.read(&mut data).expect("read failure"), LEN);
542 assert_eq!(&data[..], &[0u8; LEN][..]);
543 }
544 Err(Errno::ENOTSUP) | Err(Errno::EINVAL) => {
545 // POSIX 1003.1-2024 Issue 8 specified ENOTSUP for "the file
546 // system does not support this operation", so Nix should accept
547 // that error code and pass the test.
548 // But older POSIX required posix_fallocate to return EINVAL
549 // both for invalid arguments (i.e. len < 0) and if the
550 // operation is not supported by the file system. So we must
551 // also pass the test if it returns EINVAL.
552 }
553 _ => res.unwrap(),
554 }
555 }
556
557 #[test]
558 fn errno() {
559 let (rd, _wr) = pipe().unwrap();
560 let err = posix_fallocate(&rd, 0, 100).unwrap_err();
561 match err {
562 Errno::EINVAL | Errno::ENODEV | Errno::ESPIPE | Errno::EBADF => (),
563 errno => panic!("unexpected errno {errno}",),
564 }
565 }
566 }
567
568 #[cfg(any(target_os = "dragonfly", target_os = "netbsd", apple_targets))]
569 #[test]
570 fn test_f_get_path() {
571 use nix::fcntl::*;
572 use std::path::PathBuf;
573
574 let tmp = NamedTempFile::new().unwrap();
575 let mut path = PathBuf::new();
576 let res =
577 fcntl(&tmp, FcntlArg::F_GETPATH(&mut path)).expect("get path failed");
578 assert_ne!(res, -1);
579 assert_eq!(
580 path.as_path().canonicalize().unwrap(),
581 tmp.path().canonicalize().unwrap()
582 );
583 }
584
585 #[cfg(apple_targets)]
586 #[test]
587 fn test_f_preallocate() {
588 use nix::fcntl::*;
589
590 let tmp = NamedTempFile::new().unwrap();
591 let mut st: libc::fstore_t = unsafe { std::mem::zeroed() };
592
593 st.fst_flags = libc::F_ALLOCATECONTIG as libc::c_uint;
594 st.fst_posmode = libc::F_PEOFPOSMODE;
595 st.fst_length = 1024;
596 let res = fcntl(tmp, FcntlArg::F_PREALLOCATE(&mut st))
597 .expect("preallocation failed");
598
599 assert_eq!(res, 0);
600 assert!(st.fst_bytesalloc > 0);
601 }
602
603 #[cfg(apple_targets)]
604 #[test]
605 fn test_f_get_path_nofirmlink() {
606 use nix::fcntl::*;
607 use std::path::PathBuf;
608
609 let tmp = NamedTempFile::new().unwrap();
610 let mut path = PathBuf::new();
611 let res = fcntl(&tmp, FcntlArg::F_GETPATH_NOFIRMLINK(&mut path))
612 .expect("get path failed");
613 let mut tmpstr = String::from("/System/Volumes/Data");
614 tmpstr.push_str(
615 &tmp.path()
616 .canonicalize()
617 .unwrap()
618 .into_os_string()
619 .into_string()
620 .unwrap(),
621 );
622 assert_ne!(res, -1);
623 assert_eq!(
624 path.as_path()
625 .canonicalize()
626 .unwrap()
627 .into_os_string()
628 .into_string()
629 .unwrap(),
630 tmpstr
631 );
632 }
633
634 #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))]
635 #[test]
636 fn test_f_kinfo() {
637 use nix::fcntl::*;
638 use std::path::PathBuf;
639
640 let tmp = NamedTempFile::new().unwrap();
641 // With TMPDIR set with UFS, the vnode name is not entered
642 // into the name cache thus path is always empty.
643 // Therefore, we reopen the tempfile a second time for the test
644 // to pass.
645 let tmp2 = File::open(tmp.path()).unwrap();
646 let mut path = PathBuf::new();
647 let res =
648 fcntl(&tmp2, FcntlArg::F_KINFO(&mut path)).expect("get path failed");
649 assert_ne!(res, -1);
650 assert_eq!(path, tmp.path());
651 }
652
653 /// Test `Flock` and associated functions.
654 ///
655 #[cfg(not(any(target_os = "redox", target_os = "solaris")))]
656 mod test_flock {
657 use nix::fcntl::*;
658 use tempfile::NamedTempFile;
659
660 /// Verify that `Flock::lock()` correctly obtains a lock, and subsequently unlocks upon drop.
661 #[test]
662 fn lock_and_drop() {
663 // Get 2 `File` handles to same underlying file.
664 let file1 = NamedTempFile::new().unwrap();
665 let file2 = file1.reopen().unwrap();
666 let file1 = file1.into_file();
667
668 // Lock first handle
669 let lock1 = Flock::lock(file1, FlockArg::LockExclusive).unwrap();
670
671 // Attempt to lock second handle
672 let file2 = match Flock::lock(file2, FlockArg::LockExclusiveNonblock) {
673 Ok(_) => panic!("Expected second exclusive lock to fail."),
674 Err((f, _)) => f,
675 };
676
677 // Drop first lock
678 std::mem::drop(lock1);
679
680 // Attempt to lock second handle again (but successfully)
681 if Flock::lock(file2, FlockArg::LockExclusiveNonblock).is_err() {
682 panic!("Expected locking to be successful.");
683 }
684 }
685
686 /// An exclusive lock can be downgraded
687 #[test]
688 fn downgrade() {
689 let file1 = NamedTempFile::new().unwrap();
690 let file2 = file1.reopen().unwrap();
691 let file1 = file1.into_file();
692
693 // Lock first handle
694 let lock1 = Flock::lock(file1, FlockArg::LockExclusive).unwrap();
695
696 // Attempt to lock second handle
697 let file2 = Flock::lock(file2, FlockArg::LockSharedNonblock)
698 .unwrap_err()
699 .0;
700
701 // Downgrade the lock
702 lock1.relock(FlockArg::LockShared).unwrap();
703
704 // Attempt to lock second handle again (but successfully)
705 Flock::lock(file2, FlockArg::LockSharedNonblock)
706 .expect("Expected locking to be successful.");
707 }
708
709 /// Verify that `Flock::unlock()` correctly obtains unlocks.
710 #[test]
711 fn unlock() {
712 // Get 2 `File` handles to same underlying file.
713 let file1 = NamedTempFile::new().unwrap();
714 let file2 = file1.reopen().unwrap();
715 let file1 = file1.into_file();
716
717 // Lock first handle
718 let lock1 = Flock::lock(file1, FlockArg::LockExclusive).unwrap();
719
720 // Unlock and retain file so any erroneous flocks also remain present.
721 let _file1 = lock1.unlock().unwrap();
722
723 // Attempt to lock second handle.
724 if Flock::lock(file2, FlockArg::LockExclusiveNonblock).is_err() {
725 panic!("Expected locking to be successful.");
726 }
727 }
728
729 /// A shared lock can be upgraded
730 #[test]
731 fn upgrade() {
732 let file1 = NamedTempFile::new().unwrap();
733 let file2 = file1.reopen().unwrap();
734 let file3 = file1.reopen().unwrap();
735 let file1 = file1.into_file();
736
737 // Lock first handle
738 let lock1 = Flock::lock(file1, FlockArg::LockShared).unwrap();
739
740 // Attempt to lock second handle
741 {
742 Flock::lock(file2, FlockArg::LockSharedNonblock)
743 .expect("Locking should've succeeded");
744 }
745
746 // Upgrade the lock
747 lock1.relock(FlockArg::LockExclusive).unwrap();
748
749 // Acquiring an additional shared lock should fail
750 Flock::lock(file3, FlockArg::LockSharedNonblock)
751 .expect_err("Should not have been able to lock the file");
752 }
753 }
754
755 #[cfg(apple_targets)]
756 #[test]
757 fn test_f_rdadvise() {
758 use nix::fcntl::*;
759
760 let contents = vec![1; 1024];
761 let mut buf = [0; 1024];
762 let mut tmp = NamedTempFile::new().unwrap();
763 tmp.write_all(&contents).unwrap();
764 let fd = open(tmp.path(), OFlag::empty(), Mode::empty()).unwrap();
765 let rad = libc::radvisory {
766 ra_offset: 0,
767 ra_count: contents.len() as _,
768 };
769 let res = fcntl(&tmp, FcntlArg::F_RDADVISE(rad)).expect("rdadivse failed");
770 assert_ne!(res, -1);
771 assert_eq!(contents.len(), read(&fd, &mut buf).unwrap());
772 assert_eq!(contents, &buf[0..contents.len()]);
773 }
774
775 #[cfg(apple_targets)]
776 #[test]
777 fn test_f_log2phys() {
778 use nix::fcntl::*;
779
780 const CONTENTS: &[u8] = b"abcd";
781 let mut tmp = NamedTempFile::new().unwrap();
782 tmp.write_all(CONTENTS).unwrap();
783 let mut offset: libc::off_t = 0;
784 let mut res = fcntl(&tmp, FcntlArg::F_LOG2PHYS(&mut offset))
785 .expect("log2phys failed");
786 assert_ne!(res, -1);
787 assert_ne!(offset, 0);
788 let mut info: libc::log2phys = unsafe { std::mem::zeroed() };
789 info.l2p_contigbytes = CONTENTS.len() as _;
790 info.l2p_devoffset = 3;
791 res = fcntl(&tmp, FcntlArg::F_LOG2PHYS_EXT(&mut info))
792 .expect("log2phys failed");
793 assert_ne!(res, -1);
794 assert_ne!({ info.l2p_devoffset }, 3);
795 }
796
797 #[cfg(apple_targets)]
798 #[test]
799 fn test_f_transferextents() {
800 use nix::fcntl::*;
801 use std::os::fd::AsRawFd;
802
803 let tmp1 = NamedTempFile::new().unwrap();
804 let tmp2 = NamedTempFile::new().unwrap();
805 let res = fcntl(&tmp1, FcntlArg::F_TRANSFEREXTENTS(tmp2.as_raw_fd()))
806 .expect("transferextents failed");
807 assert_ne!(res, -1);
808 }
809
810 #[cfg(target_os = "freebsd")]
811 #[test]
812 fn test_f_readahead() {
813 use nix::fcntl::*;
814
815 let tmp = NamedTempFile::new().unwrap();
816 let mut res = fcntl(&tmp, FcntlArg::F_READAHEAD(1_000_000))
817 .expect("read ahead failed");
818 assert_ne!(res, -1);
819 res = fcntl(&tmp, FcntlArg::F_READAHEAD(-1024)).expect("read ahead failed");
820 assert_ne!(res, -1);
821 }