stat_linux.odin 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #+private
  2. package os2
  3. import "core:time"
  4. import "base:runtime"
  5. import "core:sys/linux"
  6. _fstat :: proc(f: ^File, allocator: runtime.Allocator) -> (File_Info, Error) {
  7. impl := (^File_Impl)(f.impl)
  8. return _fstat_internal(impl.fd, allocator)
  9. }
  10. _fstat_internal :: proc(fd: linux.Fd, allocator: runtime.Allocator) -> (fi: File_Info, err: Error) {
  11. s: linux.Stat
  12. errno := linux.fstat(fd, &s)
  13. if errno != .NONE {
  14. return {}, _get_platform_error(errno)
  15. }
  16. type := File_Type.Regular
  17. switch s.mode & linux.S_IFMT {
  18. case linux.S_IFBLK: type = .Block_Device
  19. case linux.S_IFCHR: type = .Character_Device
  20. case linux.S_IFDIR: type = .Directory
  21. case linux.S_IFIFO: type = .Named_Pipe
  22. case linux.S_IFLNK: type = .Symlink
  23. case linux.S_IFREG: type = .Regular
  24. case linux.S_IFSOCK: type = .Socket
  25. }
  26. mode := int(0o7777 & transmute(u32)s.mode)
  27. // TODO: As of Linux 4.11, the new statx syscall can retrieve creation_time
  28. fi = File_Info {
  29. fullpath = _get_full_path(fd, allocator) or_return,
  30. name = "",
  31. inode = u128(u64(s.ino)),
  32. size = i64(s.size),
  33. mode = mode,
  34. type = type,
  35. modification_time = time.Time {i64(s.mtime.time_sec) * i64(time.Second) + i64(s.mtime.time_nsec)},
  36. access_time = time.Time {i64(s.atime.time_sec) * i64(time.Second) + i64(s.atime.time_nsec)},
  37. creation_time = time.Time{i64(s.ctime.time_sec) * i64(time.Second) + i64(s.ctime.time_nsec)}, // regular stat does not provide this
  38. }
  39. fi.creation_time = fi.modification_time
  40. _, fi.name = split_path(fi.fullpath)
  41. return
  42. }
  43. // NOTE: _stat and _lstat are using _fstat to avoid a race condition when populating fullpath
  44. _stat :: proc(name: string, allocator: runtime.Allocator) -> (fi: File_Info, err: Error) {
  45. temp_allocator := TEMP_ALLOCATOR_GUARD({ allocator })
  46. name_cstr := clone_to_cstring(name, temp_allocator) or_return
  47. fd, errno := linux.open(name_cstr, {})
  48. if errno != .NONE {
  49. return {}, _get_platform_error(errno)
  50. }
  51. defer linux.close(fd)
  52. return _fstat_internal(fd, allocator)
  53. }
  54. _lstat :: proc(name: string, allocator: runtime.Allocator) -> (fi: File_Info, err: Error) {
  55. temp_allocator := TEMP_ALLOCATOR_GUARD({ allocator })
  56. name_cstr := clone_to_cstring(name, temp_allocator) or_return
  57. fd, errno := linux.open(name_cstr, {.PATH, .NOFOLLOW})
  58. if errno != .NONE {
  59. return {}, _get_platform_error(errno)
  60. }
  61. defer linux.close(fd)
  62. return _fstat_internal(fd, allocator)
  63. }
  64. _same_file :: proc(fi1, fi2: File_Info) -> bool {
  65. return fi1.fullpath == fi2.fullpath
  66. }