1use std::cell::RefCell;
11use std::collections::HashMap;
12use std::ffi::CString;
13use std::rc::Rc;
14
15use ext_php_rs::args::Arg;
16use ext_php_rs::builders::FunctionBuilder;
17use ext_php_rs::ffi::{
18 IS_ARRAY, IS_FALSE, IS_LONG, IS_OBJECT, ext_php_rs_executor_globals, zend_ce_exception,
19 zend_class_entry, zend_hash_index_find, zend_hash_str_find, zend_throw_exception, zval,
20};
21use ext_php_rs::flags::DataType;
22use ext_php_rs::types::Zval;
23use ext_php_rs::zend::ExecuteData;
24use speedyspec_hooks::Value;
25
26use crate::boundary;
27use crate::convert;
28
29#[derive(Clone, Debug, PartialEq)]
31pub enum NativeError {
32 Throw { class: String, message: String },
34 Rethrow(Value),
36 Silent,
38}
39
40impl NativeError {
41 pub fn throw(class: &str, message: impl Into<String>) -> NativeError {
42 NativeError::Throw {
43 class: class.to_owned(),
44 message: message.into(),
45 }
46 }
47}
48
49pub type Handler = Rc<dyn Fn(&[Value]) -> Result<Value, NativeError>>;
51
52pub type RawHandler = Rc<dyn Fn(&Args<'_>) -> Result<Value, NativeError>>;
54
55#[derive(Clone)]
56enum Body {
57 Converted(Handler),
58 Raw(RawHandler),
59}
60
61thread_local! {
62 static HANDLERS: RefCell<HashMap<String, Body>> = RefCell::new(HashMap::new());
63 static BY_FUNCTION: RefCell<HashMap<usize, Body>> = RefCell::new(HashMap::new());
65}
66
67fn register(name: &str, body: Body) -> FunctionBuilder<'static> {
68 HANDLERS.with(|h| h.borrow_mut().insert(name.to_ascii_lowercase(), body));
69 BY_FUNCTION.with(|h| h.borrow_mut().clear());
70 FunctionBuilder::new(name, dispatch)
71 .arg(Arg::new("args", DataType::Mixed).is_variadic())
72 .returns(DataType::Mixed, false, true)
73}
74
75pub fn function(
77 name: &str,
78 handler: impl Fn(&[Value]) -> Result<Value, NativeError> + 'static,
79) -> FunctionBuilder<'static> {
80 register(name, Body::Converted(Rc::new(handler)))
81}
82
83pub fn raw_function(
86 name: &str,
87 handler: impl Fn(&Args<'_>) -> Result<Value, NativeError> + 'static,
88) -> FunctionBuilder<'static> {
89 register(name, Body::Raw(Rc::new(handler)))
90}
91
92pub struct Args<'a> {
95 ex: &'a ExecuteData,
96 count: usize,
97}
98
99impl Args<'_> {
100 pub fn len(&self) -> usize {
101 self.count
102 }
103
104 pub fn is_empty(&self) -> bool {
105 self.count == 0
106 }
107
108 fn slot(&self, i: usize) -> Option<*const zval> {
110 if i >= self.count {
111 return None;
112 }
113 let zv = unsafe { self.ex.zend_call_arg(i) }?;
115 Some(unsafe { convert::deref(&raw const *zv) })
117 }
118
119 pub fn value(&self, i: usize) -> Result<Value, NativeError> {
121 let Some(zv) = self.slot(i) else {
122 return Ok(Value::Null);
123 };
124 unsafe { convert::to_value(zv) }.map_err(|why| {
126 NativeError::throw(
127 "TypeError",
128 format!(
129 "{}(): Argument #{} cannot be passed to Rust: {why}",
130 frame(self.ex).0,
131 i + 1
132 ),
133 )
134 })
135 }
136
137 pub fn pass(&self, i: usize) -> Value {
139 match self.slot(i) {
140 Some(zv) => unsafe { convert::pass_through(zv) },
142 None => Value::Null,
143 }
144 }
145
146 pub fn pass_from(&self, i: usize) -> Vec<Value> {
148 (i..self.count).map(|i| self.pass(i)).collect()
149 }
150
151 pub fn items(&self, i: usize) -> Vec<Value> {
154 let Some(zv) = self.slot(i) else {
155 return Vec::new();
156 };
157 unsafe {
159 if u32::from(convert::type_of(zv)) != IS_ARRAY {
160 return Vec::new();
161 }
162 convert::array_values((*zv).value.arr)
163 .into_iter()
164 .map(|slot| convert::pass_through(slot))
165 .collect()
166 }
167 }
168
169 pub fn string_hash(&self, i: usize) -> Option<u64> {
171 self.slot(i)
173 .and_then(|zv| unsafe { convert::string_hash(zv) })
174 }
175
176 pub fn int(&self, i: usize) -> Option<i64> {
178 let zv = self.slot(i)?;
179 unsafe { (u32::from(convert::type_of(zv)) == IS_LONG).then(|| (*zv).value.lval) }
181 }
182
183 pub fn is_false(&self, i: usize) -> bool {
185 self.slot(i)
187 .is_some_and(|zv| unsafe { u32::from(convert::type_of(zv)) == IS_FALSE })
188 }
189
190 pub fn single_object(&self, i: usize) -> Option<Value> {
192 let zv = self.slot(i)?;
193 unsafe {
195 if u32::from(convert::type_of(zv)) != IS_ARRAY {
196 return None;
197 }
198 let ht = (*zv).value.arr;
199 if (*ht).nNumOfElements != 1 {
200 return None;
201 }
202 let first = zend_hash_index_find(ht, 0);
203 if first.is_null() {
204 return None;
205 }
206 let first = convert::deref(first);
207 (u32::from(convert::type_of(first)) == IS_OBJECT).then(|| convert::pass_through(first))
208 }
209 }
210}
211
212extern "C" fn dispatch(ex: &mut ExecuteData, retval: &mut Zval) {
213 boundary::native_entry(ex, retval, dispatch_body);
214}
215
216fn body_of(ex: &ExecuteData) -> Result<Body, String> {
218 let func = ex.func as usize;
219 if let Some(body) = BY_FUNCTION.with(|h| h.borrow().get(&func).cloned()) {
220 return Ok(body);
221 }
222 let (name, _) = frame(ex);
223 let body = HANDLERS
224 .with(|h| h.borrow().get(&name.to_ascii_lowercase()).cloned())
225 .ok_or(name)?;
226 BY_FUNCTION.with(|h| h.borrow_mut().insert(func, body.clone()));
227 Ok(body)
228}
229
230fn dispatch_body(ex: &mut ExecuteData, retval: &mut Zval) {
231 let body = match body_of(ex) {
232 Ok(body) => body,
233 Err(name) => {
234 throw(NativeError::throw(
235 "Error",
236 format!("{name}() has no native handler"),
237 ));
238 return;
239 }
240 };
241 let result = match body {
242 Body::Raw(handler) => {
243 let count = unsafe { ex.This.u2.num_args } as usize;
245 handler(&Args { ex, count })
246 }
247 Body::Converted(handler) => match converted_args(ex) {
248 Ok(args) => handler(&args),
249 Err(err) => Err(err),
250 },
251 };
252 write_result(ex, retval, result);
253}
254
255fn converted_args(ex: &ExecuteData) -> Result<Vec<Value>, NativeError> {
257 let (name, count) = frame(ex);
258 let mut args = Vec::with_capacity(count);
259 for i in 0..count {
260 let Some(zv) = (unsafe { ex.zend_call_arg(i) }) else {
262 args.push(Value::Null);
263 continue;
264 };
265 match unsafe { convert::to_value(convert::deref(&raw const *zv)) } {
267 Ok(value) => args.push(value),
268 Err(why) => {
269 return Err(NativeError::throw(
270 "TypeError",
271 format!(
272 "{name}(): Argument #{} cannot be passed to Rust: {why}",
273 i + 1
274 ),
275 ));
276 }
277 }
278 }
279 Ok(args)
280}
281
282fn write_result(ex: &ExecuteData, retval: &mut Zval, result: Result<Value, NativeError>) {
284 match result {
285 Ok(value) => {
286 let out: *mut zval = retval;
287 if unsafe { convert::write_without_engine(out, &value) } {
289 return;
290 }
291 let written = boundary::guard(|| {
292 unsafe { convert::write_value(out, &value) }
294 });
295 if let Ok(Err(why)) = written {
296 let (name, _) = frame(ex);
297 throw(NativeError::throw(
298 "Error",
299 format!("{name}(): the result cannot be returned to PHP: {why}"),
300 ));
301 }
302 }
303 Err(err) => throw(err),
304 }
305}
306
307fn frame(ex: &ExecuteData) -> (String, usize) {
309 unsafe {
312 let func = ex.func;
313 let mut name = String::new();
314 if !func.is_null() {
315 let fname = (*func).common.function_name;
316 if !fname.is_null() {
317 name = String::from_utf8_lossy(convert::str_bytes(fname)).into_owned();
318 }
319 }
320 (name, ex.This.u2.num_args as usize)
321 }
322}
323
324fn throw(err: NativeError) {
325 let (class, message) = match err {
326 NativeError::Throw { class, message } => (class, message),
327 NativeError::Rethrow(object) => {
328 if let Some(handle) = convert::handle_of(&object) {
329 let copy = unsafe { convert::ZvalHandle::copy_of(handle.as_ptr()) };
331 boundary::rethrow(copy);
332 }
333 return;
334 }
335 NativeError::Silent => return,
336 };
337 if !boundary::can_enter() {
338 return;
339 }
340 let ce = find_class(&class);
341 let message = CString::new(message.replace('\0', "\\0")).unwrap_or_default();
342 let message_ptr = message.as_ptr();
343 let _ = boundary::guard(|| {
344 unsafe { zend_throw_exception(ce, message_ptr, 0) };
346 });
347}
348
349fn find_class(name: &str) -> *mut zend_class_entry {
351 let key = name.trim_start_matches('\\').to_ascii_lowercase();
352 unsafe {
354 let table = (*ext_php_rs_executor_globals()).class_table;
355 let zv = zend_hash_str_find(table, key.as_ptr().cast(), key.len());
356 if zv.is_null() {
357 zend_ce_exception
358 } else {
359 (*zv).value.ce
360 }
361 }
362}