@@ -13,6 +13,13 @@ static emacs_value emacs_true;
1313static emacs_value wrong_type_argument ;
1414static emacs_value error ;
1515
16+ // Currently the emacs runtime is transient, and there is no way to
17+ // request an environment "out of the blue". These are stack
18+ // allocated as well. So, we stash the most recent one and clear it
19+ // when done. See
20+ // https://github.com/aaptel/emacs-dynamic-module/issues/41
21+ emacs_env * closure_environment ;
22+
1623#define ARRAY_SIZE (x ) (sizeof (x) / sizeof (x[0]))
1724
1825union holder
@@ -77,7 +84,6 @@ static struct type_descriptor type_descriptors[] =
7784// Description of a closure, freed by free_closure_desc.
7885struct closure_description
7986{
80- emacs_env * env ;
8187 void * closure ;
8288 void * code ;
8389 emacs_value cif_ref ;
@@ -466,7 +472,10 @@ module_ffi_call (emacs_env *env, int nargs, emacs_value *args, void *ignore)
466472 else
467473 result = & result_holder ;
468474
475+ // See the comment by closure_environment.
476+ closure_environment = env ;
469477 ffi_call (cif , fn , result , values );
478+ closure_environment = NULL ;
470479
471480 lisp_result = convert_to_lisp (env , cif -> rtype , result , free , true);
472481 if (lisp_result )
@@ -620,7 +629,9 @@ static void
620629generic_callback (ffi_cif * cif , void * ret , void * * args , void * d )
621630{
622631 struct closure_description * desc = d ;
623- emacs_env * env = desc -> env ;
632+ emacs_env * env = closure_environment ;
633+ // You may have lost. See the comment by closure_environment.
634+ assert (env );
624635
625636 emacs_value * argvalues = malloc (cif -> nargs * sizeof (emacs_value ));
626637 int i ;
@@ -658,8 +669,12 @@ free_closure_desc (void *d)
658669{
659670 struct closure_description * desc = d ;
660671
661- desc -> env -> free_global_ref (desc -> env , desc -> cif_ref );
662- desc -> env -> free_global_ref (desc -> env , desc -> func_ref );
672+ #if 0
673+ // We just leak here as there is no place to free these things.
674+ // https://github.com/aaptel/emacs-dynamic-module/issues/41
675+ env -> free_global_ref (env , desc -> cif_ref );
676+ env -> free_global_ref (env , desc -> func_ref );
677+ #endif
663678 ffi_closure_free (desc -> closure );
664679}
665680
@@ -687,7 +702,6 @@ module_ffi_make_closure (emacs_env *env, int nargs, emacs_value *args,
687702 void * writable = ffi_closure_alloc (sizeof (ffi_closure ), & code );
688703
689704 desc = malloc (sizeof (struct closure_description ));
690- desc -> env = env ;
691705 desc -> closure = writable ;
692706 desc -> code = code ;
693707 desc -> cif_ref = cif_ref ;
0 commit comments