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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! Represents an object in PHP. Allows for overriding the internal object used by classes,
//! allowing users to store Rust data inside a PHP object.
use std::{
alloc::Layout,
convert::TryInto,
fmt::Debug,
marker::PhantomData,
mem::{self, MaybeUninit},
ops::{Deref, DerefMut},
ptr,
sync::atomic::{AtomicBool, AtomicPtr, Ordering},
};
use crate::{
bindings::{
ext_php_rs_zend_object_alloc, ext_php_rs_zend_object_release, object_properties_init,
std_object_handlers, zend_object, zend_object_handlers, zend_object_std_init,
zend_objects_clone_members, ZEND_ISEMPTY, ZEND_PROPERTY_EXISTS, ZEND_PROPERTY_ISSET,
},
errors::{Error, Result},
php::{class::ClassEntry, enums::DataType, types::string::ZendString},
};
use super::{
array::ZendHashTable,
zval::{FromZval, IntoZval, Zval},
};
pub type ZendObject = zend_object;
pub type ZendObjectHandlers = zend_object_handlers;
/// Different ways to query if a property exists.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(u32)]
pub enum PropertyQuery {
/// Property exists and is not NULL.
Isset = ZEND_PROPERTY_ISSET,
/// Property is not empty.
NotEmpty = ZEND_ISEMPTY,
/// Property exists.
Exists = ZEND_PROPERTY_EXISTS,
}
impl ZendObject {
/// Attempts to retrieve the class name of the object.
pub fn get_class_name(&self) -> Result<String> {
let name = unsafe {
ZendString::from_ptr(
self.handlers()?.get_class_name.ok_or(Error::InvalidScope)?(self),
false,
)
}?;
name.try_into()
}
/// Checks if the given object is an instance of a registered class with Rust
/// type `T`.
pub fn is_instance<T: RegisteredClass>(&self) -> bool {
(self.ce as *const ClassEntry).eq(&(T::get_metadata().ce() as *const _))
}
/// Attempts to read a property from the Object. Returns a result returning an
/// immutable reference to the [`Zval`] if the property exists and can be read,
/// and an [`Error`] otherwise.
///
/// # Parameters
///
/// * `name` - The name of the property.
/// * `query` - The type of query to use when attempting to get a property.
pub fn get_property(&self, name: &str) -> Result<&Zval> {
if !self.has_property(name, PropertyQuery::Exists)? {
return Err(Error::InvalidProperty);
}
let name = ZendString::new(name, false)?;
let mut rv = Zval::new();
unsafe {
self.handlers()?.read_property.ok_or(Error::InvalidScope)?(
self.mut_ptr(),
name.borrow_ptr(),
1,
std::ptr::null_mut(),
&mut rv,
)
.as_ref()
}
.ok_or(Error::InvalidScope)
}
/// Attempts to set a property on the object, returning an immutable reference to
/// the [`Zval`] if the property can be set.
///
/// # Parameters
///
/// * `name` - The name of the property.
/// * `value` - The value to set the property to.
pub fn set_property(&mut self, name: &str, value: impl IntoZval) -> Result<&Zval> {
let name = ZendString::new(name, false)?;
let mut value = value.into_zval(false)?;
unsafe {
self.handlers()?.write_property.ok_or(Error::InvalidScope)?(
self,
name.borrow_ptr(),
&mut value,
std::ptr::null_mut(),
)
.as_ref()
}
.ok_or(Error::InvalidScope)
}
/// Checks if a property exists on an object. Takes a property name and query parameter,
/// which defines what classifies if a property exists or not. See [`PropertyQuery`] for
/// more information.
///
/// # Parameters
///
/// * `name` - The name of the property.
/// * `query` - The 'query' to classify if a property exists.
pub fn has_property(&self, name: &str, query: PropertyQuery) -> Result<bool> {
let name = ZendString::new(name, false)?;
Ok(unsafe {
self.handlers()?.has_property.ok_or(Error::InvalidScope)?(
self.mut_ptr(),
name.borrow_ptr(),
query as _,
std::ptr::null_mut(),
)
} > 0)
}
/// Attempts to retrieve the properties of the object. Returned inside a Zend Hashtable.
pub fn get_properties(&self) -> Result<ZendHashTable> {
unsafe {
ZendHashTable::from_ptr(
self.handlers()?.get_properties.ok_or(Error::InvalidScope)?(self.mut_ptr()),
false,
)
}
}
/// Attempts to retrieve a reference to the object handlers.
#[inline]
unsafe fn handlers(&self) -> Result<&ZendObjectHandlers> {
self.handlers.as_ref().ok_or(Error::InvalidScope)
}
/// Returns a mutable pointer to `self`, regardless of the type of reference.
/// Only to be used in situations where a C function requires a mutable pointer
/// but does not modify the underlying data.
#[inline]
fn mut_ptr(&self) -> *mut Self {
(self as *const Self) as *mut Self
}
/// Increments the objects reference counter by 1.
pub(crate) fn refcount_inc(&mut self) {
self.gc.refcount += 1;
}
}
impl Debug for ZendObject {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut dbg = f.debug_struct(
self.get_class_name()
.unwrap_or_else(|_| "ZendObject".to_string())
.as_str(),
);
if let Ok(props) = self.get_properties() {
for (id, key, val) in props.into_iter() {
dbg.field(key.unwrap_or_else(|| id.to_string()).as_str(), val);
}
}
dbg.finish()
}
}
pub struct ClassRef<'a, T: RegisteredClass> {
ptr: &'a mut ZendClassObject<T>,
}
impl<'a, T: RegisteredClass> ClassRef<'a, T> {
/// Creates a new class reference from a Rust type reference.
pub fn from_ref(obj: &'a T) -> Option<Self> {
let ptr = unsafe { ZendClassObject::from_obj_ptr(obj)? };
Some(Self { ptr })
}
}
impl<'a, T: RegisteredClass> IntoZval for ClassRef<'a, T> {
const TYPE: DataType = DataType::Object;
fn set_zval(self, zv: &mut Zval, _: bool) -> Result<()> {
zv.set_object(&mut self.ptr.std);
Ok(())
}
}
pub struct ClassObject<'a, T: RegisteredClass> {
ptr: &'a mut ZendClassObject<T>,
free: bool,
}
impl<T: RegisteredClass> Default for ClassObject<'_, T> {
fn default() -> Self {
let ptr = unsafe {
ZendClassObject::new_ptr(None)
.as_mut()
.expect("Failed to allocate memory for class object.")
};
Self { ptr, free: true }
}
}
impl<T: RegisteredClass> ClassObject<'_, T> {
/// Creates a class object from a pre-existing Rust object.
///
/// # Parameters
///
/// * `obj` - The object to create a class object for.
pub fn new(obj: T) -> Self {
let ptr = unsafe {
ZendClassObject::new_ptr(Some(obj))
.as_mut()
.expect("Failed to allocate memory for class object.")
};
Self { ptr, free: true }
}
/// Consumes the class object, releasing the internal pointer without releasing the internal object.
///
/// Used to transfer ownership of the object to PHP.
pub(crate) fn into_raw(mut self) -> *mut ZendClassObject<T> {
self.free = false;
self.ptr
}
/// Returns an immutable reference to the underlying class object.
pub(crate) fn internal(&self) -> &ZendClassObject<T> {
self.ptr
}
/// Returns a mutable reference to the underlying class object.
pub(crate) fn internal_mut(&mut self) -> &mut ZendClassObject<T> {
self.ptr
}
/// Creates a new instance of [`ClassObject`] around a pre-existing class object.
///
/// # Parameters
///
/// * `ptr` - Pointer to the class object.
/// * `free` - Whether to release the underlying object which `ptr` points to.
///
/// # Safety
///
/// Caller must guarantee that `ptr` points to an aligned, non-null instance of
/// [`ZendClassObject`]. Caller must also guarantee that `ptr` will at least live for
/// the lifetime `'a` (as long as the resulting object lives).
///
/// Caller must also guarantee that it is expected to free `ptr` after dropping the
/// resulting [`ClassObject`] to prevent use-after-free situations.
///
/// # Panics
///
/// Panics when the given `ptr` is null.
pub(crate) unsafe fn from_zend_class_object(ptr: *mut ZendClassObject<T>, free: bool) -> Self {
Self {
ptr: ptr.as_mut().expect("Given pointer was null"),
free,
}
}
}
impl<T: RegisteredClass> Drop for ClassObject<'_, T> {
fn drop(&mut self) {
if self.free {
unsafe { ext_php_rs_zend_object_release(&mut (*self.ptr).std) };
}
}
}
impl<T: RegisteredClass> Deref for ClassObject<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// SAFETY: Class object constructor guarantees memory is allocated.
unsafe { &*self.ptr.obj.as_ptr() }
}
}
impl<T: RegisteredClass> DerefMut for ClassObject<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY: Class object constructor guarantees memory is allocated.
unsafe { &mut *self.ptr.obj.as_mut_ptr() }
}
}
impl<T: RegisteredClass + Clone> Clone for ClassObject<'_, T> {
fn clone(&self) -> Self {
// SAFETY: Class object constructor guarantees memory is allocated.
let mut new = Self::new(unsafe { &*self.internal().obj.as_ptr() }.clone());
unsafe {
zend_objects_clone_members(
&mut new.internal_mut().std,
&self.internal().std as *const _ as *mut _,
)
}
new
}
}
impl<T: RegisteredClass + Debug> Debug for ClassObject<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.internal().obj.fmt(f)
}
}
impl<T: RegisteredClass> IntoZval for ClassObject<'_, T> {
const TYPE: DataType = DataType::Object;
fn set_zval(self, zv: &mut Zval, _: bool) -> Result<()> {
unsafe { zv.set_object(&mut (*self.into_raw()).std) };
Ok(())
}
}
impl<T: RegisteredClass> IntoZval for T {
const TYPE: DataType = DataType::Object;
fn set_zval(self, zv: &mut Zval, persistent: bool) -> Result<()> {
ClassObject::new(self).set_zval(zv, persistent)
}
}
/// Implemented on Rust types which are exported to PHP. Allows users to get and set PHP properties on
/// the object.
pub trait RegisteredClass: Default + Sized
where
Self: 'static,
{
/// Returns a reference to the class metadata, which stores the class entry and handlers.
///
/// This must be statically allocated, and is usually done through the [`macro@php_class`]
/// macro.
///
/// [`macro@php_class`]: crate::php_class
fn get_metadata() -> &'static ClassMetadata<Self>;
/// Attempts to retrieve a property from the class object.
///
/// # Parameters
///
/// * `name` - The name of the property.
///
/// # Returns
///
/// Returns a given type `T` inside an option which is the value of the zval, or [`None`]
/// if the property could not be found.
///
/// # Safety
///
/// Caller must guarantee that the object the function is called on is immediately followed
/// by a [`zend_object`], which is true when the object was instantiated by PHP.
unsafe fn get_property<'a, T: FromZval<'a>>(&'a self, name: &str) -> Option<T> {
let obj = ZendClassObject::<Self>::from_obj_ptr(self)?;
let zv = obj.std.get_property(name).ok()?;
zv.try_into().ok()
}
/// Attempts to set the value of a property on the class object.
///
/// # Parameters
///
/// * `name` - The name of the property to set.
/// * `value` - The value to set the property to.
///
/// # Returns
///
/// Returns nothing in an option if the property was successfully set. Returns none if setting
/// the value failed.
///
/// # Safety
///
/// Caller must guarantee that the object the function is called on is immediately followed
/// by a [`zend_object`], which is true when the object was instantiated by PHP.
unsafe fn set_property(&mut self, name: &str, value: impl IntoZval) -> Option<()> {
let obj = ZendClassObject::<Self>::from_obj_ptr(self)?;
obj.std.set_property(name, value).ok()?;
Some(())
}
}
/// Representation of a Zend class object in memory. Usually seen through its managed variant
/// of [`ClassObject`].
#[repr(C)]
pub(crate) struct ZendClassObject<T: RegisteredClass> {
obj: MaybeUninit<T>,
std: zend_object,
}
impl<T: RegisteredClass> ZendClassObject<T> {
/// Allocates memory for a new PHP object. The memory is allocated using the Zend memory manager,
/// and therefore it is returned as a pointer.
pub(crate) fn new_ptr(val: Option<T>) -> *mut Self {
let size = mem::size_of::<Self>();
let meta = T::get_metadata();
let ce = meta.ce() as *const _ as *mut _;
unsafe {
let obj = (ext_php_rs_zend_object_alloc(size as _, ce) as *mut Self)
.as_mut()
.expect("Failed to allocate memory for new class object.");
zend_object_std_init(&mut obj.std, ce);
object_properties_init(&mut obj.std, ce);
obj.obj = MaybeUninit::new(val.unwrap_or_default());
obj.std.handlers = meta.handlers();
obj
}
}
/// Returns a reference to the [`ZendClassObject`] of a given object `T`. Returns [`None`]
/// if the given object is not of the type `T`.
///
/// # Parameters
///
/// * `obj` - The object to get the [`ZendClassObject`] for.
///
/// # Safety
///
/// Caller must guarantee that the given `obj` was created by Zend, which means that it
/// is immediately followed by a [`zend_object`].
pub(crate) unsafe fn from_obj_ptr(obj: &T) -> Option<&mut Self> {
let ptr = (obj as *const T as *mut Self).as_mut()?;
if ptr.std.is_instance::<T>() {
Some(ptr)
} else {
None
}
}
/// Returns a mutable reference to the underlying Zend object.
pub(crate) fn get_mut_zend_obj(&mut self) -> &mut zend_object {
&mut self.std
}
}
impl<T: RegisteredClass> Drop for ZendClassObject<T> {
fn drop(&mut self) {
// SAFETY: All constructors guarantee that `obj` is valid.
unsafe { std::ptr::drop_in_place(self.obj.as_mut_ptr()) };
}
}
/// Stores the class entry and handlers for a Rust type which has been exported to PHP.
pub struct ClassMetadata<T> {
handlers_init: AtomicBool,
handlers: MaybeUninit<ZendObjectHandlers>,
ce: AtomicPtr<ClassEntry>,
phantom: PhantomData<T>,
}
impl<T> ClassMetadata<T> {
/// Creates a new class metadata instance.
pub const fn new() -> Self {
Self {
handlers_init: AtomicBool::new(false),
handlers: MaybeUninit::uninit(),
ce: AtomicPtr::new(std::ptr::null_mut()),
phantom: PhantomData,
}
}
/// Returns an immutable reference to the object handlers contained inside the class metadata.
pub fn handlers(&self) -> &ZendObjectHandlers {
self.check_handlers();
// SAFETY: `check_handlers` guarantees that `handlers` has been initialized.
unsafe { &*self.handlers.as_ptr() }
}
/// Checks if the class entry has been stored, returning a boolean.
pub fn has_ce(&self) -> bool {
!self.ce.load(Ordering::SeqCst).is_null()
}
/// Retrieves a reference to the stored class entry.
///
/// # Panics
///
/// Panics if there is no class entry stored inside the class metadata.
pub fn ce(&self) -> &'static ClassEntry {
// SAFETY: There are only two values that can be stored in the atomic ptr: null or a static reference
// to a class entry. On the latter case, `as_ref()` will return `None` and the function will panic.
unsafe { self.ce.load(Ordering::SeqCst).as_ref() }
.expect("Attempted to retrieve class entry before it has been stored.")
}
/// Stores a reference to a class entry inside the class metadata.
///
/// # Parameters
///
/// * `ce` - The class entry to store.
///
/// # Panics
///
/// Panics if the class entry has already been set in the class metadata. This function should
/// only be called once.
pub fn set_ce(&self, ce: &'static mut ClassEntry) {
if !self.ce.load(Ordering::SeqCst).is_null() {
panic!("Class entry has already been set.");
}
self.ce.store(ce, Ordering::SeqCst);
}
/// Checks if the handlers have been initialized, and initializes them if they are not.
fn check_handlers(&self) {
if !self.handlers_init.load(Ordering::Acquire) {
// SAFETY: `MaybeUninit` has the same size as the handlers.
unsafe { ZendObjectHandlers::init::<T>(self.handlers.as_ptr() as *mut _) };
self.handlers_init.store(true, Ordering::Release);
}
}
}
impl ZendObjectHandlers {
/// 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.
pub unsafe fn init<T>(ptr: *mut ZendObjectHandlers) {
pub unsafe extern "C" fn free_obj<T>(object: *mut zend_object) {
let layout = Layout::new::<T>();
let offset = layout.size();
// Cast to *mut u8 to work in byte offsets
let ptr = (object as *mut u8).offset(0 - offset as isize) as *mut T;
ptr::drop_in_place(ptr);
match std_object_handlers.free_obj {
Some(free) => free(object),
None => core::hint::unreachable_unchecked(),
}
}
std::ptr::copy_nonoverlapping(&std_object_handlers, ptr, 1);
let offset = std::mem::size_of::<T>();
(*ptr).offset = offset as _;
(*ptr).free_obj = Some(free_obj::<T>);
}
}