summaryrefslogtreecommitdiff
path: root/lib/std/execvp.myr
blob: 8c1bffe58bd68a308e3cd55d62e0e8c0b5673e56 (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
use "alloc"
use "env"
use "errno"
use "option"
use "strfind"
use "syswrap"
use "slcp"

pkg std = 
	const execvp	: (cmd : byte[:], args : byte[:][:] -> errno)
	const execvpe	: (cmd : byte[:], args : byte[:][:], env : byte[:][:] -> errno)
;;

const execvp = {cmd, args
	var i, j, paths, binpath
	var buf : byte[512]

	match strfind(cmd, "/")
	| `Some _:
		-> execv(cmd, args)
	| `None:
		i = 0
		j = 0
		paths = std.getenvv("PATH", "/usr/local/bin:/bin:/usr/bin")
		while j < paths.len
			(i, j) = nextpath(paths, j)
			binpath = mkpath(buf[:], paths[i:j], cmd)
			execv(binpath, args)
		;;
	;;
	-> -1
}

const execvpe = {cmd, args, env
	var i, j, paths, binpath
	var buf : byte[512]

	match strfind(cmd, "/")
	| `Some _:
		-> execve(cmd, args, env)
	| `None:
		i = 0
		j = 0
		paths = std.getenvv("PATH", "/usr/local/bin:/bin:/usr/bin")
		while j < paths.len
			(i, j) = nextpath(paths, j)
			binpath = mkpath(buf[:], paths[i:j], cmd)
			execve(binpath, args, env)
		;;
	;;
	-> -1
}

const nextpath = {p, start
	var i, j

	i = start
	while i < p.len && p[i] == (':' : byte)
		i++
	;;
	j = i
	while j < p.len && p[j] != (':' : byte)
		j++
	;;
	-> (i, j)
}

const mkpath = {buf, path, bin
	var p, b

	p = path.len
	b = bin.len
	if buf.len < p + b + 1
		-> ""
	;;
	std.slcp(buf[:p], path)
	std.slcp(buf[p:p + 1], "/")
	std.slcp(buf[p + 1:p + b + 1], bin)
	-> buf[:p + b + 1]
}