file_windows.odin 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. to_read := min(win32.DWORD(length), MAX_RW)
  136. e: win32.BOOL
  137. if is_console {
  138. n, err := read_console(handle, data[total_read:][:to_read])
  139. total_read += n
  140. if err != 0 {
  141. return int(total_read), err
  142. }
  143. } else {
  144. e = win32.ReadFile(handle, &data[total_read], to_read, &single_read_length, nil)
  145. }
  146. if single_read_length <= 0 || !e {
  147. err := Errno(win32.GetLastError())
  148. return int(total_read), err
  149. }
  150. total_read += int(single_read_length)
  151. return int(total_read), ERROR_NONE
  152. }
  153. seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Errno) {
  154. w: u32
  155. switch whence {
  156. case 0: w = win32.FILE_BEGIN
  157. case 1: w = win32.FILE_CURRENT
  158. case 2: w = win32.FILE_END
  159. }
  160. hi := i32(offset>>32)
  161. lo := i32(offset)
  162. ft := win32.GetFileType(win32.HANDLE(fd))
  163. if ft == win32.FILE_TYPE_PIPE {
  164. return 0, ERROR_FILE_IS_PIPE
  165. }
  166. dw_ptr := win32.SetFilePointer(win32.HANDLE(fd), lo, &hi, w)
  167. if dw_ptr == win32.INVALID_SET_FILE_POINTER {
  168. err := Errno(win32.GetLastError())
  169. return 0, err
  170. }
  171. return i64(hi)<<32 + i64(dw_ptr), ERROR_NONE
  172. }
  173. file_size :: proc(fd: Handle) -> (i64, Errno) {
  174. length: win32.LARGE_INTEGER
  175. err: Errno
  176. if !win32.GetFileSizeEx(win32.HANDLE(fd), &length) {
  177. err = Errno(win32.GetLastError())
  178. }
  179. return i64(length), err
  180. }
  181. @(private)
  182. MAX_RW :: 1<<30
  183. @(private)
  184. pread :: proc(fd: Handle, data: []byte, offset: i64) -> (int, Errno) {
  185. buf := data
  186. if len(buf) > MAX_RW {
  187. buf = buf[:MAX_RW]
  188. }
  189. curr_offset, e := seek(fd, offset, 1)
  190. if e != 0 {
  191. return 0, e
  192. }
  193. defer seek(fd, curr_offset, 0)
  194. o := win32.OVERLAPPED{
  195. OffsetHigh = u32(offset>>32),
  196. Offset = u32(offset),
  197. }
  198. // TODO(bill): Determine the correct behaviour for consoles
  199. h := win32.HANDLE(fd)
  200. done: win32.DWORD
  201. if !win32.ReadFile(h, raw_data(buf), u32(len(buf)), &done, &o) {
  202. e = Errno(win32.GetLastError())
  203. done = 0
  204. }
  205. return int(done), e
  206. }
  207. @(private)
  208. pwrite :: proc(fd: Handle, data: []byte, offset: i64) -> (int, Errno) {
  209. buf := data
  210. if len(buf) > MAX_RW {
  211. buf = buf[:MAX_RW]
  212. }
  213. curr_offset, e := seek(fd, offset, 1)
  214. if e != 0 {
  215. return 0, e
  216. }
  217. defer seek(fd, curr_offset, 0)
  218. o := win32.OVERLAPPED{
  219. OffsetHigh = u32(offset>>32),
  220. Offset = u32(offset),
  221. }
  222. h := win32.HANDLE(fd)
  223. done: win32.DWORD
  224. if !win32.WriteFile(h, raw_data(buf), u32(len(buf)), &done, &o) {
  225. e = Errno(win32.GetLastError())
  226. done = 0
  227. }
  228. return int(done), e
  229. }
  230. read_at :: proc(fd: Handle, data: []byte, offset: i64) -> (n: int, err: Errno) {
  231. if offset < 0 {
  232. return 0, ERROR_NEGATIVE_OFFSET
  233. }
  234. b, offset := data, offset
  235. for len(b) > 0 {
  236. m, e := pread(fd, b, offset)
  237. if e != 0 {
  238. err = e
  239. break
  240. }
  241. n += m
  242. b = b[m:]
  243. offset += i64(m)
  244. }
  245. return
  246. }
  247. write_at :: proc(fd: Handle, data: []byte, offset: i64) -> (n: int, err: Errno) {
  248. if offset < 0 {
  249. return 0, ERROR_NEGATIVE_OFFSET
  250. }
  251. b, offset := data, offset
  252. for len(b) > 0 {
  253. m, e := pwrite(fd, b, offset)
  254. if e != 0 {
  255. err = e
  256. break
  257. }
  258. n += m
  259. b = b[m:]
  260. offset += i64(m)
  261. }
  262. return
  263. }
  264. // NOTE(bill): Uses startup to initialize it
  265. stdin := get_std_handle(uint(win32.STD_INPUT_HANDLE))
  266. stdout := get_std_handle(uint(win32.STD_OUTPUT_HANDLE))
  267. stderr := get_std_handle(uint(win32.STD_ERROR_HANDLE))
  268. get_std_handle :: proc "contextless" (h: uint) -> Handle {
  269. fd := win32.GetStdHandle(win32.DWORD(h))
  270. return Handle(fd)
  271. }
  272. exists :: proc(path: string) -> bool {
  273. wpath := win32.utf8_to_wstring(path, context.temp_allocator)
  274. attribs := win32.GetFileAttributesW(wpath)
  275. return i32(attribs) != win32.INVALID_FILE_ATTRIBUTES
  276. }
  277. is_file :: proc(path: string) -> bool {
  278. wpath := win32.utf8_to_wstring(path, context.temp_allocator)
  279. attribs := win32.GetFileAttributesW(wpath)
  280. if i32(attribs) != win32.INVALID_FILE_ATTRIBUTES {
  281. return attribs & win32.FILE_ATTRIBUTE_DIRECTORY == 0
  282. }
  283. return false
  284. }
  285. is_dir :: proc(path: string) -> bool {
  286. wpath := win32.utf8_to_wstring(path, context.temp_allocator)
  287. attribs := win32.GetFileAttributesW(wpath)
  288. if i32(attribs) != win32.INVALID_FILE_ATTRIBUTES {
  289. return attribs & win32.FILE_ATTRIBUTE_DIRECTORY != 0
  290. }
  291. return false
  292. }
  293. // NOTE(tetra): GetCurrentDirectory is not thread safe with SetCurrentDirectory and GetFullPathName
  294. @private cwd_lock := win32.SRWLOCK{} // zero is initialized
  295. get_current_directory :: proc(allocator := context.allocator) -> string {
  296. win32.AcquireSRWLockExclusive(&cwd_lock)
  297. sz_utf16 := win32.GetCurrentDirectoryW(0, nil)
  298. dir_buf_wstr := make([]u16, sz_utf16, context.temp_allocator) // the first time, it _includes_ the NUL.
  299. sz_utf16 = win32.GetCurrentDirectoryW(win32.DWORD(len(dir_buf_wstr)), raw_data(dir_buf_wstr))
  300. assert(int(sz_utf16)+1 == len(dir_buf_wstr)) // the second time, it _excludes_ the NUL.
  301. win32.ReleaseSRWLockExclusive(&cwd_lock)
  302. return win32.utf16_to_utf8(dir_buf_wstr, allocator) or_else ""
  303. }
  304. set_current_directory :: proc(path: string) -> (err: Errno) {
  305. wstr := win32.utf8_to_wstring(path)
  306. win32.AcquireSRWLockExclusive(&cwd_lock)
  307. if !win32.SetCurrentDirectoryW(wstr) {
  308. err = Errno(win32.GetLastError())
  309. }
  310. win32.ReleaseSRWLockExclusive(&cwd_lock)
  311. return
  312. }
  313. change_directory :: proc(path: string) -> Errno {
  314. wpath := win32.utf8_to_wstring(path, context.temp_allocator)
  315. return Errno(win32.SetCurrentDirectoryW(wpath))
  316. }
  317. make_directory :: proc(path: string, mode: u32 = 0) -> Errno {
  318. // Mode is unused on Windows, but is needed on *nix
  319. wpath := win32.utf8_to_wstring(path, context.temp_allocator)
  320. return Errno(win32.CreateDirectoryW(wpath, nil))
  321. }
  322. remove_directory :: proc(path: string) -> Errno {
  323. wpath := win32.utf8_to_wstring(path, context.temp_allocator)
  324. return Errno(win32.RemoveDirectoryW(wpath))
  325. }
  326. @(private)
  327. is_abs :: proc(path: string) -> bool {
  328. if len(path) > 0 && path[0] == '/' {
  329. return true
  330. }
  331. when ODIN_OS == .Windows {
  332. if len(path) > 2 {
  333. switch path[0] {
  334. case 'A'..='Z', 'a'..='z':
  335. return path[1] == ':' && is_path_separator(path[2])
  336. }
  337. }
  338. }
  339. return false
  340. }
  341. @(private)
  342. fix_long_path :: proc(path: string) -> string {
  343. if len(path) < 248 {
  344. return path
  345. }
  346. if len(path) >= 2 && path[:2] == `\\` {
  347. return path
  348. }
  349. if !is_abs(path) {
  350. return path
  351. }
  352. prefix :: `\\?`
  353. path_buf := make([]byte, len(prefix)+len(path)+len(`\`), context.temp_allocator)
  354. copy(path_buf, prefix)
  355. n := len(path)
  356. r, w := 0, len(prefix)
  357. for r < n {
  358. switch {
  359. case is_path_separator(path[r]):
  360. r += 1
  361. case path[r] == '.' && (r+1 == n || is_path_separator(path[r+1])):
  362. r += 1
  363. case r+1 < n && path[r] == '.' && path[r+1] == '.' && (r+2 == n || is_path_separator(path[r+2])):
  364. return path
  365. case:
  366. path_buf[w] = '\\'
  367. w += 1
  368. for ; r < n && !is_path_separator(path[r]); r += 1 {
  369. path_buf[w] = path[r]
  370. w += 1
  371. }
  372. }
  373. }
  374. if w == len(`\\?\c:`) {
  375. path_buf[w] = '\\'
  376. w += 1
  377. }
  378. return string(path_buf[:w])
  379. }
  380. link :: proc(old_name, new_name: string) -> Errno {
  381. n := win32.utf8_to_wstring(fix_long_path(new_name))
  382. o := win32.utf8_to_wstring(fix_long_path(old_name))
  383. return Errno(win32.CreateHardLinkW(n, o, nil))
  384. }
  385. unlink :: proc(path: string) -> Errno {
  386. wpath := win32.utf8_to_wstring(path, context.temp_allocator)
  387. return Errno(win32.DeleteFileW(wpath))
  388. }
  389. rename :: proc(old_path, new_path: string) -> Errno {
  390. from := win32.utf8_to_wstring(old_path, context.temp_allocator)
  391. to := win32.utf8_to_wstring(new_path, context.temp_allocator)
  392. return Errno(win32.MoveFileExW(from, to, win32.MOVEFILE_REPLACE_EXISTING))
  393. }
  394. ftruncate :: proc(fd: Handle, length: i64) -> (err: Errno) {
  395. curr_off, e := seek(fd, 0, 1)
  396. if e != 0 {
  397. return e
  398. }
  399. defer seek(fd, curr_off, 0)
  400. _, e = seek(fd, length, 0)
  401. if e != 0 {
  402. return e
  403. }
  404. ok := win32.SetEndOfFile(win32.HANDLE(fd))
  405. if !ok {
  406. return Errno(win32.GetLastError())
  407. }
  408. return ERROR_NONE
  409. }
  410. truncate :: proc(path: string, length: i64) -> (err: Errno) {
  411. fd: Handle
  412. fd, err = open(path, O_WRONLY|O_CREATE, 0o666)
  413. if err != 0 {
  414. return
  415. }
  416. defer close(fd)
  417. err = ftruncate(fd, length)
  418. return
  419. }
  420. remove :: proc(name: string) -> Errno {
  421. p := win32.utf8_to_wstring(fix_long_path(name))
  422. err, err1: win32.DWORD
  423. if !win32.DeleteFileW(p) {
  424. err = win32.GetLastError()
  425. }
  426. if err == 0 {
  427. return 0
  428. }
  429. if !win32.RemoveDirectoryW(p) {
  430. err1 = win32.GetLastError()
  431. }
  432. if err1 == 0 {
  433. return 0
  434. }
  435. if err != err1 {
  436. a := win32.GetFileAttributesW(p)
  437. if a == ~u32(0) {
  438. err = win32.GetLastError()
  439. } else {
  440. if a & win32.FILE_ATTRIBUTE_DIRECTORY != 0 {
  441. err = err1
  442. } else if a & win32.FILE_ATTRIBUTE_READONLY != 0 {
  443. if win32.SetFileAttributesW(p, a &~ win32.FILE_ATTRIBUTE_READONLY) {
  444. err = 0
  445. if !win32.DeleteFileW(p) {
  446. err = win32.GetLastError()
  447. }
  448. }
  449. }
  450. }
  451. }
  452. return Errno(err)
  453. }
  454. pipe :: proc() -> (r, w: Handle, err: Errno) {
  455. sa: win32.SECURITY_ATTRIBUTES
  456. sa.nLength = size_of(win32.SECURITY_ATTRIBUTES)
  457. sa.bInheritHandle = true
  458. if !win32.CreatePipe((^win32.HANDLE)(&r), (^win32.HANDLE)(&w), &sa, 0) {
  459. err = Errno(win32.GetLastError())
  460. }
  461. return
  462. }