module scheme import encoding.utf8 import math import math.big import os import time // ExitRequest aborts a Scheme entry without terminating the embedding process. // Native callbacks should propagate control requests, as they do continuations. pub struct ExitRequest { Error pub: status i64 emergency bool } pub fn (request &ExitRequest) msg() string { return if request.emergency { 'Scheme emergency exit requested (${request.status})' } else { 'Scheme exit requested (${request.status})' } } pub type ExitFn = fn (mut VM, ExitRequest) ! fn request_process_exit(mut _vm VM, _request ExitRequest) ! {} // terminate_process is an explicit host opt-in. Portable OS statuses use the // low eight bits; a custom hook receives the original signed-64-bit value. pub fn terminate_process(mut _vm VM, request ExitRequest) ! { system_terminate(request.status, request.emergency) } @[heap] struct SystemState { mut: arguments_supplied bool raw_arguments []string arguments []Value arguments_ready bool environment_supplied bool raw_environment map[string]string jiffy_origin u64 exit_function &Function = unsafe { nil } evaluation &EvaluationControl = unsafe { nil } records &RecordRuntime = unsafe { nil } return_function &Function = unsafe { nil } } fn new_system_state() &SystemState { return &SystemState{ jiffy_origin: time.sys_mono_now() } } fn configured_system(options Options) &SystemState { if args := options.arguments { mut state := new_system_state() state.arguments_supplied = true state.raw_arguments = filled_storage(args.len, '') for i, arg in args { container_store_validated(mut state.raw_arguments, i, arg.clone()) } if variables := options.environment { state.environment_supplied = true for key, value in variables { state.raw_environment[key.clone()] = value.clone() } } return state } if variables := options.environment { mut state := new_system_state() state.environment_supplied = true for key, value in variables { state.raw_environment[key.clone()] = value.clone() } return state } return unsafe { nil } } fn validate_system_options(options Options) ! { if offset := options.tai_utc_offset { if math.is_nan(offset) || math.is_inf(offset, 0) { return failure('TAI/UTC offset must be finite') } } } fn (mut vm VM) system_state() &SystemState { if isnil(vm.system) { vm.system = &vm.system_storage vm.system.jiffy_origin = time.sys_mono_now() } return vm.system } fn immutable_system_string(text string) !Value { if !utf8.validate_str(text) { return failure('system string is not valid UTF-8') } return literal_value(owned_string(text, unicode_length(text))) } fn decoded_arguments(args []string, owned bool) ![]Value { mut result := value_storage(args.len) for i, arg in args { container_store_validated(mut result, i, immutable_system_string(if owned { arg } else { arg.clone() })!) } return result } const system_native_descriptors = [ NativeDescriptor{'command-line', system_command_line} NativeDescriptor{'get-environment-variable', system_getenv} NativeDescriptor{'get-environment-variables', system_environ} NativeDescriptor{'file-exists?', system_file_exists} NativeDescriptor{'delete-file', system_delete_file} NativeDescriptor{'current-second', system_current_second} NativeDescriptor{'current-jiffy', system_current_jiffy} NativeDescriptor{'jiffies-per-second', system_jiffy_rate} NativeDescriptor{'exit', system_exit} NativeDescriptor{'emergency-exit', system_emergency_exit}, ]! fn (mut vm VM) install_system_primitives() { for index in 0 .. system_native_descriptors.len { entry := &system_native_descriptors[index] vm.bind_global(entry.name, procedure_value(&Procedure{ owner: vm.owner, mode: .native, name: entry.name, native: entry.callback })) } } fn system_command_line(mut vm VM, args []Value) !Value { check_arity('command-line', args.len, 0, 0)! mut state := vm.system_state() if !state.arguments_ready { if v_arena_current() != vm.allocation_owner { // Optional snapshots must not publish a borrowed arena's strings or // array into the VM. Preserve supplied input for a later owned cache. return list(if state.arguments_supplied { decoded_arguments(state.raw_arguments, true)! } else { decoded_arguments(os.args, false)! }) } state.arguments = if state.arguments_supplied { decoded_arguments(state.raw_arguments, true)! } else { decoded_arguments(os.args, false)! } state.raw_arguments = []string{} state.arguments_ready = true } return list(state.arguments) } fn system_name(value Value) !string { name := string_data(value)! if name.contains('\x00') { return failure('system name contains NUL') } if !utf8.validate_str(name) { return failure('system name is not valid UTF-8') } return name } fn system_getenv(mut vm VM, args []Value) !Value { check_arity('get-environment-variable', args.len, 1, 1)! name := system_name(args[0])! if !isnil(vm.system) && vm.system.environment_supplied { value := vm.system.raw_environment[name] or { return boolean(false) } return immutable_system_string(value) } value := os.getenv_opt(name) or { return boolean(false) } return immutable_system_string(value) } fn environment_alist(variables map[string]string) !Value { mut result := nil_value() for name, value in variables { key := immutable_system_string(name)! data := immutable_system_string(value)! result = literal_value(cons(literal_value(cons(key, data)), result)) } return result } fn system_environ(mut vm VM, args []Value) !Value { check_arity('get-environment-variables', args.len, 0, 0)! if !isnil(vm.system) && vm.system.environment_supplied { return environment_alist(vm.system.raw_environment) } return environment_alist(os.environ()) } fn system_file_exists(mut _vm VM, args []Value) !Value { check_arity('file-exists?', args.len, 1, 1)! return boolean(os.exists(system_name(args[0])!)) } fn system_delete_file(mut _vm VM, args []Value) !Value { check_arity('delete-file', args.len, 1, 1)! os.rm(system_name(args[0])!)! return unspecified() } fn utc_seconds() f64 { now := time.utc() return f64(now.unix()) + f64(now.nanosecond) / 1e9 } fn system_current_second(mut vm VM, args []Value) !Value { check_arity('current-second', args.len, 0, 0)! if offset := vm.options.tai_utc_offset { return real(utc_seconds() + offset) } if seconds := system_tai_seconds() { return real(seconds) } // R7RS permits UTC plus a suitable constant when TAI is unavailable. // IERS Bulletin C 72: 37 seconds, current through June 2027. Hosts can // override the approximation instead of waiting for a runtime update. return real(utc_seconds() + 37.0) } fn system_current_jiffy(mut vm VM, args []Value) !Value { check_arity('current-jiffy', args.len, 0, 0)! state := vm.system_state() elapsed := time.sys_mono_now() - state.jiffy_origin if elapsed > u64(exact_max) { return owned_big_integer(big.integer_from_u64(elapsed)) } return integer(i64(elapsed)) } fn system_jiffy_rate(mut _vm VM, args []Value) !Value { check_arity('jiffies-per-second', args.len, 0, 0)! return integer(1000000000) } fn exit_status(args []Value, name string) !i64 { check_arity(name, args.len, 0, 1)! if args.len == 0 { return 0 } value := args[0] if value.tag == .boolean { return if value.is_true() { 0 } else { 1 } } if !is_exact_integer(value) { return failure('${name} status must be a boolean or exact integer') } return value.as_integer() } fn system_exit(mut vm VM, args []Value) !Value { status := exit_status(args, 'exit')! if vm.active.len == 0 { return failure('exit requires an active Scheme entry') } mut state := vm.system_state() if isnil(state.exit_function) { state.exit_function = &process_exit_bridge_function } root := vm.active[0] site := vm.active.last().error_site() target := &Continuation{ owner: vm.owner context: root.context function: state.exit_function parameters: root.parameter_base parameter_base: root.parameter_base stack: vm.exit_file_entries() bridge_sites: if isnil(site.function) { []BridgeSite{} } else { [BridgeSite{site, 0}] } } return ContinuationTransfer{ continuation: target, result: integer(status) } } fn system_emergency_exit(mut vm VM, args []Value) !Value { request := ExitRequest{ status: exit_status(args, 'emergency-exit')!, emergency: true } vm.options.exit_handler(mut vm, request)! return request } fn (mut m Machine) finish_process_exit(mut vm VM, phase int) ! { if phase == 1 { m.step_process_exit_cleanup(mut vm)! return } if phase == 2 { m.collect_process_exit_cleanup() return } request := ExitRequest{ status: m.pop_value().whole() } // The exit has committed: after procedures can no longer cancel it. // Close before invoking a host hook, which may terminate the process. for index, entry in m.stack { port := entry.pair_pointer().car if !isnil(custom_port_resource(port)) { m.begin_process_exit_cleanup(request, index) return } vm.close_port(port) or { if is_control_transfer(err) { return err } } } m.truncate(0) vm.options.exit_handler(mut vm, request)! return request } // A pending exit owns an immutable snapshot in its synthetic continuation's // operand stack. Each entry pairs a port with the host context that entered it. // Keeping this with the wind plan preserves cancellation and multi-shot reentry. fn (vm &VM) append_pending_exit_files(mut entries []Value, function &Function, env &Environment, committed bool) { entries << vm.pending_exit_entries(function, env, committed) } // These queues are immutable. Cleanup can borrow them without allocating a // gather array while already handling a resource failure. fn (vm &VM) pending_exit_entries(function &Function, env &Environment, committed bool) []Value { if committed && !isnil(function) && !isnil(env) { if voidptr(function) == voidptr(&process_exit_cleanup_bridge) { state := process_exit_cleanup_state(env) return unsafe { state.entries[state.index..] } } if voidptr(function) == voidptr(&custom_close_failure_bridge) { state := unsafe { &CustomCloseFailure(env.slots[0].pointer()) } if !isnil(state.exit_recovery) { return vm.pending_exit_entries(state.exit_recovery.function, state.exit_recovery.env, true) } return []Value{} } } if isnil(vm.system) || isnil(vm.system.exit_function) || isnil(function) || voidptr(function) != voidptr(vm.wind_transfer_function) || isnil(env) { return []Value{} } target := unsafe { &Continuation(env.slots[0].pointer()) } if voidptr(target.function) == voidptr(vm.system.exit_function) { return unsafe { target.stack } } return []Value{} } fn (mut vm VM) close_pending_exit_files(machine &Machine, committed bool) { vm.close_exit_file_entries(vm.pending_exit_entries(machine.function, machine.env, committed), machine.context) for frame in machine.frames { vm.close_exit_file_entries(vm.pending_exit_entries(frame.function, frame.env, committed), machine.context) } } fn (vm &VM) pending_exit_file_entries(machine &Machine, committed bool) []Value { mut entries := []Value{} vm.append_pending_exit_files(mut entries, machine.function, machine.env, committed) for frame in machine.frames { vm.append_pending_exit_files(mut entries, frame.function, frame.env, committed) } return entries } fn (vm &VM) exit_file_entries() []Value { mut entries := []Value{} if !isnil(vm.ports) { mut binding := vm.ports.bindings for !isnil(binding) { entries << cons(binding.extent.file, integer(i64(binding.context))) binding = binding.previous } } // Another exit in an after procedure supersedes the status, but must keep // ports that earlier exit winders already removed from the active bindings. for machine in vm.active { entries << vm.pending_exit_file_entries(machine, true) } return entries } fn (mut vm VM) close_exit_file_entries(entries []Value, leaving_context u64) { for entry in entries { pair := entry.pair_pointer() context := u64(pair.cdr.whole()) if leaving_context != 0 { mut parent_owns := false for machine in vm.active { if machine.context == context && context != leaving_context { parent_owns = true break } } // A caught error from native reentry must preserve its parent's ports. if parent_owns { continue } } // Ordinary error abandonment cannot invoke a Scheme callback. Committed // exit cleanup has its own resumable driver and recovery checkpoint. if isnil(custom_port_resource(pair.car)) { vm.close_port(pair.car) or {} } } } fn (mut vm VM) cleanup_pending_exit_files(machine &Machine, err IError) { // A cross-entry continuation transfer is still winding. An outer after // procedure may cancel it, so resources must survive that propagation. if err is ContinuationTransfer { return } vm.close_pending_exit_files(machine, false) }