Skip to content

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 API
cera::api::SandboxConfig config;
config.max_heap_bytes = 10 * 1024 * 1024; // 10 MB
cera::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 bytes
int limit = Sandbox.GetMemoryLimit(); // Configured limit (0 = unlimited)

Execution Timeout

The host can set a wall-clock execution timeout:

// C++ Host API
cera::api::SandboxConfig config;
config.max_execution_ms = 5000; // 5 seconds
cera::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 active
int expired = Sandbox.CheckTimeout(); // 0 = OK, 1 = timed out

For 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, Path to prevent filesystem access
  • Omit Thread, Mutex to 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

FieldTypeDefaultDescription
max_heap_bytessize_t0Max heap memory (0 = unlimited)
max_execution_msint64_t0Max execution time in ms (0 = unlimited)

Functions

FunctionDescription
configure_sandbox(config)Apply sandbox limits
get_heap_usage()Get current heap memory in bytes

Cera Sandbox Methods

MethodReturnsDescription
Sandbox.CheckTimeout()int0 if OK, 1 if timed out
Sandbox.GetMemoryUsage()intCurrent heap bytes
Sandbox.GetMemoryLimit()intConfigured limit (0 = unlimited)
Sandbox.GetTimeoutSet()int1 if timeout is active