winzik/docker/ext/cryo/cryo_sandbox.c

4274 lines
142 KiB
C

/*
* Cryo\Sandbox — isolated execution (milestone 6).
*
* A sandbox is a child PHP process (POSIX) or a PHP instance run by the JS
* host (WebAssembly). Parent and child talk over one channel with frames:
*
* uint32 length | uint32 type | uint32 request id | payload
*
* (little endian; the payload is a PHP-serialized array). Several requests
* may be in flight; the child runs them in order and answers each with its
* id. The child never runs the PHP shutdown sequence: it leaves with _exit()
* so it cannot flush the parent's buffers or run its destructors twice.
*
* Start modes: spawn (default: exec of a fresh PHP binary), fork (copy of the
* current interpreter), snapshot (spawn + cryo_thaw(file)), thread (needs
* ZTS: refused on NTS builds).
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "php_main.h"
#include "SAPI.h"
#include "ext/standard/php_var.h"
#include "zend_exceptions.h"
#include "zend_interfaces.h"
#include "zend_closures.h"
#include "zend_smart_str.h"
#include "main/php_output.h"
#include "php_cryo.h"
#include "cryo_host.h"
#ifndef CRYO_BACKEND_WASM
# include <sys/types.h>
# include <sys/socket.h>
# include <sys/wait.h>
# include <sys/time.h>
# include <sys/resource.h>
# include <signal.h>
# include <poll.h>
# include <fcntl.h>
# include <errno.h>
# include <unistd.h>
# include <dlfcn.h>
# include <sys/stat.h>
# if defined(__linux__) && __has_include(<linux/seccomp.h>) && __has_include(<linux/filter.h>) && __has_include(<linux/audit.h>)
# include <sys/prctl.h>
# include <sys/syscall.h>
# include <linux/seccomp.h>
# include <linux/filter.h>
# include <linux/audit.h>
# include <stddef.h>
# if defined(__x86_64__)
# define CRYO_AUDIT_ARCH AUDIT_ARCH_X86_64
# elif defined(__aarch64__)
# define CRYO_AUDIT_ARCH AUDIT_ARCH_AARCH64
# elif defined(__i386__)
# define CRYO_AUDIT_ARCH AUDIT_ARCH_I386
# elif defined(__arm__)
# define CRYO_AUDIT_ARCH AUDIT_ARCH_ARM
# endif
# if defined(CRYO_AUDIT_ARCH) && defined(SYS_socket)
# define CRYO_HAVE_SECCOMP 1
# endif
# endif
# define SIGXCPU_COMPAT SIGXCPU
extern PHPAPI char *php_ini_opened_path;
extern PHPAPI char *php_ini_scanned_files;
#else
# include <unistd.h>
# define SIGXCPU_COMPAT 24
#endif
/* ------------------------------------------------------------------------ */
/* Protocol */
/* ------------------------------------------------------------------------ */
enum {
/* parent -> child */
CRYO_F_INIT = 1, CRYO_F_CALL, CRYO_F_EVAL, CRYO_F_INCLUDE, CRYO_F_GET, CRYO_F_SET,
CRYO_F_SNAPSHOT, CRYO_F_FREEZE, CRYO_F_ENGINE, CRYO_F_PROXY, CRYO_F_METRICS,
CRYO_F_CANCEL, CRYO_F_EXIT,
/* both ways */
CRYO_F_MSG = 32,
/* child -> parent */
CRYO_F_RESULT = 64, CRYO_F_ERROR, CRYO_F_FATAL, CRYO_F_HELLO
};
#define CRYO_HDR 12
#define CRYO_MAX_FRAME (256u * 1024u * 1024u)
typedef struct {
int fd; /* POSIX socket */
int32_t wid; /* WASM instance / channel id */
} cryo_chan;
/* Remove and return the first element of a hash table. */
static bool cryo_shift(HashTable *ht, zval *out)
{
zend_ulong k; zend_string *sk; zval *v;
ZEND_HASH_FOREACH_KEY_VAL(ht, k, sk, v) {
ZVAL_COPY(out, v);
if (sk) zend_hash_del(ht, sk); else zend_hash_index_del(ht, k);
return true;
} ZEND_HASH_FOREACH_END();
return false;
}
static void cryo_put32(unsigned char *p, uint32_t v)
{
p[0] = (unsigned char) (v & 0xff); p[1] = (unsigned char) ((v >> 8) & 0xff);
p[2] = (unsigned char) ((v >> 16) & 0xff); p[3] = (unsigned char) ((v >> 24) & 0xff);
}
static uint32_t cryo_get32(const unsigned char *p)
{
return (uint32_t) p[0] | ((uint32_t) p[1] << 8) | ((uint32_t) p[2] << 16) | ((uint32_t) p[3] << 24);
}
static double cryo_mono(void)
{
#ifdef CRYO_BACKEND_WASM
return cryo_host_now() / 1000.0;
#else
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (double) ts.tv_sec + (double) ts.tv_nsec / 1e9;
#endif
}
/* Serialize a zval; on failure (exception) returns NULL with EG(exception) set. */
static zend_string *cryo_ser(zval *v)
{
smart_str buf = {0};
php_serialize_data_t d;
PHP_VAR_SERIALIZE_INIT(d);
php_var_serialize(&buf, v, &d);
PHP_VAR_SERIALIZE_DESTROY(d);
if (EG(exception)) {
smart_str_free(&buf);
return NULL;
}
smart_str_0(&buf);
return buf.s ? buf.s : ZSTR_EMPTY_ALLOC();
}
static bool cryo_unser(zval *out, const char *p, size_t len)
{
const unsigned char *s = (const unsigned char *) p, *e = s + len;
php_unserialize_data_t d;
PHP_VAR_UNSERIALIZE_INIT(d);
bool ok = php_var_unserialize(out, &s, e, &d);
PHP_VAR_UNSERIALIZE_DESTROY(d);
if (!ok) {
zval_ptr_dtor(out);
ZVAL_NULL(out);
}
return ok;
}
#ifndef CRYO_BACKEND_WASM
static bool cryo_write_all(int fd, const unsigned char *p, size_t n)
{
while (n) {
# ifdef MSG_NOSIGNAL
ssize_t w = send(fd, p, n, MSG_NOSIGNAL);
# else
ssize_t w = write(fd, p, n);
# endif
if (w < 0) {
if (errno == EINTR) continue;
if (errno == EAGAIN) { struct pollfd pf = {fd, POLLOUT, 0}; poll(&pf, 1, 100); continue; }
return false;
}
p += w;
n -= (size_t) w;
}
return true;
}
/* read exactly n bytes; -1 on EOF/error */
static int cryo_read_all(int fd, unsigned char *p, size_t n)
{
while (n) {
ssize_t r = read(fd, p, n);
if (r < 0) {
if (errno == EINTR) continue;
if (errno == EAGAIN) { struct pollfd pf = {fd, POLLIN, 0}; poll(&pf, 1, 100); continue; }
return -1;
}
if (r == 0) return -1;
p += r;
n -= (size_t) r;
}
return 0;
}
#endif
static bool cryo_chan_send(cryo_chan *c, uint32_t type, uint32_t id, const char *data, size_t len)
{
unsigned char hdr[CRYO_HDR];
cryo_put32(hdr, (uint32_t) len);
cryo_put32(hdr + 4, type);
cryo_put32(hdr + 8, id);
#ifdef CRYO_BACKEND_WASM
if (cryo_host_send(c->wid, hdr, CRYO_HDR) < 0) return false;
return len == 0 || cryo_host_send(c->wid, (const uint8_t *) data, (uint32_t) len) >= 0;
#else
/* one buffer: a frame is never interleaved with another writer's */
unsigned char *buf = emalloc(CRYO_HDR + len);
memcpy(buf, hdr, CRYO_HDR);
if (len) memcpy(buf + CRYO_HDR, data, len);
bool ok = cryo_write_all(c->fd, buf, CRYO_HDR + len);
efree(buf);
return ok;
#endif
}
static bool cryo_chan_send_zv(cryo_chan *c, uint32_t type, uint32_t id, zval *payload)
{
zend_string *s = cryo_ser(payload);
if (!s) return false;
bool ok = cryo_chan_send(c, type, id, ZSTR_VAL(s), ZSTR_LEN(s));
zend_string_release(s);
return ok;
}
/*
* 1 = frame, 0 = timeout, -1 = closed. timeout < 0 waits forever (POSIX). WebAssembly never waits: the
* host only queues whole frames, so a frame is either all there or not there yet (0).
*/
static int cryo_chan_recv(cryo_chan *c, double timeout, uint32_t *type, uint32_t *id, zend_string **payload)
{
unsigned char hdr[CRYO_HDR];
#ifdef CRYO_BACKEND_WASM
(void) timeout;
int32_t r = cryo_host_recv(c->wid, hdr, CRYO_HDR, 0);
if (r == -1) return 0;
if (r != CRYO_HDR) return -1;
uint32_t len = cryo_get32(hdr);
if (len > CRYO_MAX_FRAME) return -1;
zend_string *s = zend_string_alloc(len, 0);
if (len && cryo_host_recv(c->wid, (uint8_t *) ZSTR_VAL(s), len, 0) != (int32_t) len) {
zend_string_efree(s);
return -1;
}
#else
if (timeout >= 0) {
struct pollfd pf = {c->fd, POLLIN, 0};
int ms = timeout > 2000000.0 ? 2000000000 : (int) (timeout * 1000.0);
int pr;
do { pr = poll(&pf, 1, ms); } while (pr < 0 && errno == EINTR);
if (pr == 0) return 0;
}
if (cryo_read_all(c->fd, hdr, CRYO_HDR) < 0) return -1;
uint32_t len = cryo_get32(hdr);
if (len > CRYO_MAX_FRAME) return -1;
zend_string *s = zend_string_alloc(len, 0);
if (len && cryo_read_all(c->fd, (unsigned char *) ZSTR_VAL(s), len) < 0) {
zend_string_efree(s);
return -1;
}
#endif
ZSTR_VAL(s)[len] = '\0';
*type = cryo_get32(hdr + 4);
*id = cryo_get32(hdr + 8);
*payload = s;
return 1;
}
/* ------------------------------------------------------------------------ */
/* Classes */
/* ------------------------------------------------------------------------ */
static zend_class_entry *ce_sandbox, *ce_future, *ce_pool, *ce_channel, *ce_remote, *ce_engine_proxy;
static zend_class_entry *ce_sb_exception, *ce_crashed, *ce_timeout, *ce_memory, *ce_remote_exc;
static zend_object_handlers h_sandbox, h_future, h_pool, h_remote, h_proxy, h_channel;
enum { CRYO_START_SPAWN, CRYO_START_FORK, CRYO_START_SNAPSHOT };
enum { CRYO_RESTART_NEVER, CRYO_RESTART_ON_CRASH, CRYO_RESTART_ALWAYS };
typedef struct {
int start;
zend_string *bootstrap, *snapshot, *memory_limit;
zend_long memory_bytes;
double cpu_time, timeout;
zval ini; /* array */
zval disable; /* list of names */
bool network;
int restart;
bool pass_output;
} cryo_sb_opts;
typedef struct _cryo_sandbox {
cryo_sb_opts o;
cryo_chan chan;
int err_fd;
zend_long pid; /* pid or wasm id */
bool alive, dying;
bool starting; /* WebAssembly: spawned, HELLO not received yet */
int term_signal;
int exit_code;
uint32_t next_id;
HashTable pending; /* id -> null (waiting) | array (answer) | false (cancelled) */
HashTable inbox; /* messages from the child */
zend_long calls, memory, jobs;
zend_string *last_error, *last_output;
char errtail[2048];
size_t errlen;
const char *network_level;
struct _cryo_sandbox *next_live;
zend_object std;
} cryo_sandbox;
/*
* Three kinds of futures: a request (sandbox + id), then() (parent + callbacks) and Sandbox::wait() (group).
* state: 0 pending, 1 resolved (answer: the frame of a request, the value of the others), 2 cancelled,
* 3 failed (then() / wait(): error holds the exception). A request's failure is its answer frame
* (t != RESULT); its exception is built once, on demand, into error.
*/
typedef struct {
zval sandbox; /* owning Sandbox */
uint32_t id;
int state;
zval answer; /* array frame payload + 't' (request), value (then / wait) */
zval parent; /* then(): source future */
zval callback; /* then(): callable on success */
zval on_error; /* then(): callable on failure (or undef) */
zval group; /* wait(): array of futures */
zval error; /* the exception of a failed / cancelled future (built once) */
double deadline; /* wait(): cryo_mono() deadline, 0 = none */
bool single; /* wait(Future): the value of that future, not an array */
zend_object std;
} cryo_future;
typedef struct {
zval sandbox;
zend_long handle;
zend_string *cls;
zend_object std;
} cryo_remote;
typedef struct {
zval sandbox;
zend_object std;
} cryo_proxy;
typedef struct {
zval workers; /* list of Sandbox */
zval options;
zend_long max_jobs, max_memory;
bool closed;
zend_object std;
} cryo_pool;
#define SB(o) ((cryo_sandbox *) ((char *) (o) - XtOffsetOf(cryo_sandbox, std)))
#define FUT(o) ((cryo_future *) ((char *) (o) - XtOffsetOf(cryo_future, std)))
#define REM(o) ((cryo_remote *) ((char *) (o) - XtOffsetOf(cryo_remote, std)))
#define PRX(o) ((cryo_proxy *) ((char *) (o) - XtOffsetOf(cryo_proxy, std)))
#define POOL(o) ((cryo_pool *) ((char *) (o) - XtOffsetOf(cryo_pool, std)))
static cryo_sandbox *cryo_live_sandboxes = NULL;
/* ------------------------------------------------------------------------ */
/* Child side */
/* ------------------------------------------------------------------------ */
static struct {
bool active;
cryo_chan chan;
zval queue; /* list of [type, id, payload] waiting to run */
zval inbox; /* messages from the parent */
zval objects; /* proxy handle -> object */
zend_long next_handle;
uint32_t current;
zend_long calls;
double timeout;
bool fork_mode;
zend_internal_function func;
unsigned char timeout_frame[256];
size_t timeout_len;
unsigned char *timeout_payload;
} cryo_child;
static ZEND_COLD void cryo_child_exit(int code)
{
/* never run the PHP shutdown sequence in the child */
_exit(code);
}
/* Read every frame available now (or wait up to timeout) into queue/inbox. */
static int cryo_child_pump(double timeout)
{
uint32_t type, id;
zend_string *payload;
int r = cryo_chan_recv(&cryo_child.chan, timeout, &type, &id, &payload);
if (r < 0) {
cryo_child_exit(0); /* parent gone */
}
if (r == 0) {
return 0;
}
if (type == CRYO_F_MSG) {
zval v;
cryo_unser(&v, ZSTR_VAL(payload), ZSTR_LEN(payload));
add_next_index_zval(&cryo_child.inbox, &v);
} else if (type == CRYO_F_CANCEL) {
zval *e;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL(cryo_child.queue), e) {
if ((uint32_t) Z_LVAL_P(zend_hash_index_find(Z_ARRVAL_P(e), 1)) == id) {
add_index_long(e, 0, 0); /* type 0 = skip */
}
} ZEND_HASH_FOREACH_END();
} else {
zval e;
array_init(&e);
add_next_index_long(&e, type);
add_next_index_long(&e, id);
add_next_index_str(&e, payload);
add_next_index_zval(&cryo_child.queue, &e);
return 1;
}
zend_string_release(payload);
return 1;
}
#ifndef CRYO_BACKEND_WASM
static void cryo_child_alarm(int sig)
{
(void) sig;
/* async-signal-safe: prebuilt frame + _exit */
if (cryo_child.timeout_len) {
cryo_put32(cryo_child.timeout_frame + 8, cryo_child.current);
ssize_t w = write(cryo_child.chan.fd, cryo_child.timeout_frame, cryo_child.timeout_len);
(void) w;
}
_exit(124);
}
static void cryo_child_arm(double seconds)
{
struct itimerval it;
memset(&it, 0, sizeof(it));
if (seconds > 0) {
it.it_value.tv_sec = (time_t) seconds;
it.it_value.tv_usec = (suseconds_t) ((seconds - (double) (time_t) seconds) * 1e6);
if (!it.it_value.tv_sec && !it.it_value.tv_usec) it.it_value.tv_usec = 1000;
}
setitimer(ITIMER_REAL, &it, NULL);
}
#else
/* No signals: the parent's host ends the instance after the delay and hands over the prebuilt answer. */
static void cryo_child_arm(double seconds)
{
static bool armed = false;
if (seconds > 0 && cryo_child.timeout_len) {
cryo_put32(cryo_child.timeout_frame + 8, cryo_child.current);
double ms = seconds * 1000.0;
cryo_host_arm(ms < 1 ? 1 : (ms > 2000000000.0 ? 2000000000u : (uint32_t) ms),
cryo_child.timeout_frame, (uint32_t) cryo_child.timeout_len);
armed = true;
} else if (armed) {
cryo_host_arm(0, NULL, 0);
armed = false;
}
}
#endif
static void cryo_add_exception_info(zval *out, zend_object *ex)
{
zval rv, *p;
add_assoc_str(out, "class", zend_string_copy(ex->ce->name));
p = zend_read_property_ex(zend_get_exception_base(ex), ex, ZSTR_KNOWN(ZEND_STR_MESSAGE), 1, &rv);
add_assoc_str(out, "message", zval_get_string(p));
p = zend_read_property_ex(zend_get_exception_base(ex), ex, ZSTR_KNOWN(ZEND_STR_CODE), 1, &rv);
add_assoc_long(out, "code", zval_get_long(p));
p = zend_read_property_ex(zend_get_exception_base(ex), ex, ZSTR_KNOWN(ZEND_STR_FILE), 1, &rv);
add_assoc_str(out, "file", zval_get_string(p));
p = zend_read_property_ex(zend_get_exception_base(ex), ex, ZSTR_KNOWN(ZEND_STR_LINE), 1, &rv);
add_assoc_long(out, "line", zval_get_long(p));
zval trace;
ZVAL_UNDEF(&trace);
zend_call_method_with_0_params(ex, ex->ce, NULL, "gettraceasstring", &trace);
if (EG(exception) && EG(exception) != ex) {
zend_clear_exception();
}
if (Z_TYPE(trace) == IS_STRING) {
add_assoc_zval(out, "trace", &trace);
} else {
zval_ptr_dtor(&trace);
add_assoc_string(out, "trace", "");
}
}
static void cryo_child_take_output(zval *out, int level)
{
zval o;
ZVAL_EMPTY_STRING(&o);
if (php_output_get_level() > level) {
zval c;
if (php_output_get_contents(&c) == SUCCESS) {
zval_ptr_dtor(&o);
ZVAL_COPY_VALUE(&o, &c);
}
while (php_output_get_level() > level) {
php_output_discard();
}
}
add_assoc_zval(out, "out", &o);
}
static zend_long cryo_child_remote(zval *v)
{
zend_long h = ++cryo_child.next_handle;
Z_TRY_ADDREF_P(v);
zend_hash_index_update(Z_ARRVAL(cryo_child.objects), h, v);
return h;
}
static void cryo_child_send_value(uint32_t id, zval *value, int level, bool remote)
{
zval ans;
array_init(&ans);
if (remote && Z_TYPE_P(value) == IS_OBJECT) {
add_assoc_long(&ans, "h", cryo_child_remote(value));
add_assoc_str(&ans, "class", zend_string_copy(Z_OBJCE_P(value)->name));
add_assoc_null(&ans, "v");
} else {
Z_TRY_ADDREF_P(value);
add_assoc_zval(&ans, "v", value);
}
cryo_child_take_output(&ans, level);
add_assoc_long(&ans, "mem", (zend_long) zend_memory_usage(0));
zend_string *s = cryo_ser(&ans);
if (!s) {
/* the value cannot be serialized: answer with the exception */
zend_object *ex = EG(exception);
zval err;
array_init(&err);
cryo_add_exception_info(&err, ex);
zend_clear_exception();
add_assoc_string(&err, "out", "");
add_assoc_long(&err, "mem", (zend_long) zend_memory_usage(0));
cryo_chan_send_zv(&cryo_child.chan, CRYO_F_ERROR, id, &err);
zval_ptr_dtor(&err);
} else {
cryo_chan_send(&cryo_child.chan, CRYO_F_RESULT, id, ZSTR_VAL(s), ZSTR_LEN(s));
zend_string_release(s);
}
zval_ptr_dtor(&ans);
}
static void cryo_child_fatal(uint32_t id, int level);
static void cryo_child_clear_last_error(void)
{
if (PG(last_error_message)) {
zend_string_release(PG(last_error_message));
PG(last_error_message) = NULL;
}
if (PG(last_error_file)) {
zend_string_release(PG(last_error_file));
PG(last_error_file) = NULL;
}
PG(last_error_type) = 0;
PG(last_error_lineno) = 0;
}
static void cryo_child_send_exception(uint32_t id, int level)
{
zend_object *ex = EG(exception);
if (zend_is_unwind_exit(ex) || zend_is_graceful_exit(ex)) {
zend_clear_exception();
if (PG(last_error_message) && (PG(last_error_type) & E_FATAL_ERRORS)) {
/* recent PHP versions unwind the stack on fatal errors */
zend_set_memory_limit((size_t) 0x7fffffff);
cryo_child_fatal(id, level);
cryo_child_exit(255);
}
zval f;
array_init(&f);
add_assoc_string(&f, "kind", "exit");
add_assoc_long(&f, "status", EG(exit_status));
add_assoc_string(&f, "message", "exit() called in the sandbox");
cryo_child_take_output(&f, level);
cryo_chan_send_zv(&cryo_child.chan, CRYO_F_FATAL, id, &f);
cryo_child_exit(EG(exit_status));
}
GC_ADDREF(ex);
zend_clear_exception();
zval err;
array_init(&err);
cryo_add_exception_info(&err, ex);
OBJ_RELEASE(ex);
cryo_child_take_output(&err, level);
add_assoc_long(&err, "mem", (zend_long) zend_memory_usage(0));
cryo_chan_send_zv(&cryo_child.chan, CRYO_F_ERROR, id, &err);
zval_ptr_dtor(&err);
}
static void cryo_child_send_error(uint32_t id, const char *cls, const char *msg, int level)
{
zval err;
array_init(&err);
add_assoc_string(&err, "class", (char *) cls);
add_assoc_string(&err, "message", (char *) msg);
add_assoc_long(&err, "code", 0);
add_assoc_string(&err, "file", "");
add_assoc_long(&err, "line", 0);
add_assoc_string(&err, "trace", "");
cryo_child_take_output(&err, level);
add_assoc_long(&err, "mem", (zend_long) zend_memory_usage(0));
cryo_chan_send_zv(&cryo_child.chan, CRYO_F_ERROR, id, &err);
zval_ptr_dtor(&err);
}
/* Compile and run code (eval semantics) or a file, in the global scope. */
static void cryo_child_run_code(zend_string *code, zend_string *file, zval *retval)
{
zend_op_array *op;
ZVAL_NULL(retval);
if (file) {
zend_file_handle fh;
zend_stream_init_filename_ex(&fh, file);
op = zend_compile_file(&fh, ZEND_INCLUDE);
if (op && fh.opened_path) {
zend_hash_add_empty_element(&EG(included_files), fh.opened_path);
}
zend_destroy_file_handle(&fh);
if (!op && !EG(exception)) {
zend_throw_exception_ex(zend_ce_exception, 0, "Cannot include %s", ZSTR_VAL(file));
return;
}
} else {
op = zend_compile_string(code, "sandbox eval()'d code", ZEND_COMPILE_POSITION_AFTER_OPEN_TAG);
}
if (!op) {
return;
}
zend_execute_data *saved = EG(current_execute_data);
EG(current_execute_data) = NULL; /* top-level code: global symbol table */
zval rv;
ZVAL_UNDEF(&rv);
zend_execute(op, &rv);
EG(current_execute_data) = saved;
destroy_op_array(op);
efree_size(op, sizeof(zend_op_array));
if (Z_TYPE(rv) != IS_UNDEF) {
ZVAL_COPY_VALUE(retval, &rv);
if (file && Z_TYPE_P(retval) == IS_NULL && !EG(exception)) {
ZVAL_LONG(retval, 1);
}
}
}
static bool cryo_child_call(zval *callable, zval *args, zval *retval)
{
zend_fcall_info fci;
zend_fcall_info_cache fcc;
char *error = NULL;
if (zend_fcall_info_init(callable, 0, &fci, &fcc, NULL, &error) != SUCCESS) {
zend_throw_error(NULL, "Sandbox call: %s", error ? error : "not callable");
if (error) efree(error);
return false;
}
if (error) efree(error);
fci.retval = retval;
fci.named_params = args && Z_TYPE_P(args) == IS_ARRAY ? Z_ARRVAL_P(args) : NULL;
zend_call_function(&fci, &fcc);
if (Z_ISREF_P(retval)) {
zend_unwrap_reference(retval);
}
return !EG(exception);
}
static zval *cryo_global(zend_string *name)
{
zval *v = zend_hash_find(&EG(symbol_table), name);
if (v && Z_TYPE_P(v) == IS_INDIRECT) v = Z_INDIRECT_P(v);
if (v && Z_TYPE_P(v) == IS_UNDEF) v = NULL;
return v;
}
static zval *cryo_arr(HashTable *h, const char *k)
{
zval *v = zend_hash_str_find(h, k, strlen(k));
if (v) ZVAL_DEREF(v);
return v;
}
static void cryo_child_metrics(zval *out)
{
array_init(out);
add_assoc_long(out, "pid", (zend_long) getpid());
add_assoc_long(out, "memory", (zend_long) zend_memory_usage(0));
add_assoc_long(out, "memory_real", (zend_long) zend_memory_usage(1));
add_assoc_long(out, "memory_peak", (zend_long) zend_memory_peak_usage(0));
add_assoc_long(out, "calls", cryo_child.calls);
uint32_t alive = 0;
for (uint32_t h = 1; h < EG(objects_store).top; h++) {
if (IS_OBJ_VALID(EG(objects_store).object_buckets[h])) alive++;
}
add_assoc_long(out, "objects_alive", alive);
add_assoc_long(out, "included_files", zend_hash_num_elements(&EG(included_files)));
#ifndef CRYO_BACKEND_WASM
struct rusage ru;
if (getrusage(RUSAGE_SELF, &ru) == 0) {
add_assoc_double(out, "cpu_user", (double) ru.ru_utime.tv_sec + ru.ru_utime.tv_usec / 1e6);
add_assoc_double(out, "cpu_system", (double) ru.ru_stime.tv_sec + ru.ru_stime.tv_usec / 1e6);
}
#endif
}
static void cryo_child_proxy(uint32_t id, HashTable *req, int level)
{
zval *op = cryo_arr(req, "op"), *h = cryo_arr(req, "h");
const char *o = op && Z_TYPE_P(op) == IS_STRING ? Z_STRVAL_P(op) : "";
zval retval;
ZVAL_NULL(&retval);
if (strcmp(o, "new") == 0) {
zval *x = cryo_arr(req, "x");
zend_string *code = zend_strpprintf(0, "return %s;", x && Z_TYPE_P(x) == IS_STRING ? Z_STRVAL_P(x) : "null");
cryo_child_run_code(code, NULL, &retval);
zend_string_release(code);
if (!EG(exception) && Z_TYPE(retval) != IS_OBJECT) {
zval_ptr_dtor(&retval);
cryo_child_send_error(id, "TypeError", "proxy(): the expression must evaluate to an object", level);
return;
}
} else {
zval *obj = h ? zend_hash_index_find(Z_ARRVAL(cryo_child.objects), zval_get_long(h)) : NULL;
if (!obj) {
cryo_child_send_error(id, "Error", "Remote object no longer exists", level);
return;
}
zval *n = cryo_arr(req, "n");
zend_string *name = n && Z_TYPE_P(n) == IS_STRING ? Z_STR_P(n) : ZSTR_EMPTY_ALLOC();
if (strcmp(o, "call") == 0) {
zval callable;
array_init(&callable);
Z_ADDREF_P(obj);
add_next_index_zval(&callable, obj);
add_next_index_str(&callable, zend_string_copy(name));
cryo_child_call(&callable, cryo_arr(req, "a"), &retval);
zval_ptr_dtor(&callable);
} else if (strcmp(o, "get") == 0) {
zval rv;
zval *p = Z_OBJ_HT_P(obj)->read_property(Z_OBJ_P(obj), name, BP_VAR_R, NULL, &rv);
if (!EG(exception)) ZVAL_COPY_DEREF(&retval, p);
if (p == &rv) zval_ptr_dtor(&rv);
} else if (strcmp(o, "set") == 0) {
zval *v = cryo_arr(req, "v");
zval nv;
ZVAL_NULL(&nv);
Z_OBJ_HT_P(obj)->write_property(Z_OBJ_P(obj), name, v ? v : &nv, NULL);
} else if (strcmp(o, "isset") == 0) {
ZVAL_BOOL(&retval, Z_OBJ_HT_P(obj)->has_property(Z_OBJ_P(obj), name, ZEND_PROPERTY_ISSET, NULL));
} else if (strcmp(o, "unset") == 0) {
Z_OBJ_HT_P(obj)->unset_property(Z_OBJ_P(obj), name, NULL);
} else if (strcmp(o, "free") == 0) {
zend_hash_index_del(Z_ARRVAL(cryo_child.objects), zval_get_long(h));
}
}
if (EG(exception)) {
zval_ptr_dtor(&retval);
cryo_child_send_exception(id, level);
return;
}
cryo_child_send_value(id, &retval, level, true);
zval_ptr_dtor(&retval);
}
static void cryo_child_run(uint32_t type, uint32_t id, zend_string *payload)
{
zval req;
ZVAL_UNDEF(&req);
cryo_unser(&req, ZSTR_VAL(payload), ZSTR_LEN(payload));
HashTable *h = Z_TYPE(req) == IS_ARRAY ? Z_ARRVAL(req) : NULL;
int level = php_output_get_level();
zval retval;
ZVAL_NULL(&retval);
cryo_child.current = id;
cryo_child.calls++;
cryo_child_clear_last_error();
php_output_start_default();
cryo_child_arm(cryo_child.timeout);
if (!h && type != CRYO_F_METRICS && type != CRYO_F_EXIT) {
cryo_child_send_error(id, "Error", "Malformed request", level);
goto done;
}
switch (type) {
case CRYO_F_CALL:
cryo_child_call(cryo_arr(h, "f"), cryo_arr(h, "a"), &retval);
break;
case CRYO_F_EVAL: {
zval *c = cryo_arr(h, "c");
zend_string *code = c ? zval_get_string(c) : ZSTR_EMPTY_ALLOC();
cryo_child_run_code(code, NULL, &retval);
zend_string_release(code);
break;
}
case CRYO_F_INCLUDE: {
zval *f = cryo_arr(h, "f");
zend_string *file = f ? zval_get_string(f) : ZSTR_EMPTY_ALLOC();
cryo_child_run_code(NULL, file, &retval);
zend_string_release(file);
break;
}
case CRYO_F_GET: {
zval *n = cryo_arr(h, "n");
zval *v = n && Z_TYPE_P(n) == IS_STRING ? cryo_global(Z_STR_P(n)) : NULL;
if (v) ZVAL_COPY_DEREF(&retval, v);
break;
}
case CRYO_F_SET: {
zval *n = cryo_arr(h, "n"), *v = cryo_arr(h, "v");
if (n && Z_TYPE_P(n) == IS_STRING) {
zval nv;
ZVAL_NULL(&nv);
if (!v) v = &nv;
zval *slot = cryo_global(Z_STR_P(n));
if (slot) {
ZVAL_DEREF(slot);
zval old;
ZVAL_COPY_VALUE(&old, slot);
ZVAL_COPY(slot, v);
zval_ptr_dtor(&old);
} else {
Z_TRY_ADDREF_P(v);
zend_hash_update(&EG(symbol_table), Z_STR_P(n), v);
}
}
break;
}
case CRYO_F_SNAPSHOT: {
zval *f = cryo_arr(h, "f");
if (!f || Z_TYPE_P(f) != IS_STRING || cryo_write_snapshot(Z_STR_P(f), NULL) == FAILURE) {
if (!EG(exception)) {
zend_throw_exception_ex(cryo_ce_exception, 0, "Cannot write snapshot to %s",
f && Z_TYPE_P(f) == IS_STRING ? Z_STRVAL_P(f) : "?");
}
}
break;
}
case CRYO_F_FREEZE: {
/* cryo_freeze() lives in cryo.c (milestone 5): call it by name */
/* the child waits in the C command loop: freeze its values (include without "stack") */
zval fn, args[2];
ZVAL_STRING(&fn, "cryo_freeze");
zval *f = cryo_arr(h, "f");
ZVAL_COPY(&args[0], f ? f : &EG(uninitialized_zval));
array_init(&args[1]);
add_assoc_string(&args[1], "mode", "continue");
zval inc;
array_init(&inc);
add_next_index_string(&inc, "globals");
add_next_index_string(&inc, "statics");
add_assoc_zval(&args[1], "include", &inc);
call_user_function(NULL, NULL, &fn, &retval, 2, args);
zval_ptr_dtor(&fn);
zval_ptr_dtor(&args[0]);
zval_ptr_dtor(&args[1]);
break;
}
case CRYO_F_ENGINE: {
zval *op = cryo_arr(h, "op");
const char *o = op && Z_TYPE_P(op) == IS_STRING ? Z_STRVAL_P(op) : "";
if (!cryo_engine_enabled()) {
zend_throw_exception(cryo_ce_exception, "Cryo\\Engine is disabled (cryo.engine=0)", 0);
} else if (strcmp(o, "apply") == 0) {
zval *e = cryo_arr(h, "e");
zend_long nid = e ? cryo_engine_apply_entry(e) : 0;
if (nid) ZVAL_LONG(&retval, nid);
} else if (strcmp(o, "replay") == 0) {
zval *e = cryo_arr(h, "e");
if (e) ZVAL_LONG(&retval, cryo_engine_journal_replay(e));
} else {
/* journal / revert / exportJournal on the child's engine */
zval engine, method;
zend_call_method_with_0_params(NULL, cryo_ce_engine, NULL, "current", &engine);
if (Z_TYPE(engine) == IS_OBJECT) {
ZVAL_STRING(&method, o);
zval *a = cryo_arr(h, "a");
uint32_t n = 0;
zval argv[1];
if (a && Z_TYPE_P(a) == IS_ARRAY && zend_hash_num_elements(Z_ARRVAL_P(a))) {
ZVAL_COPY(&argv[0], zend_hash_index_find(Z_ARRVAL_P(a), 0) ? zend_hash_index_find(Z_ARRVAL_P(a), 0) : &EG(uninitialized_zval));
n = 1;
}
call_user_function(NULL, &engine, &method, &retval, n, argv);
if (n) zval_ptr_dtor(&argv[0]);
zval_ptr_dtor(&method);
}
zval_ptr_dtor(&engine);
}
break;
}
case CRYO_F_PROXY:
cryo_child_arm(0);
cryo_child_proxy(id, h, level);
goto done;
case CRYO_F_METRICS:
cryo_child_metrics(&retval);
break;
case CRYO_F_EXIT:
cryo_child_exit(0);
default:
cryo_child_send_error(id, "Error", "Unknown request", level);
goto done;
}
cryo_child_arm(0);
if (EG(exception)) {
zval_ptr_dtor(&retval);
cryo_child_send_exception(id, level);
} else {
cryo_child_send_value(id, &retval, level, false);
zval_ptr_dtor(&retval);
}
done:
cryo_child_arm(0);
zval_ptr_dtor(&req);
}
static void cryo_child_fatal(uint32_t id, int level)
{
zval f;
array_init(&f);
const char *msg = PG(last_error_message) ? ZSTR_VAL(PG(last_error_message)) : "fatal error";
const char *kind = "fatal";
if (strncmp(msg, "Allowed memory size", 19) == 0 || strncmp(msg, "Out of memory", 13) == 0) {
kind = "memory";
} else if (strncmp(msg, "Maximum execution time", 22) == 0) {
kind = "timeout";
}
add_assoc_string(&f, "kind", (char *) kind);
add_assoc_string(&f, "message", (char *) msg);
add_assoc_str(&f, "file", PG(last_error_file) ? zend_string_copy(PG(last_error_file)) : ZSTR_EMPTY_ALLOC());
add_assoc_long(&f, "line", PG(last_error_lineno));
cryo_child_take_output(&f, level);
cryo_chan_send_zv(&cryo_child.chan, CRYO_F_FATAL, id, &f);
zval_ptr_dtor(&f);
}
/* Last resort when even the fatal answer cannot be built. */
static void cryo_child_raw_fatal(uint32_t id)
{
static const char payload[] = "a:3:{s:4:\"kind\";s:5:\"fatal\";s:7:\"message\";s:32:\"Fatal error in the sandbox child\";s:3:\"out\";s:0:\"\";}";
unsigned char hdr[CRYO_HDR];
cryo_put32(hdr, (uint32_t) (sizeof(payload) - 1));
cryo_put32(hdr + 4, CRYO_F_FATAL);
cryo_put32(hdr + 8, id);
#ifdef CRYO_BACKEND_WASM
cryo_host_send(cryo_child.chan.wid, hdr, CRYO_HDR);
cryo_host_send(cryo_child.chan.wid, (const uint8_t *) payload, (uint32_t) (sizeof(payload) - 1));
#else
ssize_t w = write(cryo_child.chan.fd, hdr, CRYO_HDR);
w = write(cryo_child.chan.fd, payload, sizeof(payload) - 1);
(void) w;
#endif
}
static void cryo_child_apply_ini(zval *ini)
{
if (!ini || Z_TYPE_P(ini) != IS_ARRAY) return;
zend_string *k; zval *v;
ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(ini), k, v) {
if (!k) continue;
zend_string *s = zval_get_string(v);
if (zend_alter_ini_entry_chars(k, ZSTR_VAL(s), ZSTR_LEN(s), PHP_INI_SYSTEM, PHP_INI_STAGE_RUNTIME) != SUCCESS) {
php_error_docref(NULL, E_WARNING, "Sandbox: cannot set %s", ZSTR_VAL(k));
}
zend_string_release(s);
} ZEND_HASH_FOREACH_END();
}
static ZEND_NAMED_FUNCTION(cryo_disabled_function)
{
zend_throw_error(NULL, "%s() has been disabled in this sandbox", ZSTR_VAL(EX(func)->common.function_name));
}
static void cryo_disable_functions(zval *list)
{
if (!list || Z_TYPE_P(list) != IS_ARRAY || !zend_hash_num_elements(Z_ARRVAL_P(list))) return;
zval *v;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(list), v) {
if (Z_TYPE_P(v) != IS_STRING) continue;
zend_string *lc = zend_string_tolower(Z_STR_P(v));
zend_function *f = zend_hash_find_ptr(CG(function_table), lc);
if (f && f->type == ZEND_INTERNAL_FUNCTION) {
f->internal_function.handler = cryo_disabled_function;
#if PHP_VERSION_ID >= 80400
f->internal_function.frameless_function_infos = NULL;
#endif
}
zend_string_release(lc);
} ZEND_HASH_FOREACH_END();
/* code compiled in the child must call the handlers (no VM builtins) */
CG(compiler_options) |= ZEND_COMPILE_NO_BUILTINS;
}
static const char *cryo_network_functions[] = {
"fsockopen", "pfsockopen", "stream_socket_client", "stream_socket_server", "socket_create",
"socket_create_listen", "socket_create_pair", "socket_connect", "curl_init", "curl_exec",
"curl_multi_exec", "ftp_connect", "ftp_ssl_connect", "mail", "dns_get_record", "gethostbyname",
"gethostbynamel", "file_get_contents", "fopen", "get_headers", NULL
};
/* Frames run under a dummy internal frame with no parent frames. */
static void cryo_child_setup(zend_execute_data *dummy)
{
memset(dummy, 0, sizeof(*dummy));
memset(&cryo_child.func, 0, sizeof(cryo_child.func));
cryo_child.func.type = ZEND_INTERNAL_FUNCTION;
cryo_child.func.function_name = zend_string_init("{sandbox}", sizeof("{sandbox}") - 1, 1);
dummy->func = (zend_function *) &cryo_child.func;
EG(current_execute_data) = dummy;
EG(exception) = NULL;
array_init(&cryo_child.queue);
array_init(&cryo_child.inbox);
array_init(&cryo_child.objects);
cryo_child.active = true;
}
/* The INIT frame: options, limits, bootstrap; answers HELLO. false: the child must leave (exit code 2). */
static bool cryo_child_hello(zend_string *payload)
{
zval init;
cryo_unser(&init, ZSTR_VAL(payload), ZSTR_LEN(payload));
HashTable *ih = Z_TYPE(init) == IS_ARRAY ? Z_ARRVAL(init) : NULL;
zval *zt = ih ? cryo_arr(ih, "timeout") : NULL;
cryo_child.timeout = zt ? zval_get_double(zt) : 0;
/* prebuilt timeout answer for the signal handler */
{
zval f;
array_init(&f);
add_assoc_string(&f, "kind", "timeout");
add_assoc_string(&f, "message", "Sandbox call exceeded its timeout");
add_assoc_string(&f, "out", "");
zend_string *s = cryo_ser(&f);
zval_ptr_dtor(&f);
if (s && ZSTR_LEN(s) + CRYO_HDR <= sizeof(cryo_child.timeout_frame)) {
cryo_put32(cryo_child.timeout_frame, (uint32_t) ZSTR_LEN(s));
cryo_put32(cryo_child.timeout_frame + 4, CRYO_F_FATAL);
memcpy(cryo_child.timeout_frame + CRYO_HDR, ZSTR_VAL(s), ZSTR_LEN(s));
cryo_child.timeout_len = CRYO_HDR + ZSTR_LEN(s);
}
if (s) zend_string_release(s);
}
int level = php_output_get_level();
zval hello;
array_init(&hello);
add_assoc_long(&hello, "pid", (zend_long) getpid());
volatile bool ok = true;
zend_try {
php_output_start_default();
if (ih) {
zval *ml = cryo_arr(ih, "memory_limit");
if (ml && Z_TYPE_P(ml) == IS_STRING && Z_STRLEN_P(ml)) {
zend_string *key = zend_string_init("memory_limit", sizeof("memory_limit") - 1, 0);
if (zend_alter_ini_entry_chars(key, Z_STRVAL_P(ml), Z_STRLEN_P(ml), PHP_INI_USER, PHP_INI_STAGE_RUNTIME) != SUCCESS) {
add_assoc_string(&hello, "error", "Cannot set memory_limit (lower than the current usage?)");
ok = false;
}
zend_string_release(key);
}
cryo_child_apply_ini(cryo_arr(ih, "ini"));
cryo_disable_functions(cryo_arr(ih, "disable"));
zval *net = cryo_arr(ih, "net_functions");
if (net && zend_is_true(net)) {
zval list;
array_init(&list);
for (int i = 0; cryo_network_functions[i]; i++) add_next_index_string(&list, cryo_network_functions[i]);
cryo_disable_functions(&list);
zval_ptr_dtor(&list);
}
zval *snap = cryo_arr(ih, "snapshot");
if (ok && snap && Z_TYPE_P(snap) == IS_STRING) {
zval fn, rv, arg;
ZVAL_STRING(&fn, "cryo_thaw");
ZVAL_COPY(&arg, snap);
ZVAL_UNDEF(&rv);
call_user_function(NULL, NULL, &fn, &rv, 1, &arg);
zval_ptr_dtor(&fn);
zval_ptr_dtor(&arg);
zval_ptr_dtor(&rv); /* a values-only file: cryo_thaw() restores and returns */
}
zval *boot = cryo_arr(ih, "bootstrap");
/* include_once semantics: a fork may already have loaded it */
if (ok && !EG(exception) && boot && Z_TYPE_P(boot) == IS_STRING
&& !zend_hash_exists(&EG(included_files), Z_STR_P(boot))) {
zval rv;
cryo_child_run_code(NULL, Z_STR_P(boot), &rv);
zval_ptr_dtor(&rv);
}
}
if (EG(exception)) {
zend_object *ex = EG(exception);
GC_ADDREF(ex);
zend_clear_exception();
zval err;
array_init(&err);
cryo_add_exception_info(&err, ex);
OBJ_RELEASE(ex);
add_assoc_zval(&hello, "exception", &err);
ok = false;
}
cryo_child_take_output(&hello, level);
} zend_catch {
zend_set_memory_limit((size_t) 0x7fffffff);
add_assoc_string(&hello, "error", PG(last_error_message) ? ZSTR_VAL(PG(last_error_message)) : "fatal error");
cryo_child_take_output(&hello, level);
ok = false;
} zend_end_try();
cryo_chan_send_zv(&cryo_child.chan, CRYO_F_HELLO, 0, &hello);
zval_ptr_dtor(&hello);
zval_ptr_dtor(&init);
return ok;
}
/* Run one queued request [type, id, payload] (type 0: cancelled). A fatal error ends the child. */
static void cryo_child_run_queued(zval *e)
{
uint32_t t = (uint32_t) Z_LVAL_P(zend_hash_index_find(Z_ARRVAL_P(e), 0));
uint32_t rid = (uint32_t) Z_LVAL_P(zend_hash_index_find(Z_ARRVAL_P(e), 1));
zend_string *p = Z_STR_P(zend_hash_index_find(Z_ARRVAL_P(e), 2));
if (t == 0) return;
int lvl = php_output_get_level();
zend_try {
cryo_child_run(t, rid, p);
} zend_catch {
/* a fatal error (memory limit, compile error...): the
* interpreter cannot be trusted any more; report and leave */
volatile bool sent = false;
cryo_child_arm(0);
zend_set_memory_limit((size_t) 0x7fffffff);
zend_try {
cryo_child_fatal(rid, lvl);
sent = true;
} zend_end_try();
if (!sent) {
cryo_child_raw_fatal(rid);
}
cryo_child_exit(255);
} zend_end_try();
}
/* The child event loop. Never returns. */
static ZEND_COLD void cryo_child_main(void)
{
zend_execute_data dummy;
cryo_child_setup(&dummy);
#ifndef CRYO_BACKEND_WASM
signal(SIGPIPE, SIG_IGN);
signal(SIGALRM, cryo_child_alarm);
#endif
/* INIT frame: options */
uint32_t type = 0, id = 0;
zend_string *payload = NULL;
if (cryo_chan_recv(&cryo_child.chan, -1, &type, &id, &payload) != 1 || type != CRYO_F_INIT) {
cryo_child_exit(3);
}
bool ok = cryo_child_hello(payload);
zend_string_release(payload);
if (!ok) {
cryo_child_exit(2);
}
for (;;) {
while (zend_hash_num_elements(Z_ARRVAL(cryo_child.queue)) == 0) {
cryo_child_pump(-1);
}
/* take every frame already sent: cancellations may concern queued requests */
while (cryo_child_pump(0) > 0) {}
zval e;
if (!cryo_shift(Z_ARRVAL(cryo_child.queue), &e)) continue;
cryo_child_run_queued(&e);
zval_ptr_dtor(&e);
}
}
/* ------------------------------------------------------------------------ */
/* Parent side: process control */
/* ------------------------------------------------------------------------ */
static ZEND_ATTRIBUTE_UNUSED void cryo_sb_drain_stderr(cryo_sandbox *sb)
{
#ifndef CRYO_BACKEND_WASM
if (sb->err_fd < 0) return;
char buf[1024];
for (;;) {
ssize_t r = read(sb->err_fd, buf, sizeof(buf));
if (r <= 0) break;
size_t n = (size_t) r; /* n <= sizeof(buf) < sizeof(errtail) */
if (sb->errlen + n > sizeof(sb->errtail)) {
size_t drop = sb->errlen + n - sizeof(sb->errtail);
memmove(sb->errtail, sb->errtail + drop, sb->errlen - drop);
sb->errlen -= drop;
}
memcpy(sb->errtail + sb->errlen, buf, n);
sb->errlen += n;
}
#else
(void) sb;
#endif
}
static void cryo_sb_close(cryo_sandbox *sb)
{
#ifndef CRYO_BACKEND_WASM
if (sb->chan.fd >= 0) { close(sb->chan.fd); sb->chan.fd = -1; }
if (sb->err_fd >= 0) { cryo_sb_drain_stderr(sb); close(sb->err_fd); sb->err_fd = -1; }
#endif
}
/* Reap the child; fills term_signal / exit_code. */
static void cryo_sb_reap(cryo_sandbox *sb, bool kill_it)
{
if (!sb->pid) return;
#ifdef CRYO_BACKEND_WASM
int32_t st = cryo_host_status((int32_t) sb->pid);
int32_t n = cryo_host_error((int32_t) sb->pid, (uint8_t *) sb->errtail, (uint32_t) sizeof(sb->errtail));
sb->errlen = n > 0 ? (size_t) n : 0;
/* the worker is ended in every case (after a fatal answer it is leaving anyway) */
cryo_host_kill((int32_t) sb->pid);
sb->exit_code = st >= 0 ? st : -1;
sb->term_signal = kill_it && st < 0 ? 9 : 0;
sb->starting = false;
#else
int status = 0;
pid_t pid = (pid_t) sb->pid;
if (kill_it) {
kill(pid, SIGKILL);
}
pid_t r;
do { r = waitpid(pid, &status, 0); } while (r < 0 && errno == EINTR);
if (r == pid) {
if (WIFSIGNALED(status)) { sb->term_signal = WTERMSIG(status); sb->exit_code = -1; }
else if (WIFEXITED(status)) { sb->exit_code = WEXITSTATUS(status); sb->term_signal = 0; }
}
#endif
sb->pid = 0;
sb->alive = false;
sb->dying = false;
cryo_sb_close(sb);
}
static zend_string *cryo_sb_stderr(cryo_sandbox *sb)
{
return zend_string_init(sb->errtail, sb->errlen, 0);
}
/* Resolve every waiting request with the given error answer. */
static void cryo_sb_fail_pending(cryo_sandbox *sb, zval *answer)
{
zend_ulong id;
zval *v;
ZEND_HASH_FOREACH_NUM_KEY_VAL(&sb->pending, id, v) {
(void) id;
if (Z_TYPE_P(v) == IS_NULL) {
ZVAL_COPY(v, answer);
}
} ZEND_HASH_FOREACH_END();
}
/* The channel closed: the child is gone. */
static void cryo_sb_lost(cryo_sandbox *sb)
{
cryo_sb_reap(sb, false);
zval a;
array_init(&a);
add_assoc_long(&a, "t", CRYO_F_FATAL);
add_assoc_string(&a, "kind", "crash");
add_assoc_long(&a, "signal", sb->term_signal);
add_assoc_long(&a, "exit_code", sb->exit_code);
add_assoc_str(&a, "stderr", cryo_sb_stderr(sb));
cryo_sb_fail_pending(sb, &a);
zval_ptr_dtor(&a);
}
#ifdef CRYO_BACKEND_WASM
/*
* The child's HELLO, read by the pump (cryo_sb_start does not wait for it in the browser): requests sent
* meanwhile are already queued in the worker. A failed bootstrap fails them all.
*/
static void cryo_sb_hello(cryo_sandbox *sb, zval *hello)
{
sb->starting = false;
HashTable *h = Z_ARRVAL_P(hello);
zval *e = cryo_arr(h, "exception"), *err = cryo_arr(h, "error"), *out = cryo_arr(h, "out");
if (out && Z_TYPE_P(out) == IS_STRING && Z_STRLEN_P(out)) {
if (sb->o.pass_output) PHPWRITE(Z_STRVAL_P(out), Z_STRLEN_P(out));
if (sb->last_output) zend_string_release(sb->last_output);
sb->last_output = zend_string_copy(Z_STR_P(out));
}
if (!e && !err) return;
zend_string *msg;
if (e && Z_TYPE_P(e) == IS_ARRAY) {
zval *c = cryo_arr(Z_ARRVAL_P(e), "class"), *m = cryo_arr(Z_ARRVAL_P(e), "message");
msg = zend_strpprintf(0, "Sandbox bootstrap failed: %s: %s",
c && Z_TYPE_P(c) == IS_STRING ? Z_STRVAL_P(c) : "?", m && Z_TYPE_P(m) == IS_STRING ? Z_STRVAL_P(m) : "?");
} else {
msg = zend_strpprintf(0, "Sandbox bootstrap failed: %s", Z_TYPE_P(err) == IS_STRING ? Z_STRVAL_P(err) : "?");
}
sb->dying = true;
if (sb->last_error) zend_string_release(sb->last_error);
sb->last_error = zend_string_copy(msg);
zval a;
array_init(&a);
add_assoc_long(&a, "t", CRYO_F_FATAL);
add_assoc_string(&a, "kind", "fatal");
add_assoc_str(&a, "message", msg);
cryo_sb_fail_pending(sb, &a);
zval_ptr_dtor(&a);
}
#endif
static void cryo_sb_store_answer(cryo_sandbox *sb, uint32_t type, uint32_t id, zend_string *payload)
{
zval a;
cryo_unser(&a, ZSTR_VAL(payload), ZSTR_LEN(payload));
if (Z_TYPE(a) != IS_ARRAY) {
zval_ptr_dtor(&a);
array_init(&a);
}
if (type == CRYO_F_MSG) {
zval *v = zend_hash_str_find(Z_ARRVAL(a), "v", 1);
zval m;
ZVAL_COPY(&m, v ? v : &EG(uninitialized_zval));
zend_hash_next_index_insert(&sb->inbox, &m);
zval_ptr_dtor(&a);
return;
}
#ifdef CRYO_BACKEND_WASM
if (type == CRYO_F_HELLO) {
cryo_sb_hello(sb, &a);
zval_ptr_dtor(&a);
return;
}
#endif
add_assoc_long(&a, "t", type);
zval *mem = zend_hash_str_find(Z_ARRVAL(a), "mem", 3);
if (mem && Z_TYPE_P(mem) == IS_LONG) sb->memory = Z_LVAL_P(mem);
if (type == CRYO_F_FATAL) {
sb->dying = true;
zval *msg = zend_hash_str_find(Z_ARRVAL(a), "message", 7);
if (msg && Z_TYPE_P(msg) == IS_STRING) {
if (sb->last_error) zend_string_release(sb->last_error);
sb->last_error = zend_string_copy(Z_STR_P(msg));
}
if (id == 0) {
/* timeout raised between requests: first waiting one */
zval *v;
ZEND_HASH_FOREACH_VAL(&sb->pending, v) {
if (Z_TYPE_P(v) == IS_NULL) { ZVAL_COPY(v, &a); break; }
} ZEND_HASH_FOREACH_END();
zval_ptr_dtor(&a);
return;
}
} else if (type == CRYO_F_ERROR) {
zval *msg = zend_hash_str_find(Z_ARRVAL(a), "message", 7);
if (msg && Z_TYPE_P(msg) == IS_STRING) {
if (sb->last_error) zend_string_release(sb->last_error);
sb->last_error = zend_string_copy(Z_STR_P(msg));
}
}
zval *slot = zend_hash_index_find(&sb->pending, id);
if (slot && Z_TYPE_P(slot) == IS_NULL) {
ZVAL_COPY_VALUE(slot, &a);
} else {
if (slot) zend_hash_index_del(&sb->pending, id); /* cancelled */
zval_ptr_dtor(&a);
}
}
/* Read one frame (or time out). 1 = frame handled, 0 = timeout, -1 = child lost */
static int cryo_sb_pump(cryo_sandbox *sb, double timeout)
{
if (!sb->alive) return -1;
#ifndef CRYO_BACKEND_WASM
/* keep the stderr pipe drained while waiting */
double deadline = timeout >= 0 ? cryo_mono() + timeout : -1;
for (;;) {
struct pollfd pf[2] = {{sb->chan.fd, POLLIN, 0}, {sb->err_fd, POLLIN, 0}};
double left = deadline < 0 ? -1 : deadline - cryo_mono();
if (deadline >= 0 && left < 0) left = 0;
int ms = left < 0 ? 1000 : (left > 1000 ? 1000 : (int) (left * 1000.0));
int r = poll(pf, sb->err_fd >= 0 ? 2 : 1, ms);
if (r < 0 && errno != EINTR) break;
if (r > 0 && (pf[1].revents & (POLLIN | POLLHUP))) cryo_sb_drain_stderr(sb);
if (r > 0 && (pf[0].revents & (POLLIN | POLLHUP | POLLERR))) break;
if (deadline >= 0 && cryo_mono() >= deadline) return 0;
}
#endif
uint32_t type, id;
zend_string *payload;
int r = cryo_chan_recv(&sb->chan, timeout < 0 ? -1 : 0.0, &type, &id, &payload);
if (r == 0) return 0;
if (r < 0) {
cryo_sb_lost(sb);
return -1;
}
cryo_sb_store_answer(sb, type, id, payload);
zend_string_release(payload);
return 1;
}
static void cryo_sb_opts_free(cryo_sb_opts *o)
{
if (o->bootstrap) zend_string_release(o->bootstrap);
if (o->snapshot) zend_string_release(o->snapshot);
if (o->memory_limit) zend_string_release(o->memory_limit);
zval_ptr_dtor(&o->ini);
zval_ptr_dtor(&o->disable);
memset(o, 0, sizeof(*o));
ZVAL_UNDEF(&o->ini);
ZVAL_UNDEF(&o->disable);
}
static bool cryo_sb_parse_opts(cryo_sb_opts *o, HashTable *opts)
{
memset(o, 0, sizeof(*o));
ZVAL_UNDEF(&o->ini);
ZVAL_UNDEF(&o->disable);
o->network = true;
o->start = CRYO_START_SPAWN;
if (!opts) return true;
zval *v;
if ((v = cryo_arr(opts, "start"))) {
zend_string *s = zval_get_string(v);
if (zend_string_equals_literal(s, "spawn")) o->start = CRYO_START_SPAWN;
else if (zend_string_equals_literal(s, "fork")) o->start = CRYO_START_FORK;
else if (zend_string_equals_literal(s, "snapshot")) o->start = CRYO_START_SNAPSHOT;
else if (zend_string_equals_literal(s, "thread")) {
zend_string_release(s);
#ifdef ZTS
zend_throw_exception(cryo_ce_exception, "Sandbox start=thread is not available yet", 0);
#else
zend_throw_exception(cryo_ce_exception, "Sandbox start=thread needs ZTS (this PHP is NTS)", 0);
#endif
return false;
} else {
zend_throw_exception_ex(cryo_ce_exception, 0, "Unknown sandbox start mode \"%s\" (spawn, fork, snapshot, thread)", ZSTR_VAL(s));
zend_string_release(s);
return false;
}
zend_string_release(s);
}
if ((v = cryo_arr(opts, "bootstrap")) && Z_TYPE_P(v) != IS_NULL) {
zend_string *s = zval_get_string(v);
char resolved[MAXPATHLEN];
if (VCWD_REALPATH(ZSTR_VAL(s), resolved)) {
o->bootstrap = zend_string_init(resolved, strlen(resolved), 0);
zend_string_release(s);
} else {
o->bootstrap = s;
}
}
zval *snap = cryo_arr(opts, "snapshot");
if (!snap) snap = cryo_arr(opts, "file");
if (snap && Z_TYPE_P(snap) == IS_STRING) o->snapshot = zend_string_copy(Z_STR_P(snap));
if (o->start == CRYO_START_SNAPSHOT && !o->snapshot) {
zend_throw_exception(cryo_ce_exception, "Sandbox start=snapshot needs the \"snapshot\" option (file to thaw)", 0);
return false;
}
if ((v = cryo_arr(opts, "memory_limit")) && Z_TYPE_P(v) != IS_NULL) {
if (Z_TYPE_P(v) == IS_LONG) {
o->memory_bytes = Z_LVAL_P(v);
o->memory_limit = zend_long_to_str(Z_LVAL_P(v));
} else {
o->memory_limit = zval_get_string(v);
zend_string *err = NULL;
o->memory_bytes = zend_ini_parse_quantity(o->memory_limit, &err);
if (err) {
zend_throw_exception_ex(cryo_ce_exception, 0, "Invalid memory_limit: %s", ZSTR_VAL(err));
zend_string_release(err);
return false;
}
}
}
if ((v = cryo_arr(opts, "cpu_time"))) o->cpu_time = zval_get_double(v);
if ((v = cryo_arr(opts, "timeout"))) o->timeout = zval_get_double(v);
if (!(v = cryo_arr(opts, "timeout")) && (v = cryo_arr(opts, "time_limit"))) o->timeout = zval_get_double(v);
if ((v = cryo_arr(opts, "ini")) && Z_TYPE_P(v) == IS_ARRAY) ZVAL_COPY(&o->ini, v);
if ((v = cryo_arr(opts, "disable_functions"))) {
array_init(&o->disable);
if (Z_TYPE_P(v) == IS_ARRAY) {
zval *e;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(v), e) {
add_next_index_str(&o->disable, zval_get_string(e));
} ZEND_HASH_FOREACH_END();
} else {
zend_string *s = zval_get_string(v);
char *tok, *save = NULL, *dup = estrndup(ZSTR_VAL(s), ZSTR_LEN(s));
for (tok = php_strtok_r(dup, ", ", &save); tok; tok = php_strtok_r(NULL, ", ", &save)) {
add_next_index_string(&o->disable, tok);
}
efree(dup);
zend_string_release(s);
}
}
if ((v = cryo_arr(opts, "network"))) o->network = zend_is_true(v);
if ((v = cryo_arr(opts, "restart"))) {
zend_string *s = zval_get_string(v);
if (zend_string_equals_literal(s, "never")) o->restart = CRYO_RESTART_NEVER;
else if (zend_string_equals_literal(s, "on_crash")) o->restart = CRYO_RESTART_ON_CRASH;
else if (zend_string_equals_literal(s, "always")) o->restart = CRYO_RESTART_ALWAYS;
else {
zend_throw_exception_ex(cryo_ce_exception, 0, "Unknown restart policy \"%s\" (never, on_crash, always)", ZSTR_VAL(s));
zend_string_release(s);
return false;
}
zend_string_release(s);
}
if ((v = cryo_arr(opts, "output"))) {
zend_string *s = zval_get_string(v);
o->pass_output = zend_string_equals_literal(s, "pass");
zend_string_release(s);
}
return true;
}
#ifndef CRYO_BACKEND_WASM
# ifdef CRYO_HAVE_SECCOMP
/* Deny socket() for every family but AF_UNIX (EPERM). */
static bool cryo_seccomp_no_network(void)
{
struct sock_filter filter[] = {
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, CRYO_AUDIT_ARCH, 1, 0),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_socket, 0, 4),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AF_UNIX, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (EPERM & SECCOMP_RET_DATA)),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
/* the last ALLOW is reached from the "not socket" jump */
struct sock_fprog prog = { (unsigned short) (sizeof(filter) / sizeof(filter[0])), filter };
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) return false;
return prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0) == 0;
}
# endif
static void cryo_child_limits(cryo_sb_opts *o)
{
if (o->cpu_time > 0) {
struct rlimit rl;
rl.rlim_cur = (rlim_t) (o->cpu_time < 1 ? 1 : o->cpu_time);
rl.rlim_max = rl.rlim_cur + 1;
setrlimit(RLIMIT_CPU, &rl);
}
# ifdef RLIMIT_AS
if (o->memory_bytes > 0) {
/* the address space already holds the binary and its libraries:
* the limit is what is mapped now plus room for memory_limit */
size_t now = 0;
FILE *f = fopen("/proc/self/statm", "r");
if (f) {
unsigned long pages = 0;
if (fscanf(f, "%lu", &pages) == 1) now = (size_t) pages * (size_t) sysconf(_SC_PAGESIZE);
fclose(f);
}
if (now) {
/* 64-bit arithmetic: no wrap-around on 32-bit targets */
uint64_t want = (uint64_t) now + (uint64_t) o->memory_bytes * 2 + UINT64_C(256) * 1024 * 1024;
if (want < (uint64_t) SIZE_MAX) {
struct rlimit rl;
rl.rlim_cur = rl.rlim_max = (rlim_t) want;
setrlimit(RLIMIT_AS, &rl);
}
}
}
# endif
}
static void cryo_fd_cloexec(int fd)
{
int fl = fcntl(fd, F_GETFD);
if (fl >= 0) fcntl(fd, F_SETFD, fl | FD_CLOEXEC);
}
static void cryo_add_arg(char ***argv, int *argc, int *cap, const char *s)
{
if (*argc + 2 > *cap) {
*cap = *cap ? *cap * 2 : 16;
*argv = erealloc(*argv, (size_t) *cap * sizeof(char *));
}
(*argv)[(*argc)++] = estrdup(s);
(*argv)[*argc] = NULL;
}
#endif
static void cryo_sb_init_payload(cryo_sandbox *sb, zval *init)
{
array_init(init);
if (sb->o.bootstrap) add_assoc_str(init, "bootstrap", zend_string_copy(sb->o.bootstrap));
if (sb->o.snapshot && sb->o.start == CRYO_START_SNAPSHOT) add_assoc_str(init, "snapshot", zend_string_copy(sb->o.snapshot));
if (sb->o.memory_limit) add_assoc_str(init, "memory_limit", zend_string_copy(sb->o.memory_limit));
if (Z_TYPE(sb->o.ini) == IS_ARRAY) { Z_ADDREF(sb->o.ini); add_assoc_zval(init, "ini", &sb->o.ini); }
if (Z_TYPE(sb->o.disable) == IS_ARRAY) { Z_ADDREF(sb->o.disable); add_assoc_zval(init, "disable", &sb->o.disable); }
add_assoc_double(init, "timeout", sb->o.timeout);
add_assoc_bool(init, "net_functions", !sb->o.network && strcmp(sb->network_level, "functions") == 0);
}
/* Start the child and wait for its HELLO. */
static bool cryo_sb_start(cryo_sandbox *sb)
{
sb->errlen = 0;
sb->term_signal = 0;
sb->exit_code = 0;
sb->dying = false;
sb->network_level = sb->o.network ? "full" : "functions";
#ifdef CRYO_BACKEND_WASM
if (sb->o.start == CRYO_START_FORK) {
zend_throw_exception(ce_sb_exception, "Sandbox start=fork is not available in WebAssembly: use start=spawn (the default)", 0);
return false;
}
zval init;
cryo_sb_init_payload(sb, &init);
add_assoc_string(&init, "start", "spawn");
zend_string *s = cryo_ser(&init);
zval_ptr_dtor(&init);
if (!s) return false;
/* what the JS host needs to know (it runs the timeouts) */
char *opts = NULL;
size_t olen = spprintf(&opts, 0, "{\"timeout\":%.3F,\"memory_limit\":%ld}", sb->o.timeout, (long) sb->o.memory_bytes);
int32_t id = cryo_host_present() ? cryo_host_spawn((const uint8_t *) opts, (uint32_t) olen) : -1;
efree(opts);
if (id < 0) {
zend_string_release(s);
zend_throw_exception(ce_sb_exception, "The WebAssembly host provides no sandbox support (Module.cryoHost.spawn)", 0);
return false;
}
sb->pid = id;
sb->chan.wid = id;
sb->alive = true;
sb->starting = true;
cryo_chan_send(&sb->chan, CRYO_F_INIT, 0, ZSTR_VAL(s), ZSTR_LEN(s));
zend_string_release(s);
/* no waiting for HELLO: the pump reads it (cryo_sb_hello) */
return true;
#else
int sv[2], ev[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) {
zend_throw_exception_ex(ce_sb_exception, 0, "socketpair() failed: %s", strerror(errno));
return false;
}
if (pipe(ev) != 0) {
close(sv[0]); close(sv[1]);
zend_throw_exception_ex(ce_sb_exception, 0, "pipe() failed: %s", strerror(errno));
return false;
}
cryo_fd_cloexec(sv[0]);
cryo_fd_cloexec(ev[0]);
char **argv = NULL;
int argc = 0, cap = 0;
if (sb->o.start != CRYO_START_FORK) {
const char *bin = PG(php_binary);
if (!bin || !*bin) {
close(sv[0]); close(sv[1]); close(ev[0]); close(ev[1]);
zend_throw_exception(ce_sb_exception, "Cannot find the PHP binary to spawn (use start => \"fork\")", 0);
return false;
}
cryo_add_arg(&argv, &argc, &cap, bin);
if (php_ini_opened_path) {
cryo_add_arg(&argv, &argc, &cap, "-c");
cryo_add_arg(&argv, &argc, &cap, php_ini_opened_path);
} else if (!php_ini_scanned_files) {
cryo_add_arg(&argv, &argc, &cap, "-n");
}
cryo_add_arg(&argv, &argc, &cap, "-d");
cryo_add_arg(&argv, &argc, &cap, "display_startup_errors=0");
/* the shared extensions loaded here (cryo among them) */
zend_module_entry *m;
ZEND_HASH_MAP_FOREACH_PTR(&module_registry, m) {
Dl_info info;
if (m->handle && dladdr(m, &info) && info.dli_fname) {
char *arg = NULL;
spprintf(&arg, 0, "extension=%s", info.dli_fname);
cryo_add_arg(&argv, &argc, &cap, "-d");
cryo_add_arg(&argv, &argc, &cap, arg);
efree(arg);
}
} ZEND_HASH_FOREACH_END();
if (Z_TYPE(sb->o.ini) == IS_ARRAY) {
zend_string *k; zval *v;
ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL(sb->o.ini), k, v) {
if (!k) continue;
zend_string *val = zval_get_string(v);
char *arg = NULL;
spprintf(&arg, 0, "%s=%s", ZSTR_VAL(k), ZSTR_VAL(val));
cryo_add_arg(&argv, &argc, &cap, "-d");
cryo_add_arg(&argv, &argc, &cap, arg);
efree(arg);
zend_string_release(val);
} ZEND_HASH_FOREACH_END();
}
if (Z_TYPE(sb->o.disable) == IS_ARRAY && zend_hash_num_elements(Z_ARRVAL(sb->o.disable))) {
smart_str l = {0};
smart_str_appends(&l, "disable_functions=");
zval *v;
bool first = true;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL(sb->o.disable), v) {
if (!first) smart_str_appendc(&l, ',');
smart_str_append(&l, Z_STR_P(v));
first = false;
} ZEND_HASH_FOREACH_END();
smart_str_0(&l);
cryo_add_arg(&argv, &argc, &cap, "-d");
cryo_add_arg(&argv, &argc, &cap, ZSTR_VAL(l.s));
smart_str_free(&l);
}
/* the cryo settings of this process (the key goes through the environment, not the command line) */
static const char *cryo_ini[] = { "cryo.allow_unsigned", "cryo.track_alloc", "cryo.engine",
"cryo.engine_internal_override", "cryo.metrics", NULL };
for (int i = 0; cryo_ini[i]; i++) {
const char *v = zend_ini_string_ex((char *) cryo_ini[i], strlen(cryo_ini[i]), 0, NULL);
if (!v) continue;
char *arg = NULL;
spprintf(&arg, 0, "%s=%s", cryo_ini[i], v);
cryo_add_arg(&argv, &argc, &cap, "-d");
cryo_add_arg(&argv, &argc, &cap, arg);
efree(arg);
}
cryo_add_arg(&argv, &argc, &cap, "-r");
cryo_add_arg(&argv, &argc, &cap, "Cryo\\Sandbox\\Channel::serve(3);");
}
# ifdef CRYO_HAVE_SECCOMP
if (!sb->o.network) sb->network_level = "seccomp";
# endif
fflush(stdout);
fflush(stderr);
pid_t pid = fork();
if (pid < 0) {
close(sv[0]); close(sv[1]); close(ev[0]); close(ev[1]);
for (int i = 0; i < argc; i++) efree(argv[i]);
if (argv) efree(argv);
zend_throw_exception_ex(ce_sb_exception, 0, "fork() failed: %s", strerror(errno));
return false;
}
if (pid == 0) {
/* ---- child ---- */
close(sv[0]);
close(ev[0]);
for (cryo_sandbox *o = cryo_live_sandboxes; o; o = o->next_live) {
if (o->chan.fd >= 0) close(o->chan.fd);
if (o->err_fd >= 0) close(o->err_fd);
}
int devnull = open("/dev/null", O_RDONLY);
if (devnull >= 0) { dup2(devnull, 0); close(devnull); }
dup2(ev[1], 1);
dup2(ev[1], 2);
close(ev[1]);
signal(SIGPIPE, SIG_IGN);
cryo_child_limits(&sb->o);
# ifdef CRYO_HAVE_SECCOMP
if (!sb->o.network && !cryo_seccomp_no_network()) {
const char m[] = "cryo sandbox: seccomp unavailable\n";
ssize_t w = write(2, m, sizeof(m) - 1);
(void) w;
_exit(4);
}
# endif
if (sb->o.start != CRYO_START_FORK) {
if (sv[1] != 3) {
dup2(sv[1], 3);
close(sv[1]);
}
const char *key = INI_STR("cryo.key");
if (key && *key) setenv("CRYO_KEY", key, 1);
execv(argv[0], argv);
_exit(127);
}
cryo_child.chan.fd = sv[1];
cryo_child.fork_mode = true;
cryo_child_main();
}
/* ---- parent ---- */
close(sv[1]);
close(ev[1]);
for (int i = 0; i < argc; i++) efree(argv[i]);
if (argv) efree(argv);
fcntl(ev[0], F_SETFL, fcntl(ev[0], F_GETFL) | O_NONBLOCK);
sb->chan.fd = sv[0];
sb->err_fd = ev[0];
sb->pid = pid;
sb->alive = true;
zval init;
cryo_sb_init_payload(sb, &init);
cryo_chan_send_zv(&sb->chan, CRYO_F_INIT, 0, &init);
zval_ptr_dtor(&init);
#endif
/* HELLO */
#ifndef CRYO_BACKEND_WASM
double deadline = cryo_mono() + 30.0;
for (;;) {
uint32_t type, id;
zend_string *payload = NULL;
int r;
#ifndef CRYO_BACKEND_WASM
struct pollfd pf[2] = {{sb->chan.fd, POLLIN, 0}, {sb->err_fd, POLLIN, 0}};
r = poll(pf, 2, 200);
if (r > 0 && (pf[1].revents & (POLLIN | POLLHUP))) cryo_sb_drain_stderr(sb);
if (r <= 0 || !(pf[0].revents & (POLLIN | POLLHUP | POLLERR))) {
if (cryo_mono() > deadline) {
cryo_sb_reap(sb, true);
zend_throw_exception(ce_sb_exception, "Sandbox did not start (no answer in 30 s)", 0);
return false;
}
continue;
}
#endif
r = cryo_chan_recv(&sb->chan, 30.0, &type, &id, &payload);
if (r != 1) {
cryo_sb_reap(sb, r == 0);
zend_string *err = cryo_sb_stderr(sb);
zend_throw_exception_ex(ce_crashed, 0, "Sandbox failed to start (%s%d)%s%s",
sb->term_signal ? "signal " : "exit code ", sb->term_signal ? sb->term_signal : sb->exit_code,
ZSTR_LEN(err) ? ": " : "", ZSTR_VAL(err));
zend_string_release(err);
return false;
}
if (type != CRYO_F_HELLO) {
zend_string_release(payload);
continue;
}
zval hello;
cryo_unser(&hello, ZSTR_VAL(payload), ZSTR_LEN(payload));
zend_string_release(payload);
zval *e = Z_TYPE(hello) == IS_ARRAY ? cryo_arr(Z_ARRVAL(hello), "exception") : NULL;
zval *err = Z_TYPE(hello) == IS_ARRAY ? cryo_arr(Z_ARRVAL(hello), "error") : NULL;
zval *out = Z_TYPE(hello) == IS_ARRAY ? cryo_arr(Z_ARRVAL(hello), "out") : NULL;
if (out && Z_TYPE_P(out) == IS_STRING && Z_STRLEN_P(out)) {
if (sb->o.pass_output) PHPWRITE(Z_STRVAL_P(out), Z_STRLEN_P(out));
if (sb->last_output) zend_string_release(sb->last_output);
sb->last_output = zend_string_copy(Z_STR_P(out));
}
if (e || err) {
cryo_sb_reap(sb, false);
if (e && Z_TYPE_P(e) == IS_ARRAY) {
zval *c = cryo_arr(Z_ARRVAL_P(e), "class"), *m = cryo_arr(Z_ARRVAL_P(e), "message");
zend_throw_exception_ex(ce_sb_exception, 0, "Sandbox bootstrap failed: %s: %s",
c ? Z_STRVAL_P(c) : "?", m ? Z_STRVAL_P(m) : "?");
} else {
zend_throw_exception_ex(ce_sb_exception, 0, "Sandbox bootstrap failed: %s",
Z_TYPE_P(err) == IS_STRING ? Z_STRVAL_P(err) : "?");
}
zval_ptr_dtor(&hello);
return false;
}
zval_ptr_dtor(&hello);
break;
}
return true;
#endif
}
/* ------------------------------------------------------------------------ */
/* Parent side: requests and answers */
/* ------------------------------------------------------------------------ */
static void cryo_sb_maybe_restart(cryo_sandbox *sb, bool after_failure);
static bool cryo_sb_check_alive(cryo_sandbox *sb)
{
if (sb->alive && !sb->dying) return true;
if (sb->dying) {
/* fatal answer received; the child is exiting */
cryo_sb_reap(sb, false);
}
if (sb->o.restart != CRYO_RESTART_NEVER) {
if (cryo_sb_start(sb)) return true;
return false;
}
zend_throw_exception(ce_sb_exception, "The sandbox is not running (call restart())", 0);
return false;
}
/* Send a request; returns its id (0 on failure, exception thrown). */
static uint32_t cryo_sb_request(cryo_sandbox *sb, uint32_t type, zval *payload)
{
if (!cryo_sb_check_alive(sb)) return 0;
zend_string *s = cryo_ser(payload);
if (!s) return 0;
uint32_t id = ++sb->next_id;
if (!id) id = ++sb->next_id;
zval nul;
ZVAL_NULL(&nul);
zend_hash_index_update(&sb->pending, id, &nul);
bool ok = cryo_chan_send(&sb->chan, type, id, ZSTR_VAL(s), ZSTR_LEN(s));
zend_string_release(s);
if (!ok) {
cryo_sb_lost(sb);
}
sb->calls++;
sb->jobs++;
return id;
}
static bool cryo_sb_ready(cryo_sandbox *sb, uint32_t id)
{
zval *v = zend_hash_index_find(&sb->pending, id);
return !v || Z_TYPE_P(v) != IS_NULL;
}
#ifdef CRYO_BACKEND_WASM
/* The browser runs PHP frame by frame: an answer can only arrive between two frames. */
static void cryo_sb_no_sync(void)
{
const char *cls = get_active_class_name(NULL);
const char *fn = get_active_function_name();
zend_throw_exception_ex(ce_sb_exception, 0,
"%s%s%s(): synchronous calls are not possible in the browser: use callAsync()->then() or Sandbox::wait()",
cls && *cls ? cls : "", cls && *cls ? "::" : "", fn ? fn : "Sandbox");
}
#endif
/* Read every frame already there (never waits). */
static void cryo_sb_drain(cryo_sandbox *sb)
{
while (sb->alive && cryo_sb_pump(sb, 0) > 0) {}
}
/* Wait until request id is answered. false on timeout (WebAssembly: not answered yet, exception thrown). */
static bool cryo_sb_wait(cryo_sandbox *sb, uint32_t id, double timeout)
{
#ifdef CRYO_BACKEND_WASM
(void) timeout;
cryo_sb_drain(sb);
if (cryo_sb_ready(sb, id)) return true;
cryo_sb_no_sync();
return false;
#endif
double deadline = timeout >= 0 ? cryo_mono() + timeout : -1;
/* safety net in the parent: the child's own timer should fire first */
double guard = sb->o.timeout > 0 ? sb->o.timeout * (double) (zend_hash_num_elements(&sb->pending) + 1) + 5.0 : -1;
double guard_deadline = guard > 0 ? cryo_mono() + guard : -1;
while (!cryo_sb_ready(sb, id)) {
double left = -1;
if (deadline >= 0) left = deadline - cryo_mono();
if (guard_deadline > 0 && (left < 0 || guard_deadline - cryo_mono() < left)) left = guard_deadline - cryo_mono();
if (left != -1 && left < 0) left = 0;
int r = cryo_sb_pump(sb, left);
if (r == 0) {
if (guard_deadline > 0 && cryo_mono() >= guard_deadline) {
cryo_sb_reap(sb, true);
zval a;
array_init(&a);
add_assoc_long(&a, "t", CRYO_F_FATAL);
add_assoc_string(&a, "kind", "timeout");
add_assoc_string(&a, "message", "Sandbox call exceeded its timeout (child killed)");
cryo_sb_fail_pending(sb, &a);
zval_ptr_dtor(&a);
continue;
}
if (deadline >= 0 && cryo_mono() >= deadline) return false;
}
if (r < 0 && !cryo_sb_ready(sb, id)) {
/* lost without answer for this id (already failed by cryo_sb_lost) */
break;
}
}
return true;
}
/* Build the PHP exception for an error answer. */
static void cryo_sb_throw(cryo_sandbox *sb, zval *a)
{
HashTable *h = Z_ARRVAL_P(a);
zval *t = cryo_arr(h, "t");
zend_long type = t ? zval_get_long(t) : CRYO_F_ERROR;
zval *msg = cryo_arr(h, "message");
const char *m = msg && Z_TYPE_P(msg) == IS_STRING ? Z_STRVAL_P(msg) : "";
if (type == CRYO_F_ERROR) {
zval *cls = cryo_arr(h, "class"), *file = cryo_arr(h, "file"), *line = cryo_arr(h, "line"),
*code = cryo_arr(h, "code"), *trace = cryo_arr(h, "trace");
zval ex;
object_init_ex(&ex, ce_remote_exc);
zend_object *o = Z_OBJ(ex);
zend_update_property_string(zend_ce_exception, o, "message", sizeof("message") - 1, m);
zend_update_property_long(zend_ce_exception, o, "code", sizeof("code") - 1, code ? zval_get_long(code) : 0);
if (file && Z_TYPE_P(file) == IS_STRING && Z_STRLEN_P(file)) {
zend_update_property_str(zend_ce_exception, o, "file", sizeof("file") - 1, Z_STR_P(file));
zend_update_property_long(zend_ce_exception, o, "line", sizeof("line") - 1, line ? zval_get_long(line) : 0);
}
zend_update_property_str(ce_remote_exc, o, "remoteClass", sizeof("remoteClass") - 1,
cls && Z_TYPE_P(cls) == IS_STRING ? Z_STR_P(cls) : ZSTR_EMPTY_ALLOC());
zend_update_property_str(ce_remote_exc, o, "remoteTrace", sizeof("remoteTrace") - 1,
trace && Z_TYPE_P(trace) == IS_STRING ? Z_STR_P(trace) : ZSTR_EMPTY_ALLOC());
zend_throw_exception_object(&ex);
return;
}
zval *kind = cryo_arr(h, "kind");
const char *k = kind && Z_TYPE_P(kind) == IS_STRING ? Z_STRVAL_P(kind) : "fatal";
if (strcmp(k, "crash") == 0) {
zval *sig = cryo_arr(h, "signal"), *code = cryo_arr(h, "exit_code"), *err = cryo_arr(h, "stderr");
zend_long s = sig ? zval_get_long(sig) : 0, c = code ? zval_get_long(code) : -1;
zval ex;
object_init_ex(&ex, (s == SIGXCPU_COMPAT) ? ce_timeout : ce_crashed);
zend_string *text = s
? (s == SIGXCPU_COMPAT ? zend_strpprintf(0, "Sandbox exceeded its CPU time (signal %d)", (int) s)
: zend_strpprintf(0, "Sandbox crashed (signal %d)", (int) s))
: zend_strpprintf(0, "Sandbox exited unexpectedly (exit code %d)", (int) c);
#ifdef CRYO_BACKEND_WASM
/* a trap or a worker error: say which (the first line of what the worker reported) */
if (err && Z_TYPE_P(err) == IS_STRING && Z_STRLEN_P(err)) {
const char *nl = memchr(Z_STRVAL_P(err), '\n', Z_STRLEN_P(err));
size_t n = nl ? (size_t) (nl - Z_STRVAL_P(err)) : Z_STRLEN_P(err);
if (n > 300) n = 300;
zend_string *t2 = zend_strpprintf(0, "%s: %.*s", ZSTR_VAL(text), (int) n, Z_STRVAL_P(err));
zend_string_release(text);
text = t2;
}
#endif
zend_update_property_str(zend_ce_exception, Z_OBJ(ex), "message", sizeof("message") - 1, text);
if (instanceof_function(Z_OBJCE(ex), ce_crashed)) {
zend_update_property_long(ce_crashed, Z_OBJ(ex), "signal", sizeof("signal") - 1, s);
zend_update_property_long(ce_crashed, Z_OBJ(ex), "exitCode", sizeof("exitCode") - 1, c);
if (err && Z_TYPE_P(err) == IS_STRING) {
zend_update_property_str(ce_crashed, Z_OBJ(ex), "stderr", sizeof("stderr") - 1, Z_STR_P(err));
}
}
if (sb->last_error) zend_string_release(sb->last_error);
sb->last_error = zend_string_copy(text);
zend_string_release(text);
zend_throw_exception_object(&ex);
return;
}
zend_class_entry *ce = strcmp(k, "memory") == 0 ? ce_memory : strcmp(k, "timeout") == 0 ? ce_timeout : ce_sb_exception;
if (strcmp(k, "exit") == 0) {
zval *st = cryo_arr(h, "status");
zend_throw_exception_ex(ce_sb_exception, 0, "Sandbox exited (exit status " ZEND_LONG_FMT ")", st ? zval_get_long(st) : 0);
return;
}
zend_throw_exception(ce, m, 0);
}
/* Turn an answer into a value or an exception; handles output and restart. */
static void cryo_sb_deliver(cryo_sandbox *sb, zval *a, zval *return_value)
{
HashTable *h = Z_ARRVAL_P(a);
zval *out = cryo_arr(h, "out");
if (out && Z_TYPE_P(out) == IS_STRING) {
if (sb->last_output) zend_string_release(sb->last_output);
sb->last_output = zend_string_copy(Z_STR_P(out));
if (sb->o.pass_output && Z_STRLEN_P(out)) PHPWRITE(Z_STRVAL_P(out), Z_STRLEN_P(out));
}
zval *t = cryo_arr(h, "t");
zend_long type = t ? zval_get_long(t) : 0;
if (type == CRYO_F_RESULT) {
zval *hd = cryo_arr(h, "h");
if (hd && Z_TYPE_P(hd) == IS_LONG) {
object_init_ex(return_value, ce_remote);
cryo_remote *r = REM(Z_OBJ_P(return_value));
ZVAL_OBJ_COPY(&r->sandbox, &sb->std);
r->handle = Z_LVAL_P(hd);
zval *c = cryo_arr(h, "class");
r->cls = c && Z_TYPE_P(c) == IS_STRING ? zend_string_copy(Z_STR_P(c)) : NULL;
} else {
zval *v = cryo_arr(h, "v");
if (v) ZVAL_COPY(return_value, v); else ZVAL_NULL(return_value);
}
cryo_sb_maybe_restart(sb, false);
return;
}
cryo_sb_throw(sb, a);
cryo_sb_maybe_restart(sb, type != CRYO_F_ERROR);
}
static void cryo_sb_maybe_restart(cryo_sandbox *sb, bool after_failure)
{
if (zend_hash_num_elements(&sb->pending) != 0) return;
if (after_failure && sb->dying) cryo_sb_reap(sb, false);
bool need = (sb->o.restart == CRYO_RESTART_ALWAYS)
|| (sb->o.restart == CRYO_RESTART_ON_CRASH && !sb->alive);
if (!need) return;
zend_object *pending_ex = EG(exception);
if (pending_ex) { EG(exception) = NULL; }
if (sb->alive) cryo_sb_reap(sb, true);
cryo_sb_start(sb);
if (EG(exception) && pending_ex) {
zend_exception_set_previous(EG(exception), pending_ex);
} else if (pending_ex) {
EG(exception) = pending_ex;
}
}
/* Claim the answer for id: value or exception. */
static void cryo_sb_claim(cryo_sandbox *sb, uint32_t id, zval *return_value)
{
zval *v = zend_hash_index_find(&sb->pending, id);
if (!v || Z_TYPE_P(v) != IS_ARRAY) {
if (v) zend_hash_index_del(&sb->pending, id);
zend_throw_exception(ce_sb_exception, "No answer for this request", 0);
return;
}
zval a;
ZVAL_COPY_VALUE(&a, v);
ZVAL_NULL(v);
zend_hash_index_del(&sb->pending, id);
cryo_sb_deliver(sb, &a, return_value);
zval_ptr_dtor(&a);
}
static void cryo_sb_sync(cryo_sandbox *sb, uint32_t type, zval *payload, zval *return_value)
{
#ifdef CRYO_BACKEND_WASM
(void) sb; (void) type; (void) payload; (void) return_value;
cryo_sb_no_sync();
return;
#endif
uint32_t id = cryo_sb_request(sb, type, payload);
if (!id) return;
cryo_sb_wait(sb, id, -1);
cryo_sb_claim(sb, id, return_value);
}
static zend_object *cryo_future_make(cryo_sandbox *sb, uint32_t id, zval *rv)
{
object_init_ex(rv, ce_future);
cryo_future *f = FUT(Z_OBJ_P(rv));
ZVAL_OBJ_COPY(&f->sandbox, &sb->std);
f->id = id;
return Z_OBJ_P(rv);
}
/* ------------------------------------------------------------------------ */
/* Object handlers */
/* ------------------------------------------------------------------------ */
static zend_object *cryo_sandbox_new(zend_class_entry *ce)
{
cryo_sandbox *sb = zend_object_alloc(sizeof(cryo_sandbox), ce);
zend_object_std_init(&sb->std, ce);
object_properties_init(&sb->std, ce);
sb->chan.fd = -1;
sb->err_fd = -1;
ZVAL_UNDEF(&sb->o.ini);
ZVAL_UNDEF(&sb->o.disable);
sb->network_level = "full";
zend_hash_init(&sb->pending, 8, NULL, ZVAL_PTR_DTOR, 0);
zend_hash_init(&sb->inbox, 8, NULL, ZVAL_PTR_DTOR, 0);
sb->next_live = cryo_live_sandboxes;
cryo_live_sandboxes = sb;
return &sb->std;
}
static void cryo_sandbox_free(zend_object *obj)
{
cryo_sandbox *sb = SB(obj);
if (sb->alive || sb->pid) {
cryo_sb_reap(sb, true); /* no zombie */
}
cryo_sb_close(sb);
for (cryo_sandbox **p = &cryo_live_sandboxes; *p; p = &(*p)->next_live) {
if (*p == sb) { *p = sb->next_live; break; }
}
zend_hash_destroy(&sb->pending);
zend_hash_destroy(&sb->inbox);
cryo_sb_opts_free(&sb->o);
if (sb->last_error) zend_string_release(sb->last_error);
if (sb->last_output) zend_string_release(sb->last_output);
zend_object_std_dtor(obj);
}
static zend_object *cryo_future_new(zend_class_entry *ce)
{
cryo_future *f = zend_object_alloc(sizeof(cryo_future), ce);
zend_object_std_init(&f->std, ce);
object_properties_init(&f->std, ce);
ZVAL_UNDEF(&f->sandbox);
ZVAL_UNDEF(&f->answer);
ZVAL_UNDEF(&f->parent);
ZVAL_UNDEF(&f->callback);
ZVAL_UNDEF(&f->on_error);
ZVAL_UNDEF(&f->group);
ZVAL_UNDEF(&f->error);
return &f->std;
}
static void cryo_future_free(zend_object *obj)
{
cryo_future *f = FUT(obj);
if (Z_TYPE(f->sandbox) == IS_OBJECT && f->state == 0 && f->id) {
/* nobody will read the answer: drop it when it arrives */
cryo_sandbox *sb = SB(Z_OBJ(f->sandbox));
zval *v = zend_hash_index_find(&sb->pending, f->id);
if (v && Z_TYPE_P(v) == IS_NULL) {
ZVAL_FALSE(v);
} else if (v) {
zend_hash_index_del(&sb->pending, f->id);
}
}
zval_ptr_dtor(&f->sandbox);
zval_ptr_dtor(&f->answer);
zval_ptr_dtor(&f->parent);
zval_ptr_dtor(&f->callback);
zval_ptr_dtor(&f->on_error);
zval_ptr_dtor(&f->group);
zval_ptr_dtor(&f->error);
zend_object_std_dtor(obj);
}
static HashTable *cryo_future_gc(zend_object *obj, zval **table, int *n)
{
cryo_future *f = FUT(obj);
zend_get_gc_buffer *buf = zend_get_gc_buffer_create();
zend_get_gc_buffer_add_zval(buf, &f->sandbox);
zend_get_gc_buffer_add_zval(buf, &f->answer);
zend_get_gc_buffer_add_zval(buf, &f->parent);
zend_get_gc_buffer_add_zval(buf, &f->callback);
zend_get_gc_buffer_add_zval(buf, &f->on_error);
zend_get_gc_buffer_add_zval(buf, &f->group);
zend_get_gc_buffer_add_zval(buf, &f->error);
zend_get_gc_buffer_use(buf, table, n);
return zend_std_get_properties(obj);
}
static zend_object *cryo_remote_new(zend_class_entry *ce)
{
cryo_remote *r = zend_object_alloc(sizeof(cryo_remote), ce);
zend_object_std_init(&r->std, ce);
object_properties_init(&r->std, ce);
ZVAL_UNDEF(&r->sandbox);
return &r->std;
}
static void cryo_remote_free(zend_object *obj)
{
cryo_remote *r = REM(obj);
if (Z_TYPE(r->sandbox) == IS_OBJECT && r->handle) {
cryo_sandbox *sb = SB(Z_OBJ(r->sandbox));
if (sb->alive && !sb->dying) {
/* fire and forget: the answer is dropped */
zval req;
array_init(&req);
add_assoc_string(&req, "op", "free");
add_assoc_long(&req, "h", r->handle);
zend_string *s = cryo_ser(&req);
zval_ptr_dtor(&req);
if (s) {
uint32_t id = ++sb->next_id;
zval f;
ZVAL_FALSE(&f);
zend_hash_index_update(&sb->pending, id, &f);
cryo_chan_send(&sb->chan, CRYO_F_PROXY, id, ZSTR_VAL(s), ZSTR_LEN(s));
zend_string_release(s);
}
}
}
zval_ptr_dtor(&r->sandbox);
if (r->cls) zend_string_release(r->cls);
zend_object_std_dtor(obj);
}
static zend_object *cryo_proxy_new(zend_class_entry *ce)
{
cryo_proxy *p = zend_object_alloc(sizeof(cryo_proxy), ce);
zend_object_std_init(&p->std, ce);
object_properties_init(&p->std, ce);
ZVAL_UNDEF(&p->sandbox);
return &p->std;
}
static void cryo_proxy_free(zend_object *obj)
{
zval_ptr_dtor(&PRX(obj)->sandbox);
zend_object_std_dtor(obj);
}
static zend_object *cryo_pool_new(zend_class_entry *ce)
{
cryo_pool *p = zend_object_alloc(sizeof(cryo_pool), ce);
zend_object_std_init(&p->std, ce);
object_properties_init(&p->std, ce);
array_init(&p->workers);
ZVAL_UNDEF(&p->options);
return &p->std;
}
static void cryo_pool_free(zend_object *obj)
{
cryo_pool *p = POOL(obj);
zval_ptr_dtor(&p->workers);
zval_ptr_dtor(&p->options);
zend_object_std_dtor(obj);
}
static HashTable *cryo_pool_gc(zend_object *obj, zval **table, int *n)
{
cryo_pool *p = POOL(obj);
zend_get_gc_buffer *buf = zend_get_gc_buffer_create();
zend_get_gc_buffer_add_zval(buf, &p->workers);
zend_get_gc_buffer_use(buf, table, n);
return zend_std_get_properties(obj);
}
/* ------------------------------------------------------------------------ */
/* Sandbox methods */
/* ------------------------------------------------------------------------ */
#define THIS_SB SB(Z_OBJ_P(ZEND_THIS))
static bool cryo_sb_construct(cryo_sandbox *sb, HashTable *opts)
{
if (sb->alive) {
zend_throw_exception(ce_sb_exception, "Sandbox already constructed", 0);
return false;
}
cryo_sb_opts_free(&sb->o);
if (!cryo_sb_parse_opts(&sb->o, opts)) return false;
return cryo_sb_start(sb);
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, __construct)
{
HashTable *opts = NULL;
ZEND_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_HT(opts)
ZEND_PARSE_PARAMETERS_END();
cryo_sb_construct(THIS_SB, opts);
}
static void cryo_sb_static_ctor(INTERNAL_FUNCTION_PARAMETERS, const char *start)
{
zend_string *file = NULL;
HashTable *opts = NULL;
if (start) {
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_PATH_STR(file)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_HT(opts)
ZEND_PARSE_PARAMETERS_END();
} else {
ZEND_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_HT(opts)
ZEND_PARSE_PARAMETERS_END();
}
zval o;
if (opts) ZVAL_ARR(&o, zend_array_dup(opts)); else array_init(&o);
add_assoc_string(&o, "start", start ? (char *) start : "spawn");
if (file) add_assoc_str(&o, "snapshot", zend_string_copy(file));
object_init_ex(return_value, ce_sandbox);
cryo_sb_construct(SB(Z_OBJ_P(return_value)), Z_ARRVAL(o));
zval_ptr_dtor(&o);
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, spawn) { cryo_sb_static_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU, NULL); }
ZEND_METHOD(Cryo_Sandbox_Sandbox, fromSnapshot) { cryo_sb_static_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU, "snapshot"); }
static void cryo_sb_call_payload(zval *req, zval *fn, HashTable *args)
{
array_init(req);
Z_TRY_ADDREF_P(fn);
add_assoc_zval(req, "f", fn);
zval a;
if (args) ZVAL_ARR(&a, zend_array_dup(args)); else array_init(&a);
add_assoc_zval(req, "a", &a);
}
static bool cryo_check_callable_spec(zval *fn)
{
if (Z_TYPE_P(fn) == IS_STRING) return true;
if (Z_TYPE_P(fn) == IS_ARRAY && zend_hash_num_elements(Z_ARRVAL_P(fn)) == 2) {
zval *c = zend_hash_index_find(Z_ARRVAL_P(fn), 0), *m = zend_hash_index_find(Z_ARRVAL_P(fn), 1);
if (c && m && Z_TYPE_P(c) == IS_STRING && Z_TYPE_P(m) == IS_STRING) return true;
}
zend_argument_type_error(1, "must be a function name or a [class, method] array of strings");
return false;
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, call)
{
zval *fn; HashTable *args = NULL;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ZVAL(fn)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_HT(args)
ZEND_PARSE_PARAMETERS_END();
if (!cryo_check_callable_spec(fn)) RETURN_THROWS();
zval req;
cryo_sb_call_payload(&req, fn, args);
cryo_sb_sync(THIS_SB, CRYO_F_CALL, &req, return_value);
zval_ptr_dtor(&req);
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, callAsync)
{
zval *fn; HashTable *args = NULL;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ZVAL(fn)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_HT(args)
ZEND_PARSE_PARAMETERS_END();
if (!cryo_check_callable_spec(fn)) RETURN_THROWS();
zval req;
cryo_sb_call_payload(&req, fn, args);
uint32_t id = cryo_sb_request(THIS_SB, CRYO_F_CALL, &req);
zval_ptr_dtor(&req);
if (!id) RETURN_THROWS();
cryo_future_make(THIS_SB, id, return_value);
}
static void cryo_sb_simple(INTERNAL_FUNCTION_PARAMETERS, uint32_t type, const char *key, bool async)
{
zend_string *arg;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(arg)
ZEND_PARSE_PARAMETERS_END();
zval req;
array_init(&req);
add_assoc_str(&req, key, zend_string_copy(arg));
if (async) {
uint32_t id = cryo_sb_request(THIS_SB, type, &req);
zval_ptr_dtor(&req);
if (!id) RETURN_THROWS();
cryo_future_make(THIS_SB, id, return_value);
return;
}
cryo_sb_sync(THIS_SB, type, &req, return_value);
zval_ptr_dtor(&req);
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, eval) { cryo_sb_simple(INTERNAL_FUNCTION_PARAM_PASSTHRU, CRYO_F_EVAL, "c", false); }
ZEND_METHOD(Cryo_Sandbox_Sandbox, evalAsync) { cryo_sb_simple(INTERNAL_FUNCTION_PARAM_PASSTHRU, CRYO_F_EVAL, "c", true); }
ZEND_METHOD(Cryo_Sandbox_Sandbox, include) { cryo_sb_simple(INTERNAL_FUNCTION_PARAM_PASSTHRU, CRYO_F_INCLUDE, "f", false); }
ZEND_METHOD(Cryo_Sandbox_Sandbox, get) { cryo_sb_simple(INTERNAL_FUNCTION_PARAM_PASSTHRU, CRYO_F_GET, "n", false); }
ZEND_METHOD(Cryo_Sandbox_Sandbox, includeAsync) { cryo_sb_simple(INTERNAL_FUNCTION_PARAM_PASSTHRU, CRYO_F_INCLUDE, "f", true); }
ZEND_METHOD(Cryo_Sandbox_Sandbox, getAsync) { cryo_sb_simple(INTERNAL_FUNCTION_PARAM_PASSTHRU, CRYO_F_GET, "n", true); }
/* setAsync(name, value): a Future of null */
ZEND_METHOD(Cryo_Sandbox_Sandbox, setAsync)
{
zend_string *name; zval *value;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_STR(name)
Z_PARAM_ZVAL(value)
ZEND_PARSE_PARAMETERS_END();
zval req;
array_init(&req);
add_assoc_str(&req, "n", zend_string_copy(name));
Z_TRY_ADDREF_P(value);
add_assoc_zval(&req, "v", value);
uint32_t id = cryo_sb_request(THIS_SB, CRYO_F_SET, &req);
zval_ptr_dtor(&req);
if (!id) RETURN_THROWS();
cryo_future_make(THIS_SB, id, return_value);
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, metricsAsync)
{
ZEND_PARSE_PARAMETERS_NONE();
zval req;
array_init(&req);
uint32_t id = cryo_sb_request(THIS_SB, CRYO_F_METRICS, &req);
zval_ptr_dtor(&req);
if (!id) RETURN_THROWS();
cryo_future_make(THIS_SB, id, return_value);
}
/* Every message the child sent so far (Channel::parent()->send()), oldest first; never waits. */
ZEND_METHOD(Cryo_Sandbox_Sandbox, messages)
{
ZEND_PARSE_PARAMETERS_NONE();
cryo_sandbox *sb = THIS_SB;
cryo_sb_drain(sb);
array_init(return_value);
zval m;
while (cryo_shift(&sb->inbox, &m)) add_next_index_zval(return_value, &m);
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, snapshot)
{
cryo_sb_simple(INTERNAL_FUNCTION_PARAM_PASSTHRU, CRYO_F_SNAPSHOT, "f", false);
if (!EG(exception)) { zval_ptr_dtor(return_value); ZVAL_NULL(return_value); }
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, freeze)
{
cryo_sb_simple(INTERNAL_FUNCTION_PARAM_PASSTHRU, CRYO_F_FREEZE, "f", false);
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, set)
{
zend_string *name; zval *value;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_STR(name)
Z_PARAM_ZVAL(value)
ZEND_PARSE_PARAMETERS_END();
zval req;
array_init(&req);
add_assoc_str(&req, "n", zend_string_copy(name));
Z_TRY_ADDREF_P(value);
add_assoc_zval(&req, "v", value);
zval rv;
ZVAL_NULL(&rv);
cryo_sb_sync(THIS_SB, CRYO_F_SET, &req, &rv);
zval_ptr_dtor(&rv);
zval_ptr_dtor(&req);
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, metrics)
{
ZEND_PARSE_PARAMETERS_NONE();
zval req;
array_init(&req);
cryo_sb_sync(THIS_SB, CRYO_F_METRICS, &req, return_value);
zval_ptr_dtor(&req);
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, proxy)
{
zend_string *expr;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(expr)
ZEND_PARSE_PARAMETERS_END();
zval req;
array_init(&req);
add_assoc_string(&req, "op", "new");
add_assoc_str(&req, "x", zend_string_copy(expr));
cryo_sb_sync(THIS_SB, CRYO_F_PROXY, &req, return_value);
zval_ptr_dtor(&req);
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, send)
{
zval *msg;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(msg)
ZEND_PARSE_PARAMETERS_END();
cryo_sandbox *sb = THIS_SB;
if (!cryo_sb_check_alive(sb)) RETURN_THROWS();
zend_string *s = cryo_ser(msg);
if (!s) RETURN_THROWS();
if (!cryo_chan_send(&sb->chan, CRYO_F_MSG, 0, ZSTR_VAL(s), ZSTR_LEN(s))) {
cryo_sb_lost(sb);
}
zend_string_release(s);
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, recv)
{
double timeout = -1; bool tnull = true;
ZEND_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_DOUBLE_OR_NULL(timeout, tnull)
ZEND_PARSE_PARAMETERS_END();
cryo_sandbox *sb = THIS_SB;
#ifdef CRYO_BACKEND_WASM
cryo_sb_drain(sb);
if (zend_hash_num_elements(&sb->inbox) == 0) {
if (!tnull) zend_throw_exception(ce_timeout, "No message from the sandbox yet (the browser cannot wait: use messages() at each frame)", 0);
else cryo_sb_no_sync();
RETURN_THROWS();
}
#endif
double deadline = tnull ? -1 : cryo_mono() + timeout;
while (zend_hash_num_elements(&sb->inbox) == 0) {
if (!sb->alive) {
zend_throw_exception(ce_sb_exception, "The sandbox is not running", 0);
RETURN_THROWS();
}
double left = deadline < 0 ? -1 : deadline - cryo_mono();
if (deadline >= 0 && left <= 0) {
zend_throw_exception(ce_timeout, "No message from the sandbox before the timeout", 0);
RETURN_THROWS();
}
cryo_sb_pump(sb, left);
}
cryo_shift(&sb->inbox, return_value);
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, stream)
{
ZEND_PARSE_PARAMETERS_NONE();
#ifdef CRYO_BACKEND_WASM
zend_throw_exception(ce_sb_exception, "stream() is not available with the WebAssembly backend", 0);
RETURN_THROWS();
#else
cryo_sandbox *sb = THIS_SB;
if (!sb->alive) {
zend_throw_exception(ce_sb_exception, "The sandbox is not running", 0);
RETURN_THROWS();
}
int fd = dup(sb->chan.fd);
php_stream *s = fd >= 0 ? php_stream_fopen_from_fd(fd, "r", NULL) : NULL;
if (!s) {
if (fd >= 0) close(fd);
zend_throw_exception(ce_sb_exception, "Cannot open a stream on the sandbox channel", 0);
RETURN_THROWS();
}
php_stream_to_zval(s, return_value);
#endif
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, engine)
{
ZEND_PARSE_PARAMETERS_NONE();
object_init_ex(return_value, ce_engine_proxy);
ZVAL_OBJ_COPY(&PRX(Z_OBJ_P(return_value))->sandbox, Z_OBJ_P(ZEND_THIS));
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, kill)
{
ZEND_PARSE_PARAMETERS_NONE();
cryo_sandbox *sb = THIS_SB;
if (sb->pid) {
cryo_sb_reap(sb, true);
zval a;
array_init(&a);
add_assoc_long(&a, "t", CRYO_F_FATAL);
add_assoc_string(&a, "kind", "crash");
add_assoc_long(&a, "signal", sb->term_signal);
add_assoc_long(&a, "exit_code", sb->exit_code);
add_assoc_str(&a, "stderr", cryo_sb_stderr(sb));
cryo_sb_fail_pending(sb, &a);
zval_ptr_dtor(&a);
}
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, restart)
{
ZEND_PARSE_PARAMETERS_NONE();
cryo_sandbox *sb = THIS_SB;
if (sb->pid) cryo_sb_reap(sb, true);
zval a;
array_init(&a);
add_assoc_long(&a, "t", CRYO_F_FATAL);
add_assoc_string(&a, "kind", "fatal");
add_assoc_string(&a, "message", "The sandbox was restarted");
cryo_sb_fail_pending(sb, &a);
zval_ptr_dtor(&a);
zend_hash_clean(&sb->inbox);
sb->jobs = 0;
cryo_sb_start(sb);
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, status)
{
ZEND_PARSE_PARAMETERS_NONE();
cryo_sandbox *sb = THIS_SB;
#ifndef CRYO_BACKEND_WASM
if (sb->alive && !sb->dying && sb->pid) {
int st;
if (waitpid((pid_t) sb->pid, &st, WNOHANG) == (pid_t) sb->pid) {
if (WIFSIGNALED(st)) { sb->term_signal = WTERMSIG(st); sb->exit_code = -1; }
else if (WIFEXITED(st)) sb->exit_code = WEXITSTATUS(st);
sb->pid = 0;
sb->alive = false;
cryo_sb_close(sb);
}
}
#else
cryo_sb_drain(sb);
#endif
if (sb->dying) cryo_sb_reap(sb, false);
array_init(return_value);
add_assoc_long(return_value, "pid", sb->pid);
add_assoc_bool(return_value, "alive", sb->alive);
add_assoc_bool(return_value, "starting", sb->starting);
add_assoc_string(return_value, "start", sb->o.start == CRYO_START_FORK ? "fork" : sb->o.start == CRYO_START_SNAPSHOT ? "snapshot" : "spawn");
add_assoc_string(return_value, "backend", (char *) cryo_platform_name());
add_assoc_long(return_value, "calls", sb->calls);
zend_long waiting = 0;
zval *v;
ZEND_HASH_FOREACH_VAL(&sb->pending, v) { if (Z_TYPE_P(v) == IS_NULL) waiting++; } ZEND_HASH_FOREACH_END();
add_assoc_long(return_value, "pending", waiting);
add_assoc_long(return_value, "memory", sb->memory);
if (sb->last_error) add_assoc_str(return_value, "last_error", zend_string_copy(sb->last_error));
else add_assoc_null(return_value, "last_error");
if (sb->term_signal) add_assoc_long(return_value, "signal", sb->term_signal); else add_assoc_null(return_value, "signal");
if (!sb->alive && !sb->term_signal) add_assoc_long(return_value, "exit_code", sb->exit_code); else add_assoc_null(return_value, "exit_code");
add_assoc_string(return_value, "network", (char *) sb->network_level);
add_assoc_string(return_value, "restart", sb->o.restart == CRYO_RESTART_ALWAYS ? "always" : sb->o.restart == CRYO_RESTART_ON_CRASH ? "on_crash" : "never");
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, output)
{
ZEND_PARSE_PARAMETERS_NONE();
cryo_sandbox *sb = THIS_SB;
if (sb->last_output) RETURN_STR_COPY(sb->last_output);
RETURN_EMPTY_STRING();
}
/* --- futures that settle without blocking -------------------------------- */
/*
* then() and Sandbox::wait() futures not settled yet, by object handle (a strong reference: the callbacks
* of `$sb->callAsync(...)->then(fn ...)` run even when nobody keeps the returned future). Sandbox::pump()
* settles them.
*/
static HashTable *cryo_watch = NULL;
static void cryo_watch_add(zend_object *o)
{
if (!cryo_watch) {
ALLOC_HASHTABLE(cryo_watch);
zend_hash_init(cryo_watch, 8, NULL, ZVAL_PTR_DTOR, 0);
}
zval z;
ZVAL_OBJ_COPY(&z, o);
zend_hash_index_update(cryo_watch, o->handle, &z);
}
static bool cryo_future_is_request(cryo_future *f)
{
return Z_TYPE(f->sandbox) == IS_OBJECT;
}
static cryo_future *cryo_future_root(cryo_future *f)
{
while (Z_TYPE(f->parent) == IS_OBJECT) f = FUT(Z_OBJ(f->parent));
return f;
}
/* Answered (requests), or every source answered (then: the request at the start of the chain; wait: all). */
static bool cryo_future_is_ready(cryo_future *f)
{
if (f->state != 0) return true;
if (cryo_future_is_request(f)) return cryo_sb_ready(SB(Z_OBJ(f->sandbox)), f->id);
if (Z_TYPE(f->parent) == IS_OBJECT) return cryo_future_is_ready(FUT(Z_OBJ(f->parent)));
if (Z_TYPE(f->group) == IS_ARRAY) {
zval *z;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL(f->group), z) {
if (!cryo_future_is_ready(FUT(Z_OBJ_P(z)))) return false;
} ZEND_HASH_FOREACH_END();
}
return true;
}
/* Read the frames already there for every sandbox this future depends on (never waits). */
static void cryo_future_drain(cryo_future *f)
{
if (f->state != 0) return;
if (cryo_future_is_request(f)) {
cryo_sb_drain(SB(Z_OBJ(f->sandbox)));
} else if (Z_TYPE(f->parent) == IS_OBJECT) {
cryo_future_drain(FUT(Z_OBJ(f->parent)));
} else if (Z_TYPE(f->group) == IS_ARRAY) {
zval *z;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL(f->group), z) { cryo_future_drain(FUT(Z_OBJ_P(z))); } ZEND_HASH_FOREACH_END();
}
}
/* Output and restart policy of an answer taken without being delivered (cryo_sb_deliver without throwing). */
static void cryo_sb_answer_effects(cryo_sandbox *sb, zval *a)
{
HashTable *h = Z_ARRVAL_P(a);
zval *out = cryo_arr(h, "out");
if (out && Z_TYPE_P(out) == IS_STRING) {
if (sb->last_output) zend_string_release(sb->last_output);
sb->last_output = zend_string_copy(Z_STR_P(out));
if (sb->o.pass_output && Z_STRLEN_P(out)) PHPWRITE(Z_STRVAL_P(out), Z_STRLEN_P(out));
}
zval *t = cryo_arr(h, "t");
zend_long type = t ? zval_get_long(t) : 0;
cryo_sb_maybe_restart(sb, type != CRYO_F_RESULT && type != CRYO_F_ERROR);
if (EG(exception)) {
/* the restart failed: keep the reason, the next request reports it */
zend_object *ex = EG(exception);
zval rv, *m = zend_read_property_ex(zend_get_exception_base(ex), ex, ZSTR_KNOWN(ZEND_STR_MESSAGE), 1, &rv);
if (sb->last_error) zend_string_release(sb->last_error);
sb->last_error = zval_get_string(m);
zend_clear_exception();
}
}
/* Move the answer of a request from the sandbox into the future. */
static void cryo_future_take(cryo_future *f)
{
cryo_sandbox *sb = SB(Z_OBJ(f->sandbox));
zval *v = zend_hash_index_find(&sb->pending, f->id);
if (v && Z_TYPE_P(v) == IS_ARRAY) {
ZVAL_COPY(&f->answer, v);
zend_hash_index_del(&sb->pending, f->id);
} else {
array_init(&f->answer);
add_assoc_long(&f->answer, "t", CRYO_F_FATAL);
add_assoc_string(&f->answer, "kind", "fatal");
add_assoc_string(&f->answer, "message", "No answer for this request");
if (v) zend_hash_index_del(&sb->pending, f->id);
}
f->state = 1;
}
/* Keep the pending exception in f->error (state 3). */
static void cryo_future_fail_with_current(cryo_future *f)
{
zend_object *ex = EG(exception);
GC_ADDREF(ex);
zend_clear_exception();
zval_ptr_dtor(&f->error);
ZVAL_OBJ(&f->error, ex);
f->state = 3;
}
/* The exception of a settled future that failed or was cancelled (built once), NULL otherwise. */
static zend_object *cryo_future_exception(cryo_future *f)
{
if (Z_TYPE(f->error) == IS_OBJECT) return Z_OBJ(f->error);
if (EG(exception)) return NULL; /* never build one over a pending exception */
if (f->state == 2) {
zend_throw_exception(ce_sb_exception, "The future was cancelled", 0);
} else if (f->state == 1 && cryo_future_is_request(f)) {
zval *t = cryo_arr(Z_ARRVAL(f->answer), "t");
if (t && zval_get_long(t) == CRYO_F_RESULT) return NULL;
cryo_sb_throw(SB(Z_OBJ(f->sandbox)), &f->answer);
} else {
return NULL;
}
if (!EG(exception)) return NULL;
zend_object *ex = EG(exception);
GC_ADDREF(ex);
zend_clear_exception();
ZVAL_OBJ(&f->error, ex);
return ex;
}
/* The value of a settled future that succeeded. */
static void cryo_future_value(cryo_future *f, zval *out)
{
if (f->state != 1) { ZVAL_NULL(out); return; }
if (cryo_future_is_request(f)) {
zval *v = cryo_arr(Z_ARRVAL(f->answer), "v");
if (v) ZVAL_COPY(out, v); else ZVAL_NULL(out);
return;
}
ZVAL_COPY(out, &f->answer);
}
/*
* Settle f if its sources allow it now: take a request's answer, run a then() callback, complete a wait().
* Never waits, never throws (callback exceptions fail the future). true when f is settled.
*/
static bool cryo_future_try_settle(cryo_future *f)
{
if (f->state == 4) return false; /* its callback is running */
if (f->state != 0) return true;
if (EG(exception)) return false;
if (cryo_future_is_request(f)) {
cryo_sandbox *sb = SB(Z_OBJ(f->sandbox));
if (!cryo_sb_ready(sb, f->id)) return false;
cryo_future_take(f);
cryo_sb_answer_effects(sb, &f->answer);
return true;
}
if (Z_TYPE(f->parent) == IS_OBJECT) {
cryo_future *p = FUT(Z_OBJ(f->parent));
if (!cryo_future_try_settle(p) || f->state != 0) return f->state != 0;
zend_object *ex = cryo_future_exception(p);
zval arg, *cb;
if (ex) {
if (Z_TYPE(f->on_error) == IS_UNDEF) {
ZVAL_OBJ_COPY(&f->error, ex);
f->state = 3;
return true;
}
ZVAL_OBJ_COPY(&arg, ex);
cb = &f->on_error;
} else {
cryo_future_value(p, &arg);
cb = &f->callback;
}
/* the callback may pump again: it must not run twice */
zval busy_cb;
ZVAL_COPY_VALUE(&busy_cb, cb);
ZVAL_UNDEF(cb);
zval rv;
ZVAL_UNDEF(&rv);
f->state = 4; /* running its callback */
call_user_function(NULL, NULL, &busy_cb, &rv, 1, &arg);
zval_ptr_dtor(&busy_cb);
zval_ptr_dtor(&arg);
zval_ptr_dtor(&f->callback);
zval_ptr_dtor(&f->on_error);
ZVAL_UNDEF(&f->callback);
ZVAL_UNDEF(&f->on_error);
if (EG(exception)) {
zval_ptr_dtor(&rv);
cryo_future_fail_with_current(f);
} else {
if (Z_TYPE(rv) == IS_UNDEF) ZVAL_NULL(&rv);
ZVAL_COPY_VALUE(&f->answer, &rv);
f->state = 1;
}
return true;
}
if (Z_TYPE(f->group) == IS_ARRAY) {
bool all = true;
zval *z;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL(f->group), z) {
cryo_future *m = FUT(Z_OBJ_P(z));
if (!cryo_future_try_settle(m) || m->state == 4) { all = false; continue; }
zend_object *ex = cryo_future_exception(m);
if (ex) {
ZVAL_OBJ_COPY(&f->error, ex);
f->state = 3;
return true;
}
} ZEND_HASH_FOREACH_END();
if (all) {
zval values;
array_init(&values);
zend_string *k; zend_ulong i;
ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL(f->group), i, k, z) {
zval v;
cryo_future_value(FUT(Z_OBJ_P(z)), &v);
if (k) zend_hash_update(Z_ARRVAL(values), k, &v); else zend_hash_index_update(Z_ARRVAL(values), i, &v);
} ZEND_HASH_FOREACH_END();
if (f->single) {
zval *first = zend_hash_index_find(Z_ARRVAL(values), 0);
ZVAL_COPY(&f->answer, first ? first : &EG(uninitialized_zval));
zval_ptr_dtor(&values);
} else {
ZVAL_COPY_VALUE(&f->answer, &values);
}
f->state = 1;
return true;
}
if (f->deadline > 0 && cryo_mono() >= f->deadline) {
zend_throw_exception(ce_timeout, "Sandbox::wait(): not every future settled before the timeout", 0);
cryo_future_fail_with_current(f);
return true;
}
return false;
}
return false;
}
/* Wait (POSIX) until f is settled; false on timeout. WebAssembly: false with an exception if not yet. */
static bool cryo_future_wait_settled(cryo_future *f, double timeout)
{
if (f->state != 0 && f->state != 4) return true;
if (cryo_future_is_request(f)) {
if (!cryo_sb_wait(SB(Z_OBJ(f->sandbox)), f->id, timeout)) return false;
return cryo_future_try_settle(f);
}
if (Z_TYPE(f->parent) == IS_OBJECT) {
if (!cryo_future_wait_settled(FUT(Z_OBJ(f->parent)), timeout)) return false;
return cryo_future_try_settle(f) && f->state != 4;
}
double deadline = timeout >= 0 ? cryo_mono() + timeout : -1;
for (;;) {
if (cryo_future_try_settle(f)) return true;
if (EG(exception)) return false;
cryo_future *wait_for = NULL;
zval *z;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL(f->group), z) {
cryo_future *m = FUT(Z_OBJ_P(z));
if (m->state == 0) { wait_for = m; break; }
} ZEND_HASH_FOREACH_END();
if (!wait_for) return false;
double now = cryo_mono();
double left = deadline < 0 ? -1 : deadline - now;
if (deadline >= 0 && left < 0) left = 0;
if (f->deadline > 0) {
double gl = f->deadline - now;
if (gl < 0) gl = 0;
if (left < 0 || gl < left) left = gl;
}
if (!cryo_future_wait_settled(wait_for, left)) {
if (EG(exception)) return false;
if (f->deadline > 0 && cryo_mono() >= f->deadline) continue; /* try_settle fails it */
return false;
}
}
}
/* --- waiting on several futures ---------------------------------------- */
/* POSIX: pump (at most `left` seconds, once) one sandbox some future depends on. */
static void cryo_future_pump_some(cryo_future *f, double left, bool *any)
{
if (f->state != 0) return;
if (cryo_future_is_request(f)) {
cryo_sandbox *sb = SB(Z_OBJ(f->sandbox));
if (sb->alive && !cryo_sb_ready(sb, f->id)) {
cryo_sb_pump(sb, *any ? 0 : left);
*any = true;
}
} else if (Z_TYPE(f->parent) == IS_OBJECT) {
cryo_future_pump_some(FUT(Z_OBJ(f->parent)), left, any);
} else if (Z_TYPE(f->group) == IS_ARRAY) {
zval *z;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL(f->group), z) { cryo_future_pump_some(FUT(Z_OBJ_P(z)), left, any); } ZEND_HASH_FOREACH_END();
}
}
/* Wait for any of the futures to become ready. false on timeout (WebAssembly: none ready now). */
static bool cryo_futures_poll(HashTable *futures, double timeout)
{
zval *z;
#ifdef CRYO_BACKEND_WASM
(void) timeout;
ZEND_HASH_FOREACH_VAL(futures, z) { cryo_future_drain(FUT(Z_OBJ_P(z))); } ZEND_HASH_FOREACH_END();
ZEND_HASH_FOREACH_VAL(futures, z) {
if (cryo_future_is_ready(FUT(Z_OBJ_P(z)))) return true;
} ZEND_HASH_FOREACH_END();
return false;
#else
double deadline = timeout >= 0 ? cryo_mono() + timeout : -1;
for (;;) {
ZEND_HASH_FOREACH_VAL(futures, z) {
if (cryo_future_is_ready(FUT(Z_OBJ_P(z)))) return true;
} ZEND_HASH_FOREACH_END();
double left = deadline < 0 ? 0.05 : deadline - cryo_mono();
if (deadline >= 0 && left <= 0) return false;
if (left > 0.05) left = 0.05;
/* pump every sandbox that has something pending */
bool any = false;
ZEND_HASH_FOREACH_VAL(futures, z) {
cryo_future_pump_some(FUT(Z_OBJ_P(z)), left, &any);
} ZEND_HASH_FOREACH_END();
if (!any) return true;
}
#endif
}
static bool cryo_check_futures(HashTable *futures)
{
zval *z;
ZEND_HASH_FOREACH_VAL(futures, z) {
if (Z_TYPE_P(z) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(z), ce_future)) {
zend_argument_type_error(1, "must contain only Cryo\\Sandbox\\Future objects");
return false;
}
} ZEND_HASH_FOREACH_END();
return true;
}
static void cryo_future_await(cryo_future *f, double timeout, zval *return_value);
ZEND_METHOD(Cryo_Sandbox_Sandbox, awaitAll)
{
HashTable *futures; double timeout = -1; bool tnull = true;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ARRAY_HT(futures)
Z_PARAM_OPTIONAL
Z_PARAM_DOUBLE_OR_NULL(timeout, tnull)
ZEND_PARSE_PARAMETERS_END();
if (!cryo_check_futures(futures)) RETURN_THROWS();
double deadline = tnull ? -1 : cryo_mono() + timeout;
array_init(return_value);
zend_string *k; zend_ulong i; zval *z;
ZEND_HASH_FOREACH_KEY_VAL(futures, i, k, z) {
zval rv;
ZVAL_NULL(&rv);
double left = deadline < 0 ? -1 : deadline - cryo_mono();
if (deadline >= 0 && left < 0) left = 0;
cryo_future_await(FUT(Z_OBJ_P(z)), left, &rv);
if (EG(exception)) {
zval_ptr_dtor(&rv);
RETURN_THROWS();
}
if (k) zend_hash_update(Z_ARRVAL_P(return_value), k, &rv);
else zend_hash_index_update(Z_ARRVAL_P(return_value), i, &rv);
} ZEND_HASH_FOREACH_END();
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, awaitAny)
{
HashTable *futures; double timeout = -1; bool tnull = true;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ARRAY_HT(futures)
Z_PARAM_OPTIONAL
Z_PARAM_DOUBLE_OR_NULL(timeout, tnull)
ZEND_PARSE_PARAMETERS_END();
if (!cryo_check_futures(futures)) RETURN_THROWS();
if (!zend_hash_num_elements(futures)) {
zend_argument_value_error(1, "must not be empty");
RETURN_THROWS();
}
if (!cryo_futures_poll(futures, tnull ? -1 : timeout)) {
#ifdef CRYO_BACKEND_WASM
cryo_sb_no_sync();
#else
zend_throw_exception(ce_timeout, "No future completed before the timeout", 0);
#endif
RETURN_THROWS();
}
zval *z;
ZEND_HASH_FOREACH_VAL(futures, z) {
if (cryo_future_is_ready(FUT(Z_OBJ_P(z)))) {
cryo_future_await(FUT(Z_OBJ_P(z)), 0, return_value);
return;
}
} ZEND_HASH_FOREACH_END();
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, select)
{
HashTable *futures; double timeout = 0; bool tnull = false;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ARRAY_HT(futures)
Z_PARAM_OPTIONAL
Z_PARAM_DOUBLE_OR_NULL(timeout, tnull)
ZEND_PARSE_PARAMETERS_END();
if (!cryo_check_futures(futures)) RETURN_THROWS();
cryo_futures_poll(futures, tnull ? -1 : timeout);
array_init(return_value);
zend_string *k; zend_ulong i; zval *z;
ZEND_HASH_FOREACH_KEY_VAL(futures, i, k, z) {
if (cryo_future_is_ready(FUT(Z_OBJ_P(z)))) {
if (k) add_next_index_str(return_value, zend_string_copy(k));
else add_next_index_long(return_value, (zend_long) i);
}
} ZEND_HASH_FOREACH_END();
}
/* A future that settles once every given future did (wait(Future): with its value). Never blocks. */
ZEND_METHOD(Cryo_Sandbox_Sandbox, wait)
{
zval *arg; double timeout = -1; bool tnull = true;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ZVAL(arg)
Z_PARAM_OPTIONAL
Z_PARAM_DOUBLE_OR_NULL(timeout, tnull)
ZEND_PARSE_PARAMETERS_END();
zval group;
bool single = false;
if (Z_TYPE_P(arg) == IS_OBJECT && instanceof_function(Z_OBJCE_P(arg), ce_future)) {
array_init(&group);
Z_ADDREF_P(arg);
add_next_index_zval(&group, arg);
single = true;
} else if (Z_TYPE_P(arg) == IS_ARRAY) {
if (!cryo_check_futures(Z_ARRVAL_P(arg))) RETURN_THROWS();
ZVAL_ARR(&group, zend_array_dup(Z_ARRVAL_P(arg)));
} else {
zend_argument_type_error(1, "must be of type Cryo\\Sandbox\\Future|array, %s given", zend_zval_value_name(arg));
RETURN_THROWS();
}
if (!tnull && timeout < 0) {
zval_ptr_dtor(&group);
zend_argument_value_error(2, "must be greater than or equal to 0");
RETURN_THROWS();
}
object_init_ex(return_value, ce_future);
cryo_future *f = FUT(Z_OBJ_P(return_value));
ZVAL_COPY_VALUE(&f->group, &group);
f->single = single;
f->deadline = tnull ? 0 : cryo_mono() + (timeout > 0 ? timeout : 1e-9);
cryo_watch_add(Z_OBJ_P(return_value));
}
/* Read what every sandbox sent and settle the then() / wait() futures (their callbacks run here). */
static zend_long cryo_sandbox_pump_all(void)
{
for (cryo_sandbox *sb = cryo_live_sandboxes; sb; sb = sb->next_live) {
if (sb->alive) cryo_sb_drain(sb);
}
zend_long settled = 0;
if (!cryo_watch) return 0;
bool progress = true;
while (progress && !EG(exception) && zend_hash_num_elements(cryo_watch)) {
progress = false;
zend_array *snap = zend_array_dup(cryo_watch);
zval *z;
ZEND_HASH_FOREACH_VAL(snap, z) {
cryo_future *f = FUT(Z_OBJ_P(z));
if (f->state == 4) continue;
if (cryo_future_try_settle(f)) {
zend_hash_index_del(cryo_watch, Z_OBJ_P(z)->handle);
progress = true;
settled++;
}
if (EG(exception)) break;
} ZEND_HASH_FOREACH_END();
zend_array_destroy(snap);
}
return settled;
}
ZEND_METHOD(Cryo_Sandbox_Sandbox, pump)
{
ZEND_PARSE_PARAMETERS_NONE();
RETURN_LONG(cryo_sandbox_pump_all());
}
/* Requests waiting for an answer (every sandbox) + then() / wait() futures not settled yet. */
ZEND_METHOD(Cryo_Sandbox_Sandbox, pending)
{
ZEND_PARSE_PARAMETERS_NONE();
zend_long n = cryo_watch ? zend_hash_num_elements(cryo_watch) : 0;
for (cryo_sandbox *sb = cryo_live_sandboxes; sb; sb = sb->next_live) {
zval *v;
ZEND_HASH_FOREACH_VAL(&sb->pending, v) { if (Z_TYPE_P(v) == IS_NULL) n++; } ZEND_HASH_FOREACH_END();
}
RETURN_LONG(n);
}
/* ------------------------------------------------------------------------ */
/* Future */
/* ------------------------------------------------------------------------ */
static void cryo_future_await(cryo_future *f, double timeout, zval *return_value)
{
if (!cryo_future_is_request(f)) {
/* then() / wait(): settle the sources, run the callback once */
if (f->state == 4) {
zend_throw_exception(ce_sb_exception, "The future is settling (await() from its own then() callback)", 0);
return;
}
if (!cryo_future_wait_settled(f, timeout)) {
if (!EG(exception)) zend_throw_exception(ce_timeout, "The future is not ready (await timeout)", 0);
return;
}
if (EG(exception)) return;
zend_object *ex = cryo_future_exception(f);
if (ex) {
zval z;
ZVAL_OBJ_COPY(&z, ex);
zend_throw_exception_object(&z);
return;
}
cryo_future_value(f, return_value);
return;
}
if (f->state == 2) {
zend_throw_exception(ce_sb_exception, "The future was cancelled", 0);
return;
}
cryo_sandbox *sb = SB(Z_OBJ(f->sandbox));
if (f->state == 0) {
if (!cryo_sb_wait(sb, f->id, timeout)) {
if (!EG(exception)) zend_throw_exception(ce_timeout, "The future is not ready (await timeout)", 0);
return;
}
cryo_future_take(f);
cryo_sb_deliver(sb, &f->answer, return_value);
return;
}
/* already resolved: deliver again without side effects */
zval *t = cryo_arr(Z_ARRVAL(f->answer), "t");
if (t && zval_get_long(t) == CRYO_F_RESULT) {
zval *val = cryo_arr(Z_ARRVAL(f->answer), "v");
if (val) ZVAL_COPY(return_value, val);
return;
}
cryo_sb_throw(sb, &f->answer);
}
ZEND_METHOD(Cryo_Sandbox_Future, __construct)
{
ZEND_PARSE_PARAMETERS_NONE();
}
ZEND_METHOD(Cryo_Sandbox_Future, await)
{
double timeout = -1; bool tnull = true;
ZEND_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_DOUBLE_OR_NULL(timeout, tnull)
ZEND_PARSE_PARAMETERS_END();
cryo_future_await(FUT(Z_OBJ_P(ZEND_THIS)), tnull ? -1 : timeout, return_value);
}
ZEND_METHOD(Cryo_Sandbox_Future, isReady)
{
ZEND_PARSE_PARAMETERS_NONE();
cryo_future *f = FUT(Z_OBJ_P(ZEND_THIS));
cryo_future_drain(f);
if (cryo_future_is_request(f)) {
/* the answer stays with the sandbox until it is read */
RETURN_BOOL(cryo_future_is_ready(f));
}
RETURN_BOOL(cryo_future_try_settle(f) && f->state != 4);
}
/* Settled now? (reads what already arrived, runs a then() callback whose source is settled) */
static int cryo_future_settled_state(cryo_future *f)
{
cryo_future_drain(f);
if (!cryo_future_try_settle(f) || f->state == 4) return 0;
if (f->state == 1 && cryo_future_exception(f)) return 3;
return f->state;
}
ZEND_METHOD(Cryo_Sandbox_Future, status)
{
ZEND_PARSE_PARAMETERS_NONE();
switch (cryo_future_settled_state(FUT(Z_OBJ_P(ZEND_THIS)))) {
case 1: RETURN_STRING("ready");
case 2: RETURN_STRING("cancelled");
case 3: RETURN_STRING("failed");
default: RETURN_STRING("pending");
}
}
ZEND_METHOD(Cryo_Sandbox_Future, isFailed)
{
ZEND_PARSE_PARAMETERS_NONE();
RETURN_BOOL(cryo_future_settled_state(FUT(Z_OBJ_P(ZEND_THIS))) == 3);
}
ZEND_METHOD(Cryo_Sandbox_Future, isCancelled)
{
ZEND_PARSE_PARAMETERS_NONE();
RETURN_BOOL(cryo_future_settled_state(FUT(Z_OBJ_P(ZEND_THIS))) == 2);
}
/* The value once ready, null while pending or after a failure (never throws, never waits). */
ZEND_METHOD(Cryo_Sandbox_Future, value)
{
ZEND_PARSE_PARAMETERS_NONE();
cryo_future *f = FUT(Z_OBJ_P(ZEND_THIS));
if (cryo_future_settled_state(f) != 1) RETURN_NULL();
cryo_future_value(f, return_value);
}
/* The exception of a failed or cancelled future, null otherwise (never throws, never waits). */
ZEND_METHOD(Cryo_Sandbox_Future, error)
{
ZEND_PARSE_PARAMETERS_NONE();
cryo_future *f = FUT(Z_OBJ_P(ZEND_THIS));
int st = cryo_future_settled_state(f);
if (st != 2 && st != 3) RETURN_NULL();
zend_object *ex = cryo_future_exception(f);
if (!ex) RETURN_NULL();
RETURN_OBJ_COPY(ex);
}
ZEND_METHOD(Cryo_Sandbox_Future, cancel)
{
ZEND_PARSE_PARAMETERS_NONE();
cryo_future *self = FUT(Z_OBJ_P(ZEND_THIS));
cryo_future *f = cryo_future_root(self);
if (!cryo_future_is_request(f)) {
/* a wait() future (or a then() on one) */
if (self->state != 0) RETURN_FALSE;
self->state = 2;
RETURN_TRUE;
}
if (f->state != 0) {
if (self != f && self->state == 0) { self->state = 2; RETURN_TRUE; }
RETURN_FALSE;
}
cryo_sandbox *sb = SB(Z_OBJ(f->sandbox));
zval *v = zend_hash_index_find(&sb->pending, f->id);
if (v && Z_TYPE_P(v) == IS_NULL) {
ZVAL_FALSE(v); /* drop the answer when it arrives */
if (sb->alive) cryo_chan_send(&sb->chan, CRYO_F_CANCEL, f->id, NULL, 0);
} else if (v) {
zend_hash_index_del(&sb->pending, f->id);
}
f->state = 2;
if (self != f && self->state == 0) self->state = 2;
RETURN_TRUE;
}
/*
* then(ok, err = null): a future of what ok($value) returns (err($exception) when this one fails; without
* err the failure goes on). The callback runs once: at Sandbox::pump(), or when the new future is read
* (await, isReady, status, value...).
*/
ZEND_METHOD(Cryo_Sandbox_Future, then)
{
zval *cb, *err = NULL;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ZVAL(cb)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(err)
ZEND_PARSE_PARAMETERS_END();
if (!zend_is_callable(cb, 0, NULL)) {
zend_argument_type_error(1, "must be a valid callback");
RETURN_THROWS();
}
if (err && !zend_is_callable(err, 0, NULL)) {
zend_argument_type_error(2, "must be a valid callback or null");
RETURN_THROWS();
}
object_init_ex(return_value, ce_future);
cryo_future *n = FUT(Z_OBJ_P(return_value));
ZVAL_OBJ_COPY(&n->parent, Z_OBJ_P(ZEND_THIS));
ZVAL_COPY(&n->callback, cb);
if (err) ZVAL_COPY(&n->on_error, err);
cryo_watch_add(Z_OBJ_P(return_value));
}
/* ------------------------------------------------------------------------ */
/* RemoteObject */
/* ------------------------------------------------------------------------ */
static void cryo_remote_op(INTERNAL_FUNCTION_PARAMETERS, const char *op, zend_string *name, zval *args, zval *value)
{
cryo_remote *r = REM(Z_OBJ_P(ZEND_THIS));
if (Z_TYPE(r->sandbox) != IS_OBJECT) {
zend_throw_exception(ce_sb_exception, "Detached remote object", 0);
return;
}
zval req;
array_init(&req);
add_assoc_string(&req, "op", (char *) op);
add_assoc_long(&req, "h", r->handle);
if (name) add_assoc_str(&req, "n", zend_string_copy(name));
if (args) { Z_TRY_ADDREF_P(args); add_assoc_zval(&req, "a", args); }
if (value) { Z_TRY_ADDREF_P(value); add_assoc_zval(&req, "v", value); }
cryo_sb_sync(SB(Z_OBJ(r->sandbox)), CRYO_F_PROXY, &req, return_value);
zval_ptr_dtor(&req);
}
ZEND_METHOD(Cryo_Sandbox_RemoteObject, __call)
{
zend_string *name; zval *args;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_STR(name)
Z_PARAM_ARRAY(args)
ZEND_PARSE_PARAMETERS_END();
cryo_remote_op(INTERNAL_FUNCTION_PARAM_PASSTHRU, "call", name, args, NULL);
}
ZEND_METHOD(Cryo_Sandbox_RemoteObject, __get)
{
zend_string *name;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(name)
ZEND_PARSE_PARAMETERS_END();
cryo_remote_op(INTERNAL_FUNCTION_PARAM_PASSTHRU, "get", name, NULL, NULL);
}
ZEND_METHOD(Cryo_Sandbox_RemoteObject, __set)
{
zend_string *name; zval *value;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_STR(name)
Z_PARAM_ZVAL(value)
ZEND_PARSE_PARAMETERS_END();
cryo_remote_op(INTERNAL_FUNCTION_PARAM_PASSTHRU, "set", name, NULL, value);
zval_ptr_dtor(return_value);
ZVAL_NULL(return_value);
}
ZEND_METHOD(Cryo_Sandbox_RemoteObject, __isset)
{
zend_string *name;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(name)
ZEND_PARSE_PARAMETERS_END();
cryo_remote_op(INTERNAL_FUNCTION_PARAM_PASSTHRU, "isset", name, NULL, NULL);
if (!EG(exception)) {
bool b = zend_is_true(return_value);
zval_ptr_dtor(return_value);
RETVAL_BOOL(b);
}
}
ZEND_METHOD(Cryo_Sandbox_RemoteObject, __unset)
{
zend_string *name;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(name)
ZEND_PARSE_PARAMETERS_END();
cryo_remote_op(INTERNAL_FUNCTION_PARAM_PASSTHRU, "unset", name, NULL, NULL);
zval_ptr_dtor(return_value);
ZVAL_NULL(return_value);
}
ZEND_METHOD(Cryo_Sandbox_RemoteObject, remoteClass)
{
ZEND_PARSE_PARAMETERS_NONE();
cryo_remote *r = REM(Z_OBJ_P(ZEND_THIS));
if (r->cls) RETURN_STR_COPY(r->cls);
RETURN_EMPTY_STRING();
}
/* ------------------------------------------------------------------------ */
/* EngineProxy: Cryo\Engine of the child */
/* ------------------------------------------------------------------------ */
ZEND_METHOD(Cryo_Sandbox_EngineProxy, __call)
{
zend_string *name; HashTable *args;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_STR(name)
Z_PARAM_ARRAY_HT(args)
ZEND_PARSE_PARAMETERS_END();
cryo_proxy *p = PRX(Z_OBJ_P(ZEND_THIS));
cryo_sandbox *sb = SB(Z_OBJ(p->sandbox));
zend_string *lc = zend_string_tolower(name);
zval req, entry;
array_init(&req);
ZVAL_UNDEF(&entry);
uint32_t n = zend_hash_num_elements(args);
zval *a0 = zend_hash_index_find(args, 0), *a1 = zend_hash_index_find(args, 1),
*a2 = zend_hash_index_find(args, 2), *a3 = zend_hash_index_find(args, 3);
const char *kind = NULL;
int closure_at = -1;
if (zend_string_equals_literal(lc, "journal") || zend_string_equals_literal(lc, "exportjournal")
|| zend_string_equals_literal(lc, "revert")) {
add_assoc_str(&req, "op", zend_string_copy(name));
zval a;
ZVAL_ARR(&a, zend_array_dup(args));
add_assoc_zval(&req, "a", &a);
} else if (zend_string_equals_literal(lc, "replayjournal") && a0) {
add_assoc_string(&req, "op", "replay");
Z_TRY_ADDREF_P(a0);
add_assoc_zval(&req, "e", a0);
} else {
array_init(&entry);
if (zend_string_equals_literal(lc, "redefinefunction") && n == 2) { kind = "function"; closure_at = 1; }
else if (zend_string_equals_literal(lc, "addfunction") && n == 2) { kind = "add_function"; closure_at = 1; }
else if (zend_string_equals_literal(lc, "removefunction") && n == 1) { kind = "remove_function"; }
else if (zend_string_equals_literal(lc, "renamefunction") && n == 2) { kind = "rename_function"; }
else if (zend_string_equals_literal(lc, "redefinemethod") && n == 3) { kind = "method"; closure_at = 2; }
else if (zend_string_equals_literal(lc, "addmethod") && (n == 3 || n == 4)) { kind = "add_method"; closure_at = 2; }
else if (zend_string_equals_literal(lc, "removemethod") && n == 2) { kind = "remove_method"; }
else if (zend_string_equals_literal(lc, "redefineconstant") && n == 2) { kind = "constant"; }
else if (zend_string_equals_literal(lc, "registersuperglobal") && n == 1) { kind = "superglobal"; }
if (!kind) {
zend_throw_error(NULL, "Call to undefined or misused method Cryo\\Sandbox\\EngineProxy::%s()", ZSTR_VAL(name));
goto out;
}
add_assoc_string(&entry, "kind", (char *) kind);
bool method = closure_at == 2 || strcmp(kind, "remove_method") == 0;
if (!a0 || Z_TYPE_P(a0) != IS_STRING || (method && (!a1 || Z_TYPE_P(a1) != IS_STRING))) {
zend_argument_type_error(1, "must be a string");
goto out;
}
add_assoc_str(&entry, "target", method ? zend_strpprintf(0, "%s::%s", Z_STRVAL_P(a0), Z_STRVAL_P(a1)) : zend_string_copy(Z_STR_P(a0)));
if (closure_at >= 0) {
zval *c = zend_hash_index_find(args, closure_at);
zval cd;
if (!c || Z_TYPE_P(c) != IS_OBJECT || Z_OBJCE_P(c) != zend_ce_closure) {
zend_argument_type_error(closure_at + 1, "must be a Closure");
goto out;
}
if (!cryo_closure_export(c, &cd)) {
zend_throw_exception(cryo_ce_exception, "This closure cannot be sent to the sandbox (no source file)", 0);
goto out;
}
add_assoc_zval(&entry, "closure", &cd);
}
if (strcmp(kind, "rename_function") == 0) {
if (Z_TYPE_P(a1) != IS_STRING) { zend_argument_type_error(2, "must be a string"); goto out; }
add_assoc_str(&entry, "to", zend_string_copy(Z_STR_P(a1)));
}
if (strcmp(kind, "add_method") == 0 && a3) add_assoc_long(&entry, "flags", zval_get_long(a3));
if (strcmp(kind, "constant") == 0) { Z_TRY_ADDREF_P(a1); add_assoc_zval(&entry, "value", a1); }
(void) a2;
add_assoc_string(&req, "op", "apply");
Z_ADDREF(entry);
add_assoc_zval(&req, "e", &entry);
}
cryo_sb_sync(sb, CRYO_F_ENGINE, &req, return_value);
out:
zval_ptr_dtor(&entry);
zval_ptr_dtor(&req);
zend_string_release(lc);
}
/* ------------------------------------------------------------------------ */
/* Channel (child side) */
/* ------------------------------------------------------------------------ */
ZEND_METHOD(Cryo_Sandbox_Channel, __construct)
{
ZEND_PARSE_PARAMETERS_NONE();
}
ZEND_METHOD(Cryo_Sandbox_Channel, parent)
{
ZEND_PARSE_PARAMETERS_NONE();
if (!cryo_child.active) {
zend_throw_exception(ce_sb_exception, "Channel::parent() is only available inside a sandbox", 0);
RETURN_THROWS();
}
object_init_ex(return_value, ce_channel);
}
ZEND_METHOD(Cryo_Sandbox_Channel, send)
{
zval *msg;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(msg)
ZEND_PARSE_PARAMETERS_END();
zval m;
array_init(&m);
Z_TRY_ADDREF_P(msg);
add_assoc_zval(&m, "v", msg);
cryo_chan_send_zv(&cryo_child.chan, CRYO_F_MSG, 0, &m);
zval_ptr_dtor(&m);
}
ZEND_METHOD(Cryo_Sandbox_Channel, recv)
{
double timeout = -1; bool tnull = true;
ZEND_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_DOUBLE_OR_NULL(timeout, tnull)
ZEND_PARSE_PARAMETERS_END();
#ifdef CRYO_BACKEND_WASM
while (zend_hash_num_elements(Z_ARRVAL(cryo_child.inbox)) == 0 && cryo_child_pump(0) > 0) {}
if (zend_hash_num_elements(Z_ARRVAL(cryo_child.inbox)) == 0) {
zend_throw_exception(ce_timeout, "No message from the parent yet (in the browser a sandbox cannot wait inside a request)", 0);
RETURN_THROWS();
}
#endif
double deadline = tnull ? -1 : cryo_mono() + timeout;
while (zend_hash_num_elements(Z_ARRVAL(cryo_child.inbox)) == 0) {
double left = deadline < 0 ? -1 : deadline - cryo_mono();
if (deadline >= 0 && left <= 0) {
zend_throw_exception(ce_timeout, "No message from the parent before the timeout", 0);
RETURN_THROWS();
}
cryo_child_pump(left);
}
cryo_shift(Z_ARRVAL(cryo_child.inbox), return_value);
}
ZEND_METHOD(Cryo_Sandbox_Channel, serve)
{
zend_long fd;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_LONG(fd)
ZEND_PARSE_PARAMETERS_END();
if (cryo_child.active) {
zend_throw_exception(ce_sb_exception, "Already serving", 0);
RETURN_THROWS();
}
#ifdef CRYO_BACKEND_WASM
cryo_child.chan.wid = (int32_t) fd;
#else
struct stat st;
if (fstat((int) fd, &st) != 0 || !S_ISSOCK(st.st_mode)) {
zend_throw_exception(ce_sb_exception, "Channel::serve() needs the sandbox socket", 0);
RETURN_THROWS();
}
cryo_child.chan.fd = (int) fd;
#endif
cryo_child_main();
}
#ifdef CRYO_BACKEND_WASM
/*
* Entry point of a sandbox instance (a Web Worker running its own PHP). Nothing may block there either: the
* worker queues each frame from the parent in its host (Module.cryoHost.recv), then calls this. It reads
* every frame already there and runs at most ONE request (call it again while it returns 1). The first frame
* is INIT (options, bootstrap: answered with HELLO). Answers go back through cryo_host_send(0, ...). A fatal
* error, exit() or a failed bootstrap end the instance with _exit() (the worker sees emscripten's
* ExitStatus and reports the exit code); a trap (stack overflow...) throws out of here as a JS exception.
* 0: nothing to run, 1: one request ran (more may be queued), -1: not initialized yet (no INIT frame).
*/
static zend_execute_data cryo_child_dummy;
static bool cryo_child_inited = false;
__attribute__((used, visibility("default"))) /* EXPORTED_FUNCTIONS: _cryo_sandbox_step */
int32_t cryo_sandbox_step(void)
{
if (!cryo_child.active) {
zend_execute_data *saved = EG(current_execute_data);
cryo_child.chan.wid = 0;
cryo_child_setup(&cryo_child_dummy);
EG(current_execute_data) = saved;
}
zend_execute_data *saved = EG(current_execute_data);
EG(current_execute_data) = &cryo_child_dummy;
int32_t ran = 0;
if (!cryo_child_inited) {
uint32_t type = 0, id = 0;
zend_string *payload = NULL;
int r = cryo_chan_recv(&cryo_child.chan, 0, &type, &id, &payload);
if (r == 0) { EG(current_execute_data) = saved; return -1; }
if (r < 0 || type != CRYO_F_INIT) cryo_child_exit(3);
bool ok = cryo_child_hello(payload);
zend_string_release(payload);
if (!ok) cryo_child_exit(2);
cryo_child_inited = true;
}
while (cryo_child_pump(0) > 0) {}
zval e;
if (cryo_shift(Z_ARRVAL(cryo_child.queue), &e)) {
cryo_child_run_queued(&e);
zval_ptr_dtor(&e);
ran = 1;
}
EG(current_execute_data) = saved;
return ran;
}
#endif
/* ------------------------------------------------------------------------ */
/* Pool */
/* ------------------------------------------------------------------------ */
ZEND_METHOD(Cryo_Sandbox_Pool, __construct)
{
zend_long size; HashTable *opts = NULL;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_LONG(size)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_HT(opts)
ZEND_PARSE_PARAMETERS_END();
if (size < 1 || size > 1024) {
zend_argument_value_error(1, "must be between 1 and 1024");
RETURN_THROWS();
}
cryo_pool *p = POOL(Z_OBJ_P(ZEND_THIS));
if (opts) ZVAL_ARR(&p->options, zend_array_dup(opts)); else array_init(&p->options);
zval *v;
if ((v = cryo_arr(Z_ARRVAL(p->options), "max_jobs"))) p->max_jobs = zval_get_long(v);
if ((v = cryo_arr(Z_ARRVAL(p->options), "max_memory"))) {
if (Z_TYPE_P(v) == IS_STRING) {
zend_string *err = NULL;
p->max_memory = zend_ini_parse_quantity(Z_STR_P(v), &err);
if (err) zend_string_release(err);
} else {
p->max_memory = zval_get_long(v);
}
}
zend_hash_str_del(Z_ARRVAL(p->options), "max_jobs", sizeof("max_jobs") - 1);
zend_hash_str_del(Z_ARRVAL(p->options), "max_memory", sizeof("max_memory") - 1);
if (!cryo_arr(Z_ARRVAL(p->options), "restart")) add_assoc_string(&p->options, "restart", "on_crash");
for (zend_long i = 0; i < size; i++) {
zval w;
object_init_ex(&w, ce_sandbox);
add_next_index_zval(&p->workers, &w);
if (!cryo_sb_construct(SB(Z_OBJ(w)), Z_ARRVAL(p->options))) RETURN_THROWS();
}
}
/* Least busy worker; recycles workers over max_jobs / max_memory, replaces dead ones. */
static cryo_sandbox *cryo_pool_pick(cryo_pool *p)
{
if (p->closed) {
zend_throw_exception(ce_sb_exception, "The pool is closed", 0);
return NULL;
}
cryo_sandbox *best = NULL;
uint32_t best_load = UINT32_MAX;
zval *w;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL(p->workers), w) {
cryo_sandbox *sb = SB(Z_OBJ_P(w));
uint32_t load = 0;
zval *v;
ZEND_HASH_FOREACH_VAL(&sb->pending, v) { if (Z_TYPE_P(v) == IS_NULL) load++; } ZEND_HASH_FOREACH_END();
if (load == 0) {
bool recycle = !sb->alive || sb->dying
|| (p->max_jobs > 0 && sb->jobs >= p->max_jobs)
|| (p->max_memory > 0 && sb->memory > p->max_memory);
if (recycle) {
if (sb->pid) cryo_sb_reap(sb, true);
zend_hash_clean(&sb->pending);
sb->jobs = 0;
sb->memory = 0;
if (!cryo_sb_start(sb)) return NULL;
}
}
if (load < best_load) {
best = sb;
best_load = load;
}
} ZEND_HASH_FOREACH_END();
return best;
}
static uint32_t cryo_pool_submit(cryo_pool *p, zval *fn, HashTable *args, cryo_sandbox **out)
{
cryo_sandbox *sb = cryo_pool_pick(p);
if (!sb) return 0;
zval req;
cryo_sb_call_payload(&req, fn, args);
uint32_t id = cryo_sb_request(sb, CRYO_F_CALL, &req);
zval_ptr_dtor(&req);
*out = sb;
return id;
}
ZEND_METHOD(Cryo_Sandbox_Pool, call)
{
zval *fn; HashTable *args = NULL;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ZVAL(fn)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_HT(args)
ZEND_PARSE_PARAMETERS_END();
if (!cryo_check_callable_spec(fn)) RETURN_THROWS();
#ifdef CRYO_BACKEND_WASM
cryo_sb_no_sync();
RETURN_THROWS();
#endif
cryo_sandbox *sb;
uint32_t id = cryo_pool_submit(POOL(Z_OBJ_P(ZEND_THIS)), fn, args, &sb);
if (!id) RETURN_THROWS();
cryo_sb_wait(sb, id, -1);
cryo_sb_claim(sb, id, return_value);
}
ZEND_METHOD(Cryo_Sandbox_Pool, callAsync)
{
zval *fn; HashTable *args = NULL;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ZVAL(fn)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_HT(args)
ZEND_PARSE_PARAMETERS_END();
if (!cryo_check_callable_spec(fn)) RETURN_THROWS();
cryo_sandbox *sb;
uint32_t id = cryo_pool_submit(POOL(Z_OBJ_P(ZEND_THIS)), fn, args, &sb);
if (!id) RETURN_THROWS();
cryo_future_make(sb, id, return_value);
}
ZEND_METHOD(Cryo_Sandbox_Pool, map)
{
zval *fn; HashTable *list;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_ZVAL(fn)
Z_PARAM_ARRAY_HT(list)
ZEND_PARSE_PARAMETERS_END();
if (!cryo_check_callable_spec(fn)) RETURN_THROWS();
#ifdef CRYO_BACKEND_WASM
cryo_sb_no_sync();
RETURN_THROWS();
#endif
cryo_pool *p = POOL(Z_OBJ_P(ZEND_THIS));
zval futures;
array_init(&futures);
zend_string *k; zend_ulong i; zval *args;
ZEND_HASH_FOREACH_KEY_VAL(list, i, k, args) {
zval one, f;
ZVAL_DEREF(args);
if (Z_TYPE_P(args) == IS_ARRAY) ZVAL_COPY(&one, args);
else { array_init(&one); Z_TRY_ADDREF_P(args); add_next_index_zval(&one, args); }
cryo_sandbox *sb;
uint32_t id = cryo_pool_submit(p, fn, Z_ARRVAL(one), &sb);
zval_ptr_dtor(&one);
if (!id) { zval_ptr_dtor(&futures); RETURN_THROWS(); }
cryo_future_make(sb, id, &f);
if (k) zend_hash_update(Z_ARRVAL(futures), k, &f); else zend_hash_index_update(Z_ARRVAL(futures), i, &f);
} ZEND_HASH_FOREACH_END();
array_init(return_value);
zval *f;
ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL(futures), i, k, f) {
zval rv;
ZVAL_NULL(&rv);
cryo_future_await(FUT(Z_OBJ_P(f)), -1, &rv);
if (EG(exception)) { zval_ptr_dtor(&rv); break; }
if (k) zend_hash_update(Z_ARRVAL_P(return_value), k, &rv); else zend_hash_index_update(Z_ARRVAL_P(return_value), i, &rv);
} ZEND_HASH_FOREACH_END();
zval_ptr_dtor(&futures);
}
ZEND_METHOD(Cryo_Sandbox_Pool, status)
{
ZEND_PARSE_PARAMETERS_NONE();
cryo_pool *p = POOL(Z_OBJ_P(ZEND_THIS));
array_init(return_value);
add_assoc_long(return_value, "size", zend_hash_num_elements(Z_ARRVAL(p->workers)));
add_assoc_bool(return_value, "closed", p->closed);
zval workers;
array_init(&workers);
zval *w;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL(p->workers), w) {
zval st;
zend_call_method_with_0_params(Z_OBJ_P(w), ce_sandbox, NULL, "status", &st);
add_assoc_long(&st, "jobs", SB(Z_OBJ_P(w))->jobs);
add_next_index_zval(&workers, &st);
} ZEND_HASH_FOREACH_END();
add_assoc_zval(return_value, "workers", &workers);
}
ZEND_METHOD(Cryo_Sandbox_Pool, close)
{
ZEND_PARSE_PARAMETERS_NONE();
cryo_pool *p = POOL(Z_OBJ_P(ZEND_THIS));
zval *w;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL(p->workers), w) {
cryo_sandbox *sb = SB(Z_OBJ_P(w));
if (sb->pid) cryo_sb_reap(sb, true);
} ZEND_HASH_FOREACH_END();
p->closed = true;
}
/* ------------------------------------------------------------------------ */
/* Exceptions */
/* ------------------------------------------------------------------------ */
ZEND_METHOD(Cryo_Sandbox_SandboxCrashedException, getSignal)
{
ZEND_PARSE_PARAMETERS_NONE();
zval rv;
RETURN_COPY_DEREF(zend_read_property(ce_crashed, Z_OBJ_P(ZEND_THIS), "signal", sizeof("signal") - 1, 1, &rv));
}
ZEND_METHOD(Cryo_Sandbox_SandboxCrashedException, getExitCode)
{
ZEND_PARSE_PARAMETERS_NONE();
zval rv;
RETURN_COPY_DEREF(zend_read_property(ce_crashed, Z_OBJ_P(ZEND_THIS), "exitCode", sizeof("exitCode") - 1, 1, &rv));
}
ZEND_METHOD(Cryo_Sandbox_SandboxCrashedException, getStderr)
{
ZEND_PARSE_PARAMETERS_NONE();
zval rv;
RETURN_COPY_DEREF(zend_read_property(ce_crashed, Z_OBJ_P(ZEND_THIS), "stderr", sizeof("stderr") - 1, 1, &rv));
}
ZEND_METHOD(Cryo_Sandbox_RemoteException, getRemoteClass)
{
ZEND_PARSE_PARAMETERS_NONE();
zval rv;
RETURN_COPY_DEREF(zend_read_property(ce_remote_exc, Z_OBJ_P(ZEND_THIS), "remoteClass", sizeof("remoteClass") - 1, 1, &rv));
}
ZEND_METHOD(Cryo_Sandbox_RemoteException, getRemoteTrace)
{
ZEND_PARSE_PARAMETERS_NONE();
zval rv;
RETURN_COPY_DEREF(zend_read_property(ce_remote_exc, Z_OBJ_P(ZEND_THIS), "remoteTrace", sizeof("remoteTrace") - 1, 1, &rv));
}
/* ------------------------------------------------------------------------ */
/* Arginfo */
/* ------------------------------------------------------------------------ */
ZEND_BEGIN_ARG_INFO_EX(ai_sb_construct, 0, 0, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 0, "[]")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_sb_spawn, 0, 0, IS_STATIC, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 0, "[]")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_sb_from_snapshot, 0, 1, IS_STATIC, 0)
ZEND_ARG_TYPE_INFO(0, file, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 0, "[]")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_sb_call, 0, 1, IS_MIXED, 0)
ZEND_ARG_TYPE_MASK(0, function, MAY_BE_STRING | MAY_BE_ARRAY, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, args, IS_ARRAY, 0, "[]")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(ai_sb_call_async, 0, 1, Cryo\\Sandbox\\Future, 0)
ZEND_ARG_TYPE_MASK(0, function, MAY_BE_STRING | MAY_BE_ARRAY, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, args, IS_ARRAY, 0, "[]")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_sb_code, 0, 1, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, code, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(ai_sb_code_async, 0, 1, Cryo\\Sandbox\\Future, 0)
ZEND_ARG_TYPE_INFO(0, code, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_sb_file, 0, 1, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, file, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_sb_file_void, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, file, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_sb_get, 0, 1, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_sb_set, 0, 2, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_MIXED, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_void, 0, 0, IS_VOID, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_array, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_string, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_bool, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(ai_sb_proxy, 0, 1, Cryo\\Sandbox\\RemoteObject, 0)
ZEND_ARG_TYPE_INFO(0, expression, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_sb_send, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, message, IS_MIXED, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_timeout_mixed, 0, 0, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, timeout, IS_DOUBLE, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_sb_stream, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(ai_sb_engine, 0, 0, Cryo\\Sandbox\\EngineProxy, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_await_all, 0, 1, IS_ARRAY, 0)
ZEND_ARG_TYPE_INFO(0, futures, IS_ARRAY, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, timeout, IS_DOUBLE, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_await_any, 0, 1, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, futures, IS_ARRAY, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, timeout, IS_DOUBLE, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_select, 0, 1, IS_ARRAY, 0)
ZEND_ARG_TYPE_INFO(0, futures, IS_ARRAY, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, timeout, IS_DOUBLE, 1, "0.0")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_none, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(ai_sb_set_async, 0, 2, Cryo\\Sandbox\\Future, 0)
ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_MIXED, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(ai_sb_name_async, 0, 1, Cryo\\Sandbox\\Future, 0)
ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(ai_sb_file_async, 0, 1, Cryo\\Sandbox\\Future, 0)
ZEND_ARG_TYPE_INFO(0, file, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(ai_future_none, 0, 0, Cryo\\Sandbox\\Future, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(ai_sb_wait, 0, 1, Cryo\\Sandbox\\Future, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, futures, Cryo\\Sandbox\\Future, MAY_BE_ARRAY, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, timeout, IS_DOUBLE, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_long, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_TYPE_MASK_EX(ai_future_error, 0, 0, Throwable, MAY_BE_NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(ai_future_then, 0, 1, Cryo\\Sandbox\\Future, 0)
ZEND_ARG_TYPE_INFO(0, callback, IS_CALLABLE, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, onError, IS_CALLABLE, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_mixed, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_magic_call, 0, 2, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, arguments, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_magic_get, 0, 1, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_magic_set, 0, 2, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_MIXED, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_magic_isset, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_magic_unset, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(ai_channel_parent, 0, 0, Cryo\\Sandbox\\Channel, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_channel_serve, 0, 1, IS_NEVER, 0)
ZEND_ARG_TYPE_INFO(0, fd, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_pool_construct, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, size, IS_LONG, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 0, "[]")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(ai_pool_map, 0, 2, IS_ARRAY, 0)
ZEND_ARG_TYPE_MASK(0, function, MAY_BE_STRING | MAY_BE_ARRAY, NULL)
ZEND_ARG_TYPE_INFO(0, argsList, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(ai_long_null, 0, 0, MAY_BE_LONG | MAY_BE_NULL)
ZEND_END_ARG_INFO()
static const zend_function_entry sandbox_methods[] = {
ZEND_ME(Cryo_Sandbox_Sandbox, __construct, ai_sb_construct, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, spawn, ai_sb_spawn, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
ZEND_ME(Cryo_Sandbox_Sandbox, fromSnapshot, ai_sb_from_snapshot, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
ZEND_ME(Cryo_Sandbox_Sandbox, call, ai_sb_call, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, callAsync, ai_sb_call_async, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, eval, ai_sb_code, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, evalAsync, ai_sb_code_async, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, include, ai_sb_file, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, get, ai_sb_get, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, set, ai_sb_set, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, includeAsync, ai_sb_file_async, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, getAsync, ai_sb_name_async, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, setAsync, ai_sb_set_async, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, metricsAsync, ai_future_none, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, messages, ai_array, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, snapshot, ai_sb_file_void, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, freeze, ai_sb_file, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, metrics, ai_array, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, proxy, ai_sb_proxy, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, send, ai_sb_send, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, recv, ai_timeout_mixed, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, stream, ai_sb_stream, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, engine, ai_sb_engine, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, kill, ai_void, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, restart, ai_void, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, status, ai_array, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, output, ai_string, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Sandbox, awaitAll, ai_await_all, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
ZEND_ME(Cryo_Sandbox_Sandbox, awaitAny, ai_await_any, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
ZEND_ME(Cryo_Sandbox_Sandbox, select, ai_select, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
ZEND_ME(Cryo_Sandbox_Sandbox, wait, ai_sb_wait, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
ZEND_ME(Cryo_Sandbox_Sandbox, pump, ai_long, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
ZEND_ME(Cryo_Sandbox_Sandbox, pending, ai_long, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
ZEND_FE_END
};
static const zend_function_entry future_methods[] = {
ZEND_ME(Cryo_Sandbox_Future, __construct, ai_none, ZEND_ACC_PRIVATE)
ZEND_ME(Cryo_Sandbox_Future, await, ai_timeout_mixed, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Future, isReady, ai_bool, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Future, status, ai_string, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Future, isFailed, ai_bool, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Future, isCancelled, ai_bool, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Future, value, ai_mixed, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Future, error, ai_future_error, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Future, cancel, ai_bool, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Future, then, ai_future_then, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry remote_methods[] = {
ZEND_ME(Cryo_Sandbox_Future, __construct, ai_none, ZEND_ACC_PRIVATE)
ZEND_ME(Cryo_Sandbox_RemoteObject, __call, ai_magic_call, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_RemoteObject, __get, ai_magic_get, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_RemoteObject, __set, ai_magic_set, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_RemoteObject, __isset, ai_magic_isset, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_RemoteObject, __unset, ai_magic_unset, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_RemoteObject, remoteClass, ai_string, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry engine_proxy_methods[] = {
ZEND_ME(Cryo_Sandbox_Future, __construct, ai_none, ZEND_ACC_PRIVATE)
ZEND_ME(Cryo_Sandbox_EngineProxy, __call, ai_magic_call, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry channel_methods[] = {
ZEND_ME(Cryo_Sandbox_Channel, __construct, ai_none, ZEND_ACC_PRIVATE)
ZEND_ME(Cryo_Sandbox_Channel, parent, ai_channel_parent, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
ZEND_ME(Cryo_Sandbox_Channel, send, ai_sb_send, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Channel, recv, ai_timeout_mixed, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Channel, serve, ai_channel_serve, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
ZEND_FE_END
};
static const zend_function_entry pool_methods[] = {
ZEND_ME(Cryo_Sandbox_Pool, __construct, ai_pool_construct, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Pool, call, ai_sb_call, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Pool, callAsync, ai_sb_call_async, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Pool, map, ai_pool_map, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Pool, status, ai_array, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_Pool, close, ai_void, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry crashed_methods[] = {
ZEND_ME(Cryo_Sandbox_SandboxCrashedException, getSignal, ai_long_null, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_SandboxCrashedException, getExitCode, ai_long_null, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_SandboxCrashedException, getStderr, ai_string, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry remote_exc_methods[] = {
ZEND_ME(Cryo_Sandbox_RemoteException, getRemoteClass, ai_string, ZEND_ACC_PUBLIC)
ZEND_ME(Cryo_Sandbox_RemoteException, getRemoteTrace, ai_string, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
/* ------------------------------------------------------------------------ */
/* Module hooks */
/* ------------------------------------------------------------------------ */
static zend_class_entry *cryo_register(const char *name, const zend_function_entry *methods,
zend_class_entry *parent, zend_object *(*create)(zend_class_entry *), zend_object_handlers *h,
size_t offset, void (*free_obj)(zend_object *))
{
zend_class_entry ce;
INIT_CLASS_ENTRY_EX(ce, name, strlen(name), methods);
zend_class_entry *c = parent ? zend_register_internal_class_ex(&ce, parent) : zend_register_internal_class(&ce);
if (create) {
c->create_object = create;
memcpy(h, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
h->offset = (int) offset;
h->free_obj = free_obj;
h->clone_obj = NULL;
c->default_object_handlers = h;
c->ce_flags |= ZEND_ACC_FINAL | ZEND_ACC_NOT_SERIALIZABLE;
}
return c;
}
void cryo_sandbox_minit(void)
{
#ifdef CRYO_BACKEND_WASM
(void) cryo_host_link_anchor(); /* links cryo_host.o (its EM_JS functions) out of libphp.a */
#endif
ce_sb_exception = cryo_register("Cryo\\Sandbox\\SandboxException", NULL, cryo_ce_exception, NULL, NULL, 0, NULL);
ce_crashed = cryo_register("Cryo\\Sandbox\\SandboxCrashedException", crashed_methods, ce_sb_exception, NULL, NULL, 0, NULL);
zend_declare_property_null(ce_crashed, "signal", sizeof("signal") - 1, ZEND_ACC_PROTECTED);
zend_declare_property_null(ce_crashed, "exitCode", sizeof("exitCode") - 1, ZEND_ACC_PROTECTED);
zend_declare_property_string(ce_crashed, "stderr", sizeof("stderr") - 1, "", ZEND_ACC_PROTECTED);
ce_timeout = cryo_register("Cryo\\Sandbox\\SandboxTimeoutException", NULL, ce_sb_exception, NULL, NULL, 0, NULL);
ce_memory = cryo_register("Cryo\\Sandbox\\SandboxMemoryException", NULL, ce_sb_exception, NULL, NULL, 0, NULL);
ce_remote_exc = cryo_register("Cryo\\Sandbox\\RemoteException", remote_exc_methods, ce_sb_exception, NULL, NULL, 0, NULL);
zend_declare_property_string(ce_remote_exc, "remoteClass", sizeof("remoteClass") - 1, "", ZEND_ACC_PROTECTED);
zend_declare_property_string(ce_remote_exc, "remoteTrace", sizeof("remoteTrace") - 1, "", ZEND_ACC_PROTECTED);
ce_sandbox = cryo_register("Cryo\\Sandbox\\Sandbox", sandbox_methods, NULL, cryo_sandbox_new, &h_sandbox,
XtOffsetOf(cryo_sandbox, std), cryo_sandbox_free);
ce_future = cryo_register("Cryo\\Sandbox\\Future", future_methods, NULL, cryo_future_new, &h_future,
XtOffsetOf(cryo_future, std), cryo_future_free);
h_future.get_gc = cryo_future_gc;
ce_remote = cryo_register("Cryo\\Sandbox\\RemoteObject", remote_methods, NULL, cryo_remote_new, &h_remote,
XtOffsetOf(cryo_remote, std), cryo_remote_free);
ce_engine_proxy = cryo_register("Cryo\\Sandbox\\EngineProxy", engine_proxy_methods, NULL, cryo_proxy_new, &h_proxy,
XtOffsetOf(cryo_proxy, std), cryo_proxy_free);
ce_channel = cryo_register("Cryo\\Sandbox\\Channel", channel_methods, NULL, cryo_proxy_new, &h_channel,
XtOffsetOf(cryo_proxy, std), cryo_proxy_free);
ce_pool = cryo_register("Cryo\\Sandbox\\Pool", pool_methods, NULL, cryo_pool_new, &h_pool,
XtOffsetOf(cryo_pool, std), cryo_pool_free);
h_pool.get_gc = cryo_pool_gc;
}
/* Kill every child still running (objects leaked in cycles included). */
void cryo_sandbox_rshutdown(void)
{
if (cryo_watch) {
HashTable *w = cryo_watch;
cryo_watch = NULL;
zend_hash_destroy(w);
FREE_HASHTABLE(w);
}
for (cryo_sandbox *sb = cryo_live_sandboxes; sb; sb = sb->next_live) {
if (sb->pid) {
cryo_sb_reap(sb, true);
}
}
}