Merge commit 'e7bd20f7d9b2110fdc0fa25db5a2bfe6b2214923'
[bpt/guile.git] / libguile / continuations.c
1 /* Copyright (C) 1995,1996,1998,2000,2001,2004, 2006, 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public License
5 * as published by the Free Software Foundation; either version 3 of
6 * the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
16 * 02110-1301 USA
17 */
18
19
20 \f
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24
25 #include "libguile/_scm.h"
26
27 #include <assert.h>
28 #include <string.h>
29 #include <stdio.h>
30
31 #include "libguile/async.h"
32 #include "libguile/debug.h"
33 #include "libguile/root.h"
34 #include "libguile/stackchk.h"
35 #include "libguile/smob.h"
36 #include "libguile/ports.h"
37 #include "libguile/dynstack.h"
38 #include "libguile/eval.h"
39 #include "libguile/vm.h"
40 #include "libguile/instructions.h"
41
42 #include "libguile/validate.h"
43 #include "libguile/continuations.h"
44
45 \f
46
47 static scm_t_bits tc16_continuation;
48 #define SCM_CONTREGSP(x) SCM_TYP16_PREDICATE (tc16_continuation, x)
49
50 #define SCM_CONTREGS(x) ((scm_t_contregs *) SCM_SMOB_DATA_1 (x))
51
52 #define SCM_CONTINUATION_LENGTH(x) (SCM_CONTREGS (x)->num_stack_items)
53 #define SCM_SET_CONTINUATION_LENGTH(x, n)\
54 (SCM_CONTREGS (x)->num_stack_items = (n))
55 #define SCM_JMPBUF(x) ((SCM_CONTREGS (x))->jmpbuf)
56 #define SCM_CONTINUATION_ROOT(x) ((SCM_CONTREGS (x))->root)
57 #define SCM_DFRAME(x) ((SCM_CONTREGS (x))->dframe)
58
59 \f
60
61 /* scm_i_make_continuation will return a procedure whose code will
62 reinstate the continuation. Here, as in gsubr.c, we define the form
63 of that trampoline function.
64 */
65
66 static const scm_t_uint32 continuation_stub_code[] =
67 {
68 SCM_PACK_OP_24 (continuation_call, 0)
69 };
70
71 static SCM
72 make_continuation_trampoline (SCM contregs)
73 {
74 SCM ret;
75 scm_t_bits nfree = 1;
76 scm_t_bits flags = SCM_F_PROGRAM_IS_CONTINUATION;
77
78 ret = scm_words (scm_tc7_program | (nfree << 16) | flags, nfree + 2);
79 SCM_SET_CELL_WORD_1 (ret, continuation_stub_code);
80 SCM_PROGRAM_FREE_VARIABLE_SET (ret, 0, contregs);
81
82 return ret;
83 }
84
85
86 /* {Continuations}
87 */
88
89
90 static int
91 continuation_print (SCM obj, SCM port, scm_print_state *state SCM_UNUSED)
92 {
93 scm_t_contregs *continuation = SCM_CONTREGS (obj);
94
95 scm_puts_unlocked ("#<continuation ", port);
96 scm_intprint (continuation->num_stack_items, 10, port);
97 scm_puts_unlocked (" @ ", port);
98 scm_uintprint (SCM_SMOB_DATA_1 (obj), 16, port);
99 scm_putc_unlocked ('>', port);
100 return 1;
101 }
102
103 /* James Clark came up with this neat one instruction fix for
104 * continuations on the SPARC. It flushes the register windows so
105 * that all the state of the process is contained in the stack.
106 */
107
108 #if defined (sparc) || defined (__sparc__) || defined (__sparc)
109 # define SCM_FLUSH_REGISTER_WINDOWS asm("ta 3")
110 #else
111 # define SCM_FLUSH_REGISTER_WINDOWS /* empty */
112 #endif
113
114 /* this may return more than once: the first time with the escape
115 procedure, then subsequently with SCM_UNDEFINED (the vals already having been
116 placed on the VM stack). */
117 #define FUNC_NAME "scm_i_make_continuation"
118 SCM
119 scm_i_make_continuation (int *first, struct scm_vm *vp, SCM vm_cont)
120 {
121 scm_i_thread *thread = SCM_I_CURRENT_THREAD;
122 SCM cont;
123 scm_t_contregs *continuation;
124 long stack_size;
125 SCM_STACKITEM * src;
126
127 SCM_FLUSH_REGISTER_WINDOWS;
128 stack_size = scm_stack_size (thread->continuation_base);
129 continuation = scm_gc_malloc (sizeof (scm_t_contregs)
130 + (stack_size - 1) * sizeof (SCM_STACKITEM),
131 "continuation");
132 continuation->num_stack_items = stack_size;
133 continuation->root = thread->continuation_root;
134 src = thread->continuation_base;
135 #if ! SCM_STACK_GROWS_UP
136 src -= stack_size;
137 #endif
138 continuation->offset = continuation->stack - src;
139 memcpy (continuation->stack, src, sizeof (SCM_STACKITEM) * stack_size);
140 continuation->vp = vp;
141 continuation->vm_cont = vm_cont;
142
143 SCM_NEWSMOB (cont, tc16_continuation, continuation);
144
145 *first = !SCM_I_SETJMP (continuation->jmpbuf);
146 if (*first)
147 {
148 #ifdef __ia64__
149 continuation->backing_store_size =
150 (char *) scm_ia64_ar_bsp(&continuation->jmpbuf.ctx)
151 -
152 (char *) thread->register_backing_store_base;
153 continuation->backing_store = NULL;
154 continuation->backing_store =
155 scm_gc_malloc (continuation->backing_store_size,
156 "continuation backing store");
157 memcpy (continuation->backing_store,
158 (void *) thread->register_backing_store_base,
159 continuation->backing_store_size);
160 #endif /* __ia64__ */
161 return make_continuation_trampoline (cont);
162 }
163 else
164 return SCM_UNDEFINED;
165 }
166 #undef FUNC_NAME
167
168 SCM
169 scm_i_continuation_to_frame (SCM continuation)
170 {
171 SCM contregs;
172 scm_t_contregs *cont;
173
174 contregs = SCM_PROGRAM_FREE_VARIABLE_REF (continuation, 0);
175 cont = SCM_CONTREGS (contregs);
176
177 if (scm_is_true (cont->vm_cont))
178 {
179 struct scm_vm_cont *data = SCM_VM_CONT_DATA (cont->vm_cont);
180 return scm_c_make_frame (SCM_VM_FRAME_KIND_CONT, data,
181 (data->fp + data->reloc) - data->stack_base,
182 (data->sp + data->reloc) - data->stack_base,
183 data->ra);
184 }
185 else
186 return SCM_BOOL_F;
187 }
188
189 struct scm_vm *
190 scm_i_contregs_vp (SCM contregs)
191 {
192 return SCM_CONTREGS (contregs)->vp;
193 }
194
195 SCM
196 scm_i_contregs_vm_cont (SCM contregs)
197 {
198 return SCM_CONTREGS (contregs)->vm_cont;
199 }
200
201
202 /* {Apply}
203 */
204
205 /* Invoking a continuation proceeds as follows:
206 *
207 * - the stack is made large enough for the called continuation
208 * - the old windchain is unwound down to the branching point
209 * - the continuation stack is copied into place
210 * - the windchain is rewound up to the continuation's context
211 * - the continuation is invoked via longjmp (or setcontext)
212 *
213 * This order is important so that unwind and rewind handlers are run
214 * with their correct stack.
215 */
216
217 static void scm_dynthrow (SCM);
218
219 /* Grow the stack by a fixed amount to provide space to copy in the
220 * continuation. Possibly this function has to be called several times
221 * recursively before enough space is available. Make sure the compiler does
222 * not optimize the growth array away by storing it's address into a global
223 * variable.
224 */
225
226 static scm_t_bits scm_i_dummy;
227
228 static void
229 grow_stack (SCM cont)
230 {
231 scm_t_bits growth[100];
232
233 scm_i_dummy = (scm_t_bits) growth;
234 scm_dynthrow (cont);
235 }
236
237
238 /* Copy the continuation stack into the current stack. Calling functions from
239 * within this function is safe, since only stack frames below this function's
240 * own frame are overwritten. Thus, memcpy can be used for best performance.
241 */
242
243 static void
244 copy_stack_and_call (scm_t_contregs *continuation,
245 SCM_STACKITEM * dst)
246 {
247 scm_t_dynstack *dynstack;
248 scm_t_bits *joint;
249 scm_i_thread *thread = SCM_I_CURRENT_THREAD;
250
251 dynstack = SCM_VM_CONT_DATA (continuation->vm_cont)->dynstack;
252
253 joint = scm_dynstack_unwind_fork (&thread->dynstack, dynstack);
254
255 memcpy (dst, continuation->stack,
256 sizeof (SCM_STACKITEM) * continuation->num_stack_items);
257 #ifdef __ia64__
258 thread->pending_rbs_continuation = continuation;
259 #endif
260
261 scm_dynstack_wind (&thread->dynstack, joint);
262
263 SCM_I_LONGJMP (continuation->jmpbuf, 1);
264 }
265
266 #ifdef __ia64__
267 void
268 scm_ia64_longjmp (scm_i_jmp_buf *JB, int VAL)
269 {
270 scm_i_thread *t = SCM_I_CURRENT_THREAD;
271
272 if (t->pending_rbs_continuation)
273 {
274 memcpy (t->register_backing_store_base,
275 t->pending_rbs_continuation->backing_store,
276 t->pending_rbs_continuation->backing_store_size);
277 t->pending_rbs_continuation = NULL;
278 }
279 setcontext (&JB->ctx);
280 }
281 #endif
282
283 /* Call grow_stack until the stack space is large enough, then, as the current
284 * stack frame might get overwritten, let copy_stack_and_call perform the
285 * actual copying and continuation calling.
286 */
287 static void
288 scm_dynthrow (SCM cont)
289 {
290 scm_i_thread *thread = SCM_I_CURRENT_THREAD;
291 scm_t_contregs *continuation = SCM_CONTREGS (cont);
292 SCM_STACKITEM *dst = thread->continuation_base;
293 SCM_STACKITEM stack_top_element;
294
295 if (thread->critical_section_level)
296 {
297 fprintf (stderr, "continuation invoked from within critical section.\n");
298 abort ();
299 }
300
301 #if SCM_STACK_GROWS_UP
302 if (dst + continuation->num_stack_items >= &stack_top_element)
303 grow_stack (cont);
304 #else
305 dst -= continuation->num_stack_items;
306 if (dst <= &stack_top_element)
307 grow_stack (cont);
308 #endif /* def SCM_STACK_GROWS_UP */
309
310 SCM_FLUSH_REGISTER_WINDOWS;
311 copy_stack_and_call (continuation, dst);
312 }
313
314
315 void
316 scm_i_check_continuation (SCM cont)
317 {
318 scm_i_thread *thread = SCM_I_CURRENT_THREAD;
319 scm_t_contregs *continuation = SCM_CONTREGS (cont);
320
321 if (!scm_is_eq (continuation->root, thread->continuation_root))
322 scm_misc_error
323 ("%continuation-call",
324 "invoking continuation would cross continuation barrier: ~A",
325 scm_list_1 (cont));
326 }
327
328 void
329 scm_i_reinstate_continuation (SCM cont)
330 {
331 scm_dynthrow (cont);
332 }
333
334 SCM
335 scm_i_with_continuation_barrier (scm_t_catch_body body,
336 void *body_data,
337 scm_t_catch_handler handler,
338 void *handler_data,
339 scm_t_catch_handler pre_unwind_handler,
340 void *pre_unwind_handler_data)
341 {
342 SCM_STACKITEM stack_item;
343 scm_i_thread *thread = SCM_I_CURRENT_THREAD;
344 SCM old_controot;
345 SCM_STACKITEM *old_contbase;
346 SCM result;
347
348 /* Establish a fresh continuation root.
349 */
350 old_controot = thread->continuation_root;
351 old_contbase = thread->continuation_base;
352 thread->continuation_root = scm_cons (thread->handle, old_controot);
353 thread->continuation_base = &stack_item;
354
355 /* Call FUNC inside a catch all. This is now guaranteed to return
356 directly and exactly once.
357 */
358 result = scm_c_catch (SCM_BOOL_T,
359 body, body_data,
360 handler, handler_data,
361 pre_unwind_handler, pre_unwind_handler_data);
362
363 /* Return to old continuation root.
364 */
365 thread->continuation_base = old_contbase;
366 thread->continuation_root = old_controot;
367
368 return result;
369 }
370
371 \f
372
373 static int
374 should_print_backtrace (SCM tag, SCM stack)
375 {
376 return SCM_BACKTRACE_P
377 && scm_is_true (stack)
378 && scm_initialized_p
379 /* It's generally not useful to print backtraces for errors reading
380 or expanding code in these fallback catch statements. */
381 && !scm_is_eq (tag, scm_from_latin1_symbol ("read-error"))
382 && !scm_is_eq (tag, scm_from_latin1_symbol ("syntax-error"));
383 }
384
385 static void
386 print_exception_and_backtrace (SCM port, SCM tag, SCM args)
387 {
388 SCM stack, frame;
389
390 /* We get here via a throw to a catch-all. In that case there is the
391 throw frame active, and this catch closure, so narrow by two
392 frames. */
393 stack = scm_make_stack (SCM_BOOL_T, scm_list_1 (scm_from_int (2)));
394 frame = scm_is_true (stack) ? scm_stack_ref (stack, SCM_INUM0) : SCM_BOOL_F;
395
396 if (should_print_backtrace (tag, stack))
397 {
398 scm_puts_unlocked ("Backtrace:\n", port);
399 scm_display_backtrace_with_highlights (stack, port,
400 SCM_BOOL_F, SCM_BOOL_F,
401 SCM_EOL);
402 scm_newline (port);
403 }
404
405 scm_print_exception (port, frame, tag, args);
406 }
407
408 \f
409
410 struct c_data {
411 void *(*func) (void *);
412 void *data;
413 void *result;
414 };
415
416 static SCM
417 c_body (void *d)
418 {
419 struct c_data *data = (struct c_data *)d;
420 data->result = data->func (data->data);
421 return SCM_UNSPECIFIED;
422 }
423
424 static SCM
425 c_handler (void *d, SCM tag, SCM args)
426 {
427 struct c_data *data;
428
429 /* If TAG is `quit', exit() the process. */
430 if (scm_is_eq (tag, scm_from_latin1_symbol ("quit")))
431 exit (scm_exit_status (args));
432
433 data = (struct c_data *)d;
434 data->result = NULL;
435 return SCM_UNSPECIFIED;
436 }
437
438 static SCM
439 pre_unwind_handler (void *error_port, SCM tag, SCM args)
440 {
441 /* Print the exception unless TAG is `quit'. */
442 if (!scm_is_eq (tag, scm_from_latin1_symbol ("quit")))
443 print_exception_and_backtrace (SCM_PACK_POINTER (error_port), tag, args);
444
445 return SCM_UNSPECIFIED;
446 }
447
448 void *
449 scm_c_with_continuation_barrier (void *(*func) (void *), void *data)
450 {
451 struct c_data c_data;
452 c_data.func = func;
453 c_data.data = data;
454 scm_i_with_continuation_barrier (c_body, &c_data,
455 c_handler, &c_data,
456 pre_unwind_handler,
457 SCM_UNPACK_POINTER (scm_current_error_port ()));
458 return c_data.result;
459 }
460
461 struct scm_data {
462 SCM proc;
463 };
464
465 static SCM
466 scm_body (void *d)
467 {
468 struct scm_data *data = (struct scm_data *)d;
469 return scm_call_0 (data->proc);
470 }
471
472 static SCM
473 scm_handler (void *d, SCM tag, SCM args)
474 {
475 /* Print a message. Note that if TAG is `quit', this will exit() the
476 process. */
477 scm_handle_by_message_noexit (NULL, tag, args);
478
479 return SCM_BOOL_F;
480 }
481
482 SCM_DEFINE (scm_with_continuation_barrier, "with-continuation-barrier", 1,0,0,
483 (SCM proc),
484 "Call @var{proc} and return its result. Do not allow the invocation of\n"
485 "continuations that would leave or enter the dynamic extent of the call\n"
486 "to @code{with-continuation-barrier}. Such an attempt causes an error\n"
487 "to be signaled.\n"
488 "\n"
489 "Throws (such as errors) that are not caught from within @var{proc} are\n"
490 "caught by @code{with-continuation-barrier}. In that case, a short\n"
491 "message is printed to the current error port and @code{#f} is returned.\n"
492 "\n"
493 "Thus, @code{with-continuation-barrier} returns exactly once.\n")
494 #define FUNC_NAME s_scm_with_continuation_barrier
495 {
496 struct scm_data scm_data;
497 scm_data.proc = proc;
498 return scm_i_with_continuation_barrier (scm_body, &scm_data,
499 scm_handler, &scm_data,
500 pre_unwind_handler,
501 SCM_UNPACK_POINTER (scm_current_error_port ()));
502 }
503 #undef FUNC_NAME
504
505 void
506 scm_init_continuations ()
507 {
508 tc16_continuation = scm_make_smob_type ("continuation", 0);
509 scm_set_smob_print (tc16_continuation, continuation_print);
510 #include "libguile/continuations.x"
511 }
512
513 /*
514 Local Variables:
515 c-file-style: "gnu"
516 End:
517 */