1use std::cell::Cell;
18use std::mem::{ManuallyDrop, MaybeUninit};
19use std::ptr;
20
21use ext_php_rs::ffi::{
22 IS_ARRAY, IS_OBJECT, IS_STRING, ZEND_ACC_CALL_VIA_TRAMPOLINE, ZEND_RESULT_CODE_SUCCESS,
23 ext_php_rs_executor_globals, zend_array, zend_execute_data, zend_fcall_info,
24 zend_fcall_info_cache, zend_hash_index_find, zend_is_callable_ex, zval,
25};
26use ext_php_rs::types::Zval;
27use speedyspec_hooks::{Key, Value};
28
29use crate::boundary::{
30 self, CallError, ENGINE, discard_exception, drain, guard, release_later, settle_stray,
31 take_thrown,
32};
33use crate::convert::{self, Unconvertible};
34use crate::runtime::{CallFailure, PhpError, failure_of};
35
36unsafe extern "C" {
38 fn zend_call_function(fci: *mut zend_fcall_info, fcc: *mut zend_fcall_info_cache) -> i32;
39 fn zend_release_fcall_info_cache(fcc: *mut zend_fcall_info_cache);
40}
41
42const SUPPRESS_DEPRECATIONS: u32 = 1 << 1;
44
45thread_local! {
46 static GENERATION: Cell<u64> = const { Cell::new(0) };
48}
49
50pub(crate) fn new_request() {
52 GENERATION.with(|g| g.set(g.get().wrapping_add(1)));
53}
54
55fn generation() -> u64 {
56 GENERATION.with(Cell::get)
57}
58
59#[derive(Clone, Copy)]
60enum Cached {
61 Unknown,
63 Resolved {
64 generation: u64,
65 fcc: zend_fcall_info_cache,
66 },
67 Uncacheable { generation: u64 },
69}
70
71pub struct Callable {
73 value: Value,
74 cache: Cell<Cached>,
75 shape_ok: bool,
77}
78
79impl Callable {
80 pub fn new(value: Value) -> Callable {
83 let shape_ok = cacheable_shape(&value);
84 Callable {
85 value,
86 cache: Cell::new(Cached::Unknown),
87 shape_ok,
88 }
89 }
90
91 pub fn value(&self) -> &Value {
92 &self.value
93 }
94
95 pub fn call(&self, args: &[Value]) -> Result<Value, CallFailure> {
97 let plain = |error: PhpError| CallFailure {
98 error,
99 exception: None,
100 };
101 if !boundary::alive() {
102 return Err(plain(PhpError::Boot("no PHP request is open".to_owned())));
103 }
104 let now = generation();
105 let fallback = !self.shape_ok
106 || matches!(self.cache.get(), Cached::Uncacheable { generation } if generation == now);
107 if !fallback {
108 match self.call_fast(args, now) {
109 Fast::Called(result) => return result.map_err(failure_of),
110 Fast::Unresolved => {}
111 }
112 }
113 self.call_user_func(args)
114 }
115
116 fn call_user_func(&self, args: &[Value]) -> Result<Value, CallFailure> {
118 if args.is_empty() {
119 return crate::call_catching(
120 &Value::Str("call_user_func".into()),
121 std::slice::from_ref(&self.value),
122 );
123 }
124 let list = args
125 .iter()
126 .enumerate()
127 .map(|(i, v)| (Key::Int(i as i64), v.clone()))
128 .collect();
129 crate::call_catching(
130 &Value::Str("call_user_func_array".into()),
131 &[self.value.clone(), Value::Array(list)],
132 )
133 }
134
135 fn call_fast(&self, args: &[Value], now: u64) -> Fast {
136 settle_stray();
137 let handle = convert::handle_of(&self.value);
138 let mut written = ManuallyDrop::new(Zval::new());
140 let written_ptr: *mut zval = &raw mut *written;
141 let callable_ptr: *mut zval = match handle {
142 Some(handle) => handle.as_ptr().cast_mut(),
143 None => written_ptr,
144 };
145 let needs_write = handle.is_none();
146 let value = &self.value;
147
148 let mut params: Vec<ManuallyDrop<Zval>> = args
149 .iter()
150 .map(|_| ManuallyDrop::new(Zval::new()))
151 .collect();
152 let params_ptr: *mut zval = params.as_mut_ptr().cast();
153 let count = u32::try_from(params.len()).unwrap_or(u32::MAX);
154 let mut retval = ManuallyDrop::new(Zval::new());
155 let retval_ptr: *mut zval = &raw mut *retval;
156 let dummy_func = ENGINE.with(|e| e.dummy_func.get());
157 let cache = &self.cache;
158
159 let called = guard(|| -> Result<Option<bool>, Unconvertible> {
160 unsafe {
164 if needs_write {
165 convert::write_value(written_ptr, value)?;
166 }
167 for (i, arg) in args.iter().enumerate() {
168 convert::write_value(params_ptr.add(i), arg)?;
169 }
170 let eg = ext_php_rs_executor_globals();
171 let mut dummy = MaybeUninit::<zend_execute_data>::zeroed();
172 let installed = (*eg).current_execute_data.is_null();
173 if installed {
174 (*dummy.as_mut_ptr()).func = dummy_func;
175 (*eg).current_execute_data = dummy.as_mut_ptr();
176 }
177 let mut fcc = match cache.get() {
178 Cached::Resolved { generation, fcc } if generation == now => Some(fcc),
179 _ => resolve(callable_ptr, cache, now),
180 };
181 let result = fcc.as_mut().map(|fcc| {
182 let mut fci = zend_fcall_info {
183 size: std::mem::size_of::<zend_fcall_info>(),
184 function_name: Zval::new(),
187 retval: retval_ptr,
188 params: params_ptr,
189 object: fcc.object,
190 param_count: count,
191 named_params: ptr::null_mut(),
192 };
193 zend_call_function(&raw mut fci, fcc) == ZEND_RESULT_CODE_SUCCESS
194 });
195 if installed {
196 (*eg).current_execute_data = ptr::null_mut();
197 }
198 Ok(result)
199 }
200 });
201
202 if needs_write {
203 release_later(written);
204 }
205 for param in params {
206 release_later(param);
207 }
208 let outcome = match called {
209 Ok(Ok(Some(_))) => {
210 Some(unsafe { convert::pass_through_owned(retval) })
212 }
213 _ => {
214 release_later(retval);
215 None
216 }
217 };
218 let clear_before = matches!(called, Ok(Ok(Some(true))))
220 && unsafe { (*ext_php_rs_executor_globals()).exception.is_null() };
221 drain();
222 if clear_before {
223 settle_stray();
224 }
225 match called {
226 Err(interrupted) => {
227 discard_exception();
228 Fast::Called(Err(CallError::Interrupted(interrupted)))
229 }
230 Ok(Err(why)) => Fast::Called(Err(CallError::Convert(why.to_string()))),
231 Ok(Ok(None)) => {
232 discard_exception();
235 Fast::Unresolved
236 }
237 Ok(Ok(Some(true))) => match take_thrown() {
238 Some(thrown) => Fast::Called(Err(CallError::Thrown(thrown))),
239 None => Fast::Called(Ok(outcome.unwrap_or(Value::Null))),
240 },
241 Ok(Ok(Some(false))) => match take_thrown() {
242 Some(thrown) => Fast::Called(Err(CallError::Thrown(thrown))),
243 None => Fast::Called(Err(CallError::Convert(
244 "PHP refused the call (the executor is inactive)".to_owned(),
245 ))),
246 },
247 }
248 }
249}
250
251enum Fast {
252 Called(Result<Value, CallError>),
253 Unresolved,
255}
256
257unsafe fn resolve(
264 callable: *mut zval,
265 cache: &Cell<Cached>,
266 now: u64,
267) -> Option<zend_fcall_info_cache> {
268 unsafe {
270 let mut fcc = MaybeUninit::<zend_fcall_info_cache>::zeroed().assume_init();
271 let ok = zend_is_callable_ex(
272 callable,
273 ptr::null_mut(),
274 SUPPRESS_DEPRECATIONS,
275 ptr::null_mut(),
276 &raw mut fcc,
277 ptr::null_mut(),
278 );
279 if !ok || fcc.function_handler.is_null() {
280 return None;
282 }
283 let flags = (*fcc.function_handler).common.fn_flags;
284 if flags & ZEND_ACC_CALL_VIA_TRAMPOLINE != 0 {
285 zend_release_fcall_info_cache(&raw mut fcc);
286 cache.set(Cached::Uncacheable { generation: now });
287 return None;
288 }
289 cache.set(Cached::Resolved {
290 generation: now,
291 fcc,
292 });
293 Some(fcc)
294 }
295}
296
297fn cacheable_shape(value: &Value) -> bool {
301 fn plain_class(class: &[u8]) -> bool {
302 !class.is_empty()
303 && !["self", "parent", "static"]
304 .iter()
305 .any(|kw| class.eq_ignore_ascii_case(kw.as_bytes()))
306 }
307 fn plain_name(name: &[u8]) -> bool {
308 match name.windows(2).position(|w| w == b"::") {
309 None => !name.is_empty(),
310 Some(at) => {
311 let (class, method) = (&name[..at], &name[at + 2..]);
312 plain_class(class) && !method.is_empty() && !method.windows(2).any(|w| w == b"::")
313 }
314 }
315 }
316 fn method_ok(method: &[u8]) -> bool {
317 !method.is_empty() && !method.windows(2).any(|w| w == b"::")
318 }
319 match value {
320 Value::Str(name) => plain_name(name.as_bytes()),
321 Value::Bytes(name) => plain_name(name),
322 Value::Array(entries) => {
323 let at = |i: i64| {
324 entries
325 .iter()
326 .find(|(k, _)| *k == Key::Int(i))
327 .map(|(_, v)| v)
328 };
329 entries.len() == 2
330 && match (at(0), at(1)) {
331 (Some(Value::Str(class)), Some(Value::Str(method))) => {
332 plain_class(class.as_bytes()) && method_ok(method.as_bytes())
333 }
334 (Some(Value::Opaque(_)), Some(Value::Str(method))) => {
335 method_ok(method.as_bytes())
336 }
337 _ => false,
338 }
339 }
340 Value::Opaque(_) => match convert::handle_of(value) {
341 Some(handle) => unsafe { zval_shape_ok(handle.as_ptr()) },
343 None => false,
344 },
345 _ => false,
346 }
347}
348
349unsafe fn zval_shape_ok(zv: *const zval) -> bool {
355 unsafe {
357 match u32::from(convert::type_of(zv)) {
358 IS_OBJECT => true,
359 IS_STRING | IS_ARRAY => match convert::to_value(zv) {
360 Ok(value @ (Value::Str(_) | Value::Bytes(_))) => cacheable_shape(&value),
361 Ok(Value::Array(_)) => {
362 let ht: *const zend_array = (*zv).value.arr;
363 if (*ht).nNumOfElements != 2 {
364 return false;
365 }
366 let (target, method) =
367 (zend_hash_index_find(ht, 0), zend_hash_index_find(ht, 1));
368 if target.is_null() || method.is_null() {
369 return false;
370 }
371 let (target, method) = (convert::deref(target), convert::deref(method));
372 let method = match convert::to_value(method) {
373 Ok(Value::Str(method)) => method,
374 _ => return false,
375 };
376 match u32::from(convert::type_of(target)) {
377 IS_OBJECT => !method.is_empty() && !method.contains("::"),
378 IS_STRING => match convert::to_value(target) {
379 Ok(class @ Value::Str(_)) => cacheable_shape(&Value::Array(vec![
380 (Key::Int(0), class),
381 (Key::Int(1), Value::Str(method)),
382 ])),
383 _ => false,
384 },
385 _ => false,
386 }
387 }
388 _ => false,
389 },
390 _ => false,
391 }
392 }
393}