file_windows.odin 12 KB

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