From 1beff57ac458cd26508c7e222eb23ae46a17aa28 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 | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/lupa/__init__.py b/lupa/__init__.py index b782c1cc..f939895f 100644 --- a/lupa/__init__.py +++ b/lupa/__init__.py @@ -1,11 +1,13 @@ from __future__ import absolute_import +from contextlib import contextmanager -# 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. +# Find the implementation with the latest Lua version available. +_newest_lib = None -def _try_import_with_global_library_symbols(): + +@contextmanager +def eager_global_linking(): try: from os import RTLD_NOW, RTLD_GLOBAL except ImportError: @@ -14,23 +16,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 +44,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