Debian Codegraph @

os/exec/cmd.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 use errors;
5 use fs;
6 use io;
7 use os;
8 use path;
9 use strings;
10
11 // Prepares a [[command]] based on its name and a list of arguments. The
12 // argument list should not start with the command name; it will be added for
13 // you. The argument list is borrowed from the strings you pass into this
14 // command.
15 //
16 // If 'name' does not contain a '/', the $PATH will be consulted to find the
17 // correct executable. If path resolution fails, [[nocmd]] is returned.
18 //
19 // let cmd = exec::cmd("echo", "hello world")!;
20 // let proc = exec::start(&cmd)!;
21 // let status = exec::wait(&proc)!;
22 // assert(exec::check(&status) is void);
23 //
24 // By default, the new command will inherit the current process's environment.
25 export fn cmd(name: str, args: str...) (command | error | nomem) = {
26 let platcmd = if (strings::contains(name, '/')) {
27 yield match (open(name)) {
28 case let p: platform_cmd =>
29 yield p;
30 case let err: error =>
31 return err;
32 case =>
33 return nocmd;
34 };
35 } else {
36 yield match (lookup_open(name)?) {
37 case void =>
38 return nocmd;
39 case let p: platform_cmd =>
40 yield p;
41 };
42 };
43
44 let argv = platform_newargv(name, args...)?;
45
46 let env = match (platform_dup_env(os::getenvs())) {
47 case let env: platform_env =>
48 yield env;
49 case nomem =>
50 platform_free_argv(argv);
51 return nomem;
52 };
53
54 return command {
55 platform = platcmd,
56 files = [],
57 dir = "",
58 argv = argv,
59 env = env,
60 ...
61 };
62 };
63
64 // Frees state associated with a command. You only need to call this if you do
65 // not execute the command with [[exec]] or [[start]]; in those cases the state
66 // is cleaned up for you.
67 export fn finish(cmd: *command) void = {
68 platform_finish(cmd);
69 platform_free_argv(cmd.argv);
70 platform_free_env(cmd.env);
71 free(cmd.files);
72 };
73
74 // Executes a prepared command in the current address space, overwriting the
75 // running process with the new command.
76 //
77 // This function will only return if an error occurs.
78 //
79 // const cmd = exec::cmd("/bin/sh", "-c", "echo hello world")?;
80 // const err = exec::exec(&cmd);
81 // // This only runs if exec failed:
82 // fmt::fatal("exec /bin/sh:", exec::strerror(err));
83 export fn exec(cmd: *command) error = {
84 defer finish(cmd); // Note: doesn't happen if exec succeeds
85 return platform_exec(cmd);
86 };
87
88 // Starts a prepared command in a new process.
89 export fn start(cmd: *command) (process | error) = {
90 defer finish(cmd);
91 match (platform_start(cmd)) {
92 case let err: errors::error =>
93 return err;
94 case let proc: process =>
95 return proc;
96 };
97 };
98
99 // Empties the environment variables for the command. By default, the command
100 // inherits the environment of the parent process.
101 export fn clearenv(cmd: *command) void = {
102 platform_free_env(cmd.env);
103 cmd.env = platfrom_newenv();
104 };
105
106 // Adds or sets a variable in the command environment. This does not affect the
107 // current process environment. The key may not contain '=' or '\0'.
108 export fn setenv(
109 cmd: *command,
110 key: str,
111 value: str
112 ) (void | errors::invalid | nomem) = {
113 if (strings::contains(value, '\0')) return errors::invalid;
114 unsetenv(cmd, key)?;
115 return platform_setenv(cmd, key, value);
116 };
117
118 // Removes a variable in the command environment. This does not affect the
119 // current process environment. The key may not contain '=' or '\0'.
120 export fn unsetenv(cmd: *command, key: str) (void | errors::invalid) = {
121 if (strings::contains(key, '=', '\0')) return errors::invalid;
122 return platform_unsetenv(cmd, key);
123 };
124
125 // Sets the 0th value of argv for this command. It is uncommon to need this.
126 export fn setname(cmd: *command, name: str) (void | nomem) =
127 platform_setname(cmd, name);
128
129 // Configures a file in the child process's file table, such that the file
130 // described by the 'source' parameter is mapped onto file descriptor slot
131 // 'child' in the child process via dup(2).
132 //
133 // This operation is performed atomically, such that the following code swaps
134 // stdout and stderr:
135 //
136 // exec::addfile(&cmd, os::stderr_file, os::stdout_file);
137 // exec::addfile(&cmd, os::stdout_file, os::stderr_file);
138 //
139 // Pass [[nullfd]] in the 'source' argument to map the child's file descriptor
140 // to /dev/null or the appropriate platform-specific equivalent.
141 //
142 // Pass [[closefd]] in the 'source' argument to close a file descriptor which
143 // was not opened with the CLOEXEC flag. Note that Hare opens all files with
144 // CLOEXEC by default, so this is not usually necessary.
145 //
146 // To write to a process's stdin, capture its stdout, or pipe two programs
147 // together, see the [[pipe]] function.
148 export fn addfile(
149 cmd: *command,
150 child: io::file,
151 source: (io::file | nullfd | closefd),
152 ) (void | nomem) = {
153 append(cmd.files, (source, child))?;
154 };
155
156 // Closes all standard files (stdin, stdout, and stderr) in the child process.
157 // Many programs do not work well under these conditions; you may want
158 // [[nullstd]] instead.
159 export fn closestd(cmd: *command) (void | nomem) = {
160 addfile(cmd, os::stdin_file, closefd)?;
161 addfile(cmd, os::stdout_file, closefd)?;
162 addfile(cmd, os::stderr_file, closefd)?;
163 };
164
165 // Redirects all standard files (stdin, stdout, and stderr) to /dev/null or the
166 // platform-specific equivalent.
167 export fn nullstd(cmd: *command) (void | nomem) = {
168 addfile(cmd, os::stdin_file, nullfd)?;
169 addfile(cmd, os::stdout_file, nullfd)?;
170 addfile(cmd, os::stderr_file, nullfd)?;
171 };
172
173 // Configures the child process's working directory. This does not affect the
174 // process environment. The path is borrowed from the input, and must outlive
175 // the command.
176 export fn chdir(cmd: *command, dir: str) void = {
177 cmd.dir = dir;
178 };
179
180 // Similar to [[lookup]] but TOCTOU-proof.
181 fn lookup_open(name: str, path: str = "") (platform_cmd | void | error) = {
182 static let buf = path::buffer { ... };
183 path::set(&buf)!;
184
185 // Try to open file directly
186 if (strings::contains(name, "/")) {
187 match (open(name)) {
188 case let err: error =>
189 return err;
190 case let p: platform_cmd =>
191 return p;
192 };
193 };
194
195 if (path == "") {
196 match (os::getenv("PATH")) {
197 case void =>
198 return;
199 case let s: str =>
200 path = s;
201 };
202 };
203
204 let tok = strings::tokenize(path, ":");
205 for (let item => strings::next_token(&tok)) {
206 path::set(&buf, item, name)!;
207
208 match (open(path::string(&buf))) {
209 case (errors::noaccess | errors::noentry) =>
210 continue;
211 case let err: error =>
212 return err;
213 case let p: platform_cmd =>
214 return p;
215 };
216 };
217 };
218
219 // Looks up an executable by name in the path. Consults the $PATH environment
220 // variable if no path argument is provided.
221 //
222 // The use of this function is lightly discouraged if [[cmd]] is suitable;
223 // otherwise you may have a TOCTOU issue.
224 //
225 // The return value is statically allocated.
226 export fn lookup(name: str, path: str = "") (str | fs::error) = {
227 static let buf = path::buffer { ... };
228 path::set(&buf)!;
229
230 // Try to open file directly
231 if (strings::contains(name, "/")) {
232 match (os::access(name, os::amode::X_OK)) {
233 case let exec: bool =>
234 if (exec) {
235 path::set(&buf, name)!;
236 return path::string(&buf);
237 };
238 return errors::noaccess;
239 case =>
240 return errors::noentry;
241 };
242 };
243
244 if (path == "") {
245 match (os::getenv("PATH")) {
246 case void =>
247 return errors::noentry;
248 case let s: str =>
249 path = s;
250 };
251 };
252
253 let tok = strings::tokenize(path, ":");
254 for (let item => strings::next_token(&tok)) {
255 path::set(&buf, item, name)!;
256
257 match (os::access(path::string(&buf), os::amode::X_OK)) {
258 case let exec: bool =>
259 if (exec) {
260 return path::string(&buf);
261 };
262 case => void; // Keep looking
263 };
264 };
265
266 return errors::noentry;
267 };