| 1 |
// SPDX-License-Identifier: MPL-2.0 |
| 2 |
// (c) Hare authors <https://harelang.org> |
| 3 |
|
| 4 |
use errors; |
| 5 |
use strings; |
| 6 |
|
| 7 |
// All currently supported target architectures. This enum will be extended |
| 8 |
// whenever support for a new architecture is added. |
| 9 |
export type arch = enum { |
| 10 |
AARCH64, |
| 11 |
RISCV64, |
| 12 |
X86_64, |
| 13 |
}; |
| 14 |
|
| 15 |
// Returns a portable string for an [[arch]]. |
| 16 |
export fn arch_name(arch: arch) const str = { |
| 17 |
switch (arch) { |
| 18 |
case arch::AARCH64 => |
| 19 |
return "aarch64"; |
| 20 |
case arch::RISCV64 => |
| 21 |
return "riscv64"; |
| 22 |
case arch::X86_64 => |
| 23 |
return "x86_64"; |
| 24 |
}; |
| 25 |
}; |
| 26 |
|
| 27 |
let envp: []str = []; |
| 28 |
|
| 29 |
@fini fn envp() void = strings::freeall(envp); |
| 30 |
|
| 31 |
// Looks up an environment variable and returns its value, or void if unset. |
| 32 |
export fn getenv(name: const str) (str | void) = { |
| 33 |
getenvs(); // populate envp |
| 34 |
for (let ent .. envp) { |
| 35 |
let (key, value) = strings::cut(ent, "="); |
| 36 |
if (key == name) return value; |
| 37 |
}; |
| 38 |
}; |
| 39 |
|
| 40 |
// Looks up an environment variable and returns its value, or a default value if |
| 41 |
// unset. |
| 42 |
export fn tryenv(name: const str, default: str) str = { |
| 43 |
match (getenv(name)) { |
| 44 |
case let s: str => |
| 45 |
return s; |
| 46 |
case void => |
| 47 |
return default; |
| 48 |
}; |
| 49 |
}; |
| 50 |
|
| 51 |
// Sets an environment variable, overwriting it if it's already set. The name |
| 52 |
// may not contain '=' or '\0', and the value may not contain '\0'. |
| 53 |
export fn setenv( |
| 54 |
name: const str, |
| 55 |
value: const str |
| 56 |
) (void | errors::invalid | nomem) = { |
| 57 |
if (strings::contains(value, '\0')) return errors::invalid; |
| 58 |
unsetenv(name)?; |
| 59 |
let env = strings::join("=", name, value)?; |
| 60 |
if (append(envp, env) is nomem) { |
| 61 |
free(env); |
| 62 |
return nomem; |
| 63 |
}; |
| 64 |
}; |
| 65 |
|
| 66 |
// Unsets an environment variable. Does nothing if the variable isn't set. The |
| 67 |
// name may not contain '=' or '\0'. |
| 68 |
export fn unsetenv(name: const str) (void | errors::invalid) = { |
| 69 |
if (strings::contains(name, '=', '\0')) return errors::invalid; |
| 70 |
getenvs(); // populate envp |
| 71 |
for (let i = 0z; i < len(envp); i += 1) { |
| 72 |
if (strings::cut(envp[i], "=").0 == name) { |
| 73 |
free(envp[i]); |
| 74 |
delete(envp[i]); |
| 75 |
break; |
| 76 |
}; |
| 77 |
}; |
| 78 |
}; |