* lisp/mail/smtpmail.el (smtpmail-send-data-1): No string-as-multibyte
[emacs.git] / src / emacs-module.c
blob4ee4014b4e19eaa9353d6bc7bb726eba0b18d396
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 bool
809 in_current_thread (void)
811 if (current_thread == NULL)
812 return false;
813 #ifdef HAVE_PTHREAD
814 return pthread_equal (pthread_self (), current_thread->thread_id);
815 #elif defined WINDOWSNT
816 return GetCurrentThreadId () == current_thread->thread_id;
817 #endif
820 static void
821 module_assert_thread (void)
823 if (!module_assertions)
824 return;
825 if (!in_current_thread ())
826 module_abort ("Module function called from outside "
827 "the current Lisp thread");
828 if (gc_in_progress)
829 module_abort ("Module function called during garbage collection");
832 static void
833 module_assert_runtime (struct emacs_runtime *ert)
835 if (! module_assertions)
836 return;
837 ptrdiff_t count = 0;
838 for (Lisp_Object tail = Vmodule_runtimes; CONSP (tail); tail = XCDR (tail))
840 if (XSAVE_POINTER (XCAR (tail), 0) == ert)
841 return;
842 ++count;
844 module_abort ("Runtime pointer not found in list of %"pD"d runtimes",
845 count);
848 static void
849 module_assert_env (emacs_env *env)
851 if (! module_assertions)
852 return;
853 ptrdiff_t count = 0;
854 for (Lisp_Object tail = Vmodule_environments; CONSP (tail);
855 tail = XCDR (tail))
857 if (XSAVE_POINTER (XCAR (tail), 0) == env)
858 return;
859 ++count;
861 module_abort ("Environment pointer not found in list of %"pD"d environments",
862 count);
865 static void
866 module_non_local_exit_signal_1 (emacs_env *env, Lisp_Object sym,
867 Lisp_Object data)
869 struct emacs_env_private *p = env->private_members;
870 if (p->pending_non_local_exit == emacs_funcall_exit_return)
872 p->pending_non_local_exit = emacs_funcall_exit_signal;
873 p->non_local_exit_symbol = sym;
874 p->non_local_exit_data = data;
878 static void
879 module_non_local_exit_throw_1 (emacs_env *env, Lisp_Object tag,
880 Lisp_Object value)
882 struct emacs_env_private *p = env->private_members;
883 if (p->pending_non_local_exit == emacs_funcall_exit_return)
885 p->pending_non_local_exit = emacs_funcall_exit_throw;
886 p->non_local_exit_symbol = tag;
887 p->non_local_exit_data = value;
891 /* Signal an out-of-memory condition to the caller. */
892 static void
893 module_out_of_memory (emacs_env *env)
895 /* TODO: Reimplement this so it works even if memory-signal-data has
896 been modified. */
897 module_non_local_exit_signal_1 (env, XCAR (Vmemory_signal_data),
898 XCDR (Vmemory_signal_data));
902 /* Value conversion. */
904 /* We represent Lisp objects differently depending on whether the user
905 gave -module-assertions. If assertions are disabled, emacs_value
906 objects are Lisp_Objects cast to emacs_value. If assertions are
907 enabled, emacs_value objects are pointers to Lisp_Object objects
908 allocated from the free store; they are never freed, which ensures
909 that their addresses are unique and can be used for liveness
910 checking. */
912 /* Unique Lisp_Object used to mark those emacs_values which are really
913 just containers holding a Lisp_Object that does not fit as an emacs_value,
914 either because it is an integer out of range, or is not properly aligned.
915 Used only if !plain_values. */
916 static Lisp_Object ltv_mark;
918 /* Convert V to the corresponding internal object O, such that
919 V == lisp_to_value_bits (O). Never fails. */
920 static Lisp_Object
921 value_to_lisp_bits (emacs_value v)
923 if (plain_values || USE_LSB_TAG)
924 return XPL (v);
926 /* With wide EMACS_INT and when tag bits are the most significant,
927 reassembling integers differs from reassembling pointers in two
928 ways. First, save and restore the least-significant bits of the
929 integer, not the most-significant bits. Second, sign-extend the
930 integer when restoring, but zero-extend pointers because that
931 makes TAG_PTR faster. */
933 intptr_t i = (intptr_t) v;
934 EMACS_UINT tag = i & (GCALIGNMENT - 1);
935 EMACS_UINT untagged = i - tag;
936 switch (tag)
938 case_Lisp_Int:
940 bool negative = tag & 1;
941 EMACS_UINT sign_extension
942 = negative ? VALMASK & ~(INTPTR_MAX >> INTTYPEBITS): 0;
943 uintptr_t u = i;
944 intptr_t all_but_sign = u >> GCTYPEBITS;
945 untagged = sign_extension + all_but_sign;
946 break;
950 return XIL ((tag << VALBITS) + untagged);
953 /* If V was computed from lisp_to_value (O), then return O.
954 Exits non-locally only if the stack overflows. */
955 static Lisp_Object
956 value_to_lisp (emacs_value v)
958 if (module_assertions)
960 /* Check the liveness of the value by iterating over all live
961 environments. */
962 void *vptr = v;
963 ATTRIBUTE_MAY_ALIAS Lisp_Object *optr = vptr;
964 ptrdiff_t num_environments = 0;
965 ptrdiff_t num_values = 0;
966 for (Lisp_Object environments = Vmodule_environments;
967 CONSP (environments); environments = XCDR (environments))
969 emacs_env *env = XSAVE_POINTER (XCAR (environments), 0);
970 for (Lisp_Object values = env->private_members->values;
971 CONSP (values); values = XCDR (values))
973 Lisp_Object *p = XSAVE_POINTER (XCAR (values), 0);
974 if (p == optr)
975 return *p;
976 ++num_values;
978 ++num_environments;
980 module_abort (("Emacs value not found in %"pD"d values "
981 "of %"pD"d environments"),
982 num_values, num_environments);
985 Lisp_Object o = value_to_lisp_bits (v);
986 if (! plain_values && CONSP (o) && EQ (XCDR (o), ltv_mark))
987 o = XCAR (o);
988 return o;
991 /* Attempt to convert O to an emacs_value. Do not do any checking
992 or allocate any storage; the caller should prevent or detect
993 any resulting bit pattern that is not a valid emacs_value. */
994 static emacs_value
995 lisp_to_value_bits (Lisp_Object o)
997 if (plain_values || USE_LSB_TAG)
998 return XLP (o);
1000 /* Compress O into the space of a pointer, possibly losing information. */
1001 EMACS_UINT u = XLI (o);
1002 if (INTEGERP (o))
1004 uintptr_t i = (u << VALBITS) + XTYPE (o);
1005 return (emacs_value) i;
1007 else
1009 char *p = XLP (o);
1010 void *v = p - (u & ~VALMASK) + XTYPE (o);
1011 return v;
1015 /* Convert O to an emacs_value. Allocate storage if needed; this can
1016 signal if memory is exhausted. Must be an injective function. */
1017 static emacs_value
1018 lisp_to_value (emacs_env *env, Lisp_Object o)
1020 if (module_assertions)
1022 /* Add the new value to the list of values allocated from this
1023 environment. The value is actually a pointer to the
1024 Lisp_Object cast to emacs_value. We make a copy of the
1025 object on the free store to guarantee unique addresses. */
1026 ATTRIBUTE_MAY_ALIAS Lisp_Object *optr = xmalloc (sizeof o);
1027 *optr = o;
1028 void *vptr = optr;
1029 ATTRIBUTE_MAY_ALIAS emacs_value ret = vptr;
1030 struct emacs_env_private *priv = env->private_members;
1031 priv->values = Fcons (make_save_ptr (ret), priv->values);
1032 return ret;
1035 emacs_value v = lisp_to_value_bits (o);
1037 if (! EQ (o, value_to_lisp_bits (v)))
1039 /* Package the incompressible object pointer inside a pair
1040 that is compressible. */
1041 Lisp_Object pair = Fcons (o, ltv_mark);
1042 v = (emacs_value) ((intptr_t) XCONS (pair) + Lisp_Cons);
1045 eassert (EQ (o, value_to_lisp (v)));
1046 return v;
1050 /* Environment lifetime management. */
1052 /* Must be called before the environment can be used. Returns another
1053 pointer that callers should use instead of the ENV argument. If
1054 module assertions are disabled, the return value is ENV. If module
1055 assertions are enabled, the return value points to a heap-allocated
1056 object. That object is never freed to guarantee unique
1057 addresses. */
1058 static emacs_env *
1059 initialize_environment (emacs_env *env, struct emacs_env_private *priv)
1061 if (module_assertions)
1062 env = xmalloc (sizeof *env);
1064 priv->pending_non_local_exit = emacs_funcall_exit_return;
1065 priv->values = priv->non_local_exit_symbol = priv->non_local_exit_data = Qnil;
1066 env->size = sizeof *env;
1067 env->private_members = priv;
1068 env->make_global_ref = module_make_global_ref;
1069 env->free_global_ref = module_free_global_ref;
1070 env->non_local_exit_check = module_non_local_exit_check;
1071 env->non_local_exit_clear = module_non_local_exit_clear;
1072 env->non_local_exit_get = module_non_local_exit_get;
1073 env->non_local_exit_signal = module_non_local_exit_signal;
1074 env->non_local_exit_throw = module_non_local_exit_throw;
1075 env->make_function = module_make_function;
1076 env->funcall = module_funcall;
1077 env->intern = module_intern;
1078 env->type_of = module_type_of;
1079 env->is_not_nil = module_is_not_nil;
1080 env->eq = module_eq;
1081 env->extract_integer = module_extract_integer;
1082 env->make_integer = module_make_integer;
1083 env->extract_float = module_extract_float;
1084 env->make_float = module_make_float;
1085 env->copy_string_contents = module_copy_string_contents;
1086 env->make_string = module_make_string;
1087 env->make_user_ptr = module_make_user_ptr;
1088 env->get_user_ptr = module_get_user_ptr;
1089 env->set_user_ptr = module_set_user_ptr;
1090 env->get_user_finalizer = module_get_user_finalizer;
1091 env->set_user_finalizer = module_set_user_finalizer;
1092 env->vec_set = module_vec_set;
1093 env->vec_get = module_vec_get;
1094 env->vec_size = module_vec_size;
1095 env->should_quit = module_should_quit;
1096 Vmodule_environments = Fcons (make_save_ptr (env), Vmodule_environments);
1097 return env;
1100 /* Must be called before the lifetime of the environment object
1101 ends. */
1102 static void
1103 finalize_environment (emacs_env *env)
1105 eassert (XSAVE_POINTER (XCAR (Vmodule_environments), 0) == env);
1106 Vmodule_environments = XCDR (Vmodule_environments);
1107 if (module_assertions)
1108 /* There is always at least the global environment. */
1109 eassert (CONSP (Vmodule_environments));
1112 static void
1113 finalize_environment_unwind (void *env)
1115 finalize_environment (env);
1118 static void
1119 finalize_runtime_unwind (void* raw_ert)
1121 struct emacs_runtime *ert = raw_ert;
1122 eassert (XSAVE_POINTER (XCAR (Vmodule_runtimes), 0) == ert);
1123 Vmodule_runtimes = XCDR (Vmodule_runtimes);
1124 finalize_environment (ert->private_members->env);
1127 void
1128 mark_modules (void)
1130 for (Lisp_Object tail = Vmodule_environments; CONSP (tail);
1131 tail = XCDR (tail))
1133 emacs_env *env = XSAVE_POINTER (XCAR (tail), 0);
1134 struct emacs_env_private *priv = env->private_members;
1135 mark_object (priv->non_local_exit_symbol);
1136 mark_object (priv->non_local_exit_data);
1137 mark_object (priv->values);
1142 /* Non-local exit handling. */
1144 /* Must be called after setting up a handler immediately before
1145 returning from the function. See the comments in lisp.h and the
1146 code in eval.c for details. The macros below arrange for this
1147 function to be called automatically. PHANDLERLIST points to a word
1148 containing the handler list, for sanity checking. */
1149 static void
1150 module_reset_handlerlist (struct handler **phandlerlist)
1152 eassert (handlerlist == *phandlerlist);
1153 handlerlist = handlerlist->next;
1156 /* Called on `signal'. ERR is a pair (SYMBOL . DATA), which gets
1157 stored in the environment. Set the pending non-local exit flag. */
1158 static void
1159 module_handle_signal (emacs_env *env, Lisp_Object err)
1161 module_non_local_exit_signal_1 (env, XCAR (err), XCDR (err));
1164 /* Called on `throw'. TAG_VAL is a pair (TAG . VALUE), which gets
1165 stored in the environment. Set the pending non-local exit flag. */
1166 static void
1167 module_handle_throw (emacs_env *env, Lisp_Object tag_val)
1169 module_non_local_exit_throw_1 (env, XCAR (tag_val), XCDR (tag_val));
1173 /* Support for assertions. */
1174 void
1175 init_module_assertions (bool enable)
1177 module_assertions = enable;
1178 if (enable)
1180 /* We use a hidden environment for storing the globals. This
1181 environment is never freed. */
1182 emacs_env env;
1183 global_env = initialize_environment (&env, &global_env_private);
1184 eassert (global_env != &env);
1188 static _Noreturn void
1189 ATTRIBUTE_FORMAT_PRINTF(1, 2)
1190 module_abort (const char *format, ...)
1192 fputs ("Emacs module assertion: ", stderr);
1193 va_list args;
1194 va_start (args, format);
1195 vfprintf (stderr, format, args);
1196 va_end (args);
1197 putc ('\n', stderr);
1198 fflush (NULL);
1199 emacs_abort ();
1203 /* Segment initializer. */
1205 void
1206 syms_of_module (void)
1208 if (!plain_values)
1209 ltv_mark = Fcons (Qnil, Qnil);
1210 eassert (NILP (value_to_lisp (module_nil)));
1212 DEFSYM (Qmodule_refs_hash, "module-refs-hash");
1213 DEFVAR_LISP ("module-refs-hash", Vmodule_refs_hash,
1214 doc: /* Module global reference table. */);
1216 Vmodule_refs_hash
1217 = make_hash_table (hashtest_eq, DEFAULT_HASH_SIZE,
1218 DEFAULT_REHASH_SIZE, DEFAULT_REHASH_THRESHOLD,
1219 Qnil, false);
1220 Funintern (Qmodule_refs_hash, Qnil);
1222 DEFSYM (Qmodule_runtimes, "module-runtimes");
1223 DEFVAR_LISP ("module-runtimes", Vmodule_runtimes,
1224 doc: /* List of active module runtimes. */);
1225 Vmodule_runtimes = Qnil;
1226 /* Unintern `module-runtimes' because it is only used
1227 internally. */
1228 Funintern (Qmodule_runtimes, Qnil);
1230 DEFSYM (Qmodule_environments, "module-environments");
1231 DEFVAR_LISP ("module-environments", Vmodule_environments,
1232 doc: /* List of active module environments. */);
1233 Vmodule_environments = Qnil;
1234 /* Unintern `module-environments' because it is only used
1235 internally. */
1236 Funintern (Qmodule_environments, Qnil);
1238 DEFSYM (Qmodule_load_failed, "module-load-failed");
1239 Fput (Qmodule_load_failed, Qerror_conditions,
1240 listn (CONSTYPE_PURE, 2, Qmodule_load_failed, Qerror));
1241 Fput (Qmodule_load_failed, Qerror_message,
1242 build_pure_c_string ("Module load failed"));
1244 DEFSYM (Qmodule_open_failed, "module-open-failed");
1245 Fput (Qmodule_open_failed, Qerror_conditions,
1246 listn (CONSTYPE_PURE, 3,
1247 Qmodule_open_failed, Qmodule_load_failed, Qerror));
1248 Fput (Qmodule_open_failed, Qerror_message,
1249 build_pure_c_string ("Module could not be opened"));
1251 DEFSYM (Qmodule_not_gpl_compatible, "module-not-gpl-compatible");
1252 Fput (Qmodule_not_gpl_compatible, Qerror_conditions,
1253 listn (CONSTYPE_PURE, 3,
1254 Qmodule_not_gpl_compatible, Qmodule_load_failed, Qerror));
1255 Fput (Qmodule_not_gpl_compatible, Qerror_message,
1256 build_pure_c_string ("Module is not GPL compatible"));
1258 DEFSYM (Qmissing_module_init_function, "missing-module-init-function");
1259 Fput (Qmissing_module_init_function, Qerror_conditions,
1260 listn (CONSTYPE_PURE, 3,
1261 Qmissing_module_init_function, Qmodule_load_failed, Qerror));
1262 Fput (Qmissing_module_init_function, Qerror_message,
1263 build_pure_c_string ("Module does not export an "
1264 "initialization function"));
1266 DEFSYM (Qmodule_init_failed, "module-init-failed");
1267 Fput (Qmodule_init_failed, Qerror_conditions,
1268 listn (CONSTYPE_PURE, 3,
1269 Qmodule_init_failed, Qmodule_load_failed, Qerror));
1270 Fput (Qmodule_init_failed, Qerror_message,
1271 build_pure_c_string ("Module initialization failed"));
1273 DEFSYM (Qinvalid_arity, "invalid-arity");
1274 Fput (Qinvalid_arity, Qerror_conditions,
1275 listn (CONSTYPE_PURE, 2, Qinvalid_arity, Qerror));
1276 Fput (Qinvalid_arity, Qerror_message,
1277 build_pure_c_string ("Invalid function arity"));
1279 /* Unintern `module-refs-hash' because it is internal-only and Lisp
1280 code or modules should not access it. */
1281 Funintern (Qmodule_refs_hash, Qnil);
1283 DEFSYM (Qmodule_function_p, "module-function-p");
1285 defsubr (&Smodule_load);