Debian Codegraph @

src/vm.c

raw
1 /*
2 * vm.c - virtual machine
3 *
4 * Copyright (c) 2000-2024 Shiro Kawai <[email protected]>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * 3. Neither the name of the authors nor the names of its contributors
18 * may be used to endorse or promote products derived from this
19 * software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 #define LIBGAUCHE_BODY
35 #include "gauche.h"
36 #include "gauche/priv/configP.h"
37 #include "gauche/exception.h"
38 #include "gauche/priv/builtin-syms.h"
39 #include "gauche/priv/codeP.h"
40 #include "gauche/priv/vmP.h"
41 #include "gauche/priv/glocP.h"
42 #include "gauche/priv/identifierP.h"
43 #include "gauche/priv/parameterP.h"
44 #include "gauche/priv/promiseP.h"
45 #include "gauche/code.h"
46 #include "gauche/vminsn.h"
47 #include "gauche/prof.h"
48 #include "gauche/precomp.h"
49
50 /* Experimental code to use custom mark procedure for stack gc.
51 Currently it doens't show any improvement, so we disable it
52 by default. */
53 #ifdef USE_CUSTOM_STACK_MARKER
54 #include "gc_mark.h"
55
56 static void **vm_stack_free_list;
57 static int vm_stack_kind;
58 static int vm_stack_mark_proc;
59 #endif /*USE_CUSTOM_STACK_MARKER*/
60
61 #ifdef HAVE_SCHED_H
62 #include <sched.h>
63 #endif
64
65 #ifndef EX_SOFTWARE
66 /* SRFI-22 requires this. */
67 #define EX_SOFTWARE 70
68 #endif
69
70 /* Prompt tag. Class initialization is done in class.c */
71 static void prompt_tag_print(ScmObj obj, ScmPort *out,
72 ScmWriteContext *ctx SCM_UNUSED)
73 {
74 Scm_Printf(out, "#<prompt-tag %S>", SCM_PROMPT_TAG(obj)->name);
75 }
76
77 SCM_DEFINE_BUILTIN_CLASS(Scm_PromptTagClass,
78 prompt_tag_print, NULL, NULL, NULL,
79 SCM_CLASS_DEFAULT_CPL);
80
81 static ScmPromptTag defaultPromptTag; /* initialized in initVM */
82
83 struct ScmContinuationPromptRec {
84 ScmContFrame *bottom;
85 ScmContFrame *bottom_top;
86 struct ScmContinuationPromptRec *prev;
87 };
88
89 /* bitflags for ScmContFrame->marker */
90 enum {
91 SCM_CONT_SHIFT_MARKER = (1L<<0),
92 SCM_CONT_RESET_MARKER = (1L<<1)
93 };
94
95 static void push_prompt_cont(ScmVM*, ScmObj, ScmObj);
96 static void push_boundary_cont(ScmVM*, ScmObj, ScmObj);
97
98 /* return true if cont is a boundary continuation frame */
99 #define BOUNDARY_FRAME_P(cont) ((cont)->marker & SCM_CONT_RESET_MARKER)
100
101 /* return true if cont has the end marker of partial continuation */
102 #define MARKER_FRAME_P(cont) ((cont)->marker & SCM_CONT_SHIFT_MARKER)
103
104 /* A stub VM code to make VM return immediately */
105 static ScmWord return_code[] = { SCM_VM_INSN(SCM_VM_RET) };
106 #define PC_TO_RETURN return_code
107
108 /* A dummy env frame to indicate C Continuation */
109 static ScmEnvFrame ccEnvMark = {
110 NULL, /* up */
111 SCM_FALSE, /* info */
112 0 /* size */
113 };
114
115 #define C_CONTINUATION_P(cont) ((cont)->env == &ccEnvMark)
116
117 /* If you have ScmContFrame *cont and you'll do something that can trigger
118 saving frames, you have to call this first to ensure that your
119 cont frame keeps pointing a valid frame. */
120 #define ENSURE_SAVE_CONT(cont) \
121 do { \
122 save_cont(vm); \
123 if (FORWARDED_CONT_P(cont)) { \
124 cont = FORWARDED_CONT(cont); \
125 } \
126 } while (0)
127
128 /* Unique uninterned symbol to indicate continuation procedure. */
129 static ScmObj continuation_symbol = SCM_UNBOUND;
130
131 /* Unique dynamic env keys for system use. We use uninterned symbol for
132 this purpose, for it is easier while debugging.
133 They're set during initialization. */
134 static ScmObj denv_key_exception_handler = SCM_UNBOUND;
135 static ScmObj denv_key_dynamic_handler = SCM_UNBOUND;
136 static ScmObj denv_key_parameterization = SCM_UNBOUND;
137 static ScmObj denv_key_expression_name = SCM_UNBOUND;
138
139 /* A dummy compiled code structure used as 'fill-in', when Scm_Apply
140 is called without any VM code running. See Scm_Apply below. */
141 static ScmCompiledCode internal_apply_compiled_code =
142 SCM_COMPILED_CODE_CONST_INITIALIZER(NULL, 0, 0, 0, 0,
143 SCM_SYM_INTERNAL_APPLY,
144 SCM_NIL, SCM_FALSE,
145 SCM_FALSE, SCM_FALSE);
146
147 /* This saves offset of each instruction handler, initialized by
148 the first call to run_loop. The info can be used for detailed
149 profiling. */
150 static unsigned long vminsn_offsets[SCM_VM_NUM_INSNS] = { 0, };
151
152 /*
153 * The VM.
154 *
155 * VM encapsulates the dynamic status of the current execution.
156 * In Gauche, there's always one active virtual machine per thread,
157 * referred by Scm_VM().
158 *
159 * From Scheme, VM is viewed as <thread> object. The class definition
160 * is in thrlib.stub.
161 */
162
163 static ScmVM *rootVM = NULL; /* VM for primodial thread */
164 static ScmHashCore vm_table; /* VMs other than primordial one is
165 registered to this hashtable, in order
166 to avoid being GC-ed. */
167 static ScmInternalMutex vm_table_mutex;
168 static void vm_register(ScmVM *vm);
169 static void vm_unregister(ScmVM *vm);
170
171 static u_long vm_numeric_id = 0; /* used for Scm_VM->vmid */
172 static ScmInternalMutex vm_id_mutex;
173
174 #define CALL_TRACE_SIZE_MIN 512
175 #define CALL_TRACE_SIZE_MAX 65535
176 static u_long vm_call_trace_size = 0; /* global default */
177
178 #ifdef GAUCHE_USE_PTHREADS
179 static pthread_key_t vm_key;
180 #define theVM ((ScmVM*)pthread_getspecific(vm_key))
181 #elif GAUCHE_USE_WTHREADS
182 static DWORD vm_key;
183 #define theVM ((ScmVM*)TlsGetValue(vm_key))
184 #else /* !GAUCHE_USE_PTHREADS && !GAUCHE_USE_WTHREADS */
185 static ScmVM *theVM;
186 #endif /* !GAUCHE_USE_PTHREADS */
187
188 static void save_stack(ScmVM *vm);
189
190 static ScmObj find_dynamic_env(ScmVM *vm, ScmObj key, ScmObj fallback);
191 static void push_dynamic_env(ScmVM *vm, ScmObj key, ScmObj val);
192
193 static ScmSubr default_exception_handler_rec;
194 #define DEFAULT_EXCEPTION_HANDLER SCM_OBJ(&default_exception_handler_rec)
195 static ScmObj throw_cont_calculate_handlers(ScmObj target, ScmObj current);
196 static ScmObj get_dynamic_handlers(ScmVM*);
197 static void set_dynamic_handlers(ScmVM*, ScmObj);
198 static ScmObj push_dynamic_handlers(ScmVM*, ScmObj, ScmObj, ScmObj);
199 static ScmObj pop_dynamic_handlers(ScmVM*);
200 static void call_dynamic_handlers(ScmVM*, ScmObj target, ScmObj current);
201 static ScmObj throw_cont_body(ScmObj, ScmEscapePoint*, ScmObj);
202 static void process_queued_requests(ScmVM *vm);
203 static void vm_finalize(ScmObj vm, void *data);
204 static int check_arglist_tail_for_apply(ScmVM *vm, ScmObj restargs, int max_count);
205
206 static ScmEnvFrame *get_env(ScmVM *vm);
207 static ScmObj get_inheriting_denv(ScmVM *vm);
208
209 static void call_error_reporter(ScmObj e);
210 static ScmObj call_abort_handler(ScmObj, ScmObj);
211
212 /*#define COUNT_INSN_FREQUENCY*/
213 #ifdef COUNT_INSN_FREQUENCY
214 #include "vmstat.c"
215 #endif /*COUNT_INSN_FREQUENCY*/
216
217 /*
218 * Constructor
219 *
220 * PROTO argument is treated as a prototype for the new VM, i.e.
221 * some of default values are 'inherited' from PROTO.
222 *
223 * VM should be 'attached' to the running OS thread before being
224 * used. The root thread is always attached to the primordial thread
225 * at the initialization stage (see Scm__InitVM()). For other threads,
226 * it depends on whether the thread is created from Gauche side or not.
227 *
228 * If the thread is created from Gauche side (i.e. by Scm_MakeThread()
229 * C API or make-thread Scheme API), attaching is handled automatically
230 * by Gauche.
231 *
232 * If the thread is created by other means, the VM should be attached
233 * to the thread by Scm_AttachVM() API. The VMs attached by this are
234 * somewhat different than the ones attached by Gauche; such VM can't
235 * be passed to thread-join, for example. This type of VM is for
236 * the applications that want to evaluate Gauche program in their own
237 * thread.
238 * NOTE: the thread should still be created by Boehm-GC's pthread_create,
239 * for it is the only way for GC to see the thread's stack.
240 */
241
242 ScmVM *Scm_NewVM(ScmVM *proto, ScmObj name)
243 {
244 ScmVM *v = SCM_NEW(ScmVM);
245
246 SCM_SET_CLASS(v, SCM_CLASS_VM);
247 v->state = SCM_VM_NEW;
248 (void)SCM_INTERNAL_MUTEX_INIT(v->vmlock);
249 (void)SCM_INTERNAL_COND_INIT(v->cond);
250 v->canceller = NULL;
251 v->inspector = NULL;
252 v->name = name;
253 v->specific = SCM_FALSE;
254 v->thunk = NULL;
255 v->result = SCM_UNDEFINED;
256 v->resultException = SCM_UNDEFINED;
257 v->module = proto ? proto->module : Scm_SchemeModule();
258 v->cstack = NULL;
259
260 v->threadLocals = Scm__MakeVMThreadLocalTable(proto);
261
262 v->compilerFlags = proto? proto->compilerFlags : 0;
263 v->runtimeFlags = proto? proto->runtimeFlags : 0;
264 v->attentionRequest = 0;
265 v->signalPending = 0;
266 v->finalizerPending = 0;
267 v->stopRequest = 0;
268
269 #ifdef USE_CUSTOM_STACK_MARKER
270 v->stack = (ScmObj*)GC_generic_malloc((SCM_VM_STACK_SIZE+1)*sizeof(ScmObj),
271 vm_stack_kind);
272 *v->stack++ = SCM_OBJ(v);
273 #else /*!USE_CUSTOM_STACK_MARKER*/
274 v->stack = SCM_NEW_ARRAY(ScmObj, SCM_VM_STACK_SIZE);
275 #endif /*!USE_CUSTOM_STACK_MARKER*/
276 v->sp = v->stack;
277 v->stackBase = v->stack;
278 v->stackEnd = v->stack + SCM_VM_STACK_SIZE;
279 #if GAUCHE_FFX
280 v->fpstack = SCM_NEW_ATOMIC_ARRAY(ScmFlonum, SCM_VM_STACK_SIZE);
281 v->fpstackEnd = v->fpstack + SCM_VM_STACK_SIZE;
282 v->fpsp = v->fpstack;
283 #endif /* GAUCHE_FFX */
284
285 v->env = NULL;
286 v->argp = v->stack;
287 v->cont = NULL;
288 v->pc = PC_TO_RETURN;
289 v->base = NULL;
290 v->val0 = SCM_UNDEFINED;
291 for (int i=0; i<SCM_VM_MAX_VALUES; i++) v->vals[i] = SCM_UNDEFINED;
292 v->numVals = 1;
293 v->trampoline = -1;
294
295 /* Thread inherits dynamic environment.
296 Note: We only need to inherit parameterization. Other dynamic envs
297 (exception handlers, dynamic handlers, etc.) are "reset" when the
298 thread starts, so anything "below" the dynamic handler chain is
299 irrelevant. */
300 v->denv = get_inheriting_denv(proto);
301
302 v->dynamicHandlers = SCM_NIL;
303
304 v->floatingEscapePoints = SCM_NIL;
305 v->escapeReason = SCM_VM_ESCAPE_NONE;
306 v->escapeData[0] = NULL;
307 v->escapeData[1] = NULL;
308 v->errorHandlerContinuable = FALSE;
309 v->customErrorReporter = (proto? proto->customErrorReporter : SCM_FALSE);
310 #if GAUCHE_SPLIT_STACK
311 v->lastErrorCont = NULL;
312 #endif /*GAUCHE_SPLIT_STACK*/
313
314 v->evalSituation = SCM_VM_EXECUTING;
315
316 sigemptyset(&v->sigMask);
317 Scm_SignalQueueInit(&v->sigq);
318
319 /* stats */
320 v->stat.sovCount = 0;
321 v->stat.sovTime = 0;
322 v->stat.loadStat = SCM_NIL;
323 v->profilerRunning = FALSE;
324 v->prof = NULL;
325
326 (void)SCM_INTERNAL_THREAD_INIT(v->thread);
327
328 #if defined(GAUCHE_USE_WTHREADS)
329 v->winCleanup = NULL;
330 #endif /*defined(GAUCHE_USE_WTHREADS)*/
331
332 (void)SCM_INTERNAL_MUTEX_LOCK(vm_id_mutex);
333 v->vmid = vm_numeric_id++;
334 (void)SCM_INTERNAL_MUTEX_UNLOCK(vm_id_mutex);
335
336 v->callTrace = (vm_call_trace_size
337 ? Scm__MakeCallTraceQueue(vm_call_trace_size)
338 : NULL);
339 v->codeCache = NULL;
340
341 v->currentPrompt = NULL;
342 v->resetChain = SCM_NIL;
343
344 Scm_RegisterFinalizer(SCM_OBJ(v), vm_finalize, NULL);
345 return v;
346 }
347
348 /*
349 * Taking a snapshot of VM.
350 * Copying VM is mainly to preserve a snapshot of VM for analysis.
351 * Note that internal states of some system construct (e.g. mutex) aren't
352 * be copied, so it is mainly for diagnostics; do not count on the
353 * copied VM to run independently from the original.
354 */
355
356 ScmVM *Scm_VMTakeSnapshot(ScmVM *master)
357 {
358 ScmVM *v = SCM_NEW(ScmVM);
359
360 SCM_SET_CLASS(v, SCM_CLASS_VM);
361 v->state = master->state;
362 (void)SCM_INTERNAL_MUTEX_INIT(v->vmlock);
363 (void)SCM_INTERNAL_COND_INIT(v->cond);
364 v->canceller = master->canceller;
365 v->inspector = master->inspector;
366 v->name = master->name;
367 v->specific = master->specific;
368 v->thunk = master->thunk;
369 v->result = master->result;
370 v->resultException = master->resultException;
371 v->module = master->module;
372 v->cstack = master->cstack;
373
374 v->threadLocals = Scm__MakeVMThreadLocalTable(master);
375
376 v->compilerFlags = master->compilerFlags;
377 v->runtimeFlags = master->runtimeFlags;
378 v->attentionRequest = master->attentionRequest;
379 v->signalPending = master->signalPending;
380 v->finalizerPending = master->finalizerPending;
381 v->stopRequest = master->stopRequest;
382
383 #ifdef USE_CUSTOM_STACK_MARKER
384 v->stack = (ScmObj*)GC_generic_malloc((SCM_VM_STACK_SIZE+1)*sizeof(ScmObj),
385 vm_stack_kind);
386 *v->stack++ = SCM_OBJ(v);
387 #else /*!USE_CUSTOM_STACK_MARKER*/
388 v->stack = SCM_NEW_ARRAY(ScmObj, SCM_VM_STACK_SIZE);
389 #endif /*!USE_CUSTOM_STACK_MARKER*/
390 v->sp = v->stack;
391 v->stackBase = v->stack;
392 v->stackEnd = v->stack + SCM_VM_STACK_SIZE;
393 memcpy(v->stack, master->stack, SCM_VM_STACK_SIZE*sizeof(ScmObj));
394
395 #if GAUCHE_FFX
396 v->fpstack = SCM_NEW_ATOMIC_ARRAY(ScmFlonum, SCM_VM_STACK_SIZE);
397 v->fpstackEnd = v->fpstack + SCM_VM_STACK_SIZE;
398 v->fpsp = v->fpstack;
399 memcpy(v->fpstack, master->fpstack, SCM_VM_STACK_SIZE*sizeof(ScmFlonum));
400 #endif /* GAUCHE_FFX */
401
402 v->env = master->env;
403 v->argp = master->argp;
404 v->cont = master->cont;
405 v->pc = master->pc;
406 v->base = master->base;
407 v->val0 = master->val0;
408 for (int i=0; i<SCM_VM_MAX_VALUES; i++) v->vals[i] = master->vals[i];
409 v->numVals = master->numVals;
410 v->trampoline = master->trampoline;
411 v->denv = master->denv;
412 v->dynamicHandlers = master->dynamicHandlers;
413
414 v->floatingEscapePoints = master->floatingEscapePoints;
415 v->escapeReason = master->escapeReason;
416 v->escapeData[0] = master->escapeData[0];
417 v->escapeData[1] = master->escapeData[1];
418 v->errorHandlerContinuable = master->errorHandlerContinuable;
419 v->customErrorReporter = master->customErrorReporter;
420 #if GAUCHE_SPLIT_STACK
421 v->lastErrorCont = master->lastErrorCont;
422 #endif /*GAUCHE_SPLIT_STACK*/
423
424 v->evalSituation = master->evalSituation;
425
426 sigemptyset(&v->sigMask);
427 Scm_SignalQueueInit(&v->sigq); /* TODO: Copy signal queue content */
428
429 /* stats */
430 v->stat.sovCount = master->stat.sovCount;
431 v->stat.sovTime = master->stat.sovTime;
432 v->stat.loadStat = master->stat.loadStat;
433 v->profilerRunning = master->profilerRunning;
434 v->prof = master->prof; /* TODO: Should we copy this? */
435
436 v->thread = master->thread;
437
438 #if defined(GAUCHE_USE_WTHREADS)
439 v->winCleanup = master->winCleanup;
440 #endif /*defined(GAUCHE_USE_WTHREADS)*/
441
442 v->vmid = master->vmid;
443 v->callTrace = (master->callTrace
444 ? Scm__CopyCallTraceQueue(master->callTrace)
445 : NULL);
446 v->codeCache = NULL; /* We might need to copy this as well
447 if we want to debug JIT code cache */
448
449 v->currentPrompt = master->currentPrompt;
450 v->resetChain = master->resetChain;
451 /* NB: We don't register the finalizer vm_finalize to the snapshot,
452 for we do not want the associated system resources to be cleaned
453 up when the snapshot is GCed. */
454 return v;
455 }
456
457 /* Attach the thread to the current thread.
458 See the notes of Scm_NewVM above.
459 Returns TRUE on success, FALSE on failure. */
460 int Scm_AttachVM(ScmVM *vm)
461 {
462 if (theVM != NULL) {
463 /* The current thread already has another VM attached. */
464 return FALSE;
465 }
466 /* NB: We want to check if this VM has already attached to another
467 thread or not. */
468
469 if (!SCM_INTERNAL_THREAD_SETSPECIFIC(Scm_VMKey(), vm)) return FALSE;
470
471 if (!SCM_INTERNAL_THREAD_INITIALIZED_P(vm->thread)) {
472 #ifdef GAUCHE_USE_WTHREADS
473 /* GetCurrentThread() on Windows returns a pseudo handle
474 indicating 'myself', which can't be usable from other thread.
475 We need a special care. The resulting HANDLE should be closed,
476 which is done in the finalizer. */
477 HANDLE t;
478 BOOL r = DuplicateHandle(GetCurrentProcess(), /* source process */
479 GetCurrentThread(), /* source handle */
480 GetCurrentProcess(), /* target process */
481 &t,
482 0, FALSE, DUPLICATE_SAME_ACCESS);
483 if (!r) {
484 Scm_SysError("Getting current thread handle failed");
485 }
486 vm->thread = t;
487 #else /* GAUCHE_USE_PTHREADS */
488 vm->thread = SCM_INTERNAL_THREAD_GETCURRENT();
489 #endif /* GAUCHE_USE_PTHREADS */
490 }
491 vm->state = SCM_VM_RUNNABLE;
492 vm_register(vm);
493 return TRUE;
494 }
495
496 /* If the current VM is attached by Scm_AttachVM() rather than Scheme
497 creating a thread, this needs to be called once you've done with the
498 VM (typically just before the thread terminates).
499 */
500 void Scm_DetachVM(ScmVM *vm)
501 {
502 if (vm != NULL) {
503 (void)SCM_INTERNAL_THREAD_SETSPECIFIC(Scm_VMKey(), NULL);
504 vm_unregister(vm);
505 }
506 }
507
508 int Scm_VMGetNumResults(ScmVM *vm)
509 {
510 return vm->numVals;
511 }
512
513 ScmObj Scm_VMGetResult(ScmVM *vm)
514 {
515 ScmObj head = SCM_NIL, tail = SCM_NIL;
516 if (vm->numVals == 0) return SCM_NIL;
517 SCM_APPEND1(head, tail, vm->val0);
518 for (int i=1; i<vm->numVals; i++) {
519 SCM_APPEND1(head, tail, vm->vals[i-1]);
520 }
521 return head;
522 }
523
524 void Scm_VMSetResult(ScmObj obj)
525 {
526 ScmVM *vm = theVM;
527 vm->val0 = obj;
528 vm->numVals = 1;
529 }
530
531 /*
532 * Current VM.
533 */
534 ScmVM *Scm_VM(void)
535 {
536 return theVM;
537 }
538
539 /* Some macros inserts Scm_VM() in its output. If such macros are expanded
540 below, we can safely replace Scm_VM() to theVM. */
541 #define Scm_VM() theVM
542
543 /*
544 * Get VM key
545 */
546 #if defined(GAUCHE_USE_PTHREADS)
547 pthread_key_t Scm_VMKey(void)
548 {
549 return vm_key;
550 }
551 #elif defined(GAUCHE_USE_WTHREADS)
552 DWORD Scm_VMKey(void)
553 {
554 return vm_key;
555 }
556 #endif /*GAUCHE_USE_WTHREADS*/
557
558 /* Warn if VM is terminated by uncaught exception, and GC-ed without
559 joining. It is clearly an unexpected case and worth reporting. */
560 static void vm_finalize(ScmObj obj, void *data SCM_UNUSED)
561 {
562 ScmVM *vm = SCM_VM(obj);
563 ScmObj re = vm->resultException;
564
565 if (SCM_UNCAUGHT_EXCEPTION_P(re)) {
566 Scm_Warn("A thread %S (%lu) died a lonely death"
567 " with an uncaught exception %S.",
568 vm->name, vm->vmid, SCM_THREAD_EXCEPTION(re)->data);
569 }
570 #ifdef GAUCHE_USE_WTHREADS
571 if (vm->thread != INVALID_HANDLE_VALUE) {
572 CloseHandle(vm->thread);
573 vm->thread = INVALID_HANDLE_VALUE;
574 }
575 #endif /*GAUCHE_USE_WTHREADS*/
576 }
577
578 /* Thread specific storage may not be scanned by GC. We keep pointers
579 to the live VMs in the global hashtable. */
580 static void vm_register(ScmVM *vm)
581 {
582 SCM_INTERNAL_MUTEX_LOCK(vm_table_mutex);
583 ScmDictEntry *e = Scm_HashCoreSearch(&vm_table, (intptr_t)vm,
584 SCM_DICT_CREATE);
585 (void)SCM_DICT_SET_VALUE(e, SCM_TRUE);
586 SCM_INTERNAL_MUTEX_UNLOCK(vm_table_mutex);
587 }
588
589 static void vm_unregister(ScmVM *vm)
590 {
591 SCM_INTERNAL_MUTEX_LOCK(vm_table_mutex);
592 (void)Scm_HashCoreSearch(&vm_table, (intptr_t)vm, SCM_DICT_DELETE);
593 SCM_INTERNAL_MUTEX_UNLOCK(vm_table_mutex);
594 }
595
596 /*====================================================================
597 * VM interpreter
598 *
599 * Interprets intermediate code CODE on VM.
600 */
601
602 /*
603 * Micro-operations
604 */
605
606 /* fetching */
607 #define INCR_PC (PC++)
608 #define FETCH_LOCATION(var) ((var) = (ScmWord*)*PC)
609 #define FETCH_OPERAND(var) ((var) = SCM_OBJ(*PC))
610 #define FETCH_OPERAND_PUSH (*SP++ = SCM_OBJ(*PC))
611
612 #ifndef COUNT_INSN_FREQUENCY
613 #define FETCH_INSN(var) ((var) = *PC++)
614 #else
615 #define FETCH_INSN(var) ((var) = fetch_insn_counting(vm, var))
616 #endif
617
618 /* For sanity check in debugging mode */
619 #ifdef PARANOIA
620 #define CHECK_STACK_PARANOIA(n) CHECK_STACK(n)
621 #else
622 #define CHECK_STACK_PARANOIA(n) (void)(n) /*dummy - avoid unused var warning*/
623 #endif
624
625 /* Hint for gcc -- at this moment, using __builtin_expect doesn't
626 do any good (except for SCM_PROF_COUNT_CALL). I'll try this
627 later on. */
628 #if 1
629 #define MOSTLY_FALSE(expr) __builtin_expect(expr, 0)
630 #else
631 #define MOSTLY_FALSE(expr) expr
632 #endif
633
634 /* Find the stack bottom next to the continuation frame.
635 This macro should be applied only if CONT is in stack. */
636 #define CONT_FRAME_END(cont) ((ScmObj*)(cont) + CONT_FRAME_SIZE)
637
638 /* check if *pc is an return instruction. if so, some
639 shortcuts are taken. */
640 #define TAIL_POS() (*PC == SCM_VM_INSN(SCM_VM_RET))
641
642 /* push OBJ to the top of the stack
643 The evaluation of OBJ may require to refer SP, so we can't
644 just say *SP++ = (obj). */
645 #define PUSH_ARG(obj) (*SP = (obj), SP++)
646
647 /* pop the top object of the stack and store it to VAR */
648 #define POP_ARG(var) ((var) = *--SP)
649
650 #define SHIFT_FRAME(from, to, size) \
651 do { \
652 ScmObj *f = (from), *t = (to); \
653 int c; \
654 for (c=0; c<(size); c++, f++, t++) *t = *f; \
655 } while (0)
656
657 /* VM registers. We benchmarked if keeping some of those registers
658 in local variables makes VM loop run faster; however, it turned out
659 that more local variables tended to make them spill from machine
660 registers and didn't improve performance. Having only 'vm', a pointer
661 to the current VM, on register is enough. */
662 #define PC (vm->pc)
663 #define SP (vm->sp)
664 #define VAL0 (vm->val0)
665 #define ENV (vm->env)
666 #define DENV (vm->denv)
667 #define CONT (vm->cont)
668 #define ARGP (vm->argp)
669 #define BASE (vm->base)
670
671 /* IN_STACK_P(ptr) returns true if ptr points into the active stack area.
672 IN_FULL_STACK_P(ptr) returns true if ptr points into any part of the stack.
673 */
674
675 #if GAUCHE_SPLIT_STACK
676 #define IN_STACK_P(ptr) \
677 ((ptr) >= vm->stackBase && (ptr) < vm->stackEnd)
678 #define IN_FULL_STACK_P(ptr) \
679 ((ptr) >= vm->stack && (ptr) < vm->stackEnd)
680 #else /*!GAUCHE_SPLIT_STACK*/
681 #define IN_STACK_P(ptr) \
682 ((unsigned long)((ptr) - vm->stack) < SCM_VM_STACK_SIZE)
683 #define IN_FULL_STACK_P(ptr) IN_STACK_P(ptr)
684 #endif /*!GAUCHE_SPLIT_STACK*/
685
686 /* Check if stack has room at least SIZE words. If not, active frames
687 are moved to the heap to make room. */
688 #define CHECK_STACK(size) \
689 do { \
690 if (MOSTLY_FALSE(SP >= vm->stackEnd - (size))) { \
691 save_stack(vm); \
692 } \
693 } while (0)
694
695 /* Push a continuation frame. next_pc is the PC from where execution
696 will be resumed. */
697 #define PUSH_CONT(next_pc) \
698 do { \
699 ScmContFrame *newcont = (ScmContFrame*)SP; \
700 newcont->prev = CONT; \
701 newcont->env = ENV; \
702 newcont->denv = DENV; \
703 newcont->size = (int)(SP - ARGP); \
704 newcont->marker = 0; \
705 newcont->cpc = PC; \
706 newcont->pc = next_pc; \
707 newcont->base = BASE; \
708 CONT = newcont; \
709 SP += CONT_FRAME_SIZE; \
710 ARGP = SP; \
711 } while (0)
712
713 /* pop a continuation frame, i.e. return from a procedure. */
714 #define POP_CONT() \
715 do { \
716 if (C_CONTINUATION_P(CONT)) { \
717 ScmContFrame *cont = CONT; \
718 ScmObj v = VAL0; \
719 if (IN_STACK_P((ScmObj*)cont)) { \
720 SP = (ScmObj*)cont - cont->size; \
721 } \
722 ENV = NULL; \
723 DENV = cont->denv; \
724 ARGP = SP; \
725 PC = PC_TO_RETURN; \
726 BASE = cont->base; \
727 CONT = cont->prev; \
728 vm->ccont = cont->cpc; \
729 SCM_FLONUM_ENSURE_MEM(v); \
730 vm->trampoline = -1; \
731 ScmPContinuationProc *cproc = (ScmPContinuationProc*)cont->pc; \
732 ScmObj *data = (ScmObj*)cont - cont->size; \
733 VAL0 = cproc(vm, v, data); \
734 for (int argc = vm->trampoline; argc >= 0; argc = vm->trampoline) { \
735 vm->trampoline = -1; \
736 VAL0 = SCM_SUBR(VAL0)->func(ARGP, argc, SCM_SUBR(VAL0)->data); \
737 } \
738 } else if (IN_STACK_P((ScmObj*)CONT)) { \
739 SP = (ScmObj*)CONT; \
740 ENV = CONT->env; \
741 DENV = CONT->denv; \
742 ARGP = SP - CONT->size; \
743 PC = CONT->pc; \
744 BASE = CONT->base; \
745 CONT = CONT->prev; \
746 } else { \
747 int size__ = CONT->size; \
748 ARGP = SP = vm->stackBase; \
749 ENV = CONT->env; \
750 DENV = CONT->denv; \
751 PC = CONT->pc; \
752 BASE = CONT->base; \
753 if (size__) { \
754 ScmObj *s__ = (ScmObj*)CONT - size__; \
755 ScmObj *d__ = SP; \
756 while (s__ < (ScmObj*)CONT) { \
757 *d__++ = *s__++; \
758 } \
759 SP = d__; \
760 } \
761 CONT = CONT->prev; \
762 } \
763 } while (0)
764
765 /* return operation. */
766 #define RETURN_OP() \
767 do { \
768 if (CONT == NULL || BOUNDARY_FRAME_P(CONT)) { \
769 return; /* no more continuations */ \
770 } else if (MARKER_FRAME_P(CONT)) { \
771 POP_CONT(); \
772 /* the end of partial continuation */ \
773 vm->cont = NULL; \
774 } else { \
775 POP_CONT(); \
776 } \
777 } while (0)
778
779 /* push environment header to finish the environment frame.
780 env, sp, argp is updated. */
781 #define FINISH_ENV(info_, up_) \
782 do { \
783 ScmEnvFrame *e__ = (ScmEnvFrame*)SP; \
784 e__->up = up_; \
785 e__->info = info_; \
786 e__->size = SP - ARGP; \
787 SP += ENV_HDR_SIZE; \
788 ARGP = SP; \
789 ENV = e__; \
790 } while (0)
791
792 /* extend the current environment by SIZE words. used for LET. */
793 #define PUSH_LOCAL_ENV(size_, info_) \
794 do { \
795 int i__; \
796 for (i__=0; i__<size_; i__++) { \
797 *SP++ = SCM_UNDEFINED; \
798 } \
799 FINISH_ENV(info_, ENV); \
800 } while (0)
801
802 /* used for the inlined instruction which is supposed to be called at
803 tail position (e.g. SLOT-REF). This checks whether we're at the tail
804 position or not, and if not, push a cont frame to make the operation
805 a tail call. */
806 #define TAIL_CALL_INSTRUCTION() \
807 do { \
808 if (!TAIL_POS()) { \
809 CHECK_STACK(CONT_FRAME_SIZE); \
810 PUSH_CONT(PC); \
811 PC = PC_TO_RETURN; \
812 } \
813 } while (0)
814
815 /* global reference. this piece of code is used for a few GREF-something
816 combined instruction.
817 NB: Unbound variable situation is detected and an error is thrown
818 in Scm_GlocGetValue or Scm_IdentifierGlobalRef.
819 */
820 #define GLOBAL_REF(v) \
821 do { \
822 ScmGloc *gloc; \
823 FETCH_OPERAND(v); \
824 if (!SCM_GLOCP(v)) { \
825 VM_ASSERT(SCM_IDENTIFIERP(v)); \
826 v = Scm_IdentifierGlobalRef(SCM_IDENTIFIER(v), &gloc); \
827 /* memorize gloc */ \
828 *PC = SCM_WORD(gloc); \
829 } else { \
830 v = Scm_GlocGetValue(SCM_GLOC(v)); \
831 } \
832 if (SCM_AUTOLOADP(v)) { \
833 v = Scm_ResolveAutoload(SCM_AUTOLOAD(v), 0); \
834 } \
835 INCR_PC; \
836 } while (0)
837
838 /* for debug */
839 #define VM_DUMP(delimiter) \
840 fprintf(stderr, delimiter); \
841 Scm_VMDump(vm)
842
843 #define VM_ASSERT(expr) \
844 do { \
845 if (!(expr)) { \
846 fprintf(stderr, "\"%s\", line %d: Assertion failed: %s\n", \
847 __FILE__, __LINE__, #expr); \
848 Scm_VMDump(theVM); \
849 Scm_Panic("exiting...\n"); \
850 } \
851 } while (0)
852
853 #define VM_ERR(errargs) \
854 do { \
855 Scm_Error errargs; \
856 } while (0)
857
858 /* Discard the current procedure's local frame before performing a tail call.
859 Just before the tail call, the typical stack position is like this:
860
861 SP >| |
862 | argN |
863 | : |
864 ARGP>| arg0 |
865 | env |
866 ENV >| env |
867 |localM|
868 | : |
869 |local0|
870 CONT>| cont |
871
872 Arg0...argN is the arguments for the call, and local0...localM is the
873 environment of the current procedure, which is no longer needed.
874 We shift arg0...argN to just above the continuation frame.
875
876 If the continuation frame has been saved (i.e. CONT is not pointing
877 the stack area), then we know for sure that there's no valid data
878 from the stack bottom to ARGP. So we shift arg0...argN to the
879 beginning of the stack. We set ENV = NULL afterwards to prevent
880 the debugging process from being confused---at the end of the procedure
881 calling sequence, ENV is set to point to the newly formed environment
882 frame out of arg0...argN.
883
884 MEMO: this shifting used to be done after folding &rest arguments.
885 Benchmark showed shifting first is slightly faster.
886 */
887 #define DISCARD_ENV() \
888 do { \
889 ScmObj *to; \
890 int argc = (int)(SP - ARGP); \
891 if (IN_STACK_P((ScmObj*)CONT)) { \
892 to = CONT_FRAME_END(CONT); \
893 } else { \
894 to = vm->stackBase; \
895 } \
896 if (argc) { \
897 ScmObj *t = to, *a = ARGP; \
898 int c; \
899 for (c=0; c<argc; c++) *t++ = *a++; \
900 } \
901 ARGP = to; \
902 SP = to + argc; \
903 ENV = NULL; \
904 } while (0)
905
906
907 /* inline expansion of number comparison. */
908 #define NUM_CMP(op, r) \
909 do { \
910 ScmObj x_, y_ = VAL0; \
911 POP_ARG(x_); \
912 if (SCM_INTP(y_) && SCM_INTP(x_)) { \
913 r = ((signed long)(intptr_t)x_ op (signed long)(intptr_t)y_); \
914 } else if (SCM_FLONUMP(y_) && SCM_FLONUMP(x_)) { \
915 r = (SCM_FLONUM_VALUE(x_) op SCM_FLONUM_VALUE(y_)); \
916 } else { \
917 r = (Scm_NumCmp(x_, y_) op 0); \
918 } \
919 } while (0)
920
921 #define NUM_CCMP(op, r) \
922 do { \
923 ScmObj x_, y_ = VAL0; \
924 FETCH_OPERAND(x_); \
925 r = (SCM_FLONUM_VALUE(x_) op Scm_GetDouble(y_)); \
926 } while (0)
927
928 /* We take advantage of GCC's `computed goto' feature
929 (see gcc.info, "Labels as Values").
930 'NEXT' or 'NEXT_PUSHCHECK' is placed at the end of most
931 vm insn handlers to dispatch to the next instruction.
932 We don't simply jump to the beginning of the dispatch
933 table (hence the dispatching is handled by SWITCH macro),
934 since the former performs worse in branch prediction;
935 at least, if we have dispatches at the end of every handler,
936 we can hope the branch predictor detect frequently used
937 vm insn sequence. 'NEXT_PUSHCHECK' further reduces branch
938 predictor failure - quite a few insns that yield a value
939 in VAL0 is followed by PUSH instruction, so we detect it
940 specially. We still use fused insns (e.g. LREF0-PUSH) when
941 the combination is very frequent - but for the less frequent
942 instructions, NEXT_PUSHCHECK proved effective without introducing
943 new fused vm insns.
944 */
945 #ifdef __GNUC__
946 #define SWITCH(val) goto *dispatch_table[val];
947 #define CASE(insn) SCM_CPP_CAT(LABEL_, insn) :
948 #define DEFAULT LABEL_DEFAULT :
949 #define DISPATCH /*empty*/
950 #define NEXT \
951 do { \
952 FETCH_INSN(code); \
953 goto *dispatch_table[SCM_VM_INSN_CODE(code)]; \
954 } while (0)
955 #define NEXT_PUSHCHECK \
956 do { \
957 FETCH_INSN(code); \
958 if (code == SCM_VM_PUSH) { \
959 PUSH_ARG(VAL0); \
960 FETCH_INSN(code); \
961 } \
962 goto *dispatch_table[SCM_VM_INSN_CODE(code)]; \
963 } while (0)
964 #else /* !__GNUC__ */
965 #define SWITCH(val) switch (val)
966 #define CASE(insn) case insn :
967 #define DISPATCH dispatch:
968 #define NEXT goto dispatch
969 #define NEXT_PUSHCHECK goto dispatch
970 #endif
971
972 /* Check VM interrupt request. */
973 #define CHECK_INTR \
974 do { if (vm->attentionRequest) goto process_queue; } while (0)
975
976 /* WNA - "Wrong Number of Arguments" handler. The actual call is in vmcall.c.
977 We handle the autocurrying magic here.
978
979 PROC is the procedure object (guaranteed).
980 NGIVEN is # of actual args on the VM stack. The last several args may
981 be folded in a list in APPLY_CALL context. FOLDLEN holds the number of
982 folded args. In normal call context, FOLDLEN is -1.
983
984 If the proc is curried, the VM stack state is ready to execute next op.
985 Otherwise thie procedure won't return.
986 */
987
988 static void wna(ScmVM *vm SCM_UNUSED,
989 ScmObj proc,
990 int ngiven,
991 int foldlen SCM_UNUSED)
992 {
993 int reqargs = SCM_PROCEDURE_REQUIRED(proc);
994 #if 0
995 /* Disabled for now. See proc.c (Scm_CurryProcedure) for the details. */
996 if (SCM_PROCEDURE_CURRYING(proc) && ngiven < reqargs && ngiven > 0) {
997 VAL0 = Scm_CurryProcedure(proc, ARGP, ngiven, foldlen);
998 /*TODO: how should we count this path for profiling? */
999 } else {
1000 Scm_Error("wrong number of arguments for %S (required %d, got %d)",
1001
1002 proc, reqargs, ngiven);
1003 /*NOTREACHED*/
1004 }
1005 #else
1006 Scm_Error("wrong number of arguments for %S (required %d, got %d)",
1007 proc, reqargs, ngiven);
1008 #endif
1009 }
1010
1011 /* local_env_shift
1012 Called from LOCAL-ENV-SHIFT and LOCAL-ENV-JUMP insns (see vminsn.scm),
1013 and adjusts env frames for optimized local function call.
1014 This routine does two things
1015 - Creates a new local env frame from the values in the current stack.
1016 The size of frame can be determined by SP-ARGP.
1017 - Discard DEPTH env frames.
1018 */
1019 static void local_env_shift(ScmVM *vm, int env_depth)
1020 {
1021 int nargs = (int)(SP - ARGP);
1022 ScmEnvFrame *tenv = ENV;
1023 /* We can discard env_depth environment frames.
1024 There are several cases:
1025 - if the target env frame (TENV) is in stack:
1026 -- if the current cont frame is over TENV
1027 => shift argframe on top of the current cont frame
1028 -- otherwise => shift argframe on top of TENV
1029 - if TENV is in heap:
1030 -- if the current cont frame is in stack
1031 => shift argframe on top of the current cont frame
1032 -- otherwise => shift argframe at the stack base
1033 */
1034 while (env_depth-- > 0) {
1035 SCM_ASSERT(tenv);
1036 tenv = tenv->up;
1037 }
1038
1039 ScmObj *to;
1040 if (IN_STACK_P((ScmObj*)tenv)) {
1041 if (IN_STACK_P((ScmObj*)CONT) && (((ScmObj*)CONT) > ((ScmObj*)tenv))) {
1042 to = CONT_FRAME_END(CONT);
1043 } else {
1044 to = ((ScmObj*)tenv) + ENV_HDR_SIZE;
1045 }
1046 } else {
1047 if (IN_STACK_P((ScmObj*)CONT)) {
1048 to = CONT_FRAME_END(CONT);
1049 } else {
1050 to = vm->stackBase; /* continuation has already been saved */
1051 }
1052 }
1053 if (nargs > 0 && to != ARGP) {
1054 ScmObj *t = to;
1055 ScmObj *a = ARGP;
1056 for (int c = 0; c < nargs; c++) {
1057 *t++ = *a++;
1058 }
1059 }
1060 ARGP = to;
1061 SP = to + nargs;
1062 if (nargs > 0) { FINISH_ENV(SCM_FALSE, tenv); }
1063 else { ENV = tenv; }
1064 }
1065
1066
1067 /*===================================================================
1068 * Main loop of VM
1069 */
1070 static void run_loop()
1071 {
1072 ScmVM *vm = theVM;
1073 ScmWord code = 0;
1074
1075 #ifdef __GNUC__
1076 static void *dispatch_table[256] = {
1077 #define DEFINSN(insn, name, nargs, type, flags) && SCM_CPP_CAT(LABEL_, insn),
1078 #include "vminsn.c"
1079 #undef DEFINSN
1080 };
1081 #endif /* __GNUC__ */
1082
1083 /* Records the offset of each instruction handler from run_loop entry
1084 address. They can be retrieved by gauche.internal#%vm-get-insn-offsets.
1085 Useful for tuning if used with machine instruction-level profiler. */
1086 if (vminsn_offsets[0] == 0) {
1087 /* No need to lock, for this is only executed when run_loop runs for
1088 the first time, which is in Scm_Init(). */
1089 for (int i=0; i<SCM_VM_NUM_INSNS; i++) {
1090 vminsn_offsets[i] =
1091 (unsigned long)((char*)dispatch_table[i] - (char*)run_loop);
1092 }
1093 }
1094
1095 for (;;) {
1096 DISPATCH;
1097 /*VM_DUMP("");*/
1098 if (vm->attentionRequest) goto process_queue;
1099 FETCH_INSN(code);
1100 SWITCH(SCM_VM_INSN_CODE(code)) {
1101 #define VMLOOP
1102 #include "vminsn.c"
1103 #undef VMLOOP
1104 #ifndef __GNUC__
1105 default:
1106 Scm_Panic("Illegal vm instruction: %08x",
1107 SCM_VM_INSN_CODE(code));
1108 #endif
1109 }
1110 process_queue:
1111 CHECK_STACK(CONT_FRAME_SIZE);
1112 PUSH_CONT(PC);
1113 process_queued_requests(vm);
1114 POP_CONT();
1115 NEXT;
1116 }
1117 }
1118 /* End of run_loop */
1119
1120 /*==================================================================
1121 * Stack management
1122 */
1123
1124 /* We have 'forwarding pointer' for env and cont frames being moved.
1125 Forwarding pointers are resolved within these internal routines
1126 and should never leak out.
1127
1128 Forwarded pointer is marked by the 'size' field be set -1.
1129 Env->up or Cont->prev field holds the relocated frame.
1130
1131 Invariance: forwarded pointer only appear in stack. We skip some
1132 IN_STACK_P check because of it. */
1133
1134 #define FORWARDED_ENV_P(e) ((e)&&((e)->size == -1))
1135 #define FORWARDED_ENV(e) ((e)->up)
1136
1137 #define FORWARDED_CONT_P(c) ((c)&&((c)->size == -1))
1138 #define FORWARDED_CONT(c) ((c)->prev)
1139
1140 /* Performance note: As of 0.8.4_pre1, each get_env call spends about
1141 1us to 4us on P4 2GHz machine with several benchmark suites. The
1142 average env frames to be saved is less than 3. The ratio of the pass1
1143 (env frame save) and the pass 2 (cont pointer adjustment) is somewhere
1144 around 2:1 to 1:2. Inlining SCM_NEW call didn't help.
1145
1146 This is a considerable amount of time, since save_env may be called
1147 the order of 10^6 times. I'm not sure I can optimize this routine
1148 further without a radical change in stack management code.
1149
1150 Better strategy is to put an effort in the compiler to avoid closure
1151 creation as much as possible. */
1152
1153 /* Move the chain of env frames from the stack to the heap,
1154 replacing the in-stack frames for forwarding env frames.
1155
1156 This routine just moves the env frames, but leaves pointers that
1157 point to moved frames intact (such pointers are found only in
1158 the in-stack contniuation frames, chained from vm->cont).
1159 It's the caller's responsibility to update those pointers.
1160
1161 The env frames below the stackBase is also moved, to keep the invariance
1162 that heap would never contain a pointer into the stack.
1163 */
1164 static inline ScmEnvFrame *save_env(ScmVM *vm, ScmEnvFrame *env_begin)
1165 {
1166 ScmEnvFrame *e = env_begin, *prev = NULL, *next, *head = NULL, *saved;
1167
1168 if (!IN_FULL_STACK_P((ScmObj*)e)) return e;
1169
1170 do {
1171 long esize = (long)e->size;
1172 if (esize < 0) {
1173 /* forwaded frame */
1174 if (prev) prev->up = FORWARDED_ENV(e);
1175 return head;
1176 }
1177
1178 ScmObj *d = SCM_NEW2(ScmObj*, ENV_SIZE(esize) * sizeof(ScmObj));
1179 ScmObj *s = (ScmObj*)e - esize;
1180 for (long i=esize; i>0; i--) {
1181 SCM_FLONUM_ENSURE_MEM(*s);
1182 *d++ = *s++;
1183 }
1184 *(ScmEnvFrame*)d = *e; /* copy env header */
1185 saved = (ScmEnvFrame*)d;
1186 if (prev) prev->up = saved;
1187 if (head == NULL) head = saved;
1188 next = e->up;
1189 e->up = prev = saved; /* forwarding pointer */
1190 e->size = -1; /* indicates forwarded */
1191 e->info = SCM_FALSE;
1192 e = next;
1193 } while (IN_FULL_STACK_P((ScmObj*)e));
1194 return head;
1195 }
1196
1197 static void save_cont_1(ScmVM *vm, ScmContFrame *c)
1198 {
1199 if (!IN_FULL_STACK_P((ScmObj*)c)) return;
1200
1201 ScmContFrame *prev = NULL;
1202
1203 /* First pass */
1204 do {
1205 int size = (CONT_FRAME_SIZE + c->size) * sizeof(ScmObj);
1206 ScmObj *heap = SCM_NEW2(ScmObj*, size);
1207 ScmContFrame *csave = (ScmContFrame*)(heap + c->size);
1208
1209 /* update env ptr if necessary */
1210 if (FORWARDED_ENV_P(c->env)) {
1211 c->env = FORWARDED_ENV(c->env);
1212 } else if (IN_FULL_STACK_P((ScmObj*)c->env)) {
1213 c->env = save_env(vm, c->env);
1214 }
1215
1216 /* copy cont frame */
1217 if (!C_CONTINUATION_P(c)) {
1218 ScmObj *s = (ScmObj*)c - c->size;
1219 ScmObj *d = heap;
1220 if (c->size) {
1221 for (int i=c->size; i>0; i--) {
1222 SCM_FLONUM_ENSURE_MEM(*s);
1223 *d++ = *s++;
1224 }
1225 }
1226 *(ScmContFrame*)d = *c; /* copy the frame */
1227 } else {
1228 /* C continuation */
1229 ScmObj *s = (ScmObj*)c - c->size;
1230 ScmObj *d = heap;
1231 for (int i=CONT_FRAME_SIZE + c->size; i>0; i--) {
1232 /* NB: C continuation frame contains opaque pointer,
1233 so we shouldn't ENSURE_MEM. */
1234 *d++ = *s++;
1235 }
1236 }
1237
1238 /* for boundary frame, we also need to copy promptdata */
1239 if (BOUNDARY_FRAME_P(c)) {
1240 ScmPromptData *psrc = (ScmPromptData*)c->cpc;
1241 ScmPromptData *psave = SCM_NEW(ScmPromptData);
1242 *psave = *psrc;
1243 csave->cpc = &psave->dummy;
1244 }
1245
1246 /* make the orig frame forwarded */
1247 if (prev) prev->prev = csave;
1248 prev = csave;
1249
1250 ScmContFrame *tmp = c->prev;
1251 c->prev = csave;
1252 c->size = -1;
1253 c = tmp;
1254 } while (IN_FULL_STACK_P((ScmObj*)c));
1255 }
1256
1257
1258 /* Copy the continuation frames to the heap.
1259 We run two passes, first replacing cont frames with the forwarding
1260 cont frames, then updates the pointers to them.
1261 After save_cont, the only thing possibly left in the stack is the argument
1262 frame pointed by vm->argp.
1263 */
1264 static void save_cont(ScmVM *vm)
1265 {
1266 /* Save the environment chain first. */
1267 vm->env = save_env(vm, vm->env);
1268
1269 /* First pass */
1270 save_cont_1(vm, vm->cont);
1271 #if GAUCHE_SPLIT_STACK
1272 save_cont_1(vm, vm->lastErrorCont);
1273 #endif /*GAUCHE_SPLIT_STACK*/
1274
1275 /* Second pass */
1276 if (FORWARDED_CONT_P(vm->cont)) {
1277 vm->cont = FORWARDED_CONT(vm->cont);
1278 }
1279 #if GAUCHE_SPLIT_STACK
1280 if (FORWARDED_CONT_P(vm->lastErrorCont)) {
1281 vm->lastErrorCont = FORWARDED_CONT(vm->lastErrorCont);
1282 }
1283 #endif /*GAUCHE_SPLIT_STACK*/
1284 for (ScmCStack *cstk = vm->cstack; cstk; cstk = cstk->prev) {
1285 if (FORWARDED_CONT_P(cstk->cont)) {
1286 cstk->cont = FORWARDED_CONT(cstk->cont);
1287 }
1288 }
1289 {
1290 ScmObj eps;
1291 SCM_FOR_EACH(eps, vm->floatingEscapePoints) {
1292 ScmObj ep = SCM_CAR(eps);
1293 SCM_ASSERT(SCM_ESCAPE_POINT_P(ep));
1294 ScmEscapePoint *e = SCM_ESCAPE_POINT(ep);
1295 if (FORWARDED_CONT_P(e->cont)) {
1296 e->cont = FORWARDED_CONT(e->cont);
1297 }
1298 }
1299 vm->floatingEscapePoints = SCM_NIL;
1300 }
1301 }
1302
1303 static void save_stack(ScmVM *vm)
1304 {
1305 #if HAVE_GETTIMEOFDAY
1306 int stats = SCM_VM_RUNTIME_FLAG_IS_SET(vm, SCM_COLLECT_VM_STATS);
1307 struct timeval t0, t1;
1308
1309 if (stats) {
1310 gettimeofday(&t0, NULL);
1311 }
1312 #endif
1313
1314 save_cont(vm);
1315 memmove(vm->stackBase, vm->argp,
1316 (vm->sp - (ScmObj*)vm->argp) * sizeof(ScmObj*));
1317 vm->sp -= (ScmObj*)vm->argp - vm->stackBase;
1318 vm->argp = vm->stackBase;
1319 /* Clear the stack. This removes bogus pointers and accelerates GC */
1320 for (ScmObj *p = vm->sp; p < vm->stackEnd; p++) *p = NULL;
1321
1322 #if HAVE_GETTIMEOFDAY
1323 if (stats) {
1324 gettimeofday(&t1, NULL);
1325 vm->stat.sovCount++;
1326 vm->stat.sovTime +=
1327 (t1.tv_sec - t0.tv_sec)*1000000+(t1.tv_usec - t0.tv_usec);
1328 }
1329 #endif
1330 }
1331
1332 static ScmEnvFrame *get_env(ScmVM *vm)
1333 {
1334 ScmEnvFrame *e = save_env(vm, vm->env);
1335 if (e != vm->env) {
1336 vm->env = e;
1337 for (ScmContFrame *c = vm->cont; IN_FULL_STACK_P((ScmObj*)c); c = c->prev) {
1338 if (FORWARDED_ENV_P(c->env)) {
1339 c->env = FORWARDED_ENV(c->env);
1340 }
1341 }
1342 }
1343 return e;
1344 }
1345
1346 /* Returns an denv to be inherited from the calling thread.
1347 * Note that we only need parameterizations. Other dynamic envs are "reset"
1348 * at the entrance of thread and the previous values will never be accessed.
1349 * To support thread parameters, we have to copy the parameter alist.
1350 */
1351 ScmObj get_inheriting_denv(ScmVM *vm)
1352 {
1353 if (vm == NULL) return SCM_NIL;
1354
1355 ScmObj orig = vm->denv, cp;
1356 ScmObj new_denv = SCM_NIL;
1357
1358 SCM_FOR_EACH(cp, orig) {
1359 if (!SCM_PAIRP(SCM_CAR(cp))) continue; /* can't happen, just in case */
1360 if (SCM_EQ(SCM_CAAR(cp), denv_key_parameterization)) {
1361 ScmObj hh = SCM_NIL, tt = SCM_NIL, ccp;
1362 SCM_FOR_EACH(ccp, SCM_CDAR(cp)) {
1363 ScmObj p = SCM_CAR(ccp); /* (<param> . <value>) */
1364 SCM_ASSERT(SCM_PRIMITIVE_PARAMETER_P(SCM_CAR(p)));
1365 ScmPrimitiveParameter *param =
1366 SCM_PRIMITIVE_PARAMETER(SCM_CAR(p));
1367 ScmObj newp = p;
1368 if (!Scm_PrimitiveParameterSharedP(param)) {
1369 newp = Scm_Cons(SCM_CAR(newp), SCM_CDR(newp));
1370 }
1371 SCM_APPEND1(hh, tt, newp);
1372 }
1373 new_denv = SCM_LIST1(Scm_Cons(SCM_CAAR(cp), hh));
1374 break;
1375 }
1376 }
1377 return new_denv;
1378 }
1379
1380 /* When VM stack has incomplete stack frame (that is, SP != ARGP or
1381 * *PC != SCM_VM_RET), and we need to run something on VM, we should
1382 * preserve this incomplete frame. Pushing an extra continuation
1383 * frame does the job. We set the PC to point to RET instruction,
1384 * so the next time the control returns to the calling VM loop,
1385 * the first thing it would do is to pop this extra continuation
1386 * frame (unless other thigs are pushed onto the VM stack by VMPushCC).
1387 * Returns TRUE if a new extra frame is pushed, FALSE if not.
1388 *
1389 * Caveat: This function changes the next instruction to be executed.
1390 * It is a problem if this is called during VM insturctions such as
1391 * CAR-PUSH, which expects the next instruction to make use of the
1392 * pushed value---if we make RET to be executed instead of the original
1393 * instruction, the pushed value will be lost. So, the caller of this
1394 * function needs to see if the frame is actually pushed, and call
1395 * Scm__VMUnprotectStack below to recover the original instruction.
1396 */
1397 int Scm__VMProtectStack(ScmVM *vm)
1398 {
1399 if (vm->sp != vm->argp || *vm->pc != SCM_VM_INSN(SCM_VM_RET)) {
1400 CHECK_STACK(CONT_FRAME_SIZE);
1401 PUSH_CONT(PC);
1402 vm->pc = PC_TO_RETURN;
1403 return TRUE;
1404 } else {
1405 return FALSE;
1406 }
1407 }
1408
1409 /* The inverse of Scm__VMProtectStack. This is required if you called
1410 * Scm__VMProtectStack _in_the_middle_of_VM_instruction_execution_.
1411 * The VM instruction may push things after that, counting on the fact
1412 * that subsequent instructoins use the pushed item. However,
1413 * Scm__VMProtectStack makes the next instruction to be executed
1414 * to RET. This makes the thing pushed by the current instruction be
1415 * discarded immediately, before the original subsequent instructions
1416 * seeing it. Calling Scm__VMUnprotectStack restores the original next
1417 * instruction (assuming it's properly paired up with Scm__VMProtectStack).
1418 */
1419 void Scm__VMUnprotectStack(ScmVM *vm)
1420 {
1421 SCM_ASSERT(vm->pc == PC_TO_RETURN);
1422 POP_CONT();
1423 }
1424
1425 #if GAUCHE_FFX
1426 /* Move all the FLONUM_REGs to heap and clear the fpstack.
1427 We cache small number of visited env frames to avoid duplicate scanning
1428 (if there are more env frames, linear search in the cache gets even
1429 more costly than duplicate scanning).
1430 */
1431
1432 #define ENV_CACHE_SIZE 32
1433
1434 #undef COUNT_FLUSH_FPSTACK
1435
1436 #ifdef COUNT_FLUSH_FPSTACK
1437 static int flush_fpstack_count = 0;
1438 static u_long flush_fpstack_time = 0;
1439 static void print_flush_fpstack_count(void*z)
1440 {
1441 fprintf(stderr, "fpstack count = %d time = %ldus (avg %fus)\n",
1442 flush_fpstack_count, flush_fpstack_time,
1443 flush_fpstack_time/(double)flush_fpstack_count);
1444 }
1445 #endif
1446
1447 void Scm_VMFlushFPStack(ScmVM *vm)
1448 {
1449 ScmEnvFrame *visited[ENV_CACHE_SIZE];
1450 int visited_index = 0;
1451 #ifdef COUNT_FLUSH_FPSTACK
1452 struct timeval t0, t1;
1453 gettimeofday(&t0, NULL);
1454 #endif
1455
1456 /* first, scan value registers and incomplete frames */
1457 SCM_FLONUM_ENSURE_MEM(VAL0);
1458 for (int i=0; i<SCM_VM_MAX_VALUES; i++) {
1459 SCM_FLONUM_ENSURE_MEM(vm->vals[i]);
1460 }
1461 if (IN_FULL_STACK_P(ARGP)) {
1462 for (ScmObj *p = ARGP; p < SP; p++) SCM_FLONUM_ENSURE_MEM(*p);
1463 }
1464
1465 /* scan the main environment chain */
1466 ScmEnvFrame *e = ENV;
1467 while (IN_FULL_STACK_P((ScmObj*)e)) {
1468 for (int i = 0; i < visited_index; i++) {
1469 if (visited[i] == e) goto next;
1470 }
1471 if (visited_index < ENV_CACHE_SIZE) {
1472 visited[visited_index++] = e;
1473 }
1474
1475 for (int i = 0; i < e->size; i++) {
1476 ScmObj *p = &ENV_DATA(e, i);
1477 SCM_FLONUM_ENSURE_MEM(*p);
1478 }
1479 next:
1480 e = e->up;
1481 }
1482
1483 /* scan the env chains grabbed by cont chain */
1484 ScmContFrame *c = CONT;
1485 while (IN_FULL_STACK_P((ScmObj*)c)) {
1486 e = c->env;
1487 while (IN_FULL_STACK_P((ScmObj*)e)) {
1488 for (int i = 0; i < visited_index; i++) {
1489 if (visited[i] == e) goto next2;
1490 }
1491 if (visited_index < ENV_CACHE_SIZE) {
1492 visited[visited_index++] = e;
1493 }
1494 for (int i = 0; i < e->size; i++) {
1495 ScmObj *p = &ENV_DATA(e, i);
1496 SCM_FLONUM_ENSURE_MEM(*p);
1497 }
1498 next2:
1499 e = e->up;
1500 }
1501 if (IN_FULL_STACK_P((ScmObj*)c) && c->size > 0) {
1502 ScmObj *p = (ScmObj*)c - c->size;
1503 for (int i=0; i<c->size; i++, p++) SCM_FLONUM_ENSURE_MEM(*p);
1504 }
1505 c = c->prev;
1506 }
1507 #if GAUCHE_SPLIT_STACK
1508 if ((c = vm->lastErrorCont) != NULL) {
1509 while (IN_FULL_STACK_P((ScmObj*)c)) {
1510 e = c->env;
1511 while (IN_FULL_STACK_P((ScmObj*)e)) {
1512 for (int i = 0; i < visited_index; i++) {
1513 if (visited[i] == e) goto next3;
1514 }
1515 if (visited_index < ENV_CACHE_SIZE) {
1516 visited[visited_index++] = e;
1517 }
1518 for (int i = 0; i < e->size; i++) {
1519 ScmObj *p = &ENV_DATA(e, i);
1520 SCM_FLONUM_ENSURE_MEM(*p);
1521 }
1522 next3:
1523 e = e->up;
1524 }
1525 if (IN_FULL_STACK_P((ScmObj*)c) && c->size > 0) {
1526 ScmObj *p = (ScmObj*)c - c->size;
1527 for (int i=0; i<c->size; i++, p++) SCM_FLONUM_ENSURE_MEM(*p);
1528 }
1529 c = c->prev;
1530 }
1531 }
1532 #endif
1533
1534 vm->fpsp = vm->fpstack;
1535
1536 #ifdef COUNT_FLUSH_FPSTACK
1537 flush_fpstack_count++;
1538 gettimeofday(&t1, NULL);
1539 flush_fpstack_time +=
1540 (t1.tv_sec - t0.tv_sec)*1000000+(t1.tv_usec - t0.tv_usec);
1541 #endif
1542 }
1543 #undef ENV_CACHE_SIZE
1544
1545 #endif /*GAUCHE_FFX*/
1546
1547 /*
1548 * Dynamic environment public API
1549 */
1550
1551 static void push_dynamic_env(ScmVM *vm, ScmObj key, ScmObj val)
1552 {
1553 /* If we have duplicate key in the current continuation frame,
1554 we need an extra care not to increase the dynenv chain.
1555 (See the discussion in srfi-226)
1556 */
1557 ScmContFrame *c = vm->cont;
1558 ScmObj limit = (c? c->denv : SCM_NIL);
1559
1560 for (ScmObj p = vm->denv; SCM_PAIRP(p); p = SCM_CDR(p)) {
1561 if (SCM_EQ(p, limit)) break;
1562 if (SCM_EQ(SCM_CAAR(p), key)) {
1563 /* Remove duplicate key */
1564 ScmObj h = SCM_NIL, t = SCM_NIL;
1565 for (ScmObj q = vm->denv; !SCM_EQ(q, p); q = SCM_CDR(q)) {
1566 SCM_APPEND1(h, t, SCM_CAR(q));
1567 }
1568 SCM_APPEND(h, t, SCM_CDR(p));
1569 vm->denv = h;
1570 }
1571 }
1572 vm->denv = Scm_Acons(key, val, vm->denv);
1573 }
1574
1575 /* Public API */
1576 void Scm_VMPushDynamicEnv(ScmObj key, ScmObj val)
1577 {
1578 push_dynamic_env(theVM, key, val);
1579 }
1580
1581 static ScmObj find_dynamic_env(ScmVM *vm, ScmObj key, ScmObj fallback)
1582 {
1583 ScmObj p = Scm_Assq(key, vm->denv);
1584 if (SCM_PAIRP(p)) return SCM_CDR(p);
1585 else return fallback;
1586 }
1587
1588 /* Public API */
1589 ScmObj Scm_VMFindDynamicEnv(ScmObj key, ScmObj fallback)
1590 {
1591 return find_dynamic_env(theVM, key, fallback);
1592 }
1593
1594
1595 /*==================================================================
1596 * Function application from C
1597 */
1598
1599 /* The Scm_VMApply family is supposed to be called in SUBR. It
1600 doesn't really applies the function in it. Instead, it modifies
1601 the VM state so that the specified function will be called
1602 immediately after this SUBR returns to the VM. The return value of
1603 Scm_VMApply is just a PROC, but it should be returned as the return
1604 value of SUBR, which will be used by the VM.
1605
1606 The PC is modifed to point to a CALL instruction, and arguments
1607 are pushed onto the stack. So, after returning to VM, it immediately
1608 calls VAL0 (which is PROC) with the pushed arguments.
1609
1610 The Scm_pc_Apply* are more "internal" API that are only supposed
1611 to be called from the machine generated code.
1612
1613 NB: We don't check proc is a procedure or not. It can be a
1614 non-procedure object, because of the object-apply hook.
1615
1616 NB: If we know that PROC is a subr and the number of arguments
1617 matches it expects, we use "trampoline" mode---the arguments
1618 are stored above SP, and vm->trampoline is set to the number
1619 of arguments. In that case, VM skips the argument-folding
1620 and dispatching code, and immediately invokes returned subr.
1621 This is important for precompiled-to-C code, for it tends to
1622 tail-call known subrs (we need to use trampoline to ensure the
1623 stack won't grow). We avoid to use trampoline when
1624 vm->attentionRequest is set, though, for the interrupt handling
1625 should be done while VM is a consistent state, but the trampoline
1626 is a kind of transitive state.
1627 */
1628
1629 /* Static VM instruction arrays.
1630 Scm_VMApplyN modifies VM's pc to point it. */
1631
1632 static ScmWord apply_calls[][2] = {
1633 { SCM_VM_INSN1(SCM_VM_TAIL_CALL, 0),
1634 SCM_VM_INSN(SCM_VM_RET) },
1635 { SCM_VM_INSN1(SCM_VM_TAIL_CALL, 1),
1636 SCM_VM_INSN(SCM_VM_RET) },
1637 { SCM_VM_INSN1(SCM_VM_TAIL_CALL, 2),
1638 SCM_VM_INSN(SCM_VM_RET) },
1639 { SCM_VM_INSN1(SCM_VM_TAIL_CALL, 3),
1640 SCM_VM_INSN(SCM_VM_RET) },
1641 { SCM_VM_INSN1(SCM_VM_TAIL_CALL, 4),
1642 SCM_VM_INSN(SCM_VM_RET) },
1643 };
1644
1645 static ScmWord apply_callN[2] = {
1646 SCM_VM_INSN1(SCM_VM_TAIL_APPLY, 2),
1647 SCM_VM_INSN(SCM_VM_RET)
1648 };
1649
1650 ScmObj Scm_VMApply(ScmObj proc, ScmObj args)
1651 {
1652 int numargs = Scm_Length(args);
1653 int reqstack;
1654 ScmVM *vm = theVM;
1655
1656 if (numargs < 0) Scm_Error("improper list not allowed: %S", args);
1657 SCM_ASSERT(TAIL_POS());
1658 SCM_ASSERT(ARGP == SP);
1659 #if 0
1660 reqstack = ENV_SIZE(numargs) + 1;
1661 if (reqstack >= SCM_VM_STACK_SIZE) {
1662 /* there's no way we can accept that many arguments */
1663 Scm_Error("too many arguments (%d) to apply", numargs);
1664 }
1665 CHECK_STACK(reqstack);
1666
1667 ScmObj cp;
1668 SCM_FOR_EACH(cp, args) {
1669 PUSH_ARG(SCM_CAR(cp));
1670 }
1671 if (numargs <= 4) {
1672 PC = apply_calls[numargs];
1673 } else {
1674 PC = SCM_NEW_ARRAY(ScmWord, 2);
1675 PC[0] = SCM_VM_INSN1(SCM_VM_TAIL_CALL, numargs);
1676 PC[1] = SCM_VM_INSN(SCM_VM_RET);
1677 }
1678 return proc;
1679 #else
1680 reqstack = ENV_SIZE(1) + 1;
1681 CHECK_STACK(reqstack);
1682 PUSH_ARG(proc);
1683 PC = apply_callN;
1684 return Scm_CopyList(args);
1685 #endif
1686 }
1687
1688 /* Shortcuts for common cases */
1689 ScmObj Scm_pc_Apply0(ScmVM *vm, ScmObj proc)
1690 {
1691 if (SCM_SUBRP(proc)
1692 && SCM_PROCEDURE_REQUIRED(proc) == 0
1693 && SCM_PROCEDURE_OPTIONAL(proc) == 0
1694 && !vm->attentionRequest) {
1695 vm->trampoline = 0;
1696 return proc;
1697 }
1698 vm->pc = apply_calls[0];
1699 return proc;
1700 }
1701
1702 ScmObj Scm_VMApply0(ScmObj proc)
1703 {
1704 return Scm_pc_Apply0(theVM, proc);
1705 }
1706
1707 ScmObj Scm_pc_Apply1(ScmVM *vm, ScmObj proc, ScmObj arg)
1708 {
1709 CHECK_STACK(1);
1710 if (SCM_SUBRP(proc)
1711 && SCM_PROCEDURE_REQUIRED(proc) == 1
1712 && SCM_PROCEDURE_OPTIONAL(proc) == 0
1713 && !vm->attentionRequest) {
1714 vm->trampoline = 1;
1715 SP[0] = arg;
1716 return proc;
1717 }
1718 PUSH_ARG(arg);
1719 PC = apply_calls[1];
1720 return proc;
1721 }
1722
1723 ScmObj Scm_VMApply1(ScmObj proc, ScmObj arg)
1724 {
1725 return Scm_pc_Apply1(theVM, proc, arg);
1726 }
1727
1728 ScmObj Scm_pc_Apply2(ScmVM *vm, ScmObj proc, ScmObj arg1, ScmObj arg2)
1729 {
1730 CHECK_STACK(2);
1731 if (SCM_SUBRP(proc)
1732 && SCM_PROCEDURE_REQUIRED(proc) == 2
1733 && SCM_PROCEDURE_OPTIONAL(proc) == 0
1734 && !vm->attentionRequest) {
1735 vm->trampoline = 2;
1736 SP[0] = arg1;
1737 SP[1] = arg2;
1738 return proc;
1739 }
1740 PUSH_ARG(arg1);
1741 PUSH_ARG(arg2);
1742 PC = apply_calls[2];
1743 return proc;
1744 }
1745
1746 ScmObj Scm_VMApply2(ScmObj proc, ScmObj arg1, ScmObj arg2)
1747 {
1748 return Scm_pc_Apply2(theVM, proc, arg1, arg2);
1749 }
1750
1751 ScmObj Scm_pc_Apply3(ScmVM *vm, ScmObj proc,
1752 ScmObj arg1, ScmObj arg2, ScmObj arg3)
1753 {
1754 CHECK_STACK(3);
1755 if (SCM_SUBRP(proc)
1756 && SCM_PROCEDURE_REQUIRED(proc) == 3
1757 && SCM_PROCEDURE_OPTIONAL(proc) == 0
1758 && !vm->attentionRequest) {
1759 vm->trampoline = 3;
1760 SP[0] = arg1;
1761 SP[1] = arg2;
1762 SP[2] = arg3;
1763 return proc;
1764 }
1765 PUSH_ARG(arg1);
1766 PUSH_ARG(arg2);
1767 PUSH_ARG(arg3);
1768 PC = apply_calls[3];
1769 return proc;
1770 }
1771
1772 ScmObj Scm_VMApply3(ScmObj proc, ScmObj arg1, ScmObj arg2, ScmObj arg3)
1773 {
1774 return Scm_pc_Apply3(theVM, proc, arg1, arg2, arg3);
1775 }
1776
1777 ScmObj Scm_pc_Apply4(ScmVM *vm, ScmObj proc,
1778 ScmObj arg1, ScmObj arg2, ScmObj arg3, ScmObj arg4)
1779 {
1780 CHECK_STACK(4);
1781 if (SCM_SUBRP(proc)
1782 && SCM_PROCEDURE_REQUIRED(proc) == 4
1783 && SCM_PROCEDURE_OPTIONAL(proc) == 0
1784 && !vm->attentionRequest) {
1785 vm->trampoline = 4;
1786 SP[0] = arg1;
1787 SP[1] = arg2;
1788 SP[2] = arg3;
1789 SP[3] = arg4;
1790 return proc;
1791 }
1792 PUSH_ARG(arg1);
1793 PUSH_ARG(arg2);
1794 PUSH_ARG(arg3);
1795 PUSH_ARG(arg4);
1796 PC = apply_calls[4];
1797 return proc;
1798 }
1799
1800
1801 ScmObj Scm_VMApply4(ScmObj proc,
1802 ScmObj arg1, ScmObj arg2, ScmObj arg3, ScmObj arg4)
1803 {
1804 return Scm_pc_Apply4(theVM, proc, arg1, arg2, arg3, arg4);
1805 }
1806
1807 static ScmObj eval_restore_env(ScmObj *args SCM_UNUSED,
1808 int argc SCM_UNUSED,
1809 void *data)
1810 {
1811 theVM->module = SCM_MODULE(data);
1812 return SCM_UNDEFINED;
1813 }
1814
1815 /* For now, we only supports a module as the evaluation environment */
1816 ScmObj Scm_VMEval(ScmObj expr, ScmObj e)
1817 {
1818 int restore_module = SCM_MODULEP(e);
1819 ScmVM *vm = theVM;
1820
1821 ScmObj v = Scm_Compile(expr, e);
1822 if (SCM_VM_COMPILER_FLAG_IS_SET(theVM, SCM_COMPILE_SHOWRESULT)) {
1823 Scm_CompiledCodeDump(SCM_COMPILED_CODE(v));
1824 }
1825
1826 vm->numVals = 1;
1827 if (restore_module) {
1828 /* if we swap the module, we need to make sure it is recovered
1829 after eval */
1830 ScmObj body = Scm_MakeClosure(v, NULL);
1831 ScmObj before = Scm_MakeSubr(eval_restore_env, SCM_MODULE(e),
1832 0, 0, SCM_SYM_EVAL_BEFORE);
1833 ScmObj after = Scm_MakeSubr(eval_restore_env, (void*)vm->module,
1834 0, 0, SCM_SYM_EVAL_AFTER);
1835 return Scm_VMDynamicWind(before, body, after);
1836 } else {
1837 /* shortcut */
1838 SCM_ASSERT(SCM_COMPILED_CODE_P(v));
1839 vm->base = SCM_COMPILED_CODE(v);
1840 vm->pc = SCM_COMPILED_CODE(v)->code;
1841 SCM_PROF_COUNT_CALL(vm, v);
1842 return SCM_UNDEFINED;
1843 }
1844 }
1845
1846 /*
1847 * C continuation
1848 *
1849 * This is a bit messy due to the historical evolution of C continuations.
1850 */
1851
1852 /* Common ccont frame constructor */
1853 static ScmObj *new_ccont(ScmVM *vm, ScmPContinuationProc *after,
1854 ScmWord *cpcdata, int datasize)
1855 {
1856 CHECK_STACK(CONT_FRAME_SIZE+datasize);
1857 ScmObj *s = SP;
1858 ScmContFrame *cc = (ScmContFrame*)(s + datasize);
1859 cc->prev = CONT;
1860 cc->env = &ccEnvMark;
1861 cc->denv = DENV;
1862 cc->size = datasize;
1863 cc->marker = 0;
1864 cc->cpc = cpcdata;
1865 cc->pc = (ScmWord*)after;
1866 cc->base = BASE;
1867 CONT = cc;
1868 ARGP = SP = s + datasize + CONT_FRAME_SIZE;
1869 return s;
1870 }
1871
1872 /* This is a trick to keep the backward compatibility. */
1873 static ScmObj ccont_adapter(ScmVM *vm, ScmObj val0, ScmObj *data)
1874 {
1875 ScmCContinuationProc *ccont = (ScmCContinuationProc*)vm->ccont;
1876 return ccont(val0, (void**)data);
1877 }
1878
1879 /* Arrange C function AFTER to be called after the procedure returns.
1880 * Usually followed by Scm_VMApply* function.
1881 *
1882 * This is an 'old' protocol (after procedure does not take VM pointer).
1883 * For the backward compatibility, we support this type of C continuation
1884 * with this kludge:
1885 *
1886 * - We save 'after' CCont pointer in cont->cpc, and set the PCont
1887 * pointer (cont->pc) with ccont_adapter().
1888 * - In POP_CONT, when we pop the C continuation frame, cont->cpc
1889 * is saved in vm->ccont immediately before PCont procedure is
1890 * called.
1891 * - In ccont_adapter, the original 'after' pointer is retrieved
1892 * from vm->ccont and called.
1893 *
1894 * This incurs a slight overhead for the old protocol, but does not
1895 * tax the new protocol.
1896 */
1897 void Scm_VMPushCC(ScmCContinuationProc *after,
1898 void **data, int datasize)
1899 {
1900 ScmVM *vm = theVM;
1901 ScmObj *buf = new_ccont(vm, ccont_adapter, (ScmWord*)after, datasize);
1902 for (int i=0; i<datasize; i++) {
1903 buf[i] = SCM_OBJ(data[i]);
1904 }
1905 }
1906
1907 /* Allocate SIZE words from the VM stack. The stack may be packed
1908 to make room. */
1909 ScmObj *Scm_pc_Alloca(ScmVM *vm, size_t size)
1910 {
1911 CHECK_STACK(size);
1912 ScmObj *r = SP;
1913 SP += size;
1914 return r;
1915 }
1916
1917 /* Like VMPushCC, but we just make room for data and return the
1918 pointer to it, letting caller to fill it. Supposed to be
1919 used by machine-generated C code. */
1920 ScmObj *Scm_pc_PushCC(ScmVM *vm, ScmPContinuationProc *after, int datasize)
1921 {
1922 return new_ccont(vm, after, NULL, datasize);
1923 }
1924
1925 /* A special internal procedure to push C continuation with dynamic
1926 handlers. Only used for dynamic-wind. */
1927 static ScmObj *push_dynamic_handler_cc(ScmVM *vm, ScmPContinuationProc *after,
1928 ScmObj dh, int datasize)
1929 {
1930 return new_ccont(vm, after, (ScmWord*)dh, datasize);
1931 }
1932
1933 /*
1934 * EscapePoints
1935 */
1936
1937 SCM_DEFINE_BUILTIN_CLASS(Scm_EscapePointClass,
1938 NULL, NULL, NULL, NULL,
1939 SCM_CLASS_OBJECT_CPL);
1940
1941 static ScmEscapePoint *new_ep(ScmVM *vm,
1942 ScmObj errorHandler,
1943 int rewindBefore,
1944 ScmObj promptTag,
1945 ScmObj abortHandler)
1946 {
1947 ScmEscapePoint *ep = SCM_NEW(ScmEscapePoint);
1948 SCM_SET_CLASS(ep, SCM_CLASS_ESCAPE_POINT);
1949 ep->ehandler = errorHandler;
1950 ep->cont = vm->cont;
1951 ep->denv = vm->denv;
1952 ep->dynamicHandlers = get_dynamic_handlers(vm);
1953 ep->cstack = vm->cstack;
1954 ep->xhandler = Scm_VMCurrentExceptionHandler();
1955 ep->resetChain = vm->resetChain;
1956 ep->partHandlers = SCM_NIL;
1957 ep->errorReporting =
1958 SCM_VM_RUNTIME_FLAG_IS_SET(vm, SCM_ERROR_BEING_REPORTED);
1959 ep->rewindBefore = rewindBefore;
1960 ep->promptTag = promptTag;
1961 ep->abortHandler = abortHandler;
1962 ep->bottom = NULL;
1963 return ep;
1964 }
1965
1966 /*-------------------------------------------------------------
1967 * User level eval and apply.
1968 * When the C routine wants the Scheme code to return to it,
1969 * instead of using C-continuation, the continuation
1970 * "cross the border" of C-stack and Scheme-stack. This
1971 * border has peculiar characteristics. Once the Scheme
1972 * returns, continuations saved during the execution of the
1973 * Scheme code becomes invalid.
1974 *
1975 * At the implementation level, this boundary is kept in a
1976 * structure ScmCStack.
1977 */
1978
1979 /* Border gate. All the C->Scheme calls should go through here.
1980 *
1981 * The current C stack information is saved in cstack. The
1982 * current VM stack information is saved (as a continuation
1983 * frame pointer) in cstack.cont.
1984 */
1985
1986 static ScmObj user_eval_inner(ScmObj program,
1987 ScmWord *codevec,
1988 ScmObj promptTag,
1989 ScmObj abortHandler)
1990 {
1991 ScmCStack cstack;
1992 ScmVM * volatile vm = theVM;
1993 /* Save prev_pc, for the boundary continuation uses pc slot
1994 to mark the boundary. */
1995 ScmWord * volatile prev_pc = PC;
1996 ScmObj vmhandlers = get_dynamic_handlers(vm);
1997 ScmObj vmresetChain = vm->resetChain;
1998
1999 if (SCM_FALSEP(promptTag)) {
2000 promptTag = SCM_OBJ(&defaultPromptTag);
2001 }
2002
2003 /* Push extra continuation. This continuation frame is a 'boundary
2004 frame' and marked by marker == SCM_CONT_RESET_MARKER. VM loop knows
2005 it should return to C frame when it sees a boundary frame.
2006 A boundary frame also keeps the unfinished argument frame at
2007 the point when Scm_Eval or Scm_Apply is called. */
2008 push_boundary_cont(vm, promptTag, abortHandler);
2009 SCM_ASSERT(SCM_COMPILED_CODE_P(program));
2010 vm->base = SCM_COMPILED_CODE(program);
2011 if (codevec != NULL) {
2012 PC = codevec;
2013 } else {
2014 PC = vm->base->code;
2015 CHECK_STACK(vm->base->maxstack);
2016 }
2017 SCM_PROF_COUNT_CALL(vm, program);
2018
2019 cstack.prev = vm->cstack;
2020 cstack.cont = vm->cont;
2021 vm->cstack = &cstack;
2022
2023 restart:
2024 vm->escapeReason = SCM_VM_ESCAPE_NONE;
2025 if (sigsetjmp(cstack.jbuf, FALSE) == 0) {
2026 run_loop(); /* VM loop */
2027 if (vm->cont == cstack.cont) {
2028 POP_CONT();
2029 PC = prev_pc;
2030 } else if (vm->cont == NULL) {
2031 /* we're finished with executing partial continuation. */
2032
2033 /* restore reset-chain for reset/shift */
2034 vm->resetChain = vmresetChain;
2035
2036 /* save return values */
2037 ScmObj val0 = vm->val0;
2038 int nvals = vm->numVals;
2039 ScmObj *vals = NULL;
2040 if (nvals > 1) {
2041 vals = SCM_NEW_ARRAY(ScmObj, nvals-1);
2042 memcpy(vals, vm->vals, sizeof(ScmObj)*(nvals-1));
2043 }
2044
2045 /* call dynamic handlers for returning to the caller */
2046 call_dynamic_handlers(vm, vmhandlers,
2047 get_dynamic_handlers(vm));
2048
2049 /* restore return values */
2050 vm->val0 = val0;
2051 vm->numVals = nvals;
2052 if (vals != NULL) {
2053 memcpy(vm->vals, vals, sizeof(ScmObj)*(nvals-1));
2054 }
2055
2056 vm->cont = cstack.cont;
2057 POP_CONT();
2058 PC = prev_pc;
2059 } else {
2060 /* If we come here, we've been executing a ghost continuation.
2061 The C world the ghost should return no longer exists, so we
2062 raise an error. */
2063 Scm_Error("attempt to return from a ghost continuation.");
2064 }
2065 } else {
2066 /* An escape situation happened. */
2067 if (vm->escapeReason == SCM_VM_ESCAPE_CONT) {
2068 ScmEscapePoint *ep = (ScmEscapePoint*)vm->escapeData[0];
2069 if (ep->cstack == vm->cstack) {
2070 ScmObj handlers =
2071 throw_cont_calculate_handlers(ep->dynamicHandlers,
2072 get_dynamic_handlers(vm));
2073 /* force popping continuation when restarted */
2074 vm->pc = PC_TO_RETURN;
2075 vm->val0 = throw_cont_body(handlers, ep, vm->escapeData[1]);
2076 goto restart;
2077 } else {
2078 SCM_ASSERT(vm->cstack && vm->cstack->prev);
2079 vm->cont = cstack.cont;
2080 POP_CONT();
2081 vm->cstack = vm->cstack->prev;
2082 siglongjmp(vm->cstack->jbuf, 1);
2083 }
2084 } else if (vm->escapeReason == SCM_VM_ESCAPE_ERROR) {
2085 ScmEscapePoint *ep = (ScmEscapePoint*)vm->escapeData[0];
2086 if (ep && ep->cstack == vm->cstack) {
2087 vm->cont = ep->cont;
2088 vm->denv = ep->denv;
2089 vm->pc = PC_TO_RETURN;
2090 /* restore reset-chain for reset/shift */
2091 if (ep->cstack) vm->resetChain = ep->resetChain;
2092 goto restart;
2093 } else if (vm->cstack->prev == NULL) {
2094 /* This loop is the outermost C stack, and nobody will
2095 capture the error. This happens when the base C code
2096 calls Scm_EvalRec/ApplyRec, instead of Scm_Eval/Apply.
2097 We can't return, since there's no way to pass the
2098 error info. We can only just exit.
2099 */
2100 Scm_Exit(EX_SOFTWARE);
2101 } else {
2102 /* Jump again until C stack is recovered. We could pop
2103 the extra continuation frame so that the VM stack
2104 is consistent. */
2105 vm->cont = cstack.cont;
2106 POP_CONT();
2107 vm->cstack = vm->cstack->prev;
2108 siglongjmp(vm->cstack->jbuf, 1);
2109 }
2110 } else {
2111 Scm_Panic("invalid longjmp");
2112 }
2113 /* NOTREACHED */
2114 }
2115 vm->cstack = vm->cstack->prev;
2116 return vm->val0;
2117 }
2118
2119 void push_prompt_cont(ScmVM *vm, ScmObj promptTag, ScmObj abortHandler)
2120 {
2121 /* We want to allocate ScmPromptData on stack. If there's already
2122 an unfinished argument frame, however, we need to insert ScmPromptData
2123 before it (for other parts of code assumes unfinished argument frame
2124 immediately precedes cont frame).
2125 */
2126 CHECK_STACK(CONT_FRAME_SIZE + PROMPT_DATA_SIZE + (SP - ARGP));
2127
2128 ScmPromptData *a = (ScmPromptData*)ARGP;
2129
2130 if (SP - ARGP > 0) {
2131 for (ScmObj *s = SP-1, *d = SP+PROMPT_DATA_SIZE-1;
2132 s >= ARGP;
2133 s--, d--) {
2134 *d = *s;
2135 }
2136 }
2137 SP += PROMPT_DATA_SIZE;
2138 ARGP += PROMPT_DATA_SIZE;
2139
2140 a->dummy = SCM_VM_INSN(SCM_VM_RET);
2141 a->abortHandler = abortHandler;
2142 a->dynamicHandlers = get_dynamic_handlers(vm);
2143 PUSH_CONT(SCM_PROMPT_TAG_PC(promptTag));
2144 CONT->cpc = &a->dummy;
2145 }
2146
2147 void push_boundary_cont(ScmVM *vm, ScmObj promptTag, ScmObj abortHandler)
2148 {
2149 /* Boundary continuation is a prompt cont with CONT_RESET_MARKER */
2150 push_prompt_cont(vm, promptTag, abortHandler);
2151 CONT->marker = SCM_CONT_RESET_MARKER;
2152 }
2153
2154 /* API for recursive call to VM. Exceptions are not captured.
2155 Returns the primary result. To retrieve the rest of results,
2156 you have to use Scm_VMGetResult etc. */
2157
2158 ScmObj Scm_EvalRec(ScmObj expr, ScmObj e)
2159 {
2160 ScmObj v = Scm_Compile(expr, e);
2161 SCM_COMPILED_CODE(v)->name = SCM_SYM_INTERNAL_EVAL;
2162 if (SCM_VM_COMPILER_FLAG_IS_SET(theVM, SCM_COMPILE_SHOWRESULT)) {
2163 Scm_CompiledCodeDump(SCM_COMPILED_CODE(v));
2164 }
2165 return user_eval_inner(v, NULL, SCM_FALSE, SCM_FALSE);
2166 }
2167
2168 /* NB: The ApplyRec family can be called in an inner loop (e.g. the display
2169 callback from GLUT.) So we don't want to allocate at all. We put
2170 a temporary code vector on C stack. It is OK, since once
2171 user_eval_inner returns it would never be reused. However, tools
2172 that want to keep a pointer to a code vector would need to be aware
2173 of this case. */
2174 static ScmObj apply_rec(ScmVM *vm, ScmObj proc, int nargs)
2175 {
2176 ScmWord code[2];
2177 code[0] = SCM_WORD(SCM_VM_INSN1(SCM_VM_VALUES_APPLY, nargs));
2178 code[1] = SCM_WORD(SCM_VM_INSN(SCM_VM_RET));
2179
2180 vm->val0 = proc;
2181 ScmObj program = vm->base?
2182 SCM_OBJ(vm->base) : SCM_OBJ(&internal_apply_compiled_code);
2183 return user_eval_inner(program, code, SCM_FALSE, SCM_FALSE);
2184 }
2185
2186 ScmObj Scm_ApplyRec(ScmObj proc, ScmObj args)
2187 {
2188 int nargs = Scm_Length(args);
2189 ScmVM *vm = theVM;
2190
2191 if (nargs < 0) {
2192 Scm_Error("improper list not allowed: %S", args);
2193 }
2194
2195 for (int i=0; i<nargs; i++) {
2196 if (i == SCM_VM_MAX_VALUES-1) {
2197 vm->vals[i] = args;
2198 break;
2199 }
2200 vm->vals[i] = SCM_CAR(args);
2201 args = SCM_CDR(args);
2202 }
2203 return apply_rec(vm, proc, nargs);
2204 }
2205
2206 ScmObj Scm_ApplyRec0(ScmObj proc)
2207 {
2208 return apply_rec(theVM, proc, 0);
2209 }
2210
2211 ScmObj Scm_ApplyRec1(ScmObj proc, ScmObj arg0)
2212 {
2213 ScmVM *vm = theVM;
2214 vm->vals[0] = arg0;
2215 return apply_rec(vm, proc, 1);
2216 }
2217
2218 ScmObj Scm_ApplyRec2(ScmObj proc, ScmObj arg0, ScmObj arg1)
2219 {
2220 ScmVM *vm = theVM;
2221 vm->vals[0] = arg0;
2222 vm->vals[1] = arg1;
2223 return apply_rec(vm, proc, 2);
2224 }
2225
2226 ScmObj Scm_ApplyRec3(ScmObj proc, ScmObj arg0, ScmObj arg1, ScmObj arg2)
2227 {
2228 ScmVM *vm = theVM;
2229 vm->vals[0] = arg0;
2230 vm->vals[1] = arg1;
2231 vm->vals[2] = arg2;
2232 return apply_rec(vm, proc, 3);
2233 }
2234
2235 ScmObj Scm_ApplyRec4(ScmObj proc, ScmObj arg0, ScmObj arg1, ScmObj arg2,
2236 ScmObj arg3)
2237 {
2238 ScmVM *vm = theVM;
2239 vm->vals[0] = arg0;
2240 vm->vals[1] = arg1;
2241 vm->vals[2] = arg2;
2242 vm->vals[3] = arg3;
2243 return apply_rec(vm, proc, 4);
2244 }
2245
2246 ScmObj Scm_ApplyRec5(ScmObj proc, ScmObj arg0, ScmObj arg1, ScmObj arg2,
2247 ScmObj arg3, ScmObj arg4)
2248 {
2249 ScmVM *vm = theVM;
2250 vm->vals[0] = arg0;
2251 vm->vals[1] = arg1;
2252 vm->vals[2] = arg2;
2253 vm->vals[3] = arg3;
2254 vm->vals[4] = arg4;
2255 return apply_rec(vm, proc, 5);
2256 }
2257
2258 /*
2259 * Safe version of user-level Eval, Apply and Load.
2260 * Exceptions are caught and stored in ScmEvalPacket.
2261 */
2262
2263 enum {
2264 SAFE_EVAL,
2265 SAFE_EVAL_CSTRING,
2266 SAFE_APPLY
2267 };
2268
2269 struct eval_packet_rec {
2270 ScmObj env;
2271 int kind;
2272 ScmObj arg0; /* form (EVAL), proc (APPLY) */
2273 ScmObj args; /* args (APPLY) */
2274 const char *cstr; /* cstring (EVAL_CSTRING) */
2275 ScmObj exception;
2276 };
2277
2278 static ScmObj safe_eval_handler(ScmObj *args,
2279 int nargs, void *data)
2280 {
2281 SCM_ASSERT(nargs == 1);
2282 ((struct eval_packet_rec *)data)->exception = args[0];
2283 return SCM_UNDEFINED;
2284 }
2285
2286 static ScmObj safe_eval_thunk(ScmObj *args SCM_UNUSED,
2287 int nargs SCM_UNUSED,
2288 void *data)
2289 {
2290 struct eval_packet_rec *epak = (struct eval_packet_rec*)data;
2291 ScmObj r;
2292
2293 switch (epak->kind) {
2294 case SAFE_EVAL_CSTRING:
2295 r = Scm_VMEval(Scm_ReadFromCString(epak->cstr), epak->env);
2296 break;
2297 case SAFE_EVAL:
2298 r = Scm_VMEval(epak->arg0, epak->env);
2299 break;
2300 case SAFE_APPLY:
2301 r = Scm_VMApply(epak->arg0, epak->args);
2302 break;
2303 default:
2304 Scm_Panic("safe_eval_subr: bad kind");
2305 return SCM_UNBOUND; /* dummy */
2306 }
2307 /* If expressino was select-module, the current module may be changed. */
2308 epak->env = SCM_OBJ(SCM_CURRENT_MODULE());
2309 return r;
2310 }
2311
2312 static ScmObj safe_eval_int(ScmObj *args SCM_UNUSED,
2313 int nargs SCM_UNUSED,
2314 void *data)
2315 {
2316 ScmObj thunk = Scm_MakeSubr(safe_eval_thunk, data, 0, 0, SCM_FALSE);
2317 ScmObj handler = Scm_MakeSubr(safe_eval_handler, data, 1, 0, SCM_FALSE);
2318 return Scm_VMWithErrorHandler(handler, thunk);
2319 }
2320
2321 static int safe_eval_wrap(int kind, ScmObj arg0, ScmObj args,
2322 const char *cstr, ScmObj env,
2323 ScmEvalPacket *result)
2324 {
2325 ScmVM *vm = theVM;
2326
2327 struct eval_packet_rec epak;
2328 epak.env = env;
2329 epak.kind = kind;
2330 epak.arg0 = arg0;
2331 epak.args = args;
2332 epak.cstr = cstr;
2333 epak.exception = SCM_UNBOUND;
2334
2335 ScmObj proc = Scm_MakeSubr(safe_eval_int, &epak, 0, 0, SCM_FALSE);
2336 ScmObj r = Scm_ApplyRec(proc, SCM_NIL);
2337
2338 if (SCM_UNBOUNDP(epak.exception)) {
2339 /* normal termination */
2340 if (result) {
2341 result->numResults = vm->numVals;
2342 result->results[0] = r;
2343 for (int i=1; i<vm->numVals; i++) {
2344 result->results[i] = vm->vals[i-1];
2345 }
2346 result->exception = SCM_FALSE;
2347 if (SCM_MODULEP(epak.env)) {
2348 result->module = SCM_MODULE(epak.env);
2349 }
2350 }
2351 return vm->numVals;
2352 } else {
2353 /* abnormal termination */
2354 if (result) {
2355 result->numResults = 0;
2356 result->exception = epak.exception;
2357 }
2358 return -1;
2359 }
2360 }
2361
2362 int Scm_Eval(ScmObj form, ScmObj env, ScmEvalPacket *packet)
2363 {
2364 return safe_eval_wrap(SAFE_EVAL, form, SCM_FALSE, NULL, env, packet);
2365 }
2366
2367 int Scm_EvalCString(const char *expr, ScmObj env, ScmEvalPacket *packet)
2368 {
2369 return safe_eval_wrap(SAFE_EVAL_CSTRING, SCM_FALSE, SCM_FALSE,
2370 expr, env, packet);
2371 }
2372
2373 int Scm_Apply(ScmObj proc, ScmObj args, ScmEvalPacket *packet)
2374 {
2375 return safe_eval_wrap(SAFE_APPLY, proc, args, NULL, SCM_FALSE, packet);
2376 }
2377
2378 /*
2379 * A subroutine to be called while executing apply instruction.
2380 * Apply needs to check the argument tail is a valid list. However,
2381 * naively using ordinary procedures can trigger forcing of lazy
2382 * pair, which breaks VM state.
2383 *
2384 * When called, we know vm->sp[-1] contains the tail list of arguments.
2385 * It may be a lazy pair. If so, we should force it in the safe environment.
2386 * Returns the length of the tail list.
2387 *
2388 * Currently, we force the lazy argument tail in very inefficient way,
2389 * assuming that such case is very rare.
2390 *
2391 * When max_limit is non-negative, we only check up that number of
2392 * arguments and bail. For the true length, the caller should call
2393 * again with max_limit == -1.
2394 */
2395
2396 int check_arglist_tail_for_apply(ScmVM *vm SCM_UNUSED, ScmObj z, int max_limit)
2397 {
2398 int count = 0;
2399 static ScmObj length_proc = SCM_UNDEFINED;
2400 ScmObj tortoise = z;
2401
2402 for (;;) {
2403 if (SCM_NULLP(z)) return count;
2404 if (SCM_LAZY_PAIR_P(z)) goto do_lazy_pair;
2405 if (!SCM_PAIRP(z)) goto bad_list;
2406
2407 z = SCM_CDR(z);
2408 count++;
2409
2410 if (SCM_NULLP(z)) return count;
2411 if (SCM_LAZY_PAIR_P(z)) goto do_lazy_pair;
2412 if (!SCM_PAIRP(z)) goto bad_list;
2413
2414 z = SCM_CDR(z);
2415 tortoise = SCM_CDR(tortoise);
2416 if (z == tortoise) goto bad_list; /* circular */
2417 count++;
2418
2419 if (max_limit >= 0 && count >= max_limit) return count;
2420 }
2421
2422 do_lazy_pair:
2423 {
2424 ScmEvalPacket result;
2425 SCM_BIND_PROC(length_proc, "length", Scm_GaucheModule());
2426 int nres = Scm_Apply(length_proc, SCM_LIST1(z), &result);
2427 if (nres == -1) Scm_Raise(result.exception, 0);
2428 SCM_ASSERT(nres == 1);
2429 SCM_ASSERT(SCM_INTP(result.results[0]));
2430 count += SCM_INT_VALUE(result.results[0]);
2431 return count;
2432 }
2433 bad_list:
2434 Scm_Error("improper list not allowed: %S", tortoise);
2435 }
2436
2437 /*=================================================================
2438 * Dynamic handlers
2439 */
2440
2441 /* On <handler-chain>
2442 *
2443 * Dynamic handlers is a list of <handler-entry>. Each <handler-entry>
2444 * keeps the "before" and "after" thunk of the dynamic-wind.
2445 *
2446 * <handler-entry> is ScmDynamicHandler object. It should be
2447 * treated as an opaque object except in vm.c
2448 *
2449 * It has the following members:
2450 *
2451 * <before-proc>
2452 * <after-proc>
2453 * <denv>
2454 * <args>
2455 *
2456 * <before-proc> and <after-proc> are before and after procedures. With
2457 * the basic dynamic-wind, they're thunks. When optimized, <before-proc>
2458 * and <after-proc> may take arguments <args> ....
2459 * <denv> is the dynamic environment on which handlers should be called.
2460 */
2461
2462 /* Class stuff */
2463 static void dynamic_handler_print(ScmObj obj, ScmPort *out,
2464 ScmWriteContext *ctx SCM_UNUSED)
2465 {
2466 Scm_Printf(out, "#<dynamic-handler %S %S>",
2467 SCM_DYNAMIC_HANDLER(obj)->before,
2468 SCM_DYNAMIC_HANDLER(obj)->after);
2469 }
2470
2471 SCM_DEFINE_BUILTIN_CLASS(Scm_DynamicHandlerClass,
2472 dynamic_handler_print, NULL, NULL, NULL,
2473 SCM_CLASS_DEFAULT_CPL);
2474
2475 ScmObj make_dynamic_handler(ScmVM *vm, ScmObj before, ScmObj after, ScmObj args)
2476 {
2477 ScmDynamicHandler *e = SCM_NEW(ScmDynamicHandler);
2478 SCM_SET_CLASS(e, SCM_CLASS_DYNAMIC_HANDLER);
2479 e->before = before;
2480 e->after = after;
2481 e->denv = vm->denv;
2482 e->args = args;
2483 return SCM_OBJ(e);
2484 }
2485
2486 /* Handler-chain internal API */
2487 static ScmObj get_dynamic_handlers(ScmVM *vm)
2488 {
2489 return vm->dynamicHandlers;
2490 }
2491
2492 static void set_dynamic_handlers(ScmVM *vm, ScmObj handlers)
2493 {
2494 vm->dynamicHandlers = handlers;
2495 }
2496
2497 static ScmObj push_dynamic_handlers(ScmVM *vm,
2498 ScmObj before, ScmObj after, ScmObj args)
2499 {
2500 ScmObj entry = make_dynamic_handler(vm, before, after, args);
2501 set_dynamic_handlers(vm, Scm_Cons(entry, get_dynamic_handlers(vm)));
2502 return entry;
2503 }
2504
2505 static ScmObj pop_dynamic_handlers(ScmVM *vm)
2506 {
2507 ScmObj handlers = get_dynamic_handlers(vm);
2508 SCM_ASSERT(SCM_PAIRP(handlers));
2509 set_dynamic_handlers(vm, SCM_CDR(handlers));
2510 return SCM_CAR(handlers);
2511 }
2512
2513 static void call_before_thunk(ScmVM *vm, ScmObj handler_entry)
2514 {
2515 SCM_ASSERT(SCM_DYNAMIC_HANDLER_P(handler_entry));
2516 ScmDynamicHandler *dh = SCM_DYNAMIC_HANDLER(handler_entry);
2517 vm->denv = dh->denv;
2518 if (!SCM_FALSEP(dh->before)) {
2519 Scm_ApplyRec(dh->before, dh->args);
2520 }
2521 }
2522
2523 static void call_after_thunk(ScmVM *vm, ScmObj handler_entry)
2524 {
2525 SCM_ASSERT(SCM_DYNAMIC_HANDLER_P(handler_entry));
2526 ScmDynamicHandler *dh = SCM_DYNAMIC_HANDLER(handler_entry);
2527 vm->denv = dh->denv;
2528 Scm_ApplyRec(dh->after, dh->args);
2529 }
2530
2531 static ScmObj vm_call_before_thunk(ScmVM *vm, ScmObj handler_entry)
2532 {
2533 SCM_ASSERT(SCM_DYNAMIC_HANDLER_P(handler_entry));
2534 ScmDynamicHandler *dh = SCM_DYNAMIC_HANDLER(handler_entry);
2535 vm->denv = dh->denv;
2536 if (!SCM_FALSEP(dh->before)) {
2537 return Scm_VMApply(dh->before, dh->args);
2538 } else {
2539 return SCM_UNDEFINED;
2540 }
2541 }
2542
2543 static ScmObj vm_call_after_thunk(ScmVM *vm, ScmObj handler_entry)
2544 {
2545 SCM_ASSERT(SCM_DYNAMIC_HANDLER_P(handler_entry));
2546 ScmDynamicHandler *dh = SCM_DYNAMIC_HANDLER(handler_entry);
2547 vm->denv = dh->denv;
2548 return Scm_VMApply(dh->after, dh->args);
2549 }
2550 /* End of handler-chain internal API */
2551
2552 /* public api */
2553 void Scm_VMPushDynamicHandlers(ScmObj before, ScmObj after, ScmObj args)
2554 {
2555 push_dynamic_handlers(theVM, before, after, args);
2556 }
2557
2558 ScmObj Scm_VMGetDynamicHandlers()
2559 {
2560 return get_dynamic_handlers(theVM);
2561 }
2562
2563 void Scm_VMSetDynamicHandlers(ScmObj handlers)
2564 {
2565 set_dynamic_handlers(theVM, handlers);
2566 }
2567
2568 /*
2569 * dynamic-wind
2570 *
2571 * For Scheme code, dynamic-wind is inline-expanded into VM insns.
2572 * The C implemnetation, Scm_VMDynamicWind may be invoked when
2573 * dynamic-wind is called via apply, or directly from C code.
2574 *
2575 * 'Before' handlerscan be SCM_FALSE if it doesn't
2576 * need to do anything. We can do a bit of optimization then.
2577 */
2578
2579 static ScmPContinuationProc dynwind_before_cc;
2580 static ScmPContinuationProc dynwind_body_cc;
2581 static ScmPContinuationProc dynwind_after_cc;
2582
2583 ScmObj Scm_VMDynamicWind(ScmObj before, ScmObj body, ScmObj after)
2584 {
2585 ScmVM *vm = Scm_VM();
2586 /* NB: we don't check types of arguments, since they can be non-procedure
2587 objects with object-apply hooks. */
2588
2589 if (SCM_FALSEP(before)) {
2590 /* we can skip application of 'before' */
2591 ScmObj data[3];
2592 data[0] = before;
2593 data[1] = body;
2594 data[2] = after;
2595 return dynwind_before_cc(vm, SCM_UNDEFINED, data);
2596 } else {
2597 ScmObj *data = Scm_pc_PushCC(vm, dynwind_before_cc, 3);
2598 data[0] = before;
2599 data[1] = body;
2600 data[2] = after;
2601 return Scm_VMApply0(before);
2602 }
2603 }
2604
2605 static ScmObj dynwind_before_cc(ScmVM *vm,
2606 ScmObj result SCM_UNUSED,
2607 ScmObj *data)
2608 {
2609 ScmObj before = data[0];
2610 ScmObj body = data[1];
2611 ScmObj after = data[2];
2612
2613 ScmObj dhentry = push_dynamic_handlers(vm, before, after, SCM_NIL);
2614 ScmObj *d = push_dynamic_handler_cc(vm, dynwind_body_cc, dhentry, 1);
2615 d[0] = after;
2616 return Scm_VMApply0(body);
2617 }
2618
2619 static ScmObj dynwind_body_cc(ScmVM *vm, ScmObj result, ScmObj *data)
2620 {
2621 ScmObj after = data[0];
2622
2623 pop_dynamic_handlers(vm);
2624
2625 /* Save return values.
2626 We could avoid malloc when numVals is small (we can push
2627 them directly onto the stack). But our benchmark showed doing so
2628 actually gets slightly slower. More branches may have a negative
2629 effect. So we keep it simple here.
2630 */
2631 int nvals = vm->numVals;
2632 if (nvals > 1) {
2633 ScmObj *vals = SCM_NEW_ARRAY(ScmObj, nvals-1);
2634 memcpy(vals, vm->vals, sizeof(ScmObj)*(nvals-1));
2635 ScmObj *d = Scm_pc_PushCC(vm, dynwind_after_cc, 3);
2636 d[0] = result;
2637 d[1] = SCM_OBJ((intptr_t)nvals);
2638 d[2] = SCM_OBJ(vals);
2639 } else {
2640 ScmObj *d = Scm_pc_PushCC(vm, dynwind_after_cc, 2);
2641 d[0] = result;
2642 d[1] = SCM_OBJ((intptr_t)nvals);
2643 }
2644 return Scm_VMApply0(after);
2645 }
2646
2647 static ScmObj dynwind_after_cc(ScmVM *vm, ScmObj result SCM_UNUSED,
2648 ScmObj *data)
2649 {
2650 /* Restore return values. */
2651 ScmObj val0 = SCM_OBJ(data[0]);
2652 int nvals = (int)(intptr_t)data[1];
2653 vm->numVals = nvals;
2654 if (nvals > 1) {
2655 ScmObj *vals = (ScmObj*)data[2];
2656 SCM_ASSERT(nvals <= SCM_VM_MAX_VALUES);
2657 memcpy(vm->vals, vals, sizeof(ScmObj)*(nvals-1));
2658 }
2659 return val0;
2660 }
2661
2662 /*=================================================================
2663 * Exception handling
2664 */
2665
2666 /* Conceptually, exception handling is nothing more than a particular
2667 * combination of dynamic-wind and call/cc. Gauche implements a parts
2668 * of it in C so that it will be efficient and safer to use.
2669 *
2670 * The most basic layer consists of these two functions:
2671 *
2672 * with-exception-handler
2673 * raise
2674 *
2675 * There is a slight problem, though. These two functions are defined
2676 * both in srfi-18 (multithreads) and srfi-34 (exception handling), and
2677 * two disagrees in the semantics of raise.
2678 *
2679 * Srfi-18 requires an exception handler to be called with the same dynamic
2680 * environment as the one of the primitive that raises the exception.
2681 * That means when an exception handler is running, the current
2682 * exception handler is the running handler itself. Naturally, calling
2683 * raise unconditionally within the exception handler causes infinite loop.
2684 *
2685 * Srfi-34 says that an exception handler is called with the same dynamic
2686 * environment where the exception is raised, _except_ that the current
2687 * exception handler is "popped", i.e. when an exception handler is running,
2688 * the current exception handler is the "outer" or "old" one. Calling
2689 * raise within an exception handler passes the control to the outer
2690 * exception handler.
2691 *
2692 * We used to follow srfi-18 model, for it is more "primitive". However,
2693 * R7RS adopted srfi-34 model, and there were enough confusions on entering
2694 * infinite loop, so we swithec to the srfi-34 model.
2695 * See Scm_VMThrowException.
2696 *
2697 * The following is a model of the current implementation, sans the messy
2698 * part of handling C stacks. The exception handler chain is stored in
2699 * the dynamic environment. Suppose %get-current-xhs retrieves the current
2700 * exception handler chain, and (%with-xhs new-xhs expr) calls expr with
2701 * new-xhs as the exception handler chain.
2702 *
2703 * (define (current-exception-handler)
2704 * (car (%get-current-xhs)))
2705 *
2706 * (define (raise exn)
2707 * (let1 xhs (%get-current-xhs)
2708 * (receive r ((car xhs) exn)
2709 * (when (uncontinuable-exception? exn)
2710 * (%with-xhs (cdr xhs)
2711 * (error "returned from uncontinuable exception")))
2712 * (apply values r))))
2713 *
2714 * (define (with-exception-handler handler thunk)
2715 * (%with-xhs (cons handler (%get-current-xhs))
2716 * (thunk)))
2717 *
2718 * Note that this model assumes an exception handler returns unless it
2719 * explicitly invokes continuation captured elsewhere. In reality,
2720 * "error" exceptions are not supposed to return (hence it is checked
2721 * in raise). Gauche provides another useful exception handling
2722 * constructs that automates such continuation capturing. It can be
2723 * explained by the following code.
2724 *
2725 * (define (with-error-handler handler thunk)
2726 * (call/cc
2727 * (lambda (cont)
2728 * (let ((prev-handler (current-exception-handler)))
2729 * (with-exception-handler
2730 * (lambda (exn)
2731 * (if (error? exn)
2732 * (call-with-values (handler exn) cont)
2733 * (prev-handler exn)))
2734 * thunk)))))
2735 *
2736 * In the actual implementation,
2737 *
2738 * - No "real" continuation procedure is created, but a lightweight
2739 * mechanism is used. The lightweight mechanism is similar to
2740 * "one-shot" callback (call/1cc in Chez Scheme).
2741 * - The error handler chain is kept in vm->escapePoint
2742 * - There are messy lonjmp/setjmp stuff involved to keep C stack sane.
2743 */
2744
2745 static ScmObj handle_escape(ScmObj e, ScmEscapePoint *ep)
2746 {
2747 ScmVM *vm = theVM;
2748
2749 ScmObj vmhandlers = get_dynamic_handlers(vm);
2750 ScmObj result = SCM_FALSE, rvals[SCM_VM_MAX_VALUES];
2751 int numVals = 0;
2752
2753 /* Save continuation chains into heap. This has non-negligible
2754 overhead, but we need to keep all active EPs' cont field valid.
2755 Without this, a complication occurs when save_cont occurs during
2756 executing the error handler and it returns subsequently.
2757 See https://github.com/shirok/Gauche/issues/852 for the details.
2758 */
2759 save_cont(vm);
2760
2761 #if GAUCHE_SPLIT_STACK
2762 vm->lastErrorCont = vm->cont;
2763 vm->stackBase = vm->sp;
2764 #endif
2765
2766 /* To conform SRFI-34, the error handler (clauses in 'guard' form)
2767 should be executed with the same continuation and dynamic
2768 environment of the guard form itself. That means the dynamic
2769 handlers should be rewound before we invoke the guard clause.
2770
2771 If an error is raised within the dynamic handlers, it will be
2772 captured by the same error handler. */
2773 if (ep->rewindBefore) {
2774 call_dynamic_handlers(vm, ep->dynamicHandlers,
2775 get_dynamic_handlers(vm));
2776 }
2777
2778 vm->errorHandlerContinuable = FALSE;
2779
2780 result = Scm_ApplyRec(ep->ehandler, SCM_LIST1(e));
2781
2782 /* save return values */
2783 /* NB: for loop is slightly faster than memcpy */
2784 numVals = vm->numVals;
2785 if (numVals > 1) {
2786 for (int i=0; i<numVals-1; i++) rvals[i] = vm->vals[i];
2787 }
2788
2789 /* call dynamic handlers to rewind */
2790 if (!ep->rewindBefore) {
2791 call_dynamic_handlers(vm, ep->dynamicHandlers,
2792 get_dynamic_handlers(vm));
2793 }
2794
2795 /* If exception is reraised, the exception handler can return
2796 to the caller. */
2797 if (vm->errorHandlerContinuable) {
2798 vm->errorHandlerContinuable = FALSE;
2799
2800 /* call dynamic handlers to reenter dynamic-winds */
2801 call_dynamic_handlers(vm, vmhandlers,
2802 get_dynamic_handlers(vm));
2803
2804 /* reraise and return */
2805 Scm_VMPushExceptionHandler(ep->xhandler);
2806 result = Scm_VMThrowException(vm, e, 0);
2807 Scm_VMPushExceptionHandler(DEFAULT_EXCEPTION_HANDLER);
2808 return result;
2809 }
2810
2811 /* restore return values */
2812 vm->val0 = result;
2813 vm->numVals = numVals;
2814 if (numVals > 1) {
2815 for (int i=0; i<numVals-1; i++) vm->vals[i] = rvals[i];
2816 }
2817
2818 /* Install the continuation */
2819 vm->cont = ep->cont;
2820 vm->denv = ep->denv;
2821 if (ep->errorReporting) {
2822 SCM_VM_RUNTIME_FLAG_SET(vm, SCM_ERROR_BEING_REPORTED);
2823 }
2824 /* restore reset-chain for reset/shift */
2825 if (ep->cstack) vm->resetChain = ep->resetChain;
2826
2827 SCM_ASSERT(vm->cstack);
2828 vm->escapeReason = SCM_VM_ESCAPE_ERROR;
2829 vm->escapeData[0] = ep;
2830 vm->escapeData[1] = e;
2831 siglongjmp(vm->cstack->jbuf, 1);
2832 }
2833
2834 static ScmObj handle_escape_subr(ScmObj *argv,
2835 int argc,
2836 void *data)
2837 {
2838 SCM_ASSERT(argc == 1);
2839 return handle_escape(argv[0] /*exc*/, (ScmEscapePoint*)data);
2840 }
2841
2842 ScmObj make_escape_handler(ScmEscapePoint *ep)
2843 {
2844 return Scm_MakeSubr(handle_escape_subr, (void*)ep, 1, 0, SCM_FALSE);
2845 }
2846
2847 /*
2848 * Default exception handler
2849 * This is what we have as the system default.
2850 */
2851
2852 ScmObj Scm_VMDefaultExceptionHandler(ScmObj e)
2853 {
2854 ScmVM *vm = theVM;
2855
2856 /* We don't have an active error handler, so this is the fallback
2857 behavior. Reports the error and rewind dynamic handlers and
2858 C stacks. */
2859 call_error_reporter(e);
2860 /* unwind the dynamic handlers */
2861 ScmObj hp;
2862 SCM_FOR_EACH(hp, get_dynamic_handlers(vm)) {
2863 ScmObj handler_entry = SCM_CAR(hp);
2864 set_dynamic_handlers(vm, SCM_CDR(hp));
2865 call_after_thunk(vm, handler_entry);
2866 }
2867 SCM_ASSERT(vm->cstack);
2868 vm->escapeReason = SCM_VM_ESCAPE_ERROR;
2869 vm->escapeData[0] = NULL;
2870 vm->escapeData[1] = e;
2871 siglongjmp(vm->cstack->jbuf, 1);
2872 }
2873
2874 /* Call error reporter - either the custome one, or the default
2875 Scm_ReportError. We set SCM_ERROR_BEING_REPORTED flag during it
2876 to prevent infinite loop. */
2877 static void call_error_reporter(ScmObj e)
2878 {
2879 ScmVM *vm = theVM;
2880
2881 if (SCM_VM_RUNTIME_FLAG_IS_SET(vm, SCM_ERROR_BEING_REPORTED)) {
2882 /* An _uncaptured_ error occurred during reporting an error.
2883 We can't proceed, for it will cause infinite loop.
2884 Note that it is OK for an error to occur inside the error
2885 reporter, as far as the error is handled by user-installed
2886 handler. The user-installed handler can even invoke a
2887 continuation that is captured outside; the flag is reset
2888 in such case.
2889 Be careful that it is possible that stderr is no longer
2890 available here (since it may be the very cause of the
2891 recursive error). All we can do is to abort. */
2892 Scm_Abort("Unhandled error occurred during reporting an error. Process aborted.\n");
2893 }
2894
2895 SCM_VM_RUNTIME_FLAG_SET(vm, SCM_ERROR_BEING_REPORTED);
2896 SCM_UNWIND_PROTECT {
2897 if (SCM_PROCEDUREP(vm->customErrorReporter)) {
2898 Scm_ApplyRec(vm->customErrorReporter, SCM_LIST1(e));
2899 } else {
2900 Scm_ReportError(e, SCM_OBJ(SCM_CURERR));
2901 }
2902 }
2903 SCM_WHEN_ERROR {
2904 /* NB: this is called when a continuation captured outside is
2905 invoked inside the error reporter. It may be invoked by
2906 the user's error handler. */
2907 SCM_VM_RUNTIME_FLAG_CLEAR(vm, SCM_ERROR_BEING_REPORTED);
2908 }
2909 SCM_END_PROTECT;
2910 SCM_VM_RUNTIME_FLAG_CLEAR(vm, SCM_ERROR_BEING_REPORTED);
2911 }
2912
2913 static ScmObj default_exception_handler_body(ScmObj *argv,
2914 int argc,
2915 void *data SCM_UNUSED)
2916 {
2917 SCM_ASSERT(argc == 1);
2918 return Scm_VMDefaultExceptionHandler(argv[0]);
2919 }
2920
2921 static SCM_DEFINE_STRING_CONST(default_exception_handler_name,
2922 "default-exception-handler",
2923 25, 25); /* strlen("default-exception-handler") */
2924 static SCM_DEFINE_SUBR(default_exception_handler_rec, 1, 0,
2925 SCM_OBJ(&default_exception_handler_name),
2926 default_exception_handler_body, NULL, NULL);
2927
2928 /*
2929 * Entry point of throwing exception.
2930 *
2931 * This function can be called from Scheme function raise,
2932 * or C-function Scm_Error families and signal handler.
2933 * So there may be a raw C code in the continuation of this C call.
2934 * Thus we can't use Scm_VMApply to call the user-defined exception
2935 * handler.
2936 * Note that this function may return.
2937 */
2938 ScmObj Scm_VMThrowException(ScmVM *vm, ScmObj exception, u_long raise_flags)
2939 {
2940 SCM_VM_RUNTIME_FLAG_CLEAR(vm, SCM_ERROR_BEING_HANDLED);
2941
2942 /* SRFI-34/R7RS semantics - we invoke exception handler while the handler
2943 chain is popped. */
2944 ScmObj eh = Scm_VMPopExceptionHandler();
2945
2946 if (eh != DEFAULT_EXCEPTION_HANDLER) {
2947 vm->val0 = Scm_ApplyRec(eh, SCM_LIST1(exception));
2948 if (SCM_SERIOUS_CONDITION_P(exception)
2949 || raise_flags&SCM_RAISE_NON_CONTINUABLE) {
2950 Scm_Error("user-defined exception handler returned on non-continuable exception %S", exception);
2951 }
2952 /* Continuable exception. Recover exception handler settings. */
2953 Scm_VMPushExceptionHandler(eh);
2954 return vm->val0;
2955 }
2956 return Scm_VMDefaultExceptionHandler(exception);
2957 }
2958
2959 /*
2960 * with-error-handler
2961 */
2962 static ScmObj discard_ehandler(ScmObj *args SCM_UNUSED,
2963 int nargs SCM_UNUSED,
2964 void *data)
2965 {
2966 /* restore floatingEscapePoints when necessary */
2967 ScmObj eps = SCM_OBJ(data);
2968 if (SCM_PAIRP(eps)) {
2969 ScmVM *vm = theVM;
2970 ScmContFrame *c = SCM_ESCAPE_POINT(SCM_CAR(eps))->cont;
2971 if (IN_STACK_P((ScmObj*)c)) {
2972 /* Those cont frames are not saved yet, so keep them
2973 in the chain. */
2974 theVM->floatingEscapePoints = eps;
2975 }
2976 }
2977 return SCM_UNDEFINED;
2978 }
2979
2980 static ScmObj with_error_handler(ScmVM *vm, ScmObj handler,
2981 ScmObj thunk, int rewindBefore)
2982 {
2983 ScmEscapePoint *ep = new_ep(vm, handler, rewindBefore,
2984 SCM_FALSE, SCM_FALSE);
2985
2986 ScmObj ehandler = make_escape_handler(ep);
2987 Scm_VMPushExceptionHandler(ehandler);
2988 SCM_VM_RUNTIME_FLAG_CLEAR(theVM, SCM_ERROR_BEING_REPORTED);
2989 ScmObj prev_fep = vm->floatingEscapePoints;
2990 vm->floatingEscapePoints = Scm_Cons(SCM_OBJ(ep), prev_fep);
2991 ScmObj after = Scm_MakeSubr(discard_ehandler, prev_fep, 0, 0, SCM_FALSE);
2992 return Scm_VMDynamicWind(SCM_FALSE, thunk, after);
2993 }
2994
2995 ScmObj Scm_VMWithErrorHandler(ScmObj handler, ScmObj thunk)
2996 {
2997 return with_error_handler(theVM, handler, thunk, FALSE);
2998 }
2999
3000 ScmObj Scm_VMWithGuardHandler(ScmObj handler, ScmObj thunk)
3001 {
3002 return with_error_handler(theVM, handler, thunk, TRUE);
3003 }
3004
3005 ScmObj Scm_VMReraise()
3006 {
3007 theVM->errorHandlerContinuable = TRUE;
3008 return SCM_UNDEFINED;
3009 }
3010
3011 /*
3012 * Returns internal denv keys (internal API)
3013 * These keys are uninterned symbols so that they wouldn't conflict
3014 * with user provided keys.
3015 */
3016 ScmObj Scm__GetDenvKey(ScmDenvKeyName name)
3017 {
3018 switch (name) {
3019 case SCM_DENV_KEY_EXCEPTION_HANDLER:
3020 return denv_key_exception_handler;
3021 case SCM_DENV_KEY_DYNAMIC_HANDLER:
3022 return denv_key_dynamic_handler;
3023 case SCM_DENV_KEY_PARAMETERIZATION:
3024 return denv_key_parameterization;
3025 case SCM_DENV_KEY_EXPRESSION_NAME:
3026 return denv_key_expression_name;
3027 }
3028 return SCM_UNDEFINED; /* dummy */
3029 }
3030
3031 /*
3032 * Exception handlers
3033 *
3034 * This primitive gives the programmer whole responsibility of
3035 * dealing with exceptions.
3036 *
3037 * Exception handler chain is kept in DENV, with the key
3038 * denv_key_exception_handler. Its value is a pair,
3039 * (<handler> . <prev-entry>) where <prev-entry> points to the
3040 * previous entry or ().
3041 */
3042
3043 ScmObj Scm_VMCurrentExceptionHandler()
3044 {
3045 ScmObj entry = Scm_VMFindDynamicEnv(denv_key_exception_handler, SCM_NIL);
3046 if (SCM_PAIRP(entry)) return SCM_CAR(entry);
3047 else return DEFAULT_EXCEPTION_HANDLER;
3048 }
3049
3050 ScmObj Scm_VMExceptionHandlerStack()
3051 {
3052 ScmObj entry = Scm_VMFindDynamicEnv(denv_key_exception_handler, SCM_NIL);
3053 return Scm_CopyList(entry);
3054 }
3055
3056 void Scm_VMPushExceptionHandler(ScmObj handler)
3057 {
3058 ScmObj prev = Scm_VMFindDynamicEnv(denv_key_exception_handler, SCM_NIL);
3059 Scm_VMPushDynamicEnv(denv_key_exception_handler,
3060 Scm_Cons(handler, prev));
3061 }
3062
3063 /* Set the current exception handler to the 'previous' one, returning
3064 the current handler.
3065 Note that this does not actually 'pop' the DENV; instead, we push the
3066 previous entry in DENV.
3067 */
3068 ScmObj Scm_VMPopExceptionHandler()
3069 {
3070 ScmObj current = Scm_VMFindDynamicEnv(denv_key_exception_handler, SCM_NIL);
3071 if (SCM_PAIRP(current)) {
3072 ScmObj h = SCM_CAR(current);
3073 Scm_VMPushDynamicEnv(denv_key_exception_handler, SCM_CDR(current));
3074 return h;
3075 } else {
3076 return DEFAULT_EXCEPTION_HANDLER;
3077 }
3078 }
3079
3080 ScmObj Scm_VMWithExceptionHandler(ScmObj handler, ScmObj thunk)
3081 {
3082 Scm_VMPushExceptionHandler(handler);
3083 return Scm_VMApply0(thunk);
3084 }
3085
3086 /*==============================================================
3087 * Continuation prompt tag
3088 */
3089
3090 #define DEFAULT_PROMPT_TAG_NAME "default-prompt-tag"
3091 static ScmString defaultPromptTagName =
3092 SCM_STRING_CONST_INITIALIZER(DEFAULT_PROMPT_TAG_NAME,
3093 sizeof(DEFAULT_PROMPT_TAG_NAME)-1,
3094 sizeof(DEFAULT_PROMPT_TAG_NAME)-1);
3095
3096 static void init_prompt_tag(ScmPromptTag *tag, ScmObj name)
3097 {
3098 SCM_SET_CLASS(tag, SCM_CLASS_PROMPT_TAG);
3099 tag->name = name;
3100 tag->insn = SCM_VM_INSN(SCM_VM_RET);
3101 }
3102
3103 ScmObj Scm_MakePromptTag(ScmObj name)
3104 {
3105 ScmPromptTag *pt = SCM_NEW(ScmPromptTag);
3106 init_prompt_tag(pt, name);
3107 return SCM_OBJ(pt);
3108 }
3109
3110 ScmObj Scm_DefaultPromptTag()
3111 {
3112 return SCM_OBJ(&defaultPromptTag);
3113 }
3114
3115 /*==============================================================
3116 * Continuation prompts
3117 */
3118
3119 ScmObj Scm_VMCallWithContinuationPrompt(ScmObj thunk,
3120 ScmObj promptTag,
3121 ScmObj abortHandler)
3122 {
3123 if (SCM_FALSEP(promptTag)) promptTag = Scm_DefaultPromptTag();
3124 else if (!SCM_PROMPT_TAG_P(promptTag)) {
3125 SCM_TYPE_ERROR(promptTag, "prompt tag or #f");
3126 }
3127
3128 push_prompt_cont(Scm_VM(), promptTag, abortHandler);
3129 return Scm_VMApply0(thunk);
3130 }
3131
3132 static ScmContFrame *find_prompt_frame(ScmVM *vm, ScmObj promptTag)
3133 {
3134 if (!SCM_PROMPT_TAG(promptTag)) promptTag = SCM_OBJ(&defaultPromptTag);
3135 ScmWord *pc = SCM_PROMPT_TAG_PC(promptTag);
3136 for (ScmContFrame *c = vm->cont; c; c = c->prev) {
3137 if (c->pc == pc) {
3138 return c;
3139 }
3140 }
3141 return NULL;
3142 }
3143
3144
3145 static ScmObj vm_abort_cc(ScmObj val0, void *data[]);
3146
3147 static ScmObj call_abort_handler(ScmObj abortHandler, ScmObj args)
3148 {
3149 if (SCM_FALSEP(abortHandler)) {
3150 if (!(Scm_Length(args) == 1
3151 && SCM_PROCEDUREP(SCM_CAR(args))
3152 && SCM_PROCEDURE_REQUIRED(SCM_CAR(args)) == 0)) {
3153 Scm_Error("default abort-handler requires exactly one argument, "
3154 "which must be a thunk, but got: %S", args);
3155 }
3156 return Scm_VMApply0(SCM_CAR(args));
3157 } else {
3158 /* TODO: In this case, we should run abortHandler _after_ the
3159 abortTo frame is popped. We need some more tweaks to realize it.
3160 */
3161 return Scm_VMApply(abortHandler, args);
3162 }
3163 }
3164
3165 static ScmObj vm_abort_body(ScmContFrame *abortTo, ScmObj args)
3166 {
3167 ScmPromptData *pd = (ScmPromptData*)abortTo->cpc;
3168 ScmObj abortHandler = pd->abortHandler;
3169 return call_abort_handler(abortHandler, args);
3170 }
3171
3172 static ScmObj vm_abort_cc(ScmObj val0 SCM_UNUSED, void *data[])
3173 {
3174 ScmContFrame *abortTo = data[0];
3175 ScmPromptData *pd = (ScmPromptData*)abortTo->cpc;
3176 ScmObj targetHandlers = pd->dynamicHandlers;
3177 ScmVM *vm = theVM;
3178 ScmObj currentHandlers = get_dynamic_handlers(vm);
3179 if (targetHandlers != currentHandlers && SCM_PAIRP(currentHandlers)) {
3180 Scm_VMPushCC(vm_abort_cc, data, 2);
3181 ScmObj handler_entry = pop_dynamic_handlers(vm);
3182 return vm_call_after_thunk(vm, handler_entry);
3183 } else {
3184 ScmObj args = SCM_OBJ(data[1]);
3185 return vm_abort_body(abortTo, args);
3186 }
3187 }
3188
3189
3190 ScmObj Scm_VMAbortCurrentContinuation(ScmObj promptTag, ScmObj args)
3191 {
3192 if (!(SCM_PROMPT_TAG_P(promptTag) || SCM_FALSEP(promptTag))) {
3193 SCM_TYPE_ERROR(promptTag, "prompt tag or #f");
3194 }
3195 ScmVM *vm = theVM;
3196 ScmContFrame *abortTo = find_prompt_frame(vm, promptTag);
3197 if (abortTo == NULL) {
3198 Scm_RaiseCondition(SCM_OBJ(SCM_CLASS_CONTINUATION_ERROR),
3199 "prompt-tag", promptTag,
3200 SCM_RAISE_CONDITION_MESSAGE,
3201 "Attempt to abort to stale prompt tag: %S",
3202 promptTag);
3203 }
3204
3205 ScmPromptData *pd = (ScmPromptData*)abortTo->cpc;
3206 SCM_ASSERT(pd->dummy == SCM_VM_INSN(SCM_VM_RET));
3207 ScmObj targetHandlers = pd->dynamicHandlers;
3208
3209 /* Discard continuation up to abortTo frame. */
3210 CONT = abortTo;
3211
3212 ScmObj currentHandlers = get_dynamic_handlers(vm);
3213 if (targetHandlers != currentHandlers && SCM_PAIRP(currentHandlers)) {
3214 ENSURE_SAVE_CONT(abortTo);
3215
3216 void *data[2];
3217 data[0] = abortTo;
3218 data[1] = args;
3219 Scm_VMPushCC(vm_abort_cc, data, 2);
3220 ScmObj handler_entry = pop_dynamic_handlers(vm);
3221 return vm_call_after_thunk(vm, handler_entry);
3222 } else {
3223 return vm_abort_body(abortTo, args);
3224 }
3225 }
3226
3227 /*
3228 * Continuation marks
3229 */
3230
3231 SCM_DEFINE_BUILTIN_CLASS(Scm_ContinuationMarkSetClass,
3232 NULL, NULL, NULL, NULL,
3233 SCM_CLASS_OBJECT_CPL);
3234
3235 static ScmObj make_continuation_mark_set(ScmVM *vm,
3236 ScmContFrame *cont,
3237 ScmObj denv,
3238 ScmObj promptTag)
3239 {
3240 if (!SCM_PROMPT_TAG_P(promptTag)) promptTag = SCM_OBJ(&defaultPromptTag);
3241
3242 ScmContFrame *bottom = find_prompt_frame(vm, promptTag);
3243 if (bottom == NULL) {
3244 Scm_RaiseCondition(SCM_OBJ(SCM_CLASS_CONTINUATION_ERROR),
3245 "prompt-tag", promptTag,
3246 SCM_RAISE_CONDITION_MESSAGE,
3247 "Stale prompt tag: %S",
3248 promptTag);
3249 }
3250
3251 ScmContinuationMarkSet *cm = SCM_NEW(ScmContinuationMarkSet);
3252 SCM_SET_CLASS(cm, SCM_CLASS_CONTINUATION_MARK_SET);
3253 cm->cont = cont;
3254 cm->denv = denv;
3255 cm->bottomDenv = bottom->denv;
3256 return SCM_OBJ(cm);
3257 }
3258
3259 ScmObj Scm_ContinuationMarks(ScmObj contProc, ScmObj promptTag)
3260 {
3261 if (!Scm_ContinuationP(contProc)) {
3262 SCM_TYPE_ERROR(contProc, "continuation");
3263 }
3264 ScmEscapePoint *ep = (ScmEscapePoint*)SCM_SUBR(contProc)->data;
3265 ScmContFrame *cont = ep->cont;
3266 return make_continuation_mark_set(theVM, cont, ep->denv, promptTag);
3267 }
3268
3269
3270 ScmObj Scm_CurrentContinuationMarks(ScmObj promptTag)
3271 {
3272 ScmVM *vm = theVM;
3273 save_cont(vm);
3274 return make_continuation_mark_set(vm, CONT, DENV, promptTag);
3275 }
3276
3277 ScmObj Scm_ContinuationMarkSetToList(const ScmContinuationMarkSet *cmset,
3278 ScmObj key, ScmObj promptTag)
3279 {
3280 if (!SCM_PROMPT_TAG_P(promptTag)) promptTag = SCM_OBJ(&defaultPromptTag);
3281 if (cmset == NULL) {
3282 cmset = SCM_CONTINUATION_MARK_SET(Scm_CurrentContinuationMarks(promptTag));
3283 }
3284
3285 ScmObj h = SCM_NIL, t = SCM_NIL;
3286 ScmContFrame *c = cmset->cont;
3287 ScmObj p = cmset->denv;
3288
3289 while (c && c->denv == p) {
3290 /* no new marks in the current frame */
3291 c = c->prev;
3292 }
3293 while (SCM_PAIRP(p)) {
3294 if (p == cmset->bottomDenv) break;
3295 /* TODO: Bail out if we hit promptTag */
3296 if (SCM_CAAR(p) == key) {
3297 SCM_APPEND1(h, t, SCM_CDAR(p));
3298 /* skip to the next continuation frame */
3299 if (c == NULL) break;
3300 for (p = SCM_CDR(p); SCM_PAIRP(p); p = SCM_CDR(p)) {
3301 if (c->denv == p) {
3302 do {
3303 c = c->prev;
3304 } while (c && c->denv == p);
3305 break;
3306 }
3307 }
3308 continue;
3309 } else {
3310 p = SCM_CDR(p);
3311 }
3312 }
3313 return h;
3314 }
3315
3316 /*==============================================================
3317 * Call With Current Continuation
3318 */
3319
3320 /* Figure out which before and after thunk should be called.
3321
3322 In general, handler chains consist a tree. For example,
3323 we capture a continuatoin at the chain F, then we the chain
3324 was popped to C, and we create other chains. Now we want to
3325 invoke the captured continuation. We have a handler tree like this:
3326
3327
3328 current -> I -- H -- G
3329 \
3330 C -- B -- A
3331 /
3332 target -> F -- E -- D
3333
3334
3335 Here, target is the captured continuation's chain, and current is
3336 the current head of the chain.
3337
3338 We have to call the following handlers in this order:
3339
3340 I's after handler
3341 H's after handler
3342 G's after handler
3343 D's before handler
3344 E's before handler
3345 F's before handler
3346
3347 Returns a <handler-differential-list>, or <hdlist>, which is a list of
3348 (flag . <handler-chain>)
3349 The flag indicates which of 'before' or 'after' handler should be called,
3350 and also how the handler chain shoud be updated.
3351
3352 If the flag is #f, the handler chain is set with CDR of
3353 <handler-chain>, then the AFTER handler of the CAR of <handler-chain>
3354 is called.
3355
3356 If the flag is #t, the BEFORE handler of the CAR of <handler-chain>
3357 is called, then the vm's handler chain is set to <handler-chain>.
3358 */
3359 static ScmObj throw_cont_calculate_handlers(ScmObj target, ScmObj current)
3360 {
3361 ScmObj h = SCM_NIL, t = SCM_NIL, p;
3362 ScmObj h2 = SCM_NIL;
3363
3364 /* shortcut */
3365 if (target == current) return SCM_NIL;
3366
3367 SCM_FOR_EACH(p, current) {
3368 SCM_ASSERT(SCM_DYNAMIC_HANDLER_P(SCM_CAR(p)));
3369 if (!SCM_FALSEP(Scm_Memq(SCM_CAR(p), target))) break;
3370 /* push 'after' handlers to be called */
3371 SCM_APPEND1(h, t, Scm_Cons(SCM_FALSE, p));
3372 }
3373 SCM_FOR_EACH(p, target) {
3374 SCM_ASSERT(SCM_DYNAMIC_HANDLER_P(SCM_CAR(p)));
3375 if (!SCM_FALSEP(Scm_Memq(SCM_CAR(p), current))) break;
3376 /* push 'before' handlers to be called */
3377 h2 = Scm_Cons(Scm_Cons(SCM_TRUE, p), h2);
3378 }
3379 SCM_APPEND(h, t, h2);
3380 return h;
3381 }
3382
3383 static void call_dynamic_handlers(ScmVM *vm, ScmObj target, ScmObj current)
3384 {
3385 ScmObj hdlist = throw_cont_calculate_handlers(target, current);
3386 ScmObj p;
3387 SCM_FOR_EACH(p, hdlist) {
3388 ScmObj before_flag = SCM_CAAR(p);
3389 ScmObj chain = SCM_CDAR(p);
3390 ScmObj handler_entry = SCM_CAR(chain);
3391 if (SCM_FALSEP(before_flag)) {
3392 set_dynamic_handlers(vm, SCM_CDR(chain));
3393 call_after_thunk(vm, handler_entry);
3394 } else {
3395 call_before_thunk(vm, handler_entry);
3396 set_dynamic_handlers(vm, chain);
3397 }
3398 }
3399 }
3400
3401 /* This is to execute pending dynamic handlers upon exit.
3402 NB: we ignore errors here. It may not be accurate behavior, though.
3403 (A handler may intentionally raise an error to skip the rest of
3404 handlers). We may change to break from SCM_FOR_EACH in case if
3405 we detect error in Scm_Apply. */
3406 void Scm_VMFlushDynamicHandlers()
3407 {
3408 ScmVM *vm = theVM;
3409 ScmObj hp;
3410 SCM_FOR_EACH(hp, get_dynamic_handlers(vm)) {
3411 ScmObj handler_entry = SCM_CAR(hp);
3412 set_dynamic_handlers(vm, SCM_CDR(hp));
3413 vm->denv = SCM_DYNAMIC_HANDLER(handler_entry)->denv;
3414 ScmObj proc = SCM_DYNAMIC_HANDLER(handler_entry)->after;
3415 ScmObj args = SCM_DYNAMIC_HANDLER(handler_entry)->args;
3416 Scm_Apply(proc, args, NULL);
3417 }
3418 }
3419
3420
3421 static ScmObj throw_cont_cc(ScmObj, void **);
3422
3423 static ScmObj throw_cont_body(ScmObj hdlist, /*((flag . handler-chain)...)*/
3424 ScmEscapePoint *ep, /* target continuation */
3425 ScmObj args) /* args to pass to the
3426 target continuation */
3427 {
3428 void *data[4];
3429 int nargs;
3430 ScmObj ap;
3431 ScmVM *vm = theVM;
3432
3433 /*
3434 * first, check to see if we need to evaluate dynamic handlers.
3435 */
3436 if (SCM_PAIRP(hdlist)) {
3437 SCM_ASSERT(SCM_PAIRP(SCM_CAR(hdlist)));
3438 ScmObj before_flag = SCM_CAAR(hdlist);
3439 ScmObj chain = SCM_CDAR(hdlist);
3440
3441 data[0] = (void*)SCM_CDR(hdlist);
3442 data[1] = (void*)ep;
3443 data[2] = (void*)args;
3444 data[3] = (void*)(SCM_FALSEP(before_flag)? NULL : chain);
3445 Scm_VMPushCC(throw_cont_cc, data, 4);
3446 if (SCM_FALSEP(before_flag)) {
3447 /* after handler */
3448 set_dynamic_handlers(vm, SCM_CDR(chain));
3449 return vm_call_after_thunk(vm, SCM_CAR(chain));
3450 } else {
3451 /* before handler. chain is restored in throw_cont_cc. */
3452 return vm_call_before_thunk(vm, SCM_CAR(chain));
3453 }
3454 }
3455
3456 /*
3457 * If the target continuation is a full continuation, we can abandon
3458 * the current continuation. However, if the target continuation is
3459 * partial, we must return to the current continuation after executing
3460 * the partial continuation. The returning part is handled by
3461 * user_level_inner, but we have to make sure that our current continuation
3462 * won't be overwritten by execution of the partial continuation.
3463 *
3464 * NB: As an exception case, if we'll jump into reset,
3465 * we might reach to the end of partial continuation even though
3466 * the target continuation is a full continuation.
3467 */
3468 if (ep->cstack == NULL || SCM_PAIRP(ep->resetChain)) {
3469 save_cont(vm);
3470 }
3471
3472 /*
3473 * now, install the target continuation
3474 */
3475 vm->pc = PC_TO_RETURN;
3476 vm->cont = ep->cont;
3477 vm->denv = ep->denv;
3478
3479 /* restore reset-chain for reset/shift */
3480 if (ep->cstack) vm->resetChain = ep->resetChain;
3481
3482 nargs = Scm_Length(args);
3483 if (nargs == 1) {
3484 return SCM_CAR(args);
3485 } else if (nargs < 1) {
3486 vm->numVals = 0;
3487 return SCM_UNDEFINED;
3488 } else if (nargs >= SCM_VM_MAX_VALUES) {
3489 Scm_Error("too many values passed to the continuation");
3490 }
3491
3492 ap = SCM_CDR(args);
3493 for (int i=0; SCM_PAIRP(ap); i++, ap=SCM_CDR(ap)) {
3494 vm->vals[i] = SCM_CAR(ap);
3495 }
3496 vm->numVals = nargs;
3497 return SCM_CAR(args);
3498 }
3499
3500 static ScmObj throw_cont_cc(ScmObj result SCM_UNUSED, void **data)
3501 {
3502 ScmVM *vm = theVM;
3503
3504 ScmObj hdlist = SCM_OBJ(data[0]);
3505 ScmEscapePoint *ep = (ScmEscapePoint *)data[1];
3506 ScmObj args = SCM_OBJ(data[2]);
3507 if (data[3]) {
3508 /* restore chain only after 'before' thunk. */
3509 ScmObj chain = SCM_OBJ(data[3]);
3510 set_dynamic_handlers(vm, chain);
3511 }
3512 return throw_cont_body(hdlist, ep, args);
3513 }
3514
3515 /* Body of the continuation SUBR */
3516 static ScmObj throw_continuation(ScmObj *argframe,
3517 int nargs SCM_UNUSED, void *data)
3518 {
3519 ScmEscapePoint *ep = (ScmEscapePoint*)data;
3520 ScmObj args = argframe[0];
3521 ScmVM *vm = theVM;
3522
3523 /* First, check to see if we need to rewind C stack.
3524 NB: If we are invoking a partial continuation (ep->cstack == NULL),
3525 we execute it on the current cstack. */
3526 if (ep->cstack && vm->cstack != ep->cstack) {
3527 ScmCStack *cs;
3528 for (cs = vm->cstack; cs; cs = cs->prev) {
3529 if (ep->cstack == cs) break;
3530 }
3531
3532 /* If the continuation captured below the current C stack, we rewind
3533 to the captured stack first. */
3534 if (cs != NULL) {
3535 vm->escapeReason = SCM_VM_ESCAPE_CONT;
3536 vm->escapeData[0] = ep;
3537 vm->escapeData[1] = args;
3538 siglongjmp(vm->cstack->jbuf, 1);
3539 }
3540 /* If we're here, the continuation is 'ghost'---it was captured on
3541 a C stack that no longer exists, or that was in another thread.
3542 We'll execute the Scheme part of such a ghost continuation
3543 on the current C stack. User_eval_inner will catch if we
3544 ever try to return to the stale C frame.
3545
3546 Note that current vm->cstack chain may point to a continuation
3547 frame in vm stack, so we need to save the continuation chain
3548 first, since vm->cstack may be popped when other continuation
3549 is invoked during the execution of the target one. (We may be
3550 able to save some memory access by checking vm->cstack chain to see
3551 if we really have such a frame, but just calling save_cont is
3552 easier and always safe.)
3553 */
3554 save_cont(vm);
3555 }
3556
3557 /* check reset-chain to avoid the wrong return from partial
3558 continuation */
3559 if (ep->cstack == NULL && !SCM_PAIRP(ep->resetChain)) {
3560 Scm_Error("reset missing.");
3561 }
3562
3563 ScmObj hdlist;
3564 ScmObj currentHandlers = get_dynamic_handlers(vm);
3565 if (ep->cstack) {
3566 /* for full continuation */
3567 hdlist = throw_cont_calculate_handlers(ep->dynamicHandlers,
3568 currentHandlers);
3569 } else {
3570 /* for partial continuation */
3571 hdlist
3572 = throw_cont_calculate_handlers(Scm_Append2(ep->partHandlers,
3573 currentHandlers),
3574 currentHandlers);
3575 }
3576 return throw_cont_body(hdlist, ep, args);
3577 }
3578
3579 ScmObj Scm_VMCallCC(ScmObj proc)
3580 {
3581 ScmVM *vm = theVM;
3582
3583 save_cont(vm);
3584
3585 ScmEscapePoint *ep = new_ep(vm, SCM_FALSE, FALSE, SCM_FALSE, SCM_FALSE);
3586 ScmObj contproc = Scm_MakeSubr(throw_continuation, ep, 0, 1,
3587 continuation_symbol);
3588 return Scm_VMApply1(proc, contproc);
3589 }
3590
3591 int Scm_ContinuationP(ScmObj proc)
3592 {
3593 return (SCM_SUBRP(proc) && SCM_PROCEDURE_INFO(proc) == continuation_symbol);
3594 }
3595
3596 /* call with partial continuation. this corresponds to the 'shift' operator
3597 in shift/reset controls (Gasbichler&Sperber, "Final Shift for Call/cc",
3598 ICFP02.) Note that we treat the boundary frame as the bottom of
3599 partial continuation. */
3600 ScmObj Scm_VMCallPC(ScmObj proc)
3601 {
3602 ScmVM *vm = theVM;
3603
3604 /* save the continuation. we only need to save the portion above the
3605 latest boundary frame (+environmentns pointed from them), but for now,
3606 we save everything to make things easier. If we want to squeeze
3607 performance we'll optimize it later. */
3608 save_cont(vm);
3609
3610 /* find the latest boundary frame */
3611 ScmContFrame *c, *cp;
3612 for (c = vm->cont, cp = NULL;
3613 c && !BOUNDARY_FRAME_P(c);
3614 cp = c, c = c->prev)
3615 /*empty*/;
3616
3617 /* set the end marker of partial continuation */
3618 if (cp && !MARKER_FRAME_P(cp)) {
3619 cp->marker |= SCM_CONT_SHIFT_MARKER;
3620 /* also set the delimited flag in reset information */
3621 if (SCM_PAIRP(vm->resetChain)) {
3622 SCM_SET_CAR_UNCHECKED(SCM_CAR(vm->resetChain), SCM_TRUE);
3623 }
3624 }
3625
3626 /* We need some special setup of EscapePoint for partial continaution.
3627 Hoping these tricks won't be necessary once we ovehauled partcont
3628 handling. */
3629 ScmEscapePoint *ep = new_ep(vm, SCM_FALSE, FALSE, SCM_FALSE, SCM_FALSE);
3630 ep->cont = (cp? vm->cont : NULL);
3631 ep->denv = c? c->denv : (cp? cp->denv : SCM_NIL);
3632 ep->dynamicHandlers = SCM_NIL; /* don't use for partial continuation */
3633 ep->cstack = NULL; /* so that the partial continuation can be run
3634 on any cstack state. */
3635 ep->resetChain = (SCM_PAIRP(vm->resetChain)?
3636 Scm_Cons(Scm_Cons(SCM_FALSE, SCM_NIL), SCM_NIL) :
3637 SCM_NIL); /* used only to detect reset missing */
3638
3639 /* get the dynamic handlers chain saved on reset */
3640 ScmObj reset_handlers = (SCM_PAIRP(vm->resetChain)?
3641 SCM_CDAR(vm->resetChain) : SCM_NIL);
3642
3643 /* cut the dynamic handlers chain from current to reset */
3644 ScmObj h = SCM_NIL, t = SCM_NIL, p;
3645 SCM_FOR_EACH(p, get_dynamic_handlers(vm)) {
3646 if (p == reset_handlers) break;
3647 SCM_APPEND1(h, t, SCM_CAR(p));
3648 }
3649 ep->partHandlers = h;
3650
3651 /* call dynamic handlers for exiting reset */
3652 call_dynamic_handlers(vm, reset_handlers, get_dynamic_handlers(vm));
3653
3654 ScmObj contproc = Scm_MakeSubr(throw_continuation, ep, 0, 1,
3655 continuation_symbol);
3656 /* Remove the saved continuation chain.
3657 NB: vm->cont can be NULL if we've been executing a partial continuation.
3658 It's ok, for a continuation pointed by cstack will be restored
3659 in user_eval_inner.
3660 NB: If the delimited flag in reset information is not set,
3661 we can consider we've been executing a partial continuation. */
3662 if (cp && (SCM_PAIRP(vm->resetChain) &&
3663 SCM_FALSEP(SCM_CAAR(vm->resetChain)))) {
3664 vm->cont = NULL;
3665 } else {
3666 vm->cont = c;
3667 }
3668 vm->denv = c? c->denv : (cp? cp->denv : SCM_NIL);
3669
3670 return Scm_VMApply1(proc, contproc);
3671 }
3672
3673 ScmObj Scm_VMReset(ScmObj proc)
3674 {
3675 ScmVM *vm = theVM;
3676 /* push/pop reset-chain for reset/shift */
3677 vm->resetChain = Scm_Cons(Scm_Cons(SCM_FALSE, get_dynamic_handlers(vm)),
3678 vm->resetChain);
3679 ScmObj ret = Scm_ApplyRec(proc, SCM_NIL);
3680 SCM_ASSERT(SCM_PAIRP(vm->resetChain));
3681 vm->resetChain = SCM_CDR(vm->resetChain);
3682 return ret;
3683 }
3684
3685 /*==============================================================
3686 * Unwind protect API
3687 */
3688
3689 long Scm_VMUnwindProtect(ScmVM *vm, ScmCStack *cstack)
3690 {
3691 cstack->prev = vm->cstack;
3692 cstack->cont = NULL;
3693 vm->cstack = cstack;
3694 return sigsetjmp(cstack->jbuf, FALSE);
3695 }
3696
3697 void Scm_VMNextHandler(ScmVM *vm)
3698 {
3699 if (vm->cstack->prev) {
3700 vm->cstack = vm->cstack->prev;
3701 siglongjmp(vm->cstack->jbuf, 1);
3702 } else {
3703 Scm_Exit(1);
3704 }
3705 }
3706
3707 void Scm_VMRewindProtect(ScmVM *vm)
3708 {
3709 SCM_ASSERT(vm->cstack);
3710 vm->cstack = vm->cstack->prev;
3711 }
3712
3713 /*==============================================================
3714 * Values
3715 */
3716
3717 ScmObj Scm_VMValues(ScmVM *vm, ScmObj args)
3718 {
3719 if (!SCM_PAIRP(args)) {
3720 vm->numVals = 0;
3721 return SCM_UNDEFINED;
3722 }
3723 int nvals = 1;
3724 ScmObj cp;
3725 SCM_FOR_EACH(cp, SCM_CDR(args)) {
3726 vm->vals[nvals-1] = SCM_CAR(cp);
3727 if (nvals++ >= SCM_VM_MAX_VALUES) {
3728 Scm_Error("too many values: %S", args);
3729 }
3730 }
3731 vm->numVals = nvals;
3732 return SCM_CAR(args);
3733 }
3734
3735 ScmObj Scm_Values(ScmObj args)
3736 {
3737 return Scm_VMValues(theVM, args);
3738 }
3739
3740 ScmObj Scm_VMValues2(ScmVM *vm, ScmObj val0, ScmObj val1)
3741 {
3742 vm->numVals = 2;
3743 vm->vals[0] = val1;
3744 return val0;
3745 }
3746
3747 ScmObj Scm_Values2(ScmObj val0, ScmObj val1)
3748 {
3749 return Scm_VMValues2(theVM, val0, val1);
3750 }
3751
3752 ScmObj Scm_VMValues3(ScmVM *vm, ScmObj val0, ScmObj val1, ScmObj val2)
3753 {
3754 vm->numVals = 3;
3755 vm->vals[0] = val1;
3756 vm->vals[1] = val2;
3757 return val0;
3758 }
3759
3760 ScmObj Scm_Values3(ScmObj val0, ScmObj val1, ScmObj val2)
3761 {
3762 return Scm_VMValues3(theVM, val0, val1, val2);
3763 }
3764
3765
3766 ScmObj Scm_VMValues4(ScmVM *vm, ScmObj val0, ScmObj val1,
3767 ScmObj val2, ScmObj val3)
3768 {
3769 vm->numVals = 4;
3770 vm->vals[0] = val1;
3771 vm->vals[1] = val2;
3772 vm->vals[2] = val3;
3773 return val0;
3774 }
3775
3776 ScmObj Scm_Values4(ScmObj val0, ScmObj val1, ScmObj val2, ScmObj val3)
3777 {
3778 return Scm_VMValues4(theVM, val0, val1, val2, val3);
3779 }
3780
3781 ScmObj Scm_VMValues5(ScmVM *vm, ScmObj val0, ScmObj val1,
3782 ScmObj val2, ScmObj val3, ScmObj val4)
3783 {
3784 vm->numVals = 5;
3785 vm->vals[0] = val1;
3786 vm->vals[1] = val2;
3787 vm->vals[2] = val3;
3788 vm->vals[3] = val4;
3789 return val0;
3790 }
3791
3792 ScmObj Scm_Values5(ScmObj val0, ScmObj val1,
3793 ScmObj val2, ScmObj val3, ScmObj val4)
3794 {
3795 return Scm_VMValues5(theVM, val0, val1, val2, val3, val4);
3796 }
3797
3798 ScmObj Scm_VMValuesFromArray(ScmVM *vm, ScmObj *argv, ScmSmallInt argc)
3799 {
3800 if (argc == 0) {
3801 vm->numVals = 0;
3802 return SCM_UNDEFINED;
3803 }
3804 for (ScmSmallInt i=1; i<argc; i++) {
3805 if (i >= SCM_VM_MAX_VALUES) {
3806 Scm_Error("too many values (%d)", argc);
3807 }
3808 vm->vals[i-1] = argv[i];
3809 }
3810 vm->numVals = argc;
3811 return argv[0];
3812 }
3813
3814 ScmObj Scm_ValuesFromArray(ScmObj *argv, ScmSmallInt argc)
3815 {
3816 return Scm_VMValuesFromArray(theVM, argv, argc);
3817 }
3818
3819 /*==================================================================
3820 * Queued handler processing.
3821 */
3822
3823 /* Signal handlers and finalizers are queued in VM when they
3824 * are requested, and processed when VM is in consistent state.
3825 * process_queued_requests() are called near the beginning of
3826 * VM loop, when the VM checks if there's any queued request.
3827 *
3828 * When this procedure is called, VM is in middle of any two
3829 * VM instructions. We need to make sure the handlers won't
3830 * disturb the VM state.
3831 *
3832 * Conceptually, this procedure inserts handler invocations before
3833 * the current continuation.
3834 */
3835
3836 static ScmObj process_queued_requests_cc(ScmObj result SCM_UNUSED, void **data)
3837 {
3838 /* restore the saved continuation of normal execution flow of VM */
3839 ScmVM *vm = theVM;
3840
3841 vm->numVals = (int)(intptr_t)data[0];
3842 vm->val0 = data[1];
3843 if (vm->numVals > 1) {
3844 ScmObj cp = SCM_OBJ(data[2]);
3845 for (int i=0; i<vm->numVals-1; i++) {
3846 vm->vals[i] = SCM_CAR(cp);
3847 cp = SCM_CDR(cp);
3848 }
3849 }
3850 return vm->val0;
3851 }
3852
3853 static void process_queued_requests(ScmVM *vm)
3854 {
3855 void *data[3];
3856
3857 /* preserve the current continuation */
3858 data[0] = (void*)(intptr_t)vm->numVals;
3859 data[1] = vm->val0;
3860 if (vm->numVals > 1) {
3861 ScmObj h = SCM_NIL, t = SCM_NIL;
3862
3863 for (int i=0; i<vm->numVals-1; i++) {
3864 SCM_APPEND1(h, t, vm->vals[i]);
3865 }
3866 data[2] = h;
3867 } else {
3868 data[2] = NULL;
3869 }
3870 Scm_VMPushCC(process_queued_requests_cc, data, 3);
3871
3872 /* NB: it is safe to turn off attentionRequest here; if attentionRequest
3873 is turned on again after this and before SigCheck() or FinalizerRun(),
3874 the new request is processed within these procedures; we'll enter
3875 process_queued_requests() again without anything to process, but
3876 that's an acceptable overhead. */
3877 vm->attentionRequest = FALSE;
3878
3879 /* Process queued stuff. Currently they call VM recursively,
3880 but we'd better to arrange them to be processed in the same
3881 VM level. */
3882 if (vm->signalPending) Scm_SigCheck(vm);
3883 if (vm->finalizerPending) Scm_VMFinalizerRun(vm);
3884
3885 /* VM STOP is required from other thread.
3886 See Scm_ThreadStop() in ext/threads/threads.c */
3887 if (vm->stopRequest) {
3888 SCM_INTERNAL_MUTEX_SAFE_LOCK_BEGIN(vm->vmlock);
3889 switch (vm->stopRequest) {
3890 case 0:
3891 /* stopRequest is canceled between the last check and
3892 LOCK_BEGIN. We do nothing. */
3893 break;
3894 case SCM_VM_REQUEST_SUSPEND:
3895 vm->stopRequest = 0;
3896 vm->state = SCM_VM_STOPPED;
3897 (void)SCM_INTERNAL_COND_BROADCAST(vm->cond);
3898 while (vm->state == SCM_VM_STOPPED) {
3899 /* Here the inspector thread examines VM state */
3900 (void)SCM_INTERNAL_COND_WAIT(vm->cond, vm->vmlock);
3901 }
3902 break;
3903 case SCM_VM_REQUEST_TERMINATE:
3904 vm->state = SCM_VM_TERMINATED;
3905 break;
3906 default:
3907 Scm_Panic("Unknown value in vm->stopRequest (%d). Aborting.",
3908 vm->stopRequest);
3909 }
3910 SCM_INTERNAL_MUTEX_SAFE_LOCK_END();
3911 if (vm->state == SCM_VM_TERMINATED) {
3912 SCM_INTERNAL_THREAD_EXIT(); /* this'll notify vm->cond. */
3913 }
3914 }
3915 }
3916
3917 /*==============================================================
3918 * Debug features.
3919 */
3920
3921 /*
3922 * Stack trace.
3923 *
3924 * The "lite" version returns a list of source information of
3925 * continuation frames.
3926 *
3927 * The full stack trace is consisted by a list of pair of
3928 * source information and environment vector. Environment vector
3929 * is a copy of content of env frame, with the first element
3930 * be the environment info. Environment vector may be #f if
3931 * the continuation frame doesn't have associated env.
3932 */
3933
3934 ScmObj Scm_VMGetStackLite(ScmVM *vm)
3935 {
3936 ScmContFrame *c = vm->cont;
3937 ScmObj stack = SCM_NIL, tail = SCM_NIL;
3938 ScmObj info = Scm_VMGetSourceInfo(vm->base, vm->pc);
3939 if (!SCM_FALSEP(info)) SCM_APPEND1(stack, tail, info);
3940 while (c) {
3941 info = Scm_VMGetSourceInfo(c->base, c->cpc);
3942 if (!SCM_FALSEP(info)) SCM_APPEND1(stack, tail, info);
3943 c = c->prev;
3944 }
3945 return stack;
3946 }
3947
3948 /*
3949 * Call trace
3950 */
3951 void Scm_SetCallTraceSize(u_long size)
3952 {
3953 vm_call_trace_size = size;
3954 }
3955
3956 ScmCallTrace *Scm__MakeCallTraceQueue(u_long size)
3957 {
3958 if (size > CALL_TRACE_SIZE_MAX) size = CALL_TRACE_SIZE_MAX;
3959 else if (size < CALL_TRACE_SIZE_MIN) size = CALL_TRACE_SIZE_MIN;
3960 else {
3961 u_long n = 1;
3962 while (n < size) n <<= 1; /* never overflow as we check the size above */
3963 size = n;
3964 }
3965
3966 ScmCallTrace *ct = SCM_NEW2(ScmCallTrace*,
3967 sizeof(ScmCallTrace)
3968 + (size-1)*sizeof(ScmCallTraceEntry));
3969 ct->size = size;
3970 ct->top = 0;
3971 for (u_long i=0; i<size; i++) {
3972 ct->entries[i].base = NULL;
3973 ct->entries[i].pc = NULL;
3974 }
3975 return ct;
3976 }
3977
3978 ScmCallTrace *Scm__CopyCallTraceQueue(ScmCallTrace *master)
3979 {
3980 u_long size = master->size;
3981 ScmCallTrace *ct = SCM_NEW2(ScmCallTrace*,
3982 sizeof(ScmCallTrace)
3983 + (size-1)*sizeof(ScmCallTraceEntry));
3984 ct->size = size;
3985 ct->top = master->top;
3986 for (u_long i=0; i<size; i++) {
3987 ct->entries[i].base = master->entries[i].base;
3988 ct->entries[i].pc = master->entries[i].pc;
3989 }
3990 return ct;
3991 }
3992
3993 ScmObj Scm_VMGetCallTraceLite(ScmVM *vm)
3994 {
3995 ScmObj trace = SCM_NIL, tail = SCM_NIL;
3996 ScmCallTrace *ct = vm->callTrace;
3997
3998 if (ct) {
3999 ScmObj info = Scm_VMGetSourceInfo(vm->base, vm->pc);
4000 if (!SCM_FALSEP(info)) SCM_APPEND1(trace, tail, info);
4001 for (int i = ct->size - 1; i >= 0; i--) {
4002 int j = (ct->top + i) % ct->size;
4003 info = Scm_VMGetSourceInfo(ct->entries[j].base, ct->entries[j].pc);
4004 if (!SCM_FALSEP(info)) SCM_APPEND1(trace, tail, info);
4005 }
4006 }
4007 return trace;
4008 }
4009
4010 #define DEFAULT_ENV_TABLE_SIZE 64
4011
4012 struct EnvTab {
4013 struct EnvTabEntry {
4014 ScmEnvFrame *env;
4015 ScmObj vec;
4016 } entries[DEFAULT_ENV_TABLE_SIZE];
4017 int numEntries;
4018 };
4019
4020 #if 0 /* for now */
4021 static ScmObj env2vec(ScmEnvFrame *env, struct EnvTab *etab)
4022 {
4023 if (!env) return SCM_FALSE;
4024 for (int i=0; i<etab->numEntries; i++) {
4025 if (etab->entries[i].env == env) {
4026 return etab->entries[i].vec;
4027 }
4028 }
4029 ScmObj vec = Scm_MakeVector((int)env->size+2, SCM_FALSE);
4030 SCM_VECTOR_ELEMENT(vec, 0) = env2vec(env->up, etab);
4031 SCM_VECTOR_ELEMENT(vec, 1) = SCM_NIL; /*Scm_VMGetBindInfo(env->info);*/
4032 for (int i=0; i<env->size; i++) {
4033 SCM_VECTOR_ELEMENT(vec, i+2) = ENV_DATA(env, (env->size-i-1));
4034 }
4035 if (etab->numEntries < DEFAULT_ENV_TABLE_SIZE) {
4036 etab->entries[etab->numEntries].env = env;
4037 etab->entries[etab->numEntries].vec = vec;
4038 etab->numEntries++;
4039 }
4040 return vec;
4041 }
4042 #endif
4043
4044 ScmObj Scm_VMGetStack(ScmVM *vm SCM_UNUSED /* temporary*/)
4045 {
4046 #if 0 /* for now */
4047 ScmContFrame *c = vm->cont;
4048 ScmObj stack = SCM_NIL, tail = SCM_NIL;
4049 ScmObj info, evec;
4050 struct EnvTab envTab;
4051
4052 envTab.numEntries = 0;
4053 if (SCM_PAIRP(vm->pc)) {
4054 info = Scm_VMGetSourceInfo(vm->pc);
4055 SCM_APPEND1(stack, tail, Scm_Cons(info, env2vec(vm->env, &envTab)));
4056 }
4057
4058 for (; c; c = c->prev) {
4059 if (!SCM_PAIRP(c->info)) continue;
4060 info = Scm_VMGetSourceInfo(c->info);
4061 evec = env2vec(c->env, &envTab);
4062 SCM_APPEND1(stack, tail, Scm_Cons(info, evec));
4063 }
4064 return stack;
4065 #endif
4066 return SCM_NIL;
4067 }
4068
4069 /*
4070 * Dump VM internal state.
4071 *
4072 * NB: ScmObj can't be NULL, but Scm_VMDump() may be called on a VM in a broken
4073 * state, so we have checks for it too. If an ScmObj value is NULL, it is
4074 * displayed as #NULL.
4075 */
4076
4077 static ScmObj get_debug_info(ScmCompiledCode *base, SCM_PCTYPE pc)
4078 {
4079 if (base == NULL
4080 || (pc < base->code || pc >= base->code + base->codeSize)) {
4081 return SCM_FALSE;
4082 }
4083
4084 ScmObj di = Scm_CodeDebugInfo(base);
4085 int off = (int)(pc - base->code);
4086 ScmObj ip;
4087 SCM_FOR_EACH(ip, di) {
4088 ScmObj p = SCM_CAR(ip);
4089 if (!SCM_PAIRP(p) || !SCM_INTP(SCM_CAR(p))) continue;
4090 /* PC points to the next instruction,
4091 search for info entry right before it. */
4092 if (SCM_INT_VALUE(SCM_CAR(p)) < off) {
4093 return SCM_CDR(p);
4094 }
4095 }
4096 return SCM_FALSE;
4097 }
4098
4099 ScmObj Scm_VMGetSourceInfo(ScmCompiledCode *base, SCM_PCTYPE pc)
4100 {
4101 ScmObj info = get_debug_info(base, pc);
4102 if (SCM_PAIRP(info)) {
4103 ScmObj p = Scm_Assq(SCM_SYM_SOURCE_INFO, info);
4104 if (SCM_PAIRP(p)) return SCM_CDR(p);
4105 }
4106 return SCM_FALSE;
4107 }
4108
4109 ScmObj Scm_VMGetBindInfo(ScmCompiledCode *base, SCM_PCTYPE pc)
4110 {
4111 ScmObj info = get_debug_info(base, pc);
4112 if (SCM_PAIRP(info)) {
4113 ScmObj p = Scm_Assq(SCM_SYM_BIND_INFO, info);
4114 if (SCM_PAIRP(p)) return SCM_CDR(p);
4115 }
4116 return SCM_FALSE;
4117 }
4118
4119
4120 /* returns next env */
4121 static ScmEnvFrame *dump_env(ScmVM *vm, ScmEnvFrame *env, ScmPort *out)
4122 {
4123 if (env && (IN_STACK_P((ScmObj*)env) || GC_base(env))) {
4124 Scm_Printf(out, " %p %55.1S\n", env, env->info);
4125 Scm_Printf(out, " up=%p size=%d\n", env->up, env->size);
4126 Scm_Printf(out, " [");
4127 for (int i=0; i<env->size; i++) {
4128 if (ENV_DATA(env, i)) {
4129 Scm_Printf(out, " %S", ENV_DATA(env, i));
4130 } else {
4131 Scm_Printf(out, " #NULL");
4132 }
4133 }
4134 Scm_Printf(out, " ]\n");
4135 return env->up;
4136 } else {
4137 Scm_Printf(out, " %p #INVALID\n", env);
4138 return NULL;
4139 }
4140 }
4141
4142 /* Show offset of given PC w.r.t to the beginning of the code of
4143 the current base. Note that PC may not point to the code of the
4144 base. */
4145 static void dump_pc_offset(ScmWord *pc, ScmCompiledCode *base, ScmPort *out)
4146 {
4147 if (base && base->code <= pc && pc < base->code + base->codeSize) {
4148 Scm_Printf(out, "[%5u(%p)]", (u_long)(pc - base->code), base->code);
4149 }
4150 }
4151
4152 static void print_insn(ScmObj insn, ScmPort *out)
4153 {
4154 u_int code = SCM_VM_INSN_CODE(insn);
4155 if (code >= SCM_VM_NUM_INSNS) {
4156 Scm_Printf(out, "invalid insn: %08x", SCM_WORD(insn));
4157 } else {
4158 switch (Scm_VMInsnNumParams(code)) {
4159 case 0:
4160 Scm_Printf(out, "%s", Scm_VMInsnName(code));
4161 break;
4162 case 1:
4163 Scm_Printf(out, "%s(%d)",
4164 Scm_VMInsnName(code), SCM_VM_INSN_ARG(insn));
4165 break;
4166 case 2:
4167 Scm_Printf(out, "%s(%d,%d)",
4168 Scm_VMInsnName(code),
4169 SCM_VM_INSN_ARG0(insn),
4170 SCM_VM_INSN_ARG1(insn));
4171 break;
4172 }
4173 }
4174 }
4175
4176 static void print_insn_paren(ScmObj insn, ScmPort *out)
4177 {
4178 Scm_Printf(out, " (");
4179 print_insn(insn, out);
4180 Scm_Printf(out, ")\n");
4181 }
4182
4183 void Scm_VMDump(ScmVM *vm_to_dump)
4184 {
4185 /* We first take a snapshot of the given VM, so that the act of
4186 dumping won't interfere with the state of the target.
4187 */
4188 ScmVM *vm = Scm_VMTakeSnapshot(vm_to_dump);
4189 ScmPort *out = SCM_CURERR;
4190 ScmEnvFrame *env = vm->env;
4191 ScmContFrame *cont = vm->cont;
4192 ScmCStack *cstk = vm->cstack;
4193
4194 Scm_Printf(out, "VM %p -----------------------------------------------------------\n", vm);
4195 Scm_Printf(out, " pc: %p ", vm->pc);
4196 dump_pc_offset(vm->pc, vm->base, out);
4197 print_insn_paren(SCM_OBJ(*vm->pc), out);
4198 Scm_Printf(out, " sp: %p [%p-%p-%p]\n", vm->sp,
4199 vm->stack, vm->stackBase, vm->stackEnd);
4200 Scm_Printf(out, " argp: %p\n", vm->argp);
4201 if (vm->val0) {
4202 Scm_Printf(out, " val0: %#65.1S\n", vm->val0);
4203 } else {
4204 Scm_Printf(out, " val0: #NULL\n");
4205 }
4206
4207 Scm_Printf(out, " envs:\n");
4208 while (env) {
4209 env = dump_env(vm, env, out);
4210 }
4211
4212 Scm_Printf(out, "conts:\n");
4213 while (cont) {
4214 Scm_Printf(out, " %p", cont);
4215 if (BOUNDARY_FRAME_P(cont)) {
4216 ScmPromptTag *t = SCM_PC_TO_PROMPT_TAG(cont->pc);
4217 SCM_ASSERT(t->insn == SCM_VM_INSN(SCM_VM_RET));
4218 Scm_Printf(out, "::%S\n", t);
4219 } else {
4220 Scm_Printf(out, "\n");
4221 }
4222 Scm_Printf(out, " env = %p\n", cont->env);
4223 Scm_Printf(out, " size = %d\n", cont->size);
4224 Scm_Printf(out, " base = %p", cont->base);
4225 if (cont->base && SCM_COMPILED_CODE_P(cont->base)) {
4226 Scm_Printf(out, " %S\n", cont->base->name);
4227 } else {
4228 Scm_Printf(out, "\n");
4229 }
4230 if (!C_CONTINUATION_P(cont)) {
4231 Scm_Printf(out, " pc = %p", cont->pc);
4232 dump_pc_offset(cont->pc, cont->base, out);
4233 print_insn_paren(SCM_OBJ(*cont->pc), out);
4234 } else {
4235 Scm_Printf(out, " pc = {cproc %p}\n", cont->pc);
4236 }
4237 cont = cont->prev;
4238 }
4239
4240 Scm_Printf(out, "C stacks:\n");
4241 while (cstk) {
4242 Scm_Printf(out, " %p: prev=%p, cont=%p\n",
4243 cstk, cstk->prev, cstk->cont);
4244 cstk = cstk->prev;
4245 }
4246 Scm_Printf(out, "dyn_handlers: %S\n", get_dynamic_handlers(vm));
4247
4248 Scm_Printf(out, "reset-chain-length: %d\n", (int)Scm_Length(vm->resetChain));
4249 if (vm->base) {
4250 Scm_Printf(out, "Code:\n");
4251 Scm_CompiledCodeDump(vm->base);
4252 }
4253 }
4254
4255 #ifdef USE_CUSTOM_STACK_MARKER
4256 struct GC_ms_entry *vm_stack_mark(GC_word *addr,
4257 struct GC_ms_entry *mark_sp,
4258 struct GC_ms_entry *mark_sp_limit,
4259 GC_word env)
4260 {
4261 struct GC_ms_entry *e = mark_sp;
4262 ScmObj *vmsb = ((ScmObj*)addr)+1;
4263 ScmVM *vm = (ScmVM*)*addr;
4264 int limit = vm->sp - vm->stackBase + 5;
4265 void *spb = (void *)vm->stackBase;
4266 void *sbe = (void *)(vm->stackBase + SCM_VM_STACK_SIZE);
4267 void *hb = GC_least_plausible_heap_addr;
4268 void *he = GC_greatest_plausible_heap_addr;
4269
4270 for (int i=0; i<limit; i++, vmsb++) {
4271 ScmObj z = *vmsb;
4272 if ((hb < (void *)z && (void *)z < spb)
4273 || ((void *)z > sbe && (void *)z < he)) {
4274 e = GC_mark_and_push((void *)z, e, mark_sp_limit, (void *)addr);
4275 }
4276 }
4277 return e;
4278 }
4279 #endif /*USE_CUSTOM_STACK_MARKER*/
4280
4281
4282 ScmObj Scm__VMInsnAddress(int insncode, _Bool offsetp)
4283 {
4284 if (insncode < 0 || insncode >= SCM_VM_NUM_INSNS) {
4285 Scm_Error("Insn code out of range: %d", insncode);
4286 }
4287 intptr_t r = vminsn_offsets[insncode];
4288 if (!offsetp) r += (intptr_t)(void*)run_loop;
4289 return Scm_IntptrToInteger(r);
4290 }
4291
4292 /*===============================================================
4293 * Initialization
4294 */
4295
4296 void Scm__InitVM(void)
4297 {
4298 #ifdef USE_CUSTOM_STACK_MARKER
4299 vm_stack_free_list = GC_new_free_list();
4300 vm_stack_mark_proc = GC_new_proc(vm_stack_mark);
4301 vm_stack_kind = GC_new_kind(vm_stack_free_list,
4302 GC_MAKE_PROC(vm_stack_mark_proc, 0),
4303 0, 0);
4304 #endif /*USE_CUSTOM_STACK_MARKER*/
4305
4306 Scm_HashCoreInitSimple(&vm_table, SCM_HASH_EQ, 8, NULL);
4307 SCM_INTERNAL_MUTEX_INIT(vm_table_mutex);
4308 SCM_INTERNAL_MUTEX_INIT(vm_id_mutex);
4309
4310 /* Prepare dynamic environemnt keys
4311 NB: At this moment, symbols are not initialized. However,
4312 we can safely allocate *uninterned* symbols, for it doesn't
4313 require hashtables. */
4314 #define UNINTERNED(name) Scm_MakeSymbol(SCM_STRING(SCM_MAKE_STR(#name)), FALSE)
4315 denv_key_exception_handler = UNINTERNED(exception-handler);
4316 denv_key_dynamic_handler = UNINTERNED(dynamic-handler);
4317 denv_key_parameterization = UNINTERNED(parameterization);
4318 denv_key_expression_name = UNINTERNED(expression-name);
4319 continuation_symbol = UNINTERNED(continuation);
4320
4321 /* Initialize statically allocated default prompt tag.
4322 Again, be aware that most modules are not initialized yet.
4323 */
4324 init_prompt_tag(&defaultPromptTag, SCM_OBJ(&defaultPromptTagName));
4325
4326 /* Create root VM */
4327 rootVM = Scm_NewVM(NULL, SCM_MAKE_STR_IMMUTABLE("root"));
4328 rootVM->state = SCM_VM_RUNNABLE;
4329 #ifdef GAUCHE_USE_PTHREADS
4330 if (pthread_key_create(&vm_key, NULL) != 0) {
4331 Scm_Panic("pthread_key_create failed.");
4332 }
4333 if (pthread_setspecific(vm_key, rootVM) != 0) {
4334 Scm_Panic("pthread_setspecific failed.");
4335 }
4336 rootVM->thread = pthread_self();
4337 #elif GAUCHE_USE_WTHREADS
4338 vm_key = TlsAlloc();
4339 if (vm_key == TLS_OUT_OF_INDEXES) {
4340 Scm_Panic("TlsAlloc failed");
4341 }
4342 if (!TlsSetValue(vm_key, (LPVOID)rootVM)) {
4343 Scm_Panic("TlsSetValue failed");
4344 }
4345 rootVM->thread = GetCurrentThread();
4346 #else /* no threads */
4347 theVM = rootVM;
4348 #endif /* no threads */
4349
4350 #ifdef COUNT_INSN_FREQUENCY
4351 Scm_AddCleanupHandler(dump_insn_frequency, NULL);
4352 #endif /*COUNT_INSN_FREQUENCY*/
4353
4354 #ifdef COUNT_FLUSH_FPSTACK
4355 Scm_AddCleanupHandler(print_flush_fpstack_count, NULL);
4356 #endif
4357
4358 if (Scm_GetEnv("GAUCHE_ALLOW_UNDEFINED_TEST") != NULL) {
4359 SCM_VM_RUNTIME_FLAG_CLEAR(rootVM, SCM_CHECK_UNDEFINED_TEST);
4360 } else {
4361 SCM_VM_RUNTIME_FLAG_SET(rootVM, SCM_CHECK_UNDEFINED_TEST); /* default */
4362 }
4363 if (Scm_GetEnv("GAUCHE_LEGACY_DEFINE") != NULL) {
4364 SCM_VM_COMPILER_FLAG_SET(rootVM, SCM_COMPILE_LEGACY_DEFINE);
4365 }
4366 if (Scm_GetEnv("GAUCHE_MUTABLE_LITERALS") != NULL) {
4367 SCM_VM_COMPILER_FLAG_SET(rootVM, SCM_COMPILE_MUTABLE_LITERALS);
4368 }
4369 /* NB: In 0.9.10, we warn srfi-N feature ID only when requested.
4370 We'll reverse the default in the later releases. */
4371 SCM_VM_COMPILER_FLAG_SET(rootVM, SCM_COMPILE_SRFI_FEATURE_ID);
4372 if (Scm_GetEnv("GAUCHE_WARN_SRFI_FEATURE_ID") != NULL) {
4373 SCM_VM_COMPILER_FLAG_CLEAR(rootVM, SCM_COMPILE_SRFI_FEATURE_ID);
4374 }
4375 else if (Scm_GetEnv("GAUCHE_ALLOW_SRFI_FEATURE_ID") != NULL) {
4376 SCM_VM_COMPILER_FLAG_SET(rootVM, SCM_COMPILE_SRFI_FEATURE_ID);
4377 }
4378 }