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> {
155 let Some(zv) = self.slot(i) else {
156 return Vec::new();
157 };
158 unsafe {
160 if u32::from(convert::type_of(zv)) != IS_ARRAY {
161 return Vec::new();
162 }
163 convert::array_values((*zv).value.arr)
164 .into_iter()
165 .map(|slot| convert::pass_through_slot(slot))
166 .collect()
167 }
168 }
169
170 pub fn string_hash(&self, i: usize) -> Option<u64> {
172 self.slot(i)
174 .and_then(|zv| unsafe { convert::string_hash(zv) })
175 }
176
177 pub fn int(&self, i: usize) -> Option<i64> {
179 let zv = self.slot(i)?;
180 unsafe { (u32::from(convert::type_of(zv)) == IS_LONG).then(|| (*zv).value.lval) }
182 }
183
184 pub fn is_false(&self, i: usize) -> bool {
186 self.slot(i)
188 .is_some_and(|zv| unsafe { u32::from(convert::type_of(zv)) == IS_FALSE })
189 }
190
191 pub fn single_object(&self, i: usize) -> Option<Value> {
193 let zv = self.slot(i)?;
194 unsafe {
196 if u32::from(convert::type_of(zv)) != IS_ARRAY {
197 return None;
198 }
199 let ht = (*zv).value.arr;
200 if (*ht).nNumOfElements != 1 {
201 return None;
202 }
203 let first = zend_hash_index_find(ht, 0);
204 if first.is_null() {
205 return None;
206 }
207 let first = convert::deref(first);
208 (u32::from(convert::type_of(first)) == IS_OBJECT).then(|| convert::pass_through(first))
209 }
210 }
211}
212
213extern "C" fn dispatch(ex: &mut ExecuteData, retval: &mut Zval) {
214 boundary::native_entry(ex, retval, dispatch_body);
215}
216
217fn body_of(ex: &ExecuteData) -> Result<Body, String> {
219 let func = ex.func as usize;
220 if let Some(body) = BY_FUNCTION.with(|h| h.borrow().get(&func).cloned()) {
221 return Ok(body);
222 }
223 let (name, _) = frame(ex);
224 let body = HANDLERS
225 .with(|h| h.borrow().get(&name.to_ascii_lowercase()).cloned())
226 .ok_or(name)?;
227 BY_FUNCTION.with(|h| h.borrow_mut().insert(func, body.clone()));
228 Ok(body)
229}
230
231fn dispatch_body(ex: &mut ExecuteData, retval: &mut Zval) {
232 let body = match body_of(ex) {
233 Ok(body) => body,
234 Err(name) => {
235 throw(NativeError::throw(
236 "Error",
237 format!("{name}() has no native handler"),
238 ));
239 return;
240 }
241 };
242 let result = match body {
243 Body::Raw(handler) => {
244 let count = unsafe { ex.This.u2.num_args } as usize;
246 handler(&Args { ex, count })
247 }
248 Body::Converted(handler) => match converted_args(ex) {
249 Ok(args) => handler(&args),
250 Err(err) => Err(err),
251 },
252 };
253 write_result(ex, retval, result);
254}
255
256fn converted_args(ex: &ExecuteData) -> Result<Vec<Value>, NativeError> {
258 let (name, count) = frame(ex);
259 let mut args = Vec::with_capacity(count);
260 for i in 0..count {
261 let Some(zv) = (unsafe { ex.zend_call_arg(i) }) else {
263 args.push(Value::Null);
264 continue;
265 };
266 match unsafe { convert::to_value(convert::deref(&raw const *zv)) } {
268 Ok(value) => args.push(value),
269 Err(why) => {
270 return Err(NativeError::throw(
271 "TypeError",
272 format!(
273 "{name}(): Argument #{} cannot be passed to Rust: {why}",
274 i + 1
275 ),
276 ));
277 }
278 }
279 }
280 Ok(args)
281}
282
283fn write_result(ex: &ExecuteData, retval: &mut Zval, result: Result<Value, NativeError>) {
285 match result {
286 Ok(value) => {
287 let out: *mut zval = retval;
288 if unsafe { convert::write_without_engine(out, &value) } {
290 return;
291 }
292 let written = boundary::guard(|| {
293 unsafe { convert::write_value(out, &value) }
295 });
296 if let Ok(Err(why)) = written {
297 let (name, _) = frame(ex);
298 throw(NativeError::throw(
299 "Error",
300 format!("{name}(): the result cannot be returned to PHP: {why}"),
301 ));
302 }
303 }
304 Err(err) => throw(err),
305 }
306}
307
308fn frame(ex: &ExecuteData) -> (String, usize) {
310 unsafe {
313 let func = ex.func;
314 let mut name = String::new();
315 if !func.is_null() {
316 let fname = (*func).common.function_name;
317 if !fname.is_null() {
318 name = String::from_utf8_lossy(convert::str_bytes(fname)).into_owned();
319 }
320 }
321 (name, ex.This.u2.num_args as usize)
322 }
323}
324
325fn throw(err: NativeError) {
326 let (class, message) = match err {
327 NativeError::Throw { class, message } => (class, message),
328 NativeError::Rethrow(object) => {
329 if let Some(handle) = convert::handle_of(&object) {
330 let copy = unsafe { convert::ZvalHandle::copy_of(handle.as_ptr()) };
332 boundary::rethrow(copy);
333 }
334 return;
335 }
336 NativeError::Silent => return,
337 };
338 if !boundary::can_enter() {
339 return;
340 }
341 let ce = find_class(&class);
342 let message = CString::new(message.replace('\0', "\\0")).unwrap_or_default();
343 let message_ptr = message.as_ptr();
344 let _ = boundary::guard(|| {
345 unsafe { zend_throw_exception(ce, message_ptr, 0) };
347 });
348}
349
350fn find_class(name: &str) -> *mut zend_class_entry {
352 let key = name.trim_start_matches('\\').to_ascii_lowercase();
353 unsafe {
355 let table = (*ext_php_rs_executor_globals()).class_table;
356 let zv = zend_hash_str_find(table, key.as_ptr().cast(), key.len());
357 if zv.is_null() {
358 zend_ce_exception
359 } else {
360 (*zv).value.ce
361 }
362 }
363}