vile / scheme / system.v
381 lines · 344 sloc · 12.69 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import encoding.utf8
4import math
5import math.big
6import os
7import time
8
9// ExitRequest aborts a Scheme entry without terminating the embedding process.
10// Native callbacks should propagate control requests, as they do continuations.
11pub struct ExitRequest {
12 Error
13pub:
14 status i64
15 emergency bool
16}
17
18pub fn (request &ExitRequest) msg() string {
19 return if request.emergency {
20 'Scheme emergency exit requested (${request.status})'
21 } else {
22 'Scheme exit requested (${request.status})'
23 }
24}
25
26pub type ExitFn = fn (mut VM, ExitRequest) !
27
28fn request_process_exit(mut _vm VM, _request ExitRequest) ! {}
29
30// terminate_process is an explicit host opt-in. Portable OS statuses use the
31// low eight bits; a custom hook receives the original signed-64-bit value.
32pub fn terminate_process(mut _vm VM, request ExitRequest) ! {
33 system_terminate(request.status, request.emergency)
34}
35
36@[heap]
37struct SystemState {
38mut:
39 arguments_supplied bool
40 raw_arguments []string
41 arguments []Value
42 arguments_ready bool
43 environment_supplied bool
44 raw_environment map[string]string
45 jiffy_origin u64
46 exit_function &Function = unsafe { nil }
47 evaluation &EvaluationControl = unsafe { nil }
48 records &RecordRuntime = unsafe { nil }
49 return_function &Function = unsafe { nil }
50}
51
52fn new_system_state() &SystemState {
53 return &SystemState{ jiffy_origin: time.sys_mono_now() }
54}
55
56fn configured_system(options Options) &SystemState {
57 if args := options.arguments {
58 mut state := new_system_state()
59 state.arguments_supplied = true
60 state.raw_arguments = filled_storage(args.len, '')
61 for i, arg in args { container_store_validated(mut state.raw_arguments, i, arg.clone()) }
62 if variables := options.environment {
63 state.environment_supplied = true
64 for key, value in variables { state.raw_environment[key.clone()] = value.clone() }
65 }
66 return state
67 }
68 if variables := options.environment {
69 mut state := new_system_state()
70 state.environment_supplied = true
71 for key, value in variables { state.raw_environment[key.clone()] = value.clone() }
72 return state
73 }
74 return unsafe { nil }
75}
76
77fn validate_system_options(options Options) ! {
78 if offset := options.tai_utc_offset {
79 if math.is_nan(offset) || math.is_inf(offset, 0) {
80 return failure('TAI/UTC offset must be finite')
81 }
82 }
83}
84
85fn (mut vm VM) system_state() &SystemState {
86 if isnil(vm.system) {
87 vm.system = &vm.system_storage
88 vm.system.jiffy_origin = time.sys_mono_now()
89 }
90 return vm.system
91}
92
93fn immutable_system_string(text string) !Value {
94 if !utf8.validate_str(text) { return failure('system string is not valid UTF-8') }
95 return literal_value(owned_string(text, unicode_length(text)))
96}
97
98fn decoded_arguments(args []string, owned bool) ![]Value {
99 mut result := value_storage(args.len)
100 for i, arg in args {
101 container_store_validated(mut result, i, immutable_system_string(if owned {
102 arg
103 } else {
104 arg.clone()
105 })!)
106 }
107 return result
108}
109
110const system_native_descriptors = [
111 NativeDescriptor{'command-line', system_command_line}
112 NativeDescriptor{'get-environment-variable', system_getenv}
113 NativeDescriptor{'get-environment-variables', system_environ}
114 NativeDescriptor{'file-exists?', system_file_exists}
115 NativeDescriptor{'delete-file', system_delete_file}
116 NativeDescriptor{'current-second', system_current_second}
117 NativeDescriptor{'current-jiffy', system_current_jiffy}
118 NativeDescriptor{'jiffies-per-second', system_jiffy_rate}
119 NativeDescriptor{'exit', system_exit}
120 NativeDescriptor{'emergency-exit', system_emergency_exit},
121]!
122
123fn (mut vm VM) install_system_primitives() {
124 for index in 0 .. system_native_descriptors.len {
125 entry := &system_native_descriptors[index]
126 vm.bind_global(entry.name, procedure_value(&Procedure{ owner: vm.owner, mode: .native, name: entry.name, native: entry.callback }))
127 }
128}
129
130fn system_command_line(mut vm VM, args []Value) !Value {
131 check_arity('command-line', args.len, 0, 0)!
132 mut state := vm.system_state()
133 if !state.arguments_ready {
134 if v_arena_current() != vm.allocation_owner {
135 // Optional snapshots must not publish a borrowed arena's strings or
136 // array into the VM. Preserve supplied input for a later owned cache.
137 return list(if state.arguments_supplied {
138 decoded_arguments(state.raw_arguments, true)!
139 } else {
140 decoded_arguments(os.args, false)!
141 })
142 }
143 state.arguments = if state.arguments_supplied {
144 decoded_arguments(state.raw_arguments, true)!
145 } else {
146 decoded_arguments(os.args, false)!
147 }
148 state.raw_arguments = []string{}
149 state.arguments_ready = true
150 }
151 return list(state.arguments)
152}
153
154fn system_name(value Value) !string {
155 name := string_data(value)!
156 if name.contains('\x00') { return failure('system name contains NUL') }
157 if !utf8.validate_str(name) { return failure('system name is not valid UTF-8') }
158 return name
159}
160
161fn system_getenv(mut vm VM, args []Value) !Value {
162 check_arity('get-environment-variable', args.len, 1, 1)!
163 name := system_name(args[0])!
164 if !isnil(vm.system) && vm.system.environment_supplied {
165 value := vm.system.raw_environment[name] or { return boolean(false) }
166 return immutable_system_string(value)
167 }
168 value := os.getenv_opt(name) or { return boolean(false) }
169 return immutable_system_string(value)
170}
171
172fn environment_alist(variables map[string]string) !Value {
173 mut result := nil_value()
174 for name, value in variables {
175 key := immutable_system_string(name)!
176 data := immutable_system_string(value)!
177 result = literal_value(cons(literal_value(cons(key, data)), result))
178 }
179 return result
180}
181
182fn system_environ(mut vm VM, args []Value) !Value {
183 check_arity('get-environment-variables', args.len, 0, 0)!
184 if !isnil(vm.system) && vm.system.environment_supplied {
185 return environment_alist(vm.system.raw_environment)
186 }
187 return environment_alist(os.environ())
188}
189
190fn system_file_exists(mut _vm VM, args []Value) !Value {
191 check_arity('file-exists?', args.len, 1, 1)!
192 return boolean(os.exists(system_name(args[0])!))
193}
194
195fn system_delete_file(mut _vm VM, args []Value) !Value {
196 check_arity('delete-file', args.len, 1, 1)!
197 os.rm(system_name(args[0])!)!
198 return unspecified()
199}
200
201fn utc_seconds() f64 {
202 now := time.utc()
203 return f64(now.unix()) + f64(now.nanosecond) / 1e9
204}
205
206fn system_current_second(mut vm VM, args []Value) !Value {
207 check_arity('current-second', args.len, 0, 0)!
208 if offset := vm.options.tai_utc_offset { return real(utc_seconds() + offset) }
209 if seconds := system_tai_seconds() { return real(seconds) }
210 // R7RS permits UTC plus a suitable constant when TAI is unavailable.
211 // IERS Bulletin C 72: 37 seconds, current through June 2027. Hosts can
212 // override the approximation instead of waiting for a runtime update.
213 return real(utc_seconds() + 37.0)
214}
215
216fn system_current_jiffy(mut vm VM, args []Value) !Value {
217 check_arity('current-jiffy', args.len, 0, 0)!
218 state := vm.system_state()
219 elapsed := time.sys_mono_now() - state.jiffy_origin
220 if elapsed > u64(exact_max) { return owned_big_integer(big.integer_from_u64(elapsed)) }
221 return integer(i64(elapsed))
222}
223
224fn system_jiffy_rate(mut _vm VM, args []Value) !Value {
225 check_arity('jiffies-per-second', args.len, 0, 0)!
226 return integer(1000000000)
227}
228
229fn exit_status(args []Value, name string) !i64 {
230 check_arity(name, args.len, 0, 1)!
231 if args.len == 0 { return 0 }
232 value := args[0]
233 if value.tag == .boolean { return if value.is_true() { 0 } else { 1 } }
234 if !is_exact_integer(value) {
235 return failure('${name} status must be a boolean or exact integer')
236 }
237 return value.as_integer()
238}
239
240fn system_exit(mut vm VM, args []Value) !Value {
241 status := exit_status(args, 'exit')!
242 if vm.active.len == 0 { return failure('exit requires an active Scheme entry') }
243 mut state := vm.system_state()
244 if isnil(state.exit_function) {
245 state.exit_function = &process_exit_bridge_function
246 }
247 root := vm.active[0]
248 site := vm.active.last().error_site()
249 target := &Continuation{
250 owner: vm.owner
251 context: root.context
252 function: state.exit_function
253 parameters: root.parameter_base
254 parameter_base: root.parameter_base
255 stack: vm.exit_file_entries()
256 bridge_sites: if isnil(site.function) { []BridgeSite{} } else { [BridgeSite{site, 0}] }
257 }
258 return ContinuationTransfer{ continuation: target, result: integer(status) }
259}
260
261fn system_emergency_exit(mut vm VM, args []Value) !Value {
262 request := ExitRequest{ status: exit_status(args, 'emergency-exit')!, emergency: true }
263 vm.options.exit_handler(mut vm, request)!
264 return request
265}
266
267fn (mut m Machine) finish_process_exit(mut vm VM, phase int) ! {
268 if phase == 1 {
269 m.step_process_exit_cleanup(mut vm)!
270 return
271 }
272 if phase == 2 {
273 m.collect_process_exit_cleanup()
274 return
275 }
276 request := ExitRequest{ status: m.pop_value().whole() }
277 // The exit has committed: after procedures can no longer cancel it.
278 // Close before invoking a host hook, which may terminate the process.
279 for index, entry in m.stack {
280 port := entry.pair_pointer().car
281 if !isnil(custom_port_resource(port)) {
282 m.begin_process_exit_cleanup(request, index)
283 return
284 }
285 vm.close_port(port) or { if is_control_transfer(err) { return err } }
286 }
287 m.truncate(0)
288 vm.options.exit_handler(mut vm, request)!
289 return request
290}
291
292// A pending exit owns an immutable snapshot in its synthetic continuation's
293// operand stack. Each entry pairs a port with the host context that entered it.
294// Keeping this with the wind plan preserves cancellation and multi-shot reentry.
295fn (vm &VM) append_pending_exit_files(mut entries []Value, function &Function, env &Environment, committed bool) {
296 entries << vm.pending_exit_entries(function, env, committed)
297}
298
299// These queues are immutable. Cleanup can borrow them without allocating a
300// gather array while already handling a resource failure.
301fn (vm &VM) pending_exit_entries(function &Function, env &Environment, committed bool) []Value {
302 if committed && !isnil(function) && !isnil(env) {
303 if voidptr(function) == voidptr(&process_exit_cleanup_bridge) {
304 state := process_exit_cleanup_state(env)
305 return unsafe { state.entries[state.index..] }
306 }
307 if voidptr(function) == voidptr(&custom_close_failure_bridge) {
308 state := unsafe { &CustomCloseFailure(env.slots[0].pointer()) }
309 if !isnil(state.exit_recovery) {
310 return vm.pending_exit_entries(state.exit_recovery.function, state.exit_recovery.env, true)
311 }
312 return []Value{}
313 }
314 }
315 if isnil(vm.system) || isnil(vm.system.exit_function) || isnil(function)
316 || voidptr(function) != voidptr(vm.wind_transfer_function) || isnil(env) {
317 return []Value{}
318 }
319 target := unsafe { &Continuation(env.slots[0].pointer()) }
320 if voidptr(target.function) == voidptr(vm.system.exit_function) { return unsafe { target.stack } }
321 return []Value{}
322}
323
324fn (mut vm VM) close_pending_exit_files(machine &Machine, committed bool) {
325 vm.close_exit_file_entries(vm.pending_exit_entries(machine.function, machine.env, committed), machine.context)
326 for frame in machine.frames {
327 vm.close_exit_file_entries(vm.pending_exit_entries(frame.function, frame.env, committed), machine.context)
328 }
329}
330
331fn (vm &VM) pending_exit_file_entries(machine &Machine, committed bool) []Value {
332 mut entries := []Value{}
333 vm.append_pending_exit_files(mut entries, machine.function, machine.env, committed)
334 for frame in machine.frames {
335 vm.append_pending_exit_files(mut entries, frame.function, frame.env, committed)
336 }
337 return entries
338}
339
340fn (vm &VM) exit_file_entries() []Value {
341 mut entries := []Value{}
342 if !isnil(vm.ports) {
343 mut binding := vm.ports.bindings
344 for !isnil(binding) {
345 entries << cons(binding.extent.file, integer(i64(binding.context)))
346 binding = binding.previous
347 }
348 }
349 // Another exit in an after procedure supersedes the status, but must keep
350 // ports that earlier exit winders already removed from the active bindings.
351 for machine in vm.active { entries << vm.pending_exit_file_entries(machine, true) }
352 return entries
353}
354
355fn (mut vm VM) close_exit_file_entries(entries []Value, leaving_context u64) {
356 for entry in entries {
357 pair := entry.pair_pointer()
358 context := u64(pair.cdr.whole())
359 if leaving_context != 0 {
360 mut parent_owns := false
361 for machine in vm.active {
362 if machine.context == context && context != leaving_context {
363 parent_owns = true
364 break
365 }
366 }
367 // A caught error from native reentry must preserve its parent's ports.
368 if parent_owns { continue }
369 }
370 // Ordinary error abandonment cannot invoke a Scheme callback. Committed
371 // exit cleanup has its own resumable driver and recovery checkpoint.
372 if isnil(custom_port_resource(pair.car)) { vm.close_port(pair.car) or {} }
373 }
374}
375
376fn (mut vm VM) cleanup_pending_exit_files(machine &Machine, err IError) {
377 // A cross-entry continuation transfer is still winding. An outer after
378 // procedure may cancel it, so resources must survive that propagation.
379 if err is ContinuationTransfer { return }
380 vm.close_pending_exit_files(machine, false)
381}
382