1 /* emacs-module.c - Module loading and runtime implementation
3 Copyright (C) 2015-2017 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/>. */
22 #include "emacs-module.h"
33 #include "syssignal.h"
39 /* We use different strategies for allocating the user-visible objects
40 (struct emacs_runtime, emacs_env, emacs_value), depending on
41 whether the user supplied the -module-assertions flag. If
42 assertions are disabled, all objects are allocated from the stack.
43 If assertions are enabled, all objects are allocated from the free
44 store, and objects are never freed; this guarantees that they all
45 have different addresses. We use that for checking which objects
46 are live. Without unique addresses, we might consider some dead
47 objects live because their addresses would have been reused in the
58 /* True if Lisp_Object and emacs_value have the same representation.
59 This is typically true unless WIDE_EMACS_INT. In practice, having
60 the same sizes and alignments and maximums should be a good enough
61 proxy for equality of representation. */
65 = (sizeof (Lisp_Object
) == sizeof (emacs_value
)
66 && alignof (Lisp_Object
) == alignof (emacs_value
)
67 && INTPTR_MAX
== EMACS_INT_MAX
)
70 /* Function prototype for the module init function. */
71 typedef int (*emacs_init_function
) (struct emacs_runtime
*);
73 /* Function prototype for module user-pointer finalizers. These
74 should not throw C++ exceptions, so emacs-module.h declares the
75 corresponding interfaces with EMACS_NOEXCEPT. There is only C code
76 in this module, though, so this constraint is not enforced here. */
77 typedef void (*emacs_finalizer_function
) (void *);
80 /* Private runtime and environment members. */
82 /* The private part of an environment stores the current non local exit state
83 and holds the `emacs_value' objects allocated during the lifetime
84 of the environment. */
85 struct emacs_env_private
87 enum emacs_funcall_exit pending_non_local_exit
;
89 /* Dedicated storage for non-local exit symbol and data so that
90 storage is always available for them, even in an out-of-memory
92 Lisp_Object non_local_exit_symbol
, non_local_exit_data
;
94 /* List of values allocated from this environment. The code uses
95 this only if the user gave the -module-assertions command-line
100 /* The private parts of an `emacs_runtime' object contain the initial
102 struct emacs_runtime_private
108 /* Forward declarations. */
110 static Lisp_Object
value_to_lisp (emacs_value
);
111 static emacs_value
lisp_to_value (emacs_env
*, Lisp_Object
);
112 static enum emacs_funcall_exit
module_non_local_exit_check (emacs_env
*);
113 static void module_assert_thread (void);
114 static void module_assert_runtime (struct emacs_runtime
*);
115 static void module_assert_env (emacs_env
*);
116 static _Noreturn
void module_abort (const char *format
, ...)
117 ATTRIBUTE_FORMAT_PRINTF(1, 2);
118 static emacs_env
*initialize_environment (emacs_env
*,
119 struct emacs_env_private
*);
120 static void finalize_environment (emacs_env
*);
121 static void finalize_environment_unwind (void *);
122 static void finalize_runtime_unwind (void *);
123 static void module_handle_signal (emacs_env
*, Lisp_Object
);
124 static void module_handle_throw (emacs_env
*, Lisp_Object
);
125 static void module_non_local_exit_signal_1 (emacs_env
*,
126 Lisp_Object
, Lisp_Object
);
127 static void module_non_local_exit_throw_1 (emacs_env
*,
128 Lisp_Object
, Lisp_Object
);
129 static void module_out_of_memory (emacs_env
*);
130 static void module_reset_handlerlist (struct handler
**);
132 /* We used to return NULL when emacs_value was a different type from
133 Lisp_Object, but nowadays we just use Qnil instead. Although they
134 happen to be the same thing in the current implementation, module
135 code should not assume this. */
136 verify (NIL_IS_ZERO
);
137 static emacs_value
const module_nil
= 0;
139 static bool module_assertions
= false;
140 static emacs_env
*global_env
;
141 static struct emacs_env_private global_env_private
;
143 /* Convenience macros for non-local exit handling. */
145 /* FIXME: The following implementation for non-local exit handling
146 does not support recovery from stack overflow, see sysdep.c. */
148 /* Emacs uses setjmp and longjmp for non-local exits, but
149 module frames cannot be skipped because they are in general
150 not prepared for long jumps (e.g., the behavior in C++ is undefined
151 if objects with nontrivial destructors would be skipped).
152 Therefore, catch all non-local exits. There are two kinds of
153 non-local exits: `signal' and `throw'. The macros in this section
154 can be used to catch both. Use macros to avoid additional variants
155 of `internal_condition_case' etc., and to avoid worrying about
156 passing information to the handler functions. */
158 /* Place this macro at the beginning of a function returning a number
159 or a pointer to handle non-local exits. The function must have an
160 ENV parameter. The function will return the specified value if a
161 signal or throw is caught. */
162 /* TODO: Have Fsignal check for CATCHER_ALL so we only have to install
164 #define MODULE_HANDLE_NONLOCAL_EXIT(retval) \
165 MODULE_SETJMP (CONDITION_CASE, module_handle_signal, retval); \
166 MODULE_SETJMP (CATCHER_ALL, module_handle_throw, retval)
168 #define MODULE_SETJMP(handlertype, handlerfunc, retval) \
169 MODULE_SETJMP_1 (handlertype, handlerfunc, retval, \
170 internal_handler_##handlertype, \
171 internal_cleanup_##handlertype)
173 #if !__has_attribute (cleanup)
174 #error "__attribute__ ((cleanup)) not supported by this compiler; try GCC"
177 /* It is very important that pushing the handler doesn't itself raise
178 a signal. Install the cleanup only after the handler has been
179 pushed. Use __attribute__ ((cleanup)) to avoid
180 non-local-exit-prone manual cleanup.
182 The do-while forces uses of the macro to be followed by a semicolon.
183 This macro cannot enclose its entire body inside a do-while, as the
184 code after the macro may longjmp back into the macro, which means
185 its local variable C must stay live in later code. */
187 /* TODO: Make backtraces work if this macros is used. */
189 #define MODULE_SETJMP_1(handlertype, handlerfunc, retval, c0, c) \
190 if (module_non_local_exit_check (env) != emacs_funcall_exit_return) \
192 struct handler *c0 = push_handler_nosignal (Qt, handlertype); \
195 module_out_of_memory (env); \
198 struct handler *c __attribute__ ((cleanup (module_reset_handlerlist))) \
200 if (sys_setjmp (c->jmp)) \
202 (handlerfunc) (env, c->val); \
208 /* Implementation of runtime and environment functions.
210 These should abide by the following rules:
212 1. The first argument should always be a pointer to emacs_env.
214 2. Each function should first call check_thread. Note that
215 this function is a no-op unless Emacs was built with
218 3. The very next thing each function should do is check that the
219 emacs_env object does not have a non-local exit indication set,
220 by calling module_non_local_exit_check. If that returns
221 anything but emacs_funcall_exit_return, the function should do
222 nothing and return immediately with an error indication, without
223 clobbering the existing error indication in emacs_env. This is
224 needed for correct reporting of Lisp errors to the Emacs Lisp
227 4. Any function that needs to call Emacs facilities, such as
228 encoding or decoding functions, or 'intern', or 'make_string',
229 should protect itself from signals and 'throw' in the called
230 Emacs functions, by placing the macro
231 MODULE_HANDLE_NONLOCAL_EXIT right after the above 2 tests.
233 5. Do NOT use 'eassert' for checking validity of user code in the
234 module. Instead, make those checks part of the code, and if the
235 check fails, call 'module_non_local_exit_signal_1' or
236 'module_non_local_exit_throw_1' to report the error. This is
237 because using 'eassert' in these situations will abort Emacs
238 instead of reporting the error back to Lisp, and also because
239 'eassert' is compiled to nothing in the release version. */
241 /* Use MODULE_FUNCTION_BEGIN_NO_CATCH to implement steps 2 and 3 for
242 environment functions that are known to never exit non-locally. On
243 error it will return its argument, which can be a sentinel
246 #define MODULE_FUNCTION_BEGIN_NO_CATCH(error_retval) \
248 module_assert_thread (); \
249 module_assert_env (env); \
250 if (module_non_local_exit_check (env) != emacs_funcall_exit_return) \
251 return error_retval; \
254 /* Use MODULE_FUNCTION_BEGIN to implement steps 2 through 4 for most
255 environment functions. On error it will return its argument, which
256 can be a sentinel value. */
258 #define MODULE_FUNCTION_BEGIN(error_retval) \
259 MODULE_FUNCTION_BEGIN_NO_CATCH (error_retval); \
260 MODULE_HANDLE_NONLOCAL_EXIT (error_retval)
263 CHECK_USER_PTR (Lisp_Object obj
)
265 CHECK_TYPE (USER_PTRP (obj
), Quser_ptrp
, obj
);
268 /* Catch signals and throws only if the code can actually signal or
269 throw. If checking is enabled, abort if the current thread is not
270 the Emacs main thread. */
273 module_get_environment (struct emacs_runtime
*ert
)
275 module_assert_thread ();
276 module_assert_runtime (ert
);
277 return ert
->private_members
->env
;
280 /* To make global refs (GC-protected global values) keep a hash that
281 maps global Lisp objects to reference counts. */
284 module_make_global_ref (emacs_env
*env
, emacs_value ref
)
286 MODULE_FUNCTION_BEGIN (module_nil
);
287 struct Lisp_Hash_Table
*h
= XHASH_TABLE (Vmodule_refs_hash
);
288 Lisp_Object new_obj
= value_to_lisp (ref
);
290 ptrdiff_t i
= hash_lookup (h
, new_obj
, &hashcode
);
294 Lisp_Object value
= HASH_VALUE (h
, i
);
295 EMACS_INT refcount
= XFASTINT (value
) + 1;
296 if (MOST_POSITIVE_FIXNUM
< refcount
)
297 xsignal0 (Qoverflow_error
);
298 value
= make_natnum (refcount
);
299 set_hash_value_slot (h
, i
, value
);
303 hash_put (h
, new_obj
, make_natnum (1), hashcode
);
306 return lisp_to_value (module_assertions
? global_env
: env
, new_obj
);
310 module_free_global_ref (emacs_env
*env
, emacs_value ref
)
312 /* TODO: This probably never signals. */
313 /* FIXME: Wait a minute. Shouldn't this function report an error if
314 the hash lookup fails? */
315 MODULE_FUNCTION_BEGIN ();
316 struct Lisp_Hash_Table
*h
= XHASH_TABLE (Vmodule_refs_hash
);
317 Lisp_Object obj
= value_to_lisp (ref
);
318 ptrdiff_t i
= hash_lookup (h
, obj
, NULL
);
322 EMACS_INT refcount
= XFASTINT (HASH_VALUE (h
, i
)) - 1;
324 set_hash_value_slot (h
, i
, make_natnum (refcount
));
327 eassert (refcount
== 0);
328 hash_remove_from_table (h
, obj
);
332 if (module_assertions
)
334 Lisp_Object globals
= global_env_private
.values
;
335 Lisp_Object prev
= Qnil
;
337 for (Lisp_Object tail
= global_env_private
.values
; CONSP (tail
);
340 emacs_value global
= XSAVE_POINTER (XCAR (globals
), 0);
344 global_env_private
.values
= XCDR (globals
);
346 XSETCDR (prev
, XCDR (globals
));
352 module_abort ("Global value was not found in list of %"pD
"d globals",
357 static enum emacs_funcall_exit
358 module_non_local_exit_check (emacs_env
*env
)
360 module_assert_thread ();
361 module_assert_env (env
);
362 return env
->private_members
->pending_non_local_exit
;
366 module_non_local_exit_clear (emacs_env
*env
)
368 module_assert_thread ();
369 module_assert_env (env
);
370 env
->private_members
->pending_non_local_exit
= emacs_funcall_exit_return
;
373 static enum emacs_funcall_exit
374 module_non_local_exit_get (emacs_env
*env
, emacs_value
*sym
, emacs_value
*data
)
376 module_assert_thread ();
377 module_assert_env (env
);
378 struct emacs_env_private
*p
= env
->private_members
;
379 if (p
->pending_non_local_exit
!= emacs_funcall_exit_return
)
381 /* FIXME: lisp_to_value can exit non-locally. */
382 *sym
= lisp_to_value (env
, p
->non_local_exit_symbol
);
383 *data
= lisp_to_value (env
, p
->non_local_exit_data
);
385 return p
->pending_non_local_exit
;
388 /* Like for `signal', DATA must be a list. */
390 module_non_local_exit_signal (emacs_env
*env
, emacs_value sym
, emacs_value data
)
392 module_assert_thread ();
393 module_assert_env (env
);
394 if (module_non_local_exit_check (env
) == emacs_funcall_exit_return
)
395 module_non_local_exit_signal_1 (env
, value_to_lisp (sym
),
396 value_to_lisp (data
));
400 module_non_local_exit_throw (emacs_env
*env
, emacs_value tag
, emacs_value value
)
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_throw_1 (env
, value_to_lisp (tag
),
406 value_to_lisp (value
));
409 static struct Lisp_Module_Function
*
410 allocate_module_function (void)
412 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Module_Function
,
413 min_arity
, PVEC_MODULE_FUNCTION
);
416 #define XSET_MODULE_FUNCTION(var, ptr) \
417 XSETPSEUDOVECTOR (var, ptr, PVEC_MODULE_FUNCTION)
419 /* A module function is a pseudovector of subtype
420 PVEC_MODULE_FUNCTION; see lisp.h for the definition. */
423 module_make_function (emacs_env
*env
, ptrdiff_t min_arity
, ptrdiff_t max_arity
,
424 emacs_subr subr
, const char *documentation
,
427 MODULE_FUNCTION_BEGIN (module_nil
);
429 if (! (0 <= min_arity
431 ? (min_arity
<= MOST_POSITIVE_FIXNUM
432 && max_arity
== emacs_variadic_function
)
433 : min_arity
<= max_arity
&& max_arity
<= MOST_POSITIVE_FIXNUM
)))
434 xsignal2 (Qinvalid_arity
, make_number (min_arity
), make_number (max_arity
));
436 struct Lisp_Module_Function
*function
= allocate_module_function ();
437 function
->min_arity
= min_arity
;
438 function
->max_arity
= max_arity
;
439 function
->subr
= subr
;
440 function
->data
= data
;
444 AUTO_STRING (unibyte_doc
, documentation
);
445 function
->documentation
=
446 code_convert_string_norecord (unibyte_doc
, Qutf_8
, false);
450 XSET_MODULE_FUNCTION (result
, function
);
451 eassert (MODULE_FUNCTIONP (result
));
453 return lisp_to_value (env
, result
);
457 module_funcall (emacs_env
*env
, emacs_value fun
, ptrdiff_t nargs
,
460 MODULE_FUNCTION_BEGIN (module_nil
);
462 /* Make a new Lisp_Object array starting with the function as the
463 first arg, because that's what Ffuncall takes. */
464 Lisp_Object
*newargs
;
467 if (INT_ADD_WRAPV (nargs
, 1, &nargs1
))
468 xsignal0 (Qoverflow_error
);
469 SAFE_ALLOCA_LISP (newargs
, nargs1
);
470 newargs
[0] = value_to_lisp (fun
);
471 for (ptrdiff_t i
= 0; i
< nargs
; i
++)
472 newargs
[1 + i
] = value_to_lisp (args
[i
]);
473 emacs_value result
= lisp_to_value (env
, Ffuncall (nargs1
, newargs
));
479 module_intern (emacs_env
*env
, const char *name
)
481 MODULE_FUNCTION_BEGIN (module_nil
);
482 return lisp_to_value (env
, intern (name
));
486 module_type_of (emacs_env
*env
, emacs_value value
)
488 MODULE_FUNCTION_BEGIN (module_nil
);
489 return lisp_to_value (env
, Ftype_of (value_to_lisp (value
)));
493 module_is_not_nil (emacs_env
*env
, emacs_value value
)
495 MODULE_FUNCTION_BEGIN_NO_CATCH (false);
496 return ! NILP (value_to_lisp (value
));
500 module_eq (emacs_env
*env
, emacs_value a
, emacs_value b
)
502 MODULE_FUNCTION_BEGIN_NO_CATCH (false);
503 return EQ (value_to_lisp (a
), value_to_lisp (b
));
507 module_extract_integer (emacs_env
*env
, emacs_value n
)
509 MODULE_FUNCTION_BEGIN (0);
510 Lisp_Object l
= value_to_lisp (n
);
516 module_make_integer (emacs_env
*env
, intmax_t n
)
518 MODULE_FUNCTION_BEGIN (module_nil
);
519 if (FIXNUM_OVERFLOW_P (n
))
520 xsignal0 (Qoverflow_error
);
521 return lisp_to_value (env
, make_number (n
));
525 module_extract_float (emacs_env
*env
, emacs_value f
)
527 MODULE_FUNCTION_BEGIN (0);
528 Lisp_Object lisp
= value_to_lisp (f
);
529 CHECK_TYPE (FLOATP (lisp
), Qfloatp
, lisp
);
530 return XFLOAT_DATA (lisp
);
534 module_make_float (emacs_env
*env
, double d
)
536 MODULE_FUNCTION_BEGIN (module_nil
);
537 return lisp_to_value (env
, make_float (d
));
541 module_copy_string_contents (emacs_env
*env
, emacs_value value
, char *buffer
,
544 MODULE_FUNCTION_BEGIN (false);
545 Lisp_Object lisp_str
= value_to_lisp (value
);
546 CHECK_STRING (lisp_str
);
548 Lisp_Object lisp_str_utf8
= ENCODE_UTF_8 (lisp_str
);
549 ptrdiff_t raw_size
= SBYTES (lisp_str_utf8
);
550 ptrdiff_t required_buf_size
= raw_size
+ 1;
554 *length
= required_buf_size
;
558 if (*length
< required_buf_size
)
560 *length
= required_buf_size
;
561 xsignal0 (Qargs_out_of_range
);
564 *length
= required_buf_size
;
565 memcpy (buffer
, SDATA (lisp_str_utf8
), raw_size
+ 1);
571 module_make_string (emacs_env
*env
, const char *str
, ptrdiff_t length
)
573 MODULE_FUNCTION_BEGIN (module_nil
);
574 if (! (0 <= length
&& length
<= STRING_BYTES_BOUND
))
575 xsignal0 (Qoverflow_error
);
576 /* FIXME: AUTO_STRING_WITH_LEN requires STR to be null-terminated,
577 but we shouldn’t require that. */
578 AUTO_STRING_WITH_LEN (lstr
, str
, length
);
579 return lisp_to_value (env
,
580 code_convert_string_norecord (lstr
, Qutf_8
, false));
584 module_make_user_ptr (emacs_env
*env
, emacs_finalizer_function fin
, void *ptr
)
586 MODULE_FUNCTION_BEGIN (module_nil
);
587 return lisp_to_value (env
, make_user_ptr (fin
, ptr
));
591 module_get_user_ptr (emacs_env
*env
, emacs_value uptr
)
593 MODULE_FUNCTION_BEGIN (NULL
);
594 Lisp_Object lisp
= value_to_lisp (uptr
);
595 CHECK_USER_PTR (lisp
);
596 return XUSER_PTR (lisp
)->p
;
600 module_set_user_ptr (emacs_env
*env
, emacs_value uptr
, void *ptr
)
602 MODULE_FUNCTION_BEGIN ();
603 Lisp_Object lisp
= value_to_lisp (uptr
);
604 CHECK_USER_PTR (lisp
);
605 XUSER_PTR (lisp
)->p
= ptr
;
608 static emacs_finalizer_function
609 module_get_user_finalizer (emacs_env
*env
, emacs_value uptr
)
611 MODULE_FUNCTION_BEGIN (NULL
);
612 Lisp_Object lisp
= value_to_lisp (uptr
);
613 CHECK_USER_PTR (lisp
);
614 return XUSER_PTR (lisp
)->finalizer
;
618 module_set_user_finalizer (emacs_env
*env
, emacs_value uptr
,
619 emacs_finalizer_function fin
)
621 MODULE_FUNCTION_BEGIN ();
622 Lisp_Object lisp
= value_to_lisp (uptr
);
623 CHECK_USER_PTR (lisp
);
624 XUSER_PTR (lisp
)->finalizer
= fin
;
628 check_vec_index (Lisp_Object lvec
, ptrdiff_t i
)
631 if (! (0 <= i
&& i
< ASIZE (lvec
)))
632 args_out_of_range_3 (make_fixnum_or_float (i
),
633 make_number (0), make_number (ASIZE (lvec
) - 1));
637 module_vec_set (emacs_env
*env
, emacs_value vec
, ptrdiff_t i
, emacs_value val
)
639 MODULE_FUNCTION_BEGIN ();
640 Lisp_Object lvec
= value_to_lisp (vec
);
641 check_vec_index (lvec
, i
);
642 ASET (lvec
, i
, value_to_lisp (val
));
646 module_vec_get (emacs_env
*env
, emacs_value vec
, ptrdiff_t i
)
648 MODULE_FUNCTION_BEGIN (module_nil
);
649 Lisp_Object lvec
= value_to_lisp (vec
);
650 check_vec_index (lvec
, i
);
651 return lisp_to_value (env
, AREF (lvec
, i
));
655 module_vec_size (emacs_env
*env
, emacs_value vec
)
657 MODULE_FUNCTION_BEGIN (0);
658 Lisp_Object lvec
= value_to_lisp (vec
);
663 /* This function should return true if and only if maybe_quit would do
666 module_should_quit (emacs_env
*env
)
668 MODULE_FUNCTION_BEGIN_NO_CATCH (false);
669 return (! NILP (Vquit_flag
) && NILP (Vinhibit_quit
)) || pending_signals
;
676 module_signal_or_throw (struct emacs_env_private
*env
)
678 switch (env
->pending_non_local_exit
)
680 case emacs_funcall_exit_return
:
682 case emacs_funcall_exit_signal
:
683 xsignal (env
->non_local_exit_symbol
, env
->non_local_exit_data
);
684 case emacs_funcall_exit_throw
:
685 Fthrow (env
->non_local_exit_symbol
, env
->non_local_exit_data
);
691 DEFUN ("module-load", Fmodule_load
, Smodule_load
, 1, 1, 0,
692 doc
: /* Load module FILE. */)
695 dynlib_handle_ptr handle
;
696 emacs_init_function module_init
;
700 handle
= dynlib_open (SSDATA (file
));
702 xsignal2 (Qmodule_open_failed
, file
, build_string (dynlib_error ()));
704 gpl_sym
= dynlib_sym (handle
, "plugin_is_GPL_compatible");
706 xsignal1 (Qmodule_not_gpl_compatible
, file
);
708 module_init
= (emacs_init_function
) dynlib_func (handle
, "emacs_module_init");
710 xsignal1 (Qmissing_module_init_function
, file
);
712 struct emacs_runtime rt_pub
;
713 struct emacs_runtime_private rt_priv
;
715 struct emacs_env_private env_priv
;
716 rt_priv
.env
= initialize_environment (&env_pub
, &env_priv
);
718 /* If we should use module assertions, reallocate the runtime object
719 from the free store, but never free it. That way the addresses
720 for two different runtime objects are guaranteed to be distinct,
721 which we can use for checking the liveness of runtime
723 struct emacs_runtime
*rt
= module_assertions
? xmalloc (sizeof *rt
) : &rt_pub
;
724 rt
->size
= sizeof *rt
;
725 rt
->private_members
= &rt_priv
;
726 rt
->get_environment
= module_get_environment
;
728 Vmodule_runtimes
= Fcons (make_save_ptr (rt
), Vmodule_runtimes
);
729 ptrdiff_t count
= SPECPDL_INDEX ();
730 record_unwind_protect_ptr (finalize_runtime_unwind
, rt
);
732 int r
= module_init (rt
);
734 /* Process the quit flag first, so that quitting doesn't get
735 overridden by other non-local exits. */
740 if (FIXNUM_OVERFLOW_P (r
))
741 xsignal0 (Qoverflow_error
);
742 xsignal2 (Qmodule_init_failed
, file
, make_number (r
));
745 module_signal_or_throw (&env_priv
);
746 return unbind_to (count
, Qt
);
750 funcall_module (Lisp_Object function
, ptrdiff_t nargs
, Lisp_Object
*arglist
)
752 const struct Lisp_Module_Function
*func
= XMODULE_FUNCTION (function
);
753 eassume (0 <= func
->min_arity
);
754 if (! (func
->min_arity
<= nargs
755 && (func
->max_arity
< 0 || nargs
<= func
->max_arity
)))
756 xsignal2 (Qwrong_number_of_arguments
, function
, make_number (nargs
));
759 struct emacs_env_private priv
;
760 emacs_env
*env
= initialize_environment (&pub
, &priv
);
761 ptrdiff_t count
= SPECPDL_INDEX ();
762 record_unwind_protect_ptr (finalize_environment_unwind
, env
);
765 ATTRIBUTE_MAY_ALIAS emacs_value
*args
;
766 if (plain_values
&& ! module_assertions
)
767 /* FIXME: The cast below is incorrect because the argument array
768 is not declared as const, so module functions can modify it.
769 Either declare it as const, or remove this branch. */
770 args
= (emacs_value
*) arglist
;
773 args
= SAFE_ALLOCA (nargs
* sizeof *args
);
774 for (ptrdiff_t i
= 0; i
< nargs
; i
++)
775 args
[i
] = lisp_to_value (env
, arglist
[i
]);
778 emacs_value ret
= func
->subr (env
, nargs
, args
, func
->data
);
781 eassert (&priv
== env
->private_members
);
783 /* Process the quit flag first, so that quitting doesn't get
784 overridden by other non-local exits. */
787 module_signal_or_throw (&priv
);
788 return unbind_to (count
, value_to_lisp (ret
));
792 module_function_arity (const struct Lisp_Module_Function
*const function
)
794 ptrdiff_t minargs
= function
->min_arity
;
795 ptrdiff_t maxargs
= function
->max_arity
;
796 return Fcons (make_number (minargs
),
797 maxargs
== MANY
? Qmany
: make_number (maxargs
));
801 /* Helper functions. */
804 in_current_thread (void)
806 if (current_thread
== NULL
)
809 return pthread_equal (pthread_self (), current_thread
->thread_id
);
810 #elif defined WINDOWSNT
811 return GetCurrentThreadId () == current_thread
->thread_id
;
816 module_assert_thread (void)
818 if (!module_assertions
)
820 if (!in_current_thread ())
821 module_abort ("Module function called from outside "
822 "the current Lisp thread");
824 module_abort ("Module function called during garbage collection");
828 module_assert_runtime (struct emacs_runtime
*ert
)
830 if (! module_assertions
)
833 for (Lisp_Object tail
= Vmodule_runtimes
; CONSP (tail
); tail
= XCDR (tail
))
835 if (XSAVE_POINTER (XCAR (tail
), 0) == ert
)
839 module_abort ("Runtime pointer not found in list of %"pD
"d runtimes",
844 module_assert_env (emacs_env
*env
)
846 if (! module_assertions
)
849 for (Lisp_Object tail
= Vmodule_environments
; CONSP (tail
);
852 if (XSAVE_POINTER (XCAR (tail
), 0) == env
)
856 module_abort ("Environment pointer not found in list of %"pD
"d environments",
861 module_non_local_exit_signal_1 (emacs_env
*env
, Lisp_Object sym
,
864 struct emacs_env_private
*p
= env
->private_members
;
865 if (p
->pending_non_local_exit
== emacs_funcall_exit_return
)
867 p
->pending_non_local_exit
= emacs_funcall_exit_signal
;
868 p
->non_local_exit_symbol
= sym
;
869 p
->non_local_exit_data
= data
;
874 module_non_local_exit_throw_1 (emacs_env
*env
, Lisp_Object tag
,
877 struct emacs_env_private
*p
= env
->private_members
;
878 if (p
->pending_non_local_exit
== emacs_funcall_exit_return
)
880 p
->pending_non_local_exit
= emacs_funcall_exit_throw
;
881 p
->non_local_exit_symbol
= tag
;
882 p
->non_local_exit_data
= value
;
886 /* Signal an out-of-memory condition to the caller. */
888 module_out_of_memory (emacs_env
*env
)
890 /* TODO: Reimplement this so it works even if memory-signal-data has
892 module_non_local_exit_signal_1 (env
, XCAR (Vmemory_signal_data
),
893 XCDR (Vmemory_signal_data
));
897 /* Value conversion. */
899 /* We represent Lisp objects differently depending on whether the user
900 gave -module-assertions. If assertions are disabled, emacs_value
901 objects are Lisp_Objects cast to emacs_value. If assertions are
902 enabled, emacs_value objects are pointers to Lisp_Object objects
903 allocated from the free store; they are never freed, which ensures
904 that their addresses are unique and can be used for liveness
907 /* Unique Lisp_Object used to mark those emacs_values which are really
908 just containers holding a Lisp_Object that does not fit as an emacs_value,
909 either because it is an integer out of range, or is not properly aligned.
910 Used only if !plain_values. */
911 static Lisp_Object ltv_mark
;
913 /* Convert V to the corresponding internal object O, such that
914 V == lisp_to_value_bits (O). Never fails. */
916 value_to_lisp_bits (emacs_value v
)
918 intptr_t i
= (intptr_t) v
;
919 if (plain_values
|| USE_LSB_TAG
)
922 /* With wide EMACS_INT and when tag bits are the most significant,
923 reassembling integers differs from reassembling pointers in two
924 ways. First, save and restore the least-significant bits of the
925 integer, not the most-significant bits. Second, sign-extend the
926 integer when restoring, but zero-extend pointers because that
927 makes TAG_PTR faster. */
929 EMACS_UINT tag
= i
& (GCALIGNMENT
- 1);
930 EMACS_UINT untagged
= i
- tag
;
935 bool negative
= tag
& 1;
936 EMACS_UINT sign_extension
937 = negative
? VALMASK
& ~(INTPTR_MAX
>> INTTYPEBITS
): 0;
939 intptr_t all_but_sign
= u
>> GCTYPEBITS
;
940 untagged
= sign_extension
+ all_but_sign
;
945 return XIL ((tag
<< VALBITS
) + untagged
);
948 /* If V was computed from lisp_to_value (O), then return O.
949 Exits non-locally only if the stack overflows. */
951 value_to_lisp (emacs_value v
)
953 if (module_assertions
)
955 /* Check the liveness of the value by iterating over all live
958 ATTRIBUTE_MAY_ALIAS Lisp_Object
*optr
= vptr
;
959 ptrdiff_t num_environments
= 0;
960 ptrdiff_t num_values
= 0;
961 for (Lisp_Object environments
= Vmodule_environments
;
962 CONSP (environments
); environments
= XCDR (environments
))
964 emacs_env
*env
= XSAVE_POINTER (XCAR (environments
), 0);
965 for (Lisp_Object values
= env
->private_members
->values
;
966 CONSP (values
); values
= XCDR (values
))
968 Lisp_Object
*p
= XSAVE_POINTER (XCAR (values
), 0);
975 module_abort (("Emacs value not found in %"pD
"d values "
976 "of %"pD
"d environments"),
977 num_values
, num_environments
);
980 Lisp_Object o
= value_to_lisp_bits (v
);
981 if (! plain_values
&& CONSP (o
) && EQ (XCDR (o
), ltv_mark
))
986 /* Attempt to convert O to an emacs_value. Do not do any checking or
987 or allocate any storage; the caller should prevent or detect
988 any resulting bit pattern that is not a valid emacs_value. */
990 lisp_to_value_bits (Lisp_Object o
)
992 EMACS_UINT u
= XLI (o
);
994 /* Compress U into the space of a pointer, possibly losing information. */
995 uintptr_t p
= (plain_values
|| USE_LSB_TAG
997 : (INTEGERP (o
) ? u
<< VALBITS
: u
& VALMASK
) + XTYPE (o
));
998 return (emacs_value
) p
;
1001 #ifndef HAVE_STRUCT_ATTRIBUTE_ALIGNED
1002 enum { HAVE_STRUCT_ATTRIBUTE_ALIGNED
= 0 };
1005 /* Convert O to an emacs_value. Allocate storage if needed; this can
1006 signal if memory is exhausted. Must be an injective function. */
1008 lisp_to_value (emacs_env
*env
, Lisp_Object o
)
1010 if (module_assertions
)
1012 /* Add the new value to the list of values allocated from this
1013 environment. The value is actually a pointer to the
1014 Lisp_Object cast to emacs_value. We make a copy of the
1015 object on the free store to guarantee unique addresses. */
1016 ATTRIBUTE_MAY_ALIAS Lisp_Object
*optr
= xmalloc (sizeof o
);
1019 ATTRIBUTE_MAY_ALIAS emacs_value ret
= vptr
;
1020 struct emacs_env_private
*priv
= env
->private_members
;
1021 priv
->values
= Fcons (make_save_ptr (ret
), priv
->values
);
1025 emacs_value v
= lisp_to_value_bits (o
);
1027 if (! EQ (o
, value_to_lisp_bits (v
)))
1029 /* Package the incompressible object pointer inside a pair
1030 that is compressible. */
1031 Lisp_Object pair
= Fcons (o
, ltv_mark
);
1033 if (! HAVE_STRUCT_ATTRIBUTE_ALIGNED
)
1035 /* Keep calling Fcons until it returns a compressible pair.
1036 This shouldn't take long. */
1037 while ((intptr_t) XCONS (pair
) & (GCALIGNMENT
- 1))
1038 pair
= Fcons (o
, pair
);
1040 /* Plant the mark. The garbage collector will eventually
1041 reclaim any just-allocated incompressible pairs. */
1042 XSETCDR (pair
, ltv_mark
);
1045 v
= (emacs_value
) ((intptr_t) XCONS (pair
) + Lisp_Cons
);
1048 eassert (EQ (o
, value_to_lisp (v
)));
1053 /* Environment lifetime management. */
1055 /* Must be called before the environment can be used. Returns another
1056 pointer that callers should use instead of the ENV argument. If
1057 module assertions are disabled, the return value is ENV. If module
1058 assertions are enabled, the return value points to a heap-allocated
1059 object. That object is never freed to guarantee unique
1062 initialize_environment (emacs_env
*env
, struct emacs_env_private
*priv
)
1064 if (module_assertions
)
1065 env
= xmalloc (sizeof *env
);
1067 priv
->pending_non_local_exit
= emacs_funcall_exit_return
;
1068 priv
->values
= priv
->non_local_exit_symbol
= priv
->non_local_exit_data
= Qnil
;
1069 env
->size
= sizeof *env
;
1070 env
->private_members
= priv
;
1071 env
->make_global_ref
= module_make_global_ref
;
1072 env
->free_global_ref
= module_free_global_ref
;
1073 env
->non_local_exit_check
= module_non_local_exit_check
;
1074 env
->non_local_exit_clear
= module_non_local_exit_clear
;
1075 env
->non_local_exit_get
= module_non_local_exit_get
;
1076 env
->non_local_exit_signal
= module_non_local_exit_signal
;
1077 env
->non_local_exit_throw
= module_non_local_exit_throw
;
1078 env
->make_function
= module_make_function
;
1079 env
->funcall
= module_funcall
;
1080 env
->intern
= module_intern
;
1081 env
->type_of
= module_type_of
;
1082 env
->is_not_nil
= module_is_not_nil
;
1083 env
->eq
= module_eq
;
1084 env
->extract_integer
= module_extract_integer
;
1085 env
->make_integer
= module_make_integer
;
1086 env
->extract_float
= module_extract_float
;
1087 env
->make_float
= module_make_float
;
1088 env
->copy_string_contents
= module_copy_string_contents
;
1089 env
->make_string
= module_make_string
;
1090 env
->make_user_ptr
= module_make_user_ptr
;
1091 env
->get_user_ptr
= module_get_user_ptr
;
1092 env
->set_user_ptr
= module_set_user_ptr
;
1093 env
->get_user_finalizer
= module_get_user_finalizer
;
1094 env
->set_user_finalizer
= module_set_user_finalizer
;
1095 env
->vec_set
= module_vec_set
;
1096 env
->vec_get
= module_vec_get
;
1097 env
->vec_size
= module_vec_size
;
1098 env
->should_quit
= module_should_quit
;
1099 Vmodule_environments
= Fcons (make_save_ptr (env
), Vmodule_environments
);
1103 /* Must be called before the lifetime of the environment object
1106 finalize_environment (emacs_env
*env
)
1108 eassert (XSAVE_POINTER (XCAR (Vmodule_environments
), 0) == env
);
1109 Vmodule_environments
= XCDR (Vmodule_environments
);
1110 if (module_assertions
)
1111 /* There is always at least the global environment. */
1112 eassert (CONSP (Vmodule_environments
));
1116 finalize_environment_unwind (void *env
)
1118 finalize_environment (env
);
1122 finalize_runtime_unwind (void* raw_ert
)
1124 struct emacs_runtime
*ert
= raw_ert
;
1125 eassert (XSAVE_POINTER (XCAR (Vmodule_runtimes
), 0) == ert
);
1126 Vmodule_runtimes
= XCDR (Vmodule_runtimes
);
1127 finalize_environment (ert
->private_members
->env
);
1133 for (Lisp_Object tail
= Vmodule_environments
; CONSP (tail
);
1136 emacs_env
*env
= XSAVE_POINTER (XCAR (tail
), 0);
1137 struct emacs_env_private
*priv
= env
->private_members
;
1138 mark_object (priv
->non_local_exit_symbol
);
1139 mark_object (priv
->non_local_exit_data
);
1140 mark_object (priv
->values
);
1145 /* Non-local exit handling. */
1147 /* Must be called after setting up a handler immediately before
1148 returning from the function. See the comments in lisp.h and the
1149 code in eval.c for details. The macros below arrange for this
1150 function to be called automatically. PHANDLERLIST points to a word
1151 containing the handler list, for sanity checking. */
1153 module_reset_handlerlist (struct handler
**phandlerlist
)
1155 eassert (handlerlist
== *phandlerlist
);
1156 handlerlist
= handlerlist
->next
;
1159 /* Called on `signal'. ERR is a pair (SYMBOL . DATA), which gets
1160 stored in the environment. Set the pending non-local exit flag. */
1162 module_handle_signal (emacs_env
*env
, Lisp_Object err
)
1164 module_non_local_exit_signal_1 (env
, XCAR (err
), XCDR (err
));
1167 /* Called on `throw'. TAG_VAL is a pair (TAG . VALUE), which gets
1168 stored in the environment. Set the pending non-local exit flag. */
1170 module_handle_throw (emacs_env
*env
, Lisp_Object tag_val
)
1172 module_non_local_exit_throw_1 (env
, XCAR (tag_val
), XCDR (tag_val
));
1176 /* Support for assertions. */
1178 init_module_assertions (bool enable
)
1180 module_assertions
= enable
;
1183 /* We use a hidden environment for storing the globals. This
1184 environment is never freed. */
1186 global_env
= initialize_environment (&env
, &global_env_private
);
1187 eassert (global_env
!= &env
);
1191 static _Noreturn
void
1192 ATTRIBUTE_FORMAT_PRINTF(1, 2)
1193 module_abort (const char *format
, ...)
1195 fputs ("Emacs module assertion: ", stderr
);
1197 va_start (args
, format
);
1198 vfprintf (stderr
, format
, args
);
1200 putc ('\n', stderr
);
1206 /* Segment initializer. */
1209 syms_of_module (void)
1212 ltv_mark
= Fcons (Qnil
, Qnil
);
1213 eassert (NILP (value_to_lisp (module_nil
)));
1215 DEFSYM (Qmodule_refs_hash
, "module-refs-hash");
1216 DEFVAR_LISP ("module-refs-hash", Vmodule_refs_hash
,
1217 doc
: /* Module global reference table. */);
1220 = make_hash_table (hashtest_eq
, DEFAULT_HASH_SIZE
,
1221 DEFAULT_REHASH_SIZE
, DEFAULT_REHASH_THRESHOLD
,
1223 Funintern (Qmodule_refs_hash
, Qnil
);
1225 DEFSYM (Qmodule_runtimes
, "module-runtimes");
1226 DEFVAR_LISP ("module-runtimes", Vmodule_runtimes
,
1227 doc
: /* List of active module runtimes. */);
1228 Vmodule_runtimes
= Qnil
;
1229 /* Unintern `module-runtimes' because it is only used
1231 Funintern (Qmodule_runtimes
, Qnil
);
1233 DEFSYM (Qmodule_environments
, "module-environments");
1234 DEFVAR_LISP ("module-environments", Vmodule_environments
,
1235 doc
: /* List of active module environments. */);
1236 Vmodule_environments
= Qnil
;
1237 /* Unintern `module-environments' because it is only used
1239 Funintern (Qmodule_environments
, Qnil
);
1241 DEFSYM (Qmodule_load_failed
, "module-load-failed");
1242 Fput (Qmodule_load_failed
, Qerror_conditions
,
1243 listn (CONSTYPE_PURE
, 2, Qmodule_load_failed
, Qerror
));
1244 Fput (Qmodule_load_failed
, Qerror_message
,
1245 build_pure_c_string ("Module load failed"));
1247 DEFSYM (Qmodule_open_failed
, "module-open-failed");
1248 Fput (Qmodule_open_failed
, Qerror_conditions
,
1249 listn (CONSTYPE_PURE
, 3,
1250 Qmodule_open_failed
, Qmodule_load_failed
, Qerror
));
1251 Fput (Qmodule_open_failed
, Qerror_message
,
1252 build_pure_c_string ("Module could not be opened"));
1254 DEFSYM (Qmodule_not_gpl_compatible
, "module-not-gpl-compatible");
1255 Fput (Qmodule_not_gpl_compatible
, Qerror_conditions
,
1256 listn (CONSTYPE_PURE
, 3,
1257 Qmodule_not_gpl_compatible
, Qmodule_load_failed
, Qerror
));
1258 Fput (Qmodule_not_gpl_compatible
, Qerror_message
,
1259 build_pure_c_string ("Module is not GPL compatible"));
1261 DEFSYM (Qmissing_module_init_function
, "missing-module-init-function");
1262 Fput (Qmissing_module_init_function
, Qerror_conditions
,
1263 listn (CONSTYPE_PURE
, 3,
1264 Qmissing_module_init_function
, Qmodule_load_failed
, Qerror
));
1265 Fput (Qmissing_module_init_function
, Qerror_message
,
1266 build_pure_c_string ("Module does not export an "
1267 "initialization function"));
1269 DEFSYM (Qmodule_init_failed
, "module-init-failed");
1270 Fput (Qmodule_init_failed
, Qerror_conditions
,
1271 listn (CONSTYPE_PURE
, 3,
1272 Qmodule_init_failed
, Qmodule_load_failed
, Qerror
));
1273 Fput (Qmodule_init_failed
, Qerror_message
,
1274 build_pure_c_string ("Module initialization failed"));
1276 DEFSYM (Qinvalid_arity
, "invalid-arity");
1277 Fput (Qinvalid_arity
, Qerror_conditions
,
1278 listn (CONSTYPE_PURE
, 2, Qinvalid_arity
, Qerror
));
1279 Fput (Qinvalid_arity
, Qerror_message
,
1280 build_pure_c_string ("Invalid function arity"));
1282 /* Unintern `module-refs-hash' because it is internal-only and Lisp
1283 code or modules should not access it. */
1284 Funintern (Qmodule_refs_hash
, Qnil
);
1286 DEFSYM (Qmodule_function_p
, "module-function-p");
1288 defsubr (&Smodule_load
);