Repository navigation
Expand file tree
/
Copy pathenv.wave
More file actions
86 lines (80 loc) · 2.67 KB
/
Copy pathenv.wave
File metadata and controls
86 lines (80 loc) · 2.67 KB
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
// This file is part of the Wave language project.
// Copyright (c) 2024-2026 Wave Foundation and contributors
// SPDX-License-Identifier: Apache-2.0
// Darwin's CRT process-entry accessor returns the address of the current envp.
// This is a narrow native OS adapter, shared by both supported architectures.
// ABI: https://github.com/apple-oss-distributions/Libc/blob/main/include/crt_externs.h
// KERN_PROCARGS2 also contains applev entries and cannot delimit envp reliably.
import("std::mem::layout")::{size_of};
extern(c, "_NSGetEnviron") fun darwin_environment() -> ptr<ptr<ptr<u8>>>;
// Preserve the original exported constant for callers; ordinary reads no
// longer use its not-implemented result.
pub const ERR_NOT_IMPLEMENTED: i64 = -38;
fun _copy_environment(entries: ptr<ptr<u8>>, buf: ptr<u8>, cap: i64) -> i64 {
if (entries == null) {
return 0;
}
var total: i64 = 0;
var count: i64 = 0;
var pointer_size: i64 = size_of<ptr<u8>>() as i64;
while (true) {
if (count >= 9223372036854775807 / pointer_size) {
return -75;
}
var entry: ptr<u8> = entries[count];
if (entry == null) {
break;
}
var length: i64 = 0;
// Capacity bounds source scanning as well as the destination. Reserve
// one byte for each entry's NUL before adding its length to total.
while (entry[length] != 0) {
if (length >= cap - total - 1) {
return -28;
}
length += 1;
}
if (length >= cap - total) {
return -28;
}
total += length + 1;
count += 1;
}
// Wave's environment API does not mutate envp. Native embedding code must
// not change it concurrently; copying remains bounded even if strings grow.
var written: i64 = 0;
var index: i64 = 0;
while (index < count) {
var entry: ptr<u8> = entries[index];
if (entry == null) {
return -5;
}
var offset: i64 = 0;
var complete: bool = false;
while (!complete) {
if (written >= total) {
return -5;
}
var octet: u8 = entry[offset];
buf[written] = octet;
written += 1;
offset += 1;
complete = octet == 0;
}
index += 1;
}
if (written != total) {
return -5;
}
return written;
}
pub fun env_read(buf: ptr<u8>, cap: i64) -> i64 {
if (buf == null || cap <= 0) {
return -22;
}
var address: ptr<ptr<ptr<u8>>> = darwin_environment();
if (address == null) {
return -5;
}
return _copy_environment(deref address, buf, cap);
}