Sandbox
Overview
Cera provides sandboxing controls for safe embedding in host applications. These controls limit resource usage by scripts and prevent runaway execution.
Memory Limits
The host can limit the maximum heap memory available to Cera scripts:
// C++ Host APIcera::api::SandboxConfig config;config.max_heap_bytes = 10 * 1024 * 1024; // 10 MBcera::api::configure_sandbox(config);When the limit is exceeded, GC allocation fails and an OutOfMemoryException is thrown.
From Cera Code
int usage = Sandbox.GetMemoryUsage(); // Current heap bytesint limit = Sandbox.GetMemoryLimit(); // Configured limit (0 = unlimited)Execution Timeout
The host can set a wall-clock execution timeout:
// C++ Host APIcera::api::SandboxConfig config;config.max_execution_ms = 5000; // 5 secondscera::api::configure_sandbox(config);When the timeout expires, an ExecutionTimeoutException is thrown at the next check point. Check points occur:
- On every GC allocation (covers allocation-heavy loops)
- When
Sandbox.CheckTimeout()is called explicitly
From Cera Code
int isSet = Sandbox.GetTimeoutSet(); // 1 if timeout is activeint expired = Sandbox.CheckTimeout(); // 0 = OK, 1 = timed outFor pure-compute loops that don’t allocate, call Sandbox.CheckTimeout() periodically:
while (running) { // intensive computation... Sandbox.CheckTimeout(); // throws ExecutionTimeoutException if expired}I/O Restrictions
I/O sandboxing is inherent in Cera’s architecture. The host controls which stdlib modules are registered:
- Omit
File,Directory,Pathto prevent filesystem access - Omit
Thread,Mutexto prevent concurrency - Omit
Process(when available) to prevent command execution - Use
register_thunk()to expose only approved host functions
Exception Types
Two exception types are available for catching sandbox violations:
try { // code that might exceed limits} catch (OutOfMemoryException e) { // Handle memory limit exceeded} catch (ExecutionTimeoutException e) { // Handle timeout}C++ Host API
SandboxConfig
| Field | Type | Default | Description |
|---|---|---|---|
max_heap_bytes | size_t | 0 | Max heap memory (0 = unlimited) |
max_execution_ms | int64_t | 0 | Max execution time in ms (0 = unlimited) |
Functions
| Function | Description |
|---|---|
configure_sandbox(config) | Apply sandbox limits |
get_heap_usage() | Get current heap memory in bytes |
Cera Sandbox Methods
| Method | Returns | Description |
|---|---|---|
Sandbox.CheckTimeout() | int | 0 if OK, 1 if timed out |
Sandbox.GetMemoryUsage() | int | Current heap bytes |
Sandbox.GetMemoryLimit() | int | Configured limit (0 = unlimited) |
Sandbox.GetTimeoutSet() | int | 1 if timeout is active |