bytecode.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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) with exception for distributing the bootloader.
  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)
  10. #-----------------------------------------------------------------------------
  11. """
  12. Tools for searching bytecode for key statements that indicate the need for additional resources, such as data files
  13. and package metadata.
  14. By *bytecode* I mean the ``code`` object given by ``compile()``, accessible from the ``__code__`` attribute of any
  15. non-builtin function or, in PyInstallerLand, the ``PyiModuleGraph.node("some.module").code`` attribute. The best
  16. guide for bytecode format I have found is the disassembler reference: https://docs.python.org/3/library/dis.html
  17. This parser implementation aims to combine the flexibility and speed of regex with the clarity of the output of
  18. ``dis.dis(code)``. It has not achieved the 2nd, but C'est la vie...
  19. The biggest clarity killer here is the ``EXTENDED_ARG`` opcode which can appear almost anywhere and therefore needs
  20. to be tiptoed around at every step. If this code needs to expand significantly, I would recommend an upgrade to a
  21. regex-based grammar parsing library such as Reparse. This way, little steps like unpacking ``EXTENDED_ARGS`` can be
  22. defined once then simply referenced forming a nice hierarchy rather than copied everywhere its needed.
  23. """
  24. import dis
  25. import re
  26. from types import CodeType
  27. from typing import Pattern
  28. from PyInstaller import compat
  29. # opcode name -> opcode map
  30. # Python 3.11 introduced specialized opcodes that are not covered by opcode.opmap (and equivalent dis.opmap), but dis
  31. # has a private map of all opcodes called _all_opmap. So use the latter, if available.
  32. opmap = getattr(dis, '_all_opmap', dis.opmap)
  33. def _instruction_to_regex(x: str):
  34. """
  35. Get a regex-escaped opcode byte from its human readable name.
  36. """
  37. return re.escape(bytes([opmap[x]]))
  38. def bytecode_regex(pattern: bytes, flags=re.VERBOSE | re.DOTALL):
  39. """
  40. A regex-powered Python bytecode matcher.
  41. ``bytecode_regex`` provides a very thin wrapper around :func:`re.compile`.
  42. * Any opcode names wrapped in backticks are substituted for their corresponding opcode bytes.
  43. * Patterns are compiled in VERBOSE mode by default so that whitespace and comments may be used.
  44. This aims to mirror the output of :func:`dis.dis`, which is far more readable than looking at raw byte strings.
  45. """
  46. assert isinstance(pattern, bytes)
  47. # Replace anything wrapped in backticks with regex-escaped opcodes.
  48. pattern = re.sub(
  49. rb"`(\w+)`",
  50. lambda m: _instruction_to_regex(m[1].decode()),
  51. pattern,
  52. )
  53. return re.compile(pattern, flags=flags)
  54. def finditer(pattern: Pattern, string: bytes):
  55. """
  56. Call ``pattern.finditer(string)``, but remove any matches beginning on an odd byte (i.e., matches where
  57. match.start() is not a multiple of 2).
  58. This should be used to avoid false positive matches where a bytecode pair's argument is mistaken for an opcode.
  59. """
  60. assert isinstance(string, bytes)
  61. string = _cleanup_bytecode_string(string)
  62. matches = pattern.finditer(string)
  63. while True:
  64. for match in matches:
  65. if match.start() % 2 == 0:
  66. # All is good. This match starts on an OPCODE.
  67. yield match
  68. else:
  69. # This match has started on an odd byte, meaning that it is a false positive and should be skipped.
  70. # There is a very slim chance that a genuine match overlaps this one and, because re.finditer() does not
  71. # allow overlapping matches, it would be lost. To avoid that, restart the regex scan, starting at the
  72. # next even byte.
  73. matches = pattern.finditer(string, match.start() + 1)
  74. break
  75. else:
  76. break
  77. # Opcodes involved in function calls with constant arguments. The differences between python versions are handled by
  78. # variables below, which are then used to construct the _call_function_bytecode regex.
  79. # NOTE1: the _OPCODES_* entries are typically used in (non-capturing) groups that match the opcode plus an arbitrary
  80. # argument. But because the entries themselves may contain more than on opcode (with OR operator between them), they
  81. # themselves need to be enclosed in another (non-capturing) group. E.g., "(?:(?:_OPCODES_FUNCTION_GLOBAL).)".
  82. # NOTE2: _OPCODES_EXTENDED_ARG2 is an exception, as it is used as a list of opcodes to exclude, i.e.,
  83. # "[^_OPCODES_EXTENDED_ARG2]". Therefore, multiple opcodes are not separated by the OR operator.
  84. if not compat.is_py311:
  85. # Python 3.7 introduced two new function-related opcodes, LOAD_METHOD and CALL_METHOD
  86. _OPCODES_EXTENDED_ARG = rb"`EXTENDED_ARG`"
  87. _OPCODES_EXTENDED_ARG2 = _OPCODES_EXTENDED_ARG
  88. _OPCODES_FUNCTION_GLOBAL = rb"`LOAD_NAME`|`LOAD_GLOBAL`|`LOAD_FAST`"
  89. _OPCODES_FUNCTION_LOAD = rb"`LOAD_ATTR`|`LOAD_METHOD`"
  90. _OPCODES_FUNCTION_ARGS = rb"`LOAD_CONST`"
  91. _OPCODES_FUNCTION_CALL = rb"`CALL_FUNCTION`|`CALL_METHOD`|`CALL_FUNCTION_EX`"
  92. def _cleanup_bytecode_string(bytecode):
  93. return bytecode # Nothing to do here
  94. elif not compat.is_py312:
  95. # Python 3.11 removed CALL_FUNCTION and CALL_METHOD, and replaced them with PRECALL + CALL instruction sequence.
  96. # As both PRECALL and CALL have the same parameter (the argument count), we need to match only up to the PRECALL.
  97. # The CALL_FUNCTION_EX is still present.
  98. # From Python 3.11b1 on, there is an EXTENDED_ARG_QUICK specialization opcode present.
  99. _OPCODES_EXTENDED_ARG = rb"`EXTENDED_ARG`|`EXTENDED_ARG_QUICK`"
  100. _OPCODES_EXTENDED_ARG2 = rb"`EXTENDED_ARG``EXTENDED_ARG_QUICK`" # Special case; see note above the if/else block!
  101. _OPCODES_FUNCTION_GLOBAL = rb"`LOAD_NAME`|`LOAD_GLOBAL`|`LOAD_FAST`"
  102. _OPCODES_FUNCTION_LOAD = rb"`LOAD_ATTR`|`LOAD_METHOD`"
  103. _OPCODES_FUNCTION_ARGS = rb"`LOAD_CONST`"
  104. _OPCODES_FUNCTION_CALL = rb"`PRECALL`|`CALL_FUNCTION_EX`"
  105. # Starting with python 3.11, the bytecode is peppered with CACHE instructions (which dis module conveniently hides
  106. # unless show_caches=True is used). Dealing with these CACHE instructions in regex rules is going to render them
  107. # unreadable, so instead we pre-process the bytecode and filter the offending opcodes out.
  108. _cache_instruction_filter = bytecode_regex(rb"(`CACHE`.)|(..)")
  109. def _cleanup_bytecode_string(bytecode):
  110. return _cache_instruction_filter.sub(rb"\2", bytecode)
  111. else:
  112. # Python 3.12 merged EXTENDED_ARG_QUICK back in to EXTENDED_ARG, and LOAD_METHOD in to LOAD_ATTR
  113. # PRECALL is no longer a valid key
  114. _OPCODES_EXTENDED_ARG = rb"`EXTENDED_ARG`"
  115. _OPCODES_EXTENDED_ARG2 = _OPCODES_EXTENDED_ARG
  116. if compat.is_py314:
  117. # Python 3.14.0a7 added LOAD_FAST_BORROW.
  118. _OPCODES_FUNCTION_GLOBAL = rb"`LOAD_NAME`|`LOAD_GLOBAL`|`LOAD_FAST`|`LOAD_FAST_BORROW`"
  119. else:
  120. _OPCODES_FUNCTION_GLOBAL = rb"`LOAD_NAME`|`LOAD_GLOBAL`|`LOAD_FAST`"
  121. _OPCODES_FUNCTION_LOAD = rb"`LOAD_ATTR`"
  122. if compat.is_py314:
  123. # Python 3.14.0a2 split LOAD_CONST into LOAD_CONST, LOAD_CONST_IMMORTAL, and LOAD_SMALL_INT.
  124. # https://github.com/python/cpython/commit/faa3272fb8d63d481a136cc0467a0cba6ed7b264
  125. #
  126. # The LOAD_CONST_IMMORTAL was removed in Python 3.15.0a1
  127. # https://github.com/python/cpython/commit/6dcb0fdfe0a2de083f0f1f9a568dd0a19541b863
  128. #
  129. # LOAD_COMMON_CONSTANT was added in Python 3.14.0a1...
  130. # https://github.com/python/cpython/commit/98e855fcc1f1d490c803565e84cb611b3f057e45
  131. # and was extended with additional common constants in 3.15.0b1
  132. # https://github.com/python/cpython/commit/7c9ad27dd1fc9e05149b471b055f18ad64cd05f3
  133. if not compat.is_py315:
  134. _OPCODES_FUNCTION_ARGS = rb"`LOAD_CONST`|`LOAD_SMALL_INT`|`LOAD_COMMON_CONSTANT`|`LOAD_CONST_IMMORTAL`"
  135. else:
  136. _OPCODES_FUNCTION_ARGS = rb"`LOAD_CONST`|`LOAD_SMALL_INT`|`LOAD_COMMON_CONSTANT`"
  137. else:
  138. _OPCODES_FUNCTION_ARGS = rb"`LOAD_CONST`"
  139. _OPCODES_FUNCTION_CALL = rb"`CALL`|`CALL_FUNCTION_EX`"
  140. # In Python 3.13, PUSH_NULL opcode is emitted after the LOAD_NAME (and after LOAD_ATTR opcode(s), if applicable).
  141. # In python 3.11 and 3.12, it was emitted before the LOAD_NAME, and thus fell outside of our regex matching; now,
  142. # we have to deal with it. But, instead of trying to add it to matching rules and adjusting the post-processing
  143. # to deal with it, we opt to filter them out (at the same time as we filter out CACHE opcodes), and leave the rest
  144. # of processing untouched.
  145. if compat.is_py313:
  146. _cache_instruction_filter = bytecode_regex(rb"(`CACHE`.)|(`PUSH_NULL`.)|(..)")
  147. def _cleanup_bytecode_string(bytecode):
  148. return _cache_instruction_filter.sub(rb"\3", bytecode)
  149. else:
  150. _cache_instruction_filter = bytecode_regex(rb"(`CACHE`.)|(..)")
  151. def _cleanup_bytecode_string(bytecode):
  152. return _cache_instruction_filter.sub(rb"\2", bytecode)
  153. # language=PythonVerboseRegExp
  154. _call_function_bytecode = bytecode_regex(
  155. rb"""
  156. # Matches `global_function('some', 'constant', 'arguments')`.
  157. # Load the global function. In code with >256 of names, this may require extended name references.
  158. (
  159. (?:(?:""" + _OPCODES_EXTENDED_ARG + rb""").)*
  160. (?:(?:""" + _OPCODES_FUNCTION_GLOBAL + rb""").)
  161. )
  162. # For foo.bar.whizz(), the above is the 'foo', below is the 'bar.whizz' (one opcode per name component, each
  163. # possibly preceded by name reference extension).
  164. (
  165. (?:
  166. (?:(?:""" + _OPCODES_EXTENDED_ARG + rb""").)*
  167. (?:""" + _OPCODES_FUNCTION_LOAD + rb""").
  168. )*
  169. )
  170. # Load however many arguments it takes. These (for now) must all be constants.
  171. # Again, code with >256 constants may need extended enumeration.
  172. (
  173. (?:
  174. (?:(?:""" + _OPCODES_EXTENDED_ARG + rb""").)*
  175. (?:""" + _OPCODES_FUNCTION_ARGS + rb""").
  176. )*
  177. )
  178. # Call the function. If opcode is CALL_FUNCTION_EX, the parameter are flags. For other opcodes, the parameter
  179. # is the argument count (which may be > 256).
  180. (
  181. (?:(?:""" + _OPCODES_EXTENDED_ARG + rb""").)*
  182. (?:""" + _OPCODES_FUNCTION_CALL + rb""").
  183. )
  184. """
  185. )
  186. # language=PythonVerboseRegExp
  187. _extended_arg_bytecode = bytecode_regex(
  188. rb"""(
  189. # Arbitrary number of EXTENDED_ARG pairs.
  190. (?:(?:""" + _OPCODES_EXTENDED_ARG + rb""").)*
  191. # Followed by some other instruction (usually a LOAD).
  192. [^""" + _OPCODES_EXTENDED_ARG2 + rb"""].
  193. )"""
  194. )
  195. def extended_arguments(extended_args: bytes):
  196. """
  197. Unpack the (extended) integer used to reference names or constants.
  198. The input should be a bytecode snippet of the following form::
  199. EXTENDED_ARG ? # Repeated 0-4 times.
  200. LOAD_xxx ? # Any of LOAD_NAME/LOAD_CONST/LOAD_METHOD/...
  201. Each ? byte combined together gives the number we want.
  202. """
  203. return int.from_bytes(extended_args[1::2], "big")
  204. def load(raw: bytes, code: CodeType) -> str:
  205. """
  206. Parse an (extended) LOAD_xxx instruction.
  207. """
  208. # Get the enumeration.
  209. index = extended_arguments(raw)
  210. # Work out what that enumeration was for (constant/local var/global var).
  211. # If the last instruction byte is a LOAD_FAST:
  212. if raw[-2] == opmap["LOAD_FAST"]:
  213. # Then this is a local variable.
  214. return code.co_varnames[index]
  215. # Or if it is a LOAD_CONST:
  216. if raw[-2] == opmap["LOAD_CONST"]:
  217. # Then this is a literal.
  218. return code.co_consts[index]
  219. # Otherwise, it is a global name.
  220. if compat.is_py311 and raw[-2] == opmap["LOAD_GLOBAL"]:
  221. # In python 3.11, namei>>1 is pushed on stack...
  222. return code.co_names[index >> 1]
  223. if compat.is_py312 and raw[-2] == opmap["LOAD_ATTR"]:
  224. # In python 3.12, namei>>1 is pushed on stack...
  225. return code.co_names[index >> 1]
  226. if compat.is_py314 and raw[-2] == opmap["LOAD_SMALL_INT"]:
  227. # python 3.14 introduced LOAD_SMALL_INT, which pushes its argument (int value < 256) on the stack
  228. return index
  229. if compat.is_py314 and not compat.is_py315 and raw[-2] == opmap["LOAD_CONST_IMMORTAL"]:
  230. # python 3.14 introduced LOAD_CONST_IMMORTAL, which pushes co_consts[consti] on the stack. This is intended to
  231. # be a variant of LOAD_CONST for constants that are known to be immortal. This specialized opcode was removed
  232. # in python 3.15.
  233. return code.co_consts[index]
  234. if compat.is_py314 and raw[-2] == opmap["LOAD_FAST_BORROW"]:
  235. # python 3.14 introduced LOAD_FAST_BORROW, which pushes a borrowed reference to the local co_varnames[var_num]
  236. # onto the stack.
  237. return code.co_varnames[index]
  238. if compat.is_py314 and raw[-2] == opmap["LOAD_COMMON_CONSTANT"]:
  239. # python 3.14 introduced LOAD_COMMON_CONSTANT, which pushes an identifier of a pre-defined constant onto the
  240. # stack. Python 3.15 added more such constants - including None, True, False, and -1.
  241. return dis._common_constants[index]
  242. return code.co_names[index]
  243. def loads(raw: bytes, code: CodeType) -> list:
  244. """
  245. Parse multiple consecutive LOAD_xxx instructions. Or load() in a for loop.
  246. May be used to unpack a function's parameters or nested attributes ``(foo.bar.pop.whack)``.
  247. """
  248. return [load(i, code) for i in _extended_arg_bytecode.findall(raw)]
  249. def function_calls(code: CodeType) -> list:
  250. """
  251. Scan a code object for all function calls on constant arguments.
  252. """
  253. match: re.Match
  254. out = []
  255. for match in finditer(_call_function_bytecode, code.co_code):
  256. function_root, methods, args, function_call = match.groups()
  257. # For foo():
  258. # `function_root` contains 'foo' and `methods` is empty.
  259. # For foo.bar.whizz():
  260. # `function_root` contains 'foo' and `methods` contains the rest.
  261. function_root = load(function_root, code)
  262. methods = loads(methods, code)
  263. function = ".".join([function_root] + methods)
  264. args = loads(args, code)
  265. if function_call[0] == opmap['CALL_FUNCTION_EX']:
  266. flags = extended_arguments(function_call)
  267. if flags != 0:
  268. # Keyword arguments present. Unhandled at the moment.
  269. continue
  270. # In calls with const arguments, args contains a single
  271. # tuple with all values.
  272. if len(args) != 1 or not isinstance(args[0], tuple):
  273. continue
  274. args = list(args[0])
  275. else:
  276. arg_count = extended_arguments(function_call)
  277. if arg_count != len(args):
  278. # This happens if there are variable or keyword arguments. Bail out in either case.
  279. continue
  280. out.append((function, args))
  281. return out
  282. def search_recursively(search: callable, code: CodeType, _memo=None) -> dict:
  283. """
  284. Apply a search function to a code object, recursing into child code objects (function definitions).
  285. """
  286. if _memo is None:
  287. _memo = {}
  288. if code not in _memo:
  289. _memo[code] = search(code)
  290. for const in code.co_consts:
  291. if isinstance(const, CodeType):
  292. search_recursively(search, const, _memo)
  293. return _memo
  294. def recursive_function_calls(code: CodeType) -> dict:
  295. """
  296. Scan a code object for function calls on constant arguments, recursing into function definitions and bodies of
  297. comprehension loops.
  298. """
  299. return search_recursively(function_calls, code)
  300. def any_alias(full_name: str):
  301. """List possible aliases of a fully qualified Python name.
  302. >>> list(any_alias("foo.bar.wizz"))
  303. ['foo.bar.wizz', 'bar.wizz', 'wizz']
  304. This crudely allows us to capture uses of wizz() under any of
  305. ::
  306. import foo
  307. foo.bar.wizz()
  308. ::
  309. from foo import bar
  310. bar.wizz()
  311. ::
  312. from foo.bar import wizz
  313. wizz()
  314. However, it will fail for any form of aliases and quite likely find false matches.
  315. """
  316. parts = full_name.split('.')
  317. while parts:
  318. yield ".".join(parts)
  319. parts = parts[1:]