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