emacs-diffs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Emacs-diffs] master cf97132: Implement module assertions for users


From: Philipp Stephani
Subject: [Emacs-diffs] master cf97132: Implement module assertions for users
Date: Mon, 12 Jun 2017 09:27:03 -0400 (EDT)

branch: master
commit cf97132764572928adc77fd555d04a9f41cd3cfc
Author: Philipp Stephani <address@hidden>
Commit: Philipp Stephani <address@hidden>

    Implement module assertions for users
    
    Add a new command-line option '-module-assertions' that users can
    enable developing or debugging a module.  If this option is present,
    Emacs performs additional checks to verify that modules fulfill their
    requirements.  These checks are expensive and crash Emacs if modules
    are invalid, so disable them by default.
    
    This is a command-line option instead of an ordinary variable because
    changing it while Emacs is running would cause data structure
    imbalances.
    
    * src/emacs.c (main): New command line option '-module-assertions'.
    
    * src/emacs-module.c (module_assert_main_thread)
    (module_assert_runtime, module_assert_env, module_assert_value):
    New functions to assert module requirements.
    (syms_of_module): New uninterned variable 'module-runtimes'.
    (init_module_assertions, in_main_thread, module_abort): New helper
    functions.
    (initialize_environment): Initialize value list.  If assertions are
    enabled, use a heap-allocated environment object.
    (finalize_environment): Add assertion that environment list is never
    empty.
    (finalize_runtime_unwind): Pop module runtime object stack.
    (value_to_lisp): Assert that the value is valid.
    (lisp_to_value): Record new value if assertions are enabled.
    (mark_modules): Mark allocated object list.
    (MODULE_FUNCTION_BEGIN_NO_CATCH)
    (module_non_local_exit_check, module_non_local_exit_clear)
    (module_non_local_exit_get, module_non_local_exit_signal)
    (module_non_local_exit_throw): Assert thread and environment.
    (module_get_environment): Assert thread and runtime.
    (module_make_function, module_funcall, module_intern)
    (module_funcall, module_make_integer, module_make_float)
    (module_make_string, module_make_user_ptr, module_vec_get)
    (funcall_module, Fmodule_load): Adapt callers.
    (module_make_global_ref): If assertions are enabled, use the global
    environment to store global values.
    (module_free_global_ref): Remove value from global value list.
    
    * test/Makefile.in (EMACSOPT): Enable module assertions when testing
    modules.
    
    * test/data/emacs-module/mod-test.c (Fmod_test_invalid_store)
    (Fmod_test_invalid_load): New functions to test module assertions.
    (emacs_module_init): Bind the new functions.
    
    * test/src/emacs-module-tests.el (mod-test-emacs): New constant for
    the Emacs binary file.
    (mod-test-file): New constant for the test module file name.
    (module--test-assertions): New unit test.
---
 etc/NEWS                          |   6 +
 src/emacs-module.c                | 331 ++++++++++++++++++++++++++++++--------
 src/emacs.c                       |  14 ++
 src/lisp.h                        |   1 +
 test/Makefile.in                  |   2 +-
 test/data/emacs-module/mod-test.c |  24 +++
 test/src/emacs-module-tests.el    |  40 ++++-
 7 files changed, 351 insertions(+), 67 deletions(-)

diff --git a/etc/NEWS b/etc/NEWS
index 7972511..feed62c 100644
--- a/etc/NEWS
+++ b/etc/NEWS
@@ -85,6 +85,12 @@ modern init systems such as systemd, which manage many of 
the traditional
 aspects of daemon behavior themselves.  '--bg-daemon' is now an alias
 for '--daemon'.
 
+** New option '--module-assertions'.  If the user supplies this
+option, Emacs will perform expensive correctness checks when dealing
+with dynamic modules.  This is intended for module authors that wish
+to verify that their module conforms to the module requirements.  The
+option makes Emacs abort if a module-related assertion triggers.
+
 +++
 ** Emacs now supports 24-bit colors on capable text terminals
 Terminal is automatically initialized to use 24-bit colors if the
diff --git a/src/emacs-module.c b/src/emacs-module.c
index adb09c0..2602398 100644
--- a/src/emacs-module.c
+++ b/src/emacs-module.c
@@ -21,9 +21,11 @@ along with GNU Emacs.  If not, see 
<http://www.gnu.org/licenses/>.  */
 
 #include "emacs-module.h"
 
+#include <stdarg.h>
 #include <stddef.h>
 #include <stdint.h>
 #include <stdio.h>
+#include <stdnoreturn.h>
 
 #include "lisp.h"
 #include "dynlib.h"
@@ -35,6 +37,17 @@ along with GNU Emacs.  If not, see 
<http://www.gnu.org/licenses/>.  */
 #include <intprops.h>
 #include <verify.h>
 
+/* We use different strategies for allocating the user-visible objects
+   (struct emacs_runtime, emacs_env, emacs_value), depending on
+   whether the user supplied the -module-assertions flag.  If
+   assertions are disabled, all objects are allocated from the stack.
+   If assertions are enabled, all objects are allocated from the free
+   store, and objects are never freed; this guarantees that they all
+   have different addresses.  We use that for checking which objects
+   are live.  Without unique addresses, we might consider some dead
+   objects live because their addresses would have been reused in the
+   meantime.  */
+
 
 /* Feature tests.  */
 
@@ -78,25 +91,31 @@ struct emacs_env_private
      storage is always available for them, even in an out-of-memory
      situation.  */
   Lisp_Object non_local_exit_symbol, non_local_exit_data;
+
+  /* List of values allocated from this environment.  The code uses
+     this only if the user gave the -module-assertions command-line
+     option.  */
+  Lisp_Object values;
 };
 
 /* The private parts of an `emacs_runtime' object contain the initial
    environment.  */
 struct emacs_runtime_private
 {
-  emacs_env pub;
+  emacs_env *env;
 };
 
 
 /* Forward declarations.  */
 
-struct module_fun_env;
-
 static Lisp_Object value_to_lisp (emacs_value);
-static emacs_value lisp_to_value (Lisp_Object);
+static emacs_value lisp_to_value (emacs_env *, Lisp_Object);
 static enum emacs_funcall_exit module_non_local_exit_check (emacs_env *);
-static void check_thread (void);
-static void initialize_environment (emacs_env *, struct emacs_env_private *);
+static void module_assert_thread (void);
+static void module_assert_runtime (struct emacs_runtime *);
+static void module_assert_env (emacs_env *);
+static noreturn void module_abort (const char *format, ...) 
ATTRIBUTE_FORMAT_PRINTF(1, 2);
+static emacs_env *initialize_environment (emacs_env *, struct 
emacs_env_private *);
 static void finalize_environment (emacs_env *);
 static void finalize_environment_unwind (void *);
 static void finalize_runtime_unwind (void *);
@@ -113,6 +132,10 @@ static void module_reset_handlerlist (struct handler 
*const *);
    code should not assume this.  */
 verify (NIL_IS_ZERO);
 static emacs_value const module_nil = 0;
+
+static bool module_assertions = false;
+static emacs_env *global_env;
+static struct emacs_env_private global_env_private;
 
 /* Convenience macros for non-local exit handling.  */
 
@@ -216,7 +239,8 @@ static emacs_value const module_nil = 0;
 
 #define MODULE_FUNCTION_BEGIN_NO_CATCH(error_retval)                    \
   do {                                                                  \
-    check_thread ();                                                    \
+    module_assert_thread ();                                            \
+    module_assert_env (env);                                            \
     if (module_non_local_exit_check (env) != emacs_funcall_exit_return) \
       return error_retval;                                              \
   } while (false)
@@ -242,9 +266,9 @@ CHECK_USER_PTR (Lisp_Object obj)
 static emacs_env *
 module_get_environment (struct emacs_runtime *ert)
 {
-  emacs_env *env = &ert->private_members->pub;
-  check_thread ();
-  return env;
+  module_assert_thread ();
+  module_assert_runtime (ert);
+  return ert->private_members->env;
 }
 
 /* To make global refs (GC-protected global values) keep a hash that
@@ -273,7 +297,7 @@ module_make_global_ref (emacs_env *env, emacs_value ref)
       hash_put (h, new_obj, make_natnum (1), hashcode);
     }
 
-  return lisp_to_value (new_obj);
+  return lisp_to_value (module_assertions ? global_env : env, new_obj);
 }
 
 static void
@@ -300,32 +324,59 @@ module_free_global_ref (emacs_env *env, emacs_value ref)
       else
        hash_remove_from_table (h, value);
     }
+
+  if (module_assertions)
+    {
+      Lisp_Object globals = global_env_private.values;
+      Lisp_Object prev = Qnil;
+      ptrdiff_t count = 0;
+      for (Lisp_Object tail = global_env_private.values; CONSP (tail);
+           tail = XCDR (tail))
+        {
+          emacs_value global = XSAVE_POINTER (XCAR (globals), 0);
+          if (global == ref)
+            {
+              if (NILP (prev))
+                global_env_private.values = XCDR (globals);
+              else
+                XSETCDR (prev, XCDR (globals));
+              return;
+            }
+          ++count;
+          prev = globals;
+        }
+      module_abort ("Global value was not found in list of %td globals",
+                    count);
+    }
 }
 
 static enum emacs_funcall_exit
 module_non_local_exit_check (emacs_env *env)
 {
-  check_thread ();
+  module_assert_thread ();
+  module_assert_env (env);
   return env->private_members->pending_non_local_exit;
 }
 
 static void
 module_non_local_exit_clear (emacs_env *env)
 {
-  check_thread ();
+  module_assert_thread ();
+  module_assert_env (env);
   env->private_members->pending_non_local_exit = emacs_funcall_exit_return;
 }
 
 static enum emacs_funcall_exit
 module_non_local_exit_get (emacs_env *env, emacs_value *sym, emacs_value *data)
 {
-  check_thread ();
+  module_assert_thread ();
+  module_assert_env (env);
   struct emacs_env_private *p = env->private_members;
   if (p->pending_non_local_exit != emacs_funcall_exit_return)
     {
       /* FIXME: lisp_to_value can exit non-locally.  */
-      *sym = lisp_to_value (p->non_local_exit_symbol);
-      *data = lisp_to_value (p->non_local_exit_data);
+      *sym = lisp_to_value (env, p->non_local_exit_symbol);
+      *data = lisp_to_value (env, p->non_local_exit_data);
     }
   return p->pending_non_local_exit;
 }
@@ -334,7 +385,8 @@ module_non_local_exit_get (emacs_env *env, emacs_value 
*sym, emacs_value *data)
 static void
 module_non_local_exit_signal (emacs_env *env, emacs_value sym, emacs_value 
data)
 {
-  check_thread ();
+  module_assert_thread ();
+  module_assert_env (env);
   if (module_non_local_exit_check (env) == emacs_funcall_exit_return)
     module_non_local_exit_signal_1 (env, value_to_lisp (sym),
                                    value_to_lisp (data));
@@ -343,7 +395,8 @@ module_non_local_exit_signal (emacs_env *env, emacs_value 
sym, emacs_value data)
 static void
 module_non_local_exit_throw (emacs_env *env, emacs_value tag, emacs_value 
value)
 {
-  check_thread ();
+  module_assert_thread ();
+  module_assert_env (env);
   if (module_non_local_exit_check (env) == emacs_funcall_exit_return)
     module_non_local_exit_throw_1 (env, value_to_lisp (tag),
                                   value_to_lisp (value));
@@ -393,7 +446,7 @@ module_make_function (emacs_env *env, ptrdiff_t min_arity, 
ptrdiff_t max_arity,
   XSET_MODULE_FUNCTION (result, function);
   eassert (MODULE_FUNCTIONP (result));
 
-  return lisp_to_value (result);
+  return lisp_to_value (env, result);
 }
 
 static emacs_value
@@ -413,7 +466,7 @@ module_funcall (emacs_env *env, emacs_value fun, ptrdiff_t 
nargs,
   newargs[0] = value_to_lisp (fun);
   for (ptrdiff_t i = 0; i < nargs; i++)
     newargs[1 + i] = value_to_lisp (args[i]);
-  emacs_value result = lisp_to_value (Ffuncall (nargs1, newargs));
+  emacs_value result = lisp_to_value (env, Ffuncall (nargs1, newargs));
   SAFE_FREE ();
   return result;
 }
@@ -422,14 +475,14 @@ static emacs_value
 module_intern (emacs_env *env, const char *name)
 {
   MODULE_FUNCTION_BEGIN (module_nil);
-  return lisp_to_value (intern (name));
+  return lisp_to_value (env, intern (name));
 }
 
 static emacs_value
 module_type_of (emacs_env *env, emacs_value value)
 {
   MODULE_FUNCTION_BEGIN (module_nil);
-  return lisp_to_value (Ftype_of (value_to_lisp (value)));
+  return lisp_to_value (env, Ftype_of (value_to_lisp (value)));
 }
 
 static bool
@@ -461,7 +514,7 @@ module_make_integer (emacs_env *env, intmax_t n)
   MODULE_FUNCTION_BEGIN (module_nil);
   if (FIXNUM_OVERFLOW_P (n))
     xsignal0 (Qoverflow_error);
-  return lisp_to_value (make_number (n));
+  return lisp_to_value (env, make_number (n));
 }
 
 static double
@@ -477,7 +530,7 @@ static emacs_value
 module_make_float (emacs_env *env, double d)
 {
   MODULE_FUNCTION_BEGIN (module_nil);
-  return lisp_to_value (make_float (d));
+  return lisp_to_value (env, make_float (d));
 }
 
 static bool
@@ -519,14 +572,15 @@ module_make_string (emacs_env *env, const char *str, 
ptrdiff_t length)
   if (! (0 <= length && length <= STRING_BYTES_BOUND))
     xsignal0 (Qoverflow_error);
   AUTO_STRING_WITH_LEN (lstr, str, length);
-  return lisp_to_value (code_convert_string_norecord (lstr, Qutf_8, false));
+  return lisp_to_value (env,
+                        code_convert_string_norecord (lstr, Qutf_8, false));
 }
 
 static emacs_value
 module_make_user_ptr (emacs_env *env, emacs_finalizer_function fin, void *ptr)
 {
   MODULE_FUNCTION_BEGIN (module_nil);
-  return lisp_to_value (make_user_ptr (fin, ptr));
+  return lisp_to_value (env, make_user_ptr (fin, ptr));
 }
 
 static void *
@@ -593,7 +647,7 @@ module_vec_get (emacs_env *env, emacs_value vec, ptrdiff_t 
i)
   MODULE_FUNCTION_BEGIN (module_nil);
   Lisp_Object lvec = value_to_lisp (vec);
   check_vec_index (lvec, i);
-  return lisp_to_value (AREF (lvec, i));
+  return lisp_to_value (env, AREF (lvec, i));
 }
 
 static ptrdiff_t
@@ -655,19 +709,27 @@ DEFUN ("module-load", Fmodule_load, Smodule_load, 1, 1, 0,
   if (!module_init)
     xsignal1 (Qmissing_module_init_function, file);
 
-  struct emacs_runtime_private rt; /* Includes the public emacs_env.  */
-  struct emacs_env_private priv;
-  initialize_environment (&rt.pub, &priv);
-  struct emacs_runtime pub =
-    {
-      .size = sizeof pub,
-      .private_members = &rt,
-      .get_environment = module_get_environment
-    };
+  struct emacs_runtime rt_pub;
+  struct emacs_runtime_private rt_priv;
+  emacs_env env_pub;
+  struct emacs_env_private env_priv;
+  rt_priv.env = initialize_environment (&env_pub, &env_priv);
+
+  /* If we should use module assertions, reallocate the runtime object
+     from the free store, but never free it.  That way the addresses
+     for two different runtime objects are guaranteed to be distinct,
+     which we can use for checking the liveness of runtime
+     pointers.  */
+  struct emacs_runtime *rt = module_assertions ? xmalloc (sizeof *rt) : 
&rt_pub;
+  rt->size = sizeof *rt;
+  rt->private_members = &rt_priv;
+  rt->get_environment = module_get_environment;
+
+  Vmodule_runtimes = Fcons (make_save_ptr (rt), Vmodule_runtimes);
   ptrdiff_t count = SPECPDL_INDEX ();
-  record_unwind_protect_ptr (finalize_runtime_unwind, &pub);
+  record_unwind_protect_ptr (finalize_runtime_unwind, rt);
 
-  int r = module_init (&pub);
+  int r = module_init (rt);
 
   /* Process the quit flag first, so that quitting doesn't get
      overridden by other non-local exits.  */
@@ -680,7 +742,7 @@ DEFUN ("module-load", Fmodule_load, Smodule_load, 1, 1, 0,
       xsignal2 (Qmodule_init_failed, file, make_number (r));
     }
 
-  module_signal_or_throw (&priv);
+  module_signal_or_throw (&env_priv);
   return unbind_to (count, Qt);
 }
 
@@ -695,25 +757,25 @@ funcall_module (Lisp_Object function, ptrdiff_t nargs, 
Lisp_Object *arglist)
 
   emacs_env pub;
   struct emacs_env_private priv;
-  initialize_environment (&pub, &priv);
+  emacs_env *env = initialize_environment (&pub, &priv);
   ptrdiff_t count = SPECPDL_INDEX ();
-  record_unwind_protect_ptr (finalize_environment_unwind, &pub);
+  record_unwind_protect_ptr (finalize_environment_unwind, env);
 
   USE_SAFE_ALLOCA;
   ATTRIBUTE_MAY_ALIAS emacs_value *args;
-  if (plain_values)
+  if (plain_values && ! module_assertions)
     args = (emacs_value *) arglist;
   else
     {
       args = SAFE_ALLOCA (nargs * sizeof *args);
       for (ptrdiff_t i = 0; i < nargs; i++)
-       args[i] = lisp_to_value (arglist[i]);
+       args[i] = lisp_to_value (env, arglist[i]);
     }
 
-  emacs_value ret = func->subr (&pub, nargs, args, func->data);
+  emacs_value ret = func->subr (env, nargs, args, func->data);
   SAFE_FREE ();
 
-  eassert (&priv == pub.private_members);
+  eassert (&priv == env->private_members);
 
   /* Process the quit flag first, so that quitting doesn't get
      overridden by other non-local exits.  */
@@ -735,18 +797,59 @@ module_function_arity (const struct Lisp_Module_Function 
*const function)
 
 /* Helper functions.  */
 
-static void
-check_thread (void)
+static bool
+in_current_thread (void)
 {
-  eassert (current_thread != NULL);
+  if (current_thread == NULL)
+    return false;
 #ifdef HAVE_PTHREAD
-  eassert (pthread_equal (pthread_self (), current_thread->thread_id));
+  return pthread_equal (pthread_self (), current_thread->thread_id);
 #elif defined WINDOWSNT
-  eassert (GetCurrentThreadId () == current_thread->thread_id);
+  return GetCurrentThreadId () == current_thread->thread_id;
 #endif
 }
 
 static void
+module_assert_thread (void)
+{
+  if (! module_assertions || in_current_thread ())
+    return;
+  module_abort ("Module function called from outside the current Lisp thread");
+}
+
+static void
+module_assert_runtime (struct emacs_runtime *ert)
+{
+  if (! module_assertions)
+    return;
+  ptrdiff_t count = 0;
+  for (Lisp_Object tail = Vmodule_runtimes; CONSP (tail); tail = XCDR (tail))
+    {
+      if (XSAVE_POINTER (XCAR (tail), 0) == ert)
+        return;
+      ++count;
+    }
+  module_abort ("Runtime pointer not found in list of %td runtimes", count);
+}
+
+static void
+module_assert_env (emacs_env *env)
+{
+  if (! module_assertions)
+    return;
+  ptrdiff_t count = 0;
+  for (Lisp_Object tail = Vmodule_environments; CONSP (tail);
+       tail = XCDR (tail))
+    {
+      if (XSAVE_POINTER (XCAR (tail), 0) == env)
+        return;
+      ++count;
+    }
+  module_abort ("Environment pointer not found in list of %td environments",
+                count);
+}
+
+static void
 module_non_local_exit_signal_1 (emacs_env *env, Lisp_Object sym,
                                Lisp_Object data)
 {
@@ -785,6 +888,14 @@ module_out_of_memory (emacs_env *env)
 
 /* Value conversion.  */
 
+/* We represent Lisp objects differently depending on whether the user
+   gave -module-assertions.  If assertions are disabled, emacs_value
+   objects are Lisp_Objects cast to emacs_value.  If assertions are
+   enabled, emacs_value objects are pointers to Lisp_Object objects
+   allocated from the free store; they are never freed, which ensures
+   that their addresses are unique and can be used for liveness
+   checking.  */
+
 /* Unique Lisp_Object used to mark those emacs_values which are really
    just containers holding a Lisp_Object that does not fit as an emacs_value,
    either because it is an integer out of range, or is not properly aligned.
@@ -831,6 +942,32 @@ value_to_lisp_bits (emacs_value v)
 static Lisp_Object
 value_to_lisp (emacs_value v)
 {
+  if (module_assertions)
+    {
+      /* Check the liveness of the value by iterating over all live
+         environments.  */
+      void *vptr = v;
+      ATTRIBUTE_MAY_ALIAS Lisp_Object *optr = vptr;
+      ptrdiff_t num_environments = 0;
+      ptrdiff_t num_values = 0;
+      for (Lisp_Object environments = Vmodule_environments;
+           CONSP (environments); environments = XCDR (environments))
+        {
+          emacs_env *env = XSAVE_POINTER (XCAR (environments), 0);
+          for (Lisp_Object values = env->private_members->values;
+               CONSP (values); values = XCDR (values))
+            {
+              Lisp_Object *p = XSAVE_POINTER (XCAR (values), 0);
+              if (p == optr)
+                return *p;
+              ++num_values;
+            }
+          ++num_environments;
+        }
+      module_abort ("Emacs value not found in %td values of %td environments",
+                    num_values, num_environments);
+    }
+
   Lisp_Object o = value_to_lisp_bits (v);
   if (! plain_values && CONSP (o) && EQ (XCDR (o), ltv_mark))
     o = XCAR (o);
@@ -859,8 +996,23 @@ enum { HAVE_STRUCT_ATTRIBUTE_ALIGNED = 0 };
 /* Convert O to an emacs_value.  Allocate storage if needed; this can
    signal if memory is exhausted.  Must be an injective function.  */
 static emacs_value
-lisp_to_value (Lisp_Object o)
+lisp_to_value (emacs_env *env, Lisp_Object o)
 {
+  if (module_assertions)
+    {
+      /* Add the new value to the list of values allocated from this
+         environment.  The value is actually a pointer to the
+         Lisp_Object cast to emacs_value.  We make a copy of the
+         object on the free store to guarantee unique addresses.  */
+      ATTRIBUTE_MAY_ALIAS Lisp_Object *optr = xmalloc (sizeof o);
+      *optr = o;
+      void *vptr = optr;
+      ATTRIBUTE_MAY_ALIAS emacs_value ret = vptr;
+      struct emacs_env_private *priv = env->private_members;
+      priv->values = Fcons (make_save_ptr (ret), priv->values);
+      return ret;
+    }
+
   emacs_value v = lisp_to_value_bits (o);
 
   if (! EQ (o, value_to_lisp_bits (v)))
@@ -891,12 +1043,20 @@ lisp_to_value (Lisp_Object o)
 
 /* Environment lifetime management.  */
 
-/* Must be called before the environment can be used.  */
-static void
+/* Must be called before the environment can be used.  Returns another
+   pointer that callers should use instead of the ENV argument.  If
+   module assertions are disabled, the return value is ENV.  If module
+   assertions are enabled, the return value points to a heap-allocated
+   object.  That object is never freed to guarantee unique
+   addresses.  */
+static emacs_env *
 initialize_environment (emacs_env *env, struct emacs_env_private *priv)
 {
+  if (module_assertions)
+      env = xmalloc (sizeof *env);
+
   priv->pending_non_local_exit = emacs_funcall_exit_return;
-  priv->non_local_exit_symbol = priv->non_local_exit_data = Qnil;
+  priv->values = priv->non_local_exit_symbol = priv->non_local_exit_data = 
Qnil;
   env->size = sizeof *env;
   env->private_members = priv;
   env->make_global_ref = module_make_global_ref;
@@ -928,6 +1088,7 @@ initialize_environment (emacs_env *env, struct 
emacs_env_private *priv)
   env->vec_size = module_vec_size;
   env->should_quit = module_should_quit;
   Vmodule_environments = Fcons (make_save_ptr (env), Vmodule_environments);
+  return env;
 }
 
 /* Must be called before the lifetime of the environment object
@@ -937,6 +1098,9 @@ finalize_environment (emacs_env *env)
 {
   eassert (XSAVE_POINTER (XCAR (Vmodule_environments), 0) == env);
   Vmodule_environments = XCDR (Vmodule_environments);
+  if (module_assertions)
+    /* There is always at least the global environment.  */
+    eassert (CONSP (Vmodule_environments));
 }
 
 static void
@@ -949,20 +1113,23 @@ static void
 finalize_runtime_unwind (void* raw_ert)
 {
   struct emacs_runtime *ert = raw_ert;
-  finalize_environment (&ert->private_members->pub);
+  eassert (XSAVE_POINTER (XCAR (Vmodule_runtimes), 0) == ert);
+  Vmodule_runtimes = XCDR (Vmodule_runtimes);
+  finalize_environment (ert->private_members->env);
 }
 
 void
 mark_modules (void)
 {
-  Lisp_Object tail = Vmodule_environments;
-  FOR_EACH_TAIL_SAFE (tail)
-  {
-    emacs_env *env = XSAVE_POINTER (XCAR (tail), 0);
-    struct emacs_env_private *priv = env->private_members;
-    mark_object (priv->non_local_exit_symbol);
-    mark_object (priv->non_local_exit_data);
-  }
+  for (Lisp_Object tail = Vmodule_environments; CONSP (tail);
+       tail = XCDR (tail))
+    {
+      emacs_env *env = XSAVE_POINTER (XCAR (tail), 0);
+      struct emacs_env_private *priv = env->private_members;
+      mark_object (priv->non_local_exit_symbol);
+      mark_object (priv->non_local_exit_data);
+      mark_object (priv->values);
+    }
 }
 
 
@@ -997,6 +1164,36 @@ module_handle_throw (emacs_env *env, Lisp_Object tag_val)
 }
 
 
+/* Support for assertions.  */
+void
+init_module_assertions (bool enable)
+{
+  module_assertions = enable;
+  if (enable)
+    {
+      /* We use a hidden environment for storing the globals.  This
+         environment is never freed.  */
+      emacs_env env;
+      global_env = initialize_environment (&env, &global_env_private);
+      eassert (global_env != &env);
+    }
+}
+
+static noreturn void
+ATTRIBUTE_FORMAT_PRINTF(1, 2)
+module_abort (const char *format, ...)
+{
+  fputs ("Emacs module assertion: ", stderr);
+  va_list args;
+  va_start (args, format);
+  vfprintf (stderr, format, args);
+  va_end (args);
+  putc ('\n', stderr);
+  fflush (stderr);
+  emacs_abort ();
+}
+
+
 /* Segment initializer.  */
 
 void
@@ -1016,6 +1213,14 @@ syms_of_module (void)
                       Qnil, false);
   Funintern (Qmodule_refs_hash, Qnil);
 
+  DEFSYM (Qmodule_runtimes, "module-runtimes");
+  DEFVAR_LISP ("module-runtimes", Vmodule_runtimes,
+               doc: /* List of active module runtimes.  */);
+  Vmodule_runtimes = Qnil;
+  /* Unintern `module-runtimes' because it is only used
+     internally.  */
+  Funintern (Qmodule_runtimes, Qnil);
+
   DEFSYM (Qmodule_environments, "module-environments");
   DEFVAR_LISP ("module-environments", Vmodule_environments,
                doc: /* List of active module environments.  */);
diff --git a/src/emacs.c b/src/emacs.c
index 49ebb81..b0892c7 100644
--- a/src/emacs.c
+++ b/src/emacs.c
@@ -223,6 +223,7 @@ Initialization options:\n\
 --fg-daemon[=NAME]          start a (named) server in the foreground\n\
 --debug-init                enable Emacs Lisp debugger for init file\n\
 --display, -d DISPLAY       use X server DISPLAY\n\
+--module-assertions         assert behavior of dynamic modules\n\
 ",
     "\
 --no-build-details          do not add build details such as time stamps\n\
@@ -1263,6 +1264,18 @@ Using an Emacs configured with --with-x-toolkit=lucid 
does not have this problem
   build_details = ! argmatch (argv, argc, "-no-build-details",
                              "--no-build-details", 7, NULL, &skip_args);
 
+#ifdef HAVE_MODULES
+  bool module_assertions
+    = argmatch (argv, argc, "-module-assertions", "--module-assertions", 15,
+                NULL, &skip_args);
+  if (dumping && module_assertions)
+    {
+      fputs ("Module assertions are not supported during dumping\n", stderr);
+      exit (1);
+    }
+  init_module_assertions (module_assertions);
+#endif
+
 #ifdef HAVE_NS
   ns_pool = ns_alloc_autorelease_pool ();
 #ifdef NS_IMPL_GNUSTEP
@@ -1720,6 +1733,7 @@ static const struct standard_args standard_args[] =
   { "-nl", "--no-loadup", 70, 0 },
   { "-nsl", "--no-site-lisp", 65, 0 },
   { "-no-build-details", "--no-build-details", 63, 0 },
+  { "-module-assertions", "--module-assertions", 62, 0 },
   /* -d must come last before the options handled in startup.el.  */
   { "-d", "--display", 60, 1 },
   { "-display", 0, 60, 1 },
diff --git a/src/lisp.h b/src/lisp.h
index ade188f..ff8dde2 100644
--- a/src/lisp.h
+++ b/src/lisp.h
@@ -3943,6 +3943,7 @@ extern Lisp_Object make_user_ptr (void (*finalizer) (void 
*), void *p);
 extern Lisp_Object funcall_module (Lisp_Object, ptrdiff_t, Lisp_Object *);
 extern Lisp_Object module_function_arity (const struct Lisp_Module_Function *);
 extern void mark_modules (void);
+extern void init_module_assertions (bool);
 extern void syms_of_module (void);
 #endif
 
diff --git a/test/Makefile.in b/test/Makefile.in
index 7b8c967..0c24c48 100644
--- a/test/Makefile.in
+++ b/test/Makefile.in
@@ -68,7 +68,7 @@ EMACS_EXTRAOPT=
 # Command line flags for Emacs.
 # Apparently MSYS bash would convert "-L :" to "-L ;" anyway,
 # but we might as well be explicit.
-EMACSOPT = -batch --no-site-file --no-site-lisp -L "$(SEPCHAR)$(srcdir)" 
$(EMACS_EXTRAOPT)
+EMACSOPT = -batch --no-site-file --no-site-lisp -module-assertions -L 
"$(SEPCHAR)$(srcdir)" $(EMACS_EXTRAOPT)
 
 # Prevent any settings in the user environment causing problems.
 unexport EMACSDATA EMACSDOC EMACSPATH GREP_OPTIONS
diff --git a/test/data/emacs-module/mod-test.c 
b/test/data/emacs-module/mod-test.c
index 309179d..fc29a0d 100644
--- a/test/data/emacs-module/mod-test.c
+++ b/test/data/emacs-module/mod-test.c
@@ -213,6 +213,28 @@ Fmod_test_vector_eq (emacs_env *env, ptrdiff_t nargs, 
emacs_value args[],
   return env->intern (env, "t");
 }
 
+static emacs_value invalid_stored_value;
+
+/* The next two functions perform a possibly-invalid operation: they
+   store a value in a static variable and load it.  This causes
+   undefined behavior if the environment that the value was created
+   from is no longer live.  The module assertions check for this
+   error.  */
+
+static emacs_value
+Fmod_test_invalid_store (emacs_env *env, ptrdiff_t nargs, emacs_value *args,
+                         void *data)
+{
+  return invalid_stored_value = env->make_integer (env, 123);
+}
+
+static emacs_value
+Fmod_test_invalid_load (emacs_env *env, ptrdiff_t nargs, emacs_value *args,
+                        void *data)
+{
+  return invalid_stored_value;
+}
+
 
 /* Lisp utilities for easier readability (simple wrappers).  */
 
@@ -260,6 +282,8 @@ emacs_module_init (struct emacs_runtime *ert)
   DEFUN ("mod-test-userptr-get", Fmod_test_userptr_get, 1, 1, NULL, NULL);
   DEFUN ("mod-test-vector-fill", Fmod_test_vector_fill, 2, 2, NULL, NULL);
   DEFUN ("mod-test-vector-eq", Fmod_test_vector_eq, 2, 2, NULL, NULL);
+  DEFUN ("mod-test-invalid-store", Fmod_test_invalid_store, 0, 0, NULL, NULL);
+  DEFUN ("mod-test-invalid-load", Fmod_test_invalid_load, 0, 0, NULL, NULL);
 
 #undef DEFUN
 
diff --git a/test/src/emacs-module-tests.el b/test/src/emacs-module-tests.el
index 622bbad..99a853b 100644
--- a/test/src/emacs-module-tests.el
+++ b/test/src/emacs-module-tests.el
@@ -19,9 +19,17 @@
 
 (require 'ert)
 
-(require 'mod-test
-         (expand-file-name "data/emacs-module/mod-test"
-                           (getenv "EMACS_TEST_DIRECTORY")))
+(defconst mod-test-emacs
+  (expand-file-name invocation-name invocation-directory)
+  "File name of the Emacs binary currently running.")
+
+(eval-and-compile
+  (defconst mod-test-file
+    (substitute-in-file-name
+     "$EMACS_TEST_DIRECTORY/data/emacs-module/mod-test")
+    "File name of the module test file."))
+
+(require 'mod-test mod-test-file)
 
 ;;
 ;; Basic tests.
@@ -174,4 +182,30 @@ changes."
   (should (equal (help-function-arglist #'mod-test-sum)
                  '(arg1 arg2))))
 
+(ert-deftest module--test-assertions ()
+  "Check that -module-assertions work."
+  (skip-unless (file-executable-p mod-test-emacs))
+  ;; This doesn’t yet cause undefined behavior.
+  (should (eq (mod-test-invalid-store) 123))
+  (with-temp-buffer
+    (should (equal (call-process mod-test-emacs nil t nil
+                                 "-batch" "-Q" "-module-assertions" "-eval"
+                                 (prin1-to-string
+                                  `(progn
+                                     (require 'mod-test ,mod-test-file)
+                                     ;; Storing and reloading a local
+                                     ;; value causes undefined
+                                     ;; behavior, which should be
+                                     ;; detected by the module
+                                     ;; assertions.
+                                     (mod-test-invalid-store)
+                                     (mod-test-invalid-load))))
+                   ;; FIXME: This string is probably different on
+                   ;; Windows and Linux.
+                   "Abort trap: 6"))
+    (re-search-backward (rx bos "Emacs module assertion: "
+                            "Emacs value not found in "
+                            (+ digit) " values of "
+                            (+ digit) " environments" ?\n eos))))
+
 ;;; emacs-module-tests.el ends here



reply via email to

[Prev in Thread] Current Thread [Next in Thread]