Skip to content

Commit 6b61e10

Browse files
freakboy3742mhsmithericsnowcurrently
committed
[3.12] 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 46bb44b commit 6b61e10

File tree

22 files changed

+302
-62
lines changed

22 files changed

+302
-62
lines changed

.gitignore

+1-1
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ Lib/test/data/*
6969
/_bootstrap_python
7070
/Makefile
7171
/Makefile.pre
72-
iOSTestbed.*
72+
/iOSTestbed.*
7373
iOS/Frameworks/
7474
iOS/Resources/Info.plist
7575
iOS/testbed/build

Doc/library/importlib.rst

+63
Original file line numberDiff line numberDiff line change
@@ -1241,6 +1241,69 @@ find and load modules.
12411241
and how the module's :attr:`__file__` is populated.
12421242

12431243

1244+
.. class:: AppleFrameworkLoader(name, path)
1245+
1246+
A specialization of :class:`importlib.machinery.ExtensionFileLoader` that
1247+
is able to load extension modules in Framework format.
1248+
1249+
For compatibility with the iOS App Store, *all* binary modules in an iOS app
1250+
must be dynamic libraries, contained in a framework with appropriate
1251+
metadata, stored in the ``Frameworks`` folder of the packaged app. There can
1252+
be only a single binary per framework, and there can be no executable binary
1253+
material outside the Frameworks folder.
1254+
1255+
To accomodate this requirement, when running on iOS, extension module
1256+
binaries are *not* packaged as ``.so`` files on ``sys.path``, but as
1257+
individual standalone frameworks. To discover those frameworks, this loader
1258+
is be registered against the ``.fwork`` file extension, with a ``.fwork``
1259+
file acting as a placeholder in the original location of the binary on
1260+
``sys.path``. The ``.fwork`` file contains the path of the actual binary in
1261+
the ``Frameworks`` folder, relative to the app bundle. To allow for
1262+
resolving a framework-packaged binary back to the original location, the
1263+
framework is expected to contain a ``.origin`` file that contains the
1264+
location of the ``.fwork`` file, relative to the app bundle.
1265+
1266+
For example, consider the case of an import ``from foo.bar import _whiz``,
1267+
where ``_whiz`` is implemented with the binary module
1268+
``sources/foo/bar/_whiz.abi3.so``, with ``sources`` being the location
1269+
registered on ``sys.path``, relative to the application bundle. This module
1270+
*must* be distributed as
1271+
``Frameworks/foo.bar._whiz.framework/foo.bar._whiz`` (creating the framework
1272+
name from the full import path of the module), with an ``Info.plist`` file
1273+
in the ``.framework`` directory identifying the binary as a framework. The
1274+
``foo.bar._whiz`` module would be represented in the original location with
1275+
a ``sources/foo/bar/_whiz.abi3.fwork`` marker file, containing the path
1276+
``Frameworks/foo.bar._whiz/foo.bar._whiz``. The framework would also contain
1277+
``Frameworks/foo.bar._whiz.framework/foo.bar._whiz.origin``, containing the
1278+
path to the ``.fwork`` file.
1279+
1280+
When a module is loaded with this loader, the ``__file__`` for the module
1281+
will report as the location of the ``.fwork`` file. This allows code to use
1282+
the ``__file__`` of a module as an anchor for file system traveral.
1283+
However, the spec origin will reference the location of the *actual* binary
1284+
in the ``.framework`` folder.
1285+
1286+
The Xcode project building the app is responsible for converting any ``.so``
1287+
files from wherever they exist in the ``PYTHONPATH`` into frameworks in the
1288+
``Frameworks`` folder (including stripping extensions from the module file,
1289+
the addition of framework metadata, and signing the resulting framework),
1290+
and creating the ``.fwork`` and ``.origin`` files. This will usually be done
1291+
with a build step in the Xcode project; see the iOS documentation for
1292+
details on how to construct this build step.
1293+
1294+
.. versionadded:: 3.13
1295+
1296+
.. availability:: iOS.
1297+
1298+
.. attribute:: name
1299+
1300+
Name of the module the loader supports.
1301+
1302+
.. attribute:: path
1303+
1304+
Path to the ``.fwork`` file for the extension module.
1305+
1306+
12441307
:mod:`importlib.util` -- Utility code for importers
12451308
---------------------------------------------------
12461309

Doc/tools/extensions/pyspecific.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ class Availability(SphinxDirective):
118118
known_platforms = frozenset({
119119
"AIX", "Android", "BSD", "DragonFlyBSD", "Emscripten", "FreeBSD",
120120
"Linux", "NetBSD", "OpenBSD", "POSIX", "Solaris", "Unix", "VxWorks",
121-
"WASI", "Windows", "macOS",
121+
"WASI", "Windows", "macOS", "iOS",
122122
# libc
123123
"BSD libc", "glibc", "musl",
124124
# POSIX platforms with pthreads

Lib/ctypes/__init__.py

+11
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,17 @@ def __init__(self, name, mode=DEFAULT_MODE, handle=None,
346346
winmode=None):
347347
if name:
348348
name = _os.fspath(name)
349+
350+
# If the filename that has been provided is an iOS/tvOS/watchOS
351+
# .fwork file, dereference the location to the true origin of the
352+
# binary.
353+
if name.endswith(".fwork"):
354+
with open(name) as f:
355+
name = _os.path.join(
356+
_os.path.dirname(_sys.executable),
357+
f.read().strip()
358+
)
359+
349360
self._name = name
350361
flags = self._func_flags_
351362
if use_errno:

Lib/ctypes/util.py

+1-1
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

+50-3
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

@@ -1694,6 +1694,46 @@ def __repr__(self):
16941694
return f'FileFinder({self.path!r})'
16951695

16961696

1697+
class AppleFrameworkLoader(ExtensionFileLoader):
1698+
"""A loader for modules that have been packaged as frameworks for
1699+
compatibility with Apple's iOS App Store policies.
1700+
"""
1701+
def create_module(self, spec):
1702+
# If the ModuleSpec has been created by the FileFinder, it will have
1703+
# been created with an origin pointing to the .fwork file. We need to
1704+
# redirect this to the location in the Frameworks folder, using the
1705+
# content of the .fwork file.
1706+
if spec.origin.endswith(".fwork"):
1707+
with _io.FileIO(spec.origin, 'r') as file:
1708+
framework_binary = file.read().decode().strip()
1709+
bundle_path = _path_split(sys.executable)[0]
1710+
spec.origin = _path_join(bundle_path, framework_binary)
1711+
1712+
# If the loader is created based on the spec for a loaded module, the
1713+
# path will be pointing at the Framework location. If this occurs,
1714+
# get the original .fwork location to use as the module's __file__.
1715+
if self.path.endswith(".fwork"):
1716+
path = self.path
1717+
else:
1718+
with _io.FileIO(self.path + ".origin", 'r') as file:
1719+
origin = file.read().decode().strip()
1720+
bundle_path = _path_split(sys.executable)[0]
1721+
path = _path_join(bundle_path, origin)
1722+
1723+
module = _bootstrap._call_with_frames_removed(_imp.create_dynamic, spec)
1724+
1725+
_bootstrap._verbose_message(
1726+
"Apple framework extension module {!r} loaded from {!r} (path {!r})",
1727+
spec.name,
1728+
spec.origin,
1729+
path,
1730+
)
1731+
1732+
# Ensure that the __file__ points at the .fwork location
1733+
module.__file__ = path
1734+
1735+
return module
1736+
16971737
# Import setup ###############################################################
16981738

16991739
def _fix_up_module(ns, name, pathname, cpathname=None):
@@ -1726,10 +1766,17 @@ def _get_supported_file_loaders():
17261766
17271767
Each item is a tuple (loader, suffixes).
17281768
"""
1729-
extensions = ExtensionFileLoader, _imp.extension_suffixes()
1769+
if sys.platform in {"ios", "tvos", "watchos"}:
1770+
extension_loaders = [(AppleFrameworkLoader, [
1771+
suffix.replace(".so", ".fwork")
1772+
for suffix in _imp.extension_suffixes()
1773+
])]
1774+
else:
1775+
extension_loaders = []
1776+
extension_loaders.append((ExtensionFileLoader, _imp.extension_suffixes()))
17301777
source = SourceFileLoader, SOURCE_SUFFIXES
17311778
bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES
1732-
return [extensions, source, bytecode]
1779+
return extension_loaders + [source, bytecode]
17331780

17341781

17351782
def _set_bootstrap_module(_bootstrap_module):

Lib/importlib/abc.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,11 @@ def get_code(self, fullname):
180180
else:
181181
return self.source_to_code(source, path)
182182

183-
_register(ExecutionLoader, machinery.ExtensionFileLoader)
183+
_register(
184+
ExecutionLoader,
185+
machinery.ExtensionFileLoader,
186+
machinery.AppleFrameworkLoader,
187+
)
184188

185189

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

Lib/importlib/machinery.py

+1
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
from ._bootstrap_external import NamespaceLoader
1617

1718

Lib/inspect.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -955,6 +955,10 @@ def getsourcefile(object):
955955
elif any(filename.endswith(s) for s in
956956
importlib.machinery.EXTENSION_SUFFIXES):
957957
return None
958+
elif filename.endswith(".fwork"):
959+
# Apple mobile framework markers are another type of non-source file
960+
return None
961+
958962
# return a filename found in the linecache even if it doesn't exist on disk
959963
if filename in linecache.cache:
960964
return filename
@@ -985,6 +989,7 @@ def getmodule(object, _filename=None):
985989
return object
986990
if hasattr(object, '__module__'):
987991
return sys.modules.get(object.__module__)
992+
988993
# Try the filename to modulename cache
989994
if _filename is not None and _filename in modulesbyfile:
990995
return sys.modules.get(modulesbyfile[_filename])
@@ -1078,7 +1083,7 @@ def findsource(object):
10781083
# Allow filenames in form of "<something>" to pass through.
10791084
# `doctest` monkeypatches `linecache` module to enable
10801085
# inspection, so let `linecache.getlines` to be called.
1081-
if not (file.startswith('<') and file.endswith('>')):
1086+
if (not (file.startswith('<') and file.endswith('>'))) or file.endswith('.fwork'):
10821087
raise OSError('source code not available')
10831088

10841089
module = getmodule(object, file)

Lib/modulefinder.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,12 @@ def _find_module(name, path=None):
7272
if isinstance(spec.loader, importlib.machinery.SourceFileLoader):
7373
kind = _PY_SOURCE
7474

75-
elif isinstance(spec.loader, importlib.machinery.ExtensionFileLoader):
75+
elif isinstance(
76+
spec.loader, (
77+
importlib.machinery.ExtensionFileLoader,
78+
importlib.machinery.AppleFrameworkLoader,
79+
)
80+
):
7681
kind = _C_EXTENSION
7782

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

Lib/test/test_capi/test_misc.py

+14-2
Original file line numberDiff line numberDiff line change
@@ -1979,14 +1979,21 @@ def test_module_state_shared_in_global(self):
19791979
self.addCleanup(os.close, r)
19801980
self.addCleanup(os.close, w)
19811981

1982+
# Apple extensions must be distributed as frameworks. This requires
1983+
# a specialist loader.
1984+
if support.is_apple_mobile:
1985+
loader = "AppleFrameworkLoader"
1986+
else:
1987+
loader = "ExtensionFileLoader"
1988+
19821989
script = textwrap.dedent(f"""
19831990
import importlib.machinery
19841991
import importlib.util
19851992
import os
19861993
19871994
fullname = '_test_module_state_shared'
19881995
origin = importlib.util.find_spec('_testmultiphase').origin
1989-
loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
1996+
loader = importlib.machinery.{loader}(fullname, origin)
19901997
spec = importlib.util.spec_from_loader(fullname, loader)
19911998
module = importlib.util.module_from_spec(spec)
19921999
attr_id = str(id(module.Error)).encode()
@@ -2160,7 +2167,12 @@ class Test_ModuleStateAccess(unittest.TestCase):
21602167
def setUp(self):
21612168
fullname = '_testmultiphase_meth_state_access' # XXX
21622169
origin = importlib.util.find_spec('_testmultiphase').origin
2163-
loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
2170+
# Apple extensions must be distributed as frameworks. This requires
2171+
# a specialist loader.
2172+
if support.is_apple_mobile:
2173+
loader = importlib.machinery.AppleFrameworkLoader(fullname, origin)
2174+
else:
2175+
loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
21642176
spec = importlib.util.spec_from_loader(fullname, loader)
21652177
module = importlib.util.module_from_spec(spec)
21662178
loader.exec_module(module)

0 commit comments

Comments
 (0)