os_linux.odin 17 KB

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