Skip to content

Commit

Permalink
Move dlopenflags handling into new library loader
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
riconnon committed Oct 8, 2023
1 parent 96c1e3e commit 1beff57
Showing 1 changed file with 14 additions and 17 deletions.
31 changes: 14 additions & 17 deletions lupa/__init__.py
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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
Expand All @@ -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

Expand Down

0 comments on commit 1beff57

Please sign in to comment.