devices_unix.go 1.7 KB

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