; doc/emacs/misc.texi (Network Security): Fix typo.
[emacs.git] / src / emacs-module.c
blob3a246637990e6f47b1e97c594294734129532be8
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 /* This module is lackadaisical about function casts. */
45 #if GNUC_PREREQ (8, 0, 0)
46 # pragma GCC diagnostic ignored "-Wcast-function-type"
47 #endif
49 /* We use different strategies for allocating the user-visible objects
50 (struct emacs_runtime, emacs_env, emacs_value), depending on
51 whether the user supplied the -module-assertions flag. If
52 assertions are disabled, all objects are allocated from the stack.
53 If assertions are enabled, all objects are allocated from the free
54 store, and objects are never freed; this guarantees that they all
55 have different addresses. We use that for checking which objects
56 are live. Without unique addresses, we might consider some dead
57 objects live because their addresses would have been reused in the
58 meantime. */
61 /* Feature tests. */
63 #ifdef WINDOWSNT
64 #include <windows.h>
65 #include "w32term.h"
66 #endif
68 /* True if Lisp_Object and emacs_value have the same representation.
69 This is typically true unless WIDE_EMACS_INT. In practice, having
70 the same sizes and alignments and maximums should be a good enough
71 proxy for equality of representation. */
72 enum
74 plain_values
75 = (sizeof (Lisp_Object) == sizeof (emacs_value)
76 && alignof (Lisp_Object) == alignof (emacs_value)
77 && INTPTR_MAX == EMACS_INT_MAX)
80 /* Function prototype for the module init function. */
81 typedef int (*emacs_init_function) (struct emacs_runtime *);
83 /* Function prototype for module user-pointer finalizers. These
84 should not throw C++ exceptions, so emacs-module.h declares the
85 corresponding interfaces with EMACS_NOEXCEPT. There is only C code
86 in this module, though, so this constraint is not enforced here. */
87 typedef void (*emacs_finalizer_function) (void *);
90 /* Private runtime and environment members. */
92 /* The private part of an environment stores the current non local exit state
93 and holds the `emacs_value' objects allocated during the lifetime
94 of the environment. */
95 struct emacs_env_private
97 enum emacs_funcall_exit pending_non_local_exit;
99 /* Dedicated storage for non-local exit symbol and data so that
100 storage is always available for them, even in an out-of-memory
101 situation. */
102 Lisp_Object non_local_exit_symbol, non_local_exit_data;
104 /* List of values allocated from this environment. The code uses
105 this only if the user gave the -module-assertions command-line
106 option. */
107 Lisp_Object values;
110 /* The private parts of an `emacs_runtime' object contain the initial
111 environment. */
112 struct emacs_runtime_private
114 emacs_env *env;
118 /* Forward declarations. */
120 static Lisp_Object value_to_lisp (emacs_value);
121 static emacs_value lisp_to_value (emacs_env *, Lisp_Object);
122 static enum emacs_funcall_exit module_non_local_exit_check (emacs_env *);
123 static void module_assert_thread (void);
124 static void module_assert_runtime (struct emacs_runtime *);
125 static void module_assert_env (emacs_env *);
126 static _Noreturn void module_abort (const char *format, ...)
127 ATTRIBUTE_FORMAT_PRINTF(1, 2);
128 static emacs_env *initialize_environment (emacs_env *,
129 struct emacs_env_private *);
130 static void finalize_environment (emacs_env *);
131 static void finalize_environment_unwind (void *);
132 static void finalize_runtime_unwind (void *);
133 static void module_handle_signal (emacs_env *, Lisp_Object);
134 static void module_handle_throw (emacs_env *, Lisp_Object);
135 static void module_non_local_exit_signal_1 (emacs_env *,
136 Lisp_Object, Lisp_Object);
137 static void module_non_local_exit_throw_1 (emacs_env *,
138 Lisp_Object, Lisp_Object);
139 static void module_out_of_memory (emacs_env *);
140 static void module_reset_handlerlist (struct handler **);
142 /* We used to return NULL when emacs_value was a different type from
143 Lisp_Object, but nowadays we just use Qnil instead. Although they
144 happen to be the same thing in the current implementation, module
145 code should not assume this. */
146 verify (NIL_IS_ZERO);
147 static emacs_value const module_nil = 0;
149 static bool module_assertions = false;
150 static emacs_env *global_env;
151 static struct emacs_env_private global_env_private;
153 /* Convenience macros for non-local exit handling. */
155 /* FIXME: The following implementation for non-local exit handling
156 does not support recovery from stack overflow, see sysdep.c. */
158 /* Emacs uses setjmp and longjmp for non-local exits, but
159 module frames cannot be skipped because they are in general
160 not prepared for long jumps (e.g., the behavior in C++ is undefined
161 if objects with nontrivial destructors would be skipped).
162 Therefore, catch all non-local exits. There are two kinds of
163 non-local exits: `signal' and `throw'. The macros in this section
164 can be used to catch both. Use macros to avoid additional variants
165 of `internal_condition_case' etc., and to avoid worrying about
166 passing information to the handler functions. */
168 /* Place this macro at the beginning of a function returning a number
169 or a pointer to handle non-local exits. The function must have an
170 ENV parameter. The function will return the specified value if a
171 signal or throw is caught. */
172 /* TODO: Have Fsignal check for CATCHER_ALL so we only have to install
173 one handler. */
174 #define MODULE_HANDLE_NONLOCAL_EXIT(retval) \
175 MODULE_SETJMP (CONDITION_CASE, module_handle_signal, retval); \
176 MODULE_SETJMP (CATCHER_ALL, module_handle_throw, retval)
178 #define MODULE_SETJMP(handlertype, handlerfunc, retval) \
179 MODULE_SETJMP_1 (handlertype, handlerfunc, retval, \
180 internal_handler_##handlertype, \
181 internal_cleanup_##handlertype)
183 #if !__has_attribute (cleanup)
184 #error "__attribute__ ((cleanup)) not supported by this compiler; try GCC"
185 #endif
187 /* It is very important that pushing the handler doesn't itself raise
188 a signal. Install the cleanup only after the handler has been
189 pushed. Use __attribute__ ((cleanup)) to avoid
190 non-local-exit-prone manual cleanup.
192 The do-while forces uses of the macro to be followed by a semicolon.
193 This macro cannot enclose its entire body inside a do-while, as the
194 code after the macro may longjmp back into the macro, which means
195 its local variable C must stay live in later code. */
197 /* TODO: Make backtraces work if this macros is used. */
199 #define MODULE_SETJMP_1(handlertype, handlerfunc, retval, c0, c) \
200 if (module_non_local_exit_check (env) != emacs_funcall_exit_return) \
201 return retval; \
202 struct handler *c0 = push_handler_nosignal (Qt, handlertype); \
203 if (!c0) \
205 module_out_of_memory (env); \
206 return retval; \
208 struct handler *c __attribute__ ((cleanup (module_reset_handlerlist))) \
209 = c0; \
210 if (sys_setjmp (c->jmp)) \
212 (handlerfunc) (env, c->val); \
213 return retval; \
215 do { } while (false)
218 /* Implementation of runtime and environment functions.
220 These should abide by the following rules:
222 1. The first argument should always be a pointer to emacs_env.
224 2. Each function should first call check_thread. Note that
225 this function is a no-op unless Emacs was built with
226 --enable-checking.
228 3. The very next thing each function should do is check that the
229 emacs_env object does not have a non-local exit indication set,
230 by calling module_non_local_exit_check. If that returns
231 anything but emacs_funcall_exit_return, the function should do
232 nothing and return immediately with an error indication, without
233 clobbering the existing error indication in emacs_env. This is
234 needed for correct reporting of Lisp errors to the Emacs Lisp
235 interpreter.
237 4. Any function that needs to call Emacs facilities, such as
238 encoding or decoding functions, or 'intern', or 'make_string',
239 should protect itself from signals and 'throw' in the called
240 Emacs functions, by placing the macro
241 MODULE_HANDLE_NONLOCAL_EXIT right after the above 2 tests.
243 5. Do NOT use 'eassert' for checking validity of user code in the
244 module. Instead, make those checks part of the code, and if the
245 check fails, call 'module_non_local_exit_signal_1' or
246 'module_non_local_exit_throw_1' to report the error. This is
247 because using 'eassert' in these situations will abort Emacs
248 instead of reporting the error back to Lisp, and also because
249 'eassert' is compiled to nothing in the release version. */
251 /* Use MODULE_FUNCTION_BEGIN_NO_CATCH to implement steps 2 and 3 for
252 environment functions that are known to never exit non-locally. On
253 error it will return its argument, which can be a sentinel
254 value. */
256 #define MODULE_FUNCTION_BEGIN_NO_CATCH(error_retval) \
257 do { \
258 module_assert_thread (); \
259 module_assert_env (env); \
260 if (module_non_local_exit_check (env) != emacs_funcall_exit_return) \
261 return error_retval; \
262 } while (false)
264 /* Use MODULE_FUNCTION_BEGIN to implement steps 2 through 4 for most
265 environment functions. On error it will return its argument, which
266 can be a sentinel value. */
268 #define MODULE_FUNCTION_BEGIN(error_retval) \
269 MODULE_FUNCTION_BEGIN_NO_CATCH (error_retval); \
270 MODULE_HANDLE_NONLOCAL_EXIT (error_retval)
272 static void
273 CHECK_USER_PTR (Lisp_Object obj)
275 CHECK_TYPE (USER_PTRP (obj), Quser_ptrp, obj);
278 /* Catch signals and throws only if the code can actually signal or
279 throw. If checking is enabled, abort if the current thread is not
280 the Emacs main thread. */
282 static emacs_env *
283 module_get_environment (struct emacs_runtime *ert)
285 module_assert_thread ();
286 module_assert_runtime (ert);
287 return ert->private_members->env;
290 /* To make global refs (GC-protected global values) keep a hash that
291 maps global Lisp objects to reference counts. */
293 static emacs_value
294 module_make_global_ref (emacs_env *env, emacs_value ref)
296 MODULE_FUNCTION_BEGIN (module_nil);
297 struct Lisp_Hash_Table *h = XHASH_TABLE (Vmodule_refs_hash);
298 Lisp_Object new_obj = value_to_lisp (ref);
299 EMACS_UINT hashcode;
300 ptrdiff_t i = hash_lookup (h, new_obj, &hashcode);
302 if (i >= 0)
304 Lisp_Object value = HASH_VALUE (h, i);
305 EMACS_INT refcount = XFASTINT (value) + 1;
306 if (MOST_POSITIVE_FIXNUM < refcount)
307 xsignal0 (Qoverflow_error);
308 value = make_natnum (refcount);
309 set_hash_value_slot (h, i, value);
311 else
313 hash_put (h, new_obj, make_natnum (1), hashcode);
316 return lisp_to_value (module_assertions ? global_env : env, new_obj);
319 static void
320 module_free_global_ref (emacs_env *env, emacs_value ref)
322 /* TODO: This probably never signals. */
323 /* FIXME: Wait a minute. Shouldn't this function report an error if
324 the hash lookup fails? */
325 MODULE_FUNCTION_BEGIN ();
326 struct Lisp_Hash_Table *h = XHASH_TABLE (Vmodule_refs_hash);
327 Lisp_Object obj = value_to_lisp (ref);
328 ptrdiff_t i = hash_lookup (h, obj, NULL);
330 if (i >= 0)
332 EMACS_INT refcount = XFASTINT (HASH_VALUE (h, i)) - 1;
333 if (refcount > 0)
334 set_hash_value_slot (h, i, make_natnum (refcount));
335 else
337 eassert (refcount == 0);
338 hash_remove_from_table (h, obj);
342 if (module_assertions)
344 Lisp_Object globals = global_env_private.values;
345 Lisp_Object prev = Qnil;
346 ptrdiff_t count = 0;
347 for (Lisp_Object tail = global_env_private.values; CONSP (tail);
348 tail = XCDR (tail))
350 emacs_value global = xmint_pointer (XCAR (globals));
351 if (global == ref)
353 if (NILP (prev))
354 global_env_private.values = XCDR (globals);
355 else
356 XSETCDR (prev, XCDR (globals));
357 return;
359 ++count;
360 prev = globals;
362 module_abort ("Global value was not found in list of %"pD"d globals",
363 count);
367 static enum emacs_funcall_exit
368 module_non_local_exit_check (emacs_env *env)
370 module_assert_thread ();
371 module_assert_env (env);
372 return env->private_members->pending_non_local_exit;
375 static void
376 module_non_local_exit_clear (emacs_env *env)
378 module_assert_thread ();
379 module_assert_env (env);
380 env->private_members->pending_non_local_exit = emacs_funcall_exit_return;
383 static enum emacs_funcall_exit
384 module_non_local_exit_get (emacs_env *env, emacs_value *sym, emacs_value *data)
386 module_assert_thread ();
387 module_assert_env (env);
388 struct emacs_env_private *p = env->private_members;
389 if (p->pending_non_local_exit != emacs_funcall_exit_return)
391 /* FIXME: lisp_to_value can exit non-locally. */
392 *sym = lisp_to_value (env, p->non_local_exit_symbol);
393 *data = lisp_to_value (env, p->non_local_exit_data);
395 return p->pending_non_local_exit;
398 /* Like for `signal', DATA must be a list. */
399 static void
400 module_non_local_exit_signal (emacs_env *env, emacs_value sym, emacs_value data)
402 module_assert_thread ();
403 module_assert_env (env);
404 if (module_non_local_exit_check (env) == emacs_funcall_exit_return)
405 module_non_local_exit_signal_1 (env, value_to_lisp (sym),
406 value_to_lisp (data));
409 static void
410 module_non_local_exit_throw (emacs_env *env, emacs_value tag, emacs_value value)
412 module_assert_thread ();
413 module_assert_env (env);
414 if (module_non_local_exit_check (env) == emacs_funcall_exit_return)
415 module_non_local_exit_throw_1 (env, value_to_lisp (tag),
416 value_to_lisp (value));
419 static struct Lisp_Module_Function *
420 allocate_module_function (void)
422 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Module_Function,
423 min_arity, PVEC_MODULE_FUNCTION);
426 #define XSET_MODULE_FUNCTION(var, ptr) \
427 XSETPSEUDOVECTOR (var, ptr, PVEC_MODULE_FUNCTION)
429 /* A module function is a pseudovector of subtype
430 PVEC_MODULE_FUNCTION; see lisp.h for the definition. */
432 static emacs_value
433 module_make_function (emacs_env *env, ptrdiff_t min_arity, ptrdiff_t max_arity,
434 emacs_subr subr, const char *documentation,
435 void *data)
437 MODULE_FUNCTION_BEGIN (module_nil);
439 if (! (0 <= min_arity
440 && (max_arity < 0
441 ? (min_arity <= MOST_POSITIVE_FIXNUM
442 && max_arity == emacs_variadic_function)
443 : min_arity <= max_arity && max_arity <= MOST_POSITIVE_FIXNUM)))
444 xsignal2 (Qinvalid_arity, make_number (min_arity), make_number (max_arity));
446 struct Lisp_Module_Function *function = allocate_module_function ();
447 function->min_arity = min_arity;
448 function->max_arity = max_arity;
449 function->subr = subr;
450 function->data = data;
452 if (documentation)
454 AUTO_STRING (unibyte_doc, documentation);
455 function->documentation =
456 code_convert_string_norecord (unibyte_doc, Qutf_8, false);
459 Lisp_Object result;
460 XSET_MODULE_FUNCTION (result, function);
461 eassert (MODULE_FUNCTIONP (result));
463 return lisp_to_value (env, result);
466 static emacs_value
467 module_funcall (emacs_env *env, emacs_value fun, ptrdiff_t nargs,
468 emacs_value args[])
470 MODULE_FUNCTION_BEGIN (module_nil);
472 /* Make a new Lisp_Object array starting with the function as the
473 first arg, because that's what Ffuncall takes. */
474 Lisp_Object *newargs;
475 USE_SAFE_ALLOCA;
476 ptrdiff_t nargs1;
477 if (INT_ADD_WRAPV (nargs, 1, &nargs1))
478 xsignal0 (Qoverflow_error);
479 SAFE_ALLOCA_LISP (newargs, nargs1);
480 newargs[0] = value_to_lisp (fun);
481 for (ptrdiff_t i = 0; i < nargs; i++)
482 newargs[1 + i] = value_to_lisp (args[i]);
483 emacs_value result = lisp_to_value (env, Ffuncall (nargs1, newargs));
484 SAFE_FREE ();
485 return result;
488 static emacs_value
489 module_intern (emacs_env *env, const char *name)
491 MODULE_FUNCTION_BEGIN (module_nil);
492 return lisp_to_value (env, intern (name));
495 static emacs_value
496 module_type_of (emacs_env *env, emacs_value value)
498 MODULE_FUNCTION_BEGIN (module_nil);
499 return lisp_to_value (env, Ftype_of (value_to_lisp (value)));
502 static bool
503 module_is_not_nil (emacs_env *env, emacs_value value)
505 MODULE_FUNCTION_BEGIN_NO_CATCH (false);
506 return ! NILP (value_to_lisp (value));
509 static bool
510 module_eq (emacs_env *env, emacs_value a, emacs_value b)
512 MODULE_FUNCTION_BEGIN_NO_CATCH (false);
513 return EQ (value_to_lisp (a), value_to_lisp (b));
516 static intmax_t
517 module_extract_integer (emacs_env *env, emacs_value n)
519 MODULE_FUNCTION_BEGIN (0);
520 Lisp_Object l = value_to_lisp (n);
521 CHECK_NUMBER (l);
522 return XINT (l);
525 static emacs_value
526 module_make_integer (emacs_env *env, intmax_t n)
528 MODULE_FUNCTION_BEGIN (module_nil);
529 if (FIXNUM_OVERFLOW_P (n))
530 xsignal0 (Qoverflow_error);
531 return lisp_to_value (env, make_number (n));
534 static double
535 module_extract_float (emacs_env *env, emacs_value f)
537 MODULE_FUNCTION_BEGIN (0);
538 Lisp_Object lisp = value_to_lisp (f);
539 CHECK_TYPE (FLOATP (lisp), Qfloatp, lisp);
540 return XFLOAT_DATA (lisp);
543 static emacs_value
544 module_make_float (emacs_env *env, double d)
546 MODULE_FUNCTION_BEGIN (module_nil);
547 return lisp_to_value (env, make_float (d));
550 static bool
551 module_copy_string_contents (emacs_env *env, emacs_value value, char *buffer,
552 ptrdiff_t *length)
554 MODULE_FUNCTION_BEGIN (false);
555 Lisp_Object lisp_str = value_to_lisp (value);
556 CHECK_STRING (lisp_str);
558 Lisp_Object lisp_str_utf8 = ENCODE_UTF_8 (lisp_str);
559 ptrdiff_t raw_size = SBYTES (lisp_str_utf8);
560 ptrdiff_t required_buf_size = raw_size + 1;
562 if (buffer == NULL)
564 *length = required_buf_size;
565 return true;
568 if (*length < required_buf_size)
570 *length = required_buf_size;
571 xsignal0 (Qargs_out_of_range);
574 *length = required_buf_size;
575 memcpy (buffer, SDATA (lisp_str_utf8), raw_size + 1);
577 return true;
580 static emacs_value
581 module_make_string (emacs_env *env, const char *str, ptrdiff_t length)
583 MODULE_FUNCTION_BEGIN (module_nil);
584 if (! (0 <= length && length <= STRING_BYTES_BOUND))
585 xsignal0 (Qoverflow_error);
586 /* FIXME: AUTO_STRING_WITH_LEN requires STR to be null-terminated,
587 but we shouldn't require that. */
588 AUTO_STRING_WITH_LEN (lstr, str, length);
589 return lisp_to_value (env,
590 code_convert_string_norecord (lstr, Qutf_8, false));
593 static emacs_value
594 module_make_user_ptr (emacs_env *env, emacs_finalizer_function fin, void *ptr)
596 MODULE_FUNCTION_BEGIN (module_nil);
597 return lisp_to_value (env, make_user_ptr (fin, ptr));
600 static void *
601 module_get_user_ptr (emacs_env *env, emacs_value uptr)
603 MODULE_FUNCTION_BEGIN (NULL);
604 Lisp_Object lisp = value_to_lisp (uptr);
605 CHECK_USER_PTR (lisp);
606 return XUSER_PTR (lisp)->p;
609 static void
610 module_set_user_ptr (emacs_env *env, emacs_value uptr, void *ptr)
612 MODULE_FUNCTION_BEGIN ();
613 Lisp_Object lisp = value_to_lisp (uptr);
614 CHECK_USER_PTR (lisp);
615 XUSER_PTR (lisp)->p = ptr;
618 static emacs_finalizer_function
619 module_get_user_finalizer (emacs_env *env, emacs_value uptr)
621 MODULE_FUNCTION_BEGIN (NULL);
622 Lisp_Object lisp = value_to_lisp (uptr);
623 CHECK_USER_PTR (lisp);
624 return XUSER_PTR (lisp)->finalizer;
627 static void
628 module_set_user_finalizer (emacs_env *env, emacs_value uptr,
629 emacs_finalizer_function fin)
631 MODULE_FUNCTION_BEGIN ();
632 Lisp_Object lisp = value_to_lisp (uptr);
633 CHECK_USER_PTR (lisp);
634 XUSER_PTR (lisp)->finalizer = fin;
637 static void
638 check_vec_index (Lisp_Object lvec, ptrdiff_t i)
640 CHECK_VECTOR (lvec);
641 if (! (0 <= i && i < ASIZE (lvec)))
642 args_out_of_range_3 (make_fixnum_or_float (i),
643 make_number (0), make_number (ASIZE (lvec) - 1));
646 static void
647 module_vec_set (emacs_env *env, emacs_value vec, ptrdiff_t i, emacs_value val)
649 MODULE_FUNCTION_BEGIN ();
650 Lisp_Object lvec = value_to_lisp (vec);
651 check_vec_index (lvec, i);
652 ASET (lvec, i, value_to_lisp (val));
655 static emacs_value
656 module_vec_get (emacs_env *env, emacs_value vec, ptrdiff_t i)
658 MODULE_FUNCTION_BEGIN (module_nil);
659 Lisp_Object lvec = value_to_lisp (vec);
660 check_vec_index (lvec, i);
661 return lisp_to_value (env, AREF (lvec, i));
664 static ptrdiff_t
665 module_vec_size (emacs_env *env, emacs_value vec)
667 MODULE_FUNCTION_BEGIN (0);
668 Lisp_Object lvec = value_to_lisp (vec);
669 CHECK_VECTOR (lvec);
670 return ASIZE (lvec);
673 /* This function should return true if and only if maybe_quit would do
674 anything. */
675 static bool
676 module_should_quit (emacs_env *env)
678 MODULE_FUNCTION_BEGIN_NO_CATCH (false);
679 return (! NILP (Vquit_flag) && NILP (Vinhibit_quit)) || pending_signals;
683 /* Subroutines. */
685 static void
686 module_signal_or_throw (struct emacs_env_private *env)
688 switch (env->pending_non_local_exit)
690 case emacs_funcall_exit_return:
691 return;
692 case emacs_funcall_exit_signal:
693 xsignal (env->non_local_exit_symbol, env->non_local_exit_data);
694 case emacs_funcall_exit_throw:
695 Fthrow (env->non_local_exit_symbol, env->non_local_exit_data);
696 default:
697 eassume (false);
701 DEFUN ("module-load", Fmodule_load, Smodule_load, 1, 1, 0,
702 doc: /* Load module FILE. */)
703 (Lisp_Object file)
705 dynlib_handle_ptr handle;
706 emacs_init_function module_init;
707 void *gpl_sym;
709 CHECK_STRING (file);
710 handle = dynlib_open (SSDATA (file));
711 if (!handle)
712 xsignal2 (Qmodule_open_failed, file, build_string (dynlib_error ()));
714 gpl_sym = dynlib_sym (handle, "plugin_is_GPL_compatible");
715 if (!gpl_sym)
716 xsignal1 (Qmodule_not_gpl_compatible, file);
718 module_init = (emacs_init_function) dynlib_func (handle, "emacs_module_init");
719 if (!module_init)
720 xsignal1 (Qmissing_module_init_function, file);
722 struct emacs_runtime rt_pub;
723 struct emacs_runtime_private rt_priv;
724 emacs_env env_pub;
725 struct emacs_env_private env_priv;
726 rt_priv.env = initialize_environment (&env_pub, &env_priv);
728 /* If we should use module assertions, reallocate the runtime object
729 from the free store, but never free it. That way the addresses
730 for two different runtime objects are guaranteed to be distinct,
731 which we can use for checking the liveness of runtime
732 pointers. */
733 struct emacs_runtime *rt = module_assertions ? xmalloc (sizeof *rt) : &rt_pub;
734 rt->size = sizeof *rt;
735 rt->private_members = &rt_priv;
736 rt->get_environment = module_get_environment;
738 Vmodule_runtimes = Fcons (make_mint_ptr (rt), Vmodule_runtimes);
739 ptrdiff_t count = SPECPDL_INDEX ();
740 record_unwind_protect_ptr (finalize_runtime_unwind, rt);
742 int r = module_init (rt);
744 /* Process the quit flag first, so that quitting doesn't get
745 overridden by other non-local exits. */
746 maybe_quit ();
748 if (r != 0)
750 if (FIXNUM_OVERFLOW_P (r))
751 xsignal0 (Qoverflow_error);
752 xsignal2 (Qmodule_init_failed, file, make_number (r));
755 module_signal_or_throw (&env_priv);
756 return unbind_to (count, Qt);
759 Lisp_Object
760 funcall_module (Lisp_Object function, ptrdiff_t nargs, Lisp_Object *arglist)
762 const struct Lisp_Module_Function *func = XMODULE_FUNCTION (function);
763 eassume (0 <= func->min_arity);
764 if (! (func->min_arity <= nargs
765 && (func->max_arity < 0 || nargs <= func->max_arity)))
766 xsignal2 (Qwrong_number_of_arguments, function, make_number (nargs));
768 emacs_env pub;
769 struct emacs_env_private priv;
770 emacs_env *env = initialize_environment (&pub, &priv);
771 ptrdiff_t count = SPECPDL_INDEX ();
772 record_unwind_protect_ptr (finalize_environment_unwind, env);
774 USE_SAFE_ALLOCA;
775 ATTRIBUTE_MAY_ALIAS emacs_value *args;
776 if (plain_values && ! module_assertions)
777 /* FIXME: The cast below is incorrect because the argument array
778 is not declared as const, so module functions can modify it.
779 Either declare it as const, or remove this branch. */
780 args = (emacs_value *) arglist;
781 else
783 args = SAFE_ALLOCA (nargs * sizeof *args);
784 for (ptrdiff_t i = 0; i < nargs; i++)
785 args[i] = lisp_to_value (env, arglist[i]);
788 emacs_value ret = func->subr (env, nargs, args, func->data);
789 SAFE_FREE ();
791 eassert (&priv == env->private_members);
793 /* Process the quit flag first, so that quitting doesn't get
794 overridden by other non-local exits. */
795 maybe_quit ();
797 module_signal_or_throw (&priv);
798 return unbind_to (count, value_to_lisp (ret));
801 Lisp_Object
802 module_function_arity (const struct Lisp_Module_Function *const function)
804 ptrdiff_t minargs = function->min_arity;
805 ptrdiff_t maxargs = function->max_arity;
806 return Fcons (make_number (minargs),
807 maxargs == MANY ? Qmany : make_number (maxargs));
811 /* Helper functions. */
813 static void
814 module_assert_thread (void)
816 if (!module_assertions)
817 return;
818 if (!in_current_thread ())
819 module_abort ("Module function called from outside "
820 "the current Lisp thread");
821 if (gc_in_progress)
822 module_abort ("Module function called during garbage collection");
825 static void
826 module_assert_runtime (struct emacs_runtime *ert)
828 if (! module_assertions)
829 return;
830 ptrdiff_t count = 0;
831 for (Lisp_Object tail = Vmodule_runtimes; CONSP (tail); tail = XCDR (tail))
833 if (xmint_pointer (XCAR (tail)) == ert)
834 return;
835 ++count;
837 module_abort ("Runtime pointer not found in list of %"pD"d runtimes",
838 count);
841 static void
842 module_assert_env (emacs_env *env)
844 if (! module_assertions)
845 return;
846 ptrdiff_t count = 0;
847 for (Lisp_Object tail = Vmodule_environments; CONSP (tail);
848 tail = XCDR (tail))
850 if (xmint_pointer (XCAR (tail)) == env)
851 return;
852 ++count;
854 module_abort ("Environment pointer not found in list of %"pD"d environments",
855 count);
858 static void
859 module_non_local_exit_signal_1 (emacs_env *env, Lisp_Object sym,
860 Lisp_Object data)
862 struct emacs_env_private *p = env->private_members;
863 if (p->pending_non_local_exit == emacs_funcall_exit_return)
865 p->pending_non_local_exit = emacs_funcall_exit_signal;
866 p->non_local_exit_symbol = sym;
867 p->non_local_exit_data = data;
871 static void
872 module_non_local_exit_throw_1 (emacs_env *env, Lisp_Object tag,
873 Lisp_Object value)
875 struct emacs_env_private *p = env->private_members;
876 if (p->pending_non_local_exit == emacs_funcall_exit_return)
878 p->pending_non_local_exit = emacs_funcall_exit_throw;
879 p->non_local_exit_symbol = tag;
880 p->non_local_exit_data = value;
884 /* Signal an out-of-memory condition to the caller. */
885 static void
886 module_out_of_memory (emacs_env *env)
888 /* TODO: Reimplement this so it works even if memory-signal-data has
889 been modified. */
890 module_non_local_exit_signal_1 (env, XCAR (Vmemory_signal_data),
891 XCDR (Vmemory_signal_data));
895 /* Value conversion. */
897 /* We represent Lisp objects differently depending on whether the user
898 gave -module-assertions. If assertions are disabled, emacs_value
899 objects are Lisp_Objects cast to emacs_value. If assertions are
900 enabled, emacs_value objects are pointers to Lisp_Object objects
901 allocated from the free store; they are never freed, which ensures
902 that their addresses are unique and can be used for liveness
903 checking. */
905 /* Unique Lisp_Object used to mark those emacs_values which are really
906 just containers holding a Lisp_Object that does not fit as an emacs_value,
907 either because it is an integer out of range, or is not properly aligned.
908 Used only if !plain_values. */
909 static Lisp_Object ltv_mark;
911 /* Convert V to the corresponding internal object O, such that
912 V == lisp_to_value_bits (O). Never fails. */
913 static Lisp_Object
914 value_to_lisp_bits (emacs_value v)
916 if (plain_values || USE_LSB_TAG)
917 return XPL (v);
919 /* With wide EMACS_INT and when tag bits are the most significant,
920 reassembling integers differs from reassembling pointers in two
921 ways. First, save and restore the least-significant bits of the
922 integer, not the most-significant bits. Second, sign-extend the
923 integer when restoring, but zero-extend pointers because that
924 makes TAG_PTR faster. */
926 intptr_t i = (intptr_t) v;
927 EMACS_UINT tag = i & ((1 << GCTYPEBITS) - 1);
928 EMACS_UINT untagged = i - tag;
929 switch (tag)
931 case_Lisp_Int:
933 bool negative = tag & 1;
934 EMACS_UINT sign_extension
935 = negative ? VALMASK & ~(INTPTR_MAX >> INTTYPEBITS): 0;
936 uintptr_t u = i;
937 intptr_t all_but_sign = u >> GCTYPEBITS;
938 untagged = sign_extension + all_but_sign;
939 break;
943 return XIL ((tag << VALBITS) + untagged);
946 /* If V was computed from lisp_to_value (O), then return O.
947 Exits non-locally only if the stack overflows. */
948 static Lisp_Object
949 value_to_lisp (emacs_value v)
951 if (module_assertions)
953 /* Check the liveness of the value by iterating over all live
954 environments. */
955 void *vptr = v;
956 ATTRIBUTE_MAY_ALIAS Lisp_Object *optr = vptr;
957 ptrdiff_t num_environments = 0;
958 ptrdiff_t num_values = 0;
959 for (Lisp_Object environments = Vmodule_environments;
960 CONSP (environments); environments = XCDR (environments))
962 emacs_env *env = xmint_pointer (XCAR (environments));
963 for (Lisp_Object values = env->private_members->values;
964 CONSP (values); values = XCDR (values))
966 Lisp_Object *p = xmint_pointer (XCAR (values));
967 if (p == optr)
968 return *p;
969 ++num_values;
971 ++num_environments;
973 module_abort (("Emacs value not found in %"pD"d values "
974 "of %"pD"d environments"),
975 num_values, num_environments);
978 Lisp_Object o = value_to_lisp_bits (v);
979 if (! plain_values && CONSP (o) && EQ (XCDR (o), ltv_mark))
980 o = XCAR (o);
981 return o;
984 /* Attempt to convert O to an emacs_value. Do not do any checking
985 or allocate any storage; the caller should prevent or detect
986 any resulting bit pattern that is not a valid emacs_value. */
987 static emacs_value
988 lisp_to_value_bits (Lisp_Object o)
990 if (plain_values || USE_LSB_TAG)
991 return XLP (o);
993 /* Compress O into the space of a pointer, possibly losing information. */
994 EMACS_UINT u = XLI (o);
995 if (INTEGERP (o))
997 uintptr_t i = (u << VALBITS) + XTYPE (o);
998 return (emacs_value) i;
1000 else
1002 char *p = XLP (o);
1003 void *v = p - (u & ~VALMASK) + XTYPE (o);
1004 return v;
1008 /* Convert O to an emacs_value. Allocate storage if needed; this can
1009 signal if memory is exhausted. Must be an injective function. */
1010 static emacs_value
1011 lisp_to_value (emacs_env *env, Lisp_Object o)
1013 if (module_assertions)
1015 /* Add the new value to the list of values allocated from this
1016 environment. The value is actually a pointer to the
1017 Lisp_Object cast to emacs_value. We make a copy of the
1018 object on the free store to guarantee unique addresses. */
1019 ATTRIBUTE_MAY_ALIAS Lisp_Object *optr = xmalloc (sizeof o);
1020 *optr = o;
1021 void *vptr = optr;
1022 ATTRIBUTE_MAY_ALIAS emacs_value ret = vptr;
1023 struct emacs_env_private *priv = env->private_members;
1024 priv->values = Fcons (make_mint_ptr (ret), priv->values);
1025 return ret;
1028 emacs_value v = lisp_to_value_bits (o);
1030 if (! EQ (o, value_to_lisp_bits (v)))
1032 /* Package the incompressible object pointer inside a pair
1033 that is compressible. */
1034 Lisp_Object pair = Fcons (o, ltv_mark);
1035 v = (emacs_value) ((intptr_t) XCONS (pair) + Lisp_Cons);
1038 eassert (EQ (o, value_to_lisp (v)));
1039 return v;
1043 /* Environment lifetime management. */
1045 /* Must be called before the environment can be used. Returns another
1046 pointer that callers should use instead of the ENV argument. If
1047 module assertions are disabled, the return value is ENV. If module
1048 assertions are enabled, the return value points to a heap-allocated
1049 object. That object is never freed to guarantee unique
1050 addresses. */
1051 static emacs_env *
1052 initialize_environment (emacs_env *env, struct emacs_env_private *priv)
1054 if (module_assertions)
1055 env = xmalloc (sizeof *env);
1057 priv->pending_non_local_exit = emacs_funcall_exit_return;
1058 priv->values = priv->non_local_exit_symbol = priv->non_local_exit_data = Qnil;
1059 env->size = sizeof *env;
1060 env->private_members = priv;
1061 env->make_global_ref = module_make_global_ref;
1062 env->free_global_ref = module_free_global_ref;
1063 env->non_local_exit_check = module_non_local_exit_check;
1064 env->non_local_exit_clear = module_non_local_exit_clear;
1065 env->non_local_exit_get = module_non_local_exit_get;
1066 env->non_local_exit_signal = module_non_local_exit_signal;
1067 env->non_local_exit_throw = module_non_local_exit_throw;
1068 env->make_function = module_make_function;
1069 env->funcall = module_funcall;
1070 env->intern = module_intern;
1071 env->type_of = module_type_of;
1072 env->is_not_nil = module_is_not_nil;
1073 env->eq = module_eq;
1074 env->extract_integer = module_extract_integer;
1075 env->make_integer = module_make_integer;
1076 env->extract_float = module_extract_float;
1077 env->make_float = module_make_float;
1078 env->copy_string_contents = module_copy_string_contents;
1079 env->make_string = module_make_string;
1080 env->make_user_ptr = module_make_user_ptr;
1081 env->get_user_ptr = module_get_user_ptr;
1082 env->set_user_ptr = module_set_user_ptr;
1083 env->get_user_finalizer = module_get_user_finalizer;
1084 env->set_user_finalizer = module_set_user_finalizer;
1085 env->vec_set = module_vec_set;
1086 env->vec_get = module_vec_get;
1087 env->vec_size = module_vec_size;
1088 env->should_quit = module_should_quit;
1089 Vmodule_environments = Fcons (make_mint_ptr (env), Vmodule_environments);
1090 return env;
1093 /* Must be called before the lifetime of the environment object
1094 ends. */
1095 static void
1096 finalize_environment (emacs_env *env)
1098 eassert (xmint_pointer (XCAR (Vmodule_environments)) == env);
1099 Vmodule_environments = XCDR (Vmodule_environments);
1100 if (module_assertions)
1101 /* There is always at least the global environment. */
1102 eassert (CONSP (Vmodule_environments));
1105 static void
1106 finalize_environment_unwind (void *env)
1108 finalize_environment (env);
1111 static void
1112 finalize_runtime_unwind (void *raw_ert)
1114 struct emacs_runtime *ert = raw_ert;
1115 eassert (xmint_pointer (XCAR (Vmodule_runtimes)) == ert);
1116 Vmodule_runtimes = XCDR (Vmodule_runtimes);
1117 finalize_environment (ert->private_members->env);
1120 void
1121 mark_modules (void)
1123 for (Lisp_Object tail = Vmodule_environments; CONSP (tail);
1124 tail = XCDR (tail))
1126 emacs_env *env = xmint_pointer (XCAR (tail));
1127 struct emacs_env_private *priv = env->private_members;
1128 mark_object (priv->non_local_exit_symbol);
1129 mark_object (priv->non_local_exit_data);
1130 mark_object (priv->values);
1135 /* Non-local exit handling. */
1137 /* Must be called after setting up a handler immediately before
1138 returning from the function. See the comments in lisp.h and the
1139 code in eval.c for details. The macros below arrange for this
1140 function to be called automatically. PHANDLERLIST points to a word
1141 containing the handler list, for sanity checking. */
1142 static void
1143 module_reset_handlerlist (struct handler **phandlerlist)
1145 eassert (handlerlist == *phandlerlist);
1146 handlerlist = handlerlist->next;
1149 /* Called on `signal'. ERR is a pair (SYMBOL . DATA), which gets
1150 stored in the environment. Set the pending non-local exit flag. */
1151 static void
1152 module_handle_signal (emacs_env *env, Lisp_Object err)
1154 module_non_local_exit_signal_1 (env, XCAR (err), XCDR (err));
1157 /* Called on `throw'. TAG_VAL is a pair (TAG . VALUE), which gets
1158 stored in the environment. Set the pending non-local exit flag. */
1159 static void
1160 module_handle_throw (emacs_env *env, Lisp_Object tag_val)
1162 module_non_local_exit_throw_1 (env, XCAR (tag_val), XCDR (tag_val));
1166 /* Support for assertions. */
1167 void
1168 init_module_assertions (bool enable)
1170 /* If enabling module assertions, use a hidden environment for
1171 storing the globals. This environment is never freed. */
1172 module_assertions = enable;
1173 if (enable)
1174 global_env = initialize_environment (NULL, &global_env_private);
1177 static _Noreturn void
1178 ATTRIBUTE_FORMAT_PRINTF(1, 2)
1179 module_abort (const char *format, ...)
1181 fputs ("Emacs module assertion: ", stderr);
1182 va_list args;
1183 va_start (args, format);
1184 vfprintf (stderr, format, args);
1185 va_end (args);
1186 putc ('\n', stderr);
1187 fflush (NULL);
1188 emacs_abort ();
1192 /* Segment initializer. */
1194 void
1195 syms_of_module (void)
1197 if (!plain_values)
1198 ltv_mark = Fcons (Qnil, Qnil);
1199 eassert (NILP (value_to_lisp (module_nil)));
1201 DEFSYM (Qmodule_refs_hash, "module-refs-hash");
1202 DEFVAR_LISP ("module-refs-hash", Vmodule_refs_hash,
1203 doc: /* Module global reference table. */);
1205 Vmodule_refs_hash
1206 = make_hash_table (hashtest_eq, DEFAULT_HASH_SIZE,
1207 DEFAULT_REHASH_SIZE, DEFAULT_REHASH_THRESHOLD,
1208 Qnil, false);
1209 Funintern (Qmodule_refs_hash, Qnil);
1211 DEFSYM (Qmodule_runtimes, "module-runtimes");
1212 DEFVAR_LISP ("module-runtimes", Vmodule_runtimes,
1213 doc: /* List of active module runtimes. */);
1214 Vmodule_runtimes = Qnil;
1215 /* Unintern `module-runtimes' because it is only used
1216 internally. */
1217 Funintern (Qmodule_runtimes, Qnil);
1219 DEFSYM (Qmodule_environments, "module-environments");
1220 DEFVAR_LISP ("module-environments", Vmodule_environments,
1221 doc: /* List of active module environments. */);
1222 Vmodule_environments = Qnil;
1223 /* Unintern `module-environments' because it is only used
1224 internally. */
1225 Funintern (Qmodule_environments, Qnil);
1227 DEFSYM (Qmodule_load_failed, "module-load-failed");
1228 Fput (Qmodule_load_failed, Qerror_conditions,
1229 listn (CONSTYPE_PURE, 2, Qmodule_load_failed, Qerror));
1230 Fput (Qmodule_load_failed, Qerror_message,
1231 build_pure_c_string ("Module load failed"));
1233 DEFSYM (Qmodule_open_failed, "module-open-failed");
1234 Fput (Qmodule_open_failed, Qerror_conditions,
1235 listn (CONSTYPE_PURE, 3,
1236 Qmodule_open_failed, Qmodule_load_failed, Qerror));
1237 Fput (Qmodule_open_failed, Qerror_message,
1238 build_pure_c_string ("Module could not be opened"));
1240 DEFSYM (Qmodule_not_gpl_compatible, "module-not-gpl-compatible");
1241 Fput (Qmodule_not_gpl_compatible, Qerror_conditions,
1242 listn (CONSTYPE_PURE, 3,
1243 Qmodule_not_gpl_compatible, Qmodule_load_failed, Qerror));
1244 Fput (Qmodule_not_gpl_compatible, Qerror_message,
1245 build_pure_c_string ("Module is not GPL compatible"));
1247 DEFSYM (Qmissing_module_init_function, "missing-module-init-function");
1248 Fput (Qmissing_module_init_function, Qerror_conditions,
1249 listn (CONSTYPE_PURE, 3,
1250 Qmissing_module_init_function, Qmodule_load_failed, Qerror));
1251 Fput (Qmissing_module_init_function, Qerror_message,
1252 build_pure_c_string ("Module does not export an "
1253 "initialization function"));
1255 DEFSYM (Qmodule_init_failed, "module-init-failed");
1256 Fput (Qmodule_init_failed, Qerror_conditions,
1257 listn (CONSTYPE_PURE, 3,
1258 Qmodule_init_failed, Qmodule_load_failed, Qerror));
1259 Fput (Qmodule_init_failed, Qerror_message,
1260 build_pure_c_string ("Module initialization failed"));
1262 DEFSYM (Qinvalid_arity, "invalid-arity");
1263 Fput (Qinvalid_arity, Qerror_conditions,
1264 listn (CONSTYPE_PURE, 2, Qinvalid_arity, Qerror));
1265 Fput (Qinvalid_arity, Qerror_message,
1266 build_pure_c_string ("Invalid function arity"));
1268 /* Unintern `module-refs-hash' because it is internal-only and Lisp
1269 code or modules should not access it. */
1270 Funintern (Qmodule_refs_hash, Qnil);
1272 DEFSYM (Qmodule_function_p, "module-function-p");
1274 defsubr (&Smodule_load);