os_linux.odin 16 KB

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