use crate::host::with_host;
use fusevm::Value;
use super::common::arg;
pub fn dispatch(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
let v = match name {
"is_scalar" => Value::bool(matches!(
arg(args, 0),
Value::Int(_) | Value::Float(_) | Value::Str(_) | Value::Bool(_)
)),
"is_object" => {
let a = arg(args, 0);
with_host(|h| Value::bool(h.is_object(&a) || h.is_closure(&a)))
}
"is_countable" => {
let a = arg(args, 0);
with_host(|h| {
Value::bool(
h.is_array(&a)
|| h.object_class(&a)
.is_some_and(|c| h.class_is_a_pub(&c, "Countable")),
)
})
}
"is_iterable" => {
let a = arg(args, 0);
with_host(|h| {
Value::bool(
h.is_array(&a)
|| h.is_generator_val(&a)
|| h.object_class(&a).is_some_and(|c| {
h.class_is_a_pub(&c, "Traversable")
|| h.class_is_a_pub(&c, "Iterator")
|| h.class_is_a_pub(&c, "IteratorAggregate")
}),
)
})
}
"get_debug_type" => {
let a = arg(args, 0);
let name = with_host(|h| debug_type(h, &a));
Value::str(name)
}
"serialize" => {
let a = arg(args, 0);
let out = with_host(|h| php_serialize(h, &a));
Value::str(out)
}
"unserialize" => {
let s = with_host(|h| h.to_str(&arg(args, 0)));
let bytes = s.as_bytes();
let total = bytes.len();
if total == 0 {
return Some(Ok(Value::bool(false)));
}
match php_unserialize(bytes) {
Unser::Value(v) => v,
Unser::Saturated(v) => {
with_host(|h| h.warn("unserialize(): Numerical result out of range"));
v
}
Unser::Extra(v, at) => {
with_host(|h| {
h.warn(format_args!(
"unserialize(): Extra data starting at offset {at} of {total} bytes"
))
});
v
}
Unser::Failed(at, short) => {
with_host(|h| {
if short {
h.warn("unserialize(): Unexpected end of serialized data");
}
h.warn(format_args!(
"unserialize(): Error at offset {at} of {total} bytes"
))
});
Value::bool(false)
}
}
}
_ => return None,
};
Some(Ok(v))
}
pub fn value_name(h: &crate::host::PhpHost, v: &Value) -> String {
match v {
Value::Bool(true) => "true".to_string(),
Value::Bool(false) => "false".to_string(),
_ => debug_type(h, v),
}
}
pub fn debug_type(h: &crate::host::PhpHost, v: &Value) -> String {
match v {
Value::Undef => "null".to_string(),
Value::Bool(_) => "bool".to_string(),
Value::Int(_) => "int".to_string(),
Value::Float(_) => "float".to_string(),
Value::Str(_) => "string".to_string(),
Value::Obj(_) => {
if h.is_array(v) {
"array".to_string()
} else if h.is_closure(v) {
"Closure".to_string()
} else {
h.object_class(v).map_or_else(
|| "object".to_string(),
|c| crate::host::display_class(&c).to_string(),
)
}
}
_ => "unknown".to_string(),
}
}
fn php_serialize(h: &crate::host::PhpHost, v: &Value) -> String {
php_serialize_seen(h, v, &mut crate::host::Visiting::default())
}
fn php_serialize_seen(
h: &crate::host::PhpHost,
v: &Value,
seen: &mut crate::host::Visiting,
) -> String {
if (h.is_array(v) || h.is_object(v)) && !seen.enter(v) {
return "N;".to_string();
}
let out = php_serialize_body(h, v, seen);
if h.is_array(v) || h.is_object(v) {
seen.leave();
}
out
}
fn php_serialize_body(
h: &crate::host::PhpHost,
v: &Value,
seen: &mut crate::host::Visiting,
) -> String {
match v {
Value::Undef => "N;".to_string(),
Value::Bool(b) => format!("b:{};", *b as i32),
Value::Int(n) => format!("i:{n};"),
Value::Float(f) => format!("d:{};", serialize_float(*f)),
Value::Str(s) => format!("s:{}:\"{}\";", s.len(), s),
Value::Obj(_) if h.is_array(v) => {
let pairs = h.array_pairs(v).unwrap_or_default();
let mut out = format!("a:{}:{{", pairs.len());
for (k, val) in pairs {
out.push_str(&php_serialize_seen(h, &k, seen));
out.push_str(&php_serialize_seen(h, &val, seen));
}
out.push('}');
out
}
Value::Obj(_) if h.is_object(v) => php_serialize_object(h, v, seen),
_ => "N;".to_string(),
}
}
fn php_serialize_object(
h: &crate::host::PhpHost,
v: &Value,
seen: &mut crate::host::Visiting,
) -> String {
let class = h.object_class(v).unwrap_or_else(|| "stdClass".to_string());
if let Some((case, _)) = h.enum_case_of(v) {
let tag = format!("{class}:{case}");
return format!("E:{}:\"{tag}\";", tag.len());
}
let props = h.object_props(v);
let mut out = format!("O:{}:\"{class}\":{}:{{", class.len(), props.len());
for (name, val) in props {
let key = match h.prop_visibility(&class, &name) {
Some((_, crate::ast::Visibility::Protected)) => format!("\0*\0{name}"),
Some((declaring, crate::ast::Visibility::Private)) => format!("\0{declaring}\0{name}"),
_ => name,
};
out.push_str(&format!("s:{}:\"{key}\";", key.len()));
out.push_str(&php_serialize_seen(h, &val, seen));
}
out.push('}');
out
}
pub fn serialize_float(f: f64) -> String {
if f.is_nan() {
return "NAN".to_string();
}
if f.is_infinite() {
return if f < 0.0 { "-INF" } else { "INF" }.to_string();
}
if f == 0.0 {
return if f.is_sign_negative() { "-0" } else { "0" }.to_string();
}
let neg = f < 0.0;
let a = f.abs();
let sci = format!("{a:e}");
let (mant, exp_s) = sci.split_once('e').expect("`{:e}` always contains 'e'");
let exp: i32 = exp_s.parse().expect("`{:e}` exponent is an integer");
let digits: String = mant.chars().filter(|c| *c != '.').collect();
let decpt = exp + 1;
let body = if !(-3..=17).contains(&decpt) {
let (first, rest) = digits.split_at(1);
let frac = if rest.is_empty() { "0" } else { rest };
let e = decpt - 1;
format!(
"{first}.{frac}E{}{}",
if e < 0 { "-" } else { "+" },
e.abs()
)
} else if decpt <= 0 {
format!("0.{}{}", "0".repeat((-decpt) as usize), digits)
} else if decpt as usize >= digits.len() {
format!("{digits}{}", "0".repeat(decpt as usize - digits.len()))
} else {
let (int_part, frac) = digits.split_at(decpt as usize);
format!("{int_part}.{frac}")
};
if neg {
format!("-{body}")
} else {
body
}
}
enum Unser {
Value(Value),
Extra(Value, usize),
Saturated(Value),
Failed(usize, bool),
}
fn php_unserialize(b: &[u8]) -> Unser {
let mut p = Parser {
b,
pos: 0,
fail_at: None,
unexpected_end: false,
saturated: false,
};
let Some(v) = p.value() else {
return Unser::Failed(p.fail_at.unwrap_or(0), p.unexpected_end);
};
if p.pos != b.len() {
Unser::Extra(v, p.pos)
} else if p.saturated {
Unser::Saturated(v)
} else {
Unser::Value(v)
}
}
struct Parser<'a> {
b: &'a [u8],
pos: usize,
fail_at: Option<usize>,
unexpected_end: bool,
saturated: bool,
}
impl<'a> Parser<'a> {
fn eat(&mut self, s: &[u8]) -> Option<()> {
if self.b[self.pos..].starts_with(s) {
self.pos += s.len();
Some(())
} else {
None
}
}
fn read_until(&mut self, delim: u8) -> Option<&'a [u8]> {
let start = self.pos;
while self.pos < self.b.len() && self.b[self.pos] != delim {
self.pos += 1;
}
if self.pos >= self.b.len() {
return None;
}
let slice = &self.b[start..self.pos];
self.pos += 1; Some(slice)
}
fn int_until(&mut self, delim: u8) -> Option<i64> {
let s = std::str::from_utf8(self.read_until(delim)?).ok()?;
s.parse().ok()
}
fn int_value(&mut self, delim: u8) -> Option<i64> {
let s = std::str::from_utf8(self.read_until(delim)?).ok()?;
match s.parse::<i64>() {
Ok(n) => Some(n),
Err(_) => {
let (neg, body) = match s.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, s),
};
if !body.is_empty() && body.bytes().all(|c| c.is_ascii_digit()) {
self.saturated = true;
Some(if neg { i64::MIN } else { i64::MAX })
} else {
None
}
}
}
}
fn fail_at(&mut self, offset: usize) -> Option<Value> {
self.fail_at.get_or_insert(offset);
None
}
fn container_exhausted(&mut self) -> Option<Option<Value>> {
if self.b.get(self.pos) != Some(&b'}') {
return None;
}
self.unexpected_end = true;
Some(self.fail_at(self.pos))
}
fn close_container(&mut self) -> Option<()> {
if self.b.get(self.pos) != Some(&b'}') {
self.fail_at(self.pos);
return None;
}
self.pos += 1;
Some(())
}
fn value(&mut self) -> Option<Value> {
let start = self.pos;
let Some(&tag) = self.b.get(self.pos) else {
return self.fail_at(start);
};
let blame = match tag {
b's' | b'O' | b'E' => start + 2,
_ => start,
};
match self.value_inner(tag) {
Some(v) => Some(v),
None => self.fail_at(blame),
}
}
fn value_inner(&mut self, tag: u8) -> Option<Value> {
match tag {
b'N' => {
self.eat(b"N;")?;
Some(Value::Undef)
}
b'b' => {
self.eat(b"b:")?;
let d = *self.b.get(self.pos)?;
self.pos += 1;
self.eat(b";")?;
match d {
b'0' => Some(Value::bool(false)),
b'1' => Some(Value::bool(true)),
_ => None,
}
}
b'i' => {
self.eat(b"i:")?;
let n = self.int_value(b';')?;
Some(Value::int(n))
}
b'd' => {
self.eat(b"d:")?;
let s = std::str::from_utf8(self.read_until(b';')?).ok()?;
let f = match s {
"NAN" => f64::NAN,
"INF" => f64::INFINITY,
"-INF" => f64::NEG_INFINITY,
_ => s.parse().ok()?,
};
Some(Value::float(f))
}
b's' => {
self.eat(b"s:")?;
let len = self.int_until(b':')? as usize;
self.eat(b"\"")?;
let end = self.pos.checked_add(len)?;
if end > self.b.len() {
return None;
}
let bytes = &self.b[self.pos..end];
self.pos = end;
self.eat(b"\";")?;
Some(Value::str(String::from_utf8_lossy(bytes).into_owned()))
}
b'a' => {
self.eat(b"a:")?;
let count = self.int_until(b':')?;
if count < 0 {
return None;
}
self.eat(b"{")?;
let mut pairs: Vec<(Value, Value)> = Vec::new();
for _ in 0..count {
if let Some(fail) = self.container_exhausted() {
return fail;
}
let k = self.value()?;
if let Some(fail) = self.container_exhausted() {
return fail;
}
let v = self.value()?;
pairs.push((k, v));
}
self.close_container()?;
Some(super::common::make_map(pairs))
}
b'O' => {
self.eat(b"O:")?;
let class = self.length_prefixed_string()?;
self.eat(b":")?;
let count = self.int_until(b':')?;
if count < 0 {
return None;
}
self.eat(b"{")?;
let mut props: Vec<(String, Value)> = Vec::with_capacity(count as usize);
for _ in 0..count {
if let Some(fail) = self.container_exhausted() {
return fail;
}
let Value::Str(k) = self.value()? else {
return None;
};
if let Some(fail) = self.container_exhausted() {
return fail;
}
props.push((demangle_prop(&k), self.value()?));
}
self.close_container()?;
let known = with_host(|h| h.class_exists(&class));
if !known {
props.insert(
0,
(
"__PHP_Incomplete_Class_Name".to_string(),
Value::str(class.clone()),
),
);
}
let target = if known {
class
} else {
"__PHP_Incomplete_Class".to_string()
};
Some(with_host(|h| h.new_object_bare(&target, props)))
}
b'E' => {
self.eat(b"E:")?;
let tag = self.length_prefixed_string()?;
self.eat(b";")?;
let (class, case) = tag.split_once(':')?;
crate::host::class_const(class, case).ok()
}
_ => None,
}
}
fn length_prefixed_string(&mut self) -> Option<String> {
let len = self.int_until(b':')? as usize;
self.eat(b"\"")?;
let end = self.pos.checked_add(len)?;
if end > self.b.len() {
return None;
}
let bytes = &self.b[self.pos..end];
self.pos = end;
self.eat(b"\"")?;
Some(String::from_utf8_lossy(bytes).into_owned())
}
}
fn demangle_prop(k: &str) -> String {
match k.strip_prefix('\0') {
Some(rest) => rest
.split_once('\0')
.map(|(_, name)| name.to_string())
.unwrap_or_else(|| k.to_string()),
None => k.to_string(),
}
}