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