1use std::{
2 ffi::CString,
3 mem::{ManuallyDrop, MaybeUninit},
4 ptr,
5 rc::Rc,
6};
7
8use crate::{
9 args::ArgInfoTables,
10 builders::{FunctionBuilder, function::free_registered_entries},
11 class::{ClassEntryInfo, ConstructorMeta, ConstructorResult, RegisteredClass},
12 convert::{IntoZval, IntoZvalDyn},
13 describe::DocComments,
14 error::{Error, Result},
15 exception::PhpException,
16 ffi::{
17 zend_declare_class_constant_ex, zend_declare_property, zend_do_implement_interface,
18 zend_hash_str_find_ptr_lc, zend_register_internal_class_ex,
19 zend_register_internal_interface,
20 },
21 flags::{ClassFlags, ConstantFlags, DataType, MethodFlags, PropertyFlags},
22 types::{ZendClassObject, ZendObject, ZendStr, Zval},
23 zend::function::{SensitiveParameters, mark_sensitive},
24 zend::{ClassEntry, CompilerGlobals, ExecuteData, ExecutorGlobals, FunctionEntry},
25 zend_fastcall,
26};
27
28type ConstantEntry = (
30 String,
31 Box<dyn FnOnce() -> Result<Zval>>,
32 DocComments,
33 String,
34 ConstantFlags,
35);
36type PropertyDefault = Option<Box<dyn FnOnce() -> Result<Zval>>>;
37
38pub struct ClassProperty {
40 pub name: String,
42 pub flags: PropertyFlags,
44 pub default: PropertyDefault,
46 pub docs: DocComments,
48 pub ty: Option<DataType>,
50 pub nullable: bool,
52 pub readonly: bool,
54 pub default_stub: Option<String>,
56}
57
58pub(crate) fn first_duplicate<'a>(
62 names: impl IntoIterator<Item = &'a str>,
63 fold_ascii_case: bool,
64) -> Option<&'a str> {
65 let names: Vec<&str> = names.into_iter().collect();
66 names.iter().enumerate().find_map(|(i, name)| {
67 names[..i]
68 .iter()
69 .any(|earlier| {
70 if fold_ascii_case {
71 earlier.eq_ignore_ascii_case(name)
72 } else {
73 earlier == name
74 }
75 })
76 .then_some(*name)
77 })
78}
79
80pub(crate) fn ensure_class_name_free(name: &str) -> Result<()> {
87 let class_table = CompilerGlobals::get().class_table;
88 if class_table.is_null() {
89 return Ok(());
90 }
91 let found = unsafe { zend_hash_str_find_ptr_lc(class_table, name.as_ptr().cast(), name.len()) };
94 if found.is_null() {
95 Ok(())
96 } else {
97 Err(Error::DuplicateClass {
98 class: name.to_owned(),
99 })
100 }
101}
102
103#[must_use]
105pub struct ClassBuilder {
106 pub(crate) name: String,
107 ce: ClassEntry,
108 pub(crate) extends: Option<ClassEntryInfo>,
109 pub(crate) interfaces: Vec<ClassEntryInfo>,
110 pub(crate) methods: Vec<(FunctionBuilder<'static>, MethodFlags)>,
111 object_override: Option<unsafe extern "C" fn(class_type: *mut ClassEntry) -> *mut ZendObject>,
112 pub(crate) properties: Vec<ClassProperty>,
113 pub(crate) constants: Vec<ConstantEntry>,
114 register: Option<fn(&'static mut ClassEntry, ArgInfoTables)>,
115 pub(crate) docs: DocComments,
116}
117
118impl ClassBuilder {
119 pub fn new<T: Into<String>>(name: T) -> Self {
126 Self {
127 name: name.into(),
128 ce: unsafe { MaybeUninit::zeroed().assume_init() },
131 extends: None,
132 interfaces: vec![],
133 methods: vec![],
134 object_override: None,
135 properties: vec![],
136 constants: vec![],
137 register: None,
138 docs: &[],
139 }
140 }
141
142 #[must_use]
144 pub fn get_flags(&self) -> u32 {
145 self.ce.ce_flags
146 }
147
148 pub fn extends(mut self, parent: ClassEntryInfo) -> Self {
154 self.extends = Some(parent);
155 self
156 }
157
158 pub fn implements(mut self, interface: ClassEntryInfo) -> Self {
168 self.interfaces.push(interface);
169 self
170 }
171
172 pub fn method(mut self, func: FunctionBuilder<'static>, flags: MethodFlags) -> Self {
179 self.methods.push((func, flags));
180 self
181 }
182
183 pub fn property(mut self, prop: ClassProperty) -> Self {
189 self.properties.push(prop);
190 self
191 }
192
193 pub fn constant<T: Into<String>>(
210 mut self,
211 name: T,
212 value: impl IntoZval + 'static,
213 docs: DocComments,
214 flags: ConstantFlags,
215 ) -> Result<Self> {
216 let zval = value.into_zval(true)?;
217 let stub = crate::convert::zval_to_stub(&zval);
218 self.constants
219 .push((name.into(), Box::new(|| Ok(zval)), docs, stub, flags));
220 Ok(self)
221 }
222
223 pub fn dyn_constant<T: Into<String>>(
240 mut self,
241 name: T,
242 value: &'static dyn IntoZvalDyn,
243 docs: DocComments,
244 flags: ConstantFlags,
245 ) -> Result<Self> {
246 let stub = value.stub_value();
247 let value = Rc::new(value);
248 self.constants.push((
249 name.into(),
250 Box::new(move || value.as_zval(true)),
251 docs,
252 stub,
253 flags,
254 ));
255 Ok(self)
256 }
257
258 pub fn flags(mut self, flags: ClassFlags) -> Self {
264 self.ce.ce_flags = flags.bits();
265 self
266 }
267
268 pub fn object_override<T: RegisteredClass>(mut self) -> Self {
282 extern "C" fn create_object<T: RegisteredClass>(ce: *mut ClassEntry) -> *mut ZendObject {
283 if let Some(instance) = T::default_init() {
290 let obj = ZendClassObject::<T>::new(instance).into_raw();
291 return unsafe { (*obj).get_mut_zend_obj() };
294 }
295
296 let obj = unsafe { ZendClassObject::<T>::new_uninit(ce.as_ref()) }.into_raw();
299 unsafe { (*obj).get_mut_zend_obj() }
301 }
302
303 zend_fastcall! {
304 extern fn constructor<T: RegisteredClass>(ex: &mut ExecuteData, _: &mut Zval) {
305 crate::zend::run_handler(std::panic::AssertUnwindSafe(|| {
306 let Some(ConstructorMeta { constructor, .. }) = T::constructor() else {
307 PhpException::from_message("You cannot instantiate this class from PHP.".into())
308 .throw();
309 return;
310 };
311
312 let this = match constructor(ex) {
313 ConstructorResult::Ok(this) => this,
314 ConstructorResult::Exception(e) => {
315 e.throw();
316 return;
317 }
318 ConstructorResult::ArgError => return,
319 };
320
321 let Some(this_obj) = ex.get_object_uninit::<T>() else {
324 PhpException::from_message("Failed to retrieve reference to `this` object.".into())
325 .throw();
326 return;
327 };
328
329 this_obj.initialize(this);
330 }));
331 }
332 }
333
334 debug_assert_eq!(
335 self.name.as_str(),
336 T::CLASS_NAME,
337 "Class name in builder does not match class name in `impl RegisteredClass`."
338 );
339 self.object_override = Some(create_object::<T>);
340 let is_interface = T::FLAGS.contains(ClassFlags::Interface);
341
342 if let Some(ConstructorMeta {
345 build_fn, flags, ..
346 }) = T::constructor()
347 {
348 let func = if is_interface {
349 FunctionBuilder::new_abstract("__construct")
350 } else {
351 FunctionBuilder::new("__construct", constructor::<T>)
352 };
353 let visibility = flags.unwrap_or(MethodFlags::Public);
354 self.method(build_fn(func), visibility)
355 } else if is_interface {
356 self
358 } else {
359 let func = FunctionBuilder::new("__construct", constructor::<T>);
361 self.method(func, MethodFlags::Public)
362 }
363 }
364
365 pub fn registration(mut self, register: fn(&'static mut ClassEntry, ArgInfoTables)) -> Self {
384 self.register = Some(register);
385 self
386 }
387
388 pub fn docs(mut self, docs: DocComments) -> Self {
394 self.docs = docs;
395 self
396 }
397
398 fn validate(&self) -> Result<()> {
401 if let Some(name) = first_duplicate(self.properties.iter().map(|p| p.name.as_str()), false)
402 {
403 return Err(Error::DuplicateProperty {
404 property: format!("{}::${name}", self.name),
405 });
406 }
407 if let Some(name) = first_duplicate(self.methods.iter().map(|(m, _)| m.name.as_str()), true)
408 {
409 return Err(Error::DuplicateMethod {
410 method: format!("{}::{name}", self.name),
411 });
412 }
413 if let Some(name) = first_duplicate(self.constants.iter().map(|c| c.0.as_str()), false) {
414 return Err(Error::DuplicateConstant {
415 constant: format!("{}::{name}", self.name),
416 });
417 }
418 Ok(())
419 }
420
421 pub fn register(mut self) -> Result<()> {
439 assert!(
440 !ExecutorGlobals::get().current_module.is_null(),
441 "Classes can only be registered from a module startup (MINIT) function: \
442 `do_register_internal_class` dereferences `EG(current_module)`."
443 );
444 self.validate()?;
445 ensure_class_name_free(&self.name)?;
446
447 self.ce.name = ZendStr::new_interned(&self.name, true).into_raw();
448
449 let mut arg_info = Vec::with_capacity(self.methods.len());
450 let mut methods = Vec::with_capacity(self.methods.len() + 1);
451 let mut sensitive = SensitiveParameters::new();
452 for (method, flags) in self.methods {
453 sensitive.extend(method.sensitive());
454 let (mut entry, args) = method.build()?;
455 entry.add_flags(flags);
456 methods.push(entry);
457 arg_info.push(args);
458 }
459
460 let arg_info = ManuallyDrop::new(arg_info.into_boxed_slice());
467
468 methods.push(FunctionEntry::end());
469 let entries = Box::into_raw(methods.into_boxed_slice());
470 self.ce.info.internal.builtin_functions = entries.cast::<FunctionEntry>().cast_const();
471
472 let class = if self.ce.flags().contains(ClassFlags::Interface) {
473 unsafe { zend_register_internal_interface(&raw mut self.ce) }
474 } else {
475 let parent = match self.extends {
479 Some((ptr, _)) => ptr::from_ref(ptr()).cast_mut(),
480 None => std::ptr::null_mut(),
481 };
482 unsafe { zend_register_internal_class_ex(&raw mut self.ce, parent) }
483 };
484
485 unsafe { free_registered_entries(entries) };
488
489 let class = unsafe { class.as_mut() }.ok_or(Error::InvalidPointer)?;
490 class.info.internal.builtin_functions = ptr::null();
491 mark_sensitive(&raw const class.function_table, &sensitive);
492
493 if self.object_override.is_some() {
495 cfg_if::cfg_if! {
496 if #[cfg(php81)] {
497 class.ce_flags |= ClassFlags::NotSerializable.bits();
498 } else {
499 class.serialize = Some(crate::ffi::zend_class_serialize_deny);
500 class.unserialize = Some(crate::ffi::zend_class_unserialize_deny);
501 }
502 }
503 }
504
505 for (iface, _) in self.interfaces {
506 let interface = iface();
507 assert!(
508 interface.is_interface(),
509 "Given class entry was not an interface."
510 );
511
512 unsafe { zend_do_implement_interface(class, ptr::from_ref(interface).cast_mut()) };
513 }
514
515 for prop in self.properties {
516 let mut default_zval = match prop.default {
517 Some(f) => f()?,
518 None => Zval::new(),
519 };
520 unsafe {
521 zend_declare_property(
522 class,
523 CString::new(prop.name.as_str())?.as_ptr(),
524 prop.name.len() as _,
525 &raw mut default_zval,
526 prop.flags.bits().try_into()?,
527 );
528 }
529 }
530
531 for (name, value, _, _, flags) in self.constants {
532 let name = ZendStr::new_interned(&name, true);
535 let mut value = ManuallyDrop::new(value()?);
540 unsafe {
541 zend_declare_class_constant_ex(
542 class,
543 name.as_ptr().cast_mut(),
544 &raw mut *value,
545 flags.bits().try_into()?,
546 ptr::null_mut(),
547 );
548 };
549 }
550
551 if let Some(object_override) = self.object_override {
552 class.__bindgen_anon_2.create_object = Some(object_override);
553 }
554
555 if let Some(register) = self.register {
556 register(class, ManuallyDrop::into_inner(arg_info));
557 } else {
558 panic!("Class {} was not registered.", self.name);
559 }
560
561 Ok(())
562 }
563}
564
565#[cfg(test)]
566mod tests {
567 use crate::test::test_function;
568
569 use super::*;
570
571 #[test]
572 #[allow(unpredictable_function_pointer_comparisons)]
573 fn test_new() {
574 let class = ClassBuilder::new("Foo");
575 assert_eq!(class.name, "Foo");
576 assert_eq!(class.extends, None);
577 assert_eq!(class.interfaces, vec![]);
578 assert_eq!(class.methods.len(), 0);
579 assert_eq!(class.object_override, None);
580 assert!(class.properties.is_empty());
581 assert_eq!(class.constants.len(), 0);
582 assert_eq!(class.register, None);
583 assert_eq!(class.docs, &[] as DocComments);
584 }
585
586 #[test]
587 fn test_extends() {
588 let extends: ClassEntryInfo = (|| todo!(), "Bar");
589 let class = ClassBuilder::new("Foo").extends(extends);
590 assert_eq!(class.extends, Some(extends));
591 }
592
593 #[test]
594 fn test_implements() {
595 let implements: ClassEntryInfo = (|| todo!(), "Bar");
596 let class = ClassBuilder::new("Foo").implements(implements);
597 assert_eq!(class.interfaces, vec![implements]);
598 }
599
600 #[test]
601 fn test_method() {
602 let method = FunctionBuilder::new("foo", test_function);
603 let class = ClassBuilder::new("Foo").method(method, MethodFlags::Public);
604 assert_eq!(class.methods.len(), 1);
605 }
606
607 #[test]
608 fn test_property() {
609 let class = ClassBuilder::new("Foo").property(ClassProperty {
610 name: "bar".into(),
611 flags: PropertyFlags::Public,
612 default: None,
613 docs: &["Doc 1"],
614 ty: Some(DataType::String),
615 nullable: false,
616 readonly: false,
617 default_stub: None,
618 });
619 assert_eq!(class.properties.len(), 1);
620 assert_eq!(class.properties[0].name, "bar");
621 assert_eq!(class.properties[0].flags, PropertyFlags::Public);
622 assert!(class.properties[0].default.is_none());
623 assert_eq!(class.properties[0].docs, &["Doc 1"] as DocComments);
624 assert_eq!(class.properties[0].ty, Some(DataType::String));
625 }
626
627 fn named_property(name: &str) -> ClassProperty {
628 ClassProperty {
629 name: name.into(),
630 flags: PropertyFlags::Public,
631 default: None,
632 docs: &[],
633 ty: None,
634 nullable: false,
635 readonly: false,
636 default_stub: None,
637 }
638 }
639
640 fn with_constant(mut class: ClassBuilder, name: &str) -> ClassBuilder {
641 class.constants.push((
642 name.into(),
643 Box::new(|| Err(Error::InvalidPointer)),
644 &[],
645 String::new(),
646 ConstantFlags::Public,
647 ));
648 class
649 }
650
651 #[test]
652 fn first_duplicate_folds_ascii_case_only_when_asked() {
653 assert_eq!(first_duplicate(["a", "b", "a"], false), Some("a"));
654 assert_eq!(first_duplicate(["a", "B", "b"], false), None);
655 assert_eq!(first_duplicate(["a", "B", "b"], true), Some("b"));
656 assert_eq!(first_duplicate(["ä", "Ä"], true), None);
657 assert_eq!(first_duplicate([], true), None);
658 }
659
660 #[test]
661 fn validate_rejects_a_repeated_property() {
662 let mut class = ClassBuilder::new("Foo");
663 class.properties = vec![named_property("a"), named_property("a")];
664 assert!(matches!(
665 class.validate(),
666 Err(Error::DuplicateProperty { property }) if property == "Foo::$a"
667 ));
668 }
669
670 #[test]
671 fn validate_rejects_methods_that_differ_only_by_case() {
672 let class = ClassBuilder::new("Foo")
673 .method(
674 FunctionBuilder::new("run", test_function),
675 MethodFlags::Public,
676 )
677 .method(
678 FunctionBuilder::new("RUN", test_function),
679 MethodFlags::Static,
680 );
681 assert!(matches!(
682 class.validate(),
683 Err(Error::DuplicateMethod { method }) if method == "Foo::RUN"
684 ));
685 }
686
687 #[test]
688 fn validate_compares_constants_exactly() {
689 let class = with_constant(with_constant(ClassBuilder::new("Foo"), "A"), "a");
690 assert!(class.validate().is_ok());
691 let class = with_constant(class, "A");
692 assert!(matches!(
693 class.validate(),
694 Err(Error::DuplicateConstant { constant }) if constant == "Foo::A"
695 ));
696 }
697
698 #[test]
699 #[cfg(feature = "embed")]
700 fn class_names_already_in_the_class_table_are_taken() {
701 let ran = crate::embed::Embed::run(|| {
702 assert!(matches!(
703 ensure_class_name_free("STDCLASS"),
704 Err(Error::DuplicateClass { class }) if class == "STDCLASS"
705 ));
706 assert!(ensure_class_name_free("ExtPhpRsNoSuchClass").is_ok());
707 true
708 });
709 assert!(ran);
710 }
711
712 #[test]
713 fn validate_accepts_distinct_members() {
714 let mut class = ClassBuilder::new("Foo")
715 .method(
716 FunctionBuilder::new("run", test_function),
717 MethodFlags::Public,
718 )
719 .method(
720 FunctionBuilder::new("stop", test_function),
721 MethodFlags::Public,
722 );
723 class.properties = vec![named_property("a"), named_property("b")];
724 assert!(with_constant(class, "A").validate().is_ok());
725 }
726
727 #[test]
728 #[cfg(feature = "embed")]
729 fn test_constant() {
730 let class = ClassBuilder::new("Foo")
731 .constant("bar", 42, &["Doc 1"], ConstantFlags::Public)
732 .expect("Failed to create constant");
733 assert_eq!(class.constants.len(), 1);
734 assert_eq!(class.constants[0].0, "bar");
735 assert_eq!(class.constants[0].2, &["Doc 1"] as DocComments);
736 }
737
738 #[test]
739 #[cfg(feature = "embed")]
740 fn test_dyn_constant() {
741 let class = ClassBuilder::new("Foo")
742 .dyn_constant("bar", &42, &["Doc 1"], ConstantFlags::Public)
743 .expect("Failed to create constant");
744 assert_eq!(class.constants.len(), 1);
745 assert_eq!(class.constants[0].0, "bar");
746 assert_eq!(class.constants[0].2, &["Doc 1"] as DocComments);
747 }
748
749 #[test]
750 fn test_flags() {
751 let class = ClassBuilder::new("Foo").flags(ClassFlags::Abstract);
752 assert_eq!(class.ce.ce_flags, ClassFlags::Abstract.bits());
753 }
754
755 #[test]
756 fn test_registration() {
757 let class = ClassBuilder::new("Foo").registration(|_, _| {});
758 assert!(class.register.is_some());
759 }
760
761 #[test]
762 fn test_registration_interface() {
763 let class = ClassBuilder::new("Foo")
764 .flags(ClassFlags::Interface)
765 .registration(|_, _| {});
766 assert!(class.register.is_some());
767 }
768
769 #[test]
770 fn test_docs() {
771 let class = ClassBuilder::new("Foo").docs(&["Doc 1"]);
772 assert_eq!(class.docs, &["Doc 1"] as DocComments);
773 }
774
775 }