process.odin 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. package os2
  2. import "base:runtime"
  3. import "core:strings"
  4. import "core:time"
  5. /*
  6. In procedures that explicitly state this as one of the allowed values,
  7. specifies an infinite timeout.
  8. */
  9. TIMEOUT_INFINITE :: time.MIN_DURATION // Note(flysand): Any negative duration will be treated as infinity
  10. /*
  11. Arguments to the current process.
  12. */
  13. args := get_args()
  14. @(private="file")
  15. get_args :: proc() -> []string {
  16. result := make([]string, len(runtime.args__), heap_allocator())
  17. for rt_arg, i in runtime.args__ {
  18. result[i] = string(rt_arg)
  19. }
  20. return result
  21. }
  22. /*
  23. Exit the current process.
  24. */
  25. exit :: proc "contextless" (code: int) -> ! {
  26. _exit(code)
  27. }
  28. /*
  29. Obtain the UID of the current process.
  30. **Note(windows)**: Windows doesn't follow the posix permissions model, so
  31. the function simply returns -1.
  32. */
  33. @(require_results)
  34. get_uid :: proc() -> int {
  35. return _get_uid()
  36. }
  37. /*
  38. Obtain the effective UID of the current process.
  39. The effective UID is typically the same as the UID of the process. In case
  40. the process was run by a user with elevated permissions, the process may
  41. lower the privilege to perform some tasks without privilege. In these cases
  42. the real UID of the process and the effective UID are different.
  43. **Note(windows)**: Windows doesn't follow the posix permissions model, so
  44. the function simply returns -1.
  45. */
  46. @(require_results)
  47. get_euid :: proc() -> int {
  48. return _get_euid()
  49. }
  50. /*
  51. Obtain the GID of the current process.
  52. **Note(windows)**: Windows doesn't follow the posix permissions model, so
  53. the function simply returns -1.
  54. */
  55. @(require_results)
  56. get_gid :: proc() -> int {
  57. return _get_gid()
  58. }
  59. /*
  60. Obtain the effective GID of the current process.
  61. The effective GID is typically the same as the GID of the process. In case
  62. the process was run by a user with elevated permissions, the process may
  63. lower the privilege to perform some tasks without privilege. In these cases
  64. the real GID of the process and the effective GID are different.
  65. **Note(windows)**: Windows doesn't follow the posix permissions model, so
  66. the function simply returns -1.
  67. */
  68. @(require_results)
  69. get_egid :: proc() -> int {
  70. return _get_egid()
  71. }
  72. /*
  73. Obtain the ID of the current process.
  74. */
  75. @(require_results)
  76. get_pid :: proc() -> int {
  77. return _get_pid()
  78. }
  79. /*
  80. Obtain the ID of the parent process.
  81. **Note(windows)**: Windows does not mantain strong relationships between
  82. parent and child processes. This function returns the ID of the process
  83. that has created the current process. In case the parent has died, the ID
  84. returned by this function can identify a non-existent or a different
  85. process.
  86. */
  87. @(require_results)
  88. get_ppid :: proc() -> int {
  89. return _get_ppid()
  90. }
  91. /*
  92. Obtain ID's of all processes running in the system.
  93. */
  94. @(require_results)
  95. process_list :: proc(allocator: runtime.Allocator) -> ([]int, Error) {
  96. return _process_list(allocator)
  97. }
  98. /*
  99. Bit set specifying which fields of the `Process_Info` struct need to be
  100. obtained by the `process_info()` procedure. Each bit corresponds to a
  101. field in the `Process_Info` struct.
  102. */
  103. Process_Info_Fields :: bit_set[Process_Info_Field]
  104. Process_Info_Field :: enum {
  105. Executable_Path,
  106. PPid,
  107. Priority,
  108. Command_Line,
  109. Command_Args,
  110. Environment,
  111. Username,
  112. Working_Dir,
  113. }
  114. ALL_INFO :: Process_Info_Fields{.Executable_Path, .PPid, .Priority, .Command_Line, .Command_Args, .Environment, .Username, .Working_Dir}
  115. /*
  116. Contains information about the process as obtained by the `process_info()`
  117. procedure.
  118. */
  119. Process_Info :: struct {
  120. // The information about a process the struct contains. `pid` is always
  121. // stored, no matter what.
  122. fields: Process_Info_Fields,
  123. // The ID of the process.
  124. pid: int,
  125. // The ID of the parent process.
  126. ppid: int,
  127. // The process priority.
  128. priority: int,
  129. // The path to the executable, which the process runs.
  130. executable_path: string,
  131. // The command line supplied to the process.
  132. command_line: string,
  133. // The arguments supplied to the process.
  134. command_args: []string,
  135. // The environment of the process.
  136. environment: []string,
  137. // The username of the user who started the process.
  138. username: string,
  139. // The current working directory of the process.
  140. working_dir: string,
  141. }
  142. /*
  143. Obtain information about a process.
  144. This procedure obtains an information, specified by `selection` parameter of
  145. a process given by `pid`.
  146. Use `free_process_info` to free the memory allocated by this procedure. The
  147. `free_process_info` procedure needs to be called, even if this procedure
  148. returned an error, as some of the fields may have been allocated.
  149. **Note**: The resulting information may or may contain the fields specified
  150. by the `selection` parameter. Always check whether the returned
  151. `Process_Info` struct has the required fields before checking the error code
  152. returned by this procedure.
  153. */
  154. @(require_results)
  155. process_info_by_pid :: proc(pid: int, selection: Process_Info_Fields, allocator: runtime.Allocator) -> (Process_Info, Error) {
  156. return _process_info_by_pid(pid, selection, allocator)
  157. }
  158. /*
  159. Obtain information about a process.
  160. This procedure obtains information, specified by `selection` parameter
  161. about a process that has been opened by the application, specified in
  162. the `process` parameter.
  163. Use `free_process_info` to free the memory allocated by this procedure. The
  164. `free_process_info` procedure needs to be called, even if this procedure
  165. returned an error, as some of the fields may have been allocated.
  166. **Note**: The resulting information may or may contain the fields specified
  167. by the `selection` parameter. Always check whether the returned
  168. `Process_Info` struct has the required fields before checking the error code
  169. returned by this procedure.
  170. */
  171. @(require_results)
  172. process_info_by_handle :: proc(process: Process, selection: Process_Info_Fields, allocator: runtime.Allocator) -> (Process_Info, Error) {
  173. return _process_info_by_handle(process, selection, allocator)
  174. }
  175. /*
  176. Obtain information about the current process.
  177. This procedure obtains the information, specified by `selection` parameter
  178. about the currently running process.
  179. Use `free_process_info` to free the memory allocated by this procedure. The
  180. `free_process_info` procedure needs to be called, even if this procedure
  181. returned an error, as some of the fields may have been allocated.
  182. **Note**: The resulting information may or may contain the fields specified
  183. by the `selection` parameter. Always check whether the returned
  184. `Process_Info` struct has the required fields before checking the error code
  185. returned by this procedure.
  186. */
  187. @(require_results)
  188. current_process_info :: proc(selection: Process_Info_Fields, allocator: runtime.Allocator) -> (Process_Info, Error) {
  189. return _current_process_info(selection, allocator)
  190. }
  191. /*
  192. Obtain information about the specified process.
  193. */
  194. process_info :: proc {
  195. process_info_by_pid,
  196. process_info_by_handle,
  197. current_process_info,
  198. }
  199. /*
  200. Free the information about the process.
  201. This procedure frees the memory occupied by process info using the provided
  202. allocator. The allocator needs to be the same allocator that was supplied
  203. to the `process_info` function.
  204. */
  205. free_process_info :: proc(pi: Process_Info, allocator: runtime.Allocator) {
  206. delete(pi.executable_path, allocator)
  207. delete(pi.command_line, allocator)
  208. for a in pi.command_args {
  209. delete(a, allocator)
  210. }
  211. delete(pi.command_args, allocator)
  212. for s in pi.environment {
  213. delete(s, allocator)
  214. }
  215. delete(pi.environment, allocator)
  216. delete(pi.working_dir, allocator)
  217. delete(pi.username, allocator)
  218. }
  219. /*
  220. Represents a process handle.
  221. When a process dies, the OS is free to re-use the pid of that process. The
  222. `Process` struct represents a handle to the process that will refer to a
  223. specific process, even after it has died.
  224. **Note(linux)**: The `handle` will be referring to pidfd.
  225. */
  226. Process :: struct {
  227. pid: int,
  228. handle: uintptr,
  229. }
  230. Process_Open_Flags :: bit_set[Process_Open_Flag]
  231. Process_Open_Flag :: enum {
  232. // Request for reading from the virtual memory of another process.
  233. Mem_Read,
  234. // Request for writing to the virtual memory of another process.
  235. Mem_Write,
  236. }
  237. /*
  238. Open a process handle using it's pid.
  239. This procedure obtains a process handle of a process specified by `pid`.
  240. This procedure can be subject to race conditions. See the description of
  241. `Process`.
  242. Use `process_close()` function to close the process handle.
  243. */
  244. @(require_results)
  245. process_open :: proc(pid: int, flags := Process_Open_Flags {}) -> (Process, Error) {
  246. return _process_open(pid, flags)
  247. }
  248. /*
  249. The description of how a process should be created.
  250. */
  251. Process_Desc :: struct {
  252. // OS-specific attributes.
  253. sys_attr: _Sys_Process_Attributes,
  254. // The working directory of the process. If the string has length 0, the
  255. // working directory is assumed to be the current working directory of the
  256. // current process.
  257. working_dir: string,
  258. // The command to run. Each element of the slice is a separate argument to
  259. // the process. The first element of the slice would be the executable.
  260. command: []string,
  261. // A slice of strings, each having the format `KEY=VALUE` representing the
  262. // full environment that the child process will receive.
  263. // In case this slice is `nil`, the current process' environment is used.
  264. // NOTE(laytan): maybe should be `Maybe([]string)` so you can do `nil` == current env, empty == empty/no env.
  265. env: []string,
  266. // The `stderr` handle to give to the child process. It can be either a file
  267. // or a writeable end of a pipe. Passing `nil` will shut down the process'
  268. // stderr output.
  269. stderr: ^File,
  270. // The `stdout` handle to give to the child process. It can be either a file
  271. // or a writeabe end of a pipe. Passing a `nil` will shut down the process'
  272. // stdout output.
  273. stdout: ^File,
  274. // The `stdin` handle to give to the child process. It can either be a file
  275. // or a readable end of a pipe. Passing a `nil` will shut down the process'
  276. // input.
  277. stdin: ^File,
  278. }
  279. /*
  280. Create a new process and obtain its handle.
  281. This procedure creates a new process, with a given command and environment
  282. strings as parameters. Use `environ()` to inherit the environment of the
  283. current process.
  284. The `desc` parameter specifies the description of how the process should
  285. be created. It contains information such as the command line, the
  286. environment of the process, the starting directory and many other options.
  287. Most of the fields in the struct can be set to `nil` or an empty value.
  288. Use `process_close` to close the handle to the process. Note, that this
  289. is not the same as terminating the process. One can terminate the process
  290. and not close the handle, in which case the handle would be leaked. In case
  291. the function returns an error, an invalid handle is returned.
  292. This procedure is not thread-safe. It may alter the inheritance properties
  293. of file handles in an unpredictable manner. In case multiple threads change
  294. handle inheritance properties, make sure to serialize all those calls.
  295. */
  296. @(require_results)
  297. process_start :: proc(desc: Process_Desc) -> (Process, Error) {
  298. return _process_start(desc)
  299. }
  300. /*
  301. Execute the process and capture stdout and stderr streams.
  302. This procedure creates a new process, with a given command and environment
  303. strings as parameters, and waits until the process finishes execution. While
  304. the process is running, this procedure accumulates the output of its stdout
  305. and stderr streams and returns byte slices containing the captured data from
  306. the streams.
  307. This procedure expects that `stdout` and `stderr` fields of the `desc` parameter
  308. are left at default, i.e. a `nil` value. You can not capture stdout/stderr and
  309. redirect it to a file at the same time.
  310. This procedure does not free `stdout` and `stderr` slices before an error is
  311. returned. Make sure to call `delete` on these slices.
  312. */
  313. @(require_results)
  314. process_exec :: proc(
  315. desc: Process_Desc,
  316. allocator: runtime.Allocator,
  317. loc := #caller_location,
  318. ) -> (
  319. state: Process_State,
  320. stdout: []u8,
  321. stderr: []u8,
  322. err: Error,
  323. ) {
  324. assert(desc.stdout == nil, "Cannot redirect stdout when it's being captured", loc)
  325. assert(desc.stderr == nil, "Cannot redirect stderr when it's being captured", loc)
  326. stdout_r, stdout_w := pipe() or_return
  327. defer close(stdout_r)
  328. stderr_r, stderr_w := pipe() or_return
  329. defer close(stdout_w)
  330. process: Process
  331. {
  332. // NOTE(flysand): Make sure the write-ends are closed, regardless
  333. // of the outcome. This makes read-ends readable on our side.
  334. defer close(stdout_w)
  335. defer close(stderr_w)
  336. desc := desc
  337. desc.stdout = stdout_w
  338. desc.stderr = stderr_w
  339. process = process_start(desc) or_return
  340. }
  341. stdout_builder := strings.builder_make(allocator) or_return
  342. stderr_builder := strings.builder_make(allocator) or_return
  343. read_data: for {
  344. buf: [1024]u8
  345. n: int
  346. has_data: bool
  347. hangup := false
  348. has_data, err = pipe_has_data(stdout_r)
  349. if has_data {
  350. n, err = read(stdout_r, buf[:])
  351. strings.write_bytes(&stdout_builder, buf[:n])
  352. }
  353. switch err {
  354. case nil: // nothing
  355. case .Broken_Pipe:
  356. hangup = true
  357. case:
  358. return
  359. }
  360. has_data, err = pipe_has_data(stderr_r)
  361. if has_data {
  362. n, err = read(stderr_r, buf[:])
  363. strings.write_bytes(&stderr_builder, buf[:n])
  364. }
  365. switch err {
  366. case nil: // nothing
  367. case .Broken_Pipe:
  368. hangup = true
  369. case:
  370. return
  371. }
  372. if hangup {
  373. break read_data
  374. }
  375. }
  376. err = nil
  377. stdout = transmute([]u8) strings.to_string(stdout_builder)
  378. stderr = transmute([]u8) strings.to_string(stderr_builder)
  379. state = process_wait(process) or_return
  380. return
  381. }
  382. /*
  383. The state of the process after it has finished execution.
  384. */
  385. Process_State :: struct {
  386. // The ID of the process.
  387. pid: int,
  388. // Specifies whether the process has terminated or is still running.
  389. exited: bool,
  390. // The exit code of the process, if it has exited.
  391. // Will also store the number of the exception or signal that has crashed the
  392. // process.
  393. exit_code: int,
  394. // Specifies whether the termination of the process was successfull or not,
  395. // i.e. whether it has crashed or not.
  396. // **Note(windows)**: On windows `true` is always returned, as there is no
  397. // reliable way to obtain information about whether the process has crashed.
  398. success: bool,
  399. // The time the process has spend executing in kernel time.
  400. system_time: time.Duration,
  401. // The time the process has spend executing in userspace.
  402. user_time: time.Duration,
  403. }
  404. /*
  405. Wait for a process event.
  406. This procedure blocks the execution until the process has exited or the
  407. timeout (if specified) has reached zero. If the timeout is `TIMEOUT_INFINITE`,
  408. no timeout restriction is imposed and the procedure can block indefinately.
  409. If the timeout has expired, the `General_Error.Timeout` is returned as
  410. the error.
  411. If an error is returned for any other reason, other than timeout, the
  412. process state is considered undetermined.
  413. */
  414. @(require_results)
  415. process_wait :: proc(process: Process, timeout := TIMEOUT_INFINITE) -> (Process_State, Error) {
  416. return _process_wait(process, timeout)
  417. }
  418. /*
  419. Close the handle to a process.
  420. This procedure closes the handle associated with a process. It **does not**
  421. terminate a process, in case it was running. In case a termination is
  422. desired, kill the process first, wait for the process to finish,
  423. then close the handle.
  424. */
  425. @(require_results)
  426. process_close :: proc(process: Process) -> (Error) {
  427. return _process_close(process)
  428. }
  429. /*
  430. Terminate a process.
  431. This procedure terminates a process, specified by it's handle, `process`.
  432. */
  433. @(require_results)
  434. process_kill :: proc(process: Process) -> (Error) {
  435. return _process_kill(process)
  436. }