ext-php-rs 0.15.9

Bindings for the Zend API to build PHP extensions natively in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use std::{ffi::CString, ffi::c_void, mem::MaybeUninit, os::raw::c_int, ptr};

use crate::{
    class::RegisteredClass,
    exception::PhpResult,
    ffi::{
        ext_php_rs_executor_globals, instanceof_function_slow, std_object_handlers,
        zend_class_entry, zend_is_true, zend_object_handlers, zend_object_std_dtor,
        zend_objects_clone_members, zend_std_get_properties, zend_std_has_property,
        zend_std_read_property, zend_std_write_property, zend_throw_error,
    },
    flags::{PropertyFlags, ZvalTypeFlags},
    types::{ZendClassObject, ZendHashTable, ZendObject, ZendStr, Zval},
};

/// A set of functions associated with a PHP class.
pub type ZendObjectHandlers = zend_object_handlers;

impl ZendObjectHandlers {
    /// Creates a new set of object handlers based on the standard object
    /// handlers.
    #[must_use]
    pub fn new<T: RegisteredClass>() -> ZendObjectHandlers {
        let mut this = MaybeUninit::uninit();

        // SAFETY: `this` is allocated on the stack and is a valid memory location.
        unsafe { Self::init::<T>(&raw mut *this.as_mut_ptr()) };

        // SAFETY: We just initialized the handlers in the previous statement, therefore
        // we are returning a valid object.
        unsafe { this.assume_init() }
    }

    /// Initializes a given set of object handlers by copying the standard
    /// object handlers into the memory location, as well as setting up the
    /// `T` type destructor.
    ///
    /// # Parameters
    ///
    /// * `ptr` - Pointer to memory location to copy the standard handlers to.
    ///
    /// # Safety
    ///
    /// Caller must guarantee that the `ptr` given is a valid memory location.
    ///
    /// # Panics
    ///
    /// * If the offset of the `T` type is not a valid `i32` value.
    pub unsafe fn init<T: RegisteredClass>(ptr: *mut ZendObjectHandlers) {
        unsafe { ptr::copy_nonoverlapping(&raw const std_object_handlers, ptr, 1) };
        let offset = ZendClassObject::<T>::std_offset();
        unsafe { (*ptr).offset = offset.try_into().expect("Invalid offset") };
        unsafe { (*ptr).free_obj = Some(Self::free_obj::<T>) };
        unsafe { (*ptr).clone_obj = Some(Self::clone_obj::<T>) };
        unsafe { (*ptr).read_property = Some(Self::read_property::<T>) };
        unsafe { (*ptr).write_property = Some(Self::write_property::<T>) };
        unsafe { (*ptr).get_properties = Some(Self::get_properties::<T>) };
        unsafe { (*ptr).has_property = Some(Self::has_property::<T>) };
    }

    unsafe extern "C" fn free_obj<T: RegisteredClass>(object: *mut ZendObject) {
        // Try to get the ZendClassObject. This may return None for:
        // - PHP subclasses/mocks that didn't call the parent constructor
        // - Objects where the Rust side was never initialized
        if let Some(obj) = unsafe {
            object
                .as_mut()
                .and_then(|obj| ZendClassObject::<T>::from_zend_obj_mut(obj))
        } {
            // Manually drop the object as we don't want to free the underlying memory.
            unsafe { ptr::drop_in_place(&raw mut obj.obj) };
        }

        // Always call the standard destructor to clean up the PHP object
        unsafe { zend_object_std_dtor(object) };
    }

    unsafe extern "C" fn clone_obj<T: RegisteredClass>(object: *mut ZendObject) -> *mut ZendObject {
        // PHP will call OBJ_RELEASE on the returned pointer if an exception
        // is thrown, so we must NEVER return the original object. Always
        // allocate a new (possibly uninitialized) object for error paths.
        let cloned_val = unsafe {
            object
                .as_ref()
                .and_then(|obj| ZendClassObject::<T>::from_zend_obj(obj))
                .and_then(|old| old.obj.as_ref())
                .and_then(RegisteredClass::clone_obj)
        };

        if let Some(val) = cloned_val {
            let mut new = ZendClassObject::<T>::new(val);
            unsafe { zend_objects_clone_members(&raw mut new.std, object) };
            let raw = new.into_raw();
            &raw mut raw.std
        } else {
            let msg = CString::new(format!(
                "Trying to clone an uncloneable object of class {}",
                T::CLASS_NAME
            ))
            .expect("Failed to create error message");
            unsafe { zend_throw_error(ptr::null_mut(), msg.as_ptr()) };
            // Return a new uninitialized object that PHP can safely release.
            // free_obj handles uninitialized (None) objects gracefully.
            let empty = unsafe { ZendClassObject::<T>::new_uninit(None) };
            let raw = empty.into_raw();
            &raw mut raw.std
        }
    }

    #[allow(clippy::items_after_statements)]
    unsafe extern "C" fn read_property<T: RegisteredClass>(
        object: *mut ZendObject,
        member: *mut ZendStr,
        type_: c_int,
        cache_slot: *mut *mut c_void,
        rv: *mut Zval,
    ) -> *mut Zval {
        // If the object doesn't have a valid Rust backing (e.g., a mock or subclass
        // that didn't call the parent constructor), fall back to standard PHP handling
        let Some(obj) = (unsafe {
            object
                .as_mut()
                .and_then(|obj| ZendClassObject::<T>::from_zend_obj_mut(obj))
        }) else {
            return unsafe { zend_std_read_property(object, member, type_, cache_slot, rv) };
        };

        #[allow(clippy::inline_always)]
        #[inline(always)]
        unsafe fn internal<T: RegisteredClass>(
            object: *mut ZendObject,
            obj: &mut ZendClassObject<T>,
            member: *mut ZendStr,
            type_: c_int,
            cache_slot: *mut *mut c_void,
            rv: *mut Zval,
        ) -> PhpResult<*mut Zval> {
            let prop_name = unsafe {
                member
                    .as_ref()
                    .ok_or("Invalid property name pointer given")?
            };
            let self_ = &mut *obj;
            let props = T::get_metadata().get_properties();
            let prop = props.get(prop_name.as_str()?);

            // retval needs to be treated as initialized, so we set the type to null
            let rv_mut = unsafe { rv.as_mut().ok_or("Invalid return zval given")? };
            rv_mut.u1.type_info = ZvalTypeFlags::Null.bits();

            Ok(match prop {
                Some(prop_info) => {
                    // Check visibility before allowing access
                    let object_ce = unsafe { (*object).ce };
                    if !unsafe { check_property_access(prop_info.flags, object_ce) } {
                        let is_private = prop_info.flags.contains(PropertyFlags::Private);
                        unsafe {
                            throw_property_access_error(
                                T::CLASS_NAME,
                                prop_name.as_str()?,
                                is_private,
                            );
                        }
                        return Ok(rv);
                    }
                    prop_info.prop.get(self_, rv_mut)?;
                    rv
                }
                None => unsafe { zend_std_read_property(object, member, type_, cache_slot, rv) },
            })
        }

        match unsafe { internal::<T>(object, obj, member, type_, cache_slot, rv) } {
            Ok(rv) => rv,
            Err(e) => {
                let _ = e.throw();
                unsafe { (*rv).set_null() };
                rv
            }
        }
    }

    #[allow(clippy::items_after_statements)]
    unsafe extern "C" fn write_property<T: RegisteredClass>(
        object: *mut ZendObject,
        member: *mut ZendStr,
        value: *mut Zval,
        cache_slot: *mut *mut c_void,
    ) -> *mut Zval {
        // If the object doesn't have a valid Rust backing (e.g., a mock or subclass
        // that didn't call the parent constructor), fall back to standard PHP handling
        let Some(obj) = (unsafe {
            object
                .as_mut()
                .and_then(|obj| ZendClassObject::<T>::from_zend_obj_mut(obj))
        }) else {
            return unsafe { zend_std_write_property(object, member, value, cache_slot) };
        };

        #[allow(clippy::inline_always)]
        #[inline(always)]
        unsafe fn internal<T: RegisteredClass>(
            object: *mut ZendObject,
            obj: &mut ZendClassObject<T>,
            member: *mut ZendStr,
            value: *mut Zval,
            cache_slot: *mut *mut c_void,
        ) -> PhpResult<*mut Zval> {
            let prop_name = unsafe {
                member
                    .as_ref()
                    .ok_or("Invalid property name pointer given")?
            };
            let self_ = &mut *obj;
            let props = T::get_metadata().get_properties();
            let prop = props.get(prop_name.as_str()?);
            let value_mut = unsafe { value.as_mut().ok_or("Invalid return zval given")? };

            Ok(match prop {
                Some(prop_info) => {
                    // Check visibility before allowing access
                    let object_ce = unsafe { (*object).ce };
                    if !unsafe { check_property_access(prop_info.flags, object_ce) } {
                        let is_private = prop_info.flags.contains(PropertyFlags::Private);
                        unsafe {
                            throw_property_access_error(
                                T::CLASS_NAME,
                                prop_name.as_str()?,
                                is_private,
                            );
                        }
                        return Ok(value);
                    }
                    prop_info.prop.set(self_, value_mut)?;
                    value
                }
                None => unsafe { zend_std_write_property(object, member, value, cache_slot) },
            })
        }

        match unsafe { internal::<T>(object, obj, member, value, cache_slot) } {
            Ok(rv) => rv,
            Err(e) => {
                let _ = e.throw();
                value
            }
        }
    }

    #[allow(clippy::items_after_statements)]
    unsafe extern "C" fn get_properties<T: RegisteredClass>(
        object: *mut ZendObject,
    ) -> *mut ZendHashTable {
        // Get the standard properties first (this works for all objects)
        let props = unsafe {
            zend_std_get_properties(object)
                .as_mut()
                .or_else(|| Some(ZendHashTable::new().into_raw()))
                .expect("Failed to get property hashtable")
        };

        // If the object doesn't have a valid Rust backing (e.g., a mock or subclass
        // that didn't call the parent constructor), just return standard properties
        let Some(obj) = (unsafe {
            object
                .as_mut()
                .and_then(|obj| ZendClassObject::<T>::from_zend_obj_mut(obj))
        }) else {
            return props;
        };

        #[allow(clippy::inline_always)]
        #[inline(always)]
        unsafe fn internal<T: RegisteredClass>(
            obj: &mut ZendClassObject<T>,
            props: &mut ZendHashTable,
        ) -> PhpResult {
            let self_ = &mut *obj;
            let struct_props = T::get_metadata().get_properties();

            for (&name, val) in struct_props {
                let mut zv = Zval::new();
                if val.prop.get(self_, &mut zv).is_err() {
                    continue;
                }

                // Mangle property name according to visibility for debug output
                // PHP convention: private = "\0ClassName\0propName", protected =
                // "\0*\0propName"
                let mangled_name = if val.flags.contains(PropertyFlags::Private) {
                    format!("\0{}\0{name}", T::CLASS_NAME)
                } else if val.flags.contains(PropertyFlags::Protected) {
                    format!("\0*\0{name}")
                } else {
                    name.to_string()
                };

                props.insert(mangled_name.as_str(), zv).map_err(|e| {
                    format!("Failed to insert value into properties hashtable: {e:?}")
                })?;
            }

            Ok(())
        }

        if let Err(e) = unsafe { internal::<T>(obj, props) } {
            let _ = e.throw();
        }

        props
    }

    #[allow(clippy::items_after_statements)]
    unsafe extern "C" fn has_property<T: RegisteredClass>(
        object: *mut ZendObject,
        member: *mut ZendStr,
        has_set_exists: c_int,
        cache_slot: *mut *mut c_void,
    ) -> c_int {
        // If the object doesn't have a valid Rust backing (e.g., a mock or subclass
        // that didn't call the parent constructor), fall back to standard PHP handling
        let Some(obj) = (unsafe {
            object
                .as_mut()
                .and_then(|obj| ZendClassObject::<T>::from_zend_obj_mut(obj))
        }) else {
            return unsafe { zend_std_has_property(object, member, has_set_exists, cache_slot) };
        };

        #[allow(clippy::inline_always)]
        #[inline(always)]
        unsafe fn internal<T: RegisteredClass>(
            object: *mut ZendObject,
            obj: &mut ZendClassObject<T>,
            member: *mut ZendStr,
            has_set_exists: c_int,
            cache_slot: *mut *mut c_void,
        ) -> PhpResult<c_int> {
            let prop_name = unsafe {
                member
                    .as_ref()
                    .ok_or("Invalid property name pointer given")?
            };
            let props = T::get_metadata().get_properties();
            let prop = props.get(prop_name.as_str()?);
            let self_ = &mut *obj;

            match has_set_exists {
                //
                // * 0 (has) whether property exists and is not NULL
                0 => {
                    if let Some(val) = prop {
                        let mut zv = Zval::new();
                        val.prop.get(self_, &mut zv)?;
                        if !zv.is_null() {
                            return Ok(1);
                        }
                    }
                }
                //
                // * 1 (set) whether property exists and is true
                1 => {
                    if let Some(val) = prop {
                        let mut zv = Zval::new();
                        val.prop.get(self_, &mut zv)?;

                        cfg_if::cfg_if! {
                            if #[cfg(php84)] {
                                #[allow(clippy::unnecessary_mut_passed)]
                                if unsafe { zend_is_true(&raw mut zv) } {
                                    return Ok(1);
                                }
                            } else {
                                #[allow(clippy::unnecessary_mut_passed)]
                                if unsafe { zend_is_true(&raw mut zv) } == 1 {
                                    return Ok(1);
                                }
                            }
                        }
                    }
                }
                //
                // * 2 (exists) whether property exists
                2 => {
                    if prop.is_some() {
                        return Ok(1);
                    }
                }
                _ => return Err(
                    "Invalid value given for `has_set_exists` in struct `has_property` function."
                        .into(),
                ),
            }

            Ok(unsafe { zend_std_has_property(object, member, has_set_exists, cache_slot) })
        }

        match unsafe { internal::<T>(object, obj, member, has_set_exists, cache_slot) } {
            Ok(rv) => rv,
            Err(e) => {
                let _ = e.throw();
                0
            }
        }
    }
}

/// Gets the current calling scope from the executor globals.
///
/// # Safety
///
/// Must only be called during PHP execution when executor globals are valid.
#[inline]
unsafe fn get_calling_scope() -> *const zend_class_entry {
    let eg = unsafe { ext_php_rs_executor_globals().as_ref() };
    let Some(eg) = eg else {
        return ptr::null();
    };
    let execute_data = eg.current_execute_data;

    if execute_data.is_null() {
        return ptr::null();
    }

    let func = unsafe { (*execute_data).func };
    if func.is_null() {
        return ptr::null();
    }

    // Access the common.scope field through the union
    unsafe { (*func).common.scope }
}

/// Checks if the calling scope has access to a property with the given flags.
///
/// Returns `true` if access is allowed, `false` otherwise.
///
/// # Safety
///
/// Must only be called during PHP execution when executor globals are valid.
/// The `object_ce` pointer must be valid.
#[inline]
unsafe fn check_property_access(flags: PropertyFlags, object_ce: *const zend_class_entry) -> bool {
    // Public properties are always accessible
    if !flags.contains(PropertyFlags::Private) && !flags.contains(PropertyFlags::Protected) {
        return true;
    }

    let calling_scope = unsafe { get_calling_scope() };

    if flags.contains(PropertyFlags::Private) {
        // Private: must be called from the exact same class
        return calling_scope == object_ce;
    }

    if flags.contains(PropertyFlags::Protected) {
        // Protected: must be called from same class or a subclass
        if calling_scope.is_null() {
            return false;
        }

        // Same class check
        if calling_scope == object_ce {
            return true;
        }

        // Check if calling_scope is a subclass of object_ce
        // or if object_ce is a subclass of calling_scope (for parent access)
        unsafe {
            instanceof_function_slow(calling_scope, object_ce)
                || instanceof_function_slow(object_ce, calling_scope)
        }
    } else {
        true
    }
}

/// Throws an error for invalid property access.
///
/// # Safety
///
/// Must only be called during PHP execution.
///
/// # Panics
///
/// Panics if the error message cannot be converted to a `CString`.
unsafe fn throw_property_access_error(class_name: &str, prop_name: &str, is_private: bool) {
    let visibility = if is_private { "private" } else { "protected" };
    let message = CString::new(format!(
        "Cannot access {visibility} property {class_name}::${prop_name}"
    ))
    .expect("Failed to create error message");

    unsafe {
        zend_throw_error(ptr::null_mut(), message.as_ptr());
    }
}