use std::fmt;
use std::mem::ManuallyDrop;
use std::ptr;
use std::rc::Rc;
use ext_php_rs::ffi::{
_zend_new_array, Bucket, IS_ARRAY, IS_ARRAY_EX, IS_DOUBLE, IS_FALSE, IS_INDIRECT, IS_LONG,
IS_NULL, IS_OBJECT, IS_REFERENCE, IS_RESOURCE, IS_STRING, IS_STRING_EX, IS_TRUE,
IS_TYPE_REFCOUNTED, IS_UNDEF, ext_php_rs_zend_string_init, zend_array, zend_hash_index_update,
zend_hash_str_update, zend_object, zend_string, zend_ulong, zval,
};
use ext_php_rs::types::Zval;
use speedyspec_hooks::{Key, Value};
use crate::boundary;
pub(crate) const HASH_FLAG_PACKED: u32 = 1 << 2;
const GC_IMMUTABLE: u32 = 1 << 6;
const MAX_DEPTH: usize = 512;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ConvertError {
Recursive,
TooDeep,
NonUtf8Key,
Unsupported,
}
impl fmt::Display for ConvertError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Recursive => "the array contains itself",
Self::TooDeep => "the value is nested too deeply",
Self::NonUtf8Key => "an array key is not valid UTF-8",
Self::Unsupported => "the value has an unsupported type",
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Unconvertible {
ForeignOpaque,
TooDeep,
}
impl fmt::Display for Unconvertible {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::ForeignOpaque => "an opaque Rust value cannot be passed to PHP",
Self::TooDeep => "the value is nested too deeply",
})
}
}
pub(crate) struct ZvalHandle {
zv: ManuallyDrop<Zval>,
}
impl ZvalHandle {
pub(crate) unsafe fn copy_of(src: *const zval) -> Self {
let zv = unsafe { ptr::read(src.cast::<ManuallyDrop<Zval>>()) };
unsafe { add_ref(&raw const *zv) };
Self { zv }
}
pub(crate) unsafe fn adopt_object(obj: *mut zend_object) -> Self {
let mut zv = ManuallyDrop::new(Zval::new());
zv.value.obj = obj;
zv.u1.type_info = ext_php_rs::ffi::IS_OBJECT_EX;
Self { zv }
}
pub(crate) fn as_ptr(&self) -> *const zval {
&raw const *self.zv
}
pub(crate) unsafe fn adopt(zv: ManuallyDrop<Zval>) -> Self {
Self { zv }
}
pub(crate) fn object(&self) -> Option<*mut zend_object> {
unsafe { (type_of(self.as_ptr()) == IS_OBJECT as u8).then(|| self.zv.value.obj) }
}
pub(crate) fn into_object(self) -> Option<*mut zend_object> {
let obj = self.object()?;
std::mem::forget(self);
Some(obj)
}
}
impl Drop for ZvalHandle {
fn drop(&mut self) {
let zv = unsafe { ManuallyDrop::take(&mut self.zv) };
boundary::release_later(ManuallyDrop::new(zv));
}
}
pub(crate) unsafe fn pass_through(zv: *const zval) -> Value {
unsafe {
let zv = deref(zv);
match u32::from(type_of(zv)) {
IS_LONG => Value::Int((*zv).value.lval),
IS_DOUBLE => Value::Float((*zv).value.dval),
IS_FALSE => Value::Bool(false),
IS_TRUE => Value::Bool(true),
IS_STRING | IS_ARRAY | IS_OBJECT | IS_RESOURCE => {
Value::Opaque(Rc::new(ZvalHandle::copy_of(zv)))
}
_ => Value::Null,
}
}
}
pub(crate) unsafe fn pass_through_owned(zv: ManuallyDrop<Zval>) -> Value {
unsafe {
match u32::from(type_of(&raw const *zv)) {
IS_STRING | IS_ARRAY | IS_OBJECT | IS_RESOURCE => {
Value::Opaque(Rc::new(ZvalHandle::adopt(zv)))
}
IS_REFERENCE => {
let value = pass_through(&raw const *zv);
boundary::release_later(zv);
value
}
_ => pass_through(&raw const *zv),
}
}
}
pub(crate) fn readable_opaque(any: &dyn std::any::Any) -> bool {
any.downcast_ref::<ZvalHandle>().is_some_and(|handle| {
let ty = u32::from(unsafe { type_of(handle.as_ptr()) });
ty == IS_STRING || ty == IS_ARRAY
})
}
pub(crate) fn read_opaque(any: &dyn std::any::Any) -> Option<Value> {
if !readable_opaque(any) {
return None;
}
let handle = any.downcast_ref::<ZvalHandle>()?;
unsafe { to_value(handle.as_ptr()).ok() }
}
pub(crate) unsafe fn string_hash(zv: *const zval) -> Option<u64> {
unsafe {
let zv = deref(zv);
if u32::from(type_of(zv)) != IS_STRING {
return None;
}
let s = (*zv).value.str_;
let h = (*s).h;
Some(if h != 0 { h } else { zend_string_hash_func(s) })
}
}
unsafe extern "C" {
fn zend_string_hash_func(s: *mut zend_string) -> zend_ulong;
}
pub(crate) fn handle_of(value: &Value) -> Option<&ZvalHandle> {
match value {
Value::Opaque(any) => any.downcast_ref::<ZvalHandle>(),
_ => None,
}
}
pub(crate) unsafe fn type_of(zv: *const zval) -> u8 {
unsafe { (*zv).u1.v.type_ }
}
pub(crate) unsafe fn add_ref(zv: *const zval) {
unsafe {
if u32::from((*zv).u1.v.type_flags) & IS_TYPE_REFCOUNTED != 0 {
(*(*zv).value.counted).gc.refcount += 1;
}
}
}
pub(crate) unsafe fn deref(mut zv: *const zval) -> *const zval {
unsafe {
loop {
match u32::from(type_of(zv)) {
IS_REFERENCE => zv = &raw const (*(*zv).value.ref_).val,
IS_INDIRECT => zv = (*zv).value.zv,
_ => return zv,
}
}
}
}
pub(crate) unsafe fn str_bytes<'a>(s: *const zend_string) -> &'a [u8] {
unsafe { std::slice::from_raw_parts((&raw const (*s).val).cast::<u8>(), (*s).len) }
}
pub(crate) unsafe fn to_value(zv: *const zval) -> Result<Value, ConvertError> {
let mut arrays = Vec::new();
unsafe { read(zv, &mut arrays) }
}
unsafe fn read(
zv: *const zval,
arrays: &mut Vec<*const zend_array>,
) -> Result<Value, ConvertError> {
unsafe {
let zv = deref(zv);
Ok(match u32::from(type_of(zv)) {
IS_UNDEF | IS_NULL => Value::Null,
IS_FALSE => Value::Bool(false),
IS_TRUE => Value::Bool(true),
IS_LONG => Value::Int((*zv).value.lval),
IS_DOUBLE => Value::Float((*zv).value.dval),
IS_STRING => {
let bytes = str_bytes((*zv).value.str_);
match std::str::from_utf8(bytes) {
Ok(s) => Value::Str(s.to_owned()),
Err(_) => Value::Bytes(bytes.to_vec()),
}
}
IS_ARRAY => read_array((*zv).value.arr, arrays)?,
IS_OBJECT | IS_RESOURCE => Value::Opaque(Rc::new(ZvalHandle::copy_of(zv))),
_ => return Err(ConvertError::Unsupported),
})
}
}
unsafe fn read_array(
ht: *const zend_array,
arrays: &mut Vec<*const zend_array>,
) -> Result<Value, ConvertError> {
if arrays.contains(&ht) {
return Err(ConvertError::Recursive);
}
if arrays.len() >= MAX_DEPTH {
return Err(ConvertError::TooDeep);
}
arrays.push(ht);
let items = unsafe {
let used = (*ht).nNumUsed as usize;
let mut items = Vec::with_capacity((*ht).nNumOfElements as usize);
if (*ht).u.flags & HASH_FLAG_PACKED != 0 {
let packed = (*ht).__bindgen_anon_1.arPacked;
for i in 0..used {
let slot = packed.add(i);
if is_hole(slot) {
continue;
}
let key = Key::Int(i64::try_from(i).unwrap_or(i64::MAX));
items.push((key, read(slot, arrays)?));
}
} else {
let data: *const Bucket = (*ht).__bindgen_anon_1.arData;
for i in 0..used {
let bucket = data.add(i);
let slot = &raw const (*bucket).val;
if is_hole(slot) {
continue;
}
let key = if (*bucket).key.is_null() {
Key::Int((*bucket).h as i64)
} else {
let bytes = str_bytes((*bucket).key);
let s = std::str::from_utf8(bytes).map_err(|_| ConvertError::NonUtf8Key)?;
Key::Str(s.to_owned())
};
items.push((key, read(slot, arrays)?));
}
}
items
};
arrays.pop();
Ok(Value::Array(items))
}
pub(crate) unsafe fn array_values(ht: *const zend_array) -> Vec<*const zval> {
unsafe {
let used = (*ht).nNumUsed as usize;
let mut slots = Vec::with_capacity((*ht).nNumOfElements as usize);
if (*ht).u.flags & HASH_FLAG_PACKED != 0 {
let packed = (*ht).__bindgen_anon_1.arPacked;
for i in 0..used {
let slot = packed.add(i).cast_const();
if !is_hole(slot) {
slots.push(slot);
}
}
} else {
let data: *const Bucket = (*ht).__bindgen_anon_1.arData;
for i in 0..used {
let slot = &raw const (*data.add(i)).val;
if !is_hole(slot) {
slots.push(slot);
}
}
}
slots
}
}
pub(crate) unsafe fn pop_last(ht: *mut zend_array) {
unsafe {
let used = (*ht).nNumUsed as usize;
if (*ht).u.flags & HASH_FLAG_PACKED != 0 {
let packed = (*ht).__bindgen_anon_1.arPacked;
let Some(i) = (0..used).rev().find(|&i| !is_hole(packed.add(i))) else {
return;
};
ext_php_rs::ffi::zend_hash_index_del(ht, i as zend_ulong);
if i as i64 == (*ht).nNextFreeElement - 1 {
(*ht).nNextFreeElement -= 1;
}
} else {
let data: *mut Bucket = (*ht).__bindgen_anon_1.arData;
let Some(i) = (0..used)
.rev()
.find(|&i| !is_hole(&raw const (*data.add(i)).val))
else {
return;
};
let bucket = data.add(i);
if (*bucket).key.is_null() {
let h = (*bucket).h;
ext_php_rs::ffi::zend_hash_index_del(ht, h);
if h as i64 == (*ht).nNextFreeElement - 1 {
(*ht).nNextFreeElement -= 1;
}
} else {
ext_php_rs::ffi::zend_hash_del(ht, (*bucket).key);
}
}
(*ht).nInternalPointer = 0;
}
}
pub(crate) unsafe fn is_hole(slot: *const zval) -> bool {
unsafe {
let ty = u32::from(type_of(slot));
ty == IS_UNDEF || (ty == IS_INDIRECT && u32::from(type_of((*slot).value.zv)) == IS_UNDEF)
}
}
pub(crate) unsafe fn write_value(out: *mut zval, value: &Value) -> Result<(), Unconvertible> {
unsafe { write(out, value, 0) }
}
pub(crate) unsafe fn write_without_engine(out: *mut zval, value: &Value) -> bool {
match value {
Value::Null | Value::Bool(_) | Value::Int(_) | Value::Float(_) => {
unsafe { write(out, value, 0) }.is_ok()
}
Value::Opaque(_) => match handle_of(value) {
Some(handle) => {
unsafe {
ptr::copy_nonoverlapping(handle.as_ptr(), out, 1);
add_ref(out);
}
true
}
None => false,
},
_ => false,
}
}
unsafe fn write(out: *mut zval, value: &Value, depth: usize) -> Result<(), Unconvertible> {
if depth >= MAX_DEPTH {
return Err(Unconvertible::TooDeep);
}
unsafe {
match value {
Value::Null => (*out).u1.type_info = IS_NULL,
Value::Bool(b) => (*out).u1.type_info = if *b { IS_TRUE } else { IS_FALSE },
Value::Int(i) => {
(*out).value.lval = *i;
(*out).u1.type_info = IS_LONG;
}
Value::Float(f) => {
(*out).value.dval = *f;
(*out).u1.type_info = IS_DOUBLE;
}
Value::Str(s) => write_string(out, s.as_bytes()),
Value::Bytes(b) => write_string(out, b),
Value::Array(items) => {
let size = u32::try_from(items.len()).unwrap_or(u32::MAX);
let ht = _zend_new_array(size);
(*out).value.arr = ht;
(*out).u1.type_info = IS_ARRAY_EX;
for (key, item) in items {
let mut null = ManuallyDrop::new(Zval::new());
let tmp: *mut zval = &raw mut *null;
let slot = match key {
Key::Int(i) => zend_hash_index_update(ht, *i as zend_ulong, tmp),
Key::Str(s) => match canonical_int_key(s) {
Some(i) => zend_hash_index_update(ht, i as zend_ulong, tmp),
None => zend_hash_str_update(ht, s.as_ptr().cast(), s.len(), tmp),
},
};
write(slot, item, depth + 1)?;
}
}
Value::Opaque(_) => {
let handle = handle_of(value).ok_or(Unconvertible::ForeignOpaque)?;
ptr::copy_nonoverlapping(handle.as_ptr(), out, 1);
add_ref(out);
}
}
}
Ok(())
}
unsafe fn write_string(out: *mut zval, bytes: &[u8]) {
unsafe {
let s = ext_php_rs_zend_string_init(bytes.as_ptr().cast(), bytes.len(), false);
(*out).value.str_ = s;
(*out).u1.type_info = if (*s).gc.u.type_info & GC_IMMUTABLE != 0 {
IS_STRING
} else {
IS_STRING_EX
};
}
}
fn canonical_int_key(s: &str) -> Option<i64> {
let digits = s.strip_prefix('-').unwrap_or(s);
let canonical = !digits.is_empty()
&& digits.bytes().all(|b| b.is_ascii_digit())
&& (digits == "0" || !digits.starts_with('0'))
&& s != "-0";
if canonical { s.parse().ok() } else { None }
}
#[cfg(test)]
mod tests {
use super::canonical_int_key;
#[test]
fn canonical_int_keys_follow_php() {
assert_eq!(canonical_int_key("5"), Some(5));
assert_eq!(canonical_int_key("0"), Some(0));
assert_eq!(canonical_int_key("-3"), Some(-3));
for s in ["", "-", "05", "-0", "+1", "1 ", "a", "9223372036854775808"] {
assert_eq!(canonical_int_key(s), None, "{s:?}");
}
}
}