Skip to content

Commit 48335bc

Browse files
freakboy3742mhsmithericsnowcurrently
committed
[3.10] pythongh-114099 - Add iOS framework loading machinery. (pythonGH-116454)
Co-authored-by: Malcolm Smith <[email protected]> Co-authored-by: Eric Snow <[email protected]>
1 parent cd690e8 commit 48335bc

File tree

20 files changed

+2934
-2675
lines changed

20 files changed

+2934
-2675
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ Lib/test/data/*
6161
!Lib/test/data/README
6262
/Makefile
6363
/Makefile.pre
64-
iOSTestbed.*
64+
/iOSTestbed.*
6565
iOS/Frameworks/
6666
iOS/Resources/Info.plist
6767
iOS/testbed/build

Doc/library/importlib.rst

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1466,6 +1466,69 @@ find and load modules.
14661466
Boolean indicating whether or not the module's "origin"
14671467
attribute refers to a loadable location.
14681468

1469+
.. class:: AppleFrameworkLoader(name, path)
1470+
1471+
A specialization of :class:`importlib.machinery.ExtensionFileLoader` that
1472+
is able to load extension modules in Framework format.
1473+
1474+
For compatibility with the iOS App Store, *all* binary modules in an iOS app
1475+
must be dynamic libraries, contained in a framework with appropriate
1476+
metadata, stored in the ``Frameworks`` folder of the packaged app. There can
1477+
be only a single binary per framework, and there can be no executable binary
1478+
material outside the Frameworks folder.
1479+
1480+
To accomodate this requirement, when running on iOS, extension module
1481+
binaries are *not* packaged as ``.so`` files on ``sys.path``, but as
1482+
individual standalone frameworks. To discover those frameworks, this loader
1483+
is be registered against the ``.fwork`` file extension, with a ``.fwork``
1484+
file acting as a placeholder in the original location of the binary on
1485+
``sys.path``. The ``.fwork`` file contains the path of the actual binary in
1486+
the ``Frameworks`` folder, relative to the app bundle. To allow for
1487+
resolving a framework-packaged binary back to the original location, the
1488+
framework is expected to contain a ``.origin`` file that contains the
1489+
location of the ``.fwork`` file, relative to the app bundle.
1490+
1491+
For example, consider the case of an import ``from foo.bar import _whiz``,
1492+
where ``_whiz`` is implemented with the binary module
1493+
``sources/foo/bar/_whiz.abi3.so``, with ``sources`` being the location
1494+
registered on ``sys.path``, relative to the application bundle. This module
1495+
*must* be distributed as
1496+
``Frameworks/foo.bar._whiz.framework/foo.bar._whiz`` (creating the framework
1497+
name from the full import path of the module), with an ``Info.plist`` file
1498+
in the ``.framework`` directory identifying the binary as a framework. The
1499+
``foo.bar._whiz`` module would be represented in the original location with
1500+
a ``sources/foo/bar/_whiz.abi3.fwork`` marker file, containing the path
1501+
``Frameworks/foo.bar._whiz/foo.bar._whiz``. The framework would also contain
1502+
``Frameworks/foo.bar._whiz.framework/foo.bar._whiz.origin``, containing the
1503+
path to the ``.fwork`` file.
1504+
1505+
When a module is loaded with this loader, the ``__file__`` for the module
1506+
will report as the location of the ``.fwork`` file. This allows code to use
1507+
the ``__file__`` of a module as an anchor for file system traveral.
1508+
However, the spec origin will reference the location of the *actual* binary
1509+
in the ``.framework`` folder.
1510+
1511+
The Xcode project building the app is responsible for converting any ``.so``
1512+
files from wherever they exist in the ``PYTHONPATH`` into frameworks in the
1513+
``Frameworks`` folder (including stripping extensions from the module file,
1514+
the addition of framework metadata, and signing the resulting framework),
1515+
and creating the ``.fwork`` and ``.origin`` files. This will usually be done
1516+
with a build step in the Xcode project; see the iOS documentation for
1517+
details on how to construct this build step.
1518+
1519+
.. versionadded:: 3.13
1520+
1521+
.. availability:: iOS.
1522+
1523+
.. attribute:: name
1524+
1525+
Name of the module the loader supports.
1526+
1527+
.. attribute:: path
1528+
1529+
Path to the ``.fwork`` file for the extension module.
1530+
1531+
14691532
:mod:`importlib.util` -- Utility code for importers
14701533
---------------------------------------------------
14711534

Lib/ctypes/__init__.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,19 @@ def __init__(self, name, mode=DEFAULT_MODE, handle=None,
341341
use_errno=False,
342342
use_last_error=False,
343343
winmode=None):
344+
if name:
345+
name = _os.fspath(name)
346+
347+
# If the filename that has been provided is an iOS/tvOS/watchOS
348+
# .fwork file, dereference the location to the true origin of the
349+
# binary.
350+
if name.endswith(".fwork"):
351+
with open(name) as f:
352+
name = _os.path.join(
353+
_os.path.dirname(_sys.executable),
354+
f.read().strip()
355+
)
356+
344357
self._name = name
345358
flags = self._func_flags_
346359
if use_errno:

Lib/ctypes/util.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def find_library(name):
6767
return fname
6868
return None
6969

70-
elif os.name == "posix" and sys.platform == "darwin":
70+
elif os.name == "posix" and sys.platform in {"darwin", "ios", "tvos", "watchos"}:
7171
from ctypes.macholib.dyld import dyld_find as _dyld_find
7272
def find_library(name):
7373
possible = ['lib%s.dylib' % name,

Lib/importlib/_bootstrap_external.py

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252

5353
# Bootstrap-related code ######################################################
5454
_CASE_INSENSITIVE_PLATFORMS_STR_KEY = 'win',
55-
_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY = 'cygwin', 'darwin'
55+
_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY = 'cygwin', 'darwin', 'ios', 'tvos', 'watchos'
5656
_CASE_INSENSITIVE_PLATFORMS = (_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY
5757
+ _CASE_INSENSITIVE_PLATFORMS_STR_KEY)
5858

@@ -1637,6 +1637,46 @@ def __repr__(self):
16371637
return 'FileFinder({!r})'.format(self.path)
16381638

16391639

1640+
class AppleFrameworkLoader(ExtensionFileLoader):
1641+
"""A loader for modules that have been packaged as frameworks for
1642+
compatibility with Apple's iOS App Store policies.
1643+
"""
1644+
def create_module(self, spec):
1645+
# If the ModuleSpec has been created by the FileFinder, it will have
1646+
# been created with an origin pointing to the .fwork file. We need to
1647+
# redirect this to the location in the Frameworks folder, using the
1648+
# content of the .fwork file.
1649+
if spec.origin.endswith(".fwork"):
1650+
with _io.FileIO(spec.origin, 'r') as file:
1651+
framework_binary = file.read().decode().strip()
1652+
bundle_path = _path_split(sys.executable)[0]
1653+
spec.origin = _path_join(bundle_path, framework_binary)
1654+
1655+
# If the loader is created based on the spec for a loaded module, the
1656+
# path will be pointing at the Framework location. If this occurs,
1657+
# get the original .fwork location to use as the module's __file__.
1658+
if self.path.endswith(".fwork"):
1659+
path = self.path
1660+
else:
1661+
with _io.FileIO(self.path + ".origin", 'r') as file:
1662+
origin = file.read().decode().strip()
1663+
bundle_path = _path_split(sys.executable)[0]
1664+
path = _path_join(bundle_path, origin)
1665+
1666+
module = _bootstrap._call_with_frames_removed(_imp.create_dynamic, spec)
1667+
1668+
_bootstrap._verbose_message(
1669+
"Apple framework extension module {!r} loaded from {!r} (path {!r})",
1670+
spec.name,
1671+
spec.origin,
1672+
path,
1673+
)
1674+
1675+
# Ensure that the __file__ points at the .fwork location
1676+
module.__file__ = path
1677+
1678+
return module
1679+
16401680
# Import setup ###############################################################
16411681

16421682
def _fix_up_module(ns, name, pathname, cpathname=None):
@@ -1667,10 +1707,17 @@ def _get_supported_file_loaders():
16671707
16681708
Each item is a tuple (loader, suffixes).
16691709
"""
1670-
extensions = ExtensionFileLoader, _imp.extension_suffixes()
1710+
if sys.platform in {"ios", "tvos", "watchos"}:
1711+
extension_loaders = [(AppleFrameworkLoader, [
1712+
suffix.replace(".so", ".fwork")
1713+
for suffix in _imp.extension_suffixes()
1714+
])]
1715+
else:
1716+
extension_loaders = []
1717+
extension_loaders.append((ExtensionFileLoader, _imp.extension_suffixes()))
16711718
source = SourceFileLoader, SOURCE_SUFFIXES
16721719
bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES
1673-
return [extensions, source, bytecode]
1720+
return extension_loaders + [source, bytecode]
16741721

16751722

16761723
def _set_bootstrap_module(_bootstrap_module):

Lib/importlib/abc.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,11 @@ def get_code(self, fullname):
250250
else:
251251
return self.source_to_code(source, path)
252252

253-
_register(ExecutionLoader, machinery.ExtensionFileLoader)
253+
_register(
254+
ExecutionLoader,
255+
machinery.ExtensionFileLoader,
256+
machinery.AppleFrameworkLoader,
257+
)
254258

255259

256260
class FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader):

Lib/importlib/machinery.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from ._bootstrap_external import SourceFileLoader
1313
from ._bootstrap_external import SourcelessFileLoader
1414
from ._bootstrap_external import ExtensionFileLoader
15+
from ._bootstrap_external import AppleFrameworkLoader
1516

1617

1718
def all_suffixes():

Lib/inspect.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -853,6 +853,7 @@ def getmodule(object, _filename=None):
853853
return object
854854
if hasattr(object, '__module__'):
855855
return sys.modules.get(object.__module__)
856+
856857
# Try the filename to modulename cache
857858
if _filename is not None and _filename in modulesbyfile:
858859
return sys.modules.get(modulesbyfile[_filename])
@@ -946,7 +947,7 @@ def findsource(object):
946947
# Allow filenames in form of "<something>" to pass through.
947948
# `doctest` monkeypatches `linecache` module to enable
948949
# inspection, so let `linecache.getlines` to be called.
949-
if not (file.startswith('<') and file.endswith('>')):
950+
if (not (file.startswith('<') and file.endswith('>'))) or file.endswith('.fwork'):
950951
raise OSError('source code not available')
951952

952953
module = getmodule(object, file)

Lib/modulefinder.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,12 @@ def _find_module(name, path=None):
8080
if isinstance(spec.loader, importlib.machinery.SourceFileLoader):
8181
kind = _PY_SOURCE
8282

83-
elif isinstance(spec.loader, importlib.machinery.ExtensionFileLoader):
83+
elif isinstance(
84+
spec.loader, (
85+
importlib.machinery.ExtensionFileLoader,
86+
importlib.machinery.AppleFrameworkLoader,
87+
)
88+
):
8489
kind = _C_EXTENSION
8590

8691
elif isinstance(spec.loader, importlib.machinery.SourcelessFileLoader):

Lib/test/test_capi/test_misc.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -791,14 +791,21 @@ def test_module_state_shared_in_global(self):
791791
self.addCleanup(os.close, r)
792792
self.addCleanup(os.close, w)
793793

794+
# Apple extensions must be distributed as frameworks. This requires
795+
# a specialist loader.
796+
if support.is_apple_mobile:
797+
loader = "AppleFrameworkLoader"
798+
else:
799+
loader = "ExtensionFileLoader"
800+
794801
script = textwrap.dedent(f"""
795802
import importlib.machinery
796803
import importlib.util
797804
import os
798805
799806
fullname = '_test_module_state_shared'
800807
origin = importlib.util.find_spec('_testmultiphase').origin
801-
loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
808+
loader = importlib.machinery.{loader}(fullname, origin)
802809
spec = importlib.util.spec_from_loader(fullname, loader)
803810
module = importlib.util.module_from_spec(spec)
804811
attr_id = str(id(module.Error)).encode()
@@ -996,7 +1003,12 @@ class Test_ModuleStateAccess(unittest.TestCase):
9961003
def setUp(self):
9971004
fullname = '_testmultiphase_meth_state_access' # XXX
9981005
origin = importlib.util.find_spec('_testmultiphase').origin
999-
loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
1006+
# Apple extensions must be distributed as frameworks. This requires
1007+
# a specialist loader.
1008+
if support.is_apple_mobile:
1009+
loader = importlib.machinery.AppleFrameworkLoader(fullname, origin)
1010+
else:
1011+
loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
10001012
spec = importlib.util.spec_from_loader(fullname, loader)
10011013
module = importlib.util.module_from_spec(spec)
10021014
loader.exec_module(module)

0 commit comments

Comments
 (0)