bext-php 0.2.0

Embedded PHP runtime for bext — custom SAPI linking libphp via Rust FFI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/*
 * bext PHP SAPI — embeds the PHP interpreter into the bext Rust process.
 *
 * Two execution modes:
 *   1. Classic mode: one php_execute_script() per HTTP request
 *   2. Worker mode:  boot the application once, dispatch requests to a
 *                    long-running PHP loop via bext_handle_request()
 *
 * Worker mode eliminates per-request framework bootstrap (~3ms for Laravel,
 * ~5ms for Symfony), matching FrankenPHP's architecture.
 *
 * Supports PHP 8.2+ (NTS and ZTS).
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "bext_php_sapi.h"

/* ZTS: Force dynamic TSRM lookup path.
 * lld (Rust's linker) doesn't do TLS symbol interposition, so defining
 * our own _tsrm_ls_cache creates a separate copy from libphp.so's.
 * Undefine ZEND_ENABLE_STATIC_TSRMLS_CACHE BEFORE including headers
 * so EG()/SG()/PG()/CG() use tsrm_get_ls_cache() (a function call). */
#undef ZEND_ENABLE_STATIC_TSRMLS_CACHE

#include <sapi/embed/php_embed.h>
#include <main/php.h>
#include <main/SAPI.h>
#include <main/php_main.h>
#include <main/php_variables.h>
#include <main/php_ini.h>
#include <main/php_output.h>
#include <ext/standard/info.h>
#include <Zend/zend_exceptions.h>

#ifdef ZTS
#include <TSRM/TSRM.h>
#endif

#include <string.h>
#include <stdlib.h>
#ifdef __linux__
#include <sys/resource.h>
#endif

/* ---------------------------------------------------------------------------
 * Thread-local state
 * ---------------------------------------------------------------------------*/
static __thread bext_request_ctx *tls_request_ctx = NULL;
static __thread int tls_is_worker = 0;
static __thread int tls_worker_had_request = 0;

/* No ZEND_TSRMLS_CACHE_DEFINE — using dynamic path */

/* ---------------------------------------------------------------------------
 * SAPI callbacks
 * ---------------------------------------------------------------------------*/

static size_t bext_ub_write(const char *str, size_t str_length)
{
    if (!tls_request_ctx) return 0;
    return bext_sapi_ub_write(tls_request_ctx, str, str_length);
}

static size_t bext_read_post(char *buffer, size_t count_bytes)
{
    if (!tls_request_ctx) return 0;
    return bext_sapi_read_post(tls_request_ctx, buffer, count_bytes);
}

static char *bext_read_cookies(void)
{
    if (!tls_request_ctx) return NULL;
    return bext_sapi_read_cookies(tls_request_ctx);
}

static int bext_header_handler(sapi_header_struct *sapi_header,
                                sapi_header_op_enum op,
                                sapi_headers_struct *sapi_headers)
{
    (void)sapi_headers;
    if (!tls_request_ctx || !sapi_header || !sapi_header->header) return 0;
    if (op == SAPI_HEADER_ADD || op == SAPI_HEADER_REPLACE) {
        bext_sapi_on_header(tls_request_ctx, sapi_header->header, sapi_header->header_len);
    }
    return 0;
}

static int bext_send_headers(sapi_headers_struct *sapi_headers)
{
    (void)sapi_headers;
    return SAPI_HEADER_SENT_SUCCESSFULLY;
}

static void bext_register_variables(zval *track_vars_array)
{
    php_import_environment_variables(track_vars_array);
    if (tls_request_ctx) {
        bext_sapi_register_server_variables(tls_request_ctx, track_vars_array);
    }
}

static void bext_log_message(const char *message, int syslog_type_int)
{
    bext_sapi_log_message(message, syslog_type_int);
}

/* ---------------------------------------------------------------------------
 * Worker mode: bext_handle_request() PHP function
 *
 * Registered as an internal PHP function during module startup.
 * Called from PHP worker scripts in a loop:
 *
 *   $app = new MyApp();
 *   $app->boot();
 *   while (bext_handle_request(function() use ($app) {
 *       $app->handle($_GET, $_POST, $_SERVER);
 *   })) {
 *       gc_collect_cycles();
 *   }
 * ---------------------------------------------------------------------------*/


/* Reset superglobals for the new worker request.
 * Destroys http_globals entries individually (safe in both NTS and ZTS)
 * so sapi_activate() re-creates them from the new request context. */
static void bext_reset_superglobals(void)
{
    /* Remove superglobals from the symbol table.  On next access,
     * PHP's auto_global JIT mechanism will call the SAPI's
     * register_server_variables (for $_SERVER) and PHP's built-in
     * parsers (for $_GET, $_POST, $_COOKIE) using the new SG(request_info). */
    zend_hash_str_del(&EG(symbol_table), "_SERVER",  sizeof("_SERVER")  - 1);
    zend_hash_str_del(&EG(symbol_table), "_GET",     sizeof("_GET")     - 1);
    zend_hash_str_del(&EG(symbol_table), "_POST",    sizeof("_POST")    - 1);
    zend_hash_str_del(&EG(symbol_table), "_COOKIE",  sizeof("_COOKIE")  - 1);
    zend_hash_str_del(&EG(symbol_table), "_FILES",   sizeof("_FILES")   - 1);
    zend_hash_str_del(&EG(symbol_table), "_REQUEST", sizeof("_REQUEST") - 1);
    zend_hash_str_del(&EG(symbol_table), "_SESSION", sizeof("_SESSION") - 1);

    /* Re-import $_SERVER by calling our register_server_variables callback
     * directly with a fresh array, then inject it into the symbol table. */
    {
        zval server_arr;
        array_init(&server_arr);
        /* Call the standard PHP env import first */
        php_import_environment_variables(&server_arr);
        /* Then our custom SAPI callback to add request-specific vars */
        if (tls_request_ctx) {
            bext_sapi_register_server_variables(tls_request_ctx, &server_arr);
        }
        /* Also add the standard CGI vars from SG(request_info) */
        if (SG(request_info).request_method) {
            php_register_variable_safe("REQUEST_METHOD",
                (char*)SG(request_info).request_method,
                strlen(SG(request_info).request_method), &server_arr);
        }
        if (SG(request_info).request_uri) {
            php_register_variable_safe("REQUEST_URI",
                (char*)SG(request_info).request_uri,
                strlen(SG(request_info).request_uri), &server_arr);
        }
        if (SG(request_info).query_string && *SG(request_info).query_string) {
            php_register_variable_safe("QUERY_STRING",
                (char*)SG(request_info).query_string,
                strlen(SG(request_info).query_string), &server_arr);
        }
        if (SG(request_info).content_type) {
            php_register_variable_safe("CONTENT_TYPE",
                (char*)SG(request_info).content_type,
                strlen(SG(request_info).content_type), &server_arr);
        }
        if (SG(request_info).content_length > 0) {
            char cl[32];
            snprintf(cl, sizeof(cl), "%ld", (long)SG(request_info).content_length);
            php_register_variable_safe("CONTENT_LENGTH", cl, strlen(cl), &server_arr);
        }
        /* Store as $_SERVER in the symbol table */
        zend_hash_str_update(&EG(symbol_table), "_SERVER", sizeof("_SERVER") - 1, &server_arr);
    }

    /* Re-import $_GET from the new query string */
    {
        zval get_arr;
        array_init(&get_arr);
        if (SG(request_info).query_string && *SG(request_info).query_string) {
            char *qs = estrdup(SG(request_info).query_string);
            sapi_module.treat_data(PARSE_STRING, qs, &get_arr);
            /* treat_data frees qs */
        }
        zend_hash_str_update(&EG(symbol_table), "_GET", sizeof("_GET") - 1, &get_arr);
    }

    /* Initialize $_POST, $_COOKIE, $_FILES, $_REQUEST as empty arrays.
     * Symfony/Laravel's Request::createFromGlobals() requires these to be
     * arrays, not null.  POST body parsing could be added here in the future. */
    {
        static const char *empty_globals[] = {
            "_POST", "_COOKIE", "_FILES", "_REQUEST"
        };
        for (int i = 0; i < 4; i++) {
            zval arr;
            array_init(&arr);
            zend_hash_str_update(&EG(symbol_table),
                empty_globals[i], strlen(empty_globals[i]), &arr);
        }
    }
}

/* PHP_FUNCTION(bext_handle_request) — NOT static, needed for function table */
PHP_FUNCTION(bext_handle_request)
{
    zend_fcall_info fci;
    zend_fcall_info_cache fcc;

    ZEND_PARSE_PARAMETERS_START(1, 1)
        Z_PARAM_FUNC(fci, fcc)
    ZEND_PARSE_PARAMETERS_END();

    if (!tls_is_worker) {
        zend_throw_exception_ex(NULL, 0,
            "bext_handle_request() can only be called from a worker script");
        RETURN_FALSE;
    }

    /* Wait for next request — blocks until Rust dispatches one. */
    int has_request = bext_sapi_worker_wait_request(&tls_request_ctx);
    if (!has_request) {
        RETURN_FALSE;
    }

    /* Update SAPI request info for the new request */
    SG(request_info).request_method  = bext_sapi_get_method(tls_request_ctx);
    SG(request_info).request_uri     = (char *)bext_sapi_get_uri(tls_request_ctx);
    SG(request_info).query_string    = (char *)bext_sapi_get_query_string(tls_request_ctx);
    SG(request_info).content_type    = bext_sapi_get_content_type(tls_request_ctx);
    SG(request_info).content_length  = bext_sapi_get_content_length(tls_request_ctx);

    /* Reset headers so header() works */
    SG(headers_sent) = 0;
    SG(sapi_headers).http_response_code = 200;

    /* Rebuild $_SERVER and $_GET from the new request info */
    bext_reset_superglobals();

#if defined(ZEND_CHECK_STACK_LIMIT) && !defined(ZTS)
    EG(stack_limit) = (void *)0;
#endif

    /* --- Call the user callback --- */
    zval retval;
    fci.retval = &retval;
    fci.param_count = 0;
    fci.params = NULL;

    if (zend_call_function(&fci, &fcc) == FAILURE) {
        /* Callback failed to execute */
        bext_sapi_log_message("bext_handle_request: callback execution failed", 3);
    }

    /* Handle exceptions thrown by the callback */
    if (EG(exception)) {
        if (zend_is_unwind_exit(EG(exception)) || zend_is_graceful_exit(EG(exception))) {
            /* exit()/die() — kill the worker script, it will be restarted */
            zval_ptr_dtor(&retval);
            zend_bailout();
        }
        /* Regular exception — log it, continue the worker loop */
        zend_exception_error(EG(exception), E_ERROR);
    }

    zval_ptr_dtor(&retval);

    /* --- Notify Rust the request is complete --- */
    int status = SG(sapi_headers).http_response_code
                     ? SG(sapi_headers).http_response_code : 200;
    bext_sapi_worker_finish_request(tls_request_ctx, status);

    RETURN_TRUE;
}

/* ---------------------------------------------------------------------------
 * bext_render() — shared memory bridge to JSC render pool.
 *
 * Usage:
 *   $html = bext_render('DashboardPage', json_encode(['orders' => 42]));
 *   echo $html;
 *
 * This calls directly into the JSC pool via Rust FFI — no HTTP, no headers.
 * ~100μs round-trip for a component render.
 * ---------------------------------------------------------------------------*/

PHP_FUNCTION(bext_render)
{
    char *component = NULL;
    size_t component_len = 0;
    char *props_json = NULL;
    size_t props_len = 0;

    ZEND_PARSE_PARAMETERS_START(1, 2)
        Z_PARAM_STRING(component, component_len)
        Z_PARAM_OPTIONAL
        Z_PARAM_STRING(props_json, props_len)
    ZEND_PARSE_PARAMETERS_END();

    if (!props_json || props_len == 0) {
        props_json = "{}";
    }

    /* Call Rust → JSC pool → HTML */
    char *html = bext_sapi_jsc_render(component, props_json);
    if (!html) {
        RETURN_STRING("<div>bext_render: null result</div>");
    }

    /* Copy into PHP string and free the Rust allocation */
    size_t html_len = strlen(html);
    RETVAL_STRINGL(html, html_len);
    bext_sapi_free_string(html);
}

/* ---------------------------------------------------------------------------
 * PHP function registration
 * ---------------------------------------------------------------------------*/

static const zend_function_entry bext_functions[] = {
    ZEND_FE(bext_handle_request, NULL)
    ZEND_FE(bext_render, NULL)
    PHP_FE_END
};

/* ---------------------------------------------------------------------------
 * C helper: register a $_SERVER variable
 * ---------------------------------------------------------------------------*/
void bext_php_register_variable(const char *key, const char *val, void *track_vars_array)
{
    if (key && val && track_vars_array) {
        php_register_variable_safe(
            (char *)key, (char *)val, strlen(val), (zval *)track_vars_array);
    }
}

/* ---------------------------------------------------------------------------
 * Public API — called from Rust
 * ---------------------------------------------------------------------------*/

int bext_php_module_init(const char *ini_entries)
{
    /* Use PHP's built-in embed SAPI for initialization — it handles
     * TSRM setup, module loading, and OPcache correctly.  We then
     * override the SAPI callbacks to route I/O through Rust. */

    /* Set INI overrides via the embed module's ini_entries */
    const char *prefix = "zend.max_allowed_stack_size=-1\nzend.reserved_stack_size=0\n";
    size_t prefix_len = strlen(prefix);
    size_t user_len = (ini_entries && *ini_entries) ? strlen(ini_entries) : 0;
    char *combined = malloc(prefix_len + user_len + 1);
    if (combined) {
        memcpy(combined, prefix, prefix_len);
        if (user_len > 0) {
            memcpy(combined + prefix_len, ini_entries, user_len);
        }
        combined[prefix_len + user_len] = '\0';
        php_embed_module.ini_entries = combined;
    }

    /* Initialize PHP via the embed SAPI */
    char *argv[] = {"bext-php", NULL};
    if (php_embed_init(1, argv) == FAILURE) {
        if (combined) free(combined);
        return -1;
    }

    /* No TSRMLS_CACHE_UPDATE needed — using dynamic path */

    /* Function registration (bext_handle_request) happens per-thread in
     * execute_worker/execute_script because CG(function_table) is per-thread
     * in ZTS mode.  Don't register the module here — it causes double
     * registration errors when worker threads also register. */

    /* php_embed_init starts a request context — shut it down so worker
     * threads can start their own independent request contexts. */
    php_request_shutdown(NULL);

    /* Override SAPI callbacks with our Rust-bridging versions.
     * Note: sapi_module is the global SAPI struct used by PHP internally.
     * After php_embed_init(), sapi_module == php_embed_module. */
    sapi_module.ub_write = bext_ub_write;
    sapi_module.read_post = bext_read_post;
    sapi_module.read_cookies = bext_read_cookies;
    sapi_module.header_handler = bext_header_handler;
    sapi_module.send_headers = bext_send_headers;
    sapi_module.register_server_variables = bext_register_variables;
    sapi_module.log_message = bext_log_message;

    return 0;
}

void bext_php_register_functions(void)
{
    zend_register_functions(NULL, bext_functions, NULL, MODULE_PERSISTENT);
}

void bext_php_module_shutdown(void)
{
    php_embed_shutdown();
}

int bext_php_execute_script(bext_request_ctx *ctx,
                             const char *script_path,
                             const char *method,
                             const char *uri,
                             const char *query_string,
                             const char *content_type,
                             int64_t content_length)
{
    volatile int status = 200;
    tls_request_ctx = ctx;
    tls_is_worker = 0;

#ifdef ZTS
    (void)ts_resource(0);
#endif

    if (php_request_startup() == FAILURE) {
        tls_request_ctx = NULL;
        return 500;
    }

    SG(request_info).request_method  = method;
    SG(request_info).request_uri     = (char *)uri;
    SG(request_info).query_string    = query_string ? (char *)query_string : "";
    SG(request_info).content_type    = content_type;
    SG(request_info).content_length  = (content_length >= 0) ? content_length : 0;
    SG(request_info).proto_num       = 1001;
    SG(request_info).path_translated = (char *)script_path;

    /* Disable PHP 8.4's call stack size enforcement.
     *
     * NTS builds: EG() accesses a global struct directly — we can write it.
     * ZTS builds: EG() uses a thread-local symbol inside libphp.so that
     * can't be referenced from our static archive.  ZTS with 16MB thread
     * stacks doesn't need this workaround — the auto-detected limit is
     * large enough.  For NTS, getrlimit returns the main thread's limit
     * which is wrong for our spawned worker threads.
     */
#if defined(ZEND_CHECK_STACK_LIMIT) && !defined(ZTS)
    EG(stack_limit) = (void *)0;
#endif

    zend_file_handle file_handle;
    zend_stream_init_filename(&file_handle, script_path);

    zend_first_try {
        php_execute_script(&file_handle);
    } zend_catch {
        status = 500;
    } zend_end_try();

    if (SG(sapi_headers).http_response_code) {
        status = SG(sapi_headers).http_response_code;
    }

    php_request_shutdown(NULL);
    tls_request_ctx = NULL;

    return status;
}

int bext_php_execute_worker(bext_request_ctx *initial_ctx,
                             const char *worker_script_path)
{
    tls_request_ctx = initial_ctx;
    tls_is_worker = 1;
    tls_worker_had_request = 0;

#ifdef ZTS
    ts_resource(0);
#endif

    if (php_request_startup() == FAILURE) {
        tls_request_ctx = NULL;
        tls_is_worker = 0;
        return -1;
    }
#ifdef ZTS
    ZEND_TSRMLS_CACHE_UPDATE();
#endif
    bext_php_register_functions();

    /* Set request_info AFTER startup (TSRM fully initialized) */
    SG(request_info).request_method  = "GET";
    SG(request_info).request_uri     = "/";
    SG(request_info).query_string    = "";
    SG(request_info).proto_num       = 1001;
    SG(request_info).path_translated = (char *)worker_script_path;

    PG(ignore_user_abort) = 1;

    /* Disable stack limit enforcement (NTS only — see classic mode comment) */
#if defined(ZEND_CHECK_STACK_LIMIT) && !defined(ZTS)
    EG(stack_limit) = (void *)0;
#endif

    int exit_status = 0;
    zend_file_handle file_handle;
    zend_stream_init_filename(&file_handle, worker_script_path);

    zend_first_try {
        php_execute_script(&file_handle);
        exit_status = EG(exit_status);
    } zend_catch {
        exit_status = 1;
    } zend_end_try();

    php_request_shutdown(NULL);
    tls_request_ctx = NULL;
    tls_is_worker = 0;

    return exit_status;
}