PHP zval

PHP uses the zval structure as an all in one data management structure. On the 64-bit CPU's and parallel data lines, where data addresses are 64 bits, a zval is an optimal size. Two 64-bit words, one to hold the value of a piece of data, the second is for meta-data. The meta-data is essential to interpret how to treat the bits in the value word.

PHP passes an array of zval structures as function arguments for every function call in zend_execute_data structure. A pointer to this structure is passed to any internal function which is implementing the call. The job of every function and object method registered to PHP is to first query the meta-data of the parameters, and check that they fit those allowed by its parameter declarations.

After a registered function does its parameter checks, it may extract its data, do some processing, call some more functions, and finally return a value to the second parameter passed to it, which is another zval pointer usually labelled as return_value.

To do our checks zpp uses a val_ptr C structure which is initialised with a pointer to zval structure. Its only member is that address, so it takes up the same memory space. There are some cheap check methods zpp::val_ptr has, that can be to establish that a random zval address contains the sort of value that might be required.

A zval is an implementation of a well-defined variant paradigm. Its generic description is "data + identity tag". The C header definition below is from the source file "Zend/zend_type.h", of a PHP recent version 8.5. zend_value, is the data, the "data" is a C union of a std::int_64 (zend_long), and a double, and pointer types to storage of many kinds, labelled as "zend_value".

What the contents actually mean depends on the first member of the metadata, its identiy tag. The details of this are wrapped with a C-macro "ZEND_ENDIAN_LOHI_3", which actually does nothing to the layout when compiled for a little endian Intel CPU. This has been placed so that the "type" tag is the most important, as it is positioned at the lowest address in its definition structure, at the "little" end, and therefore the most efficient to access.

All the PHP C-macros that read the type such as Z_TYPE_P(x) , refer to a inlined function "uint8_t zval_get_type(const zval*)".

This is frequent pattern in the PHP source. Exactly why, is surely about compiling for so many different platforms. How much of this is historical reasons, or for idiosyncratic optimizing compilers or CPU archecture, or just because code is so old, no one remembers just why is it so. In any case PHP and its extensions have thousands of tests to validate a build, all of which in turn are dependencies that maintain each other.

A lot of code in PHP is using low level macros is thus "inlined", as part of the quest for fast execution. And macros like Z_TYPE(p_) are easier to remember than p_->u1.v.type. It shows how much compiler optimization is essential and can be very deep, and also at times confounding.

Methods of zpp::val_ptr to get the type just pull out the type.


// The metadata part of a zval is taken up by two uint32_t union type, u1 and u2.
// Amazing how this space is so utilized.
struct _zval_struct {
    zend_value        value;			/* union of value types  */
    union {
        uint32_t type_info;
        struct {
                    ZEND_ENDIAN_LOHI_3(
                        uint8_t    type,			/* active type */
                        uint8_t    type_flags,
                        union {
                            uint16_t  extra;        /* not further specified */
                        } u)
                } v;
        } u1;
union {
        uint32_t     next;                 /* hash collision chain */
        uint32_t     cache_slot;           /* cache slot (for RECV_INIT) */
        uint32_t     opline_num;           /* opline number (for FAST_CALL) */
        uint32_t     lineno;               /* line number (for ast nodes) */
        uint32_t     num_args;             /* arguments number for EX(This) */
        uint32_t     fe_pos;               /* foreach position */
        uint32_t     fe_iter_idx;          /* foreach iterator index */
        uint32_t     guard;                /* recursion and single property guard */
        uint32_t     constant_flags;       /* constant flags */
        uint32_t     extra;                /* not further specified */
    } u2;
};

/* a trail of C macros for Z_TYPE finally use this inline PHP function */

static zend_always_inline uint8_t zval_get_type(const zval* pz) {
    return pz->u1.v.type;
}

So when source code in zpp::val_ptr uses Z_TYPE_P(p_) it should convert to p_->u1.v.type, a data value at a specific place in memory of type uint8_t.

val_ptr

val_ptr holds a zval*, given by PHP from a function call, or from inside an array. val_ptr does not do automatic reference counting on its content in constructor or destructor. There is no declared destructor function. val_ptr merely copies a zval* to its only internal member value, zval* p_, for further inspection and/or work.

The main externally used purpose of val_ptr, is to pass along zval* without reference counting, and read its enclose value type, and extract its encloses PHP types without altering the value within, as most functions are delared as () const;

The val_ptr does have some protected methods which will increment its reference count. These are used by some methods of the val_rc class, htab_ptr and htab_rw class, which declared as "friends".

There are also some static methods, inlined as declared in the val_ptr header. These are string_bind, object_bind, and array_bind. They so not increment their stored values reference count. This is because where used the increment happens only on success of the operation, usually a write to a HashTable, or in setting an object property. As this is mostly successful, the code really ought to increment the reference count, and undo only on unexpected failure. But it is to allow the use of "throwaway" temporary plain zval structure, increment not done, and also no need for a destructor with a check for reference decrement.

The author decided to indulge further and return a boolean value from string_bind, object_bind, and array_bind to be true if value is reference counted.

If the contained zval* is a nullptr, isNull() returns true, and ok() returns false. Method is_nullptr() returns true only for the specific case of containing a nullptr.

class val_ptr {
protected:
    zval *p_;
//...
public:

int ztype() const {
        if (!p_)
                {
                    // nullptr
            return IS_UNDEF;
                }
        return p_->u1.v.type; //Z_TYPE_P(p_);
}

// ultimately returnable value type
int  ref_type() const;

//....

};

The result from the inlined method ztype() cannot be relied apon to give up the value type that can actually retrieved via a zval*. PHP has reference type, IS_REFERENCE, which means the zval contains a handle, which is reference counted, which contains its own embedded zval. To distinguish the ultimately returned value, from an arbitrary zval*, this method checks for IS_REFERENCE or IS_INDIRECT, and if either of these, returns their ztype(). The chance of having more than one level of indirection recursivity is ignored.

The method isEmpty() also checks for reference type, and tries to have the same foible behaviour as PHP empty() function. The method ok() does not have a PHP exact equivalent, although isset() comes close. It returns true, if the value is likely to be interesting. Here this is defined as if the zval* has a value that is IS_TRUE or worth retrieving. Empty array or empty string return false, but all numeric values return true, but IS_UNDEF, IS_NULL, IS_FALSE all return false.

// How zval temporary is used to set a string property
void obj_ptr::property(str_ptr key, str_ptr value)
{
    zval temp = {};
    // No rc++, because zval is thrown away on exit.
    val_ptr::string_bind(&temp, value);
    property(key, val_ptr(&temp));
}

// How zval temporary is assigned a specific type
void htab_rw::push_back(zend_string* zs)
{
    zval tmp = {};
    bool refct = val_ptr::string_bind(&tmp,zs);

    if (zend_hash_next_index_insert(ht_, &tmp))
    {
        // avoid double checks
        if (refct) GC_ADDREF(zs);	
    }
}

// the static try_addref methods are type specific and also likely to be inlined
// 
static void str_rc::try_addref(zend_string* zs)
        {
            if (GC_TYPE_INFO(zs) & IS_STR_INTERNED)
            {
                return;
            }
            GC_ADDREF(zs);
        }

These methods are for inner part of the workings of some operators and classes of zpp, and should hardly ever be used externally by other C++ class code.

All of this list below of "isXXX" methods have the same pattern as "bool isXXXXX() const;".

isEmpty, isArray, isBoolean, isCallable, isDouble, isFalse, isLong, isNull, is_nullptr, isObject, isPointer, isReference, isResource, isString, isTrue, ok, isset.

//! method to check contained PHP type
int  ref_type() const;

Value coercion

There are more "const" methods of val_ptr. These try to fetch the type of the return value. Strings can be coerced to numbers, and other values possibly coerced to a string.

Get string types

// in val_ptr{public:
      /** Return as managed zend_string wrapper, or as a coerced string */
        str_rc  to_zstr() const;

    //! return  the  internal zend_string* , else nullptr
    zend_string* zstr() const;

    //! returned value as a string. A std::string with PHP request memory allocated.
    rqstring  cstr() const;

    //! return string_view pointing to value, if IS_STRING, or empty string constant
    std::string_view vstr() const;
        
        //! return zend_string* pointer,  if length > 0
    bool getStringData(zend_string** retstr = nullptr) const ;

Get data types

    //! return interned class name string if an object, else nullptr
    zend_string* className() const;

    //! return  the zend_object* pointer, else nullptr
    zend_object* zobject() const;
        
        //! return HashTable* pointer or nullptr
        HashTable* zarray() const;
        
//! return or convert to double
    double  get_double() const;

    //! return or convert to boolean
    bool get_bool() const; 

    //! return or convert to long
    zend_long get_long() const;

Static val_ptr::h_bind(zval*) methods

These are for convenience, as used by the htab_rw class, where binding flags on a zval, and a possible increment of reference count are separated by a bit of logic. This is because zval "type_flags" are normally set along with the type number, for data that requires zval garbage collection management, and arrays might try to delete immutable data or interned strings if zval containing them has garbage collection flags set.

Each static method for a PHP data handle type, binds to the passed zval* , according to its need to have special flags set in the zval, and returns a bool value that indicates if reference count update is required.

If the binding returns a boolean value of true, a call to the generic C macro GC_ADDREF( handle ) is required, only if a zval destructor process is expected later, which will cause premature deletion, and may leave a dangling pointer. This is the case in obj_ptr property setting functions.

In some cases, such as using the zpp::fn_call classes to make calls to PHP functions, a destructor call is unnecessary, and so a reference count increment should not be made.

These are used for some internals of zpp classes, and setting values of zval parameters when making calls to PHP functions.

// in val_ptr{public:
// return true if reference count increment required

static bool string_bind(zval* zt, zend_string* s);
static bool array_bind(zval* zt, HashTable* ht);
static bool object_bind(zval* zt, zend_object* obj);