Skip to main content

speedyspec_php/
global_array.rs

1//! Reading a global PHP array in place, without converting the whole array.
2//!
3//! An area that consults a global on every call (the Shortcode API reads `$shortcode_tags` per `do_shortcode()`)
4//! needs its keys and one entry, not a copy of every value. These functions run no PHP code and allocate no PHP
5//! memory.
6
7use ext_php_rs::ffi::{
8    Bucket, IS_ARRAY, IS_UNDEF, zend_array, zend_hash_index_find, zend_hash_str_find, zval,
9};
10use speedyspec_hooks::Value;
11
12use crate::convert;
13
14/// The live array `$GLOBALS[$name]` holds, references followed.
15///
16/// # Safety
17///
18/// A request is open, on the engine's thread; the pointer is valid until PHP code runs.
19unsafe fn global_table(name: &str) -> Option<*const zend_array> {
20    if !crate::boundary::alive() {
21        return None;
22    }
23    // SAFETY: forwarded from the caller; the slot found is a live zval.
24    unsafe {
25        let slot = crate::runtime::global_slot(name)?;
26        let value = convert::deref(slot);
27        (u32::from(convert::type_of(value)) == IS_ARRAY).then(|| (*value).value.arr.cast_const())
28    }
29}
30
31/// PHP's canonical integer key for `key` (`"7"` but not `"07"`), as array access converts it.
32fn int_key(key: &[u8]) -> Option<i64> {
33    let digits = key.strip_prefix(b"-").unwrap_or(key);
34    if digits.is_empty() || !digits.iter().all(u8::is_ascii_digit) {
35        return None;
36    }
37    if digits[0] == b'0' && (digits.len() > 1 || key.len() != digits.len()) {
38        return None;
39    }
40    std::str::from_utf8(key).ok()?.parse().ok()
41}
42
43/// `$GLOBALS[$name][$key]`'s slot, PHP's key conversion applied.
44///
45/// # Safety
46///
47/// As [`global_table`].
48unsafe fn entry(name: &str, key: &[u8]) -> Option<*const zval> {
49    // SAFETY: forwarded from the caller; both lookups only read the live table.
50    unsafe {
51        let table = global_table(name)?;
52        let slot = match int_key(key) {
53            Some(i) => zend_hash_index_find(table, i as u64),
54            None => zend_hash_str_find(table, key.as_ptr().cast(), key.len()),
55        };
56        if slot.is_null() || u32::from(convert::type_of(convert::deref(slot))) == IS_UNDEF {
57            return None;
58        }
59        Some(slot.cast_const())
60    }
61}
62
63/// The keys of the array in `$GLOBALS[$name]`, in PHP's order, as bytes (integer keys in decimal); `None` when the
64/// global is unset or not an array.
65pub fn global_array_keys(name: &str) -> Option<Vec<Vec<u8>>> {
66    // SAFETY: the table is read and nothing runs PHP code meanwhile. A packed array stores `nNumUsed` zvals in
67    // `arPacked`, any other array `nNumUsed` buckets in `arData`; holes are skipped, as PHP's own iteration does.
68    unsafe {
69        let ht = global_table(name)?;
70        let used = (*ht).nNumUsed as usize;
71        let mut keys = Vec::with_capacity((*ht).nNumOfElements as usize);
72        if (*ht).u.flags & convert::HASH_FLAG_PACKED != 0 {
73            let packed = (*ht).__bindgen_anon_1.arPacked;
74            for i in 0..used {
75                if !convert::is_hole(packed.add(i)) {
76                    keys.push(i.to_string().into_bytes());
77                }
78            }
79        } else {
80            let data: *const Bucket = (*ht).__bindgen_anon_1.arData;
81            for i in 0..used {
82                let bucket = data.add(i);
83                if convert::is_hole(&raw const (*bucket).val) {
84                    continue;
85                }
86                keys.push(if (*bucket).key.is_null() {
87                    ((*bucket).h as i64).to_string().into_bytes()
88                } else {
89                    convert::str_bytes((*bucket).key).to_vec()
90                });
91            }
92        }
93        Some(keys)
94    }
95}
96
97/// `array_key_exists( $key, $GLOBALS[$name] )`.
98pub fn global_array_contains(name: &str, key: &[u8]) -> bool {
99    // SAFETY: a lookup in the live table.
100    unsafe { entry(name, key).is_some() }
101}
102
103/// `$GLOBALS[$name][$key]`, converted to a [`Value`]; `None` when absent. Only that entry is converted.
104pub fn global_array_get(name: &str, key: &[u8]) -> Option<Value> {
105    // SAFETY: the entry is live, and `to_value` runs no PHP code.
106    unsafe { convert::to_value(entry(name, key)?).ok() }
107}