github.com/Andyfoo/golang/x/sys@v0.0.0-20190901054642-57c1bf301704/unix/syscall_linux_test.go (about) 1 // Copyright 2016 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // +build linux 6 7 package unix_test 8 9 import ( 10 "bufio" 11 "bytes" 12 "errors" 13 "fmt" 14 "io/ioutil" 15 "os" 16 "runtime" 17 "runtime/debug" 18 "strconv" 19 "strings" 20 "testing" 21 "time" 22 23 "github.com/Andyfoo/golang/x/sys/unix" 24 ) 25 26 func TestIoctlGetInt(t *testing.T) { 27 f, err := os.Open("/dev/random") 28 if err != nil { 29 t.Fatalf("failed to open device: %v", err) 30 } 31 defer f.Close() 32 33 v, err := unix.IoctlGetInt(int(f.Fd()), unix.RNDGETENTCNT) 34 if err != nil { 35 t.Fatalf("failed to perform ioctl: %v", err) 36 } 37 38 t.Logf("%d bits of entropy available", v) 39 } 40 41 func TestIoctlGetRTCTime(t *testing.T) { 42 f, err := os.Open("/dev/rtc0") 43 if err != nil { 44 t.Skipf("skipping test, %v", err) 45 } 46 defer f.Close() 47 48 v, err := unix.IoctlGetRTCTime(int(f.Fd())) 49 if err != nil { 50 t.Fatalf("failed to perform ioctl: %v", err) 51 } 52 53 t.Logf("RTC time: %04d-%02d-%02d %02d:%02d:%02d", v.Year+1900, v.Mon+1, v.Mday, v.Hour, v.Min, v.Sec) 54 } 55 56 func TestPpoll(t *testing.T) { 57 if runtime.GOOS == "android" { 58 t.Skip("mkfifo syscall is not available on android, skipping test") 59 } 60 61 defer chtmpdir(t)() 62 f, cleanup := mktmpfifo(t) 63 defer cleanup() 64 65 const timeout = 100 * time.Millisecond 66 67 ok := make(chan bool, 1) 68 go func() { 69 select { 70 case <-time.After(10 * timeout): 71 t.Errorf("Ppoll: failed to timeout after %d", 10*timeout) 72 case <-ok: 73 } 74 }() 75 76 fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}} 77 timeoutTs := unix.NsecToTimespec(int64(timeout)) 78 n, err := unix.Ppoll(fds, &timeoutTs, nil) 79 ok <- true 80 if err != nil { 81 t.Errorf("Ppoll: unexpected error: %v", err) 82 return 83 } 84 if n != 0 { 85 t.Errorf("Ppoll: wrong number of events: got %v, expected %v", n, 0) 86 return 87 } 88 } 89 90 func TestTime(t *testing.T) { 91 var ut unix.Time_t 92 ut2, err := unix.Time(&ut) 93 if err != nil { 94 t.Fatalf("Time: %v", err) 95 } 96 if ut != ut2 { 97 t.Errorf("Time: return value %v should be equal to argument %v", ut2, ut) 98 } 99 100 var now time.Time 101 102 for i := 0; i < 10; i++ { 103 ut, err = unix.Time(nil) 104 if err != nil { 105 t.Fatalf("Time: %v", err) 106 } 107 108 now = time.Now() 109 110 if int64(ut) == now.Unix() { 111 return 112 } 113 } 114 115 t.Errorf("Time: return value %v should be nearly equal to time.Now().Unix() %v", ut, now.Unix()) 116 } 117 118 func TestUtime(t *testing.T) { 119 defer chtmpdir(t)() 120 121 touch(t, "file1") 122 123 buf := &unix.Utimbuf{ 124 Modtime: 12345, 125 } 126 127 err := unix.Utime("file1", buf) 128 if err != nil { 129 t.Fatalf("Utime: %v", err) 130 } 131 132 fi, err := os.Stat("file1") 133 if err != nil { 134 t.Fatal(err) 135 } 136 137 if fi.ModTime().Unix() != 12345 { 138 t.Errorf("Utime: failed to change modtime: expected %v, got %v", 12345, fi.ModTime().Unix()) 139 } 140 } 141 142 func TestUtimesNanoAt(t *testing.T) { 143 defer chtmpdir(t)() 144 145 symlink := "symlink1" 146 os.Remove(symlink) 147 err := os.Symlink("nonexisting", symlink) 148 if err != nil { 149 t.Fatal(err) 150 } 151 152 ts := []unix.Timespec{ 153 {Sec: 1111, Nsec: 2222}, 154 {Sec: 3333, Nsec: 4444}, 155 } 156 err = unix.UtimesNanoAt(unix.AT_FDCWD, symlink, ts, unix.AT_SYMLINK_NOFOLLOW) 157 if err != nil { 158 t.Fatalf("UtimesNanoAt: %v", err) 159 } 160 161 var st unix.Stat_t 162 err = unix.Lstat(symlink, &st) 163 if err != nil { 164 t.Fatalf("Lstat: %v", err) 165 } 166 167 // Only check Mtim, Atim might not be supported by the underlying filesystem 168 expected := ts[1] 169 if st.Mtim.Nsec == 0 { 170 // Some filesystems only support 1-second time stamp resolution 171 // and will always set Nsec to 0. 172 expected.Nsec = 0 173 } 174 if st.Mtim != expected { 175 t.Errorf("UtimesNanoAt: wrong mtime: expected %v, got %v", expected, st.Mtim) 176 } 177 } 178 179 func TestRlimitAs(t *testing.T) { 180 // disable GC during to avoid flaky test 181 defer debug.SetGCPercent(debug.SetGCPercent(-1)) 182 183 var rlim unix.Rlimit 184 err := unix.Getrlimit(unix.RLIMIT_AS, &rlim) 185 if err != nil { 186 t.Fatalf("Getrlimit: %v", err) 187 } 188 var zero unix.Rlimit 189 if zero == rlim { 190 t.Fatalf("Getrlimit: got zero value %#v", rlim) 191 } 192 set := rlim 193 set.Cur = uint64(unix.Getpagesize()) 194 err = unix.Setrlimit(unix.RLIMIT_AS, &set) 195 if err != nil { 196 t.Fatalf("Setrlimit: set failed: %#v %v", set, err) 197 } 198 199 // RLIMIT_AS was set to the page size, so mmap()'ing twice the page size 200 // should fail. See 'man 2 getrlimit'. 201 _, err = unix.Mmap(-1, 0, 2*unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE) 202 if err == nil { 203 t.Fatal("Mmap: unexpectedly succeeded after setting RLIMIT_AS") 204 } 205 206 err = unix.Setrlimit(unix.RLIMIT_AS, &rlim) 207 if err != nil { 208 t.Fatalf("Setrlimit: restore failed: %#v %v", rlim, err) 209 } 210 211 b, err := unix.Mmap(-1, 0, 2*unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE) 212 if err != nil { 213 t.Fatalf("Mmap: %v", err) 214 } 215 err = unix.Munmap(b) 216 if err != nil { 217 t.Fatalf("Munmap: %v", err) 218 } 219 } 220 221 func TestSelect(t *testing.T) { 222 _, err := unix.Select(0, nil, nil, nil, &unix.Timeval{Sec: 0, Usec: 0}) 223 if err != nil { 224 t.Fatalf("Select: %v", err) 225 } 226 227 dur := 150 * time.Millisecond 228 tv := unix.NsecToTimeval(int64(dur)) 229 start := time.Now() 230 _, err = unix.Select(0, nil, nil, nil, &tv) 231 took := time.Since(start) 232 if err != nil { 233 t.Fatalf("Select: %v", err) 234 } 235 236 if took < dur { 237 t.Errorf("Select: timeout should have been at least %v, got %v", dur, took) 238 } 239 } 240 241 func TestPselect(t *testing.T) { 242 _, err := unix.Pselect(0, nil, nil, nil, &unix.Timespec{Sec: 0, Nsec: 0}, nil) 243 if err != nil { 244 t.Fatalf("Pselect: %v", err) 245 } 246 247 dur := 2500 * time.Microsecond 248 ts := unix.NsecToTimespec(int64(dur)) 249 start := time.Now() 250 _, err = unix.Pselect(0, nil, nil, nil, &ts, nil) 251 took := time.Since(start) 252 if err != nil { 253 t.Fatalf("Pselect: %v", err) 254 } 255 256 if took < dur { 257 t.Errorf("Pselect: timeout should have been at least %v, got %v", dur, took) 258 } 259 } 260 261 func TestSchedSetaffinity(t *testing.T) { 262 runtime.LockOSThread() 263 defer runtime.UnlockOSThread() 264 265 var oldMask unix.CPUSet 266 err := unix.SchedGetaffinity(0, &oldMask) 267 if err != nil { 268 t.Fatalf("SchedGetaffinity: %v", err) 269 } 270 271 var newMask unix.CPUSet 272 newMask.Zero() 273 if newMask.Count() != 0 { 274 t.Errorf("CpuZero: didn't zero CPU set: %v", newMask) 275 } 276 cpu := 1 277 newMask.Set(cpu) 278 if newMask.Count() != 1 || !newMask.IsSet(cpu) { 279 t.Errorf("CpuSet: didn't set CPU %d in set: %v", cpu, newMask) 280 } 281 cpu = 5 282 newMask.Set(cpu) 283 if newMask.Count() != 2 || !newMask.IsSet(cpu) { 284 t.Errorf("CpuSet: didn't set CPU %d in set: %v", cpu, newMask) 285 } 286 newMask.Clear(cpu) 287 if newMask.Count() != 1 || newMask.IsSet(cpu) { 288 t.Errorf("CpuClr: didn't clear CPU %d in set: %v", cpu, newMask) 289 } 290 291 if runtime.NumCPU() < 2 { 292 t.Skip("skipping setaffinity tests on single CPU system") 293 } 294 if runtime.GOOS == "android" { 295 t.Skip("skipping setaffinity tests on android") 296 } 297 298 // On a system like ppc64x where some cores can be disabled using ppc64_cpu, 299 // setaffinity should only be called with enabled cores. The valid cores 300 // are found from the oldMask, but if none are found then the setaffinity 301 // tests are skipped. Issue #27875. 302 if !oldMask.IsSet(cpu) { 303 newMask.Zero() 304 for i := 0; i < len(oldMask); i++ { 305 if oldMask.IsSet(i) { 306 newMask.Set(i) 307 break 308 } 309 } 310 if newMask.Count() == 0 { 311 t.Skip("skipping setaffinity tests if CPU not available") 312 } 313 } 314 315 err = unix.SchedSetaffinity(0, &newMask) 316 if err != nil { 317 t.Fatalf("SchedSetaffinity: %v", err) 318 } 319 320 var gotMask unix.CPUSet 321 err = unix.SchedGetaffinity(0, &gotMask) 322 if err != nil { 323 t.Fatalf("SchedGetaffinity: %v", err) 324 } 325 326 if gotMask != newMask { 327 t.Errorf("SchedSetaffinity: returned affinity mask does not match set affinity mask") 328 } 329 330 // Restore old mask so it doesn't affect successive tests 331 err = unix.SchedSetaffinity(0, &oldMask) 332 if err != nil { 333 t.Fatalf("SchedSetaffinity: %v", err) 334 } 335 } 336 337 func TestStatx(t *testing.T) { 338 var stx unix.Statx_t 339 err := unix.Statx(unix.AT_FDCWD, ".", 0, 0, &stx) 340 if err == unix.ENOSYS || err == unix.EPERM { 341 t.Skip("statx syscall is not available, skipping test") 342 } else if err != nil { 343 t.Fatalf("Statx: %v", err) 344 } 345 346 defer chtmpdir(t)() 347 touch(t, "file1") 348 349 var st unix.Stat_t 350 err = unix.Stat("file1", &st) 351 if err != nil { 352 t.Fatalf("Stat: %v", err) 353 } 354 355 flags := unix.AT_STATX_SYNC_AS_STAT 356 err = unix.Statx(unix.AT_FDCWD, "file1", flags, unix.STATX_ALL, &stx) 357 if err != nil { 358 t.Fatalf("Statx: %v", err) 359 } 360 361 if uint32(stx.Mode) != st.Mode { 362 t.Errorf("Statx: returned stat mode does not match Stat") 363 } 364 365 ctime := unix.StatxTimestamp{Sec: int64(st.Ctim.Sec), Nsec: uint32(st.Ctim.Nsec)} 366 mtime := unix.StatxTimestamp{Sec: int64(st.Mtim.Sec), Nsec: uint32(st.Mtim.Nsec)} 367 368 if stx.Ctime != ctime { 369 t.Errorf("Statx: returned stat ctime does not match Stat") 370 } 371 if stx.Mtime != mtime { 372 t.Errorf("Statx: returned stat mtime does not match Stat") 373 } 374 375 err = os.Symlink("file1", "symlink1") 376 if err != nil { 377 t.Fatal(err) 378 } 379 380 err = unix.Lstat("symlink1", &st) 381 if err != nil { 382 t.Fatalf("Lstat: %v", err) 383 } 384 385 err = unix.Statx(unix.AT_FDCWD, "symlink1", flags, unix.STATX_BASIC_STATS, &stx) 386 if err != nil { 387 t.Fatalf("Statx: %v", err) 388 } 389 390 // follow symlink, expect a regulat file 391 if stx.Mode&unix.S_IFREG == 0 { 392 t.Errorf("Statx: didn't follow symlink") 393 } 394 395 err = unix.Statx(unix.AT_FDCWD, "symlink1", flags|unix.AT_SYMLINK_NOFOLLOW, unix.STATX_ALL, &stx) 396 if err != nil { 397 t.Fatalf("Statx: %v", err) 398 } 399 400 // follow symlink, expect a symlink 401 if stx.Mode&unix.S_IFLNK == 0 { 402 t.Errorf("Statx: unexpectedly followed symlink") 403 } 404 if uint32(stx.Mode) != st.Mode { 405 t.Errorf("Statx: returned stat mode does not match Lstat") 406 } 407 408 ctime = unix.StatxTimestamp{Sec: int64(st.Ctim.Sec), Nsec: uint32(st.Ctim.Nsec)} 409 mtime = unix.StatxTimestamp{Sec: int64(st.Mtim.Sec), Nsec: uint32(st.Mtim.Nsec)} 410 411 if stx.Ctime != ctime { 412 t.Errorf("Statx: returned stat ctime does not match Lstat") 413 } 414 if stx.Mtime != mtime { 415 t.Errorf("Statx: returned stat mtime does not match Lstat") 416 } 417 } 418 419 // stringsFromByteSlice converts a sequence of attributes to a []string. 420 // On Linux, each entry is a NULL-terminated string. 421 func stringsFromByteSlice(buf []byte) []string { 422 var result []string 423 off := 0 424 for i, b := range buf { 425 if b == 0 { 426 result = append(result, string(buf[off:i])) 427 off = i + 1 428 } 429 } 430 return result 431 } 432 433 func TestFaccessat(t *testing.T) { 434 defer chtmpdir(t)() 435 touch(t, "file1") 436 437 err := unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, 0) 438 if err != nil { 439 t.Errorf("Faccessat: unexpected error: %v", err) 440 } 441 442 err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, 2) 443 if err != unix.EINVAL { 444 t.Errorf("Faccessat: unexpected error: %v, want EINVAL", err) 445 } 446 447 err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, unix.AT_EACCESS) 448 if err != nil { 449 t.Errorf("Faccessat: unexpected error: %v", err) 450 } 451 452 err = os.Symlink("file1", "symlink1") 453 if err != nil { 454 t.Fatal(err) 455 } 456 457 err = unix.Faccessat(unix.AT_FDCWD, "symlink1", unix.R_OK, unix.AT_SYMLINK_NOFOLLOW) 458 if err != nil { 459 t.Errorf("Faccessat SYMLINK_NOFOLLOW: unexpected error %v", err) 460 } 461 462 // We can't really test AT_SYMLINK_NOFOLLOW, because there 463 // doesn't seem to be any way to change the mode of a symlink. 464 // We don't test AT_EACCESS because such tests are only 465 // meaningful if run as root. 466 467 err = unix.Fchmodat(unix.AT_FDCWD, "file1", 0, 0) 468 if err != nil { 469 t.Errorf("Fchmodat: unexpected error %v", err) 470 } 471 472 err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.F_OK, unix.AT_SYMLINK_NOFOLLOW) 473 if err != nil { 474 t.Errorf("Faccessat: unexpected error: %v", err) 475 } 476 477 err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, unix.AT_SYMLINK_NOFOLLOW) 478 if err != unix.EACCES { 479 if unix.Getuid() != 0 { 480 t.Errorf("Faccessat: unexpected error: %v, want EACCES", err) 481 } 482 } 483 } 484 485 func TestSyncFileRange(t *testing.T) { 486 file, err := ioutil.TempFile("", "TestSyncFileRange") 487 if err != nil { 488 t.Fatal(err) 489 } 490 defer os.Remove(file.Name()) 491 defer file.Close() 492 493 err = unix.SyncFileRange(int(file.Fd()), 0, 0, 0) 494 if err == unix.ENOSYS || err == unix.EPERM { 495 t.Skip("sync_file_range syscall is not available, skipping test") 496 } else if err != nil { 497 t.Fatalf("SyncFileRange: %v", err) 498 } 499 500 // invalid flags 501 flags := 0xf00 502 err = unix.SyncFileRange(int(file.Fd()), 0, 0, flags) 503 if err != unix.EINVAL { 504 t.Fatalf("SyncFileRange: unexpected error: %v, want EINVAL", err) 505 } 506 } 507 508 func TestClockNanosleep(t *testing.T) { 509 delay := 100 * time.Millisecond 510 511 // Relative timespec. 512 start := time.Now() 513 rel := unix.NsecToTimespec(delay.Nanoseconds()) 514 err := unix.ClockNanosleep(unix.CLOCK_MONOTONIC, 0, &rel, nil) 515 if err == unix.ENOSYS || err == unix.EPERM { 516 t.Skip("clock_nanosleep syscall is not available, skipping test") 517 } else if err != nil { 518 t.Errorf("ClockNanosleep(CLOCK_MONOTONIC, 0, %#v, nil) = %v", &rel, err) 519 } else if slept := time.Since(start); slept < delay { 520 t.Errorf("ClockNanosleep(CLOCK_MONOTONIC, 0, %#v, nil) slept only %v", &rel, slept) 521 } 522 523 // Absolute timespec. 524 start = time.Now() 525 until := start.Add(delay) 526 abs := unix.NsecToTimespec(until.UnixNano()) 527 err = unix.ClockNanosleep(unix.CLOCK_REALTIME, unix.TIMER_ABSTIME, &abs, nil) 528 if err != nil { 529 t.Errorf("ClockNanosleep(CLOCK_REALTIME, TIMER_ABSTIME, %#v (=%v), nil) = %v", &abs, until, err) 530 } else if slept := time.Since(start); slept < delay { 531 t.Errorf("ClockNanosleep(CLOCK_REALTIME, TIMER_ABSTIME, %#v (=%v), nil) slept only %v", &abs, until, slept) 532 } 533 534 // Invalid clock. clock_nanosleep(2) says EINVAL, but it’s actually EOPNOTSUPP. 535 err = unix.ClockNanosleep(unix.CLOCK_THREAD_CPUTIME_ID, 0, &rel, nil) 536 if err != unix.EINVAL && err != unix.EOPNOTSUPP { 537 t.Errorf("ClockNanosleep(CLOCK_THREAD_CPUTIME_ID, 0, %#v, nil) = %v, want EINVAL or EOPNOTSUPP", &rel, err) 538 } 539 } 540 541 func TestOpenByHandleAt(t *testing.T) { 542 skipIfNotSupported := func(t *testing.T, name string, err error) { 543 if err == unix.EPERM { 544 t.Skipf("skipping %s test without CAP_DAC_READ_SEARCH", name) 545 } 546 if err == unix.ENOSYS { 547 t.Skipf("%s system call not available", name) 548 } 549 if err == unix.EOPNOTSUPP { 550 t.Skipf("%s not supported on this filesystem", name) 551 } 552 } 553 554 h, mountID, err := unix.NameToHandleAt(unix.AT_FDCWD, "syscall_linux_test.go", 0) 555 if err != nil { 556 skipIfNotSupported(t, "name_to_handle_at", err) 557 t.Fatalf("NameToHandleAt: %v", err) 558 } 559 t.Logf("mountID: %v, handle: size=%d, type=%d, bytes=%q", mountID, 560 h.Size(), h.Type(), h.Bytes()) 561 mount, err := openMountByID(mountID) 562 if err != nil { 563 t.Fatalf("openMountByID: %v", err) 564 } 565 defer mount.Close() 566 567 for _, clone := range []bool{false, true} { 568 t.Run("clone="+strconv.FormatBool(clone), func(t *testing.T) { 569 if clone { 570 h = unix.NewFileHandle(h.Type(), h.Bytes()) 571 } 572 fd, err := unix.OpenByHandleAt(int(mount.Fd()), h, unix.O_RDONLY) 573 skipIfNotSupported(t, "open_by_handle_at", err) 574 if err != nil { 575 t.Fatalf("OpenByHandleAt: %v", err) 576 } 577 defer unix.Close(fd) 578 579 t.Logf("opened fd %v", fd) 580 f := os.NewFile(uintptr(fd), "") 581 slurp, err := ioutil.ReadAll(f) 582 if err != nil { 583 t.Fatal(err) 584 } 585 const substr = "Some substring for a test." 586 if !strings.Contains(string(slurp), substr) { 587 t.Errorf("didn't find substring %q in opened file; read %d bytes", substr, len(slurp)) 588 } 589 }) 590 } 591 } 592 593 func openMountByID(mountID int) (f *os.File, err error) { 594 mi, err := os.Open("/proc/self/mountinfo") 595 if err != nil { 596 return nil, err 597 } 598 defer mi.Close() 599 bs := bufio.NewScanner(mi) 600 wantPrefix := []byte(fmt.Sprintf("%v ", mountID)) 601 for bs.Scan() { 602 if !bytes.HasPrefix(bs.Bytes(), wantPrefix) { 603 continue 604 } 605 fields := strings.Fields(bs.Text()) 606 dev := fields[4] 607 return os.Open(dev) 608 } 609 if err := bs.Err(); err != nil { 610 return nil, err 611 } 612 return nil, errors.New("mountID not found") 613 }