configurable trans-membrance hostcall blocklist

This commit is contained in:
root
2026-06-16 01:13:06 +00:00
parent 52cf266a5e
commit f2a3503ac3
60 changed files with 1675 additions and 338 deletions
+17
View File
@@ -53,6 +53,17 @@ static String wasm_backend_ensure_started(Request* context)
wc.memory_limit = (int64_t)to_u64(cfg["WASM_MEMORY_LIMIT_BYTES"], 512ull * 1024 * 1024);
wc.epoch_deadline_ticks = to_u64(cfg["WASM_EPOCH_DEADLINE_TICKS"], 200);
wc.verbose = to_bool(cfg["WASM_BACKEND_VERBOSE"], false);
// UCE_HOSTCALL_BLOCKLIST: comma-separated uce_host_* names (with or without
// the "uce_host_" prefix) the sysadmin disables; each blocked call traps into
// the error page (see make_host_import). Parsed once here, per worker process.
for(String entry : split(cfg["UCE_HOSTCALL_BLOCKLIST"], ","))
{
entry = trim(entry);
if(entry.rfind("uce_host_", 0) == 0)
entry = entry.substr(9);
if(entry != "")
wc.hostcall_blocklist.insert(entry);
}
g_wasm_worker = new WasmWorker(wc);
g_wasm_init_error = g_wasm_worker->init();
@@ -131,6 +142,12 @@ String wasm_backend_serve(Request& request, const String& entry_unit, const Stri
// Raw request body: cli_input() parses a JSON CLI payload from context.in,
// and serve_http handlers read it as req->in; carried into the workspace.
ctx["in"] = request.in;
// Configurable error pages read context.call["error"] (the error_info DValue
// set natively in render_wasm_error_page). apply_context binds context.call to
// the decoded ctx, so marshal the native request.call children across the
// membrane — otherwise the error page renders with no error data.
for(auto& entry : request.call._map)
ctx[entry.first] = entry.second;
// WebSocket event context: the workspace owns no connections, so the frame's
// connection identity goes in and the handler's ws_send/ws_close dispatch
// commands come back out (below) for the native broker to apply.
+34 -5
View File
@@ -3,6 +3,13 @@ uce_host_time_precise
uce_host_env
uce_host_log
uce_host_random
uce_host_sha256
uce_host_sha256_hex
uce_host_hmac_sha256
uce_host_hmac_sha256_hex
uce_host_base64_encode
uce_host_base64_decode
uce_host_crypto_equal
uce_host_task_spawn
uce_host_task_pid
uce_host_task_kill
@@ -20,6 +27,14 @@ uce_host_units
uce_host_component_resolve
uce_host_request_perf
uce_host_shell_exec
uce_host_http_request
uce_host_http_request_async
uce_host_shell_exec_dv
uce_host_shell_spawn
uce_host_job_status
uce_host_job_result
uce_host_job_await
uce_host_job_cancel
uce_host_file_exists
uce_host_file_read
uce_host_file_write
@@ -27,11 +42,25 @@ uce_host_file_unlink
uce_host_file_list
uce_host_file_mkdir
uce_host_file_mtime
uce_host_file_open_locked
uce_host_file_close_locked
uce_host_file_release_process_locks
uce_host_file_read_locked_fd
uce_host_file_write_locked_fd
uce_host_file_open
uce_host_file_handle_read
uce_host_file_handle_pread
uce_host_file_handle_write
uce_host_file_handle_pwrite
uce_host_file_handle_seek
uce_host_file_handle_tell
uce_host_file_handle_close
uce_host_file_stat
uce_host_dir_list
uce_host_file_rename
uce_host_file_copy
uce_host_file_truncate
uce_host_dir_remove
uce_host_file_temp
uce_host_file_chmod
uce_host_file_symlink
uce_host_file_readlink
uce_host_file_fsync
uce_host_path_real
uce_host_path_is_within
uce_host_cwd_get
+639 -103
View File
@@ -31,7 +31,9 @@
#include <cstring>
#include <ctime>
#include <fstream>
#include <filesystem>
#include <map>
#include <set>
#include <cstdio>
#include <memory>
#include <optional>
@@ -49,6 +51,9 @@
#include <algorithm>
#include <dirent.h>
#include <cerrno>
#include <sys/wait.h>
#include <signal.h>
#include <poll.h>
struct WasmDylinkInfo
{
@@ -86,6 +91,10 @@ struct WasmWorkerConfig
u32 table_headroom = 4096;
u64 epoch_deadline_ticks = 200; // ticker period × ticks = CPU budget
bool verbose = false;
// uce_host_* names (bare, without the "uce_host_" prefix) the sysadmin has
// disabled via UCE_HOSTCALL_BLOCKLIST. A blocked hostcall resolves to a trap
// stub at workspace birth (see make_host_import); empty = feature off.
std::set<String> hostcall_blocklist;
};
struct WasmResponse
@@ -100,6 +109,345 @@ struct WasmResponse
u64 component_resolve_total_us = 0;
};
static u64 wasm_file_lock_timeout_ms()
{
const char* raw = getenv("UCE_FILE_LOCK_TIMEOUT_MS");
if(!raw || !*raw)
return(2000);
char* end = 0;
unsigned long long parsed = strtoull(raw, &end, 10);
return(end == raw ? 2000 : (u64)parsed);
}
static u64 wasm_monotonic_ms()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return((u64)ts.tv_sec * 1000ull + (u64)ts.tv_nsec / 1000000ull);
}
static int wasm_open_locked_file(const String& file_name, int flags, int lock_type, bool truncate_after_lock)
{
int fd = open(file_name.c_str(), flags, 0644);
if(fd < 0)
return(-1);
fcntl(fd, F_SETFD, FD_CLOEXEC);
u64 timeout = wasm_file_lock_timeout_ms();
u64 deadline = wasm_monotonic_ms() + timeout;
while(true)
{
if(flock(fd, lock_type | LOCK_NB) == 0)
{
if(truncate_after_lock && ftruncate(fd, 0) != 0)
{
flock(fd, LOCK_UN);
close(fd);
return(-1);
}
return(fd);
}
if(errno != EWOULDBLOCK && errno != EAGAIN && errno != EINTR)
{
close(fd);
return(-1);
}
if(timeout == 0 || wasm_monotonic_ms() >= deadline)
{
fprintf(stderr, "[wasm] file lock timeout after %llums: %s\n", (unsigned long long)timeout, file_name.c_str());
close(fd);
return(-1);
}
usleep(10000);
}
}
static bool wasm_fd_write_all(int fd, const char* data, size_t remaining, u64* written_out)
{
u64 total = 0;
while(remaining > 0)
{
ssize_t n = write(fd, data, remaining);
if(n < 0)
{
if(errno == EINTR)
continue;
return(false);
}
if(n == 0)
return(false);
data += n;
remaining -= (size_t)n;
total += (u64)n;
}
if(written_out)
*written_out = total;
return(true);
}
// ---- file-backed async job registry + bounded process execution ----------
static String uce_job_root()
{
const char* env = getenv("UCE_JOB_ROOT");
String root = (env && *env) ? String(env) : String("/run/uce/jobs");
std::error_code ec;
std::filesystem::create_directories(root, ec);
if(ec)
{
root = "/tmp/uce/jobs";
std::filesystem::create_directories(root, ec);
}
return(root);
}
static String uce_job_path(u64 id) { return(uce_job_root() + "/" + std::to_string(id)); }
static String uce_read_text(const String& path) { std::ifstream in(path, std::ios::binary); if(!in) return(""); std::ostringstream ss; ss << in.rdbuf(); return(ss.str()); }
static void uce_write_text(const String& path, const String& data) { std::ofstream out(path, std::ios::binary|std::ios::trunc); out.write(data.data(), (std::streamsize)data.size()); }
static u64 uce_job_new(const String& kind)
{
String root = uce_job_root();
std::error_code ec;
std::filesystem::create_directories(root, ec);
u64 seed = ((u64)time(0) << 32) ^ ((u64)getpid() << 16) ^ (u64)rand();
for(int i = 0; i < 100; i++)
{
u64 id = seed ^ (wasm_monotonic_ms() + (u64)i * 0x9e3779b97f4a7c15ull);
String dir = root + "/" + std::to_string(id);
if(mkdir(dir.c_str(), 0700) == 0)
{
uce_write_text(dir + "/kind", kind);
uce_write_text(dir + "/created", std::to_string((u64)time(0)));
uce_write_text(dir + "/state", "pending");
return(id);
}
}
return(0);
}
static void uce_job_reap()
{
String root = uce_job_root();
u64 now = (u64)time(0);
u64 ttl = 3600;
if(const char* raw = getenv("UCE_JOB_TTL_SECONDS")) { char* e=0; unsigned long long v=strtoull(raw,&e,10); if(e!=raw && v>0) ttl=(u64)v; }
std::error_code ec;
for(auto& e : std::filesystem::directory_iterator(root, ec))
{
if(!e.is_directory()) continue;
u64 created = strtoull(uce_read_text(e.path().string()+"/created").c_str(), 0, 10);
if(created > 0 && now > created + ttl)
std::filesystem::remove_all(e.path(), ec);
}
}
static DValue uce_process_exec(String cmd, String input, StringMap env, u64 timeout_ms)
{
DValue r;
r["exit_code"] = (f64)-1;
r["stdout"] = "";
r["stderr"] = "";
r["timed_out"].set_bool(false);
if(timeout_ms == 0) timeout_ms = 5000;
int inpipe[2], outpipe[2], errpipe[2];
if(pipe(inpipe) || pipe(outpipe) || pipe(errpipe)) { r["stderr"]="pipe failed"; return(r); }
pid_t pid = fork();
if(pid == 0)
{
dup2(inpipe[0], 0); dup2(outpipe[1], 1); dup2(errpipe[1], 2);
close(inpipe[0]); close(inpipe[1]); close(outpipe[0]); close(outpipe[1]); close(errpipe[0]); close(errpipe[1]);
for(auto& kv : env) setenv(kv.first.c_str(), kv.second.c_str(), 1);
execl("/bin/sh", "sh", "-c", cmd.c_str(), (char*)0);
_exit(127);
}
close(inpipe[0]); close(outpipe[1]); close(errpipe[1]);
fcntl(outpipe[0], F_SETFL, fcntl(outpipe[0], F_GETFL, 0) | O_NONBLOCK);
fcntl(errpipe[0], F_SETFL, fcntl(errpipe[0], F_GETFL, 0) | O_NONBLOCK);
size_t input_off = 0; bool in_open = true, out_open = true, err_open = true; int status = 0; bool exited = false;
u64 deadline = wasm_monotonic_ms() + timeout_ms;
while(out_open || err_open || !exited)
{
if(!exited)
{
pid_t w = waitpid(pid, &status, WNOHANG);
if(w == pid) exited = true;
}
if(in_open)
{
if(input_off < input.size()) { ssize_t n=write(inpipe[1], input.data()+input_off, input.size()-input_off); if(n>0) input_off += (size_t)n; else if(n<0 && errno!=EINTR) { close(inpipe[1]); in_open=false; } }
else { close(inpipe[1]); in_open=false; }
}
char buf[4096];
ssize_t n;
while((n=read(outpipe[0], buf, sizeof(buf))) > 0) r["stdout"] = r["stdout"].to_string() + String(buf, n);
if(n == 0 && out_open) { close(outpipe[0]); out_open=false; }
while((n=read(errpipe[0], buf, sizeof(buf))) > 0) r["stderr"] = r["stderr"].to_string() + String(buf, n);
if(n == 0 && err_open) { close(errpipe[0]); err_open=false; }
if(!exited && wasm_monotonic_ms() >= deadline)
{
r["timed_out"].set_bool(true);
kill(pid, SIGKILL);
waitpid(pid, &status, 0);
exited = true;
}
if((out_open || err_open || !exited)) usleep(10000);
}
if(WIFEXITED(status)) { r["exit_code"] = (f64)WEXITSTATUS(status); r["timed_out"].set_bool(false); }
else if(WIFSIGNALED(status)) r["exit_code"] = (f64)(128 + WTERMSIG(status));
return(r);
}
static DValue uce_shell_exec_spec(const DValue& spec)
{
return(uce_process_exec(spec.key("cmd") ? spec.key("cmd")->to_string() : String(""), spec.key("stdin") ? spec.key("stdin")->to_string() : String(""), spec.key("env") ? spec.key("env")->to_stringmap() : StringMap(), spec.key("timeout_ms") ? spec.key("timeout_ms")->to_u64(5000) : 5000));
}
static void uce_job_finish(u64 id, DValue result, String final_state="done")
{
String dir = uce_job_path(id);
uce_write_text(dir + "/result.tmp", ucb_encode(result));
rename((dir + "/result.tmp").c_str(), (dir + "/result").c_str());
uce_write_text(dir + "/state", final_state);
}
static u64 uce_shell_spawn_spec(const DValue& spec)
{
uce_job_reap();
u64 id = uce_job_new("shell");
if(!id) return(0);
pid_t pid = fork();
if(pid == 0)
{
setsid();
uce_write_text(uce_job_path(id) + "/worker_pid", std::to_string((long long)getpid()));
uce_write_text(uce_job_path(id) + "/state", "running");
DValue result = uce_shell_exec_spec(spec);
uce_job_finish(id, result, "done");
_exit(0);
}
if(pid < 0) { DValue r; r["error"]="fork failed"; uce_job_finish(id,r,"failed"); return(id); }
uce_write_text(uce_job_path(id) + "/worker_pid", std::to_string((long long)pid));
uce_write_text(uce_job_path(id) + "/state", "running");
return(id);
}
static DValue uce_exec_argv_capture(std::vector<String> argv, String input, u64 timeout_ms)
{
DValue r; r["exit_code"]=(f64)-1; r["stdout"]=""; r["stderr"]=""; r["timed_out"].set_bool(false);
if(argv.empty()) { r["stderr"]="empty argv"; return(r); }
if(timeout_ms == 0) timeout_ms = 5000;
int inpipe[2], outpipe[2], errpipe[2];
if(pipe(inpipe)||pipe(outpipe)||pipe(errpipe)) { r["stderr"]="pipe failed"; return(r); }
pid_t pid=fork();
if(pid==0)
{
dup2(inpipe[0],0); dup2(outpipe[1],1); dup2(errpipe[1],2);
close(inpipe[0]); close(inpipe[1]); close(outpipe[0]); close(outpipe[1]); close(errpipe[0]); close(errpipe[1]);
std::vector<char*> args; for(auto& a: argv) args.push_back((char*)a.c_str()); args.push_back(0);
execvp(args[0], args.data()); _exit(127);
}
close(inpipe[0]); close(outpipe[1]); close(errpipe[1]);
fcntl(outpipe[0], F_SETFL, fcntl(outpipe[0], F_GETFL, 0)|O_NONBLOCK); fcntl(errpipe[0], F_SETFL, fcntl(errpipe[0], F_GETFL, 0)|O_NONBLOCK);
size_t input_off=0; bool in_open=true,out_open=true,err_open=true,exited=false; int status=0; u64 deadline=wasm_monotonic_ms()+timeout_ms;
while(out_open || err_open || !exited)
{
if(!exited) { pid_t w=waitpid(pid,&status,WNOHANG); if(w==pid) exited=true; }
if(in_open) { if(input_off<input.size()) { ssize_t n=write(inpipe[1], input.data()+input_off, input.size()-input_off); if(n>0) input_off+=(size_t)n; else if(n<0 && errno!=EINTR) { close(inpipe[1]); in_open=false; } } else { close(inpipe[1]); in_open=false; } }
char buf[4096]; ssize_t n; while((n=read(outpipe[0],buf,sizeof(buf)))>0) r["stdout"] = r["stdout"].to_string()+String(buf,n); if(n==0&&out_open){close(outpipe[0]);out_open=false;}
while((n=read(errpipe[0],buf,sizeof(buf)))>0) r["stderr"] = r["stderr"].to_string()+String(buf,n); if(n==0&&err_open){close(errpipe[0]);err_open=false;}
if(!exited && wasm_monotonic_ms() >= deadline) { r["timed_out"].set_bool(true); kill(pid,SIGKILL); waitpid(pid,&status,0); exited=true; }
if(out_open || err_open || !exited) usleep(10000);
}
if(WIFEXITED(status)) { r["exit_code"]=(f64)WEXITSTATUS(status); r["timed_out"].set_bool(false); } else if(WIFSIGNALED(status)) r["exit_code"]=(f64)(128+WTERMSIG(status));
return(r);
}
static bool uce_header_name_safe(String name)
{
if(name=="") return(false);
for(unsigned char c: name) if(!(isalnum(c)||c=='-'||c=='_')) return(false);
return(true);
}
static DValue uce_http_request_value(const DValue& req)
{
DValue r; r["status"]=(f64)0; r["headers"].set_array(); r["body"]=""; r["error"]="";
String method = req.key("method") ? to_upper(req.key("method")->to_string()) : String("GET");
String url = req.key("url") ? req.key("url")->to_string() : String("");
if(url=="" || url.find('\0')!=String::npos) { r["error"]="missing url"; return(r); }
if(method=="") method="GET";
std::vector<String> argv = {"curl", "-sS", "--http1.0", "-X", method, "-D", "-", "-w", "\nUCE_HTTP_STATUS:%{http_code}", "--max-time", std::to_string(std::max<u64>(1, (req.key("timeout_ms") ? req.key("timeout_ms")->to_u64(5000) : 5000) / 1000))};
if(req.key("follow_redirects") && req.key("follow_redirects")->to_bool()) argv.push_back("-L");
if(req.key("headers")) req.key("headers")->each([&](const DValue& v, String k){ if(uce_header_name_safe(k)) { argv.push_back("-H"); argv.push_back(k + ": " + replace(replace(v.to_string(), "\r", " "), "\n", " ")); } });
String body = req.key("body") ? req.key("body")->to_string() : String("");
if(req.key("body")) { argv.push_back("--data-binary"); argv.push_back("@-"); }
argv.push_back(url);
if(access("/usr/bin/curl", X_OK)!=0 && access("/bin/curl", X_OK)!=0) { r["error"]="curl binary not found in runtime PATH"; return(r); }
DValue pr = uce_exec_argv_capture(argv, body, req.key("timeout_ms") ? req.key("timeout_ms")->to_u64(5000) : 5000);
String out = pr["stdout"].to_string();
String marker="\nUCE_HTTP_STATUS:"; size_t mp=out.rfind(marker);
if(mp!=String::npos) { r["status"]=(f64)strtoull(out.c_str()+mp+marker.size(),0,10); out=out.substr(0,mp); }
else r["error"]="curl did not report status";
String sep="\r\n\r\n"; size_t hp=out.rfind(sep); size_t sep_len=4; if(hp==String::npos) { sep="\n\n"; hp=out.rfind(sep); sep_len=2; }
String hdrs = hp==String::npos ? String("") : out.substr(0,hp); r["body"] = hp==String::npos ? out : out.substr(hp+sep_len);
DValue headers;
for(String line: split(replace(hdrs,"\r",""), "\n")) { size_t c=line.find(':'); if(c!=String::npos) headers[trim(line.substr(0,c))] = trim(line.substr(c+1)); }
r["headers"] = headers;
if(pr["exit_code"].to_s64() != 0 && r["error"].to_string()=="") r["error"] = trim(pr["stderr"].to_string());
return(r);
}
static u64 uce_http_spawn_spec(const DValue& req)
{
uce_job_reap(); u64 id=uce_job_new("http"); if(!id) return(0);
pid_t pid=fork();
if(pid==0) { setsid(); uce_write_text(uce_job_path(id)+"/worker_pid", std::to_string((long long)getpid())); uce_write_text(uce_job_path(id)+"/state", "running"); DValue result=uce_http_request_value(req); uce_job_finish(id,result,result["error"].to_string()==""?"done":"failed"); _exit(0); }
if(pid<0) { DValue r; r["error"]="fork failed"; uce_job_finish(id,r,"failed"); return(id); }
uce_write_text(uce_job_path(id)+"/worker_pid", std::to_string((long long)pid)); uce_write_text(uce_job_path(id)+"/state", "running"); return(id);
}
static DValue uce_job_status_value(u64 id)
{
DValue r; String dir=uce_job_path(id); r["job_id"]=(f64)id;
if(id==0 || !std::filesystem::is_directory(dir)) { r["state"]="missing"; return(r); }
String state=trim(uce_read_text(dir+"/state")); if(state=="") state="pending"; r["state"]=state;
r["kind"]=trim(uce_read_text(dir+"/kind")); r["pid"]=(f64)strtoull(uce_read_text(dir+"/worker_pid").c_str(),0,10);
r["done"].set_bool(state=="done"||state=="failed"||state=="cancelled");
return(r);
}
static DValue uce_job_result_value(u64 id, u64 timeout_ms)
{
u64 deadline = wasm_monotonic_ms() + timeout_ms;
while(timeout_ms > 0 && wasm_monotonic_ms() < deadline)
{
DValue st = uce_job_status_value(id);
if(st["done"].to_bool()) break;
usleep(10000);
}
DValue r = uce_job_status_value(id);
String encoded = uce_read_text(uce_job_path(id)+"/result");
if(encoded != "") { DValue decoded; String err; if(ucb_decode(encoded, decoded, &err)) r["result"] = decoded; }
return(r);
}
static bool uce_job_cancel_value(u64 id)
{
DValue st = uce_job_status_value(id);
if(st["state"].to_string()=="missing") return(false);
String state = st["state"].to_string();
if(state == "done" || state == "failed" || state == "cancelled")
return(false);
pid_t pid = (pid_t)st["pid"].to_u64(0);
if(pid > 0) kill(-pid, SIGKILL);
DValue result; result["cancelled"].set_bool(true);
uce_job_finish(id, result, "cancelled");
return(true);
}
// ---- module byte parsing (hardened; carried from the phase 3 spike) -------
// included into both w3_driver.cpp and the native server TU (via backend.cpp);
@@ -411,6 +759,13 @@ public:
u64 component_resolve_count = 0;
u64 component_resolve_total_us = 0;
struct FileHandle
{
int fd = -1;
bool writable = false;
};
std::vector<FileHandle> file_handles;
struct RequestPerfSnapshot
{
u64 worker_pid = 0;
@@ -435,9 +790,6 @@ public:
request_perf.active = true;
}
// Host-owned opaque fd handles opened by wasm file_open_locked().
std::vector<int> locked_file_handles;
#ifdef UCE_WASM_HOST_CONNECTORS
// Host-owned resource handle table (§3.1): connections opened by the guest
// live here and are closed when the workspace drops at request end.
@@ -446,12 +798,15 @@ public:
#endif
~WasmWorkspace()
{
for(int fd : locked_file_handles)
if(fd >= 0)
for(auto& h : file_handles)
{
if(h.fd >= 0)
{
flock(fd, LOCK_UN);
::close(fd);
flock(h.fd, LOCK_UN);
close(h.fd);
h.fd = -1;
}
}
#ifdef UCE_WASM_HOST_CONNECTORS
for(auto* db : sqlite_handles)
if(db)
@@ -1124,7 +1479,7 @@ private:
{
char root_real[4096];
if(root != "" && realpath(root.c_str(), root_real))
root_prefixes.push_back(String(root_real) + "/");
root_prefixes.push_back(String(root_real));
}
for(auto& candidate : candidates)
{
@@ -1134,7 +1489,7 @@ private:
String path(resolved);
bool allowed = false;
for(auto& prefix : root_prefixes)
if(path.rfind(prefix, 0) == 0)
if(path == prefix || path.rfind(prefix + "/", 0) == 0)
{
allowed = true;
break;
@@ -1304,6 +1659,25 @@ private:
return(host_funcs.back());
};
// Hostcall blocklist (UCE_HOSTCALL_BLOCKLIST): a sysadmin-disabled hostcall
// resolves to a trap stub instead of its real implementation, so a unit
// invoking it fails at runtime into the configurable error page. The
// decision is made once per import at workspace birth — no per-call cost,
// and zero cost when nothing is blocked. A small core set stays exempt so
// the runtime itself cannot be bricked.
if(mod == "env" && !worker.cfg.hostcall_blocklist.empty() && name.rfind("uce_host_", 0) == 0)
{
static const std::set<String> non_blockable = { "component_resolve" };
String bare = name.substr(9);
if(worker.cfg.hostcall_blocklist.count(bare) && !non_blockable.count(bare))
{
std::string blocked(name);
return(add([blocked](Caller, Span<const Val>, Span<Val>) -> Result<std::monostate, Trap> {
return(Trap("UCE_POLICY_BLOCKED:" + blocked));
}));
}
}
if(mod == "env" && name == "uce_host_time")
return(add([](Caller, Span<const Val>, Span<Val> results) -> Result<std::monostate, Trap> {
results[0] = Val((int64_t)::time(0));
@@ -1367,6 +1741,20 @@ private:
results[0] = Val((int32_t)bytes.size());
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_sha256")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String in; self->hostcall_read(args[0].i32(), args[1].i32(), in); String out=sha256_native(in); u32 cap=(u32)args[3].i32(); int32_t buf=args[2].i32(); if(buf&&cap>=out.size()) self->hostcall_write(buf,out); results[0]=Val((int32_t)out.size()); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_sha256_hex")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String in; self->hostcall_read(args[0].i32(), args[1].i32(), in); String out=sha256_hex_native(in); u32 cap=(u32)args[3].i32(); int32_t buf=args[2].i32(); if(buf&&cap>=out.size()) self->hostcall_write(buf,out); results[0]=Val((int32_t)out.size()); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_hmac_sha256")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String key,in; self->hostcall_read(args[0].i32(), args[1].i32(), key); self->hostcall_read(args[2].i32(), args[3].i32(), in); String out=hmac_sha256_native(key,in); u32 cap=(u32)args[5].i32(); int32_t buf=args[4].i32(); if(buf&&cap>=out.size()) self->hostcall_write(buf,out); results[0]=Val((int32_t)out.size()); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_hmac_sha256_hex")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String key,in; self->hostcall_read(args[0].i32(), args[1].i32(), key); self->hostcall_read(args[2].i32(), args[3].i32(), in); String out=hmac_sha256_hex_native(key,in); u32 cap=(u32)args[5].i32(); int32_t buf=args[4].i32(); if(buf&&cap>=out.size()) self->hostcall_write(buf,out); results[0]=Val((int32_t)out.size()); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_base64_encode")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String in; self->hostcall_read(args[0].i32(), args[1].i32(), in); String out=base64_encode(in); u32 cap=(u32)args[3].i32(); int32_t buf=args[2].i32(); if(buf&&cap>=out.size()) self->hostcall_write(buf,out); results[0]=Val((int32_t)out.size()); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_base64_decode")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String in; self->hostcall_read(args[0].i32(), args[1].i32(), in); bool ok=false; String out=base64_decode(in, ok); if(!ok) out=""; u32 cap=(u32)args[3].i32(); int32_t buf=args[2].i32(); if(buf&&cap>=out.size()) self->hostcall_write(buf,out); results[0]=Val((int32_t)out.size()); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_crypto_equal")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String a,b; self->hostcall_read(args[0].i32(), args[1].i32(), a); self->hostcall_read(args[2].i32(), args[3].i32(), b); results[0]=Val((int32_t)(crypto_equal_native(a,b)?1:0)); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_log")
return(add([self](Caller, Span<const Val> args, Span<Val>) -> Result<std::monostate, Trap> {
String text;
@@ -1394,6 +1782,36 @@ private:
results[0] = Val((int32_t)out.size());
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_http_request")
return(add([self](Caller caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
String encoded; self->hostcall_read(args[0].i32(), args[1].i32(), encoded); u32 cap=(u32)args[3].i32(); int32_t buf=args[2].i32(); String out; String stage_key="http:"+encoded;
if(!self->hostcall_staged(stage_key,out)) { DValue req,response; String err; if(ucb_decode(encoded,req,&err)) response=uce_http_request_value(req); else response["error"]="http_request decode failed: "+err; out=ucb_encode(response); if(buf==0) self->hostcall_stage(stage_key,out); }
if(buf&&cap>=out.size()) self->hostcall_write(buf,out); caller.context().set_epoch_deadline(self->worker.cfg.epoch_deadline_ticks); results[0]=Val((int32_t)out.size()); return(std::monostate());
}));
if(mod == "env" && name == "uce_host_http_request_async")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String encoded; self->hostcall_read(args[0].i32(), args[1].i32(), encoded); DValue req; String err; u64 id=0; if(ucb_decode(encoded,req,&err)) id=uce_http_spawn_spec(req); results[0]=Val((int64_t)id); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_shell_exec_dv")
return(add([self](Caller caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
String encoded; self->hostcall_read(args[0].i32(), args[1].i32(), encoded);
u32 cap=(u32)args[3].i32(); int32_t buf=args[2].i32();
String out; String stage_key="shell_dv:"+encoded;
if(!self->hostcall_staged(stage_key,out)) { DValue spec, response; String err; if(ucb_decode(encoded,spec,&err)) response=uce_shell_exec_spec(spec); else response["error"]="shell_exec spec decode failed: "+err; out=ucb_encode(response); if(buf==0) self->hostcall_stage(stage_key,out); }
if(buf&&cap>=out.size()) self->hostcall_write(buf,out);
caller.context().set_epoch_deadline(self->worker.cfg.epoch_deadline_ticks);
results[0]=Val((int32_t)out.size()); return(std::monostate());
}));
if(mod == "env" && name == "uce_host_shell_spawn")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
String encoded; self->hostcall_read(args[0].i32(), args[1].i32(), encoded); DValue spec; String err; u64 id=0; if(ucb_decode(encoded,spec,&err)) id=uce_shell_spawn_spec(spec); results[0]=Val((int64_t)id); return(std::monostate());
}));
if(mod == "env" && name == "uce_host_job_status")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String out=ucb_encode(uce_job_status_value((u64)args[0].i64())); u32 cap=(u32)args[2].i32(); int32_t buf=args[1].i32(); if(buf&&cap>=out.size()) self->hostcall_write(buf,out); results[0]=Val((int32_t)out.size()); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_job_result")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String out=ucb_encode(uce_job_result_value((u64)args[0].i64(), 100)); u32 cap=(u32)args[2].i32(); int32_t buf=args[1].i32(); if(buf&&cap>=out.size()) self->hostcall_write(buf,out); results[0]=Val((int32_t)out.size()); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_job_await")
return(add([self](Caller caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { u64 timeout=std::min<u64>((u64)args[1].i64(), 30000); String out=ucb_encode(uce_job_result_value((u64)args[0].i64(), timeout)); u32 cap=(u32)args[3].i32(); int32_t buf=args[2].i32(); if(buf&&cap>=out.size()) self->hostcall_write(buf,out); caller.context().set_epoch_deadline(self->worker.cfg.epoch_deadline_ticks); results[0]=Val((int32_t)out.size()); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_job_cancel")
return(add([](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { results[0]=Val((int32_t)(uce_job_cancel_value((u64)args[0].i64())?1:0)); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_path_real")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
String path;
@@ -1484,109 +1902,25 @@ private:
results[0] = Val((int64_t)mtime);
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_open_locked")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
String path, purpose, current;
self->hostcall_read(args[0].i32(), args[1].i32(), path);
self->hostcall_read(args[6].i32(), args[7].i32(), purpose);
self->hostcall_read(args[8].i32(), args[9].i32(), current);
int open_flags = args[2].i32();
bool may_write = (open_flags & (O_WRONLY | O_RDWR | O_CREAT | O_TRUNC | O_APPEND)) != 0;
String resolved = may_write ? self->resolve_guest_write(path, current) : self->resolve_guest_file(path, current);
int fd = resolved != "" ? ::file_open_locked(resolved, open_flags, args[3].i32(), args[4].i32(), args[5].f64(), purpose) : -1;
int handle = -1;
if(fd >= 0)
{
for(size_t i = 0; i < self->locked_file_handles.size(); i++)
if(self->locked_file_handles[i] < 0)
{
self->locked_file_handles[i] = fd;
handle = (int)i + 1;
break;
}
if(handle < 0)
{
self->locked_file_handles.push_back(fd);
handle = (int)self->locked_file_handles.size();
}
}
results[0] = Val((int32_t)handle);
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_close_locked")
return(add([self](Caller, Span<const Val> args, Span<Val>) -> Result<std::monostate, Trap> {
int handle = args[0].i32();
if(handle >= 1 && (size_t)handle <= self->locked_file_handles.size())
{
int& fd = self->locked_file_handles[(size_t)handle - 1];
if(fd >= 0)
{
::file_close_locked(fd);
fd = -1;
}
}
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_release_process_locks")
return(add([self](Caller, Span<const Val>, Span<Val>) -> Result<std::monostate, Trap> {
for(int& fd : self->locked_file_handles)
if(fd >= 0)
{
::file_close_locked(fd);
fd = -1;
}
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_read_locked_fd")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
int handle = args[0].i32();
String content;
if(handle >= 1 && (size_t)handle <= self->locked_file_handles.size())
{
int fd = self->locked_file_handles[(size_t)handle - 1];
if(fd >= 0)
content = ::file_get_contents_locked_fd(fd);
}
u32 cap = (u32)args[2].i32();
int32_t buf = args[1].i32();
if(buf != 0 && cap >= content.size())
self->hostcall_write(buf, content);
results[0] = Val((int32_t)content.size());
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_write_locked_fd")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
int handle = args[0].i32();
String content;
self->hostcall_read(args[1].i32(), args[2].i32(), content);
bool ok = false;
if(handle >= 1 && (size_t)handle <= self->locked_file_handles.size())
{
int fd = self->locked_file_handles[(size_t)handle - 1];
if(fd >= 0)
ok = ::file_put_contents_locked_fd(fd, content);
}
results[0] = Val(ok ? (int32_t)1 : (int32_t)0);
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_read")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
String path, current;
self->hostcall_read(args[0].i32(), args[1].i32(), path);
self->hostcall_read(args[2].i32(), args[3].i32(), current);
String resolved = self->resolve_guest_file(path, current);
std::vector<u8> bytes;
if(resolved == "" || !wasm_read_file(resolved, bytes))
String stage_key = "file_read:" + path + "\0" + current;
String content;
if(!self->hostcall_staged(stage_key, content))
{
results[0] = Val((int32_t)0);
return(std::monostate());
String resolved = self->resolve_guest_file(path, current);
content = resolved == "" ? String("") : ::file_get_contents(resolved);
self->hostcall_stage(stage_key, content);
}
u32 cap = (u32)args[5].i32();
int32_t buf = args[4].i32();
// length-query convention: no copy unless the buffer fits
if(buf != 0 && cap >= bytes.size())
self->hostcall_write(buf, String((const char*)bytes.data(), bytes.size()));
results[0] = Val((int32_t)bytes.size());
if(buf != 0 && cap >= content.size())
self->hostcall_write(buf, content);
results[0] = Val((int32_t)content.size());
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_list")
@@ -1631,12 +1965,214 @@ private:
String resolved = self->resolve_guest_write(path, current);
bool ok = false;
if(resolved != "")
ok = append ? file_append_contents(resolved, content) : file_put_contents(resolved, content);
ok = append ? file_append(resolved, content) : file_put_contents(resolved, content);
else if(self->worker.cfg.verbose)
fprintf(stderr, "[wasm] file_write denied: %s\n", path.c_str());
results[0] = Val(ok ? (int32_t)1 : (int32_t)0);
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_open")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
String path, current, mode;
self->hostcall_read(args[0].i32(), args[1].i32(), path);
self->hostcall_read(args[2].i32(), args[3].i32(), current);
self->hostcall_read(args[4].i32(), args[5].i32(), mode);
String resolved;
int flags = O_RDONLY;
int lock_type = LOCK_SH;
bool writable = false;
bool truncate_after_lock = false;
if(mode == "r")
resolved = self->resolve_guest_file(path, current);
else if(mode == "w")
{
resolved = self->resolve_guest_write(path, current);
flags = O_RDWR | O_CREAT;
lock_type = LOCK_EX;
writable = true;
truncate_after_lock = true;
}
else if(mode == "a")
{
resolved = self->resolve_guest_write(path, current);
flags = O_RDWR | O_CREAT | O_APPEND;
lock_type = LOCK_EX;
writable = true;
}
else if(mode == "r+")
{
resolved = self->resolve_guest_write(path, current);
flags = O_RDWR;
lock_type = LOCK_EX;
writable = true;
}
uint64_t handle = 0;
if(resolved != "")
{
int fd = wasm_open_locked_file(resolved, flags, lock_type, truncate_after_lock);
if(fd >= 0)
{
if(mode == "a")
lseek(fd, 0, SEEK_END);
self->file_handles.push_back({fd, writable});
handle = self->file_handles.size();
}
}
results[0] = Val((int64_t)handle);
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_handle_read")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
u64 handle = (u64)args[0].i64();
u64 len = (u64)args[1].i64();
u32 cap = (u32)args[3].i32();
int32_t buf = args[2].i32();
String out;
String stage_key = "file_handle_read:" + std::to_string(handle) + ":" + std::to_string(len);
if(!self->hostcall_staged(stage_key, out))
{
if(handle >= 1 && handle <= self->file_handles.size())
{
int fd = self->file_handles[(size_t)handle - 1].fd;
if(fd >= 0 && len > 0)
{
out.resize((size_t)std::min<u64>(len, 16ull * 1024ull * 1024ull));
ssize_t n = read(fd, &out[0], out.size());
out.resize(n > 0 ? (size_t)n : 0);
}
}
if(buf == 0) self->hostcall_stage(stage_key, out);
}
if(buf != 0 && cap >= out.size()) self->hostcall_write(buf, out);
results[0] = Val((int32_t)out.size());
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_handle_pread")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
u64 handle = (u64)args[0].i64();
u64 offset = (u64)args[1].i64();
u64 len = (u64)args[2].i64();
u32 cap = (u32)args[4].i32();
int32_t buf = args[3].i32();
String out;
String stage_key = "file_handle_pread:" + std::to_string(handle) + ":" + std::to_string(offset) + ":" + std::to_string(len);
if(!self->hostcall_staged(stage_key, out))
{
if(handle >= 1 && handle <= self->file_handles.size())
{
int fd = self->file_handles[(size_t)handle - 1].fd;
if(fd >= 0 && len > 0)
{
out.resize((size_t)std::min<u64>(len, 16ull * 1024ull * 1024ull));
ssize_t n = pread(fd, &out[0], out.size(), (off_t)offset);
out.resize(n > 0 ? (size_t)n : 0);
}
}
if(buf == 0) self->hostcall_stage(stage_key, out);
}
if(buf != 0 && cap >= out.size()) self->hostcall_write(buf, out);
results[0] = Val((int32_t)out.size());
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_handle_write")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
String data; self->hostcall_read(args[1].i32(), args[2].i32(), data);
u64 handle = (u64)args[0].i64(); u64 written = 0;
if(handle >= 1 && handle <= self->file_handles.size())
{
auto& h = self->file_handles[(size_t)handle - 1];
if(h.fd >= 0 && h.writable) wasm_fd_write_all(h.fd, data.data(), data.size(), &written);
}
results[0] = Val((int64_t)written);
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_handle_pwrite")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
String data; self->hostcall_read(args[2].i32(), args[3].i32(), data);
u64 handle = (u64)args[0].i64(); u64 offset = (u64)args[1].i64(); u64 written = 0;
if(handle >= 1 && handle <= self->file_handles.size())
{
auto& h = self->file_handles[(size_t)handle - 1];
if(h.fd >= 0 && h.writable)
{
while(written < data.size())
{
ssize_t n = pwrite(h.fd, data.data() + written, data.size() - written, (off_t)(offset + written));
if(n < 0 && errno == EINTR) continue;
if(n <= 0) break;
written += (u64)n;
}
}
}
results[0] = Val((int64_t)written);
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_handle_seek")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
u64 handle = (u64)args[0].i64(); s64 pos = -1;
if(handle >= 1 && handle <= self->file_handles.size())
{
int fd = self->file_handles[(size_t)handle - 1].fd;
if(fd >= 0) pos = (s64)lseek(fd, (off_t)args[1].i64(), args[2].i32());
}
results[0] = Val((int64_t)pos);
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_handle_tell")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
u64 handle = (u64)args[0].i64(); s64 pos = -1;
if(handle >= 1 && handle <= self->file_handles.size())
{
int fd = self->file_handles[(size_t)handle - 1].fd;
if(fd >= 0) pos = (s64)lseek(fd, 0, SEEK_CUR);
}
results[0] = Val((int64_t)pos);
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_handle_close")
return(add([self](Caller, Span<const Val> args, Span<Val>) -> Result<std::monostate, Trap> {
u64 handle = (u64)args[0].i64();
if(handle >= 1 && handle <= self->file_handles.size())
{
auto& h = self->file_handles[(size_t)handle - 1];
if(h.fd >= 0) { flock(h.fd, LOCK_UN); close(h.fd); h.fd = -1; }
}
return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_stat")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
String path, current; self->hostcall_read(args[0].i32(), args[1].i32(), path); self->hostcall_read(args[2].i32(), args[3].i32(), current);
String resolved = self->resolve_guest_file(path, current, true); DValue r; struct stat st;
r["exists"].set_bool(resolved != "" && lstat(resolved.c_str(), &st) == 0);
if(r["exists"].to_bool()) { r["size"]=(f64)st.st_size; r["mtime"]=(f64)st.st_mtime; r["ctime"]=(f64)st.st_ctime; r["mode"]=(f64)(st.st_mode & 07777); r["is_dir"].set_bool(S_ISDIR(st.st_mode)); r["is_file"].set_bool(S_ISREG(st.st_mode)); r["is_symlink"].set_bool(S_ISLNK(st.st_mode)); }
else { r["size"]=(f64)0; r["mtime"]=(f64)0; r["ctime"]=(f64)0; r["mode"]=(f64)0; r["is_dir"].set_bool(false); r["is_file"].set_bool(false); r["is_symlink"].set_bool(false); }
String out = ucb_encode(r); u32 cap=(u32)args[5].i32(); int32_t buf=args[4].i32(); if(buf && cap>=out.size()) self->hostcall_write(buf,out); results[0]=Val((int32_t)out.size()); return(std::monostate());
}));
if(mod == "env" && name == "uce_host_dir_list")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
String path, current; self->hostcall_read(args[0].i32(), args[1].i32(), path); self->hostcall_read(args[2].i32(), args[3].i32(), current);
String resolved = self->resolve_guest_file(path, current, true); DValue list; list.set_array();
if(resolved != "") { std::vector<String> names; if(DIR* d=opendir(resolved.c_str())) { while(struct dirent* e=readdir(d)) { String n=e->d_name; if(n!="."&&n!="..") names.push_back(n); } closedir(d); } std::sort(names.begin(), names.end()); for(auto& n:names) { String p=resolved+"/"+n; struct stat st; DValue item; item["name"]=n; if(lstat(p.c_str(), &st)==0) { item["size"]=(f64)st.st_size; item["mtime"]=(f64)st.st_mtime; item["type"]=S_ISDIR(st.st_mode)?"dir":S_ISLNK(st.st_mode)?"symlink":S_ISREG(st.st_mode)?"file":"other"; } list.push(item); } }
String out=ucb_encode(list); u32 cap=(u32)args[5].i32(); int32_t buf=args[4].i32(); if(buf&&cap>=out.size()) self->hostcall_write(buf,out); results[0]=Val((int32_t)out.size()); return(std::monostate());
}));
if(mod == "env" && name == "uce_host_file_rename")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String from,to,current; self->hostcall_read(args[0].i32(),args[1].i32(),from); self->hostcall_read(args[2].i32(),args[3].i32(),to); self->hostcall_read(args[4].i32(),args[5].i32(),current); String rf=self->resolve_guest_write(from,current), rt=self->resolve_guest_write(to,current); results[0]=Val((int32_t)(rf!=""&&rt!=""&&rename(rf.c_str(),rt.c_str())==0)); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_file_copy")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String from,to,current; self->hostcall_read(args[0].i32(),args[1].i32(),from); self->hostcall_read(args[2].i32(),args[3].i32(),to); self->hostcall_read(args[4].i32(),args[5].i32(),current); String rf=self->resolve_guest_file(from,current), rt=self->resolve_guest_write(to,current); bool ok=false; if(rf!=""&&rt!="") { std::ifstream in(rf, std::ios::binary); std::ofstream out(rt, std::ios::binary|std::ios::trunc); out<<in.rdbuf(); struct stat st; if(in&&out) { ok=true; if(stat(rf.c_str(),&st)==0) chmod(rt.c_str(), st.st_mode & 07777); } } results[0]=Val((int32_t)ok); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_file_truncate")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String path,current; self->hostcall_read(args[0].i32(),args[1].i32(),path); self->hostcall_read(args[2].i32(),args[3].i32(),current); String r=self->resolve_guest_write(path,current); results[0]=Val((int32_t)(r!=""&&truncate(r.c_str(),(off_t)args[4].i64())==0)); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_dir_remove")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String path,current; self->hostcall_read(args[0].i32(),args[1].i32(),path); self->hostcall_read(args[2].i32(),args[3].i32(),current); String r=self->resolve_guest_write(path,current); bool rec=args[4].i32()!=0; bool ok=false; if(r!="") { if(rec) ok=std::filesystem::remove_all(r)>0; else ok=::rmdir(r.c_str())==0; } results[0]=Val((int32_t)ok); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_file_temp")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String prefix,current; self->hostcall_read(args[0].i32(),args[1].i32(),prefix); self->hostcall_read(args[2].i32(),args[3].i32(),current); u32 cap=(u32)args[5].i32(); int32_t buf=args[4].i32(); String out; String stage_key="file_temp:"+prefix+"\0"+current; if(!self->hostcall_staged(stage_key,out)) { if(prefix=="") prefix="/tmp/uce-temp"; String templ=self->resolve_guest_write(prefix+"XXXXXX",current); if(templ!="") { std::vector<char> t(templ.begin(), templ.end()); t.push_back(0); int fd=mkstemp(t.data()); if(fd>=0) { close(fd); out=t.data(); } } if(buf==0) self->hostcall_stage(stage_key,out); } if(buf&&cap>=out.size()) self->hostcall_write(buf,out); results[0]=Val((int32_t)out.size()); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_file_chmod")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String path,current; self->hostcall_read(args[0].i32(),args[1].i32(),path); self->hostcall_read(args[2].i32(),args[3].i32(),current); String r=self->resolve_guest_write(path,current); results[0]=Val((int32_t)(r!=""&&chmod(r.c_str(),(mode_t)args[4].i32())==0)); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_file_symlink")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String target,linkpath,current; self->hostcall_read(args[0].i32(),args[1].i32(),target); self->hostcall_read(args[2].i32(),args[3].i32(),linkpath); self->hostcall_read(args[4].i32(),args[5].i32(),current); String rt=self->resolve_guest_file(target,current), rl=self->resolve_guest_write(linkpath,current); results[0]=Val((int32_t)(rt!=""&&rl!=""&&symlink(rt.c_str(),rl.c_str())==0)); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_file_readlink")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { String path,current; self->hostcall_read(args[0].i32(),args[1].i32(),path); self->hostcall_read(args[2].i32(),args[3].i32(),current); String r=self->resolve_guest_write(path,current); String out; if(r!="") { char b[4096]; ssize_t n=readlink(r.c_str(),b,sizeof(b)); if(n>0) out.assign(b,n); } u32 cap=(u32)args[5].i32(); int32_t buf=args[4].i32(); if(buf&&cap>=out.size()) self->hostcall_write(buf,out); results[0]=Val((int32_t)out.size()); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_file_fsync")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> { u64 handle=(u64)args[0].i64(); bool ok=false; if(handle>=1&&handle<=self->file_handles.size()) { int fd=self->file_handles[(size_t)handle-1].fd; ok=fd>=0&&fsync(fd)==0; } results[0]=Val((int32_t)ok); return(std::monostate()); }));
if(mod == "env" && name == "uce_host_zip")
return(add([self](Caller, Span<const Val> args, Span<Val> results) -> Result<std::monostate, Trap> {
String encoded;