From 74da7d32c7ce03d6f6c2249bda1e3e645426ab0b Mon Sep 17 00:00:00 2001 From: Richard Connon Date: Sun, 8 Oct 2023 01:00:52 +0100 Subject: [PATCH] Move dlopenflags handling into new library loader The C library is no longer dynamically loaded directly when `_lupa` is imported, so we need to move the special handling of dlopenflags into the `_import_newest_lib()` function in order to ensure they are set when the lupa C extension is `dlopen`'d. We also expose a context manager `eager_global_linking()` for users with special needs to get the same behaviour. --- lupa/__init__.py | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/lupa/__init__.py b/lupa/__init__.py index b782c1cc..9ea49c4e 100644 --- a/lupa/__init__.py +++ b/lupa/__init__.py @@ -1,11 +1,15 @@ from __future__ import absolute_import +import sys + +from contextlib import contextmanager + +# Find the implementation with the latest Lua version available. +_newest_lib = None -# We need to enable global symbol visibility for lupa in order to -# support binary module loading in Lua. If we can enable it here, we -# do it temporarily. -def _try_import_with_global_library_symbols(): +@contextmanager +def eager_global_linking(): try: from os import RTLD_NOW, RTLD_GLOBAL except ImportError: @@ -14,23 +18,13 @@ def _try_import_with_global_library_symbols(): import sys old_flags = sys.getdlopenflags() + try: sys.setdlopenflags(dlopen_flags) - import lupa._lupa + yield finally: sys.setdlopenflags(old_flags) -try: - _try_import_with_global_library_symbols() -except: - pass - -del _try_import_with_global_library_symbols - - -# Find the implementation with the latest Lua version available. -_newest_lib = None - def _import_newest_lib(): global _newest_lib @@ -52,7 +46,12 @@ def _import_newest_lib(): raise RuntimeError("Failed to import Lupa binary module.") # prefer Lua over LuaJIT and high versions over low versions. module_name = max(modules, key=lambda m: (m[1] == 'lua', tuple(map(int, m[2] or '0')))) - _newest_lib = __import__(module_name[0], level=1, fromlist="*", globals=globals()) + + # We need to enable global symbol visibility for lupa in order to + # support binary module loading in Lua. If we can enable it here, we + # do it temporarily. + with eager_global_linking(): + _newest_lib = __import__(module_name[0], level=1, fromlist="*", globals=globals()) return _newest_lib @@ -66,7 +65,6 @@ def __getattr__(name): return getattr(lua, name) -import sys if sys.version_info < (3, 7): # Module level "__getattr__" requires Py3.7 or later => import latest Lua now _import_newest_lib()