Module initialization - zpp::state_init

ZPP classes create and use some C++ static lookup data structures, for use of request class methods and function calls. There are also class manager instances declared "static" inside each kind of C++ zend_object class implementation. These are all created as "read-only" after the constructor call.

It seems that PHP interns every string constant that it reads duing load when compiling to byte-code. These values are saved in an indexed common table, so that only one instance of each unique string exists. It is only fair to use this available facility with a zpp::str_intern class, that does the same, and will use the stored instance of any interned string that is already allocated. Accordingly nearly every class example as a static instance derived from zpp::state_init that has many interned strings, include those of function names it may have or call.

Classes derived from zpp::state_init can also mix in static HashTable structures.

class Route_init : public zpp::state_init {
// constructor called by default
public:
    str_intern GET_S;
    str_intern POST_S;
    //...
    HashTable  route_verbs;
    HashTable  verb_names;
    //..
    void init() override;
    ...
};

void Route_init::init() 
{
    zend_hash_init(&route_verbs, 16, NULL, nodestroy,1);
    zend_hash_init(&verb_names, 16, NULL, nodestroy,1);
    GET_S = "GET";
    POST_S = "POST";
    //...
}

void Route_init::end() 
{
    freehtmemory(&verb_names);
    freehtmemory(&route_verbs);
}

zpp::state_init derived classes get linked in a single linked list during static initialisation, and have virtual call back methods for module start and end, and request start and end. If they are used in more than one module, it is important that only one of the modules (extension), usually the one with the zpp classes binary, actually calls the list traversal for the events. Other extensions will automatically link their static class variants into that list.


 class  state_init {
    protected:
        static state_init* first_;
        static state_init* last_;

        state_init* next_;
public:
        virtual ~state_init()
                
// At module start/end (Call in one extension only)
        static void init_all();
        static void end_all();

// At request start/end  (Call in one extension only)
        static void  init_request();
        static void  end_request();

// override module init/end calls for permanent / interned data
        virtual void init();
        virtual void end();

// override request init/end calls for request lifetime data, like object instances.
        virtual void init_req();
        virtual void end_req();
}

In the init() function, zend_hash_init needs to be called. In the end() function, freehtmemory(&ht) works. This works if the string keys are already interned. This was done in wcc/route.cpp Route_init class.

Interned string class zpp::str_intern can also be used as std::map values, as done in the wcc/global_response.cpp in the Response_init class, to lookup status code strings. The map structure was initialized using a C++ initializer inside its Response_init::init() method.

Request initialization

The base constructor of zpp::state_init links itself into a single linked list, so make sure derived class constructors call it. All linked nstances are iterated during module initialize, request initialize, request shutdown and module shutdown.

Currently, in zpp::fn_call.pp, a large number of fn_call class instances are declared as public inside a standalone class "TLfnTable which is instanced as "thread_local". Which means that an instance is created for every new thread. It does contain a "configured" flag, in case a thread is used for multiple request events. This initialisation is checked during an init_req() call. Here all of the interned string function names have already been set by the module init() call. Various wrapper function calls forward their parameters to a corresponding function call structure. The author is not sure if this is all entirely necessary, and hopes the "configured" flag only initializes once.

For instance the implementation of Wcc\Plate, in wcc/plate.cpp, has such a class, with some simple function call objects, which are setup in normal static storage at module init time.

// In zpp/fn_call.cpp

thread_local TLfnTable TLFNs;

void fntable::init_req()
{
    //zend_printf("init_req\n");

    TLFNs.init(*this);
}
//....
str_rc 
dirname(str_ptr path, int level)
{
    return TLFNs.get_dirname.call(path, level);
}

// In wcc/plate.cpp, called last by PlateInit::init()

void
OBtable::init()
{
    obstart.set_fname(PLD.obstart_fn);
    obgetclean.set_fname(PLD.obgetclean_fn);
    obgetlevel.set_fname(PLD.obgetlevel_fn);
    obendclean.set_fname(PLD.obendclean_fn);
    obgetcontents.set_fname(PLD.obgetcontents_fn);
}

Module Initialization

Interned strings

PHP script compilation turns all string contents into "interned" strings, which ensures that one unique zend_string* exists in a shared table across all its interpreter compiled units. Classes using zpp can make use of this, by creating a class based on zpp::state_init, and store instances of zpp::str_intern during PHP module initialization. This will minimize run-time conversion of embedded C-style strings into things like array keys, with direct reference to unchanged str_intern values for every iteration or request.

I suspect that the PHP-CPP code has some impositions on efficiency in its design, due to using a single Value class wrapper for all PHP types. It uses an extra class "HashMember" to return values of Arrays, to implement a convenience operator[], and so has a few overheads in its C++ structure management which could be elided.

Debugged reference count management

This is a remembered taste a few of the problems encountered, which were required to be nailed down and fixed, during work with earlier versions of the ZPP classses. Which classes had which functions and returned what.

After a segfault or execution failure, there was a track down memory leaks due to mistake somewhere in managing PHP reference counts. This required compiling a debug version of PHP which added extra memory tracking information and checking to its data structures. Sometimes all the compile optimization -O2 was turned off, which didn't always help.

The debug version of PHP mains memory tracking fences around its objects, and prints out information about unfreed memory at the end of a script request.

As a flavor, here is a direct copy and pasted output of a recent example of such a leak, which was later fixed.

[Tue Apr 15 23:24:06 2025]  Script:  '/home/michael/www/wcp/test/xmlread.php'
/home/michael/dev/php-8.4.5/Zend/zend_string.h(176) :  Freeing 0x00007f4f91203b40 (32 bytes), script=/home/michael/www/wcp/test/xmlread.php
Last leak repeated 3 times.

Its good to have all the sources of these fixed, because when trying out new C++ code for extension, it can normally blamed on the latest new code.

Minizing the use of *_rc objects reduced reference count management overhead, and the number of places where reference counting bugs might occur, as long as an array returned value to _ptr wasn't unset in the meantime.

In fact a lot of time developing earlier versions of this zpp classes suite, was learning how to make typical C++ operators and methods do the right thing with their managed PHP pointer types, with constructor, assignments and destructor. Also setting array values must ensure the zval flags for garbage collection during array destruction, are not marked inappropriately for interned or constant values. It took a while to figure out how this might happen.

There are a couple of zend_string API functions, that may or may not return a new string, like zend_string_tolower, but which always return a refence count bump even if the same string is returned. This still seems perverse. And C++ assignment operators got stumped by this, especially when the zend_string gets assigned back to the same class instance, that still has it. And PHP code tends to require lots of string manipulation and building, and who doesn't like reusing variables?

As a mitigation, the author resorted moving these functions from the zpp::str_ptr to the zpp::str_rc class, and changed code in some places where it might happen, to just avoiding this everywhere, just in case,


str_rc a_str = some_function();
// This was leaking a rc++
a_str = a_str.to_lower();
// This was still safe to do.
str_rc b_str = a_str.to_lower();

// This currently works ok, but feels crazy
a_str.lowercase();

// current implementation 
void
str_rc::lowercase() 
{
    if (s)
    {
        // always adds a reference count
        zend_string* p = zend_string_tolower(s);
        if (p == s) // just the same but another count was added!
        {
            try_decref(p); // undo unwanted rc++
        }
        else {
            adopt(p);  // take up new pointer
        }
    }
}

str_rc 
str_rc::to_lower() 
{
    str_rc result(*this);
    if (result.ok())
    {
        result.lowercase();
    }
    return result;
}

Passing direct parameters to zend functions.

To minimize use of casting when calling zend API functions, the string, object and array and value wrappers all have casting operators to automatically pass the enclosed pointer type, like this.

// obj_ptr Inline cast to the enclosed pointer type.
operator zend_object* () const { return (zend_object*) obj_; }

Use PHP's extension class development system

ZPP builds use the current PHP extension build process, starting with a extension skelaton, a folder generated from a PHP distribution. Extension class interface files of "class_arginfo.h" are generated from "class.stub.php" files. This generate all the class object function names and signatures. The generated registration code for class registration, also includes setup of class constants, and will even add class properties that are declared in a "stub.php" file.

For C++ source, need to specify C++ compiler specified in the "config.m4" file, instead of a C compiler. Here is the config.m4 lines from the wcc extension project. All *arginfo.h files (and included php source files) get included inside an extern "C" {} wrap, and each ZEND_FUNCTION can then coded in the normal way.

It would be difficult to discuss newer build systems, eg meson, without any experience building PHP extensions with them yet.

dnl Everything is compiled from the one file.
PHP_ARG_ENABLE([wcc],
  [whether to enable wcc support],
  [ --enable-wcc], [Enable wcc support.])

if test "$PHP_WCC" != "no"; then

  AC_DEFINE(COMPILE_DL_WCC, 1, [ Have wcc support ])
  
  FLAGS="-fPIC"
  CXXFLAGS="$CXXFLAGS -Wall -O2 --std=c++23 -I./include"
  
  PHP_REQUIRE_CXX()
  AC_LANG([C++])
  
  PHP_NEW_EXTENSION(wcc, wcc.cpp , $ext_shared, , $FLAGS)
fi

The build process

In preparation for code builds, an initialization step of "phpize" command needs to be done first, followed by ".\configure". A build using "make", and install using "(sudo) make install", should then work with the settings of the current configured PHP enviroment.

In this project the _stub.php and _arginfo.h files exist in the /stub folder, and a shell script build.sh calls the make command for each name individually.

ZPP is used and distributed as C++ source code only. If an extension has compiled this into its own binary (shared library) then only the C++ headers of the very same version (and compiler name mangling) are required, since two shared libraries with the same zpp binary code will behave rather badly.

Multiple extensions using ZPP should each have their own compiled version of the zpp namespace code. Linkage to other code libraries is not prohibited. Next chapter to step through the process of making such an extension.

Shared access and exceptions

In linux OS, static variables declared extern are shared in the process memory space. I have abandoned windows, apart from some old virtual images, and only keep a Mac for hosting aarch64 linux virtuals.

On linux the nm utility and a few others show which symbols exist, and have addresses, or are unknown, and might so cause a link-load error. Symbols used, but found in other modules, are marked with "U" for unknown address. A way to void clashes of shared symbol names, and rectify missing or unfilled symbol addresses is required.

Getting into mischief with C++ exceptions encouraged me to avoid using them altogether in this environment. All extension class methods will need to pass errors manually back up, ultimately to create a zend_throw_error, which returns and the zend interpreter only throws the error after method return. This is a later on decision, and only some classes worked on later on, have this. The class template to do this, returns an error string, along with some other "normal path" return type, is defined in zpp::bireturn.h. Once an error is set, it should be discovered on checking, handled or returned back up the call chain, finally to where the PHP function call is handled.

struct error_return {
    str_buf*  errors_;
    // Other usual methods C++ likes to have
};

template <typename T>
struct bireturn  : public error_return 
{
    T   	  value_;
    // Other usual methods C++ likes to have
};

Namespaces and mangling.

C++ has a famous (practical? reasonable?) solution, in using namespaces, and mangle garbled names of namespaces, functions and their parameter types. Fortunately these are reversible for finding out where something is wrong.

Here is an example from extension modules used later in this book.

''' /* wccz.so includes the source code zpp/fn_call.cpp, where FTAB is a static instance. It contains static declarations of interned strings and callable PHP functions. B means "The symbol is in the BSS data section." */

nm -D --demangle wccz.so | grep FTAB 000000000005d560 B zpp::FTAB

/* wccr includes and references headers zpp/fn_call.h, where FTAB is declared, but its address is "Unknown". It will call this symbols address at some time. The contents and offsets of its "U" are not exported, but are embedded in the compiled code, which means the same version of the headers, and accessing code is required by all referring symbol tables in different extensions. Symbols can be data or functions. */

nm -D --demangle wccr.so | grep FTAB U zpp::FTAB

/* on loading, wccr.so, most symbols are "resolved" into addresses. Otherwise if not found, such when not resolved because no real owner module is not loaded, an error exception is thrown. */

A utility called c++filt was used to demangle such cryptic link errors from PHP into readable form.

Run simple PHP test scripts

When faced with puzzling errors, make scripts to reproduce it in the simplest way, to allow valgrind or other tricks to expose the cause. The web classes and scripts also can be made to work from the command line.