os_linux.odin 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. package os
  2. foreign import dl "system:dl"
  3. foreign import libc "system:c"
  4. import "core:runtime"
  5. import "core:strings"
  6. import "core:c"
  7. import "core:strconv"
  8. Handle :: distinct i32;
  9. File_Time :: distinct u64;
  10. Errno :: distinct i32;
  11. Syscall :: distinct i32;
  12. INVALID_HANDLE :: ~Handle(0);
  13. ERROR_NONE: Errno : 0;
  14. EPERM: Errno : 1;
  15. ENOENT: Errno : 2;
  16. ESRCH: Errno : 3;
  17. EINTR: Errno : 4;
  18. EIO: Errno : 5;
  19. ENXIO: Errno : 6;
  20. EBADF: Errno : 9;
  21. EAGAIN: Errno : 11;
  22. ENOMEM: Errno : 12;
  23. EACCES: Errno : 13;
  24. EFAULT: Errno : 14;
  25. EEXIST: Errno : 17;
  26. ENODEV: Errno : 19;
  27. ENOTDIR: Errno : 20;
  28. EISDIR: Errno : 21;
  29. EINVAL: Errno : 22;
  30. ENFILE: Errno : 23;
  31. EMFILE: Errno : 24;
  32. ETXTBSY: Errno : 26;
  33. EFBIG: Errno : 27;
  34. ENOSPC: Errno : 28;
  35. ESPIPE: Errno : 29;
  36. EROFS: Errno : 30;
  37. EPIPE: Errno : 32;
  38. ERANGE: Errno : 34; /* Result too large */
  39. EDEADLK: Errno : 35; /* Resource deadlock would occur */
  40. ENAMETOOLONG: Errno : 36; /* File name too long */
  41. ENOLCK: Errno : 37; /* No record locks available */
  42. ENOSYS: Errno : 38; /* Invalid system call number */
  43. ENOTEMPTY: Errno : 39; /* Directory not empty */
  44. ELOOP: Errno : 40; /* Too many symbolic links encountered */
  45. EWOULDBLOCK: Errno : EAGAIN; /* Operation would block */
  46. ENOMSG: Errno : 42; /* No message of desired type */
  47. EIDRM: Errno : 43; /* Identifier removed */
  48. ECHRNG: Errno : 44; /* Channel number out of range */
  49. EL2NSYNC: Errno : 45; /* Level 2 not synchronized */
  50. EL3HLT: Errno : 46; /* Level 3 halted */
  51. EL3RST: Errno : 47; /* Level 3 reset */
  52. ELNRNG: Errno : 48; /* Link number out of range */
  53. EUNATCH: Errno : 49; /* Protocol driver not attached */
  54. ENOCSI: Errno : 50; /* No CSI structure available */
  55. EL2HLT: Errno : 51; /* Level 2 halted */
  56. EBADE: Errno : 52; /* Invalid exchange */
  57. EBADR: Errno : 53; /* Invalid request descriptor */
  58. EXFULL: Errno : 54; /* Exchange full */
  59. ENOANO: Errno : 55; /* No anode */
  60. EBADRQC: Errno : 56; /* Invalid request code */
  61. EBADSLT: Errno : 57; /* Invalid slot */
  62. EDEADLOCK: Errno : EDEADLK;
  63. EBFONT: Errno : 59; /* Bad font file format */
  64. ENOSTR: Errno : 60; /* Device not a stream */
  65. ENODATA: Errno : 61; /* No data available */
  66. ETIME: Errno : 62; /* Timer expired */
  67. ENOSR: Errno : 63; /* Out of streams resources */
  68. ENONET: Errno : 64; /* Machine is not on the network */
  69. ENOPKG: Errno : 65; /* Package not installed */
  70. EREMOTE: Errno : 66; /* Object is remote */
  71. ENOLINK: Errno : 67; /* Link has been severed */
  72. EADV: Errno : 68; /* Advertise error */
  73. ESRMNT: Errno : 69; /* Srmount error */
  74. ECOMM: Errno : 70; /* Communication error on send */
  75. EPROTO: Errno : 71; /* Protocol error */
  76. EMULTIHOP: Errno : 72; /* Multihop attempted */
  77. EDOTDOT: Errno : 73; /* RFS specific error */
  78. EBADMSG: Errno : 74; /* Not a data message */
  79. EOVERFLOW: Errno : 75; /* Value too large for defined data type */
  80. ENOTUNIQ: Errno : 76; /* Name not unique on network */
  81. EBADFD: Errno : 77; /* File descriptor in bad state */
  82. EREMCHG: Errno : 78; /* Remote address changed */
  83. ELIBACC: Errno : 79; /* Can not access a needed shared library */
  84. ELIBBAD: Errno : 80; /* Accessing a corrupted shared library */
  85. ELIBSCN: Errno : 81; /* .lib section in a.out corrupted */
  86. ELIBMAX: Errno : 82; /* Attempting to link in too many shared libraries */
  87. ELIBEXEC: Errno : 83; /* Cannot exec a shared library directly */
  88. EILSEQ: Errno : 84; /* Illegal byte sequence */
  89. ERESTART: Errno : 85; /* Interrupted system call should be restarted */
  90. ESTRPIPE: Errno : 86; /* Streams pipe error */
  91. EUSERS: Errno : 87; /* Too many users */
  92. ENOTSOCK: Errno : 88; /* Socket operation on non-socket */
  93. EDESTADDRREQ: Errno : 89; /* Destination address required */
  94. EMSGSIZE: Errno : 90; /* Message too long */
  95. EPROTOTYPE: Errno : 91; /* Protocol wrong type for socket */
  96. ENOPROTOOPT: Errno : 92; /* Protocol not available */
  97. EPROTONOSUPPORT:Errno : 93; /* Protocol not supported */
  98. ESOCKTNOSUPPORT:Errno : 94; /* Socket type not supported */
  99. EOPNOTSUPP: Errno : 95; /* Operation not supported on transport endpoint */
  100. EPFNOSUPPORT: Errno : 96; /* Protocol family not supported */
  101. EAFNOSUPPORT: Errno : 97; /* Address family not supported by protocol */
  102. EADDRINUSE: Errno : 98; /* Address already in use */
  103. EADDRNOTAVAIL: Errno : 99; /* Cannot assign requested address */
  104. ENETDOWN: Errno : 100; /* Network is down */
  105. ENETUNREACH: Errno : 101; /* Network is unreachable */
  106. ENETRESET: Errno : 102; /* Network dropped connection because of reset */
  107. ECONNABORTED: Errno : 103; /* Software caused connection abort */
  108. ECONNRESET: Errno : 104; /* Connection reset by peer */
  109. ENOBUFS: Errno : 105; /* No buffer space available */
  110. EISCONN: Errno : 106; /* Transport endpoint is already connected */
  111. ENOTCONN: Errno : 107; /* Transport endpoint is not connected */
  112. ESHUTDOWN: Errno : 108; /* Cannot send after transport endpoint shutdown */
  113. ETOOMANYREFS: Errno : 109; /* Too many references: cannot splice */
  114. ETIMEDOUT: Errno : 110; /* Connection timed out */
  115. ECONNREFUSED: Errno : 111; /* Connection refused */
  116. EHOSTDOWN: Errno : 112; /* Host is down */
  117. EHOSTUNREACH: Errno : 113; /* No route to host */
  118. EALREADY: Errno : 114; /* Operation already in progress */
  119. EINPROGRESS: Errno : 115; /* Operation now in progress */
  120. ESTALE: Errno : 116; /* Stale file handle */
  121. EUCLEAN: Errno : 117; /* Structure needs cleaning */
  122. ENOTNAM: Errno : 118; /* Not a XENIX named type file */
  123. ENAVAIL: Errno : 119; /* No XENIX semaphores available */
  124. EISNAM: Errno : 120; /* Is a named type file */
  125. EREMOTEIO: Errno : 121; /* Remote I/O error */
  126. EDQUOT: Errno : 122; /* Quota exceeded */
  127. ENOMEDIUM: Errno : 123; /* No medium found */
  128. EMEDIUMTYPE: Errno : 124; /* Wrong medium type */
  129. ECANCELED: Errno : 125; /* Operation Canceled */
  130. ENOKEY: Errno : 126; /* Required key not available */
  131. EKEYEXPIRED: Errno : 127; /* Key has expired */
  132. EKEYREVOKED: Errno : 128; /* Key has been revoked */
  133. EKEYREJECTED: Errno : 129; /* Key was rejected by service */
  134. /* for robust mutexes */
  135. EOWNERDEAD: Errno : 130; /* Owner died */
  136. ENOTRECOVERABLE: Errno : 131; /* State not recoverable */
  137. ERFKILL: Errno : 132; /* Operation not possible due to RF-kill */
  138. EHWPOISON: Errno : 133; /* Memory page has hardware error */
  139. O_RDONLY :: 0x00000;
  140. O_WRONLY :: 0x00001;
  141. O_RDWR :: 0x00002;
  142. O_CREATE :: 0x00040;
  143. O_EXCL :: 0x00080;
  144. O_NOCTTY :: 0x00100;
  145. O_TRUNC :: 0x00200;
  146. O_NONBLOCK :: 0x00800;
  147. O_APPEND :: 0x00400;
  148. O_SYNC :: 0x01000;
  149. O_ASYNC :: 0x02000;
  150. O_CLOEXEC :: 0x80000;
  151. SEEK_SET :: 0;
  152. SEEK_CUR :: 1;
  153. SEEK_END :: 2;
  154. SEEK_DATA :: 3;
  155. SEEK_HOLE :: 4;
  156. SEEK_MAX :: SEEK_HOLE;
  157. // NOTE(zangent): These are OS specific!
  158. // Do not mix these up!
  159. RTLD_LAZY :: 0x001;
  160. RTLD_NOW :: 0x002;
  161. RTLD_BINDING_MASK :: 0x3;
  162. RTLD_GLOBAL :: 0x100;
  163. // "Argv" arguments converted to Odin strings
  164. args := _alloc_command_line_arguments();
  165. Unix_File_Time :: struct {
  166. seconds: i64,
  167. nanoseconds: i64,
  168. }
  169. OS_Stat :: struct {
  170. device_id: u64, // ID of device containing file
  171. serial: u64, // File serial number
  172. nlink: u64, // Number of hard links
  173. mode: u32, // Mode of the file
  174. uid: u32, // User ID of the file's owner
  175. gid: u32, // Group ID of the file's group
  176. _padding: i32, // 32 bits of padding
  177. rdev: u64, // Device ID, if device
  178. size: i64, // Size of the file, in bytes
  179. block_size: i64, // Optimal bllocksize for I/O
  180. blocks: i64, // Number of 512-byte blocks allocated
  181. last_access: Unix_File_Time, // Time of last access
  182. modified: Unix_File_Time, // Time of last modification
  183. status_change: Unix_File_Time, // Time of last status change
  184. _reserve1,
  185. _reserve2,
  186. _reserve3: i64,
  187. };
  188. // NOTE(laleksic, 2021-01-21): Comment and rename these to match OS_Stat above
  189. Dirent :: struct {
  190. ino: u64,
  191. off: u64,
  192. reclen: u16,
  193. type: u8,
  194. name: [256]byte,
  195. };
  196. Dir :: distinct rawptr; // DIR*
  197. // File type
  198. S_IFMT :: 0o170000; // Type of file mask
  199. S_IFIFO :: 0o010000; // Named pipe (fifo)
  200. S_IFCHR :: 0o020000; // Character special
  201. S_IFDIR :: 0o040000; // Directory
  202. S_IFBLK :: 0o060000; // Block special
  203. S_IFREG :: 0o100000; // Regular
  204. S_IFLNK :: 0o120000; // Symbolic link
  205. S_IFSOCK :: 0o140000; // Socket
  206. // File mode
  207. // Read, write, execute/search by owner
  208. S_IRWXU :: 0o0700; // RWX mask for owner
  209. S_IRUSR :: 0o0400; // R for owner
  210. S_IWUSR :: 0o0200; // W for owner
  211. S_IXUSR :: 0o0100; // X for owner
  212. // Read, write, execute/search by group
  213. S_IRWXG :: 0o0070; // RWX mask for group
  214. S_IRGRP :: 0o0040; // R for group
  215. S_IWGRP :: 0o0020; // W for group
  216. S_IXGRP :: 0o0010; // X for group
  217. // Read, write, execute/search by others
  218. S_IRWXO :: 0o0007; // RWX mask for other
  219. S_IROTH :: 0o0004; // R for other
  220. S_IWOTH :: 0o0002; // W for other
  221. S_IXOTH :: 0o0001; // X for other
  222. S_ISUID :: 0o4000; // Set user id on execution
  223. S_ISGID :: 0o2000; // Set group id on execution
  224. S_ISVTX :: 0o1000; // Directory restrcted delete
  225. S_ISLNK :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFLNK; }
  226. S_ISREG :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFREG; }
  227. S_ISDIR :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFDIR; }
  228. S_ISCHR :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFCHR; }
  229. S_ISBLK :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFBLK; }
  230. S_ISFIFO :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFIFO; }
  231. S_ISSOCK :: #force_inline proc(m: u32) -> bool { return (m & S_IFMT) == S_IFSOCK; }
  232. F_OK :: 0; // Test for file existance
  233. X_OK :: 1; // Test for execute permission
  234. W_OK :: 2; // Test for write permission
  235. R_OK :: 4; // Test for read permission
  236. SYS_GETTID: Syscall : 186;
  237. foreign libc {
  238. @(link_name="__errno_location") __errno_location :: proc() -> ^int ---;
  239. @(link_name="syscall") syscall :: proc(number: Syscall, #c_vararg args: ..any) -> i32 ---;
  240. @(link_name="open") _unix_open :: proc(path: cstring, flags: c.int, mode: c.int) -> Handle ---;
  241. @(link_name="close") _unix_close :: proc(fd: Handle) -> c.int ---;
  242. @(link_name="read") _unix_read :: proc(fd: Handle, buf: rawptr, size: c.size_t) -> c.ssize_t ---;
  243. @(link_name="write") _unix_write :: proc(fd: Handle, buf: rawptr, size: c.size_t) -> c.ssize_t ---;
  244. @(link_name="lseek64") _unix_seek :: proc(fd: Handle, offset: i64, whence: c.int) -> i64 ---;
  245. @(link_name="gettid") _unix_gettid :: proc() -> u64 ---;
  246. @(link_name="getpagesize") _unix_getpagesize :: proc() -> c.int ---;
  247. @(link_name="stat64") _unix_stat :: proc(path: cstring, stat: ^OS_Stat) -> c.int ---;
  248. @(link_name="lstat") _unix_lstat :: proc(path: cstring, stat: ^OS_Stat) -> c.int ---;
  249. @(link_name="fstat") _unix_fstat :: proc(fd: Handle, stat: ^OS_Stat) -> c.int ---;
  250. @(link_name="fdopendir") _unix_fdopendir :: proc(fd: Handle) -> Dir ---;
  251. @(link_name="closedir") _unix_closedir :: proc(dirp: Dir) -> c.int ---;
  252. @(link_name="rewinddir") _unix_rewinddir :: proc(dirp: Dir) ---;
  253. @(link_name="readdir_r") _unix_readdir_r :: proc(dirp: Dir, entry: ^Dirent, result: ^^Dirent) -> c.int ---;
  254. @(link_name="readlink") _unix_readlink :: proc(path: cstring, buf: ^byte, bufsiz: c.size_t) -> c.ssize_t ---;
  255. @(link_name="access") _unix_access :: proc(path: cstring, mask: c.int) -> c.int ---;
  256. @(link_name="malloc") _unix_malloc :: proc(size: c.size_t) -> rawptr ---;
  257. @(link_name="calloc") _unix_calloc :: proc(num, size: c.size_t) -> rawptr ---;
  258. @(link_name="free") _unix_free :: proc(ptr: rawptr) ---;
  259. @(link_name="realloc") _unix_realloc :: proc(ptr: rawptr, size: c.size_t) -> rawptr ---;
  260. @(link_name="getenv") _unix_getenv :: proc(cstring) -> cstring ---;
  261. @(link_name="getcwd") _unix_getcwd :: proc(buf: cstring, len: c.size_t) -> cstring ---;
  262. @(link_name="chdir") _unix_chdir :: proc(buf: cstring) -> c.int ---;
  263. @(link_name="realpath") _unix_realpath :: proc(path: cstring, resolved_path: rawptr) -> rawptr ---;
  264. @(link_name="exit") _unix_exit :: proc(status: c.int) -> ! ---;
  265. }
  266. foreign dl {
  267. @(link_name="dlopen") _unix_dlopen :: proc(filename: cstring, flags: c.int) -> rawptr ---;
  268. @(link_name="dlsym") _unix_dlsym :: proc(handle: rawptr, symbol: cstring) -> rawptr ---;
  269. @(link_name="dlclose") _unix_dlclose :: proc(handle: rawptr) -> c.int ---;
  270. @(link_name="dlerror") _unix_dlerror :: proc() -> cstring ---;
  271. }
  272. is_path_separator :: proc(r: rune) -> bool {
  273. return r == '/';
  274. }
  275. get_last_error :: proc() -> int {
  276. return __errno_location()^;
  277. }
  278. open :: proc(path: string, flags: int = O_RDONLY, mode: int = 0) -> (Handle, Errno) {
  279. cstr := strings.clone_to_cstring(path);
  280. handle := _unix_open(cstr, c.int(flags), c.int(mode));
  281. delete(cstr);
  282. if handle == -1 {
  283. return INVALID_HANDLE, Errno(get_last_error());
  284. }
  285. return handle, ERROR_NONE;
  286. }
  287. close :: proc(fd: Handle) -> Errno {
  288. result := _unix_close(fd);
  289. if result == -1 {
  290. return Errno(get_last_error());
  291. }
  292. return ERROR_NONE;
  293. }
  294. read :: proc(fd: Handle, data: []byte) -> (int, Errno) {
  295. bytes_read := _unix_read(fd, &data[0], c.size_t(len(data)));
  296. if bytes_read == -1 {
  297. return -1, Errno(get_last_error());
  298. }
  299. return int(bytes_read), ERROR_NONE;
  300. }
  301. write :: proc(fd: Handle, data: []byte) -> (int, Errno) {
  302. if len(data) == 0 {
  303. return 0, ERROR_NONE;
  304. }
  305. bytes_written := _unix_write(fd, &data[0], c.size_t(len(data)));
  306. if bytes_written == -1 {
  307. return -1, Errno(get_last_error());
  308. }
  309. return int(bytes_written), ERROR_NONE;
  310. }
  311. seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Errno) {
  312. res := _unix_seek(fd, offset, c.int(whence));
  313. if res == -1 {
  314. return -1, Errno(get_last_error());
  315. }
  316. return res, ERROR_NONE;
  317. }
  318. file_size :: proc(fd: Handle) -> (i64, Errno) {
  319. s, err := _fstat(fd);
  320. if err != ERROR_NONE {
  321. return 0, err;
  322. }
  323. return max(s.size, 0), ERROR_NONE;
  324. }
  325. // NOTE(bill): Uses startup to initialize it
  326. stdin: Handle = 0;
  327. stdout: Handle = 1;
  328. stderr: Handle = 2;
  329. /* TODO(zangent): Implement these!
  330. last_write_time :: proc(fd: Handle) -> File_Time {}
  331. last_write_time_by_name :: proc(name: string) -> File_Time {}
  332. */
  333. last_write_time :: proc(fd: Handle) -> (File_Time, Errno) {
  334. s, err := _fstat(fd);
  335. if err != ERROR_NONE {
  336. return 0, err;
  337. }
  338. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds;
  339. return File_Time(modified), ERROR_NONE;
  340. }
  341. last_write_time_by_name :: proc(name: string) -> (File_Time, Errno) {
  342. s, err := _stat(name);
  343. if err != ERROR_NONE {
  344. return 0, err;
  345. }
  346. modified := s.modified.seconds * 1_000_000_000 + s.modified.nanoseconds;
  347. return File_Time(modified), ERROR_NONE;
  348. }
  349. @private
  350. _stat :: proc(path: string) -> (OS_Stat, Errno) {
  351. cstr := strings.clone_to_cstring(path);
  352. defer delete(cstr);
  353. s: OS_Stat;
  354. result := _unix_stat(cstr, &s);
  355. if result == -1 {
  356. return s, Errno(get_last_error());
  357. }
  358. return s, ERROR_NONE;
  359. }
  360. @private
  361. _lstat :: proc(path: string) -> (OS_Stat, Errno) {
  362. cstr := strings.clone_to_cstring(path);
  363. defer delete(cstr);
  364. s: OS_Stat;
  365. result := _unix_lstat(cstr, &s);
  366. if result == -1 {
  367. return s, Errno(get_last_error());
  368. }
  369. return s, ERROR_NONE;
  370. }
  371. @private
  372. _fstat :: proc(fd: Handle) -> (OS_Stat, Errno) {
  373. s: OS_Stat;
  374. result := _unix_fstat(fd, &s);
  375. if result == -1 {
  376. return s, Errno(get_last_error());
  377. }
  378. return s, ERROR_NONE;
  379. }
  380. @private
  381. _fdopendir :: proc(fd: Handle) -> (Dir, Errno) {
  382. dirp := _unix_fdopendir(fd);
  383. if dirp == cast(Dir)nil {
  384. return nil, Errno(get_last_error());
  385. }
  386. return dirp, ERROR_NONE;
  387. }
  388. @private
  389. _closedir :: proc(dirp: Dir) -> Errno {
  390. rc := _unix_closedir(dirp);
  391. if rc != 0 {
  392. return Errno(get_last_error());
  393. }
  394. return ERROR_NONE;
  395. }
  396. @private
  397. _rewinddir :: proc(dirp: Dir) {
  398. _unix_rewinddir(dirp);
  399. }
  400. @private
  401. _readdir :: proc(dirp: Dir) -> (entry: Dirent, err: Errno, end_of_stream: bool) {
  402. result: ^Dirent;
  403. rc := _unix_readdir_r(dirp, &entry, &result);
  404. if rc != 0 {
  405. err = Errno(get_last_error());
  406. return;
  407. }
  408. err = ERROR_NONE;
  409. if result == nil {
  410. end_of_stream = true;
  411. return;
  412. }
  413. end_of_stream = false;
  414. return;
  415. }
  416. @private
  417. _readlink :: proc(path: string) -> (string, Errno) {
  418. path_cstr := strings.clone_to_cstring(path);
  419. defer delete(path_cstr);
  420. bufsz : uint = 256;
  421. buf := make([]byte, bufsz);
  422. for {
  423. rc := _unix_readlink(path_cstr, &(buf[0]), bufsz);
  424. if rc == -1 {
  425. delete(buf);
  426. return "", Errno(get_last_error());
  427. } else if rc == int(bufsz) {
  428. // NOTE(laleksic, 2021-01-21): Any cleaner way to resize the slice?
  429. bufsz *= 2;
  430. delete(buf);
  431. buf = make([]byte, bufsz);
  432. } else {
  433. return strings.string_from_ptr(&buf[0], rc), ERROR_NONE;
  434. }
  435. }
  436. }
  437. absolute_path_from_handle :: proc(fd: Handle) -> (string, Errno) {
  438. buf : [256]byte;
  439. fd_str := strconv.itoa( buf[:], cast(int)fd );
  440. procfs_path := strings.concatenate( []string{ "/proc/self/fd/", fd_str } );
  441. defer delete(procfs_path);
  442. return _readlink(procfs_path);
  443. }
  444. absolute_path_from_relative :: proc(rel: string) -> (path: string, err: Errno) {
  445. rel := rel;
  446. if rel == "" {
  447. rel = ".";
  448. }
  449. rel_cstr := strings.clone_to_cstring(rel);
  450. defer delete(rel_cstr);
  451. path_ptr := _unix_realpath(rel_cstr, nil);
  452. if path_ptr == nil {
  453. return "", Errno(get_last_error());
  454. }
  455. defer _unix_free(path_ptr);
  456. path_cstr := transmute(cstring)path_ptr;
  457. path = strings.clone( string(path_cstr) );
  458. return path, ERROR_NONE;
  459. }
  460. access :: proc(path: string, mask: int) -> (bool, Errno) {
  461. cstr := strings.clone_to_cstring(path);
  462. defer delete(cstr);
  463. result := _unix_access(cstr, c.int(mask));
  464. if result == -1 {
  465. return false, Errno(get_last_error());
  466. }
  467. return true, ERROR_NONE;
  468. }
  469. heap_alloc :: proc(size: int) -> rawptr {
  470. assert(size >= 0);
  471. return _unix_calloc(1, c.size_t(size));
  472. }
  473. heap_resize :: proc(ptr: rawptr, new_size: int) -> rawptr {
  474. return _unix_realloc(ptr, c.size_t(new_size));
  475. }
  476. heap_free :: proc(ptr: rawptr) {
  477. _unix_free(ptr);
  478. }
  479. getenv :: proc(name: string) -> (string, bool) {
  480. path_str := strings.clone_to_cstring(name);
  481. defer delete(path_str);
  482. cstr := _unix_getenv(path_str);
  483. if cstr == nil {
  484. return "", false;
  485. }
  486. return string(cstr), true;
  487. }
  488. get_current_directory :: proc() -> string {
  489. // NOTE(tetra): I would use PATH_MAX here, but I was not able to find
  490. // an authoritative value for it across all systems.
  491. // The largest value I could find was 4096, so might as well use the page size.
  492. page_size := get_page_size();
  493. buf := make([dynamic]u8, page_size);
  494. for {
  495. cwd := _unix_getcwd(cstring(#no_bounds_check &buf[0]), c.size_t(len(buf)));
  496. if cwd != nil {
  497. return string(cwd);
  498. }
  499. if Errno(get_last_error()) != ERANGE {
  500. return "";
  501. }
  502. resize(&buf, len(buf)+page_size);
  503. }
  504. unreachable();
  505. }
  506. set_current_directory :: proc(path: string) -> (err: Errno) {
  507. cstr := strings.clone_to_cstring(path, context.temp_allocator);
  508. res := _unix_chdir(cstr);
  509. if res == -1 {
  510. return Errno(get_last_error());
  511. }
  512. return ERROR_NONE;
  513. }
  514. exit :: proc "contextless" (code: int) -> ! {
  515. _unix_exit(c.int(code));
  516. }
  517. current_thread_id :: proc "contextless" () -> int {
  518. return cast(int)syscall(SYS_GETTID);
  519. }
  520. dlopen :: proc(filename: string, flags: int) -> rawptr {
  521. cstr := strings.clone_to_cstring(filename);
  522. defer delete(cstr);
  523. handle := _unix_dlopen(cstr, c.int(flags));
  524. return handle;
  525. }
  526. dlsym :: proc(handle: rawptr, symbol: string) -> rawptr {
  527. assert(handle != nil);
  528. cstr := strings.clone_to_cstring(symbol);
  529. defer delete(cstr);
  530. proc_handle := _unix_dlsym(handle, cstr);
  531. return proc_handle;
  532. }
  533. dlclose :: proc(handle: rawptr) -> bool {
  534. assert(handle != nil);
  535. return _unix_dlclose(handle) == 0;
  536. }
  537. dlerror :: proc() -> string {
  538. return string(_unix_dlerror());
  539. }
  540. get_page_size :: proc() -> int {
  541. // NOTE(tetra): The page size never changes, so why do anything complicated
  542. // if we don't have to.
  543. @static page_size := -1;
  544. if page_size != -1 {
  545. return page_size;
  546. }
  547. page_size = int(_unix_getpagesize());
  548. return page_size;
  549. }
  550. _alloc_command_line_arguments :: proc() -> []string {
  551. res := make([]string, len(runtime.args__));
  552. for arg, i in runtime.args__ {
  553. res[i] = string(arg);
  554. }
  555. return res;
  556. }