Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move dlopenflags handling into new library loader #247

Merged
merged 7 commits into from
Dec 10, 2023
Merged
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 28 additions & 18 deletions lupa/__init__.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,46 @@
from __future__ import absolute_import

from contextlib import contextmanager
scoder marked this conversation as resolved.
Show resolved Hide resolved

# 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


@contextmanager
scoder marked this conversation as resolved.
Show resolved Hide resolved
def allow_lua_module_loading():
"""
A context manager for enabling binary Lua module loading when importing Lua.

def _try_import_with_global_library_symbols():
This can only be used once within a Python runtime and must wrap the import of the
``lupa.*`` Lua module, e.g.::

with lupa.allow_lua_module_loading()
from lupa import lua54
scoder marked this conversation as resolved.
Show resolved Hide resolved

lua = lua54.LuaRuntime()
lua.require('cjson')
"""
try:
from os import RTLD_NOW, RTLD_GLOBAL
except ImportError:
from DLFCN import RTLD_NOW, RTLD_GLOBAL # Py2.7
try:
from DLFCN import RTLD_NOW, RTLD_GLOBAL # Py2.7
except ImportError:
# MS-Windows does not have dlopen-flags.
yield
return

dlopen_flags = RTLD_NOW | RTLD_GLOBAL

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,8 +62,8 @@ 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())

_newest_lib = __import__(module_name[0], level=1, fromlist="*", globals=globals())
return _newest_lib


Expand Down
Loading