_parent.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. # -----------------------------------------------------------------------------
  2. # Copyright (c) 2021-2023, PyInstaller Development Team.
  3. #
  4. # Distributed under the terms of the GNU General Public License (version 2
  5. # or later) or, at the user's discretion, the MIT License.
  6. #
  7. # The full license is in the file COPYING.txt, distributed with this software.
  8. #
  9. # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception OR MIT)
  10. # -----------------------------------------------------------------------------
  11. import os
  12. from pathlib import Path
  13. from marshal import loads, dumps
  14. from base64 import b64encode, b64decode
  15. import functools
  16. import subprocess
  17. import sys
  18. from PyInstaller import compat
  19. from PyInstaller import log as logging
  20. logger = logging.getLogger(__name__)
  21. # WinAPI bindings for Windows-specific codepath
  22. if os.name == "nt":
  23. import msvcrt
  24. import ctypes
  25. import ctypes.wintypes
  26. # CreatePipe
  27. class SECURITY_ATTRIBUTES(ctypes.Structure):
  28. _fields_ = [
  29. ("nLength", ctypes.wintypes.DWORD),
  30. ("lpSecurityDescriptor", ctypes.wintypes.LPVOID),
  31. ("bInheritHandle", ctypes.wintypes.BOOL),
  32. ]
  33. HANDLE_FLAG_INHERIT = 0x0001
  34. LPSECURITY_ATTRIBUTES = ctypes.POINTER(SECURITY_ATTRIBUTES)
  35. CreatePipe = ctypes.windll.kernel32.CreatePipe
  36. CreatePipe.argtypes = [
  37. ctypes.POINTER(ctypes.wintypes.HANDLE),
  38. ctypes.POINTER(ctypes.wintypes.HANDLE),
  39. LPSECURITY_ATTRIBUTES,
  40. ctypes.wintypes.DWORD,
  41. ]
  42. CreatePipe.restype = ctypes.wintypes.BOOL
  43. # CloseHandle
  44. CloseHandle = ctypes.windll.kernel32.CloseHandle
  45. CloseHandle.argtypes = [ctypes.wintypes.HANDLE]
  46. CloseHandle.restype = ctypes.wintypes.BOOL
  47. CHILD_PY = Path(__file__).with_name("_child.py")
  48. def create_pipe(read_handle_inheritable, write_handle_inheritable):
  49. """
  50. Create a one-way pipe for sending data to child processes.
  51. Args:
  52. read_handle_inheritable:
  53. A boolean flag indicating whether the handle corresponding to the read end-point of the pipe should be
  54. marked as inheritable by subprocesses.
  55. write_handle_inheritable:
  56. A boolean flag indicating whether the handle corresponding to the write end-point of the pipe should be
  57. marked as inheritable by subprocesses.
  58. Returns:
  59. A read/write pair of file descriptors (which are just integers) on posix or system file handles on Windows.
  60. The pipe may be used either by this process or subprocesses of this process but not globally.
  61. """
  62. return _create_pipe_impl(read_handle_inheritable, write_handle_inheritable)
  63. def close_pipe_endpoint(pipe_handle):
  64. """
  65. Close the file descriptor (posix) or handle (Windows) belonging to a pipe.
  66. """
  67. return _close_pipe_endpoint_impl(pipe_handle)
  68. if os.name == "nt":
  69. def _create_pipe_impl(read_handle_inheritable, write_handle_inheritable):
  70. # Use WinAPI CreatePipe function to create the pipe. Python's os.pipe() does the same, but wraps the resulting
  71. # handles into inheritable file descriptors (https://github.com/python/cpython/issues/77046). Instead, we want
  72. # just handles, and will set the inheritable flag on corresponding handle ourselves.
  73. read_handle = ctypes.wintypes.HANDLE()
  74. write_handle = ctypes.wintypes.HANDLE()
  75. # SECURITY_ATTRIBUTES with inherit handle set to True
  76. security_attributes = SECURITY_ATTRIBUTES()
  77. security_attributes.nLength = ctypes.sizeof(security_attributes)
  78. security_attributes.bInheritHandle = True
  79. security_attributes.lpSecurityDescriptor = None
  80. # CreatePipe()
  81. succeeded = CreatePipe(
  82. ctypes.byref(read_handle), # hReadPipe
  83. ctypes.byref(write_handle), # hWritePipe
  84. ctypes.byref(security_attributes), # lpPipeAttributes
  85. 0, # nSize
  86. )
  87. if not succeeded:
  88. raise ctypes.WinError()
  89. # Set inheritable flags. Instead of binding and using SetHandleInformation WinAPI function, we can use
  90. # os.set_handle_inheritable().
  91. os.set_handle_inheritable(read_handle.value, read_handle_inheritable)
  92. os.set_handle_inheritable(write_handle.value, write_handle_inheritable)
  93. return read_handle.value, write_handle.value
  94. def _close_pipe_endpoint_impl(pipe_handle):
  95. succeeded = CloseHandle(pipe_handle)
  96. if not succeeded:
  97. raise ctypes.WinError()
  98. else:
  99. def _create_pipe_impl(read_fd_inheritable, write_fd_inheritable):
  100. # Create pipe, using os.pipe()
  101. read_fd, write_fd = os.pipe()
  102. # The default behaviour of pipes is that they are process specific. I.e., they can only be used by this
  103. # process to talk to itself. Setting inheritable flags means that child processes may also use these pipes.
  104. os.set_inheritable(read_fd, read_fd_inheritable)
  105. os.set_inheritable(write_fd, write_fd_inheritable)
  106. return read_fd, write_fd
  107. def _close_pipe_endpoint_impl(pipe_fd):
  108. os.close(pipe_fd)
  109. def child(read_from_parent: int, write_to_parent: int):
  110. """
  111. Spawn a Python subprocess sending it the two file descriptors it needs to talk back to this parent process.
  112. """
  113. if os.name != 'nt':
  114. # Explicitly disabling close_fds is a requirement for making file descriptors inheritable by child processes.
  115. extra_kwargs = {
  116. "env": _subprocess_env(),
  117. "close_fds": False,
  118. }
  119. else:
  120. # On Windows, we can use subprocess.STARTUPINFO to explicitly pass the list of file handles to be inherited,
  121. # so we can avoid disabling close_fds
  122. extra_kwargs = {
  123. "env": _subprocess_env(),
  124. "close_fds": True,
  125. "startupinfo": subprocess.STARTUPINFO(lpAttributeList={"handle_list": [read_from_parent, write_to_parent]})
  126. }
  127. # Run the _child.py script directly passing it the two file descriptors it needs to talk back to the parent.
  128. cmd, options = compat.__wrap_python([str(CHILD_PY), str(read_from_parent), str(write_to_parent)], extra_kwargs)
  129. # I'm intentionally leaving stdout and stderr alone so that print() can still be used for emergency debugging and
  130. # unhandled errors in the child are still visible.
  131. return subprocess.Popen(cmd, **options)
  132. def _subprocess_env():
  133. """
  134. Define the environment variables to be readable in a child process.
  135. """
  136. from PyInstaller.config import CONF
  137. python_path = CONF["pathex"]
  138. if "PYTHONPATH" in os.environ:
  139. python_path = python_path + [os.environ["PYTHONPATH"]]
  140. env = os.environ.copy()
  141. env["PYTHONPATH"] = os.pathsep.join(python_path)
  142. return env
  143. class SubprocessDiedError(RuntimeError):
  144. pass
  145. class Python:
  146. """
  147. Start and connect to a separate Python subprocess.
  148. This is the lowest level of public API provided by this module. The advantage of using this class directly is
  149. that it allows multiple functions to be evaluated in a single subprocess, making it faster than multiple calls to
  150. :func:`call`.
  151. The ``strict_mode`` argument controls behavior when the child process fails to shut down; if strict mode is enabled,
  152. an error is raised, otherwise only warning is logged. If the value of ``strict_mode`` is ``None``, the value of
  153. ``PyInstaller.compat.strict_collect_mode`` is used (which in turn is controlled by the
  154. ``PYINSTALLER_STRICT_COLLECT_MODE`` environment variable.
  155. Examples:
  156. To call some predefined functions ``x = foo()``, ``y = bar("numpy")`` and ``z = bazz(some_flag=True)`` all using
  157. the same isolated subprocess use::
  158. with isolated.Python() as child:
  159. x = child.call(foo)
  160. y = child.call(bar, "numpy")
  161. z = child.call(bazz, some_flag=True)
  162. """
  163. def __init__(self, strict_mode=None):
  164. self._child = None
  165. # Re-use the compat.strict_collect_mode and its PYINSTALLER_STRICT_COLLECT_MODE environment variable for
  166. # default strict-mode setting.
  167. self._strict_mode = strict_mode if strict_mode is not None else compat.strict_collect_mode
  168. # Check if we are already running in PyInstaller's isolated subprocess, to prevent further nesting.
  169. self._already_isolated = getattr(sys, '_pyi_isolated_subprocess', False)
  170. def __enter__(self):
  171. # No-op if already running in an isolated subprocess.
  172. if self._already_isolated:
  173. return self
  174. # We need two pipes. One for the child to send data to the parent. The (write) end-point passed to the
  175. # child needs to be marked as inheritable.
  176. read_from_child, write_to_parent = create_pipe(False, True)
  177. # And one for the parent to send data to the child. The (read) end-point passed to the child needs to be
  178. # marked as inheritable.
  179. read_from_parent, write_to_child = create_pipe(True, False)
  180. # Spawn a Python subprocess sending it the two file descriptors it needs to talk back to this parent process.
  181. self._child = child(read_from_parent, write_to_parent)
  182. # Close the end-points that were inherited by the child.
  183. close_pipe_endpoint(read_from_parent)
  184. close_pipe_endpoint(write_to_parent)
  185. del read_from_parent
  186. del write_to_parent
  187. # Open file handles to talk to the child. This should fully transfer ownership of the underlying file
  188. # descriptor to the opened handle; so when we close the latter, the former should be closed as well.
  189. if os.name == 'nt':
  190. # On Windows, we must first open file descriptor on top of the handle using _open_osfhandle (which
  191. # python wraps in msvcrt.open_osfhandle). According to MSDN, this transfers the ownership of the
  192. # underlying file handle to the file descriptors; i.e., they are both closed when the file descriptor
  193. # is closed).
  194. self._write_handle = os.fdopen(msvcrt.open_osfhandle(write_to_child, 0), "wb")
  195. self._read_handle = os.fdopen(msvcrt.open_osfhandle(read_from_child, 0), "rb")
  196. else:
  197. self._write_handle = os.fdopen(write_to_child, "wb")
  198. self._read_handle = os.fdopen(read_from_child, "rb")
  199. self._send(sys.path)
  200. return self
  201. def __exit__(self, exc_type, exc_val, exc_tb):
  202. # No-op if already running in an isolated subprocess.
  203. if self._already_isolated:
  204. return
  205. if exc_type and issubclass(exc_type, SubprocessDiedError):
  206. self._write_handle.close()
  207. self._read_handle.close()
  208. del self._read_handle, self._write_handle
  209. self._child = None
  210. return
  211. # Send the signal (a blank line) to the child to tell it that it's time to stop.
  212. self._write_handle.write(b"\n")
  213. self._write_handle.flush()
  214. # Wait for the child process to exit. The timeout is necessary for corner cases when the sub-process fails to
  215. # exit (such as due to dangling non-daemon threads; see #7290). At this point, the subprocess already did all
  216. # its work, so it should be safe to terminate. And as we expect it to shut down quickly (or not at all), the
  217. # timeout is relatively short.
  218. #
  219. # In strict build mode, we raise an error when the subprocess fails to exit on its own, but do so only after
  220. # we attempt to kill the subprocess, to avoid leaving zombie processes.
  221. shutdown_error = False
  222. try:
  223. self._child.wait(timeout=5)
  224. except subprocess.TimeoutExpired:
  225. logger.warning("Timed out while waiting for the child process to exit!")
  226. shutdown_error = True
  227. self._child.kill()
  228. try:
  229. self._child.wait(timeout=15)
  230. except subprocess.TimeoutExpired:
  231. logger.warning("Timed out while waiting for the child process to be killed!")
  232. # Give up and fall through
  233. # Close the handles. This should also close the underlying file descriptors.
  234. self._write_handle.close()
  235. self._read_handle.close()
  236. del self._read_handle, self._write_handle
  237. self._child = None
  238. # Raise an error in strict mode, after all clean-up has been performed.
  239. if shutdown_error and self._strict_mode:
  240. raise RuntimeError("Timed out while waiting for the child process to exit!")
  241. def call(self, function, *args, **kwargs):
  242. """
  243. Call a function in the child Python. Retrieve its return value. Usage of this method is identical to that
  244. of the :func:`call` function.
  245. """
  246. # If already running in an isolated subprocess, directly execute the function.
  247. if self._already_isolated:
  248. return function(*args, **kwargs)
  249. if self._child is None:
  250. raise RuntimeError("An isolated.Python object must be used in a 'with' clause.")
  251. self._send(function.__code__, function.__defaults__, function.__kwdefaults__, args, kwargs)
  252. # Read a single line of output back from the child. This contains if the function worked and either its return
  253. # value or a traceback. This will block indefinitely until it receives a '\n' byte.
  254. try:
  255. ok, output = loads(b64decode(self._read_handle.readline()))
  256. except (EOFError, BrokenPipeError):
  257. # Subprocess appears to have died in an unhandleable way (e.g. SIGSEV). Raise an error.
  258. raise SubprocessDiedError(
  259. f"Child process died calling {function.__name__}() with args={args} and "
  260. f"kwargs={kwargs}. Its exit code was {self._child.wait()}."
  261. ) from None
  262. # If all went well, then ``output`` is the return value.
  263. if ok:
  264. return output
  265. # Otherwise an error happened and ``output`` is a string-ified stacktrace. Raise an error appending the
  266. # stacktrace. Having the output in this order gives a nice fluent transition from parent to child in the stack
  267. # trace.
  268. raise RuntimeError(f"Child process call to {function.__name__}() failed with:\n" + output)
  269. def _send(self, *objects):
  270. for object in objects:
  271. self._write_handle.write(b64encode(dumps(object)))
  272. self._write_handle.write(b"\n")
  273. # Flushing is very important. Without it, the data is not sent but forever sits in a buffer so that the child is
  274. # forever waiting for its data and the parent in turn is forever waiting for the child's response.
  275. self._write_handle.flush()
  276. def call(function, *args, **kwargs):
  277. r"""
  278. Call a function with arguments in a separate child Python. Retrieve its return value.
  279. Args:
  280. function:
  281. The function to send and invoke.
  282. *args:
  283. **kwargs:
  284. Positional and keyword arguments to send to the function. These must be simple builtin types - not custom
  285. classes.
  286. Returns:
  287. The return value of the function. Again, these must be basic types serialisable by :func:`marshal.dumps`.
  288. Raises:
  289. RuntimeError:
  290. Any exception which happens inside an isolated process is caught and reraised in the parent process.
  291. To use, define a function which returns the information you're looking for. Any imports it requires must happen in
  292. the body of the function. For example, to safely check the output of ``matplotlib.get_data_path()`` use::
  293. # Define a function to be ran in isolation.
  294. def get_matplotlib_data_path():
  295. import matplotlib
  296. return matplotlib.get_data_path()
  297. # Call it with isolated.call().
  298. get_matplotlib_data_path = isolated.call(matplotlib_data_path)
  299. For single use functions taking no arguments like the above you can abuse the decorator syntax slightly to define
  300. and execute a function in one go. ::
  301. >>> @isolated.call
  302. ... def matplotlib_data_dir():
  303. ... import matplotlib
  304. ... return matplotlib.get_data_path()
  305. >>> matplotlib_data_dir
  306. '/home/brenainn/.pyenv/versions/3.9.6/lib/python3.9/site-packages/matplotlib/mpl-data'
  307. Functions may take positional and keyword arguments and return most generic Python data types. ::
  308. >>> def echo_parameters(*args, **kwargs):
  309. ... return args, kwargs
  310. >>> isolated.call(echo_parameters, 1, 2, 3)
  311. (1, 2, 3), {}
  312. >>> isolated.call(echo_parameters, foo=["bar"])
  313. (), {'foo': ['bar']}
  314. Notes:
  315. To make a function behave differently if it's isolated, check for the ``__isolated__`` global. ::
  316. if globals().get("__isolated__", False):
  317. # We're inside a child process.
  318. ...
  319. else:
  320. # This is the master process.
  321. ...
  322. """
  323. with Python() as isolated:
  324. return isolated.call(function, *args, **kwargs)
  325. def decorate(function):
  326. """
  327. Decorate a function so that it is always called in an isolated subprocess.
  328. Examples:
  329. To use, write a function then prepend ``@isolated.decorate``. ::
  330. @isolated.decorate
  331. def add_1(x):
  332. '''Add 1 to ``x``, displaying the current process ID.'''
  333. import os
  334. print(f"Process {os.getpid()}: Adding 1 to {x}.")
  335. return x + 1
  336. The resultant ``add_1()`` function can now be called as you would a
  337. normal function and it'll automatically use a subprocess.
  338. >>> add_1(4)
  339. Process 4920: Adding 1 to 4.
  340. 5
  341. >>> add_1(13.2)
  342. Process 4928: Adding 1 to 13.2.
  343. 14.2
  344. """
  345. @functools.wraps(function)
  346. def wrapped(*args, **kwargs):
  347. return call(function, *args, **kwargs)
  348. return wrapped