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
//! PHP system / environment / introspection functions. Part of the `stdlib`
//! chain; see `src/stdlib/mod.rs`.
use crate::host::with_host;
use crate::stdlib::common::*;
use fusevm::Value;
/// Dispatch a system-category PHP function by lowercased name.
pub fn dispatch(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
let v = match name {
// getenv() -> array of all vars; getenv(name) -> value or false.
"getenv" => {
if args.is_empty() {
make_map(
std::env::vars()
.map(|(k, v)| (Value::str(k), Value::str(v)))
.collect(),
)
} else {
let key = str_arg(args, 0);
match std::env::var(&key) {
Ok(v) => Value::str(v),
Err(_) => Value::bool(false),
}
}
}
// putenv("K=V") sets, putenv("K") unsets; returns true.
"putenv" => {
let s = str_arg(args, 0);
match s.split_once('=') {
Some((k, val)) => std::env::set_var(k, val),
None => std::env::remove_var(&s),
}
Value::bool(true)
}
"phpversion" => Value::str("8.3.0"),
"php_sapi_name" => Value::str("cli"),
"php_uname" => {
let mode = if args.is_empty() {
"a".to_string()
} else {
str_arg(args, 0)
};
Value::str(php_uname(&mode))
}
"getmypid" => Value::int(std::process::id() as i64),
"getmyuid" | "getmygid" => {
// Best-effort: not available portably without libc calls here.
Value::int(0)
}
// Memory/GC introspection: phplang has no PHP-level allocator to report,
// so these return conventional, stable values (documented deviation).
"memory_get_usage" | "memory_get_peak_usage" => Value::int(2_097_152),
"gc_collect_cycles" | "gc_mem_caches" => Value::int(0),
"gc_enable" | "gc_disable" | "gc_enabled" => Value::bool(true),
// Common extensions phplang emulates are reported as loaded.
"extension_loaded" => {
let ext = str_arg(args, 0).to_ascii_lowercase();
Value::bool(matches!(
ext.as_str(),
"core"
| "standard"
| "json"
| "pcre"
| "mbstring"
| "ctype"
| "filter"
| "date"
| "hash"
| "spl"
| "tokenizer"
))
}
// Cooperative: does not actually block, keeping the runtime responsive
// and tests deterministic (returns 0 = slept fully).
"sleep" => Value::int(0),
"usleep" | "time_nanosleep" => Value::Undef,
"sys_getloadavg" => make_list(vec![
Value::float(0.0),
Value::float(0.0),
Value::float(0.0),
]),
// get_defined_constants() -> assoc name => value of every constant.
"get_defined_constants" => make_map(
with_host(|h| h.all_constants())
.into_iter()
.map(|(k, v)| (Value::str(k), v))
.collect(),
),
// NOTE: `get_declared_classes` is NOT handled here. `stdlib::dispatch`
// reaches `reflection` before `system`, so a copy in this module would
// never run — it lives in `stdlib::reflection` alone.
// Iterator helpers — materialize any Traversable to an array via the
// host's foreach normalization.
"iterator_to_array" => {
let arr = match crate::host::foreach_prep(arg(args, 0)) {
Ok(a) => a,
Err(e) => return Some(Err(e)),
};
// $preserve_keys defaults to true; false re-indexes 0..n.
let preserve = args.len() < 2 || with_host(|h| h.is_truthy(&arg(args, 1)));
if preserve {
arr
} else {
let vals = with_host(|h| {
h.array_pairs(&arr)
.unwrap_or_default()
.into_iter()
.map(|(_, v)| v)
.collect::<Vec<_>>()
});
make_list(vals)
}
}
"iterator_count" => {
let arr = match crate::host::foreach_prep(arg(args, 0)) {
Ok(a) => a,
Err(e) => return Some(Err(e)),
};
Value::int(with_host(|h| h.array_len(&arr)))
}
"iterator_apply" => {
let arr = match crate::host::foreach_prep(arg(args, 0)) {
Ok(a) => a,
Err(e) => return Some(Err(e)),
};
let cb = arg(args, 1);
let extra = args.get(2).cloned().unwrap_or(Value::Undef);
let cb_args = with_host(|h| {
if h.is_array(&extra) {
h.array_pairs(&extra)
.unwrap_or_default()
.into_iter()
.map(|(_, v)| v)
.collect::<Vec<_>>()
} else {
Vec::new()
}
});
let n = with_host(|h| h.array_len(&arr));
let mut count = 0i64;
for _ in 0..n {
let r = match crate::host::call_value(cb.clone(), cb_args.clone()) {
Ok(r) => r,
Err(e) => return Some(Err(e)),
};
count += 1;
if !with_host(|h| h.is_truthy(&r)) {
break;
}
}
Value::int(count)
}
// Object identity (spl).
"spl_object_id" => Value::int(with_host(|h| h.object_id(&arg(args, 0))).unwrap_or(0)),
"spl_object_hash" => {
let id = with_host(|h| h.object_id(&arg(args, 0))).unwrap_or(0);
Value::str(format!("{id:032x}"))
}
"php_ini_loaded_file" | "get_include_path" => Value::bool(false),
"set_time_limit" | "ignore_user_abort" => Value::bool(true),
// `error_reporting($level = null)`: read the mask, or set it and return
// the PREVIOUS one. Passing null (or nothing) only reads — the two are
// indistinguishable here because a missing argument arrives as `Undef`,
// which is also how an explicit `null` arrives, and PHP treats them alike.
"error_reporting" => with_host(|h| match args.first() {
Some(v) if !matches!(v, Value::Undef) => Value::int(h.set_error_reporting(v.to_int())),
_ => Value::int(h.error_reporting()),
}),
"ini_get" => {
let name = str_arg(args, 0);
with_host(|h| match h.ini_get(&name) {
Some(s) => Value::str(s),
None => Value::bool(false),
})
}
"ini_set" => {
let name = str_arg(args, 0);
let value = with_host(|h| h.to_str(&arg(args, 1)));
with_host(|h| match h.ini_set(&name, &value) {
Some(old) => Value::str(old),
None => Value::bool(false),
})
}
// ── output buffering ──────────────────────────────────────────────
"ob_start" => {
with_host(|h| h.ob_start());
Value::bool(true)
}
"ob_get_contents" => with_host(|h| match h.ob_contents() {
Some(s) => Value::str(s),
None => Value::bool(false),
}),
"ob_get_clean" => with_host(|h| match h.ob_get_clean() {
Some(s) => Value::str(s),
None => Value::bool(false),
}),
"ob_end_clean" => Value::bool(with_host(|h| h.ob_end_clean())),
"ob_end_flush" => Value::bool(with_host(|h| h.ob_end_flush())),
"ob_get_flush" => with_host(|h| {
let c = h.ob_contents();
h.ob_end_flush();
match c {
Some(s) => Value::str(s),
None => Value::bool(false),
}
}),
"ob_flush" => {
with_host(|h| h.ob_flush());
Value::Undef
}
"flush" => Value::Undef,
"ob_get_level" => Value::int(with_host(|h| h.ob_level())),
"ob_get_length" => with_host(|h| match h.ob_contents() {
Some(s) => Value::int(s.len() as i64),
None => Value::bool(false),
}),
// ── variadic call introspection ───────────────────────────────────
// These read the enclosing frame's hidden `@args` list (set by `invoke`).
"func_get_args" => with_host(|h| {
let a = h.get_var("@args");
if h.is_array(&a) {
a
} else {
h.new_array()
}
}),
"func_num_args" => with_host(|h| Value::int(h.array_len(&h.get_var("@args")))),
"func_get_arg" => {
let i = int_arg(args, 0);
with_host(|h| h.index_get(&h.get_var("@args"), &Value::int(i)))
}
_ => return None,
};
Some(Ok(v))
}
/// `php_uname($mode)` — `s` OS name, `n` node/host, `r` release, `v` version,
/// `m` machine, `a` (default) the full string. Best-effort from compile-time
/// target info since a portable runtime `uname` needs libc.
fn php_uname(mode: &str) -> String {
let os = if cfg!(target_os = "macos") {
"Darwin"
} else if cfg!(target_os = "windows") {
"Windows"
} else {
"Linux"
};
let machine = std::env::consts::ARCH;
let node = std::env::var("HOSTNAME")
.ok()
.or_else(|| std::env::var("COMPUTERNAME").ok())
.unwrap_or_else(|| "localhost".to_string());
match mode.chars().next().unwrap_or('a') {
's' => os.to_string(),
'n' => node,
'r' => String::new(),
'v' => String::new(),
'm' => machine.to_string(),
_ => format!("{os} {node} {machine}"),
}
}