Skip to main content

ext_php_rs/builders/
module.rs

1use std::{convert::TryFrom, ffi::CString, mem, ptr};
2
3use super::{ClassBuilder, FunctionBuilder, class::first_duplicate};
4use crate::{
5    PHP_DEBUG, PHP_ZTS,
6    class::RegisteredClass,
7    constant::IntoConst,
8    describe::DocComments,
9    error::Result,
10    ffi::{ZEND_MODULE_API_NO, ext_php_rs_php_build_id},
11    flags::ClassFlags,
12    zend::function::{SensitiveParameters, mark_sensitive},
13    zend::{
14        FunctionEntry, ModuleAllocations, ModuleEntry, ModuleGlobal, ModuleGlobals,
15        SapiRequestInfo,
16        sapi_activate::{self, ActivateCallback},
17    },
18};
19#[cfg(feature = "enum")]
20use crate::{builders::enum_builder::EnumBuilder, enum_::RegisteredEnum};
21
22/// Builds a Zend module extension to be registered with PHP. Must be called
23/// from within an external function called `get_module`, returning a mutable
24/// pointer to a `ModuleEntry`.
25///
26/// ```rust,no_run
27/// use ext_php_rs::{
28///     builders::ModuleBuilder,
29///     zend::{ModuleEntry, StaticModuleEntry},
30///     info_table_start, info_table_end, info_table_row
31/// };
32///
33/// #[unsafe(no_mangle)]
34/// pub extern "C" fn php_module_info(_module: *mut ModuleEntry) {
35///     info_table_start!();
36///     info_table_row!("column 1", "column 2");
37///     info_table_end!();
38/// }
39///
40/// #[unsafe(no_mangle)]
41/// pub extern "C" fn get_module() -> *mut ModuleEntry {
42///     static MODULE: StaticModuleEntry = StaticModuleEntry::new();
43///     MODULE.get_or_init(|| {
44///         let (entry, _startup, owned) = ModuleBuilder::new("ext-name", "ext-version")
45///             .info_function(php_module_info)
46///             .try_into()
47///             .unwrap();
48///         (entry, owned)
49///     })
50/// }
51/// ```
52#[must_use]
53#[derive(Debug)]
54pub struct ModuleBuilder<'a> {
55    pub(crate) name: String,
56    pub(crate) version: String,
57    pub(crate) functions: Vec<FunctionBuilder<'a>>,
58    pub(crate) constants: Vec<(String, Box<dyn IntoConst + Send>, DocComments)>,
59    pub(crate) classes: Vec<fn() -> ClassBuilder>,
60    pub(crate) interfaces: Vec<fn() -> ClassBuilder>,
61    #[cfg(feature = "enum")]
62    pub(crate) enums: Vec<fn() -> EnumBuilder>,
63    startup_func: Option<StartupShutdownFunc>,
64    shutdown_func: Option<StartupShutdownFunc>,
65    request_startup_func: Option<StartupShutdownFunc>,
66    request_shutdown_func: Option<StartupShutdownFunc>,
67    post_deactivate_func: Option<unsafe extern "C" fn() -> i32>,
68    sapi_activate: Option<ActivateCallback>,
69    info_func: Option<InfoFunc>,
70    globals_size: usize,
71    #[cfg(php_zts)]
72    globals_id_ptr: *mut i32,
73    #[cfg(not(php_zts))]
74    globals_ptr: *mut std::ffi::c_void,
75    globals_ctor: Option<unsafe extern "C" fn(*mut std::ffi::c_void)>,
76    globals_dtor: Option<unsafe extern "C" fn(*mut std::ffi::c_void)>,
77}
78
79impl Default for ModuleBuilder<'_> {
80    fn default() -> Self {
81        Self {
82            name: String::new(),
83            version: String::new(),
84            functions: vec![],
85            constants: vec![],
86            classes: vec![],
87            interfaces: vec![],
88            #[cfg(feature = "enum")]
89            enums: vec![],
90            startup_func: None,
91            shutdown_func: None,
92            request_startup_func: None,
93            request_shutdown_func: None,
94            post_deactivate_func: None,
95            sapi_activate: None,
96            info_func: None,
97            globals_size: 0,
98            #[cfg(php_zts)]
99            globals_id_ptr: ptr::null_mut(),
100            #[cfg(not(php_zts))]
101            globals_ptr: ptr::null_mut(),
102            globals_ctor: None,
103            globals_dtor: None,
104        }
105    }
106}
107
108impl ModuleBuilder<'_> {
109    /// Creates a new module builder with a given name and version.
110    ///
111    /// # Arguments
112    ///
113    /// * `name` - The name of the extension.
114    /// * `version` - The current version of the extension.
115    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
116        Self {
117            name: name.into(),
118            version: version.into(),
119            ..Default::default()
120        }
121    }
122
123    /// Overrides module name.
124    ///
125    /// # Arguments
126    ///
127    /// * `name` - The name of the extension.
128    pub fn name(mut self, name: impl Into<String>) -> Self {
129        self.name = name.into();
130        self
131    }
132
133    /// Overrides module version.
134    ///
135    /// # Arguments
136    ///
137    /// * `version` - The current version of the extension.
138    pub fn version(mut self, version: impl Into<String>) -> Self {
139        self.version = version.into();
140        self
141    }
142
143    /// Sets the startup function for the extension.
144    ///
145    /// # Arguments
146    ///
147    /// * `func` - The function to be called on startup.
148    pub fn startup_function(mut self, func: StartupShutdownFunc) -> Self {
149        self.startup_func = Some(func);
150        self
151    }
152
153    /// Sets the shutdown function for the extension.
154    ///
155    /// # Arguments
156    ///
157    /// * `func` - The function to be called on shutdown.
158    pub fn shutdown_function(mut self, func: StartupShutdownFunc) -> Self {
159        self.shutdown_func = Some(func);
160        self
161    }
162
163    /// Sets the request startup function for the extension.
164    ///
165    /// # Arguments
166    ///
167    /// * `func` - The function to be called when startup is requested.
168    pub fn request_startup_function(mut self, func: StartupShutdownFunc) -> Self {
169        self.request_startup_func = Some(func);
170        self
171    }
172
173    /// Sets the request shutdown function for the extension.
174    ///
175    /// # Arguments
176    ///
177    /// * `func` - The function to be called when shutdown is requested.
178    pub fn request_shutdown_function(mut self, func: StartupShutdownFunc) -> Self {
179        self.request_shutdown_func = Some(func);
180        self
181    }
182
183    /// Sets the post request shutdown function for the extension.
184    ///
185    /// This function can be useful if you need to do any final cleanup at the
186    /// very end of a request, after all other resources have been released. For
187    /// example, if your extension creates any persistent resources that last
188    /// beyond a single request, you could use this function to clean those up.
189    /// # Arguments
190    ///
191    /// * `func` - The function to be called when shutdown is requested.
192    pub fn post_deactivate_function(mut self, func: unsafe extern "C" fn() -> i32) -> Self {
193        self.post_deactivate_func = Some(func);
194        self
195    }
196
197    /// Runs `callback` at the start of every request, with the request
198    /// information that the SAPI gives.
199    ///
200    /// The callback runs from `sapi_module.activate`, after the SAPI handler.
201    /// Unlike the request startup function, it also runs for each request of a
202    /// `FrankenPHP` worker. At this point the response headers are empty, so
203    /// [`set_header`](crate::zend::set_header) and
204    /// [`set_response_code`](crate::zend::set_response_code) work. `$_SERVER`
205    /// does not exist yet and no PHP code can run.
206    ///
207    /// A panic in `callback` is printed and ignored. A module loaded with
208    /// `dl()` refuses to start when it has this callback. Calling this method
209    /// again replaces the callback.
210    ///
211    /// ```ignore
212    /// use ext_php_rs::prelude::*;
213    /// use ext_php_rs::zend::{SapiRequestInfo, set_header, set_response_code};
214    ///
215    /// #[php_module]
216    /// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
217    ///     module.sapi_activate_function(|info: &SapiRequestInfo| {
218    ///         if info.request_uri() == Some("/old") {
219    ///             let _ = set_header("Location: /new");
220    ///             let _ = set_response_code(301);
221    ///         }
222    ///     })
223    /// }
224    /// ```
225    pub fn sapi_activate_function<F>(mut self, callback: F) -> Self
226    where
227        F: Fn(&SapiRequestInfo) + Send + Sync + 'static,
228    {
229        self.sapi_activate = Some(ActivateCallback::new(callback));
230        self
231    }
232
233    /// Sets the extension information function for the extension.
234    ///
235    /// # Arguments
236    ///
237    /// * `func` - The function to be called to retrieve the information about
238    ///   the extension.
239    pub fn info_function(mut self, func: InfoFunc) -> Self {
240        self.info_func = Some(func);
241        self
242    }
243
244    /// Registers a module globals struct with this extension.
245    ///
246    /// PHP will allocate per-thread storage (ZTS) or use the static's inline
247    /// storage (non-ZTS), calling GINIT/GSHUTDOWN callbacks automatically.
248    ///
249    /// Only one globals struct per module is supported (PHP limitation).
250    /// Calling this a second time will overwrite the previous registration.
251    ///
252    /// # Arguments
253    ///
254    /// * `handle` - A static [`ModuleGlobals`] that will hold the globals.
255    ///
256    /// # Examples
257    ///
258    /// ```ignore
259    /// use ext_php_rs::prelude::*;
260    /// use ext_php_rs::zend::{ModuleGlobal, ModuleGlobals};
261    ///
262    /// #[derive(Default)]
263    /// struct MyGlobals { counter: i64 }
264    /// impl ModuleGlobal for MyGlobals {}
265    ///
266    /// static MY_GLOBALS: ModuleGlobals<MyGlobals> = ModuleGlobals::new();
267    ///
268    /// #[php_module]
269    /// pub fn module(module: ModuleBuilder) -> ModuleBuilder {
270    ///     module.globals(&MY_GLOBALS)
271    /// }
272    /// ```
273    pub fn globals<T: ModuleGlobal>(mut self, handle: &'static ModuleGlobals<T>) -> Self {
274        use crate::zend::module_globals::{ginit_callback, gshutdown_callback};
275
276        self.globals_size = std::mem::size_of::<T>();
277        #[cfg(php_zts)]
278        {
279            self.globals_id_ptr = handle.id_ptr();
280        }
281        #[cfg(not(php_zts))]
282        {
283            self.globals_ptr = handle.data_ptr();
284        }
285        self.globals_ctor = Some(ginit_callback::<T>);
286        self.globals_dtor = Some(gshutdown_callback::<T>);
287        self
288    }
289
290    /// Registers a function call observer for profiling or tracing.
291    ///
292    /// The factory function is called once, at the first MINIT, to create
293    /// a singleton observer instance shared across all requests and threads.
294    /// When the SAPI starts the module again in the same process, the hook is
295    /// registered again with the same instance.
296    /// The observer must be `Send + Sync` as it may be accessed concurrently
297    /// in ZTS builds.
298    ///
299    /// # Arguments
300    ///
301    /// * `factory` - A function that creates an observer instance
302    ///
303    /// # Example
304    ///
305    /// ```ignore
306    /// use ext_php_rs::prelude::*;
307    /// use ext_php_rs::zend::{FcallObserver, FcallInfo, ExecuteData};
308    /// use ext_php_rs::types::Zval;
309    ///
310    /// struct MyProfiler;
311    ///
312    /// impl FcallObserver for MyProfiler {
313    ///     fn should_observe(&self, info: &FcallInfo) -> bool {
314    ///         !info.is_internal
315    ///     }
316    ///     fn begin(&self, _: &ExecuteData) {}
317    ///     fn end(&self, _: &ExecuteData, _: Option<&Zval>) {}
318    /// }
319    ///
320    /// #[php_module]
321    /// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
322    ///     module.fcall_observer(|| MyProfiler)
323    /// }
324    /// ```
325    ///
326    /// # Panics
327    ///
328    /// Panics if called more than once on the same module.
329    #[cfg(feature = "observer")]
330    pub fn fcall_observer<F, O>(self, factory: F) -> Self
331    where
332        F: Fn() -> O + Send + Sync + 'static,
333        O: crate::zend::FcallObserver + Send + Sync,
334    {
335        let boxed_factory: Box<
336            dyn Fn() -> Box<dyn crate::zend::FcallObserver + Send + Sync> + Send + Sync,
337        > = Box::new(move || Box::new(factory()));
338        crate::zend::observer::register_fcall_observer_factory(boxed_factory);
339        self
340    }
341
342    /// Registers an error observer for monitoring PHP errors.
343    ///
344    /// The factory function is called once, at the first MINIT, to create
345    /// a singleton observer instance shared across all requests.
346    /// When the SAPI starts the module again in the same process, the hook is
347    /// registered again with the same instance.
348    /// The observer must be `Send + Sync` for ZTS builds.
349    ///
350    /// # Arguments
351    ///
352    /// * `factory` - A function that creates an observer instance
353    ///
354    /// # Example
355    ///
356    /// ```ignore
357    /// use ext_php_rs::prelude::*;
358    ///
359    /// struct MyErrorLogger;
360    ///
361    /// impl ErrorObserver for MyErrorLogger {
362    ///     fn should_observe(&self, error_type: ErrorType) -> bool {
363    ///         ErrorType::Fatal.contains(error_type)
364    ///     }
365    ///
366    ///     fn on_error(&self, error: &ErrorInfo) {
367    ///         eprintln!("[{}:{}] {}",
368    ///             error.filename.unwrap_or("<unknown>"),
369    ///             error.lineno,
370    ///             error.message
371    ///         );
372    ///     }
373    /// }
374    ///
375    /// #[php_module]
376    /// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
377    ///     module.error_observer(MyErrorLogger)
378    /// }
379    /// ```
380    ///
381    /// # Panics
382    ///
383    /// Panics if called more than once on the same module.
384    #[cfg(feature = "observer")]
385    pub fn error_observer<F, O>(self, factory: F) -> Self
386    where
387        F: Fn() -> O + Send + Sync + 'static,
388        O: crate::zend::ErrorObserver + Send + Sync,
389    {
390        let boxed_factory: Box<
391            dyn Fn() -> Box<dyn crate::zend::ErrorObserver + Send + Sync> + Send + Sync,
392        > = Box::new(move || Box::new(factory()));
393        crate::zend::error_observer::register_error_observer_factory(boxed_factory);
394        self
395    }
396
397    /// Registers an exception observer for monitoring thrown PHP exceptions.
398    ///
399    /// The factory function is called once, at the first MINIT, to create
400    /// a singleton observer instance shared across all requests.
401    /// When the SAPI starts the module again in the same process, the hook is
402    /// registered again with the same instance.
403    /// The observer must be `Send + Sync` for ZTS builds.
404    ///
405    /// The observer is called at throw time, before any catch blocks are
406    /// evaluated.
407    ///
408    /// # Arguments
409    ///
410    /// * `factory` - A function that creates an observer instance
411    ///
412    /// # Example
413    ///
414    /// ```ignore
415    /// use ext_php_rs::prelude::*;
416    ///
417    /// struct MyExceptionLogger;
418    ///
419    /// impl ExceptionObserver for MyExceptionLogger {
420    ///     fn on_exception(&self, exception: &ExceptionInfo) {
421    ///         eprintln!("[EXCEPTION] {}: {} at {}:{}",
422    ///             exception.class_name,
423    ///             exception.message.as_deref().unwrap_or("<no message>"),
424    ///             exception.file.as_deref().unwrap_or("<unknown>"),
425    ///             exception.line
426    ///         );
427    ///     }
428    /// }
429    ///
430    /// #[php_module]
431    /// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
432    ///     module.exception_observer(|| MyExceptionLogger)
433    /// }
434    /// ```
435    ///
436    /// # Panics
437    ///
438    /// Panics if called more than once on the same module.
439    #[cfg(feature = "observer")]
440    pub fn exception_observer<F, O>(self, factory: F) -> Self
441    where
442        F: Fn() -> O + Send + Sync + 'static,
443        O: crate::zend::ExceptionObserver + Send + Sync,
444    {
445        let boxed_factory: Box<
446            dyn Fn() -> Box<dyn crate::zend::ExceptionObserver + Send + Sync> + Send + Sync,
447        > = Box::new(move || Box::new(factory()));
448        crate::zend::exception_observer::register_exception_observer_factory(boxed_factory);
449        self
450    }
451
452    /// Adds a function to the extension.
453    ///
454    /// # Arguments
455    ///
456    /// * `func` - The function to be added to the extension.
457    pub fn function(mut self, func: FunctionBuilder<'static>) -> Self {
458        self.functions.push(func);
459        self
460    }
461
462    /// Adds a constant to the extension.
463    ///
464    /// # Arguments
465    ///
466    /// * `const` - Tuple containing the name, value and doc comments for the
467    ///   constant. This is a tuple to support the [`wrap_constant`] macro.
468    ///
469    /// [`wrap_constant`]: crate::wrap_constant
470    pub fn constant(
471        mut self,
472        r#const: (&str, impl IntoConst + Send + 'static, DocComments),
473    ) -> Self {
474        let (name, val, docs) = r#const;
475        self.constants.push((
476            name.into(),
477            Box::new(val) as Box<dyn IntoConst + Send>,
478            docs,
479        ));
480        self
481    }
482
483    /// Adds a interface to the extension.
484    ///
485    /// # Panics
486    ///
487    /// * Panics if a constant could not be registered.
488    #[expect(
489        clippy::expect_used,
490        reason = "registration runs in MINIT, where a failure is an extension bug the engine cannot recover from"
491    )]
492    pub fn interface<T: RegisteredClass>(mut self) -> Self {
493        self.interfaces.push(|| {
494            let mut builder = ClassBuilder::new(T::CLASS_NAME);
495            for (method, flags) in T::method_builders() {
496                builder = builder.method(method, flags);
497            }
498            for interface in T::IMPLEMENTS {
499                builder = builder.implements(*interface);
500            }
501            for (name, value, docs, flags) in T::constants() {
502                builder = builder
503                    .dyn_constant(*name, *value, docs, *flags)
504                    .expect("Failed to register constant");
505            }
506
507            if let Some(modifier) = T::BUILDER_MODIFIER {
508                builder = modifier(builder);
509            }
510
511            builder = builder.flags(ClassFlags::Interface);
512            // Note: interfaces should NOT have object_override because they cannot be
513            // instantiated
514            builder
515                .registration(|ce, arg_info| {
516                    T::get_metadata().set_ce(ce);
517                    T::get_metadata().set_arg_info(arg_info);
518                })
519                .docs(T::DOC_COMMENTS)
520        });
521        self
522    }
523
524    /// Adds a class to the extension.
525    ///
526    /// # Panics
527    ///
528    /// * Panics if a constant could not be registered.
529    #[expect(
530        clippy::expect_used,
531        reason = "registration runs in MINIT, where a failure is an extension bug the engine cannot recover from"
532    )]
533    pub fn class<T: RegisteredClass>(mut self) -> Self {
534        self.classes.push(|| {
535            let mut builder = ClassBuilder::new(T::CLASS_NAME);
536            for (method, flags) in T::method_builders() {
537                builder = builder.method(method, flags);
538            }
539            // Methods from #[php_impl_interface] trait implementations.
540            // Uses the inventory crate for cross-crate method discovery.
541            for (method, flags) in T::interface_method_implementations() {
542                builder = builder.method(method, flags);
543            }
544            if let Some(parent) = T::EXTENDS {
545                builder = builder.extends(parent);
546            }
547            // Interfaces declared via #[php(implements(...))] attribute
548            for interface in T::IMPLEMENTS {
549                builder = builder.implements(*interface);
550            }
551            // Interfaces from #[php_impl_interface] trait implementations.
552            // Uses the inventory crate for cross-crate interface discovery.
553            for interface in T::interface_implementations() {
554                builder = builder.implements(interface);
555            }
556            for (name, value, docs, flags) in T::constants() {
557                builder = builder
558                    .dyn_constant(*name, *value, docs, *flags)
559                    .expect("Failed to register constant");
560            }
561            for desc in T::get_metadata().all_properties() {
562                let default_stub = if desc.nullable {
563                    Some("null".into())
564                } else {
565                    None
566                };
567                builder = builder.property(crate::builders::ClassProperty {
568                    name: desc.name.into(),
569                    flags: desc.flags,
570                    default: None,
571                    docs: desc.docs,
572                    ty: Some(desc.ty),
573                    nullable: desc.nullable,
574                    readonly: desc.readonly,
575                    default_stub,
576                });
577            }
578            for (name, flags, default, docs) in T::static_properties() {
579                let default_stub = default.map(crate::convert::IntoZvalDyn::stub_value);
580                let default_fn = default.map(|v| {
581                    Box::new(move || v.as_zval(true))
582                        as Box<dyn FnOnce() -> crate::error::Result<crate::types::Zval>>
583                });
584                builder = builder.property(crate::builders::ClassProperty {
585                    name: (*name).into(),
586                    flags: *flags,
587                    default: default_fn,
588                    docs,
589                    ty: None,
590                    nullable: false,
591                    readonly: false,
592                    default_stub,
593                });
594            }
595            if let Some(modifier) = T::BUILDER_MODIFIER {
596                builder = modifier(builder);
597            }
598
599            builder
600                .flags(T::FLAGS)
601                .object_override::<T>()
602                .registration(|ce, arg_info| {
603                    T::get_metadata().set_ce(ce);
604                    T::get_metadata().set_arg_info(arg_info);
605                })
606                .docs(T::DOC_COMMENTS)
607        });
608        self
609    }
610
611    /// Adds an enum to the extension.
612    #[cfg(feature = "enum")]
613    pub fn enumeration<T>(mut self) -> Self
614    where
615        T: RegisteredClass + RegisteredEnum,
616    {
617        self.enums.push(|| {
618            let mut builder = EnumBuilder::new(T::CLASS_NAME);
619            for case in T::CASES {
620                builder = builder.case(case);
621            }
622            for (method, flags) in T::method_builders() {
623                builder = builder.method(method, flags);
624            }
625
626            builder
627                .registration(|ce, arg_info| {
628                    T::get_metadata().set_ce(ce);
629                    T::get_metadata().set_arg_info(arg_info);
630                })
631                .docs(T::DOC_COMMENTS)
632        });
633
634        self
635    }
636}
637
638#[cfg(feature = "observer")]
639impl<'a> ModuleBuilder<'a> {
640    /// Register a [`ZendExtensionHandler`] and configure which hooks PHP should
641    /// call.
642    ///
643    /// Returns a [`ZendExtensionBuilder`] that exposes three opt-in methods
644    /// (`hook_statements`, `hook_fcalls`, `hook_op_array_compile`). Call
645    /// [`ZendExtensionBuilder::finish`] to return to `ModuleBuilder`.
646    ///
647    /// # Example
648    ///
649    /// ```ignore
650    /// module
651    ///     .zend_extension(|| MyProfiler::new())
652    ///     .hook_statements()
653    ///     .finish()
654    /// ```
655    ///
656    /// # Panics
657    ///
658    /// Panics if called more than once on the same module.
659    ///
660    /// [`ZendExtensionHandler`]: crate::zend::ZendExtensionHandler
661    /// [`ZendExtensionBuilder`]: crate::zend::ZendExtensionBuilder
662    /// [`ZendExtensionBuilder::finish`]: crate::zend::ZendExtensionBuilder::finish
663    pub fn zend_extension<F, H>(
664        self,
665        factory: F,
666    ) -> crate::zend::zend_extension::ZendExtensionBuilder<'a>
667    where
668        F: Fn() -> H + Send + Sync + 'static,
669        H: crate::zend::ZendExtensionHandler,
670    {
671        crate::zend::zend_extension::ZendExtensionBuilder::new(self, factory)
672    }
673}
674
675/// Artifacts from the [`ModuleBuilder`] that should be revisited inside the
676/// extension startup function.
677pub struct ModuleStartup {
678    #[cfg(feature = "observer")]
679    name: String,
680    #[cfg(feature = "observer")]
681    version: String,
682    constants: Vec<(String, Box<dyn IntoConst + Send>)>,
683    classes: Vec<fn() -> ClassBuilder>,
684    interfaces: Vec<fn() -> ClassBuilder>,
685    #[cfg(feature = "enum")]
686    enums: Vec<fn() -> EnumBuilder>,
687    /// Parameters of the module's functions to mark `#[\SensitiveParameter]`.
688    /// The engine registers the functions before MINIT, so `startup` can.
689    sensitive: SensitiveParameters,
690}
691
692impl ModuleStartup {
693    /// Completes startup of the module. Should only be called inside the module
694    /// startup function, which runs again when the SAPI starts the module again
695    /// in the same process (e.g. a `FrankenPHP` worker restart): everything is
696    /// registered anew each time.
697    ///
698    /// # Errors
699    ///
700    /// * Returns an error if a constant, interface, class or enum could not be
701    ///   registered. The generated MINIT then returns `FAILURE` and PHP refuses
702    ///   to start the module.
703    pub fn startup(&self, ty: i32, mod_num: i32) -> Result<()> {
704        for (name, val) in &self.constants {
705            val.register_constant(name, mod_num)?;
706        }
707
708        if !self.sensitive.is_empty() {
709            let table = crate::zend::CompilerGlobals::get().function_table;
710            mark_sensitive(table, &self.sensitive);
711        }
712
713        // Interfaces must be registered before classes so that classes can implement
714        // them
715        self.interfaces.iter().try_for_each(|c| c().register())?;
716
717        self.classes.iter().try_for_each(|c| c().register())?;
718
719        #[cfg(feature = "enum")]
720        self.enums
721            .iter()
722            .try_for_each(|builder| builder().register())?;
723
724        // Initialize observer systems if registered
725        #[cfg(feature = "observer")]
726        unsafe {
727            crate::zend::observer::observer_startup();
728            crate::zend::error_observer::error_observer_startup();
729            crate::zend::exception_observer::exception_observer_startup();
730            crate::zend::zend_extension::zend_extension_startup(&self.name, &self.version);
731        }
732
733        // SAFETY: this runs in MINIT, and the hook goes in last so that no
734        // failed step leaves it installed.
735        unsafe { sapi_activate::install(ty) }
736    }
737}
738
739/// A function to be called when the extension is starting up or shutting down.
740pub type StartupShutdownFunc = unsafe extern "C" fn(_type: i32, _module_number: i32) -> i32;
741
742/// A function to be called when `phpinfo();` is called.
743pub type InfoFunc = unsafe extern "C" fn(zend_module: *mut ModuleEntry);
744
745impl ModuleBuilder<'_> {
746    /// Checks that no two functions share a PHP name. The engine compares
747    /// function names ignoring ASCII case.
748    fn validate(&self) -> Result<()> {
749        match first_duplicate(self.functions.iter().map(|f| f.name.as_str()), true) {
750            Some(name) => Err(crate::error::Error::DuplicateFunction {
751                function: name.to_owned(),
752            }),
753            None => Ok(()),
754        }
755    }
756}
757
758/// Builds a [`ModuleEntry`] and [`ModuleStartup`] from a [`ModuleBuilder`].
759/// This is the entry point for the module to be registered with PHP.
760impl TryFrom<ModuleBuilder<'_>> for (ModuleEntry, ModuleStartup, ModuleAllocations) {
761    type Error = crate::error::Error;
762
763    #[allow(clippy::too_many_lines)]
764    fn try_from(builder: ModuleBuilder) -> Result<Self, Self::Error> {
765        builder.validate()?;
766        let mut arg_info = Vec::with_capacity(builder.functions.len());
767        let mut function_table = Vec::with_capacity(builder.functions.len() + 1);
768        let mut sensitive = SensitiveParameters::new();
769        for function in builder.functions {
770            sensitive.extend(function.sensitive());
771            let (entry, args) = function.build()?;
772            function_table.push(entry);
773            arg_info.push(args);
774        }
775        function_table.push(FunctionEntry::end());
776        let function_table = function_table.into_boxed_slice();
777        let functions = function_table.as_ptr();
778
779        #[cfg(feature = "observer")]
780        let ext_name = builder.name.clone();
781        #[cfg(feature = "observer")]
782        let ext_version = builder.version.clone();
783
784        sapi_activate::set_callback(builder.sapi_activate);
785
786        let owned_name = CString::new(builder.name)?;
787        let owned_version = CString::new(builder.version)?;
788        let name = owned_name.as_ptr();
789        let version = owned_version.as_ptr();
790
791        let startup = ModuleStartup {
792            #[cfg(feature = "observer")]
793            name: ext_name,
794            #[cfg(feature = "observer")]
795            version: ext_version,
796            constants: builder
797                .constants
798                .into_iter()
799                .map(|(n, v, _)| (n, v))
800                .collect(),
801            classes: builder.classes,
802            interfaces: builder.interfaces,
803            #[cfg(feature = "enum")]
804            enums: builder.enums,
805            sensitive,
806        };
807
808        #[cfg(not(php_zts))]
809        let module_entry = ModuleEntry {
810            size: mem::size_of::<ModuleEntry>().try_into()?,
811            zend_api: ZEND_MODULE_API_NO,
812            zend_debug: u8::from(PHP_DEBUG),
813            zts: u8::from(PHP_ZTS),
814            ini_entry: ptr::null(),
815            deps: ptr::null(),
816            name,
817            functions,
818            module_startup_func: builder.startup_func,
819            module_shutdown_func: builder.shutdown_func,
820            request_startup_func: builder.request_startup_func,
821            request_shutdown_func: builder.request_shutdown_func,
822            info_func: builder.info_func,
823            version,
824            globals_size: builder.globals_size,
825            globals_ptr: builder.globals_ptr,
826            globals_ctor: builder.globals_ctor,
827            globals_dtor: builder.globals_dtor,
828            post_deactivate_func: builder.post_deactivate_func,
829            module_started: 0,
830            type_: 0,
831            handle: ptr::null_mut(),
832            module_number: 0,
833            build_id: unsafe { ext_php_rs_php_build_id() },
834        };
835
836        #[cfg(php_zts)]
837        let module_entry = ModuleEntry {
838            size: mem::size_of::<ModuleEntry>().try_into()?,
839            zend_api: ZEND_MODULE_API_NO,
840            zend_debug: u8::from(PHP_DEBUG),
841            zts: u8::from(PHP_ZTS),
842            ini_entry: ptr::null(),
843            deps: ptr::null(),
844            name,
845            functions,
846            module_startup_func: builder.startup_func,
847            module_shutdown_func: builder.shutdown_func,
848            request_startup_func: builder.request_startup_func,
849            request_shutdown_func: builder.request_shutdown_func,
850            info_func: builder.info_func,
851            version,
852            globals_size: builder.globals_size,
853            globals_id_ptr: builder.globals_id_ptr,
854            globals_ctor: builder.globals_ctor,
855            globals_dtor: builder.globals_dtor,
856            post_deactivate_func: builder.post_deactivate_func,
857            module_started: 0,
858            type_: 0,
859            handle: ptr::null_mut(),
860            module_number: 0,
861            build_id: unsafe { ext_php_rs_php_build_id() },
862        };
863
864        Ok((
865            module_entry,
866            startup,
867            ModuleAllocations {
868                functions: function_table,
869                arg_info: arg_info.into_boxed_slice(),
870                name: owned_name,
871                version: owned_version,
872            },
873        ))
874    }
875}
876
877#[cfg(test)]
878mod tests {
879    use crate::test::{
880        test_deactivate_function, test_function, test_info_function, test_startup_shutdown_function,
881    };
882
883    use super::*;
884
885    #[test]
886    fn test_new() {
887        let builder = ModuleBuilder::new("test", "1.0");
888        assert_eq!(builder.name, "test");
889        assert_eq!(builder.version, "1.0");
890        assert!(builder.functions.is_empty());
891        assert!(builder.constants.is_empty());
892        assert_eq!(builder.classes.len(), 0);
893        assert_eq!(builder.interfaces.len(), 0);
894        assert!(builder.startup_func.is_none());
895        assert!(builder.shutdown_func.is_none());
896        assert!(builder.request_startup_func.is_none());
897        assert!(builder.request_shutdown_func.is_none());
898        assert!(builder.post_deactivate_func.is_none());
899        assert!(builder.info_func.is_none());
900        #[cfg(feature = "enum")]
901        assert_eq!(builder.enums.len(), 0);
902    }
903
904    #[test]
905    fn functions_that_differ_only_by_case_fail_the_module_build() {
906        let builder = ModuleBuilder::new("test", "1.0")
907            .function(FunctionBuilder::new("say_hello", test_function))
908            .function(FunctionBuilder::new("Say_Hello", test_function));
909        let built = <(ModuleEntry, ModuleStartup, ModuleAllocations)>::try_from(builder);
910        assert!(matches!(
911            built,
912            Err(crate::error::Error::DuplicateFunction { function }) if function == "Say_Hello"
913        ));
914    }
915
916    #[test]
917    fn test_name() {
918        let builder = ModuleBuilder::new("test", "1.0").name("new_test");
919        assert_eq!(builder.name, "new_test");
920    }
921
922    #[test]
923    fn test_version() {
924        let builder = ModuleBuilder::new("test", "1.0").version("2.0");
925        assert_eq!(builder.version, "2.0");
926    }
927
928    #[test]
929    fn test_startup_function() {
930        let builder =
931            ModuleBuilder::new("test", "1.0").startup_function(test_startup_shutdown_function);
932        assert!(builder.startup_func.is_some());
933    }
934
935    #[test]
936    fn test_shutdown_function() {
937        let builder =
938            ModuleBuilder::new("test", "1.0").shutdown_function(test_startup_shutdown_function);
939        assert!(builder.shutdown_func.is_some());
940    }
941
942    #[test]
943    fn test_request_startup_function() {
944        let builder = ModuleBuilder::new("test", "1.0")
945            .request_startup_function(test_startup_shutdown_function);
946        assert!(builder.request_startup_func.is_some());
947    }
948
949    #[test]
950    fn test_request_shutdown_function() {
951        let builder = ModuleBuilder::new("test", "1.0")
952            .request_shutdown_function(test_startup_shutdown_function);
953        assert!(builder.request_shutdown_func.is_some());
954    }
955
956    #[test]
957    fn test_set_post_deactivate_function() {
958        let builder =
959            ModuleBuilder::new("test", "1.0").post_deactivate_function(test_deactivate_function);
960        assert!(builder.post_deactivate_func.is_some());
961    }
962
963    #[test]
964    fn test_set_info_function() {
965        let builder = ModuleBuilder::new("test", "1.0").info_function(test_info_function);
966        assert!(builder.info_func.is_some());
967    }
968
969    #[test]
970    fn test_add_function() {
971        let builder =
972            ModuleBuilder::new("test", "1.0").function(FunctionBuilder::new("test", test_function));
973        assert_eq!(builder.functions.len(), 1);
974    }
975
976    #[test]
977    #[cfg(feature = "embed")]
978    fn test_add_constant() {
979        let builder =
980            ModuleBuilder::new("test", "1.0").constant(("TEST_CONST", 42, DocComments::default()));
981        assert_eq!(builder.constants.len(), 1);
982        assert_eq!(builder.constants[0].0, "TEST_CONST");
983        // TODO: Check if the value is 42
984        assert_eq!(builder.constants[0].2, DocComments::default());
985    }
986}