aboutsummaryrefslogtreecommitdiff
path: root/core/os/process_linux.odin
blob: 7041e16b7cc48d810d33f9af7810765d47deb65e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
#+build linux
#+private file
package os

import "base:runtime"
import "base:intrinsics"

import "core:c"
import "core:time"
import "core:slice"
import "core:strings"
import "core:strconv"
import "core:sys/unix"
import "core:sys/linux"

foreign import libc "system:c"

foreign libc {
	@(link_name="get_nprocs")       _unix_get_nprocs    :: proc() -> c.int ---
}

PIDFD_UNASSIGNED  :: ~uintptr(0)

@(private="package")
_get_uid :: proc() -> int {
	return int(linux.getuid())
}

@(private="package")
_get_euid :: proc() -> int {
	return int(linux.geteuid())
}

@(private="package")
_get_gid :: proc() -> int {
	return int(linux.getgid())
}

@(private="package")
_get_egid :: proc() -> int {
	return int(linux.getegid())
}

@(private="package")
_get_pid :: proc() -> int {
	return int(linux.getpid())
}

@(private="package")
_get_ppid :: proc() -> int {
	return int(linux.getppid())
}

@(private="package")
_get_current_thread_id :: proc "contextless" () -> int {
	return unix.sys_gettid()
}

@(private="package")
_get_processor_core_count :: proc() -> (core_count: int) {
	cpu_set: [128]u64
	if n, err := linux.sched_getaffinity(0, size_of(cpu_set), &cpu_set); err == nil {
		for set in cpu_set[:n / 8] {
			core_count += int(intrinsics.count_ones(set))
		}
	}
	return
}

@(private="package")
_process_list :: proc(allocator: runtime.Allocator) -> (list: []int, err: Error) {
	temp_allocator := TEMP_ALLOCATOR_GUARD({ allocator })

	dir_fd, errno := linux.open("/proc/", _OPENDIR_FLAGS)
	#partial switch errno {
	case .NONE:
		// okay
	case .ENOTDIR:
		err = .Invalid_Dir
		return
	case .ENOENT:
		err = .Not_Exist
		return
	case:
		err = _get_platform_error(errno)
		return
	}
	defer linux.close(dir_fd)

	dynamic_list := make([dynamic]int, temp_allocator) or_return

	buf := make([dynamic]u8, 128, 128, temp_allocator) or_return
	loop: for {
		buflen: int
		buflen, errno = linux.getdents(dir_fd, buf[:])
		#partial switch errno {
		case .EINVAL:
			resize(&buf, len(buf) * 2)
			continue loop
		case .NONE:
			if buflen == 0 { break loop }
		case:
			return {}, _get_platform_error(errno)
		}

		offset: int
		for d in linux.dirent_iterate_buf(buf[:buflen], &offset) {
			d_name_str := linux.dirent_name(d)

			if pid, ok := strconv.parse_int(d_name_str); ok {
				append(&dynamic_list, pid)
			}
		}
	}

	list, err = slice.clone(dynamic_list[:], allocator)
	return
}

@(private="package")
_process_info_by_pid :: proc(pid: int, selection: Process_Info_Fields, allocator: runtime.Allocator) -> (info: Process_Info, err: Error) {
	temp_allocator := TEMP_ALLOCATOR_GUARD({ allocator })

	info.pid = pid

	// Use this to make cstrings without copying.
	path_backing: [48]u8
	path_builder := strings.builder_from_bytes(path_backing[:])

	strings.write_string(&path_builder, "/proc/")
	strings.write_int(&path_builder, pid)
	proc_fd, errno := linux.open(strings.to_cstring(&path_builder) or_return, _OPENDIR_FLAGS)
	if errno != .NONE {
		err = _get_platform_error(errno)
		return
	}
	defer linux.close(proc_fd)

	username_if: if .Username in selection {
		s: linux.Stat
		if errno = linux.fstat(proc_fd, &s); errno != .NONE {
			err = _get_platform_error(errno)
			break username_if
		}

		passwd_bytes: []u8
		passwd_err: Error
		passwd_bytes, passwd_err = _read_entire_pseudo_file_cstring("/etc/passwd", temp_allocator)
		if passwd_err != nil {
			err = passwd_err
			break username_if
		}

		passwd := string(passwd_bytes)
		for len(passwd) > 0 {
			n := strings.index_byte(passwd, ':')
			if n < 0 {
				break
			}
			username := passwd[:n]
			passwd = passwd[n+1:]

			// skip password field
			passwd = passwd[strings.index_byte(passwd, ':') + 1:]

			n = strings.index_byte(passwd, ':')
			if uid, ok := strconv.parse_int(passwd[:n]); ok && uid == int(s.uid) {
				info.username = strings.clone(username, allocator) or_return
				info.fields += {.Username}
				break
			} else if !ok {
				err = .Invalid_File
				break username_if
			}

			eol := strings.index_byte(passwd, '\n')
			if eol < 0 {
				break
			}
			passwd = passwd[eol + 1:]
		}
	}

	cmdline_if: if selection & {.Working_Dir, .Command_Line, .Command_Args} != {} {
		strings.builder_reset(&path_builder)
		strings.write_string(&path_builder, "/proc/")
		strings.write_int(&path_builder, pid)
		strings.write_string(&path_builder, "/cmdline")

		cmdline_bytes, cmdline_err := _read_entire_pseudo_file(strings.to_cstring(&path_builder) or_return, temp_allocator)
		if cmdline_err != nil || len(cmdline_bytes) == 0 {
			err = cmdline_err
			break cmdline_if
		}
		cmdline := string(cmdline_bytes)

		terminator := strings.index_byte(cmdline, 0)
		assert(terminator > 0)

		// command_line_exec := cmdline[:terminator]

		// Still need cwd if the execution on the command line is relative.
		cwd: string
		cwd_err: Error
		if .Working_Dir in selection {
			strings.builder_reset(&path_builder)
			strings.write_string(&path_builder, "/proc/")
			strings.write_int(&path_builder, pid)
			strings.write_string(&path_builder, "/cwd")

			cwd, cwd_err = _read_link_cstr(strings.to_cstring(&path_builder) or_return, temp_allocator) // allowed to fail
			if cwd_err == nil && .Working_Dir in selection {
				info.working_dir = strings.clone(cwd, allocator) or_return
				info.fields += {.Working_Dir}
			} else if cwd_err != nil {
				err = cwd_err
				break cmdline_if
			}
		}

		if selection & {.Command_Line, .Command_Args} != {} {
			// skip to first arg
			//cmdline = cmdline[terminator + 1:]
			command_line_builder: strings.Builder
			command_args_list: [dynamic]string

			if .Command_Line in selection {
				command_line_builder = strings.builder_make(allocator) or_return
				info.fields += {.Command_Line}
			}

			for i := 0; len(cmdline) > 0; i += 1 {
				if terminator = strings.index_byte(cmdline, 0); terminator < 0 {
					break
				}

				if .Command_Line in selection {
					if i > 0 {
						strings.write_byte(&command_line_builder, ' ')
					}
					strings.write_string(&command_line_builder, cmdline[:terminator])
				}
				if .Command_Args in selection {
					if i == 1 {
						command_args_list = make([dynamic]string, allocator) or_return
						info.fields += {.Command_Args}
					}
					if i > 0 {
						arg := strings.clone(cmdline[:terminator], allocator) or_return
						append(&command_args_list, arg) or_return
					}
				}

				cmdline = cmdline[terminator + 1:]
			}
			info.command_line = strings.to_string(command_line_builder)
			info.command_args = command_args_list[:]
		}
	}

	stat_if: if selection & {.PPid, .Priority} != {} {
		strings.builder_reset(&path_builder)
		strings.write_string(&path_builder, "/proc/")
		strings.write_int(&path_builder, pid)
		strings.write_string(&path_builder, "/stat")

		proc_stat_bytes, stat_err := _read_entire_pseudo_file(strings.to_cstring(&path_builder) or_return, temp_allocator)
		if stat_err != nil {
			err = stat_err
			break stat_if
		}
		if len(proc_stat_bytes) <= 0 {
			break stat_if
		}

		// Skip to the first field after the executable name
		stats: string
		if start := strings.last_index_byte(string(proc_stat_bytes), ')'); start != -1 {
			stats = string(proc_stat_bytes[start + 2:])
		} else {
			break stat_if
		}

		// NOTE: index 0 corresponds to field 3 (state) from `man 5 proc_pid_stat`
		//       because we skipped passed the executable name above.
		Fields :: enum {
			State,
			PPid,
			PGrp,
			Session,
			Tty_Nr,
			TpGid,
			Flags,
			MinFlt,
			CMinFlt,
			MajFlt,
			CMajFlt,
			UTime,
			STime,
			CUTime,
			CSTime,
			Priority,
			Nice,
			//... etc,
		}
		stat_fields := strings.split(stats, " ", temp_allocator) or_return

		if len(stat_fields) <= int(Fields.Nice) {
			break stat_if
		}

		if .PPid in selection {
			if ppid, ok := strconv.parse_int(stat_fields[Fields.PPid]); ok {
				info.ppid = ppid
				info.fields += {.PPid}
			} else {
				err = .Invalid_File
				break stat_if
			}
		}

		if .Priority in selection {
			if nice, ok := strconv.parse_int(stat_fields[Fields.Nice]); ok {
				info.priority = nice
				info.fields += {.Priority}
			} else {
				err = .Invalid_File
				break stat_if
			}
		}
	}

	if .Executable_Path in selection {
		/*
		NOTE(Jeroen):

		The old version returned the wrong executable path for things like `bash` or `sh`,
		for whom `/proc/<pid>/cmdline` will just report "bash" or "sh",
		resulting in misleading paths like `$PWD/sh`, even though that executable doesn't exist there.

		Thanks to Yawning for suggesting `/proc/self/exe`.
		*/

		strings.builder_reset(&path_builder)
		strings.write_string(&path_builder, "/proc/")
		strings.write_int(&path_builder, pid)
		strings.write_string(&path_builder, "/exe")

		if exe_bytes, exe_err := _read_link(strings.to_string(path_builder), temp_allocator); exe_err == nil {
			info.executable_path = strings.clone(string(exe_bytes), allocator) or_return
			info.fields += {.Executable_Path}
		} else {
			err = exe_err
		}
	}

	if .Environment in selection {
		strings.builder_reset(&path_builder)
		strings.write_string(&path_builder, "/proc/")
		strings.write_int(&path_builder, pid)
		strings.write_string(&path_builder, "/environ")

		if env_bytes, env_err := _read_entire_pseudo_file(strings.to_cstring(&path_builder) or_return, temp_allocator); env_err == nil {
			env := string(env_bytes)

			env_list := make([dynamic]string, allocator) or_return
			for len(env) > 0 {
				terminator := strings.index_byte(env, 0)
				if terminator <= 0 {
					break
				}
				e := strings.clone(env[:terminator], allocator) or_return
				append(&env_list, e) or_return
				env = env[terminator + 1:]
			}
			info.environment = env_list[:]
			info.fields += {.Environment}
		} else if err == nil {
			err = env_err
		}
	}

	return
}

@(private="package")
_process_info_by_handle :: proc(process: Process, selection: Process_Info_Fields, allocator: runtime.Allocator) -> (info: Process_Info, err: Error) {
	return _process_info_by_pid(process.pid, selection, allocator)
}

@(private="package")
_current_process_info :: proc(selection: Process_Info_Fields, allocator: runtime.Allocator) -> (info: Process_Info, err: Error) {
	return _process_info_by_pid(get_pid(), selection, allocator)
}

@(private="package")
_process_open :: proc(pid: int, _: Process_Open_Flags) -> (process: Process, err: Error) {
	process.pid = pid
	process.handle = PIDFD_UNASSIGNED

	pidfd, errno := linux.pidfd_open(linux.Pid(pid), {})
	if errno == .ENOSYS {
		return process, .Unsupported
	}
	if errno != .NONE {
		return process, _get_platform_error(errno)
	}
	process.handle = uintptr(pidfd)
	return
}

@(private="package")
_process_start :: proc(desc: Process_Desc) -> (process: Process, err: Error) {
	temp_allocator := TEMP_ALLOCATOR_GUARD({})

	if len(desc.command) == 0 {
		return process, .Invalid_Command
	}

	dir_fd := linux.AT_FDCWD
	errno: linux.Errno
	if desc.working_dir != "" {
		dir_cstr := clone_to_cstring(desc.working_dir, temp_allocator) or_return
		if dir_fd, errno = linux.open(dir_cstr, _OPENDIR_FLAGS); errno != .NONE {
			return process, _get_platform_error(errno)
		}
	}
	defer if desc.working_dir != "" {
		linux.close(dir_fd)
	}

	// search PATH if just a plain name is provided
	exe_path: cstring
	executable_name := desc.command[0]
	if strings.index_byte(executable_name, '/') < 0 {
		path_env := get_env("PATH", temp_allocator)
		path_dirs := split_path_list(path_env, temp_allocator) or_return

		exe_builder := strings.builder_make(temp_allocator) or_return

		found: bool
		for dir in path_dirs {
			strings.builder_reset(&exe_builder)
			strings.write_string(&exe_builder, dir)
			strings.write_byte(&exe_builder, '/')
			strings.write_string(&exe_builder, executable_name)

			exe_path = strings.to_cstring(&exe_builder) or_return
			stat := linux.Stat{}
			if linux.stat(exe_path, &stat) == .NONE && .IFREG in stat.mode && .IXUSR in stat.mode {
				found = true
				break
			}
		}
		if !found {
			// check in cwd to match windows behavior
			strings.builder_reset(&exe_builder)
			strings.write_string(&exe_builder, "./")
			strings.write_string(&exe_builder, executable_name)

			exe_path = strings.to_cstring(&exe_builder) or_return
			if linux.access(exe_path, linux.X_OK) != .NONE {
				return process, .Not_Exist
			}
		}
	} else {
		exe_path = clone_to_cstring(executable_name, temp_allocator) or_return
		if linux.access(exe_path, linux.X_OK) != .NONE {
			return process, .Not_Exist
		}
	}

	// args and environment need to be a list of cstrings
	// that are terminated by a nil pointer.
	cargs := make([]cstring, len(desc.command) + 1, temp_allocator) or_return
	for command, i in desc.command {
		cargs[i] = clone_to_cstring(command, temp_allocator) or_return
	}

	// Use current process' environment if description didn't provide it.
	env: [^]cstring
	if desc.env == nil {
		// take this process's current environment
		env = raw_data(export_cstring_environment(temp_allocator))
	} else {
		cenv := make([]cstring, len(desc.env) + 1, temp_allocator) or_return
		for env, i in desc.env {
			cenv[i] = clone_to_cstring(env, temp_allocator) or_return
		}
		env = &cenv[0]
	}

	child_pipe_fds: [2]linux.Fd
	if errno = linux.pipe2(&child_pipe_fds, {.CLOEXEC}); errno != .NONE {
		return process, _get_platform_error(errno)
	}
	defer linux.close(child_pipe_fds[READ])

	// TODO: This is the traditional textbook implementation with fork.
	//       A more efficient implementation with vfork:
	//
	//       1. retrieve signal handlers
	//       2. block all signals
	//       3. allocate some stack space
	//       4. vfork (waits for child exit or execve); In child:
	//           a. set child signal handlers
	//           b. set up any necessary pipes
	//           c. execve
	//       5. restore signal handlers
	//
	pid: linux.Pid
	if pid, errno = linux.fork(); errno != .NONE {
		linux.close(child_pipe_fds[WRITE])
		return process, _get_platform_error(errno)
	}

	STDIN  :: linux.Fd(0)
	STDOUT :: linux.Fd(1)
	STDERR :: linux.Fd(2)

	READ :: 0
	WRITE :: 1

	if pid == 0 {
		// in child process now
		write_errno_to_parent_and_abort :: proc(parent_fd: linux.Fd, errno: linux.Errno) -> ! {
			error_byte: [1]u8 = { u8(errno) }
			linux.write(parent_fd, error_byte[:])
			linux.exit(126)
		}

		stdin_fd: linux.Fd
		stdout_fd: linux.Fd
		stderr_fd: linux.Fd

		if desc.stdin != nil {
			stdin_fd = linux.Fd(fd(desc.stdin))
		} else {
			stdin_fd, errno = linux.open("/dev/null", {})
			if errno != .NONE {
				write_errno_to_parent_and_abort(child_pipe_fds[WRITE], errno)
			}
		}

		write_devnull: linux.Fd = -1

		if desc.stdout != nil {
			stdout_fd = linux.Fd(fd(desc.stdout))
		} else {
			write_devnull, errno = linux.open("/dev/null", {.WRONLY})
			if errno != .NONE {
				write_errno_to_parent_and_abort(child_pipe_fds[WRITE], errno)
			}
			stdout_fd = write_devnull
		}

		if desc.stderr != nil {
			stderr_fd = linux.Fd(fd(desc.stderr))
		} else {
			if write_devnull < 0 {
				write_devnull, errno = linux.open("/dev/null", {.WRONLY})
				if errno != .NONE {
					write_errno_to_parent_and_abort(child_pipe_fds[WRITE], errno)
				}
			}
			stderr_fd = write_devnull
		}

		if _, errno = linux.dup2(stdin_fd, STDIN); errno != .NONE {
			write_errno_to_parent_and_abort(child_pipe_fds[WRITE], errno)
		}
		if _, errno = linux.dup2(stdout_fd, STDOUT); errno != .NONE {
			write_errno_to_parent_and_abort(child_pipe_fds[WRITE], errno)
		}
		if _, errno = linux.dup2(stderr_fd, STDERR); errno != .NONE {
			write_errno_to_parent_and_abort(child_pipe_fds[WRITE], errno)
		}
		if dir_fd != linux.AT_FDCWD {
			if errno = linux.fchdir(dir_fd); errno != .NONE {
				write_errno_to_parent_and_abort(child_pipe_fds[WRITE], errno)
			}
		}

		errno = linux.execveat(dir_fd, exe_path, &cargs[0], env)
		assert(errno != nil)
		write_errno_to_parent_and_abort(child_pipe_fds[WRITE], errno)
	}

	linux.close(child_pipe_fds[WRITE])

	process.pid = int(pid)

	child_byte: [1]u8
	errno = .EINTR
	for errno == .EINTR {
		_, errno = linux.read(child_pipe_fds[READ], child_byte[:])
	}

	// If the read failed, something weird happened. Do not return the read
	// error so the user knows to wait on it.
	if errno == .NONE {
		child_errno := linux.Errno(child_byte[0])
		if child_errno != .NONE {
			// We can assume it trapped here.
			_reap_terminated(process)
			process.pid = 0
			return process, _get_platform_error(child_errno)
		}
	}

	process, _ = process_open(int(pid))
	return
}

_process_state_update_times :: proc(state: ^Process_State) -> (err: Error) {
	temp_allocator := TEMP_ALLOCATOR_GUARD({})

	stat_path_buf: [48]u8
	path_builder := strings.builder_from_bytes(stat_path_buf[:])
	strings.write_string(&path_builder, "/proc/")
	strings.write_int(&path_builder, int(state.pid))
	strings.write_string(&path_builder, "/stat")

	stat_buf: []u8
	stat_buf, err = _read_entire_pseudo_file(strings.to_cstring(&path_builder) or_return, temp_allocator)
	if err != nil {
		return
	}

	// ')' will be the end of the executable name (item 2)
	idx := strings.last_index_byte(string(stat_buf), ')')
	stats := string(stat_buf[idx + 2:])

	// utime and stime are the 14 and 15th items, respectively, and we are
	// currently on item 3. Skip 11 items here.
	for _ in 0..<11 {
		stats = stats[strings.index_byte(stats, ' ') + 1:]
	}

	idx = strings.index_byte(stats, ' ')
	utime_str := stats[:idx]

	stats = stats[idx + 1:]
	stime_str := stats[:strings.index_byte(stats, ' ')]

	utime, stime: int
	ok: bool
	if utime, ok = strconv.parse_int(utime_str, 10); !ok {
		return .Invalid_File
	}
	if stime, ok = strconv.parse_int(stime_str, 10); !ok {
		return .Invalid_File
	}

	// NOTE: Assuming HZ of 100, 1 jiffy == 10 ms
	state.user_time = time.Duration(utime) * 10 * time.Millisecond
	state.system_time = time.Duration(stime) * 10 * time.Millisecond

	return
}

_reap_terminated :: proc(process: Process) -> (state: Process_State, err: Error) {
	state.pid = process.pid
	_process_state_update_times(&state)

	info: linux.Sig_Info
	errno := linux.Errno.EINTR
	for errno == .EINTR {
		errno = linux.waitid(.PID, linux.Id(process.pid), &info, {.WEXITED}, nil)
	}
	err = _get_platform_error(errno)

	switch linux.Sig_Child_Code(info.code) {
	case .NONE, .CONTINUED, .STOPPED:
		unreachable()
	case .EXITED:
		state.exited = true
		state.exit_code = int(info.status)
		state.success = state.exit_code == 0
	case .KILLED, .DUMPED, .TRAPPED:
		state.exited = true
		state.exit_code = int(info.status)
		state.success = false
	}
	return
}

_timed_wait_on_handle :: proc(process: Process, timeout: time.Duration) -> (process_state: Process_State, err: Error) {
	timeout := timeout

	process_state.pid = process.pid
	pidfd := linux.Fd(process.handle)
	pollfd: [1]linux.Poll_Fd = {
		{
			fd = pidfd,
			events = {.IN},
		},
	}

	start_tick := time.tick_now()

	mask: bit_set[0..<64; u64]
	mask += { int(linux.Signal.SIGCHLD) - 1 }
	sigchld_set := transmute(linux.Sig_Set)(mask)

	info: linux.Sig_Info
	for {
		if timeout <= 0 {
			_process_state_update_times(&process_state)
			err = .Timeout
			return
		}

		ts: linux.Time_Spec = {
			time_sec  = uint(timeout / time.Second),
			time_nsec = uint(timeout % time.Second),
		}

		n, errno := linux.ppoll(pollfd[:], &ts, &sigchld_set)
		if errno != .NONE {
			if errno == .EINTR {
				timeout -= time.tick_since(start_tick)
				start_tick = time.tick_now()
				continue
			}
			return process_state, _get_platform_error(errno)
		}

		if n == 0 {  // timeout with no events
			_process_state_update_times(&process_state)
			err = .Timeout
			return
		}

		if errno = linux.waitid(.PIDFD, linux.Id(process.handle), &info, {.WEXITED, .WNOHANG, .WNOWAIT}, nil); errno != .NONE {
			return process_state, _get_platform_error(errno)
		}

		if info.signo == .SIGCHLD {
			break
		}

		timeout -= time.tick_since(start_tick)
		start_tick = time.tick_now()
	}

	// _reap_terminated for pidfd
	{
		_process_state_update_times(&process_state)

		errno := linux.Errno.EINTR
		for errno == .EINTR {
			errno = linux.waitid(.PIDFD, linux.Id(process.handle), &info, {.WEXITED}, nil)
		}
		err = _get_platform_error(errno)

		switch linux.Sig_Child_Code(info.code) {
		case .NONE, .CONTINUED, .STOPPED:
			unreachable()
		case .EXITED:
			process_state.exited = true
			process_state.exit_code = int(info.status)
			process_state.success = process_state.exit_code == 0
		case .KILLED, .DUMPED, .TRAPPED:
			process_state.exited = true
			process_state.exit_code = int(info.status)
			process_state.success = false
		}
	}
	return
}

_timed_wait_on_pid :: proc(process: Process, timeout: time.Duration) -> (process_state: Process_State, err: Error) {
	timeout := timeout
	process_state.pid = process.pid

	mask: bit_set[0..<64; u64]
	mask += { int(linux.Signal.SIGCHLD) - 1 }
	sigchld_set := transmute(linux.Sig_Set)(mask)

	start_tick := time.tick_now()

	org_sigset: linux.Sig_Set
	errno := linux.rt_sigprocmask(.SIG_BLOCK, &sigchld_set, &org_sigset)
	if errno != .NONE {
		return process_state, _get_platform_error(errno)
	}
	defer linux.rt_sigprocmask(.SIG_SETMASK, &org_sigset, nil)

	// In case there was a signal handler on SIGCHLD, avoid race
	// condition by checking wait first.
	info: linux.Sig_Info
	errno = linux.waitid(.PID, linux.Id(process.pid), &info, {.WNOWAIT, .WEXITED, .WNOHANG}, nil)

	for errno != .NONE || info.code == 0 || info.pid != linux.Pid(process.pid) {
		if timeout <= 0 {
			_process_state_update_times(&process_state)
			err = .Timeout
			return
		}

		ts: linux.Time_Spec = {
			time_sec  = uint(timeout / time.Second),
			time_nsec = uint(timeout % time.Second),
		}

		_, errno = linux.rt_sigtimedwait(&sigchld_set, &info, &ts)
		#partial switch errno {
		case .EAGAIN:   // timeout
			_process_state_update_times(&process_state)
			err = .Timeout
			return
		case .EINTR:
			timeout -= time.tick_since(start_tick)
			start_tick = time.tick_now()
		case .EINVAL:
			return process_state, _get_platform_error(errno)
		}
	}

	return _reap_terminated(process)
}

@(private="package")
_process_wait :: proc(process: Process, timeout: time.Duration) -> (Process_State, Error) {
	if timeout > 0 {
		if process.handle == PIDFD_UNASSIGNED {
			return _timed_wait_on_pid(process, timeout)
		} else {
			return _timed_wait_on_handle(process, timeout)
		}
	}

	process_state: Process_State = {
		pid = process.pid,
	}

	errno: linux.Errno
	options: linux.Wait_Options = {.WEXITED}
	if timeout == 0 {
		options += {.WNOHANG}
	}

	info: linux.Sig_Info

	errno = .EINTR
	for errno == .EINTR {
		errno = linux.waitid(.PID, linux.Id(process.pid), &info, options + {.WNOWAIT}, nil)
	}
	if errno == .EAGAIN || (errno == .NONE && info.signo != .SIGCHLD) {
		_process_state_update_times(&process_state)
		return process_state, .Timeout
	}
	if errno != .NONE {
		return process_state, _get_platform_error(errno)
	}

	return _reap_terminated(process)
}

@(private="package")
_process_close :: proc(process: Process) -> Error {
	if process.handle == 0 || process.handle == PIDFD_UNASSIGNED {
		return nil
	}
	pidfd := linux.Fd(process.handle)
	return _get_platform_error(linux.close(pidfd))
}

@(private="package")
_process_kill :: proc(process: Process) -> Error {
	return _get_platform_error(linux.kill(linux.Pid(process.pid), .SIGKILL))
}