2
0

file_windows.odin 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. package os
  2. import win32 "core:sys/windows"
  3. import "core:intrinsics"
  4. import "core:unicode/utf16"
  5. is_path_separator :: proc(c: byte) -> bool {
  6. return c == '/' || c == '\\'
  7. }
  8. open :: proc(path: string, mode: int = O_RDONLY, perm: int = 0) -> (Handle, Errno) {
  9. if len(path) == 0 {
  10. return INVALID_HANDLE, ERROR_FILE_NOT_FOUND
  11. }
  12. access: u32
  13. switch mode & (O_RDONLY|O_WRONLY|O_RDWR) {
  14. case O_RDONLY: access = win32.FILE_GENERIC_READ
  15. case O_WRONLY: access = win32.FILE_GENERIC_WRITE
  16. case O_RDWR: access = win32.FILE_GENERIC_READ | win32.FILE_GENERIC_WRITE
  17. }
  18. if mode&O_CREATE != 0 {
  19. access |= win32.FILE_GENERIC_WRITE
  20. }
  21. if mode&O_APPEND != 0 {
  22. access &~= win32.FILE_GENERIC_WRITE
  23. access |= win32.FILE_APPEND_DATA
  24. }
  25. share_mode := win32.FILE_SHARE_READ|win32.FILE_SHARE_WRITE
  26. sa: ^win32.SECURITY_ATTRIBUTES = nil
  27. sa_inherit := win32.SECURITY_ATTRIBUTES{nLength = size_of(win32.SECURITY_ATTRIBUTES), bInheritHandle = true}
  28. if mode&O_CLOEXEC == 0 {
  29. sa = &sa_inherit
  30. }
  31. create_mode: u32
  32. switch {
  33. case mode&(O_CREATE|O_EXCL) == (O_CREATE | O_EXCL):
  34. create_mode = win32.CREATE_NEW
  35. case mode&(O_CREATE|O_TRUNC) == (O_CREATE | O_TRUNC):
  36. create_mode = win32.CREATE_ALWAYS
  37. case mode&O_CREATE == O_CREATE:
  38. create_mode = win32.OPEN_ALWAYS
  39. case mode&O_TRUNC == O_TRUNC:
  40. create_mode = win32.TRUNCATE_EXISTING
  41. case:
  42. create_mode = win32.OPEN_EXISTING
  43. }
  44. wide_path := win32.utf8_to_wstring(path)
  45. handle := Handle(win32.CreateFileW(wide_path, access, share_mode, sa, create_mode, win32.FILE_ATTRIBUTE_NORMAL|win32.FILE_FLAG_BACKUP_SEMANTICS, nil))
  46. if handle != INVALID_HANDLE {
  47. return handle, ERROR_NONE
  48. }
  49. err := Errno(win32.GetLastError())
  50. return INVALID_HANDLE, err
  51. }
  52. close :: proc(fd: Handle) -> Errno {
  53. if !win32.CloseHandle(win32.HANDLE(fd)) {
  54. return Errno(win32.GetLastError())
  55. }
  56. return ERROR_NONE
  57. }
  58. flush :: proc(fd: Handle) -> (err: Errno) {
  59. if !win32.FlushFileBuffers(win32.HANDLE(fd)) {
  60. err = Errno(win32.GetLastError())
  61. }
  62. return
  63. }
  64. write :: proc(fd: Handle, data: []byte) -> (int, Errno) {
  65. if len(data) == 0 {
  66. return 0, ERROR_NONE
  67. }
  68. single_write_length: win32.DWORD
  69. total_write: i64
  70. length := i64(len(data))
  71. for total_write < length {
  72. remaining := length - total_write
  73. to_write := win32.DWORD(min(i32(remaining), MAX_RW))
  74. e := win32.WriteFile(win32.HANDLE(fd), &data[total_write], to_write, &single_write_length, nil)
  75. if single_write_length <= 0 || !e {
  76. err := Errno(win32.GetLastError())
  77. return int(total_write), err
  78. }
  79. total_write += i64(single_write_length)
  80. }
  81. return int(total_write), ERROR_NONE
  82. }
  83. @(private="file")
  84. read_console :: proc(handle: win32.HANDLE, b: []byte) -> (n: int, err: Errno) {
  85. if len(b) == 0 {
  86. return 0, 0
  87. }
  88. BUF_SIZE :: 386
  89. buf16: [BUF_SIZE]u16
  90. buf8: [4*BUF_SIZE]u8
  91. for n < len(b) && err == 0 {
  92. min_read := max(len(b)/4, 1 if len(b) > 0 else 0)
  93. max_read := u32(min(BUF_SIZE, min_read))
  94. if max_read == 0 {
  95. break
  96. }
  97. single_read_length: u32
  98. ok := win32.ReadConsoleW(handle, &buf16[0], max_read, &single_read_length, nil)
  99. if !ok {
  100. err = Errno(win32.GetLastError())
  101. }
  102. buf8_len := utf16.decode_to_utf8(buf8[:], buf16[:single_read_length])
  103. src := buf8[:buf8_len]
  104. ctrl_z := false
  105. for i := 0; i < len(src) && n+i < len(b); i += 1 {
  106. x := src[i]
  107. if x == 0x1a { // ctrl-z
  108. ctrl_z = true
  109. break
  110. }
  111. b[n] = x
  112. n += 1
  113. }
  114. if ctrl_z || single_read_length < max_read {
  115. break
  116. }
  117. // NOTE(bill): if the last two values were a newline, then it is expected that
  118. // this is the end of the input
  119. if n >= 2 && single_read_length == max_read && string(b[n-2:n]) == "\r\n" {
  120. break
  121. }
  122. }
  123. return
  124. }
  125. read :: proc(fd: Handle, data: []byte) -> (int, Errno) {
  126. if len(data) == 0 {
  127. return 0, ERROR_NONE
  128. }
  129. handle := win32.HANDLE(fd)
  130. m: u32
  131. is_console := win32.GetConsoleMode(handle, &m)
  132. single_read_length: win32.DWORD
  133. total_read: int
  134. length := len(data)
  135. // NOTE(Jeroen): `length` can't be casted to win32.DWORD here because it'll overflow if > 4 GiB and return 0 if exactly that.
  136. to_read := min(i64(length), MAX_RW)
  137. e: win32.BOOL
  138. if is_console {
  139. n, err := read_console(handle, data[total_read:][:to_read])
  140. total_read += n
  141. if err != 0 {
  142. return int(total_read), err
  143. }
  144. } else {
  145. // NOTE(Jeroen): So we cast it here *after* we've ensured that `to_read` is at most MAX_RW (1 GiB)
  146. e = win32.ReadFile(handle, &data[total_read], win32.DWORD(to_read), &single_read_length, nil)
  147. }
  148. if single_read_length <= 0 || !e {
  149. err := Errno(win32.GetLastError())
  150. return int(total_read), err
  151. }
  152. total_read += int(single_read_length)
  153. return int(total_read), ERROR_NONE
  154. }
  155. seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Errno) {
  156. w: u32
  157. switch whence {
  158. case 0: w = win32.FILE_BEGIN
  159. case 1: w = win32.FILE_CURRENT
  160. case 2: w = win32.FILE_END
  161. }
  162. hi := i32(offset>>32)
  163. lo := i32(offset)
  164. ft := win32.GetFileType(win32.HANDLE(fd))
  165. if ft == win32.FILE_TYPE_PIPE {
  166. return 0, ERROR_FILE_IS_PIPE
  167. }
  168. dw_ptr := win32.SetFilePointer(win32.HANDLE(fd), lo, &hi, w)
  169. if dw_ptr == win32.INVALID_SET_FILE_POINTER {
  170. err := Errno(win32.GetLastError())
  171. return 0, err
  172. }
  173. return i64(hi)<<32 + i64(dw_ptr), ERROR_NONE
  174. }
  175. file_size :: proc(fd: Handle) -> (i64, Errno) {
  176. length: win32.LARGE_INTEGER
  177. err: Errno
  178. if !win32.GetFileSizeEx(win32.HANDLE(fd), &length) {
  179. err = Errno(win32.GetLastError())
  180. }
  181. return i64(length), err
  182. }
  183. @(private)
  184. MAX_RW :: 1<<30
  185. @(private)
  186. pread :: proc(fd: Handle, data: []byte, offset: i64) -> (int, Errno) {
  187. buf := data
  188. if len(buf) > MAX_RW {
  189. buf = buf[:MAX_RW]
  190. }
  191. curr_offset, e := seek(fd, offset, 1)
  192. if e != 0 {
  193. return 0, e
  194. }
  195. defer seek(fd, curr_offset, 0)
  196. o := win32.OVERLAPPED{
  197. OffsetHigh = u32(offset>>32),
  198. Offset = u32(offset),
  199. }
  200. // TODO(bill): Determine the correct behaviour for consoles
  201. h := win32.HANDLE(fd)
  202. done: win32.DWORD
  203. if !win32.ReadFile(h, raw_data(buf), u32(len(buf)), &done, &o) {
  204. e = Errno(win32.GetLastError())
  205. done = 0
  206. }
  207. return int(done), e
  208. }
  209. @(private)
  210. pwrite :: proc(fd: Handle, data: []byte, offset: i64) -> (int, Errno) {
  211. buf := data
  212. if len(buf) > MAX_RW {
  213. buf = buf[:MAX_RW]
  214. }
  215. curr_offset, e := seek(fd, offset, 1)
  216. if e != 0 {
  217. return 0, e
  218. }
  219. defer seek(fd, curr_offset, 0)
  220. o := win32.OVERLAPPED{
  221. OffsetHigh = u32(offset>>32),
  222. Offset = u32(offset),
  223. }
  224. h := win32.HANDLE(fd)
  225. done: win32.DWORD
  226. if !win32.WriteFile(h, raw_data(buf), u32(len(buf)), &done, &o) {
  227. e = Errno(win32.GetLastError())
  228. done = 0
  229. }
  230. return int(done), e
  231. }
  232. read_at :: proc(fd: Handle, data: []byte, offset: i64) -> (n: int, err: Errno) {
  233. if offset < 0 {
  234. return 0, ERROR_NEGATIVE_OFFSET
  235. }
  236. b, offset := data, offset
  237. for len(b) > 0 {
  238. m, e := pread(fd, b, offset)
  239. if e != 0 {
  240. err = e
  241. break
  242. }
  243. n += m
  244. b = b[m:]
  245. offset += i64(m)
  246. }
  247. return
  248. }
  249. write_at :: proc(fd: Handle, data: []byte, offset: i64) -> (n: int, err: Errno) {
  250. if offset < 0 {
  251. return 0, ERROR_NEGATIVE_OFFSET
  252. }
  253. b, offset := data, offset
  254. for len(b) > 0 {
  255. m, e := pwrite(fd, b, offset)
  256. if e != 0 {
  257. err = e
  258. break
  259. }
  260. n += m
  261. b = b[m:]
  262. offset += i64(m)
  263. }
  264. return
  265. }
  266. // NOTE(bill): Uses startup to initialize it
  267. stdin := get_std_handle(uint(win32.STD_INPUT_HANDLE))
  268. stdout := get_std_handle(uint(win32.STD_OUTPUT_HANDLE))
  269. stderr := get_std_handle(uint(win32.STD_ERROR_HANDLE))
  270. get_std_handle :: proc "contextless" (h: uint) -> Handle {
  271. fd := win32.GetStdHandle(win32.DWORD(h))
  272. return Handle(fd)
  273. }
  274. exists :: proc(path: string) -> bool {
  275. wpath := win32.utf8_to_wstring(path, context.temp_allocator)
  276. attribs := win32.GetFileAttributesW(wpath)
  277. return i32(attribs) != win32.INVALID_FILE_ATTRIBUTES
  278. }
  279. is_file :: proc(path: string) -> bool {
  280. wpath := win32.utf8_to_wstring(path, context.temp_allocator)
  281. attribs := win32.GetFileAttributesW(wpath)
  282. if i32(attribs) != win32.INVALID_FILE_ATTRIBUTES {
  283. return attribs & win32.FILE_ATTRIBUTE_DIRECTORY == 0
  284. }
  285. return false
  286. }
  287. is_dir :: proc(path: string) -> bool {
  288. wpath := win32.utf8_to_wstring(path, context.temp_allocator)
  289. attribs := win32.GetFileAttributesW(wpath)
  290. if i32(attribs) != win32.INVALID_FILE_ATTRIBUTES {
  291. return attribs & win32.FILE_ATTRIBUTE_DIRECTORY != 0
  292. }
  293. return false
  294. }
  295. // NOTE(tetra): GetCurrentDirectory is not thread safe with SetCurrentDirectory and GetFullPathName
  296. @private cwd_lock := win32.SRWLOCK{} // zero is initialized
  297. get_current_directory :: proc(allocator := context.allocator) -> string {
  298. win32.AcquireSRWLockExclusive(&cwd_lock)
  299. sz_utf16 := win32.GetCurrentDirectoryW(0, nil)
  300. dir_buf_wstr := make([]u16, sz_utf16, context.temp_allocator) // the first time, it _includes_ the NUL.
  301. sz_utf16 = win32.GetCurrentDirectoryW(win32.DWORD(len(dir_buf_wstr)), raw_data(dir_buf_wstr))
  302. assert(int(sz_utf16)+1 == len(dir_buf_wstr)) // the second time, it _excludes_ the NUL.
  303. win32.ReleaseSRWLockExclusive(&cwd_lock)
  304. return win32.utf16_to_utf8(dir_buf_wstr, allocator) or_else ""
  305. }
  306. set_current_directory :: proc(path: string) -> (err: Errno) {
  307. wstr := win32.utf8_to_wstring(path)
  308. win32.AcquireSRWLockExclusive(&cwd_lock)
  309. if !win32.SetCurrentDirectoryW(wstr) {
  310. err = Errno(win32.GetLastError())
  311. }
  312. win32.ReleaseSRWLockExclusive(&cwd_lock)
  313. return
  314. }
  315. change_directory :: proc(path: string) -> (err: Errno) {
  316. wpath := win32.utf8_to_wstring(path, context.temp_allocator)
  317. if !win32.SetCurrentDirectoryW(wpath) {
  318. err = Errno(win32.GetLastError())
  319. }
  320. return
  321. }
  322. make_directory :: proc(path: string, mode: u32 = 0) -> (err: Errno) {
  323. // Mode is unused on Windows, but is needed on *nix
  324. wpath := win32.utf8_to_wstring(path, context.temp_allocator)
  325. if !win32.CreateDirectoryW(wpath, nil) {
  326. err = Errno(win32.GetLastError())
  327. }
  328. return
  329. }
  330. remove_directory :: proc(path: string) -> (err: Errno) {
  331. wpath := win32.utf8_to_wstring(path, context.temp_allocator)
  332. if !win32.RemoveDirectoryW(wpath) {
  333. err = Errno(win32.GetLastError())
  334. }
  335. return
  336. }
  337. @(private)
  338. is_abs :: proc(path: string) -> bool {
  339. if len(path) > 0 && path[0] == '/' {
  340. return true
  341. }
  342. when ODIN_OS == .Windows {
  343. if len(path) > 2 {
  344. switch path[0] {
  345. case 'A'..='Z', 'a'..='z':
  346. return path[1] == ':' && is_path_separator(path[2])
  347. }
  348. }
  349. }
  350. return false
  351. }
  352. @(private)
  353. fix_long_path :: proc(path: string) -> string {
  354. if len(path) < 248 {
  355. return path
  356. }
  357. if len(path) >= 2 && path[:2] == `\\` {
  358. return path
  359. }
  360. if !is_abs(path) {
  361. return path
  362. }
  363. prefix :: `\\?`
  364. path_buf := make([]byte, len(prefix)+len(path)+len(`\`), context.temp_allocator)
  365. copy(path_buf, prefix)
  366. n := len(path)
  367. r, w := 0, len(prefix)
  368. for r < n {
  369. switch {
  370. case is_path_separator(path[r]):
  371. r += 1
  372. case path[r] == '.' && (r+1 == n || is_path_separator(path[r+1])):
  373. r += 1
  374. case r+1 < n && path[r] == '.' && path[r+1] == '.' && (r+2 == n || is_path_separator(path[r+2])):
  375. return path
  376. case:
  377. path_buf[w] = '\\'
  378. w += 1
  379. for ; r < n && !is_path_separator(path[r]); r += 1 {
  380. path_buf[w] = path[r]
  381. w += 1
  382. }
  383. }
  384. }
  385. if w == len(`\\?\c:`) {
  386. path_buf[w] = '\\'
  387. w += 1
  388. }
  389. return string(path_buf[:w])
  390. }
  391. link :: proc(old_name, new_name: string) -> (err: Errno) {
  392. n := win32.utf8_to_wstring(fix_long_path(new_name))
  393. o := win32.utf8_to_wstring(fix_long_path(old_name))
  394. return Errno(win32.CreateHardLinkW(n, o, nil))
  395. }
  396. unlink :: proc(path: string) -> (err: Errno) {
  397. wpath := win32.utf8_to_wstring(path, context.temp_allocator)
  398. if !win32.DeleteFileW(wpath) {
  399. err = Errno(win32.GetLastError())
  400. }
  401. return
  402. }
  403. rename :: proc(old_path, new_path: string) -> (err: Errno) {
  404. from := win32.utf8_to_wstring(old_path, context.temp_allocator)
  405. to := win32.utf8_to_wstring(new_path, context.temp_allocator)
  406. if !win32.MoveFileExW(from, to, win32.MOVEFILE_REPLACE_EXISTING) {
  407. err = Errno(win32.GetLastError())
  408. }
  409. return
  410. }
  411. ftruncate :: proc(fd: Handle, length: i64) -> (err: Errno) {
  412. curr_off, e := seek(fd, 0, 1)
  413. if e != 0 {
  414. return e
  415. }
  416. defer seek(fd, curr_off, 0)
  417. _, e = seek(fd, length, 0)
  418. if e != 0 {
  419. return e
  420. }
  421. ok := win32.SetEndOfFile(win32.HANDLE(fd))
  422. if !ok {
  423. return Errno(win32.GetLastError())
  424. }
  425. return ERROR_NONE
  426. }
  427. truncate :: proc(path: string, length: i64) -> (err: Errno) {
  428. fd: Handle
  429. fd, err = open(path, O_WRONLY|O_CREATE, 0o666)
  430. if err != 0 {
  431. return
  432. }
  433. defer close(fd)
  434. err = ftruncate(fd, length)
  435. return
  436. }
  437. remove :: proc(name: string) -> Errno {
  438. p := win32.utf8_to_wstring(fix_long_path(name))
  439. err, err1: win32.DWORD
  440. if !win32.DeleteFileW(p) {
  441. err = win32.GetLastError()
  442. }
  443. if err == 0 {
  444. return 0
  445. }
  446. if !win32.RemoveDirectoryW(p) {
  447. err1 = win32.GetLastError()
  448. }
  449. if err1 == 0 {
  450. return 0
  451. }
  452. if err != err1 {
  453. a := win32.GetFileAttributesW(p)
  454. if a == ~u32(0) {
  455. err = win32.GetLastError()
  456. } else {
  457. if a & win32.FILE_ATTRIBUTE_DIRECTORY != 0 {
  458. err = err1
  459. } else if a & win32.FILE_ATTRIBUTE_READONLY != 0 {
  460. if win32.SetFileAttributesW(p, a &~ win32.FILE_ATTRIBUTE_READONLY) {
  461. err = 0
  462. if !win32.DeleteFileW(p) {
  463. err = win32.GetLastError()
  464. }
  465. }
  466. }
  467. }
  468. }
  469. return Errno(err)
  470. }
  471. pipe :: proc() -> (r, w: Handle, err: Errno) {
  472. sa: win32.SECURITY_ATTRIBUTES
  473. sa.nLength = size_of(win32.SECURITY_ATTRIBUTES)
  474. sa.bInheritHandle = true
  475. if !win32.CreatePipe((^win32.HANDLE)(&r), (^win32.HANDLE)(&w), &sa, 0) {
  476. err = Errno(win32.GetLastError())
  477. }
  478. return
  479. }