]> code.delx.au - gnu-emacs/blob - src/emacs-module.c
b57636e54e53315c38a736e2e01d2762cbe4c604
[gnu-emacs] / src / emacs-module.c
1 /* emacs-module.c - Module loading and runtime implementation
2
3 Copyright (C) 2015-2016 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
19
20 #include <config.h>
21
22 #include "emacs-module.h"
23
24 #include <stdbool.h>
25 #include <stddef.h>
26 #include <stdint.h>
27 #include <stdio.h>
28 #include <string.h>
29
30 #include "lisp.h"
31 #include "dynlib.h"
32 #include "coding.h"
33 #include "verify.h"
34
35 \f
36 /* Feature tests. */
37
38 #if __has_attribute (cleanup)
39 enum { module_has_cleanup = true };
40 #else
41 enum { module_has_cleanup = false };
42 #endif
43
44 /* Handle to the main thread. Used to verify that modules call us in
45 the right thread. */
46 #ifdef HAVE_PTHREAD
47 # include <pthread.h>
48 static pthread_t main_thread;
49 #elif defined WINDOWSNT
50 #include <windows.h>
51 #include "w32term.h"
52 static DWORD main_thread;
53 #endif
54
55 /* True if Lisp_Object and emacs_value have the same representation.
56 This is typically true unless WIDE_EMACS_INT. In practice, having
57 the same sizes and alignments and maximums should be a good enough
58 proxy for equality of representation. */
59 enum
60 {
61 plain_values
62 = (sizeof (Lisp_Object) == sizeof (emacs_value)
63 && alignof (Lisp_Object) == alignof (emacs_value)
64 && INTPTR_MAX == EMACS_INT_MAX)
65 };
66
67 /* Function prototype for the module init function. */
68 typedef int (*emacs_init_function) (struct emacs_runtime *);
69
70 /* Function prototype for the module Lisp functions. */
71 typedef emacs_value (*emacs_subr) (emacs_env *, ptrdiff_t,
72 emacs_value [], void *);
73
74 /* Function prototype for module user-pointer finalizers. These
75 should not throw C++ exceptions, so emacs-module.h declares the
76 corresponding interfaces with EMACS_NOEXCEPT. There is only C code
77 in this module, though, so this constraint is not enforced here. */
78 typedef void (*emacs_finalizer_function) (void *);
79
80 \f
81 /* Private runtime and environment members. */
82
83 /* The private part of an environment stores the current non local exit state
84 and holds the `emacs_value' objects allocated during the lifetime
85 of the environment. */
86 struct emacs_env_private
87 {
88 enum emacs_funcall_exit pending_non_local_exit;
89
90 /* Dedicated storage for non-local exit symbol and data so that
91 storage is always available for them, even in an out-of-memory
92 situation. */
93 Lisp_Object non_local_exit_symbol, non_local_exit_data;
94 };
95
96 /* The private parts of an `emacs_runtime' object contain the initial
97 environment. */
98 struct emacs_runtime_private
99 {
100 /* FIXME: Ideally, we would just define "struct emacs_runtime_private"
101 as a synonym of "emacs_env", but I don't know how to do that in C. */
102 emacs_env pub;
103 };
104 \f
105
106 /* Forward declarations. */
107
108 struct module_fun_env;
109
110 static Lisp_Object module_format_fun_env (const struct module_fun_env *);
111 static Lisp_Object value_to_lisp (emacs_value);
112 static emacs_value lisp_to_value (Lisp_Object);
113 static enum emacs_funcall_exit module_non_local_exit_check (emacs_env *);
114 static void check_main_thread (void);
115 static void finalize_environment (struct emacs_env_private *);
116 static void initialize_environment (emacs_env *, struct emacs_env_private *priv);
117 static void module_handle_signal (emacs_env *, Lisp_Object);
118 static void module_handle_throw (emacs_env *, Lisp_Object);
119 static void module_non_local_exit_signal_1 (emacs_env *, Lisp_Object, Lisp_Object);
120 static void module_non_local_exit_throw_1 (emacs_env *, Lisp_Object, Lisp_Object);
121 static void module_out_of_memory (emacs_env *);
122 static void module_reset_handlerlist (const int *);
123
124 /* We used to return NULL when emacs_value was a different type from
125 Lisp_Object, but nowadays we just use Qnil instead. Although they
126 happen to be the same thing in the current implementation, module
127 code should not assume this. */
128 verify (NIL_IS_ZERO);
129 static emacs_value const module_nil = 0;
130 \f
131 /* Convenience macros for non-local exit handling. */
132
133 /* FIXME: The following implementation for non-local exit handling
134 does not support recovery from stack overflow, see sysdep.c. */
135
136 /* Emacs uses setjmp and longjmp for non-local exits, but
137 module frames cannot be skipped because they are in general
138 not prepared for long jumps (e.g., the behavior in C++ is undefined
139 if objects with nontrivial destructors would be skipped).
140 Therefore, catch all non-local exits. There are two kinds of
141 non-local exits: `signal' and `throw'. The macros in this section
142 can be used to catch both. Use macros to avoid additional variants
143 of `internal_condition_case' etc., and to avoid worrying about
144 passing information to the handler functions. */
145
146 /* Place this macro at the beginning of a function returning a number
147 or a pointer to handle non-local exits. The function must have an
148 ENV parameter. The function will return the specified value if a
149 signal or throw is caught. */
150 // TODO: Have Fsignal check for CATCHER_ALL so we only have to install
151 // one handler.
152 #define MODULE_HANDLE_NONLOCAL_EXIT(retval) \
153 MODULE_SETJMP (CONDITION_CASE, module_handle_signal, retval); \
154 MODULE_SETJMP (CATCHER_ALL, module_handle_throw, retval)
155
156 #define MODULE_SETJMP(handlertype, handlerfunc, retval) \
157 MODULE_SETJMP_1 (handlertype, handlerfunc, retval, \
158 internal_handler_##handlertype, \
159 internal_cleanup_##handlertype)
160
161 /* It is very important that pushing the handler doesn't itself raise
162 a signal. Install the cleanup only after the handler has been
163 pushed. Use __attribute__ ((cleanup)) to avoid
164 non-local-exit-prone manual cleanup.
165
166 The do-while forces uses of the macro to be followed by a semicolon.
167 This macro cannot enclose its entire body inside a do-while, as the
168 code after the macro may longjmp back into the macro, which means
169 its local variable C must stay live in later code. */
170
171 // TODO: Make backtraces work if this macros is used.
172
173 #define MODULE_SETJMP_1(handlertype, handlerfunc, retval, c, dummy) \
174 if (module_non_local_exit_check (env) != emacs_funcall_exit_return) \
175 return retval; \
176 struct handler *c = push_handler_nosignal (Qt, handlertype); \
177 if (!c) \
178 { \
179 module_out_of_memory (env); \
180 return retval; \
181 } \
182 verify (module_has_cleanup); \
183 int dummy __attribute__ ((cleanup (module_reset_handlerlist))); \
184 if (sys_setjmp (c->jmp)) \
185 { \
186 (handlerfunc) (env, c->val); \
187 return retval; \
188 } \
189 do { } while (false)
190
191 \f
192 /* Function environments. */
193
194 /* A function environment is an auxiliary structure used by
195 `module_make_function' to store information about a module
196 function. It is stored in a save pointer and retrieved by
197 `internal--module-call'. Its members correspond to the arguments
198 given to `module_make_function'. */
199
200 struct module_fun_env
201 {
202 ptrdiff_t min_arity, max_arity;
203 emacs_subr subr;
204 void *data;
205 };
206
207 \f
208 /* Implementation of runtime and environment functions.
209
210 These should abide by the following rules:
211
212 1. The first argument should always be a pointer to emacs_env.
213
214 2. Each function should first call check_main_thread. Note that
215 this function is a no-op unless Emacs was built with
216 --enable-checking.
217
218 3. The very next thing each function should do is check that the
219 emacs_env object does not have a non-local exit indication set,
220 by calling module_non_local_exit_check. If that returns
221 anything but emacs_funcall_exit_return, the function should do
222 nothing and return immediately with an error indication, without
223 clobbering the existing error indication in emacs_env. This is
224 needed for correct reporting of Lisp errors to the Emacs Lisp
225 interpreter.
226
227 4. Any function that needs to call Emacs facilities, such as
228 encoding or decoding functions, or 'intern', or 'make_string',
229 should protect itself from signals and 'throw' in the called
230 Emacs functions, by placing the macro
231 MODULE_HANDLE_NONLOCAL_EXIT right after the above 2 tests.
232
233 5. Do NOT use 'eassert' for checking validity of user code in the
234 module. Instead, make those checks part of the code, and if the
235 check fails, call 'module_non_local_exit_signal_1' or
236 'module_non_local_exit_throw_1' to report the error. This is
237 because using 'eassert' in these situations will abort Emacs
238 instead of reporting the error back to Lisp, and also because
239 'eassert' is compiled to nothing in the release version. */
240
241 /* Use MODULE_FUNCTION_BEGIN to implement steps 2 through 4 for most
242 environment functions. On error it will return its argument, which
243 should be a sentinel value. */
244
245 #define MODULE_FUNCTION_BEGIN(error_retval) \
246 check_main_thread (); \
247 if (module_non_local_exit_check (env) != emacs_funcall_exit_return) \
248 return error_retval; \
249 MODULE_HANDLE_NONLOCAL_EXIT (error_retval)
250
251 static void
252 CHECK_USER_PTR (Lisp_Object obj)
253 {
254 CHECK_TYPE (USER_PTRP (obj), Quser_ptrp, obj);
255 }
256
257 /* Catch signals and throws only if the code can actually signal or
258 throw. If checking is enabled, abort if the current thread is not
259 the Emacs main thread. */
260
261 static emacs_env *
262 module_get_environment (struct emacs_runtime *ert)
263 {
264 check_main_thread ();
265 return &ert->private_members->pub;
266 }
267
268 /* To make global refs (GC-protected global values) keep a hash that
269 maps global Lisp objects to reference counts. */
270
271 static emacs_value
272 module_make_global_ref (emacs_env *env, emacs_value ref)
273 {
274 MODULE_FUNCTION_BEGIN (module_nil);
275 struct Lisp_Hash_Table *h = XHASH_TABLE (Vmodule_refs_hash);
276 Lisp_Object new_obj = value_to_lisp (ref);
277 EMACS_UINT hashcode;
278 ptrdiff_t i = hash_lookup (h, new_obj, &hashcode);
279
280 if (i >= 0)
281 {
282 Lisp_Object value = HASH_VALUE (h, i);
283 EMACS_INT refcount = XFASTINT (value) + 1;
284 if (MOST_POSITIVE_FIXNUM < refcount)
285 xsignal0 (Qoverflow_error);
286 value = make_natnum (refcount);
287 set_hash_value_slot (h, i, value);
288 }
289 else
290 {
291 hash_put (h, new_obj, make_natnum (1), hashcode);
292 }
293
294 return lisp_to_value (new_obj);
295 }
296
297 static void
298 module_free_global_ref (emacs_env *env, emacs_value ref)
299 {
300 /* TODO: This probably never signals. */
301 /* FIXME: Wait a minute. Shouldn't this function report an error if
302 the hash lookup fails? */
303 MODULE_FUNCTION_BEGIN ();
304 struct Lisp_Hash_Table *h = XHASH_TABLE (Vmodule_refs_hash);
305 Lisp_Object obj = value_to_lisp (ref);
306 EMACS_UINT hashcode;
307 ptrdiff_t i = hash_lookup (h, obj, &hashcode);
308
309 if (i >= 0)
310 {
311 Lisp_Object value = HASH_VALUE (h, i);
312 EMACS_INT refcount = XFASTINT (value) - 1;
313 if (refcount > 0)
314 {
315 value = make_natnum (refcount);
316 set_hash_value_slot (h, i, value);
317 }
318 else
319 hash_remove_from_table (h, value);
320 }
321 }
322
323 static enum emacs_funcall_exit
324 module_non_local_exit_check (emacs_env *env)
325 {
326 check_main_thread ();
327 return env->private_members->pending_non_local_exit;
328 }
329
330 static void
331 module_non_local_exit_clear (emacs_env *env)
332 {
333 check_main_thread ();
334 env->private_members->pending_non_local_exit = emacs_funcall_exit_return;
335 }
336
337 static enum emacs_funcall_exit
338 module_non_local_exit_get (emacs_env *env, emacs_value *sym, emacs_value *data)
339 {
340 check_main_thread ();
341 struct emacs_env_private *p = env->private_members;
342 if (p->pending_non_local_exit != emacs_funcall_exit_return)
343 {
344 /* FIXME: lisp_to_value can exit non-locally. */
345 *sym = lisp_to_value (p->non_local_exit_symbol);
346 *data = lisp_to_value (p->non_local_exit_data);
347 }
348 return p->pending_non_local_exit;
349 }
350
351 /* Like for `signal', DATA must be a list. */
352 static void
353 module_non_local_exit_signal (emacs_env *env, emacs_value sym, emacs_value data)
354 {
355 check_main_thread ();
356 if (module_non_local_exit_check (env) == emacs_funcall_exit_return)
357 module_non_local_exit_signal_1 (env, value_to_lisp (sym),
358 value_to_lisp (data));
359 }
360
361 static void
362 module_non_local_exit_throw (emacs_env *env, emacs_value tag, emacs_value value)
363 {
364 check_main_thread ();
365 if (module_non_local_exit_check (env) == emacs_funcall_exit_return)
366 module_non_local_exit_throw_1 (env, value_to_lisp (tag),
367 value_to_lisp (value));
368 }
369
370 /* A module function is lambda function that calls
371 `internal--module-call', passing the function pointer of the module
372 function along with the module emacs_env pointer as arguments.
373
374 (function (lambda (&rest arglist)
375 (internal--module-call envobj arglist))) */
376
377 static emacs_value
378 module_make_function (emacs_env *env, ptrdiff_t min_arity, ptrdiff_t max_arity,
379 emacs_subr subr, const char *documentation,
380 void *data)
381 {
382 MODULE_FUNCTION_BEGIN (module_nil);
383
384 if (! (0 <= min_arity
385 && (max_arity < 0
386 ? max_arity == emacs_variadic_function
387 : min_arity <= max_arity)))
388 xsignal2 (Qinvalid_arity, make_number (min_arity), make_number (max_arity));
389
390 /* FIXME: This should be freed when envobj is GC'd. */
391 struct module_fun_env *envptr = xmalloc (sizeof *envptr);
392 envptr->min_arity = min_arity;
393 envptr->max_arity = max_arity;
394 envptr->subr = subr;
395 envptr->data = data;
396
397 Lisp_Object envobj = make_save_ptr (envptr);
398 Lisp_Object doc
399 = (documentation
400 ? code_convert_string_norecord (build_unibyte_string (documentation),
401 Qutf_8, false)
402 : Qnil);
403 /* FIXME: Use a bytecompiled object, or even better a subr. */
404 Lisp_Object ret = list4 (Qlambda,
405 list2 (Qand_rest, Qargs),
406 doc,
407 list4 (Qapply,
408 list2 (Qfunction, Qinternal__module_call),
409 envobj,
410 Qargs));
411
412 return lisp_to_value (ret);
413 }
414
415 static emacs_value
416 module_funcall (emacs_env *env, emacs_value fun, ptrdiff_t nargs,
417 emacs_value args[])
418 {
419 MODULE_FUNCTION_BEGIN (module_nil);
420
421 /* Make a new Lisp_Object array starting with the function as the
422 first arg, because that's what Ffuncall takes. */
423 Lisp_Object *newargs;
424 USE_SAFE_ALLOCA;
425 if (nargs == PTRDIFF_MAX)
426 xsignal0 (Qoverflow_error);
427 SAFE_ALLOCA_LISP (newargs, nargs + 1);
428 newargs[0] = value_to_lisp (fun);
429 for (ptrdiff_t i = 0; i < nargs; i++)
430 newargs[1 + i] = value_to_lisp (args[i]);
431 emacs_value result = lisp_to_value (Ffuncall (nargs + 1, newargs));
432 SAFE_FREE ();
433 return result;
434 }
435
436 static emacs_value
437 module_intern (emacs_env *env, const char *name)
438 {
439 MODULE_FUNCTION_BEGIN (module_nil);
440 return lisp_to_value (intern (name));
441 }
442
443 static emacs_value
444 module_type_of (emacs_env *env, emacs_value value)
445 {
446 MODULE_FUNCTION_BEGIN (module_nil);
447 return lisp_to_value (Ftype_of (value_to_lisp (value)));
448 }
449
450 static bool
451 module_is_not_nil (emacs_env *env, emacs_value value)
452 {
453 check_main_thread ();
454 if (module_non_local_exit_check (env) != emacs_funcall_exit_return)
455 return false;
456 return ! NILP (value_to_lisp (value));
457 }
458
459 static bool
460 module_eq (emacs_env *env, emacs_value a, emacs_value b)
461 {
462 check_main_thread ();
463 if (module_non_local_exit_check (env) != emacs_funcall_exit_return)
464 return false;
465 return EQ (value_to_lisp (a), value_to_lisp (b));
466 }
467
468 static intmax_t
469 module_extract_integer (emacs_env *env, emacs_value n)
470 {
471 MODULE_FUNCTION_BEGIN (0);
472 Lisp_Object l = value_to_lisp (n);
473 CHECK_NUMBER (l);
474 return XINT (l);
475 }
476
477 static emacs_value
478 module_make_integer (emacs_env *env, intmax_t n)
479 {
480 MODULE_FUNCTION_BEGIN (module_nil);
481 if (FIXNUM_OVERFLOW_P (n))
482 xsignal0 (Qoverflow_error);
483 return lisp_to_value (make_number (n));
484 }
485
486 static double
487 module_extract_float (emacs_env *env, emacs_value f)
488 {
489 MODULE_FUNCTION_BEGIN (0);
490 Lisp_Object lisp = value_to_lisp (f);
491 CHECK_TYPE (FLOATP (lisp), Qfloatp, lisp);
492 return XFLOAT_DATA (lisp);
493 }
494
495 static emacs_value
496 module_make_float (emacs_env *env, double d)
497 {
498 MODULE_FUNCTION_BEGIN (module_nil);
499 return lisp_to_value (make_float (d));
500 }
501
502 static bool
503 module_copy_string_contents (emacs_env *env, emacs_value value, char *buffer,
504 ptrdiff_t *length)
505 {
506 MODULE_FUNCTION_BEGIN (false);
507 Lisp_Object lisp_str = value_to_lisp (value);
508 CHECK_STRING (lisp_str);
509
510 Lisp_Object lisp_str_utf8 = ENCODE_UTF_8 (lisp_str);
511 ptrdiff_t raw_size = SBYTES (lisp_str_utf8);
512 ptrdiff_t required_buf_size = raw_size + 1;
513
514 eassert (length != NULL);
515
516 if (buffer == NULL)
517 {
518 *length = required_buf_size;
519 return true;
520 }
521
522 eassert (*length >= 0);
523
524 if (*length < required_buf_size)
525 {
526 *length = required_buf_size;
527 xsignal0 (Qargs_out_of_range);
528 }
529
530 *length = required_buf_size;
531 memcpy (buffer, SDATA (lisp_str_utf8), raw_size + 1);
532
533 return true;
534 }
535
536 static emacs_value
537 module_make_string (emacs_env *env, const char *str, ptrdiff_t length)
538 {
539 MODULE_FUNCTION_BEGIN (module_nil);
540 Lisp_Object lstr = make_unibyte_string (str, length);
541 return lisp_to_value (code_convert_string_norecord (lstr, Qutf_8, false));
542 }
543
544 static emacs_value
545 module_make_user_ptr (emacs_env *env, emacs_finalizer_function fin, void *ptr)
546 {
547 MODULE_FUNCTION_BEGIN (module_nil);
548 return lisp_to_value (make_user_ptr (fin, ptr));
549 }
550
551 static void *
552 module_get_user_ptr (emacs_env *env, emacs_value uptr)
553 {
554 MODULE_FUNCTION_BEGIN (NULL);
555 Lisp_Object lisp = value_to_lisp (uptr);
556 CHECK_USER_PTR (lisp);
557 return XUSER_PTR (lisp)->p;
558 }
559
560 static void
561 module_set_user_ptr (emacs_env *env, emacs_value uptr, void *ptr)
562 {
563 /* FIXME: This function should return bool because it can fail. */
564 MODULE_FUNCTION_BEGIN ();
565 Lisp_Object lisp = value_to_lisp (uptr);
566 CHECK_USER_PTR (lisp);
567 XUSER_PTR (lisp)->p = ptr;
568 }
569
570 static emacs_finalizer_function
571 module_get_user_finalizer (emacs_env *env, emacs_value uptr)
572 {
573 MODULE_FUNCTION_BEGIN (NULL);
574 Lisp_Object lisp = value_to_lisp (uptr);
575 CHECK_USER_PTR (lisp);
576 return XUSER_PTR (lisp)->finalizer;
577 }
578
579 static void
580 module_set_user_finalizer (emacs_env *env, emacs_value uptr,
581 emacs_finalizer_function fin)
582 {
583 /* FIXME: This function should return bool because it can fail. */
584 MODULE_FUNCTION_BEGIN ();
585 Lisp_Object lisp = value_to_lisp (uptr);
586 CHECK_USER_PTR (lisp);
587 XUSER_PTR (lisp)->finalizer = fin;
588 }
589
590 static void
591 check_vec_index (Lisp_Object lvec, ptrdiff_t i)
592 {
593 CHECK_VECTOR (lvec);
594 if (! (0 <= i && i < ASIZE (lvec)))
595 args_out_of_range_3 (make_fixnum_or_float (i),
596 make_number (0), make_number (ASIZE (lvec) - 1));
597 }
598
599 static void
600 module_vec_set (emacs_env *env, emacs_value vec, ptrdiff_t i, emacs_value val)
601 {
602 /* FIXME: This function should return bool because it can fail. */
603 MODULE_FUNCTION_BEGIN ();
604 Lisp_Object lvec = value_to_lisp (vec);
605 check_vec_index (lvec, i);
606 ASET (lvec, i, value_to_lisp (val));
607 }
608
609 static emacs_value
610 module_vec_get (emacs_env *env, emacs_value vec, ptrdiff_t i)
611 {
612 MODULE_FUNCTION_BEGIN (module_nil);
613 Lisp_Object lvec = value_to_lisp (vec);
614 check_vec_index (lvec, i);
615 return lisp_to_value (AREF (lvec, i));
616 }
617
618 static ptrdiff_t
619 module_vec_size (emacs_env *env, emacs_value vec)
620 {
621 /* FIXME: Return a sentinel value (e.g., -1) on error. */
622 MODULE_FUNCTION_BEGIN (0);
623 Lisp_Object lvec = value_to_lisp (vec);
624 CHECK_VECTOR (lvec);
625 return ASIZE (lvec);
626 }
627
628 \f
629 /* Subroutines. */
630
631 DEFUN ("module-load", Fmodule_load, Smodule_load, 1, 1, 0,
632 doc: /* Load module FILE. */)
633 (Lisp_Object file)
634 {
635 dynlib_handle_ptr handle;
636 emacs_init_function module_init;
637 void *gpl_sym;
638
639 CHECK_STRING (file);
640 handle = dynlib_open (SSDATA (file));
641 if (!handle)
642 error ("Cannot load file %s: %s", SDATA (file), dynlib_error ());
643
644 gpl_sym = dynlib_sym (handle, "plugin_is_GPL_compatible");
645 if (!gpl_sym)
646 error ("Module %s is not GPL compatible", SDATA (file));
647
648 module_init = (emacs_init_function) dynlib_func (handle, "emacs_module_init");
649 if (!module_init)
650 error ("Module %s does not have an init function.", SDATA (file));
651
652 struct emacs_runtime_private rt; /* Includes the public emacs_env. */
653 struct emacs_env_private priv;
654 initialize_environment (&rt.pub, &priv);
655 struct emacs_runtime pub =
656 {
657 .size = sizeof pub,
658 .private_members = &rt,
659 .get_environment = module_get_environment
660 };
661 int r = module_init (&pub);
662 finalize_environment (&priv);
663
664 if (r != 0)
665 {
666 if (! (MOST_NEGATIVE_FIXNUM <= r && r <= MOST_POSITIVE_FIXNUM))
667 xsignal0 (Qoverflow_error);
668 xsignal2 (Qmodule_load_failed, file, make_number (r));
669 }
670
671 return Qt;
672 }
673
674 DEFUN ("internal--module-call", Finternal_module_call, Sinternal_module_call, 1, MANY, 0,
675 doc: /* Internal function to call a module function.
676 ENVOBJ is a save pointer to a module_fun_env structure.
677 ARGLIST is a list of arguments passed to SUBRPTR.
678 usage: (module-call ENVOBJ &rest ARGLIST) */)
679 (ptrdiff_t nargs, Lisp_Object *arglist)
680 {
681 Lisp_Object envobj = arglist[0];
682 /* FIXME: Rather than use a save_value, we should create a new object type.
683 Making save_value visible to Lisp is wrong. */
684 CHECK_TYPE (SAVE_VALUEP (envobj), Qsave_value_p, envobj);
685 struct Lisp_Save_Value *save_value = XSAVE_VALUE (envobj);
686 CHECK_TYPE (save_type (save_value, 0) == SAVE_POINTER, Qsave_pointer_p, envobj);
687 /* FIXME: We have no reason to believe that XSAVE_POINTER (envobj, 0)
688 is a module_fun_env pointer. If some other part of Emacs also
689 exports save_value objects to Elisp, than we may be getting here this
690 other kind of save_value which will likely hold something completely
691 different in this field. */
692 struct module_fun_env *envptr = XSAVE_POINTER (envobj, 0);
693 EMACS_INT len = nargs - 1;
694 eassume (0 <= envptr->min_arity);
695 if (! (envptr->min_arity <= len
696 && len <= (envptr->max_arity < 0 ? PTRDIFF_MAX : envptr->max_arity)))
697 xsignal2 (Qwrong_number_of_arguments, module_format_fun_env (envptr),
698 make_number (len));
699
700 emacs_env pub;
701 struct emacs_env_private priv;
702 initialize_environment (&pub, &priv);
703
704 USE_SAFE_ALLOCA;
705 emacs_value *args;
706 if (plain_values)
707 args = (emacs_value *) arglist + 1;
708 else
709 {
710 args = SAFE_ALLOCA (len * sizeof *args);
711 for (ptrdiff_t i = 0; i < len; i++)
712 args[i] = lisp_to_value (arglist[i + 1]);
713 }
714
715 emacs_value ret = envptr->subr (&pub, len, args, envptr->data);
716 SAFE_FREE ();
717
718 eassert (&priv == pub.private_members);
719
720 switch (priv.pending_non_local_exit)
721 {
722 case emacs_funcall_exit_return:
723 finalize_environment (&priv);
724 return value_to_lisp (ret);
725 case emacs_funcall_exit_signal:
726 {
727 Lisp_Object symbol = priv.non_local_exit_symbol;
728 Lisp_Object data = priv.non_local_exit_data;
729 finalize_environment (&priv);
730 xsignal (symbol, data);
731 }
732 case emacs_funcall_exit_throw:
733 {
734 Lisp_Object tag = priv.non_local_exit_symbol;
735 Lisp_Object value = priv.non_local_exit_data;
736 finalize_environment (&priv);
737 Fthrow (tag, value);
738 }
739 default:
740 eassume (false);
741 }
742 }
743
744 \f
745 /* Helper functions. */
746
747 static void
748 check_main_thread (void)
749 {
750 #ifdef HAVE_PTHREAD
751 eassert (pthread_equal (pthread_self (), main_thread));
752 #elif defined WINDOWSNT
753 eassert (GetCurrentThreadId () == main_thread);
754 #endif
755 }
756
757 static void
758 module_non_local_exit_signal_1 (emacs_env *env, Lisp_Object sym,
759 Lisp_Object data)
760 {
761 struct emacs_env_private *p = env->private_members;
762 if (p->pending_non_local_exit == emacs_funcall_exit_return)
763 {
764 p->pending_non_local_exit = emacs_funcall_exit_signal;
765 p->non_local_exit_symbol = sym;
766 p->non_local_exit_data = data;
767 }
768 }
769
770 static void
771 module_non_local_exit_throw_1 (emacs_env *env, Lisp_Object tag,
772 Lisp_Object value)
773 {
774 struct emacs_env_private *p = env->private_members;
775 if (p->pending_non_local_exit == emacs_funcall_exit_return)
776 {
777 p->pending_non_local_exit = emacs_funcall_exit_throw;
778 p->non_local_exit_symbol = tag;
779 p->non_local_exit_data = value;
780 }
781 }
782
783 /* Signal an out-of-memory condition to the caller. */
784 static void
785 module_out_of_memory (emacs_env *env)
786 {
787 /* TODO: Reimplement this so it works even if memory-signal-data has
788 been modified. */
789 module_non_local_exit_signal_1 (env, XCAR (Vmemory_signal_data),
790 XCDR (Vmemory_signal_data));
791 }
792
793 \f
794 /* Value conversion. */
795
796 /* Unique Lisp_Object used to mark those emacs_values which are really
797 just containers holding a Lisp_Object that does not fit as an emacs_value,
798 either because it is an integer out of range, or is not properly aligned.
799 Used only if !plain_values. */
800 static Lisp_Object ltv_mark;
801
802 /* Convert V to the corresponding internal object O, such that
803 V == lisp_to_value_bits (O). Never fails. */
804 static Lisp_Object
805 value_to_lisp_bits (emacs_value v)
806 {
807 intptr_t i = (intptr_t) v;
808 if (plain_values || USE_LSB_TAG)
809 return XIL (i);
810
811 /* With wide EMACS_INT and when tag bits are the most significant,
812 reassembling integers differs from reassembling pointers in two
813 ways. First, save and restore the least-significant bits of the
814 integer, not the most-significant bits. Second, sign-extend the
815 integer when restoring, but zero-extend pointers because that
816 makes TAG_PTR faster. */
817
818 EMACS_UINT tag = i & (GCALIGNMENT - 1);
819 EMACS_UINT untagged = i - tag;
820 switch (tag)
821 {
822 case_Lisp_Int:
823 {
824 bool negative = tag & 1;
825 EMACS_UINT sign_extension
826 = negative ? VALMASK & ~(INTPTR_MAX >> INTTYPEBITS): 0;
827 uintptr_t u = i;
828 intptr_t all_but_sign = u >> GCTYPEBITS;
829 untagged = sign_extension + all_but_sign;
830 break;
831 }
832 }
833
834 return XIL ((tag << VALBITS) + untagged);
835 }
836
837 /* If V was computed from lisp_to_value (O), then return O.
838 Exits non-locally only if the stack overflows. */
839 static Lisp_Object
840 value_to_lisp (emacs_value v)
841 {
842 Lisp_Object o = value_to_lisp_bits (v);
843 if (! plain_values && CONSP (o) && EQ (XCDR (o), ltv_mark))
844 o = XCAR (o);
845 return o;
846 }
847
848 /* Attempt to convert O to an emacs_value. Do not do any checking or
849 or allocate any storage; the caller should prevent or detect
850 any resulting bit pattern that is not a valid emacs_value. */
851 static emacs_value
852 lisp_to_value_bits (Lisp_Object o)
853 {
854 EMACS_UINT u = XLI (o);
855
856 /* Compress U into the space of a pointer, possibly losing information. */
857 uintptr_t p = (plain_values || USE_LSB_TAG
858 ? u
859 : (INTEGERP (o) ? u << VALBITS : u & VALMASK) + XTYPE (o));
860 return (emacs_value) p;
861 }
862
863 #ifndef HAVE_STRUCT_ATTRIBUTE_ALIGNED
864 enum { HAVE_STRUCT_ATTRIBUTE_ALIGNED = 0 };
865 #endif
866
867 /* Convert O to an emacs_value. Allocate storage if needed; this can
868 signal if memory is exhausted. Must be an injective function. */
869 static emacs_value
870 lisp_to_value (Lisp_Object o)
871 {
872 emacs_value v = lisp_to_value_bits (o);
873
874 if (! EQ (o, value_to_lisp_bits (v)))
875 {
876 /* Package the incompressible object pointer inside a pair
877 that is compressible. */
878 Lisp_Object pair = Fcons (o, ltv_mark);
879
880 if (! HAVE_STRUCT_ATTRIBUTE_ALIGNED)
881 {
882 /* Keep calling Fcons until it returns a compressible pair.
883 This shouldn't take long. */
884 while ((intptr_t) XCONS (pair) & (GCALIGNMENT - 1))
885 pair = Fcons (o, pair);
886
887 /* Plant the mark. The garbage collector will eventually
888 reclaim any just-allocated incompressible pairs. */
889 XSETCDR (pair, ltv_mark);
890 }
891
892 v = (emacs_value) ((intptr_t) XCONS (pair) + Lisp_Cons);
893 }
894
895 eassert (EQ (o, value_to_lisp (v)));
896 return v;
897 }
898
899 \f
900 /* Environment lifetime management. */
901
902 /* Must be called before the environment can be used. */
903 static void
904 initialize_environment (emacs_env *env, struct emacs_env_private *priv)
905 {
906 priv->pending_non_local_exit = emacs_funcall_exit_return;
907 env->size = sizeof *env;
908 env->private_members = priv;
909 env->make_global_ref = module_make_global_ref;
910 env->free_global_ref = module_free_global_ref;
911 env->non_local_exit_check = module_non_local_exit_check;
912 env->non_local_exit_clear = module_non_local_exit_clear;
913 env->non_local_exit_get = module_non_local_exit_get;
914 env->non_local_exit_signal = module_non_local_exit_signal;
915 env->non_local_exit_throw = module_non_local_exit_throw;
916 env->make_function = module_make_function;
917 env->funcall = module_funcall;
918 env->intern = module_intern;
919 env->type_of = module_type_of;
920 env->is_not_nil = module_is_not_nil;
921 env->eq = module_eq;
922 env->extract_integer = module_extract_integer;
923 env->make_integer = module_make_integer;
924 env->extract_float = module_extract_float;
925 env->make_float = module_make_float;
926 env->copy_string_contents = module_copy_string_contents;
927 env->make_string = module_make_string;
928 env->make_user_ptr = module_make_user_ptr;
929 env->get_user_ptr = module_get_user_ptr;
930 env->set_user_ptr = module_set_user_ptr;
931 env->get_user_finalizer = module_get_user_finalizer;
932 env->set_user_finalizer = module_set_user_finalizer;
933 env->vec_set = module_vec_set;
934 env->vec_get = module_vec_get;
935 env->vec_size = module_vec_size;
936 Vmodule_environments = Fcons (make_save_ptr (env), Vmodule_environments);
937 }
938
939 /* Must be called before the lifetime of the environment object
940 ends. */
941 static void
942 finalize_environment (struct emacs_env_private *env)
943 {
944 Vmodule_environments = XCDR (Vmodule_environments);
945 }
946
947 \f
948 /* Non-local exit handling. */
949
950 /* Must be called after setting up a handler immediately before
951 returning from the function. See the comments in lisp.h and the
952 code in eval.c for details. The macros below arrange for this
953 function to be called automatically. DUMMY is ignored. */
954 static void
955 module_reset_handlerlist (const int *dummy)
956 {
957 handlerlist = handlerlist->next;
958 }
959
960 /* Called on `signal'. ERR is a pair (SYMBOL . DATA), which gets
961 stored in the environment. Set the pending non-local exit flag. */
962 static void
963 module_handle_signal (emacs_env *env, Lisp_Object err)
964 {
965 module_non_local_exit_signal_1 (env, XCAR (err), XCDR (err));
966 }
967
968 /* Called on `throw'. TAG_VAL is a pair (TAG . VALUE), which gets
969 stored in the environment. Set the pending non-local exit flag. */
970 static void
971 module_handle_throw (emacs_env *env, Lisp_Object tag_val)
972 {
973 module_non_local_exit_throw_1 (env, XCAR (tag_val), XCDR (tag_val));
974 }
975
976 \f
977 /* Function environments. */
978
979 /* Return a string object that contains a user-friendly
980 representation of the function environment. */
981 static Lisp_Object
982 module_format_fun_env (const struct module_fun_env *env)
983 {
984 /* Try to print a function name if possible. */
985 const char *path, *sym;
986 static char const noaddr_format[] = "#<module function at %p>";
987 char buffer[sizeof noaddr_format + INT_STRLEN_BOUND (intptr_t) + 256];
988 char *buf = buffer;
989 ptrdiff_t bufsize = sizeof buffer;
990 ptrdiff_t size
991 = (dynlib_addr (env->subr, &path, &sym)
992 ? exprintf (&buf, &bufsize, buffer, -1,
993 "#<module function %s from %s>", sym, path)
994 : sprintf (buffer, noaddr_format, env->subr));
995 Lisp_Object unibyte_result = make_unibyte_string (buffer, size);
996 if (buf != buffer)
997 xfree (buf);
998 return code_convert_string_norecord (unibyte_result, Qutf_8, false);
999 }
1000
1001 \f
1002 /* Segment initializer. */
1003
1004 void
1005 syms_of_module (void)
1006 {
1007 if (!plain_values)
1008 ltv_mark = Fcons (Qnil, Qnil);
1009 eassert (NILP (value_to_lisp (module_nil)));
1010
1011 DEFSYM (Qmodule_refs_hash, "module-refs-hash");
1012 DEFVAR_LISP ("module-refs-hash", Vmodule_refs_hash,
1013 doc: /* Module global reference table. */);
1014
1015 Vmodule_refs_hash
1016 = make_hash_table (hashtest_eq, make_number (DEFAULT_HASH_SIZE),
1017 make_float (DEFAULT_REHASH_SIZE),
1018 make_float (DEFAULT_REHASH_THRESHOLD),
1019 Qnil);
1020 Funintern (Qmodule_refs_hash, Qnil);
1021
1022 DEFSYM (Qmodule_environments, "module-environments");
1023 DEFVAR_LISP ("module-environments", Vmodule_environments,
1024 doc: /* List of active module environments. */);
1025 Vmodule_environments = Qnil;
1026 /* Unintern `module-environments' because it is only used
1027 internally. */
1028 Funintern (Qmodule_environments, Qnil);
1029
1030 DEFSYM (Qmodule_load_failed, "module-load-failed");
1031 Fput (Qmodule_load_failed, Qerror_conditions,
1032 listn (CONSTYPE_PURE, 2, Qmodule_load_failed, Qerror));
1033 Fput (Qmodule_load_failed, Qerror_message,
1034 build_pure_c_string ("Module load failed"));
1035
1036 DEFSYM (Qinvalid_module_call, "invalid-module-call");
1037 Fput (Qinvalid_module_call, Qerror_conditions,
1038 listn (CONSTYPE_PURE, 2, Qinvalid_module_call, Qerror));
1039 Fput (Qinvalid_module_call, Qerror_message,
1040 build_pure_c_string ("Invalid module call"));
1041
1042 DEFSYM (Qinvalid_arity, "invalid-arity");
1043 Fput (Qinvalid_arity, Qerror_conditions,
1044 listn (CONSTYPE_PURE, 2, Qinvalid_arity, Qerror));
1045 Fput (Qinvalid_arity, Qerror_message,
1046 build_pure_c_string ("Invalid function arity"));
1047
1048 /* Unintern `module-refs-hash' because it is internal-only and Lisp
1049 code or modules should not access it. */
1050 Funintern (Qmodule_refs_hash, Qnil);
1051
1052 DEFSYM (Qsave_value_p, "save-value-p");
1053 DEFSYM (Qsave_pointer_p, "save-pointer-p");
1054
1055 defsubr (&Smodule_load);
1056
1057 DEFSYM (Qinternal__module_call, "internal--module-call");
1058 defsubr (&Sinternal_module_call);
1059 }
1060
1061 /* Unlike syms_of_module, this initializer is called even from an
1062 initialized (dumped) Emacs. */
1063
1064 void
1065 module_init (void)
1066 {
1067 /* It is not guaranteed that dynamic initializers run in the main thread,
1068 therefore detect the main thread here. */
1069 #ifdef HAVE_PTHREAD
1070 main_thread = pthread_self ();
1071 #elif defined WINDOWSNT
1072 /* The 'main' function already recorded the main thread's thread ID,
1073 so we need just to use it . */
1074 main_thread = dwMainThreadId;
1075 #endif
1076 }