Some function calls can be made directly to the C API of other PHP extensions. Usually such function names are declared as external API, conventionally begin with php_, and are found as declared in the C header files in the extension source. These can be coded directly by including the header file, and compiling, with suitable data arguments.
However a majority of scripted functionality, such is registered on load with the reflection API, is only available by going through the zend interpreter, after module is loaded and so registered. It is callable by names of functions, classes and object methods. Such "callables" that are more frequently used can have their interpreter discovered low-level details cached to speed up subsequent calls.
Setting up C++ cached versions of PHP functions for frequently used callables requires a bit of preparation setup.
It seems a good idea to intern string the desired class, function or method names, so they are already available with each request.
Calling a PHP registered function, at a low level from C/C++ involves setting up the "zend_fcall_info" structure.
For a global function call, it needs the name of the function, and a pointer to a block of zval structures for arguments. Optionally a HashTable pointer for use of positional index, or named arguments can be set.
For an object method call, a pointer to the zend_object is also required. And for all calls a pointer to a zval struct is required to hold the returned value.
The PHP API function used is zend_call_function.
// As pasted from recent PHP source.
typedef struct _zend_fcall_info {
size_t size;
zval function_name;
zval *retval;
zval *params;
zend_object *object;
uint32_t param_count;
/* This hashtable can also contain positional arguments (with integer keys),
* which will be appended to the normal params[]. This makes it easier to
* integrate APIs like call_user_func_array(). The usual restriction that
* there may not be position arguments after named arguments applies. */
HashTable *named_params;
} zend_fcall_info;
ZEND_API zend_result zend_call_function(zend_fcall_info *fci,
zend_fcall_info_cache *fci_cache);
typedef struct _zend_fcall_info_cache {
zend_function *function_handler;
zend_class_entry *calling_scope;
zend_class_entry *called_scope;
zend_object *object; /* Instance of object for method calls */
zend_object *closure; /* Closure reference, only if the callable *is* the object */
} zend_fcall_info_cache;
The zend_fcall_info_cache must be zeroed out before the first time call usage. Its values are filled in by lookups done prior to making the call. Subsequent calls to the same function are optimized by Zend re-using the cached information.
This means that it pays to have frequently used functions keep the call cache information around. The following C++ classes have been through a few revisions, to try and be clear about flexible and error-free coding usage.
The zpp::fn_call structure contains these zend provided call - caching structures. It can be usefully created at module initialisation time with interned names, or dynamically during request time inside another C++ class or function.
// From zpp/fn_call.h
class fn_call {
protected:
zend_fcall_info fci_;
// PHP call cache info for multiple calls
zend_fcall_info_cache cache_;
void init_f();
friend class fn_result; // This class will do the management work.
public:
fn_call();
fn_call(zend_string* method);
fn_call(zend_string* method, zend_object* obj);
~fn_call();
void set_fci(zend_string* method, zend_object* obj = nullptr);
void set_obj(zend_object* obj); // for method calls
};
/* The fn_result class , has space for a function result,
and is initialised with a reference to a fn_call.
The call is done using the call_fn() method.
For no parameters, the fn_noparams class should be used,
to ensure setParams is called.
Function call information can be setup from here,
but maybe cached elsewhere. So making a call can be done
from the stack, without losing cached call information.
*/
class fn_result {
protected:
fn_call& cfi_;
fn_result(fn_call& fn) : cfi_(fn), result_({0})
{
cfi_.fci_.retval = &result_;
}
fn_result(fn_call& fn, zend_object* obj) : cfi_(fn), result_({0})
{
cfi_.fci_.retval = &result_;
cfi_.set_obj(obj);
}
public:
zval result_;
void named_args(HashTable* ht)
{
cfi_.fci_.named_params = ht;
}
void set_obj(zend_object* c)
{
cfi_.set_obj(c);
}
void setParams(zval* p, size_t ct, HashTable* nargs = nullptr)
{
auto& ci = cfi_.fci_;
ci.param_count = ct;
ci.params = p;
ci.named_params = nargs;
if (ct) {
std::memset(p, 0, ct*sizeof(zval));
}
}
bool call_fn();
/** Various return types */
val_rc mixed();
str_rc str();
obj_rc obj();
bool zbool();
htab_rc array();
zend_long zlong();
}
/*
Actual calls should be done from these classes,
according to the number of parameters to be passed,
from none, to ARGCT
*/
class fn_noparams : public fn_result {
public:
fn_noparams(fn_call& fn) : fn_result(fn) {
setParams(nullptr, 0);
}
fn_noparams(fn_call& fn, HashTable* nargs) : fn_result(fn)
{
setParams(nullptr, 0, nargs);
}
};
template <size_t ARGCT>
class fn_params : public fn_result {
public:
zval params[ARGCT];
fn_params(fn_call& fn) : fn_result(fn)
{
setParams(¶ms[0], ARGCT);
}
fn_params(fn_call& fn, HashTable* nargs) : fn_result(fn)
{
setParams(¶ms[0], ARGCT, nargs);
}
zval* argsptr() { return params; /*¶ms[0];*/ }
};
Function call layout strategy
The source file zpp/fn_call.cpp illustrates the fn_call reuse strategy. Function call names are declared as str_intern inside a state_init derived structure, so they are created at module initialization. These are declared as static C++ structures in the source file, to be set in single linked list of them, just after any class registrations. This ensures the virtual function calls to "init()" and "init_req()" will be made.
// From zpp/fn_call.cpp
namespace zpp {
// static and externals
fntable FTAB;
strtable STAB;
void register_fn_calls()
{
STATE_INIT_ADD(FTAB);
STATE_INIT_ADD(STAB);
}
class TLfnTable {
public:
TLfnTable() : configured_(false) {}
bool configured_;
//fn_simple_loader simple_loader;
fn_call addcslashes;
fn_call array_pop;
fn_call array_splice;
//....
void init(const fntable& ftab)
{
if (configured_)
{
return;
}
configured_ = true;
addcslashes.set_fci(ftab.s_addcslashes);
array_pop.set_fci(ftab.s_array_pop);
array_splice.set_fci(ftab.s_array_splice);
//...
}
};
// A necessity for thread_local declaration hasn't really been tested.
thread_local TLfnTable TLFNs;
The fn_call structures that are to be reused are declared as static "thread_local" storage. PHP requests correspond to threads in the multi-threaded server environment, or the main thread, in the serial request reuse envionment. A necessity for thread_local storage declaration has been imagined as useful , but hasn't really been tested in multithread build.
It is also possible to setup a reusable fn_call structure, in a C++ structure to be part of an object, or on the stack for reuse in a loop.
At init_req() call to a state_init variant, the functions are initialized with their permanent string names, and this can setup fn_call data.
Here is a couple of examples of fully wrapped calls to PHP functions. Care needs to be taken. Particularly with immutable or copy-on-write arguments.
The binding of the string arguments to a zval, can be dangerous with immutable strings, as using the default ZVAL_STR macros did at one time seem to flag zvals with immutable bindings as disposable. Hence the paranoia with which the binding is done here with val_ptr::string_bind. This static function returns a boolean value if a reference count increment was indicated, which gets ignored, but it sets up zval memory flags correctly, which is needed to all htab_rw updates to HashTable*.
Return values are assumed to have had reference counts upped by the called function.
str_rc
addcslashes(str_ptr s, str_ptr escapes)
{
fn_params<2> fn(TLFNs.addcslashes);
zval* pz = fn.argsptr();
val_ptr::string_bind(pz, (zend_string*) s);
val_ptr::string_bind(pz+1, (zend_string*) escapes);
return fn.str();
}
val_rc
array_pop(val_rc& array_ref)
{
fn_params<1> fn(TLFNs.array_pop);
htab_rw hw(array_ref); // must be writable
array_ref.make_ref(); // must be reference
//zend_printf("\nprepare 2 array_pop\n");
ZVAL_COPY_VALUE(fn.argsptr(), array_ref);
return fn.mixed();
}
htab_rc
array_splice(htab_rc& input, int offset, int length, htab_ptr replace)
{
fn_params<4> fn(TLFNs.array_splice);
zval* pz = fn.argsptr();
htab_rw hw(input); // make writable
val_ptr::array_bind(pz, input);
ZVAL_NEW_REF(pz, pz);
ZVAL_LONG(pz+1,offset);
ZVAL_LONG(pz+2, length);
if (replace.size())
{
val_ptr::array_bind(pz+3, replace);
}
else {
ZVAL_EMPTY_ARRAY(pz+3);
}
return fn.array();
}
The call to zend_call_function_ is only made in one place, by the fn_result class call_fn().
bool
fn_result::call_fn()
{
result_ = {0};
if (cfi_.fci_.size==0)
{
throw_failed();
}
else if (zend_call_function(&cfi_.fci_, &cfi_.cache_) == SUCCESS)
{
return true;
}
throw_failed();
return false;
}