Allow 'browse-url-emacs' to fetch URL in the selected window
[emacs.git] / src / emacs-module.c
blob385c3089a90977cc17eb35593c2f0e2f0c9def75
1 /* emacs-module.c - Module loading and runtime implementation
3 Copyright (C) 2015-2018 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
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.
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.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include "emacs-module.h"
24 #include <stdarg.h>
25 #include <stddef.h>
26 #include <stdint.h>
27 #include <stdio.h>
29 #include "lisp.h"
30 #include "dynlib.h"
31 #include "coding.h"
32 #include "keyboard.h"
33 #include "syssignal.h"
34 #include "thread.h"
36 #include <intprops.h>
37 #include <verify.h>
39 /* Work around GCC bug 83162. */
40 #if GNUC_PREREQ (4, 3, 0)
41 # pragma GCC diagnostic ignored "-Wclobbered"
42 #endif
44 /* We use different strategies for allocating the user-visible objects
45 (struct emacs_runtime, emacs_env, emacs_value), depending on
46 whether the user supplied the -module-assertions flag. If
47 assertions are disabled, all objects are allocated from the stack.
48 If assertions are enabled, all objects are allocated from the free
49 store, and objects are never freed; this guarantees that they all
50 have different addresses. We use that for checking which objects
51 are live. Without unique addresses, we might consider some dead
52 objects live because their addresses would have been reused in the
53 meantime. */
56 /* Feature tests. */
58 #ifdef WINDOWSNT
59 #include <windows.h>
60 #include "w32term.h"
61 #endif
63 /* True if Lisp_Object and emacs_value have the same representation.
64 This is typically true unless WIDE_EMACS_INT. In practice, having
65 the same sizes and alignments and maximums should be a good enough
66 proxy for equality of representation. */
67 enum
69 plain_values
70 = (sizeof (Lisp_Object) == sizeof (emacs_value)
71 && alignof (Lisp_Object) == alignof (emacs_value)
72 && INTPTR_MAX == EMACS_INT_MAX)
75 /* Function prototype for the module init function. */
76 typedef int (*emacs_init_function) (struct emacs_runtime *);
78 /* Function prototype for module user-pointer finalizers. These
79 should not throw C++ exceptions, so emacs-module.h declares the
80 corresponding interfaces with EMACS_NOEXCEPT. There is only C code
81 in this module, though, so this constraint is not enforced here. */
82 typedef void (*emacs_finalizer_function) (void *);
85 /* Private runtime and environment members. */
87 /* The private part of an environment stores the current non local exit state
88 and holds the `emacs_value' objects allocated during the lifetime
89 of the environment. */
90 struct emacs_env_private
92 enum emacs_funcall_exit pending_non_local_exit;
94 /* Dedicated storage for non-local exit symbol and data so that
95 storage is always available for them, even in an out-of-memory
96 situation. */
97 Lisp_Object non_local_exit_symbol, non_local_exit_data;
99 /* List of values allocated from this environment. The code uses
100 this only if the user gave the -module-assertions command-line
101 option. */
102 Lisp_Object values;
105 /* The private parts of an `emacs_runtime' object contain the initial
106 environment. */
107 struct emacs_runtime_private
109 emacs_env *env;
113 /* Forward declarations. */
115 static Lisp_Object value_to_lisp (emacs_value);
116 static emacs_value lisp_to_value (emacs_env *, Lisp_Object);
117 static enum emacs_funcall_exit module_non_local_exit_check (emacs_env *);
118 static void module_assert_thread (void);
119 static void module_assert_runtime (struct emacs_runtime *);
120 static void module_assert_env (emacs_env *);
121 static _Noreturn void module_abort (const char *format, ...)
122 ATTRIBUTE_FORMAT_PRINTF(1, 2);
123 static emacs_env *initialize_environment (emacs_env *,
124 struct emacs_env_private *);
125 static void finalize_environment (emacs_env *);
126 static void finalize_environment_unwind (void *);
127 static void finalize_runtime_unwind (void *);
128 static void module_handle_signal (emacs_env *, Lisp_Object);
129 static void module_handle_throw (emacs_env *, Lisp_Object);
130 static void module_non_local_exit_signal_1 (emacs_env *,
131 Lisp_Object, Lisp_Object);
132 static void module_non_local_exit_throw_1 (emacs_env *,
133 Lisp_Object, Lisp_Object);
134 static void module_out_of_memory (emacs_env *);
135 static void module_reset_handlerlist (struct handler **);
137 /* We used to return NULL when emacs_value was a different type from
138 Lisp_Object, but nowadays we just use Qnil instead. Although they
139 happen to be the same thing in the current implementation, module
140 code should not assume this. */
141 verify (NIL_IS_ZERO);
142 static emacs_value const module_nil = 0;
144 static bool module_assertions = false;
145 static emacs_env *global_env;
146 static struct emacs_env_private global_env_private;
148 /* Convenience macros for non-local exit handling. */
150 /* FIXME: The following implementation for non-local exit handling
151 does not support recovery from stack overflow, see sysdep.c. */
153 /* Emacs uses setjmp and longjmp for non-local exits, but
154 module frames cannot be skipped because they are in general
155 not prepared for long jumps (e.g., the behavior in C++ is undefined
156 if objects with nontrivial destructors would be skipped).
157 Therefore, catch all non-local exits. There are two kinds of
158 non-local exits: `signal' and `throw'. The macros in this section
159 can be used to catch both. Use macros to avoid additional variants
160 of `internal_condition_case' etc., and to avoid worrying about
161 passing information to the handler functions. */
163 /* Place this macro at the beginning of a function returning a number
164 or a pointer to handle non-local exits. The function must have an
165 ENV parameter. The function will return the specified value if a
166 signal or throw is caught. */
167 /* TODO: Have Fsignal check for CATCHER_ALL so we only have to install
168 one handler. */
169 #define MODULE_HANDLE_NONLOCAL_EXIT(retval) \
170 MODULE_SETJMP (CONDITION_CASE, module_handle_signal, retval); \
171 MODULE_SETJMP (CATCHER_ALL, module_handle_throw, retval)
173 #define MODULE_SETJMP(handlertype, handlerfunc, retval) \
174 MODULE_SETJMP_1 (handlertype, handlerfunc, retval, \
175 internal_handler_##handlertype, \
176 internal_cleanup_##handlertype)
178 #if !__has_attribute (cleanup)
179 #error "__attribute__ ((cleanup)) not supported by this compiler; try GCC"
180 #endif
182 /* It is very important that pushing the handler doesn't itself raise
183 a signal. Install the cleanup only after the handler has been
184 pushed. Use __attribute__ ((cleanup)) to avoid
185 non-local-exit-prone manual cleanup.
187 The do-while forces uses of the macro to be followed by a semicolon.
188 This macro cannot enclose its entire body inside a do-while, as the
189 code after the macro may longjmp back into the macro, which means
190 its local variable C must stay live in later code. */
192 /* TODO: Make backtraces work if this macros is used. */
194 #define MODULE_SETJMP_1(handlertype, handlerfunc, retval, c0, c) \
195 if (module_non_local_exit_check (env) != emacs_funcall_exit_return) \
196 return retval; \
197 struct handler *c0 = push_handler_nosignal (Qt, handlertype); \
198 if (!c0) \
200 module_out_of_memory (env); \
201 return retval; \
203 struct handler *c __attribute__ ((cleanup (module_reset_handlerlist))) \
204 = c0; \
205 if (sys_setjmp (c->jmp)) \
207 (handlerfunc) (env, c->val); \
208 return retval; \
210 do { } while (false)
213 /* Implementation of runtime and environment functions.
215 These should abide by the following rules:
217 1. The first argument should always be a pointer to emacs_env.
219 2. Each function should first call check_thread. Note that
220 this function is a no-op unless Emacs was built with
221 --enable-checking.
223 3. The very next thing each function should do is check that the
224 emacs_env object does not have a non-local exit indication set,
225 by calling module_non_local_exit_check. If that returns
226 anything but emacs_funcall_exit_return, the function should do
227 nothing and return immediately with an error indication, without
228 clobbering the existing error indication in emacs_env. This is
229 needed for correct reporting of Lisp errors to the Emacs Lisp
230 interpreter.
232 4. Any function that needs to call Emacs facilities, such as
233 encoding or decoding functions, or 'intern', or 'make_string',
234 should protect itself from signals and 'throw' in the called
235 Emacs functions, by placing the macro
236 MODULE_HANDLE_NONLOCAL_EXIT right after the above 2 tests.
238 5. Do NOT use 'eassert' for checking validity of user code in the
239 module. Instead, make those checks part of the code, and if the
240 check fails, call 'module_non_local_exit_signal_1' or
241 'module_non_local_exit_throw_1' to report the error. This is
242 because using 'eassert' in these situations will abort Emacs
243 instead of reporting the error back to Lisp, and also because
244 'eassert' is compiled to nothing in the release version. */
246 /* Use MODULE_FUNCTION_BEGIN_NO_CATCH to implement steps 2 and 3 for
247 environment functions that are known to never exit non-locally. On
248 error it will return its argument, which can be a sentinel
249 value. */
251 #define MODULE_FUNCTION_BEGIN_NO_CATCH(error_retval) \
252 do { \
253 module_assert_thread (); \
254 module_assert_env (env); \
255 if (module_non_local_exit_check (env) != emacs_funcall_exit_return) \
256 return error_retval; \
257 } while (false)
259 /* Use MODULE_FUNCTION_BEGIN to implement steps 2 through 4 for most
260 environment functions. On error it will return its argument, which
261 can be a sentinel value. */
263 #define MODULE_FUNCTION_BEGIN(error_retval) \
264 MODULE_FUNCTION_BEGIN_NO_CATCH (error_retval); \
265 MODULE_HANDLE_NONLOCAL_EXIT (error_retval)
267 static void
268 CHECK_USER_PTR (Lisp_Object obj)
270 CHECK_TYPE (USER_PTRP (obj), Quser_ptrp, obj);
273 /* Catch signals and throws only if the code can actually signal or
274 throw. If checking is enabled, abort if the current thread is not
275 the Emacs main thread. */
277 static emacs_env *
278 module_get_environment (struct emacs_runtime *ert)
280 module_assert_thread ();
281 module_assert_runtime (ert);
282 return ert->private_members->env;
285 /* To make global refs (GC-protected global values) keep a hash that
286 maps global Lisp objects to reference counts. */
288 static emacs_value
289 module_make_global_ref (emacs_env *env, emacs_value ref)
291 MODULE_FUNCTION_BEGIN (module_nil);
292 struct Lisp_Hash_Table *h = XHASH_TABLE (Vmodule_refs_hash);
293 Lisp_Object new_obj = value_to_lisp (ref);
294 EMACS_UINT hashcode;
295 ptrdiff_t i = hash_lookup (h, new_obj, &hashcode);
297 if (i >= 0)
299 Lisp_Object value = HASH_VALUE (h, i);
300 EMACS_INT refcount = XFASTINT (value) + 1;
301 if (MOST_POSITIVE_FIXNUM < refcount)
302 xsignal0 (Qoverflow_error);
303 value = make_natnum (refcount);
304 set_hash_value_slot (h, i, value);
306 else
308 hash_put (h, new_obj, make_natnum (1), hashcode);
311 return lisp_to_value (module_assertions ? global_env : env, new_obj);
314 static void
315 module_free_global_ref (emacs_env *env, emacs_value ref)
317 /* TODO: This probably never signals. */
318 /* FIXME: Wait a minute. Shouldn't this function report an error if
319 the hash lookup fails? */
320 MODULE_FUNCTION_BEGIN ();
321 struct Lisp_Hash_Table *h = XHASH_TABLE (Vmodule_refs_hash);
322 Lisp_Object obj = value_to_lisp (ref);
323 ptrdiff_t i = hash_lookup (h, obj, NULL);
325 if (i >= 0)
327 EMACS_INT refcount = XFASTINT (HASH_VALUE (h, i)) - 1;
328 if (refcount > 0)
329 set_hash_value_slot (h, i, make_natnum (refcount));
330 else
332 eassert (refcount == 0);
333 hash_remove_from_table (h, obj);
337 if (module_assertions)
339 Lisp_Object globals = global_env_private.values;
340 Lisp_Object prev = Qnil;
341 ptrdiff_t count = 0;
342 for (Lisp_Object tail = global_env_private.values; CONSP (tail);
343 tail = XCDR (tail))
345 emacs_value global = XSAVE_POINTER (XCAR (globals), 0);
346 if (global == ref)
348 if (NILP (prev))
349 global_env_private.values = XCDR (globals);
350 else
351 XSETCDR (prev, XCDR (globals));
352 return;
354 ++count;
355 prev = globals;
357 module_abort ("Global value was not found in list of %"pD"d globals",
358 count);
362 static enum emacs_funcall_exit
363 module_non_local_exit_check (emacs_env *env)
365 module_assert_thread ();
366 module_assert_env (env);
367 return env->private_members->pending_non_local_exit;
370 static void
371 module_non_local_exit_clear (emacs_env *env)
373 module_assert_thread ();
374 module_assert_env (env);
375 env->private_members->pending_non_local_exit = emacs_funcall_exit_return;
378 static enum emacs_funcall_exit
379 module_non_local_exit_get (emacs_env *env, emacs_value *sym, emacs_value *data)
381 module_assert_thread ();
382 module_assert_env (env);
383 struct emacs_env_private *p = env->private_members;
384 if (p->pending_non_local_exit != emacs_funcall_exit_return)
386 /* FIXME: lisp_to_value can exit non-locally. */
387 *sym = lisp_to_value (env, p->non_local_exit_symbol);
388 *data = lisp_to_value (env, p->non_local_exit_data);
390 return p->pending_non_local_exit;
393 /* Like for `signal', DATA must be a list. */
394 static void
395 module_non_local_exit_signal (emacs_env *env, emacs_value sym, emacs_value data)
397 module_assert_thread ();
398 module_assert_env (env);
399 if (module_non_local_exit_check (env) == emacs_funcall_exit_return)
400 module_non_local_exit_signal_1 (env, value_to_lisp (sym),
401 value_to_lisp (data));
404 static void
405 module_non_local_exit_throw (emacs_env *env, emacs_value tag, emacs_value value)
407 module_assert_thread ();
408 module_assert_env (env);
409 if (module_non_local_exit_check (env) == emacs_funcall_exit_return)
410 module_non_local_exit_throw_1 (env, value_to_lisp (tag),
411 value_to_lisp (value));
414 static struct Lisp_Module_Function *
415 allocate_module_function (void)
417 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Module_Function,
418 min_arity, PVEC_MODULE_FUNCTION);
421 #define XSET_MODULE_FUNCTION(var, ptr) \
422 XSETPSEUDOVECTOR (var, ptr, PVEC_MODULE_FUNCTION)
424 /* A module function is a pseudovector of subtype
425 PVEC_MODULE_FUNCTION; see lisp.h for the definition. */
427 static emacs_value
428 module_make_function (emacs_env *env, ptrdiff_t min_arity, ptrdiff_t max_arity,
429 emacs_subr subr, const char *documentation,
430 void *data)
432 MODULE_FUNCTION_BEGIN (module_nil);
434 if (! (0 <= min_arity
435 && (max_arity < 0
436 ? (min_arity <= MOST_POSITIVE_FIXNUM
437 && max_arity == emacs_variadic_function)
438 : min_arity <= max_arity && max_arity <= MOST_POSITIVE_FIXNUM)))
439 xsignal2 (Qinvalid_arity, make_number (min_arity), make_number (max_arity));
441 struct Lisp_Module_Function *function = allocate_module_function ();
442 function->min_arity = min_arity;
443 function->max_arity = max_arity;
444 function->subr = subr;
445 function->data = data;
447 if (documentation)
449 AUTO_STRING (unibyte_doc, documentation);
450 function->documentation =
451 code_convert_string_norecord (unibyte_doc, Qutf_8, false);
454 Lisp_Object result;
455 XSET_MODULE_FUNCTION (result, function);
456 eassert (MODULE_FUNCTIONP (result));
458 return lisp_to_value (env, result);
461 static emacs_value
462 module_funcall (emacs_env *env, emacs_value fun, ptrdiff_t nargs,
463 emacs_value args[])
465 MODULE_FUNCTION_BEGIN (module_nil);
467 /* Make a new Lisp_Object array starting with the function as the
468 first arg, because that's what Ffuncall takes. */
469 Lisp_Object *newargs;
470 USE_SAFE_ALLOCA;
471 ptrdiff_t nargs1;
472 if (INT_ADD_WRAPV (nargs, 1, &nargs1))
473 xsignal0 (Qoverflow_error);
474 SAFE_ALLOCA_LISP (newargs, nargs1);
475 newargs[0] = value_to_lisp (fun);
476 for (ptrdiff_t i = 0; i < nargs; i++)
477 newargs[1 + i] = value_to_lisp (args[i]);
478 emacs_value result = lisp_to_value (env, Ffuncall (nargs1, newargs));
479 SAFE_FREE ();
480 return result;
483 static emacs_value
484 module_intern (emacs_env *env, const char *name)
486 MODULE_FUNCTION_BEGIN (module_nil);
487 return lisp_to_value (env, intern (name));
490 static emacs_value
491 module_type_of (emacs_env *env, emacs_value value)
493 MODULE_FUNCTION_BEGIN (module_nil);
494 return lisp_to_value (env, Ftype_of (value_to_lisp (value)));
497 static bool
498 module_is_not_nil (emacs_env *env, emacs_value value)
500 MODULE_FUNCTION_BEGIN_NO_CATCH (false);
501 return ! NILP (value_to_lisp (value));
504 static bool
505 module_eq (emacs_env *env, emacs_value a, emacs_value b)
507 MODULE_FUNCTION_BEGIN_NO_CATCH (false);
508 return EQ (value_to_lisp (a), value_to_lisp (b));
511 static intmax_t
512 module_extract_integer (emacs_env *env, emacs_value n)
514 MODULE_FUNCTION_BEGIN (0);
515 Lisp_Object l = value_to_lisp (n);
516 CHECK_NUMBER (l);
517 return XINT (l);
520 static emacs_value
521 module_make_integer (emacs_env *env, intmax_t n)
523 MODULE_FUNCTION_BEGIN (module_nil);
524 if (FIXNUM_OVERFLOW_P (n))
525 xsignal0 (Qoverflow_error);
526 return lisp_to_value (env, make_number (n));
529 static double
530 module_extract_float (emacs_env *env, emacs_value f)
532 MODULE_FUNCTION_BEGIN (0);
533 Lisp_Object lisp = value_to_lisp (f);
534 CHECK_TYPE (FLOATP (lisp), Qfloatp, lisp);
535 return XFLOAT_DATA (lisp);
538 static emacs_value
539 module_make_float (emacs_env *env, double d)
541 MODULE_FUNCTION_BEGIN (module_nil);
542 return lisp_to_value (env, make_float (d));
545 static bool
546 module_copy_string_contents (emacs_env *env, emacs_value value, char *buffer,
547 ptrdiff_t *length)
549 MODULE_FUNCTION_BEGIN (false);
550 Lisp_Object lisp_str = value_to_lisp (value);
551 CHECK_STRING (lisp_str);
553 Lisp_Object lisp_str_utf8 = ENCODE_UTF_8 (lisp_str);
554 ptrdiff_t raw_size = SBYTES (lisp_str_utf8);
555 ptrdiff_t required_buf_size = raw_size + 1;
557 if (buffer == NULL)
559 *length = required_buf_size;
560 return true;
563 if (*length < required_buf_size)
565 *length = required_buf_size;
566 xsignal0 (Qargs_out_of_range);
569 *length = required_buf_size;
570 memcpy (buffer, SDATA (lisp_str_utf8), raw_size + 1);
572 return true;
575 static emacs_value
576 module_make_string (emacs_env *env, const char *str, ptrdiff_t length)
578 MODULE_FUNCTION_BEGIN (module_nil);
579 if (! (0 <= length && length <= STRING_BYTES_BOUND))
580 xsignal0 (Qoverflow_error);
581 /* FIXME: AUTO_STRING_WITH_LEN requires STR to be null-terminated,
582 but we shouldn't require that. */
583 AUTO_STRING_WITH_LEN (lstr, str, length);
584 return lisp_to_value (env,
585 code_convert_string_norecord (lstr, Qutf_8, false));
588 static emacs_value
589 module_make_user_ptr (emacs_env *env, emacs_finalizer_function fin, void *ptr)
591 MODULE_FUNCTION_BEGIN (module_nil);
592 return lisp_to_value (env, make_user_ptr (fin, ptr));
595 static void *
596 module_get_user_ptr (emacs_env *env, emacs_value uptr)
598 MODULE_FUNCTION_BEGIN (NULL);
599 Lisp_Object lisp = value_to_lisp (uptr);
600 CHECK_USER_PTR (lisp);
601 return XUSER_PTR (lisp)->p;
604 static void
605 module_set_user_ptr (emacs_env *env, emacs_value uptr, void *ptr)
607 MODULE_FUNCTION_BEGIN ();
608 Lisp_Object lisp = value_to_lisp (uptr);
609 CHECK_USER_PTR (lisp);
610 XUSER_PTR (lisp)->p = ptr;
613 static emacs_finalizer_function
614 module_get_user_finalizer (emacs_env *env, emacs_value uptr)
616 MODULE_FUNCTION_BEGIN (NULL);
617 Lisp_Object lisp = value_to_lisp (uptr);
618 CHECK_USER_PTR (lisp);
619 return XUSER_PTR (lisp)->finalizer;
622 static void
623 module_set_user_finalizer (emacs_env *env, emacs_value uptr,
624 emacs_finalizer_function fin)
626 MODULE_FUNCTION_BEGIN ();
627 Lisp_Object lisp = value_to_lisp (uptr);
628 CHECK_USER_PTR (lisp);
629 XUSER_PTR (lisp)->finalizer = fin;
632 static void
633 check_vec_index (Lisp_Object lvec, ptrdiff_t i)
635 CHECK_VECTOR (lvec);
636 if (! (0 <= i && i < ASIZE (lvec)))
637 args_out_of_range_3 (make_fixnum_or_float (i),
638 make_number (0), make_number (ASIZE (lvec) - 1));
641 static void
642 module_vec_set (emacs_env *env, emacs_value vec, ptrdiff_t i, emacs_value val)
644 MODULE_FUNCTION_BEGIN ();
645 Lisp_Object lvec = value_to_lisp (vec);
646 check_vec_index (lvec, i);
647 ASET (lvec, i, value_to_lisp (val));
650 static emacs_value
651 module_vec_get (emacs_env *env, emacs_value vec, ptrdiff_t i)
653 MODULE_FUNCTION_BEGIN (module_nil);
654 Lisp_Object lvec = value_to_lisp (vec);
655 check_vec_index (lvec, i);
656 return lisp_to_value (env, AREF (lvec, i));
659 static ptrdiff_t
660 module_vec_size (emacs_env *env, emacs_value vec)
662 MODULE_FUNCTION_BEGIN (0);
663 Lisp_Object lvec = value_to_lisp (vec);
664 CHECK_VECTOR (lvec);
665 return ASIZE (lvec);
668 /* This function should return true if and only if maybe_quit would do
669 anything. */
670 static bool
671 module_should_quit (emacs_env *env)
673 MODULE_FUNCTION_BEGIN_NO_CATCH (false);
674 return (! NILP (Vquit_flag) && NILP (Vinhibit_quit)) || pending_signals;
678 /* Subroutines. */
680 static void
681 module_signal_or_throw (struct emacs_env_private *env)
683 switch (env->pending_non_local_exit)
685 case emacs_funcall_exit_return:
686 return;
687 case emacs_funcall_exit_signal:
688 xsignal (env->non_local_exit_symbol, env->non_local_exit_data);
689 case emacs_funcall_exit_throw:
690 Fthrow (env->non_local_exit_symbol, env->non_local_exit_data);
691 default:
692 eassume (false);
696 DEFUN ("module-load", Fmodule_load, Smodule_load, 1, 1, 0,
697 doc: /* Load module FILE. */)
698 (Lisp_Object file)
700 dynlib_handle_ptr handle;
701 emacs_init_function module_init;
702 void *gpl_sym;
704 CHECK_STRING (file);
705 handle = dynlib_open (SSDATA (file));
706 if (!handle)
707 xsignal2 (Qmodule_open_failed, file, build_string (dynlib_error ()));
709 gpl_sym = dynlib_sym (handle, "plugin_is_GPL_compatible");
710 if (!gpl_sym)
711 xsignal1 (Qmodule_not_gpl_compatible, file);
713 module_init = (emacs_init_function) dynlib_func (handle, "emacs_module_init");
714 if (!module_init)
715 xsignal1 (Qmissing_module_init_function, file);
717 struct emacs_runtime rt_pub;
718 struct emacs_runtime_private rt_priv;
719 emacs_env env_pub;
720 struct emacs_env_private env_priv;
721 rt_priv.env = initialize_environment (&env_pub, &env_priv);
723 /* If we should use module assertions, reallocate the runtime object
724 from the free store, but never free it. That way the addresses
725 for two different runtime objects are guaranteed to be distinct,
726 which we can use for checking the liveness of runtime
727 pointers. */
728 struct emacs_runtime *rt = module_assertions ? xmalloc (sizeof *rt) : &rt_pub;
729 rt->size = sizeof *rt;
730 rt->private_members = &rt_priv;
731 rt->get_environment = module_get_environment;
733 Vmodule_runtimes = Fcons (make_save_ptr (rt), Vmodule_runtimes);
734 ptrdiff_t count = SPECPDL_INDEX ();
735 record_unwind_protect_ptr (finalize_runtime_unwind, rt);
737 int r = module_init (rt);
739 /* Process the quit flag first, so that quitting doesn't get
740 overridden by other non-local exits. */
741 maybe_quit ();
743 if (r != 0)
745 if (FIXNUM_OVERFLOW_P (r))
746 xsignal0 (Qoverflow_error);
747 xsignal2 (Qmodule_init_failed, file, make_number (r));
750 module_signal_or_throw (&env_priv);
751 return unbind_to (count, Qt);
754 Lisp_Object
755 funcall_module (Lisp_Object function, ptrdiff_t nargs, Lisp_Object *arglist)
757 const struct Lisp_Module_Function *func = XMODULE_FUNCTION (function);
758 eassume (0 <= func->min_arity);
759 if (! (func->min_arity <= nargs
760 && (func->max_arity < 0 || nargs <= func->max_arity)))
761 xsignal2 (Qwrong_number_of_arguments, function, make_number (nargs));
763 emacs_env pub;
764 struct emacs_env_private priv;
765 emacs_env *env = initialize_environment (&pub, &priv);
766 ptrdiff_t count = SPECPDL_INDEX ();
767 record_unwind_protect_ptr (finalize_environment_unwind, env);
769 USE_SAFE_ALLOCA;
770 ATTRIBUTE_MAY_ALIAS emacs_value *args;
771 if (plain_values && ! module_assertions)
772 /* FIXME: The cast below is incorrect because the argument array
773 is not declared as const, so module functions can modify it.
774 Either declare it as const, or remove this branch. */
775 args = (emacs_value *) arglist;
776 else
778 args = SAFE_ALLOCA (nargs * sizeof *args);
779 for (ptrdiff_t i = 0; i < nargs; i++)
780 args[i] = lisp_to_value (env, arglist[i]);
783 emacs_value ret = func->subr (env, nargs, args, func->data);
784 SAFE_FREE ();
786 eassert (&priv == env->private_members);
788 /* Process the quit flag first, so that quitting doesn't get
789 overridden by other non-local exits. */
790 maybe_quit ();
792 module_signal_or_throw (&priv);
793 return unbind_to (count, value_to_lisp (ret));
796 Lisp_Object
797 module_function_arity (const struct Lisp_Module_Function *const function)
799 ptrdiff_t minargs = function->min_arity;
800 ptrdiff_t maxargs = function->max_arity;
801 return Fcons (make_number (minargs),
802 maxargs == MANY ? Qmany : make_number (maxargs));
806 /* Helper functions. */
808 static void
809 module_assert_thread (void)
811 if (!module_assertions)
812 return;
813 if (!in_current_thread ())
814 module_abort ("Module function called from outside "
815 "the current Lisp thread");
816 if (gc_in_progress)
817 module_abort ("Module function called during garbage collection");
820 static void
821 module_assert_runtime (struct emacs_runtime *ert)
823 if (! module_assertions)
824 return;
825 ptrdiff_t count = 0;
826 for (Lisp_Object tail = Vmodule_runtimes; CONSP (tail); tail = XCDR (tail))
828 if (XSAVE_POINTER (XCAR (tail), 0) == ert)
829 return;
830 ++count;
832 module_abort ("Runtime pointer not found in list of %"pD"d runtimes",
833 count);
836 static void
837 module_assert_env (emacs_env *env)
839 if (! module_assertions)
840 return;
841 ptrdiff_t count = 0;
842 for (Lisp_Object tail = Vmodule_environments; CONSP (tail);
843 tail = XCDR (tail))
845 if (XSAVE_POINTER (XCAR (tail), 0) == env)
846 return;
847 ++count;
849 module_abort ("Environment pointer not found in list of %"pD"d environments",
850 count);
853 static void
854 module_non_local_exit_signal_1 (emacs_env *env, Lisp_Object sym,
855 Lisp_Object data)
857 struct emacs_env_private *p = env->private_members;
858 if (p->pending_non_local_exit == emacs_funcall_exit_return)
860 p->pending_non_local_exit = emacs_funcall_exit_signal;
861 p->non_local_exit_symbol = sym;
862 p->non_local_exit_data = data;
866 static void
867 module_non_local_exit_throw_1 (emacs_env *env, Lisp_Object tag,
868 Lisp_Object value)
870 struct emacs_env_private *p = env->private_members;
871 if (p->pending_non_local_exit == emacs_funcall_exit_return)
873 p->pending_non_local_exit = emacs_funcall_exit_throw;
874 p->non_local_exit_symbol = tag;
875 p->non_local_exit_data = value;
879 /* Signal an out-of-memory condition to the caller. */
880 static void
881 module_out_of_memory (emacs_env *env)
883 /* TODO: Reimplement this so it works even if memory-signal-data has
884 been modified. */
885 module_non_local_exit_signal_1 (env, XCAR (Vmemory_signal_data),
886 XCDR (Vmemory_signal_data));
890 /* Value conversion. */
892 /* We represent Lisp objects differently depending on whether the user
893 gave -module-assertions. If assertions are disabled, emacs_value
894 objects are Lisp_Objects cast to emacs_value. If assertions are
895 enabled, emacs_value objects are pointers to Lisp_Object objects
896 allocated from the free store; they are never freed, which ensures
897 that their addresses are unique and can be used for liveness
898 checking. */
900 /* Unique Lisp_Object used to mark those emacs_values which are really
901 just containers holding a Lisp_Object that does not fit as an emacs_value,
902 either because it is an integer out of range, or is not properly aligned.
903 Used only if !plain_values. */
904 static Lisp_Object ltv_mark;
906 /* Convert V to the corresponding internal object O, such that
907 V == lisp_to_value_bits (O). Never fails. */
908 static Lisp_Object
909 value_to_lisp_bits (emacs_value v)
911 if (plain_values || USE_LSB_TAG)
912 return XPL (v);
914 /* With wide EMACS_INT and when tag bits are the most significant,
915 reassembling integers differs from reassembling pointers in two
916 ways. First, save and restore the least-significant bits of the
917 integer, not the most-significant bits. Second, sign-extend the
918 integer when restoring, but zero-extend pointers because that
919 makes TAG_PTR faster. */
921 intptr_t i = (intptr_t) v;
922 EMACS_UINT tag = i & (GCALIGNMENT - 1);
923 EMACS_UINT untagged = i - tag;
924 switch (tag)
926 case_Lisp_Int:
928 bool negative = tag & 1;
929 EMACS_UINT sign_extension
930 = negative ? VALMASK & ~(INTPTR_MAX >> INTTYPEBITS): 0;
931 uintptr_t u = i;
932 intptr_t all_but_sign = u >> GCTYPEBITS;
933 untagged = sign_extension + all_but_sign;
934 break;
938 return XIL ((tag << VALBITS) + untagged);
941 /* If V was computed from lisp_to_value (O), then return O.
942 Exits non-locally only if the stack overflows. */
943 static Lisp_Object
944 value_to_lisp (emacs_value v)
946 if (module_assertions)
948 /* Check the liveness of the value by iterating over all live
949 environments. */
950 void *vptr = v;
951 ATTRIBUTE_MAY_ALIAS Lisp_Object *optr = vptr;
952 ptrdiff_t num_environments = 0;
953 ptrdiff_t num_values = 0;
954 for (Lisp_Object environments = Vmodule_environments;
955 CONSP (environments); environments = XCDR (environments))
957 emacs_env *env = XSAVE_POINTER (XCAR (environments), 0);
958 for (Lisp_Object values = env->private_members->values;
959 CONSP (values); values = XCDR (values))
961 Lisp_Object *p = XSAVE_POINTER (XCAR (values), 0);
962 if (p == optr)
963 return *p;
964 ++num_values;
966 ++num_environments;
968 module_abort (("Emacs value not found in %"pD"d values "
969 "of %"pD"d environments"),
970 num_values, num_environments);
973 Lisp_Object o = value_to_lisp_bits (v);
974 if (! plain_values && CONSP (o) && EQ (XCDR (o), ltv_mark))
975 o = XCAR (o);
976 return o;
979 /* Attempt to convert O to an emacs_value. Do not do any checking
980 or allocate any storage; the caller should prevent or detect
981 any resulting bit pattern that is not a valid emacs_value. */
982 static emacs_value
983 lisp_to_value_bits (Lisp_Object o)
985 if (plain_values || USE_LSB_TAG)
986 return XLP (o);
988 /* Compress O into the space of a pointer, possibly losing information. */
989 EMACS_UINT u = XLI (o);
990 if (INTEGERP (o))
992 uintptr_t i = (u << VALBITS) + XTYPE (o);
993 return (emacs_value) i;
995 else
997 char *p = XLP (o);
998 void *v = p - (u & ~VALMASK) + XTYPE (o);
999 return v;
1003 /* Convert O to an emacs_value. Allocate storage if needed; this can
1004 signal if memory is exhausted. Must be an injective function. */
1005 static emacs_value
1006 lisp_to_value (emacs_env *env, Lisp_Object o)
1008 if (module_assertions)
1010 /* Add the new value to the list of values allocated from this
1011 environment. The value is actually a pointer to the
1012 Lisp_Object cast to emacs_value. We make a copy of the
1013 object on the free store to guarantee unique addresses. */
1014 ATTRIBUTE_MAY_ALIAS Lisp_Object *optr = xmalloc (sizeof o);
1015 *optr = o;
1016 void *vptr = optr;
1017 ATTRIBUTE_MAY_ALIAS emacs_value ret = vptr;
1018 struct emacs_env_private *priv = env->private_members;
1019 priv->values = Fcons (make_save_ptr (ret), priv->values);
1020 return ret;
1023 emacs_value v = lisp_to_value_bits (o);
1025 if (! EQ (o, value_to_lisp_bits (v)))
1027 /* Package the incompressible object pointer inside a pair
1028 that is compressible. */
1029 Lisp_Object pair = Fcons (o, ltv_mark);
1030 v = (emacs_value) ((intptr_t) XCONS (pair) + Lisp_Cons);
1033 eassert (EQ (o, value_to_lisp (v)));
1034 return v;
1038 /* Environment lifetime management. */
1040 /* Must be called before the environment can be used. Returns another
1041 pointer that callers should use instead of the ENV argument. If
1042 module assertions are disabled, the return value is ENV. If module
1043 assertions are enabled, the return value points to a heap-allocated
1044 object. That object is never freed to guarantee unique
1045 addresses. */
1046 static emacs_env *
1047 initialize_environment (emacs_env *env, struct emacs_env_private *priv)
1049 if (module_assertions)
1050 env = xmalloc (sizeof *env);
1052 priv->pending_non_local_exit = emacs_funcall_exit_return;
1053 priv->values = priv->non_local_exit_symbol = priv->non_local_exit_data = Qnil;
1054 env->size = sizeof *env;
1055 env->private_members = priv;
1056 env->make_global_ref = module_make_global_ref;
1057 env->free_global_ref = module_free_global_ref;
1058 env->non_local_exit_check = module_non_local_exit_check;
1059 env->non_local_exit_clear = module_non_local_exit_clear;
1060 env->non_local_exit_get = module_non_local_exit_get;
1061 env->non_local_exit_signal = module_non_local_exit_signal;
1062 env->non_local_exit_throw = module_non_local_exit_throw;
1063 env->make_function = module_make_function;
1064 env->funcall = module_funcall;
1065 env->intern = module_intern;
1066 env->type_of = module_type_of;
1067 env->is_not_nil = module_is_not_nil;
1068 env->eq = module_eq;
1069 env->extract_integer = module_extract_integer;
1070 env->make_integer = module_make_integer;
1071 env->extract_float = module_extract_float;
1072 env->make_float = module_make_float;
1073 env->copy_string_contents = module_copy_string_contents;
1074 env->make_string = module_make_string;
1075 env->make_user_ptr = module_make_user_ptr;
1076 env->get_user_ptr = module_get_user_ptr;
1077 env->set_user_ptr = module_set_user_ptr;
1078 env->get_user_finalizer = module_get_user_finalizer;
1079 env->set_user_finalizer = module_set_user_finalizer;
1080 env->vec_set = module_vec_set;
1081 env->vec_get = module_vec_get;
1082 env->vec_size = module_vec_size;
1083 env->should_quit = module_should_quit;
1084 Vmodule_environments = Fcons (make_save_ptr (env), Vmodule_environments);
1085 return env;
1088 /* Must be called before the lifetime of the environment object
1089 ends. */
1090 static void
1091 finalize_environment (emacs_env *env)
1093 eassert (XSAVE_POINTER (XCAR (Vmodule_environments), 0) == env);
1094 Vmodule_environments = XCDR (Vmodule_environments);
1095 if (module_assertions)
1096 /* There is always at least the global environment. */
1097 eassert (CONSP (Vmodule_environments));
1100 static void
1101 finalize_environment_unwind (void *env)
1103 finalize_environment (env);
1106 static void
1107 finalize_runtime_unwind (void* raw_ert)
1109 struct emacs_runtime *ert = raw_ert;
1110 eassert (XSAVE_POINTER (XCAR (Vmodule_runtimes), 0) == ert);
1111 Vmodule_runtimes = XCDR (Vmodule_runtimes);
1112 finalize_environment (ert->private_members->env);
1115 void
1116 mark_modules (void)
1118 for (Lisp_Object tail = Vmodule_environments; CONSP (tail);
1119 tail = XCDR (tail))
1121 emacs_env *env = XSAVE_POINTER (XCAR (tail), 0);
1122 struct emacs_env_private *priv = env->private_members;
1123 mark_object (priv->non_local_exit_symbol);
1124 mark_object (priv->non_local_exit_data);
1125 mark_object (priv->values);
1130 /* Non-local exit handling. */
1132 /* Must be called after setting up a handler immediately before
1133 returning from the function. See the comments in lisp.h and the
1134 code in eval.c for details. The macros below arrange for this
1135 function to be called automatically. PHANDLERLIST points to a word
1136 containing the handler list, for sanity checking. */
1137 static void
1138 module_reset_handlerlist (struct handler **phandlerlist)
1140 eassert (handlerlist == *phandlerlist);
1141 handlerlist = handlerlist->next;
1144 /* Called on `signal'. ERR is a pair (SYMBOL . DATA), which gets
1145 stored in the environment. Set the pending non-local exit flag. */
1146 static void
1147 module_handle_signal (emacs_env *env, Lisp_Object err)
1149 module_non_local_exit_signal_1 (env, XCAR (err), XCDR (err));
1152 /* Called on `throw'. TAG_VAL is a pair (TAG . VALUE), which gets
1153 stored in the environment. Set the pending non-local exit flag. */
1154 static void
1155 module_handle_throw (emacs_env *env, Lisp_Object tag_val)
1157 module_non_local_exit_throw_1 (env, XCAR (tag_val), XCDR (tag_val));
1161 /* Support for assertions. */
1162 void
1163 init_module_assertions (bool enable)
1165 module_assertions = enable;
1166 if (enable)
1168 /* We use a hidden environment for storing the globals. This
1169 environment is never freed. */
1170 emacs_env env;
1171 global_env = initialize_environment (&env, &global_env_private);
1172 eassert (global_env != &env);
1176 static _Noreturn void
1177 ATTRIBUTE_FORMAT_PRINTF(1, 2)
1178 module_abort (const char *format, ...)
1180 fputs ("Emacs module assertion: ", stderr);
1181 va_list args;
1182 va_start (args, format);
1183 vfprintf (stderr, format, args);
1184 va_end (args);
1185 putc ('\n', stderr);
1186 fflush (NULL);
1187 emacs_abort ();
1191 /* Segment initializer. */
1193 void
1194 syms_of_module (void)
1196 if (!plain_values)
1197 ltv_mark = Fcons (Qnil, Qnil);
1198 eassert (NILP (value_to_lisp (module_nil)));
1200 DEFSYM (Qmodule_refs_hash, "module-refs-hash");
1201 DEFVAR_LISP ("module-refs-hash", Vmodule_refs_hash,
1202 doc: /* Module global reference table. */);
1204 Vmodule_refs_hash
1205 = make_hash_table (hashtest_eq, DEFAULT_HASH_SIZE,
1206 DEFAULT_REHASH_SIZE, DEFAULT_REHASH_THRESHOLD,
1207 Qnil, false);
1208 Funintern (Qmodule_refs_hash, Qnil);
1210 DEFSYM (Qmodule_runtimes, "module-runtimes");
1211 DEFVAR_LISP ("module-runtimes", Vmodule_runtimes,
1212 doc: /* List of active module runtimes. */);
1213 Vmodule_runtimes = Qnil;
1214 /* Unintern `module-runtimes' because it is only used
1215 internally. */
1216 Funintern (Qmodule_runtimes, Qnil);
1218 DEFSYM (Qmodule_environments, "module-environments");
1219 DEFVAR_LISP ("module-environments", Vmodule_environments,
1220 doc: /* List of active module environments. */);
1221 Vmodule_environments = Qnil;
1222 /* Unintern `module-environments' because it is only used
1223 internally. */
1224 Funintern (Qmodule_environments, Qnil);
1226 DEFSYM (Qmodule_load_failed, "module-load-failed");
1227 Fput (Qmodule_load_failed, Qerror_conditions,
1228 listn (CONSTYPE_PURE, 2, Qmodule_load_failed, Qerror));
1229 Fput (Qmodule_load_failed, Qerror_message,
1230 build_pure_c_string ("Module load failed"));
1232 DEFSYM (Qmodule_open_failed, "module-open-failed");
1233 Fput (Qmodule_open_failed, Qerror_conditions,
1234 listn (CONSTYPE_PURE, 3,
1235 Qmodule_open_failed, Qmodule_load_failed, Qerror));
1236 Fput (Qmodule_open_failed, Qerror_message,
1237 build_pure_c_string ("Module could not be opened"));
1239 DEFSYM (Qmodule_not_gpl_compatible, "module-not-gpl-compatible");
1240 Fput (Qmodule_not_gpl_compatible, Qerror_conditions,
1241 listn (CONSTYPE_PURE, 3,
1242 Qmodule_not_gpl_compatible, Qmodule_load_failed, Qerror));
1243 Fput (Qmodule_not_gpl_compatible, Qerror_message,
1244 build_pure_c_string ("Module is not GPL compatible"));
1246 DEFSYM (Qmissing_module_init_function, "missing-module-init-function");
1247 Fput (Qmissing_module_init_function, Qerror_conditions,
1248 listn (CONSTYPE_PURE, 3,
1249 Qmissing_module_init_function, Qmodule_load_failed, Qerror));
1250 Fput (Qmissing_module_init_function, Qerror_message,
1251 build_pure_c_string ("Module does not export an "
1252 "initialization function"));
1254 DEFSYM (Qmodule_init_failed, "module-init-failed");
1255 Fput (Qmodule_init_failed, Qerror_conditions,
1256 listn (CONSTYPE_PURE, 3,
1257 Qmodule_init_failed, Qmodule_load_failed, Qerror));
1258 Fput (Qmodule_init_failed, Qerror_message,
1259 build_pure_c_string ("Module initialization failed"));
1261 DEFSYM (Qinvalid_arity, "invalid-arity");
1262 Fput (Qinvalid_arity, Qerror_conditions,
1263 listn (CONSTYPE_PURE, 2, Qinvalid_arity, Qerror));
1264 Fput (Qinvalid_arity, Qerror_message,
1265 build_pure_c_string ("Invalid function arity"));
1267 /* Unintern `module-refs-hash' because it is internal-only and Lisp
1268 code or modules should not access it. */
1269 Funintern (Qmodule_refs_hash, Qnil);
1271 DEFSYM (Qmodule_function_p, "module-function-p");
1273 defsubr (&Smodule_load);