devices_unix.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //go:build !windows
  2. // +build !windows
  3. /*
  4. Copyright The containerd Authors.
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. */
  15. package devices
  16. import (
  17. "fmt"
  18. "os"
  19. "syscall"
  20. "golang.org/x/sys/unix"
  21. )
  22. func DeviceInfo(fi os.FileInfo) (uint64, uint64, error) {
  23. sys, ok := fi.Sys().(*syscall.Stat_t)
  24. if !ok {
  25. return 0, 0, fmt.Errorf("cannot extract device from os.FileInfo")
  26. }
  27. //nolint:unconvert
  28. dev := uint64(sys.Rdev)
  29. return uint64(unix.Major(dev)), uint64(unix.Minor(dev)), nil
  30. }
  31. // mknod provides a shortcut for syscall.Mknod
  32. func Mknod(p string, mode os.FileMode, maj, min int) error {
  33. var (
  34. m = syscallMode(mode.Perm())
  35. dev uint64
  36. )
  37. if mode&os.ModeDevice != 0 {
  38. dev = unix.Mkdev(uint32(maj), uint32(min))
  39. if mode&os.ModeCharDevice != 0 {
  40. m |= unix.S_IFCHR
  41. } else {
  42. m |= unix.S_IFBLK
  43. }
  44. } else if mode&os.ModeNamedPipe != 0 {
  45. m |= unix.S_IFIFO
  46. }
  47. return mknod(p, m, dev)
  48. }
  49. // syscallMode returns the syscall-specific mode bits from Go's portable mode bits.
  50. func syscallMode(i os.FileMode) (o uint32) {
  51. o |= uint32(i.Perm())
  52. if i&os.ModeSetuid != 0 {
  53. o |= unix.S_ISUID
  54. }
  55. if i&os.ModeSetgid != 0 {
  56. o |= unix.S_ISGID
  57. }
  58. if i&os.ModeSticky != 0 {
  59. o |= unix.S_ISVTX
  60. }
  61. return
  62. }