golang.org/x/sys@v0.20.1-0.20240517151509-673e0f94c16d/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 //go:build linux 6 7 package unix_test 8 9 import ( 10 "bufio" 11 "bytes" 12 "encoding/hex" 13 "errors" 14 "fmt" 15 "io" 16 "net" 17 "os" 18 "os/exec" 19 "path/filepath" 20 "runtime" 21 "runtime/debug" 22 "strconv" 23 "strings" 24 "syscall" 25 "testing" 26 "time" 27 "unsafe" 28 29 "golang.org/x/sys/unix" 30 ) 31 32 func TestIoctlGetEthtoolDrvinfo(t *testing.T) { 33 if runtime.GOOS == "android" { 34 t.Skip("ethtool driver info is not available on android, skipping test") 35 } 36 37 s, err := unix.Socket(unix.AF_INET, unix.SOCK_STREAM, 0) 38 if err != nil { 39 t.Fatalf("failed to open socket: %v", err) 40 } 41 defer unix.Close(s) 42 43 ifis, err := net.Interfaces() 44 if err != nil { 45 t.Fatalf("failed to get network interfaces: %v", err) 46 } 47 48 // Print the interface name and associated driver information for each 49 // network interface supported by ethtool. 50 for _, ifi := range ifis { 51 drv, err := unix.IoctlGetEthtoolDrvinfo(s, ifi.Name) 52 if err != nil { 53 if err == unix.EOPNOTSUPP { 54 continue 55 } 56 57 if err == unix.EBUSY { 58 // See https://go.dev/issues/67350 59 t.Logf("%s: ethtool driver busy, possible kernel bug", ifi.Name) 60 continue 61 } 62 63 t.Fatalf("failed to get ethtool driver info for %q: %v", ifi.Name, err) 64 } 65 66 // Trim trailing NULLs. 67 t.Logf("%s: %q", ifi.Name, string(bytes.TrimRight(drv.Driver[:], "\x00"))) 68 } 69 } 70 71 func TestIoctlGetInt(t *testing.T) { 72 f, err := os.Open("/dev/random") 73 if err != nil { 74 t.Fatalf("failed to open device: %v", err) 75 } 76 defer f.Close() 77 78 v, err := unix.IoctlGetInt(int(f.Fd()), unix.RNDGETENTCNT) 79 if err != nil { 80 t.Fatalf("failed to perform ioctl: %v", err) 81 } 82 83 t.Logf("%d bits of entropy available", v) 84 } 85 86 func TestIoctlRetInt(t *testing.T) { 87 f, err := os.Open("/proc/self/ns/mnt") 88 if err != nil { 89 t.Skipf("skipping test, %v", err) 90 } 91 defer f.Close() 92 93 v, err := unix.IoctlRetInt(int(f.Fd()), unix.NS_GET_NSTYPE) 94 if err != nil { 95 if err == unix.ENOTTY { 96 t.Skipf("old kernel? (need Linux >= 4.11)") 97 } 98 t.Fatalf("failed to perform ioctl: %v", err) 99 } 100 if v != unix.CLONE_NEWNS { 101 t.Fatalf("unexpected return from ioctl; expected %v, got %v", v, unix.CLONE_NEWNS) 102 } 103 } 104 105 func TestIoctlGetRTCTime(t *testing.T) { 106 f, err := os.Open("/dev/rtc0") 107 if err != nil { 108 t.Skipf("skipping test, %v", err) 109 } 110 defer f.Close() 111 112 v, err := unix.IoctlGetRTCTime(int(f.Fd())) 113 if err != nil { 114 t.Fatalf("failed to perform ioctl: %v", err) 115 } 116 117 t.Logf("RTC time: %04d-%02d-%02d %02d:%02d:%02d", v.Year+1900, v.Mon+1, v.Mday, v.Hour, v.Min, v.Sec) 118 } 119 120 func TestIoctlGetRTCWkAlrm(t *testing.T) { 121 f, err := os.Open("/dev/rtc0") 122 if err != nil { 123 t.Skipf("skipping test, %v", err) 124 } 125 defer f.Close() 126 127 v, err := unix.IoctlGetRTCWkAlrm(int(f.Fd())) 128 129 // Not all RTC drivers support wakeup alarms, and will return EINVAL in such cases. 130 if err == unix.EINVAL { 131 t.Skip("RTC_WKALM_RD ioctl not supported on this rtc, skipping test") 132 } 133 134 if err != nil { 135 t.Fatalf("failed to perform ioctl: %v", err) 136 } 137 138 t.Logf("RTC wake alarm enabled '%d'; time: %04d-%02d-%02d %02d:%02d:%02d", 139 v.Enabled, v.Time.Year+1900, v.Time.Mon+1, v.Time.Mday, v.Time.Hour, v.Time.Min, v.Time.Sec) 140 } 141 142 func TestIoctlIfreq(t *testing.T) { 143 s, err := unix.Socket(unix.AF_INET, unix.SOCK_STREAM, 0) 144 if err != nil { 145 t.Fatalf("failed to open socket: %v", err) 146 } 147 defer unix.Close(s) 148 149 ifis, err := net.Interfaces() 150 if err != nil { 151 t.Fatalf("failed to get network interfaces: %v", err) 152 } 153 154 // Compare the network interface fetched from rtnetlink with the data from 155 // the equivalent ioctl API. 156 for _, ifi := range ifis { 157 ifr, err := unix.NewIfreq(ifi.Name) 158 if err != nil { 159 t.Fatalf("failed to create ifreq for %q: %v", ifi.Name, err) 160 } 161 162 if err := unix.IoctlIfreq(s, unix.SIOCGIFINDEX, ifr); err != nil { 163 t.Fatalf("failed to get interface index for %q: %v", ifi.Name, err) 164 } 165 166 if want, got := ifi.Index, int(ifr.Uint32()); want != got { 167 t.Fatalf("unexpected interface index for %q: got: %d, want: %d", 168 ifi.Name, got, want) 169 } 170 171 if want, got := ifi.Name, ifr.Name(); want != got { 172 t.Fatalf("unexpected interface name for index %d: got: %q, want: %q", 173 ifi.Index, got, want) 174 } 175 176 wantIP, ok := firstIPv4(t, &ifi) 177 if err := unix.IoctlIfreq(s, unix.SIOCGIFADDR, ifr); err != nil { 178 // Interface may have no assigned IPv4 address. 179 if err != unix.EADDRNOTAVAIL { 180 t.Fatalf("failed to get IPv4 address for %q: %v", ifi.Name, err) 181 } 182 183 // But if we found an address via rtnetlink, we should expect the 184 // ioctl to return one. 185 if ok { 186 t.Fatalf("found IPv4 address %q for %q but ioctl returned none", wantIP, ifi.Name) 187 } 188 189 continue 190 } 191 192 // Found an address, compare it directly. 193 addr, err := ifr.Inet4Addr() 194 if err != nil { 195 t.Fatalf("failed to get ifreq IPv4 address: %v", err) 196 } 197 198 if want, got := wantIP, addr; !want.Equal(got) { 199 t.Fatalf("unexpected first IPv4 address for %q: got: %q, want: %q", 200 ifi.Name, got, want) 201 } 202 } 203 } 204 205 // firstIPv4 reports whether the interface has an IPv4 address assigned, 206 // returning the first discovered address. 207 func firstIPv4(t *testing.T, ifi *net.Interface) (net.IP, bool) { 208 t.Helper() 209 210 addrs, err := ifi.Addrs() 211 if err != nil { 212 t.Fatalf("failed to get interface %q addresses: %v", ifi.Name, err) 213 } 214 215 for _, a := range addrs { 216 // Only want valid IPv4 addresses. 217 ipn, ok := a.(*net.IPNet) 218 if !ok || ipn.IP.To4() == nil { 219 continue 220 } 221 222 return ipn.IP, true 223 } 224 225 return nil, false 226 } 227 228 func TestPidfd(t *testing.T) { 229 // Start a child process which will sleep for 1 hour; longer than the 10 230 // minute default Go test timeout. 231 cmd := exec.Command("sleep", "1h") 232 if err := cmd.Start(); err != nil { 233 t.Fatalf("failed to exec sleep: %v", err) 234 } 235 236 fd, err := unix.PidfdOpen(cmd.Process.Pid, 0) 237 if err != nil { 238 // GOARCH arm/arm64 and GOOS android builders do not support pidfds. 239 if errors.Is(err, unix.ENOSYS) { 240 t.Skipf("skipping, pidfd_open is not implemented: %v", err) 241 } 242 243 t.Fatalf("failed to open child pidfd: %v", err) 244 } 245 defer unix.Close(fd) 246 247 // Child is running but not terminated. 248 if err := unix.Waitid(unix.P_PIDFD, fd, nil, unix.WEXITED|unix.WNOHANG, nil); err != nil { 249 if errors.Is(err, unix.EINVAL) { 250 t.Skip("skipping due to waitid EINVAL, see https://go.dev/issues/52014") 251 } 252 253 t.Fatalf("failed to check for child exit: %v", err) 254 } 255 256 const want = unix.SIGHUP 257 if err := unix.PidfdSendSignal(fd, want, nil, 0); err != nil { 258 t.Fatalf("failed to signal child process: %v", err) 259 } 260 261 // Now verify that the child process received the expected signal. 262 var eerr *exec.ExitError 263 if err := cmd.Wait(); !errors.As(err, &eerr) { 264 t.Fatalf("child process terminated but did not return an exit error: %v", err) 265 } 266 267 if err := unix.Waitid(unix.P_PIDFD, fd, nil, unix.WEXITED, nil); !errors.Is(err, unix.ECHILD) { 268 t.Fatalf("expected ECHILD for final waitid, but got: %v", err) 269 } 270 271 ws, ok := eerr.Sys().(syscall.WaitStatus) 272 if !ok { 273 t.Fatalf("expected syscall.WaitStatus value, but got: %#T", eerr.Sys()) 274 } 275 276 if got := ws.Signal(); got != want { 277 t.Fatalf("unexpected child exit signal, got: %s, want: %s", got, want) 278 } 279 } 280 281 func TestPpoll(t *testing.T) { 282 if runtime.GOOS == "android" { 283 t.Skip("mkfifo syscall is not available on android, skipping test") 284 } 285 286 chtmpdir(t) 287 f := mktmpfifo(t) 288 289 const timeout = 100 * time.Millisecond 290 291 ok := make(chan bool, 1) 292 go func() { 293 select { 294 case <-time.After(10 * timeout): 295 t.Errorf("Ppoll: failed to timeout after %d", 10*timeout) 296 case <-ok: 297 } 298 }() 299 300 fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}} 301 timeoutTs := unix.NsecToTimespec(int64(timeout)) 302 n, err := unix.Ppoll(fds, &timeoutTs, nil) 303 ok <- true 304 if err != nil { 305 t.Errorf("Ppoll: unexpected error: %v", err) 306 return 307 } 308 if n != 0 { 309 t.Errorf("Ppoll: wrong number of events: got %v, expected %v", n, 0) 310 return 311 } 312 } 313 314 func TestTime(t *testing.T) { 315 var ut unix.Time_t 316 ut2, err := unix.Time(&ut) 317 if err != nil { 318 t.Fatalf("Time: %v", err) 319 } 320 if ut != ut2 { 321 t.Errorf("Time: return value %v should be equal to argument %v", ut2, ut) 322 } 323 324 var now time.Time 325 326 for i := 0; i < 10; i++ { 327 ut, err = unix.Time(nil) 328 if err != nil { 329 t.Fatalf("Time: %v", err) 330 } 331 332 now = time.Now() 333 diff := int64(ut) - now.Unix() 334 if -1 <= diff && diff <= 1 { 335 return 336 } 337 } 338 339 t.Errorf("Time: return value %v should be nearly equal to time.Now().Unix() %v±1", ut, now.Unix()) 340 } 341 342 func TestUtime(t *testing.T) { 343 chtmpdir(t) 344 345 touch(t, "file1") 346 347 buf := &unix.Utimbuf{ 348 Modtime: 12345, 349 } 350 351 err := unix.Utime("file1", buf) 352 if err != nil { 353 t.Fatalf("Utime: %v", err) 354 } 355 356 fi, err := os.Stat("file1") 357 if err != nil { 358 t.Fatal(err) 359 } 360 361 if fi.ModTime().Unix() != 12345 { 362 t.Errorf("Utime: failed to change modtime: expected %v, got %v", 12345, fi.ModTime().Unix()) 363 } 364 } 365 366 func TestRlimitAs(t *testing.T) { 367 // disable GC during to avoid flaky test 368 defer debug.SetGCPercent(debug.SetGCPercent(-1)) 369 370 var rlim unix.Rlimit 371 err := unix.Getrlimit(unix.RLIMIT_AS, &rlim) 372 if err != nil { 373 t.Fatalf("Getrlimit: %v", err) 374 } 375 var zero unix.Rlimit 376 if zero == rlim { 377 t.Fatalf("Getrlimit: got zero value %#v", rlim) 378 } 379 set := rlim 380 set.Cur = uint64(unix.Getpagesize()) 381 err = unix.Setrlimit(unix.RLIMIT_AS, &set) 382 if err != nil { 383 t.Fatalf("Setrlimit: set failed: %#v %v", set, err) 384 } 385 386 // RLIMIT_AS was set to the page size, so mmap()'ing twice the page size 387 // should fail. See 'man 2 getrlimit'. 388 _, err = unix.Mmap(-1, 0, 2*unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE) 389 if err == nil { 390 t.Fatal("Mmap: unexpectedly succeeded after setting RLIMIT_AS") 391 } 392 393 err = unix.Setrlimit(unix.RLIMIT_AS, &rlim) 394 if err != nil { 395 t.Fatalf("Setrlimit: restore failed: %#v %v", rlim, err) 396 } 397 398 b, err := unix.Mmap(-1, 0, 2*unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE) 399 if err != nil { 400 t.Fatalf("Mmap: %v", err) 401 } 402 err = unix.Munmap(b) 403 if err != nil { 404 t.Fatalf("Munmap: %v", err) 405 } 406 } 407 408 func TestPselect(t *testing.T) { 409 for { 410 n, err := unix.Pselect(0, nil, nil, nil, &unix.Timespec{Sec: 0, Nsec: 0}, nil) 411 if err == unix.EINTR { 412 t.Logf("Pselect interrupted") 413 continue 414 } else if err != nil { 415 t.Fatalf("Pselect: %v", err) 416 } 417 if n != 0 { 418 t.Fatalf("Pselect: got %v ready file descriptors, expected 0", n) 419 } 420 break 421 } 422 423 dur := 2500 * time.Microsecond 424 var took time.Duration 425 for { 426 // On some platforms (e.g. Linux), the passed-in timespec is 427 // updated by pselect(2). Make sure to reset to the full 428 // duration in case of an EINTR. 429 ts := unix.NsecToTimespec(int64(dur)) 430 start := time.Now() 431 n, err := unix.Pselect(0, nil, nil, nil, &ts, nil) 432 took = time.Since(start) 433 if err == unix.EINTR { 434 t.Logf("Pselect interrupted after %v", took) 435 continue 436 } else if err != nil { 437 t.Fatalf("Pselect: %v", err) 438 } 439 if n != 0 { 440 t.Fatalf("Pselect: got %v ready file descriptors, expected 0", n) 441 } 442 break 443 } 444 445 // On some builder the actual timeout might also be slightly less than the requested. 446 // Add an acceptable margin to avoid flaky tests. 447 if took < dur*2/3 { 448 t.Errorf("Pselect: got %v timeout, expected at least %v", took, dur) 449 } 450 } 451 452 func TestPselectWithSigmask(t *testing.T) { 453 var sigmask unix.Sigset_t 454 sigmask.Val[0] |= 1 << (uint(unix.SIGUSR1) - 1) 455 for { 456 n, err := unix.Pselect(0, nil, nil, nil, &unix.Timespec{Sec: 0, Nsec: 0}, &sigmask) 457 if err == unix.EINTR { 458 t.Logf("Pselect interrupted") 459 continue 460 } else if err != nil { 461 t.Fatalf("Pselect: %v", err) 462 } 463 if n != 0 { 464 t.Fatalf("Pselect: got %v ready file descriptors, expected 0", n) 465 } 466 break 467 } 468 } 469 470 func TestSchedSetaffinity(t *testing.T) { 471 var newMask unix.CPUSet 472 newMask.Zero() 473 if newMask.Count() != 0 { 474 t.Errorf("CpuZero: didn't zero CPU set: %v", newMask) 475 } 476 cpu := 1 477 newMask.Set(cpu) 478 if newMask.Count() != 1 || !newMask.IsSet(cpu) { 479 t.Errorf("CpuSet: didn't set CPU %d in set: %v", cpu, newMask) 480 } 481 cpu = 5 482 newMask.Set(cpu) 483 if newMask.Count() != 2 || !newMask.IsSet(cpu) { 484 t.Errorf("CpuSet: didn't set CPU %d in set: %v", cpu, newMask) 485 } 486 newMask.Clear(cpu) 487 if newMask.Count() != 1 || newMask.IsSet(cpu) { 488 t.Errorf("CpuClr: didn't clear CPU %d in set: %v", cpu, newMask) 489 } 490 491 runtime.LockOSThread() 492 defer runtime.UnlockOSThread() 493 494 var oldMask unix.CPUSet 495 err := unix.SchedGetaffinity(0, &oldMask) 496 if err != nil { 497 t.Fatalf("SchedGetaffinity: %v", err) 498 } 499 500 if runtime.NumCPU() < 2 { 501 t.Skip("skipping setaffinity tests on single CPU system") 502 } 503 if runtime.GOOS == "android" { 504 t.Skip("skipping setaffinity tests on android") 505 } 506 507 // On a system like ppc64x where some cores can be disabled using ppc64_cpu, 508 // setaffinity should only be called with enabled cores. The valid cores 509 // are found from the oldMask, but if none are found then the setaffinity 510 // tests are skipped. Issue #27875. 511 cpu = 1 512 if !oldMask.IsSet(cpu) { 513 newMask.Zero() 514 for i := 0; i < len(oldMask); i++ { 515 if oldMask.IsSet(i) { 516 newMask.Set(i) 517 break 518 } 519 } 520 if newMask.Count() == 0 { 521 t.Skip("skipping setaffinity tests if CPU not available") 522 } 523 } 524 525 err = unix.SchedSetaffinity(0, &newMask) 526 if err != nil { 527 t.Fatalf("SchedSetaffinity: %v", err) 528 } 529 530 var gotMask unix.CPUSet 531 err = unix.SchedGetaffinity(0, &gotMask) 532 if err != nil { 533 t.Fatalf("SchedGetaffinity: %v", err) 534 } 535 536 if gotMask != newMask { 537 t.Errorf("SchedSetaffinity: returned affinity mask does not match set affinity mask") 538 } 539 540 // Restore old mask so it doesn't affect successive tests 541 err = unix.SchedSetaffinity(0, &oldMask) 542 if err != nil { 543 t.Fatalf("SchedSetaffinity: %v", err) 544 } 545 } 546 547 func TestStatx(t *testing.T) { 548 var stx unix.Statx_t 549 err := unix.Statx(unix.AT_FDCWD, ".", 0, 0, &stx) 550 if err == unix.ENOSYS || err == unix.EPERM { 551 t.Skip("statx syscall is not available, skipping test") 552 } else if err != nil { 553 t.Fatalf("Statx: %v", err) 554 } 555 556 chtmpdir(t) 557 touch(t, "file1") 558 559 var st unix.Stat_t 560 err = unix.Stat("file1", &st) 561 if err != nil { 562 t.Fatalf("Stat: %v", err) 563 } 564 565 flags := unix.AT_STATX_SYNC_AS_STAT 566 err = unix.Statx(unix.AT_FDCWD, "file1", flags, unix.STATX_ALL, &stx) 567 if err != nil { 568 t.Fatalf("Statx: %v", err) 569 } 570 571 if uint32(stx.Mode) != st.Mode { 572 t.Errorf("Statx: returned stat mode does not match Stat") 573 } 574 575 ctime := unix.StatxTimestamp{Sec: int64(st.Ctim.Sec), Nsec: uint32(st.Ctim.Nsec)} 576 mtime := unix.StatxTimestamp{Sec: int64(st.Mtim.Sec), Nsec: uint32(st.Mtim.Nsec)} 577 578 if stx.Ctime != ctime { 579 t.Errorf("Statx: returned stat ctime does not match Stat") 580 } 581 if stx.Mtime != mtime { 582 t.Errorf("Statx: returned stat mtime does not match Stat") 583 } 584 585 err = os.Symlink("file1", "symlink1") 586 if err != nil { 587 t.Fatal(err) 588 } 589 590 err = unix.Lstat("symlink1", &st) 591 if err != nil { 592 t.Fatalf("Lstat: %v", err) 593 } 594 595 err = unix.Statx(unix.AT_FDCWD, "symlink1", flags, unix.STATX_BASIC_STATS, &stx) 596 if err != nil { 597 t.Fatalf("Statx: %v", err) 598 } 599 600 // follow symlink, expect a regulat file 601 if stx.Mode&unix.S_IFREG == 0 { 602 t.Errorf("Statx: didn't follow symlink") 603 } 604 605 err = unix.Statx(unix.AT_FDCWD, "symlink1", flags|unix.AT_SYMLINK_NOFOLLOW, unix.STATX_ALL, &stx) 606 if err != nil { 607 t.Fatalf("Statx: %v", err) 608 } 609 610 // follow symlink, expect a symlink 611 if stx.Mode&unix.S_IFLNK == 0 { 612 t.Errorf("Statx: unexpectedly followed symlink") 613 } 614 if uint32(stx.Mode) != st.Mode { 615 t.Errorf("Statx: returned stat mode does not match Lstat") 616 } 617 618 ctime = unix.StatxTimestamp{Sec: int64(st.Ctim.Sec), Nsec: uint32(st.Ctim.Nsec)} 619 mtime = unix.StatxTimestamp{Sec: int64(st.Mtim.Sec), Nsec: uint32(st.Mtim.Nsec)} 620 621 if stx.Ctime != ctime { 622 t.Errorf("Statx: returned stat ctime does not match Lstat") 623 } 624 if stx.Mtime != mtime { 625 t.Errorf("Statx: returned stat mtime does not match Lstat") 626 } 627 } 628 629 // stringsFromByteSlice converts a sequence of attributes to a []string. 630 // On Linux, each entry is a NULL-terminated string. 631 func stringsFromByteSlice(buf []byte) []string { 632 var result []string 633 off := 0 634 for i, b := range buf { 635 if b == 0 { 636 result = append(result, string(buf[off:i])) 637 off = i + 1 638 } 639 } 640 return result 641 } 642 643 func TestFaccessat(t *testing.T) { 644 chtmpdir(t) 645 touch(t, "file1") 646 647 err := unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, 0) 648 if err != nil { 649 t.Errorf("Faccessat: unexpected error: %v", err) 650 } 651 652 err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, 2) 653 if err != unix.EINVAL { 654 t.Errorf("Faccessat: unexpected error: %v, want EINVAL", err) 655 } 656 657 err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, unix.AT_EACCESS) 658 if err != nil { 659 t.Errorf("Faccessat: unexpected error: %v", err) 660 } 661 662 err = os.Symlink("file1", "symlink1") 663 if err != nil { 664 t.Fatal(err) 665 } 666 667 err = unix.Faccessat(unix.AT_FDCWD, "symlink1", unix.R_OK, unix.AT_SYMLINK_NOFOLLOW) 668 if err != nil { 669 t.Errorf("Faccessat SYMLINK_NOFOLLOW: unexpected error %v", err) 670 } 671 672 // We can't really test AT_SYMLINK_NOFOLLOW, because there 673 // doesn't seem to be any way to change the mode of a symlink. 674 // We don't test AT_EACCESS because such tests are only 675 // meaningful if run as root. 676 677 err = unix.Fchmodat(unix.AT_FDCWD, "file1", 0, 0) 678 if err != nil { 679 t.Errorf("Fchmodat: unexpected error %v", err) 680 } 681 682 err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.F_OK, unix.AT_SYMLINK_NOFOLLOW) 683 if err != nil { 684 t.Errorf("Faccessat: unexpected error: %v", err) 685 } 686 687 err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, unix.AT_SYMLINK_NOFOLLOW) 688 if err != unix.EACCES { 689 if unix.Getuid() != 0 { 690 t.Errorf("Faccessat: unexpected error: %v, want EACCES", err) 691 } 692 } 693 } 694 695 func TestSyncFileRange(t *testing.T) { 696 file, err := os.Create(filepath.Join(t.TempDir(), t.Name())) 697 if err != nil { 698 t.Fatal(err) 699 } 700 defer file.Close() 701 702 err = unix.SyncFileRange(int(file.Fd()), 0, 0, 0) 703 if err == unix.ENOSYS || err == unix.EPERM { 704 t.Skip("sync_file_range syscall is not available, skipping test") 705 } else if err != nil { 706 t.Fatalf("SyncFileRange: %v", err) 707 } 708 709 // invalid flags 710 flags := 0xf00 711 err = unix.SyncFileRange(int(file.Fd()), 0, 0, flags) 712 if err != unix.EINVAL { 713 t.Fatalf("SyncFileRange: unexpected error: %v, want EINVAL", err) 714 } 715 } 716 717 func TestClockNanosleep(t *testing.T) { 718 delay := 50 * time.Millisecond 719 720 // Relative timespec. 721 start := time.Now() 722 rel := unix.NsecToTimespec(delay.Nanoseconds()) 723 remain := unix.Timespec{} 724 for { 725 err := unix.ClockNanosleep(unix.CLOCK_MONOTONIC, 0, &rel, &remain) 726 if err == unix.ENOSYS || err == unix.EPERM { 727 t.Skip("clock_nanosleep syscall is not available, skipping test") 728 } else if err == unix.EINTR { 729 t.Logf("ClockNanosleep interrupted after %v", time.Since(start)) 730 rel = remain 731 continue 732 } else if err != nil { 733 t.Errorf("ClockNanosleep(CLOCK_MONOTONIC, 0, %#v, nil) = %v", &rel, err) 734 } else if slept := time.Since(start); slept < delay { 735 t.Errorf("ClockNanosleep(CLOCK_MONOTONIC, 0, %#v, nil) slept only %v", &rel, slept) 736 } 737 break 738 } 739 740 // Absolute timespec. 741 for { 742 start = time.Now() 743 until := start.Add(delay) 744 abs := unix.NsecToTimespec(until.UnixNano()) 745 err := unix.ClockNanosleep(unix.CLOCK_REALTIME, unix.TIMER_ABSTIME, &abs, nil) 746 if err == unix.EINTR { 747 t.Logf("ClockNanosleep interrupted after %v", time.Since(start)) 748 continue 749 } else if err != nil { 750 t.Errorf("ClockNanosleep(CLOCK_REALTIME, TIMER_ABSTIME, %#v (=%v), nil) = %v", &abs, until, err) 751 } else { 752 // We asked for CLOCK_REALTIME, but we have no way to know whether it 753 // jumped backward after ClockNanosleep returned. Compare both ways, 754 // and only fail if both the monotonic and wall clocks agree that 755 // the elapsed sleep was too short. 756 // 757 // This can still theoretically fail spuriously: if the clock jumps 758 // forward during ClockNanosleep and then backward again before we can 759 // call time.Now, then we could end up with a time that is too short on 760 // both the monotonic scale (because of the forward jump) and the 761 // real-time scale (because of the backward jump. However, it seems 762 // unlikely that two such contrary jumps will ever occur in the time it 763 // takes to execute this test. 764 if now := time.Now(); now.Before(until) && now.Round(0).Before(until) { 765 t.Errorf("ClockNanosleep(CLOCK_REALTIME, TIMER_ABSTIME, %#v (=%v), nil) slept only until %v", &abs, until, now) 766 } 767 } 768 break 769 } 770 771 // Invalid clock. clock_nanosleep(2) says EINVAL, but it’s actually EOPNOTSUPP. 772 err := unix.ClockNanosleep(unix.CLOCK_THREAD_CPUTIME_ID, 0, &rel, nil) 773 if err != unix.EINVAL && err != unix.EOPNOTSUPP { 774 t.Errorf("ClockNanosleep(CLOCK_THREAD_CPUTIME_ID, 0, %#v, nil) = %v, want EINVAL or EOPNOTSUPP", &rel, err) 775 } 776 } 777 778 func TestOpenByHandleAt(t *testing.T) { 779 skipIfNotSupported := func(t *testing.T, name string, err error) { 780 if err == unix.EPERM { 781 t.Skipf("skipping %s test without CAP_DAC_READ_SEARCH", name) 782 } 783 if err == unix.ENOSYS { 784 t.Skipf("%s system call not available", name) 785 } 786 if err == unix.EOPNOTSUPP { 787 t.Skipf("%s not supported on this filesystem", name) 788 } 789 } 790 791 h, mountID, err := unix.NameToHandleAt(unix.AT_FDCWD, "syscall_linux_test.go", 0) 792 if err != nil { 793 skipIfNotSupported(t, "name_to_handle_at", err) 794 t.Fatalf("NameToHandleAt: %v", err) 795 } 796 t.Logf("mountID: %v, handle: size=%d, type=%d, bytes=%q", mountID, 797 h.Size(), h.Type(), h.Bytes()) 798 mount, err := openMountByID(mountID) 799 if err != nil { 800 t.Fatalf("openMountByID: %v", err) 801 } 802 defer mount.Close() 803 804 for _, clone := range []bool{false, true} { 805 t.Run("clone="+strconv.FormatBool(clone), func(t *testing.T) { 806 if clone { 807 h = unix.NewFileHandle(h.Type(), h.Bytes()) 808 } 809 fd, err := unix.OpenByHandleAt(int(mount.Fd()), h, unix.O_RDONLY) 810 skipIfNotSupported(t, "open_by_handle_at", err) 811 if err != nil { 812 t.Fatalf("OpenByHandleAt: %v", err) 813 } 814 t.Logf("opened fd %v", fd) 815 f := os.NewFile(uintptr(fd), "") 816 defer f.Close() 817 818 slurp, err := io.ReadAll(f) 819 if err != nil { 820 t.Fatal(err) 821 } 822 const substr = "Some substring for a test." 823 if !strings.Contains(string(slurp), substr) { 824 t.Errorf("didn't find substring %q in opened file; read %d bytes", substr, len(slurp)) 825 } 826 }) 827 } 828 } 829 830 func openMountByID(mountID int) (f *os.File, err error) { 831 mi, err := os.Open("/proc/self/mountinfo") 832 if err != nil { 833 return nil, err 834 } 835 defer mi.Close() 836 bs := bufio.NewScanner(mi) 837 wantPrefix := []byte(fmt.Sprintf("%v ", mountID)) 838 for bs.Scan() { 839 if !bytes.HasPrefix(bs.Bytes(), wantPrefix) { 840 continue 841 } 842 fields := strings.Fields(bs.Text()) 843 dev := fields[4] 844 return os.Open(dev) 845 } 846 if err := bs.Err(); err != nil { 847 return nil, err 848 } 849 return nil, errors.New("mountID not found") 850 } 851 852 func TestEpoll(t *testing.T) { 853 efd, err := unix.EpollCreate1(unix.EPOLL_CLOEXEC) 854 if err != nil { 855 t.Fatalf("EpollCreate1: %v", err) 856 } 857 defer unix.Close(efd) 858 859 r, w, err := os.Pipe() 860 if err != nil { 861 t.Fatal(err) 862 } 863 defer r.Close() 864 defer w.Close() 865 866 fd := int(r.Fd()) 867 ev := unix.EpollEvent{Events: unix.EPOLLIN, Fd: int32(fd)} 868 869 err = unix.EpollCtl(efd, unix.EPOLL_CTL_ADD, fd, &ev) 870 if err != nil { 871 t.Fatalf("EpollCtl: %v", err) 872 } 873 874 if _, err := w.Write([]byte("HELLO GOPHER")); err != nil { 875 t.Fatal(err) 876 } 877 878 events := make([]unix.EpollEvent, 128) 879 n, err := unix.EpollWait(efd, events, 1) 880 if err != nil { 881 t.Fatalf("EpollWait: %v", err) 882 } 883 884 if n != 1 { 885 t.Errorf("EpollWait: wrong number of events: got %v, expected 1", n) 886 } 887 888 got := int(events[0].Fd) 889 if got != fd { 890 t.Errorf("EpollWait: wrong Fd in event: got %v, expected %v", got, fd) 891 } 892 } 893 894 func TestPrctlRetInt(t *testing.T) { 895 skipc := make(chan bool, 1) 896 skip := func() { 897 skipc <- true 898 runtime.Goexit() 899 } 900 901 go func() { 902 // This test uses prctl to modify the calling thread, so run it on its own 903 // throwaway thread and do not unlock it when the goroutine exits. 904 runtime.LockOSThread() 905 defer close(skipc) 906 907 err := unix.Prctl(unix.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) 908 if err != nil { 909 t.Logf("Prctl: %v, skipping test", err) 910 skip() 911 } 912 913 v, err := unix.PrctlRetInt(unix.PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) 914 if err != nil { 915 t.Errorf("failed to perform prctl: %v", err) 916 } 917 if v != 1 { 918 t.Errorf("unexpected return from prctl; got %v, expected %v", v, 1) 919 } 920 }() 921 922 if <-skipc { 923 t.SkipNow() 924 } 925 } 926 927 func TestTimerfd(t *testing.T) { 928 var now unix.Timespec 929 if err := unix.ClockGettime(unix.CLOCK_REALTIME, &now); err != nil { 930 t.Fatalf("ClockGettime: %v", err) 931 } 932 933 tfd, err := unix.TimerfdCreate(unix.CLOCK_REALTIME, 0) 934 if err == unix.ENOSYS { 935 t.Skip("timerfd_create system call not implemented") 936 } else if err != nil { 937 t.Fatalf("TimerfdCreate: %v", err) 938 } 939 defer unix.Close(tfd) 940 941 var timeSpec unix.ItimerSpec 942 if err := unix.TimerfdGettime(tfd, &timeSpec); err != nil { 943 t.Fatalf("TimerfdGettime: %v", err) 944 } 945 946 if timeSpec.Value.Nsec != 0 || timeSpec.Value.Sec != 0 { 947 t.Fatalf("TimerfdGettime: timer is already set, but shouldn't be") 948 } 949 950 timeSpec = unix.ItimerSpec{ 951 Interval: unix.NsecToTimespec(int64(time.Millisecond)), 952 Value: now, 953 } 954 955 if err := unix.TimerfdSettime(tfd, unix.TFD_TIMER_ABSTIME, &timeSpec, nil); err != nil { 956 t.Fatalf("TimerfdSettime: %v", err) 957 } 958 959 const totalTicks = 10 960 const bufferLength = 8 961 962 buffer := make([]byte, bufferLength) 963 964 var count uint64 = 0 965 for count < totalTicks { 966 n, err := unix.Read(tfd, buffer) 967 if err != nil { 968 t.Fatalf("Timerfd: %v", err) 969 } else if n != bufferLength { 970 t.Fatalf("Timerfd: got %d bytes from timerfd, expected %d bytes", n, bufferLength) 971 } 972 973 count += *(*uint64)(unsafe.Pointer(&buffer)) 974 } 975 } 976 977 func TestOpenat2(t *testing.T) { 978 how := &unix.OpenHow{ 979 Flags: unix.O_RDONLY, 980 } 981 fd, err := unix.Openat2(unix.AT_FDCWD, ".", how) 982 if err != nil { 983 if err == unix.ENOSYS || err == unix.EPERM { 984 t.Skipf("openat2: %v (old kernel? need Linux >= 5.6)", err) 985 } 986 t.Fatalf("openat2: %v", err) 987 } 988 if err := unix.Close(fd); err != nil { 989 t.Fatalf("close: %v", err) 990 } 991 992 // prepare 993 subdir := filepath.Join(t.TempDir(), "dir") 994 if err := os.Mkdir(subdir, 0755); err != nil { 995 t.Fatal(err) 996 } 997 symlink := filepath.Join(subdir, "symlink") 998 if err := os.Symlink("../", symlink); err != nil { 999 t.Fatal(err) 1000 } 1001 1002 dirfd, err := unix.Open(subdir, unix.O_RDONLY, 0) 1003 if err != nil { 1004 t.Fatalf("open(%q): %v", subdir, err) 1005 } 1006 defer unix.Close(dirfd) 1007 1008 // openat2 with no extra flags -- should succeed 1009 fd, err = unix.Openat2(dirfd, "symlink", how) 1010 if err != nil { 1011 t.Errorf("Openat2 should succeed, got %v", err) 1012 } 1013 if err := unix.Close(fd); err != nil { 1014 t.Fatalf("close: %v", err) 1015 } 1016 1017 // open with RESOLVE_BENEATH, should result in EXDEV 1018 how.Resolve = unix.RESOLVE_BENEATH 1019 fd, err = unix.Openat2(dirfd, "symlink", how) 1020 if err == nil { 1021 if err := unix.Close(fd); err != nil { 1022 t.Fatalf("close: %v", err) 1023 } 1024 } 1025 if err != unix.EXDEV { 1026 t.Errorf("Openat2 should fail with EXDEV, got %v", err) 1027 } 1028 } 1029 1030 func TestIoctlFileDedupeRange(t *testing.T) { 1031 dir := t.TempDir() 1032 f1, err := os.Create(filepath.Join(dir, "f1")) 1033 if err != nil { 1034 t.Fatal(err) 1035 } 1036 defer f1.Close() 1037 1038 // Test deduplication with two blocks of zeros 1039 data := make([]byte, 4096) 1040 1041 for i := 0; i < 2; i += 1 { 1042 _, err = f1.Write(data) 1043 if err != nil { 1044 t.Fatal(err) 1045 } 1046 } 1047 1048 f2, err := os.Create(filepath.Join(dir, "f2")) 1049 if err != nil { 1050 t.Fatal(err) 1051 } 1052 defer f2.Close() 1053 1054 for i := 0; i < 2; i += 1 { 1055 // Make the 2nd block different 1056 if i == 1 { 1057 data[1] = 1 1058 } 1059 1060 _, err = f2.Write(data) 1061 if err != nil { 1062 t.Fatal(err) 1063 } 1064 } 1065 1066 dedupe := unix.FileDedupeRange{ 1067 Src_offset: uint64(0), 1068 Src_length: uint64(4096), 1069 Info: []unix.FileDedupeRangeInfo{ 1070 unix.FileDedupeRangeInfo{ 1071 Dest_fd: int64(f2.Fd()), 1072 Dest_offset: uint64(0), 1073 }, 1074 unix.FileDedupeRangeInfo{ 1075 Dest_fd: int64(f2.Fd()), 1076 Dest_offset: uint64(4096), 1077 }, 1078 }} 1079 1080 err = unix.IoctlFileDedupeRange(int(f1.Fd()), &dedupe) 1081 if err == unix.EOPNOTSUPP || err == unix.EINVAL || err == unix.ENOTTY { 1082 t.Skip("deduplication not supported on this filesystem") 1083 } else if err != nil { 1084 t.Fatal(err) 1085 } 1086 1087 // The first Info should be equal 1088 if dedupe.Info[0].Status < 0 { 1089 errno := unix.Errno(-dedupe.Info[0].Status) 1090 if errno == unix.EINVAL { 1091 t.Skip("deduplication not supported on this filesystem") 1092 } 1093 t.Errorf("Unexpected error in FileDedupeRange: %s", unix.ErrnoName(errno)) 1094 } else if dedupe.Info[0].Status == unix.FILE_DEDUPE_RANGE_DIFFERS { 1095 t.Errorf("Unexpected different bytes in FileDedupeRange") 1096 } 1097 if dedupe.Info[0].Bytes_deduped != 4096 { 1098 t.Errorf("Unexpected amount of bytes deduped %v != %v", 1099 dedupe.Info[0].Bytes_deduped, 4096) 1100 } 1101 1102 // The second Info should be different 1103 if dedupe.Info[1].Status < 0 { 1104 errno := unix.Errno(-dedupe.Info[1].Status) 1105 if errno == unix.EINVAL { 1106 t.Skip("deduplication not supported on this filesystem") 1107 } 1108 t.Errorf("Unexpected error in FileDedupeRange: %s", unix.ErrnoName(errno)) 1109 } else if dedupe.Info[1].Status == unix.FILE_DEDUPE_RANGE_SAME { 1110 t.Errorf("Unexpected equal bytes in FileDedupeRange") 1111 } 1112 if dedupe.Info[1].Bytes_deduped != 0 { 1113 t.Errorf("Unexpected amount of bytes deduped %v != %v", 1114 dedupe.Info[1].Bytes_deduped, 0) 1115 } 1116 } 1117 1118 // TestPwritevOffsets tests golang.org/issues/57291 where 1119 // offs2lohi was shifting by the size of long in bytes, not bits. 1120 func TestPwritevOffsets(t *testing.T) { 1121 path := filepath.Join(t.TempDir(), "x.txt") 1122 1123 f, err := os.Create(path) 1124 if err != nil { 1125 t.Fatal(err) 1126 } 1127 t.Cleanup(func() { f.Close() }) 1128 1129 const ( 1130 off = 20 1131 ) 1132 b := [][]byte{{byte(0)}} 1133 n, err := unix.Pwritev(int(f.Fd()), b, off) 1134 if err != nil { 1135 t.Fatal(err) 1136 } 1137 if n != len(b) { 1138 t.Fatalf("expected to write %d, wrote %d", len(b), n) 1139 } 1140 1141 info, err := f.Stat() 1142 if err != nil { 1143 t.Fatal(err) 1144 } 1145 want := off + int64(len(b)) 1146 if info.Size() != want { 1147 t.Fatalf("expected size to be %d, got %d", want, info.Size()) 1148 } 1149 } 1150 1151 func TestReadvAllocate(t *testing.T) { 1152 f, err := os.Create(filepath.Join(t.TempDir(), "test")) 1153 if err != nil { 1154 t.Fatal(err) 1155 } 1156 t.Cleanup(func() { f.Close() }) 1157 1158 test := func(name string, fn func(fd int)) { 1159 n := int(testing.AllocsPerRun(100, func() { 1160 fn(int(f.Fd())) 1161 })) 1162 if n != 0 { 1163 t.Errorf("%q got %d allocations, want 0", name, n) 1164 } 1165 } 1166 1167 iovs := make([][]byte, 8) 1168 for i := range iovs { 1169 iovs[i] = []byte{'A'} 1170 } 1171 1172 test("Writev", func(fd int) { 1173 unix.Writev(fd, iovs) 1174 }) 1175 test("Pwritev", func(fd int) { 1176 unix.Pwritev(fd, iovs, 0) 1177 }) 1178 test("Pwritev2", func(fd int) { 1179 unix.Pwritev2(fd, iovs, 0, 0) 1180 }) 1181 test("Readv", func(fd int) { 1182 unix.Readv(fd, iovs) 1183 }) 1184 test("Preadv", func(fd int) { 1185 unix.Preadv(fd, iovs, 0) 1186 }) 1187 test("Preadv2", func(fd int) { 1188 unix.Preadv2(fd, iovs, 0, 0) 1189 }) 1190 } 1191 1192 func TestSockaddrALG(t *testing.T) { 1193 // Open a socket to perform SHA1 hashing. 1194 fd, err := unix.Socket(unix.AF_ALG, unix.SOCK_SEQPACKET, 0) 1195 if err != nil { 1196 t.Skip("socket(AF_ALG):", err) 1197 } 1198 defer unix.Close(fd) 1199 addr := &unix.SockaddrALG{Type: "hash", Name: "sha1"} 1200 if err := unix.Bind(fd, addr); err != nil { 1201 t.Fatal("bind:", err) 1202 } 1203 // Need to call accept(2) with the second and third arguments as 0, 1204 // which is not possible via unix.Accept, thus the use of unix.Syscall. 1205 hashfd, _, errno := unix.Syscall6(unix.SYS_ACCEPT4, uintptr(fd), 0, 0, 0, 0, 0) 1206 if errno != 0 { 1207 t.Fatal("accept:", errno) 1208 } 1209 1210 hash := os.NewFile(hashfd, "sha1") 1211 defer hash.Close() 1212 1213 // Hash an input string and read the results. 1214 const ( 1215 input = "Hello, world." 1216 exp = "2ae01472317d1935a84797ec1983ae243fc6aa28" 1217 ) 1218 if _, err := hash.WriteString(input); err != nil { 1219 t.Fatal(err) 1220 } 1221 b := make([]byte, 20) 1222 if _, err := hash.Read(b); err != nil { 1223 t.Fatal(err) 1224 } 1225 got := hex.EncodeToString(b) 1226 if got != exp { 1227 t.Fatalf("got: %q, want: %q", got, exp) 1228 } 1229 }