utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2005-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. Utility functions related to analyzing/bundling dependencies.
  13. """
  14. import ctypes.util
  15. import os
  16. import re
  17. import shutil
  18. from types import CodeType
  19. from PyInstaller import compat
  20. from PyInstaller import log as logging
  21. from PyInstaller.depend import bytecode
  22. from PyInstaller.depend.dylib import include_library
  23. from PyInstaller.exceptions import ExecCommandFailed
  24. logger = logging.getLogger(__name__)
  25. def scan_code_for_ctypes(co):
  26. binaries = __recursively_scan_code_objects_for_ctypes(co)
  27. # If any of the libraries has been requested with anything else than the basename, drop that entry and warn the
  28. # user - PyInstaller would need to patch the compiled pyc file to make it work correctly!
  29. binaries = set(binaries)
  30. for binary in list(binaries):
  31. # 'binary' might be in some cases None. Some Python modules (e.g., PyObjC.objc._bridgesupport) might contain
  32. # code like this:
  33. # dll = ctypes.CDLL(None)
  34. if not binary:
  35. # None values have to be removed too.
  36. binaries.remove(binary)
  37. elif binary != os.path.basename(binary):
  38. # TODO make these warnings show up somewhere.
  39. try:
  40. filename = co.co_filename
  41. except Exception:
  42. filename = 'UNKNOWN'
  43. logger.warning(
  44. "Ignoring %s imported from %s - only basenames are supported with ctypes imports!", binary, filename
  45. )
  46. binaries.remove(binary)
  47. binaries = _resolveCtypesImports(binaries)
  48. return binaries
  49. def __recursively_scan_code_objects_for_ctypes(code: CodeType):
  50. """
  51. Detects ctypes dependencies, using reasonable heuristics that should cover most common ctypes usages; returns a
  52. list containing names of binaries detected as dependencies.
  53. """
  54. from PyInstaller.depend.bytecode import any_alias, search_recursively
  55. binaries = []
  56. ctypes_dll_names = {
  57. *any_alias("ctypes.CDLL"),
  58. *any_alias("ctypes.cdll.LoadLibrary"),
  59. *any_alias("ctypes.WinDLL"),
  60. *any_alias("ctypes.windll.LoadLibrary"),
  61. *any_alias("ctypes.OleDLL"),
  62. *any_alias("ctypes.oledll.LoadLibrary"),
  63. *any_alias("ctypes.PyDLL"),
  64. *any_alias("ctypes.pydll.LoadLibrary"),
  65. }
  66. find_library_names = {
  67. *any_alias("ctypes.util.find_library"),
  68. }
  69. for calls in bytecode.recursive_function_calls(code).values():
  70. for (name, args) in calls:
  71. if not len(args) == 1 or not isinstance(args[0], str):
  72. continue
  73. if name in ctypes_dll_names:
  74. # ctypes.*DLL() or ctypes.*dll.LoadLibrary()
  75. binaries.append(*args)
  76. elif name in find_library_names:
  77. # ctypes.util.find_library() needs to be handled separately, because we need to resolve the library base
  78. # name given as the argument (without prefix and suffix, e.g. 'gs') into corresponding full name (e.g.,
  79. # 'libgs.so.9').
  80. libname = args[0]
  81. if libname:
  82. try: # this try was inserted due to the ctypes bug https://github.com/python/cpython/issues/93094
  83. libname = ctypes.util.find_library(libname)
  84. except FileNotFoundError:
  85. libname = None
  86. logger.warning(
  87. 'ctypes.util.find_library raised a FileNotFoundError. '
  88. 'Supressing and assuming no lib with the name "%s" was found.', args[0]
  89. )
  90. if libname:
  91. # On Windows, `find_library` may return a full pathname. See issue #1934.
  92. libname = os.path.basename(libname)
  93. binaries.append(libname)
  94. # The above handles any flavour of function/class call. We still need to capture the (albeit rarely used) case of
  95. # loading libraries with ctypes.cdll's getattr.
  96. for i in search_recursively(_scan_code_for_ctypes_getattr, code).values():
  97. binaries.extend(i)
  98. return binaries
  99. _ctypes_getattr_regex = bytecode.bytecode_regex(
  100. rb"""
  101. # Matches 'foo.bar' or 'foo.bar.whizz'.
  102. # Load the 'foo'.
  103. (
  104. (?:(?:""" + bytecode._OPCODES_EXTENDED_ARG + rb""").)*
  105. (?:""" + bytecode._OPCODES_FUNCTION_GLOBAL + rb""").
  106. )
  107. # Load the 'bar.whizz' (one opcode per name component, each possibly preceded by name reference extension).
  108. (
  109. (?:
  110. (?:(?:""" + bytecode._OPCODES_EXTENDED_ARG + rb""").)*
  111. (?:""" + bytecode._OPCODES_FUNCTION_LOAD + rb""").
  112. )+
  113. )
  114. """
  115. )
  116. def _scan_code_for_ctypes_getattr(code: CodeType):
  117. """
  118. Detect uses of ``ctypes.cdll.library_name``, which implies that ``library_name.dll`` should be collected.
  119. """
  120. key_names = ("cdll", "oledll", "pydll", "windll")
  121. for match in bytecode.finditer(_ctypes_getattr_regex, code.co_code):
  122. name, attrs = match.groups()
  123. name = bytecode.load(name, code)
  124. attrs = bytecode.loads(attrs, code)
  125. if attrs and attrs[-1] == "LoadLibrary":
  126. continue
  127. # Capture `from ctypes import ole; ole.dll_name`.
  128. if len(attrs) == 1:
  129. if name in key_names:
  130. yield attrs[0] + ".dll"
  131. # Capture `import ctypes; ctypes.ole.dll_name`.
  132. if len(attrs) == 2:
  133. if name == "ctypes" and attrs[0] in key_names:
  134. yield attrs[1] + ".dll"
  135. # TODO: reuse this code with modulegraph implementation.
  136. def _resolveCtypesImports(cbinaries):
  137. """
  138. Completes ctypes BINARY entries for modules with their full path.
  139. Input is a list of c-binary-names (as found by `scan_code_instruction_for_ctypes`). Output is a list of tuples
  140. ready to be appended to the ``binaries`` of a modules.
  141. This function temporarily extents PATH, LD_LIBRARY_PATH or DYLD_LIBRARY_PATH (depending on the platform) by
  142. CONF['pathex'] so shared libs will be search there, too.
  143. Example:
  144. >>> _resolveCtypesImports(['libgs.so'])
  145. [(libgs.so', ''/usr/lib/libgs.so', 'BINARY')]
  146. """
  147. from ctypes.util import find_library
  148. from PyInstaller.config import CONF
  149. if compat.is_unix:
  150. envvar = "LD_LIBRARY_PATH"
  151. elif compat.is_darwin:
  152. envvar = "DYLD_LIBRARY_PATH"
  153. else:
  154. envvar = "PATH"
  155. def _setPaths():
  156. path = os.pathsep.join(CONF['pathex'])
  157. old = compat.getenv(envvar)
  158. if old is not None:
  159. path = os.pathsep.join((path, old))
  160. compat.setenv(envvar, path)
  161. return old
  162. def _restorePaths(old):
  163. if old is None:
  164. compat.unsetenv(envvar)
  165. else:
  166. compat.setenv(envvar, old)
  167. ret = []
  168. # Try to locate the shared library on the disk. This is done by calling ctypes.util.find_library with
  169. # ImportTracker's local paths temporarily prepended to the library search paths (and restored after the call).
  170. old = _setPaths()
  171. for cbin in cbinaries:
  172. try:
  173. # There is an issue with find_library() where it can run into errors trying to locate the library. See
  174. # #5734.
  175. cpath = find_library(os.path.splitext(cbin)[0])
  176. except FileNotFoundError:
  177. # In these cases, find_library() should return None.
  178. cpath = None
  179. if compat.is_unix or compat.is_cygwin:
  180. # CAVEAT: find_library() is not the correct function. ctype's documentation says that it is meant to resolve
  181. # only the filename (as a *compiler* does) not the full path. Anyway, it works well enough on Windows and
  182. # macOS. On Linux, we need to implement more code to find out the full path.
  183. if cpath is None:
  184. cpath = cbin
  185. # "man ld.so" says that we should first search LD_LIBRARY_PATH and then the ldcache.
  186. for d in compat.getenv(envvar, '').split(os.pathsep):
  187. if os.path.isfile(os.path.join(d, cpath)):
  188. cpath = os.path.join(d, cpath)
  189. break
  190. else:
  191. if LDCONFIG_CACHE is None:
  192. load_ldconfig_cache()
  193. if cpath in LDCONFIG_CACHE:
  194. cpath = LDCONFIG_CACHE[cpath]
  195. assert os.path.isfile(cpath)
  196. else:
  197. cpath = None
  198. if cpath is None:
  199. # Skip warning message if cbin (basename of library) is ignored. This prevents messages like:
  200. # 'W: library kernel32.dll required via ctypes not found'
  201. if not include_library(cbin):
  202. continue
  203. # On non-Windows, automatically ignore all ctypes-based referenes to DLL files. This complements the above
  204. # check, which might not match potential case variations (e.g., `KERNEL32.dll`, instead of `kernel32.dll`)
  205. # due to case-sensitivity of the matching that is in effect on non-Windows platforms.
  206. if (not compat.is_win and not compat.is_cygwin) and cbin.lower().endswith('.dll'):
  207. continue
  208. logger.warning("Library %s required via ctypes not found", cbin)
  209. else:
  210. if not include_library(cpath):
  211. continue
  212. ret.append((cbin, cpath, "BINARY"))
  213. _restorePaths(old)
  214. return ret
  215. LDCONFIG_CACHE = None # cache the output of `/sbin/ldconfig -p`
  216. def load_ldconfig_cache():
  217. """
  218. Create a cache of the `ldconfig`-output to call it only once.
  219. It contains thousands of libraries and running it on every dylib is expensive.
  220. """
  221. global LDCONFIG_CACHE
  222. if LDCONFIG_CACHE is not None:
  223. return
  224. if compat.is_cygwin:
  225. # Not available under Cygwin; but we might be re-using general POSIX codepaths, and end up here. So exit early.
  226. LDCONFIG_CACHE = {}
  227. return
  228. if compat.is_musl:
  229. # Musl deliberately doesn't use ldconfig. The ldconfig executable either doesn't exist or it's a functionless
  230. # executable which, on calling with any arguments, simply tells you that those arguments are invalid.
  231. LDCONFIG_CACHE = {}
  232. return
  233. ldconfig = shutil.which('ldconfig')
  234. if ldconfig is None:
  235. # If `ldconfig` is not found in $PATH, search for it in some fixed directories. Simply use a second call instead
  236. # of fiddling around with checks for empty env-vars and string-concat.
  237. ldconfig = shutil.which('ldconfig', path='/usr/sbin:/sbin:/usr/bin:/bin')
  238. # If we still could not find the 'ldconfig' command...
  239. if ldconfig is None:
  240. LDCONFIG_CACHE = {}
  241. return
  242. if compat.is_freebsd or compat.is_openbsd:
  243. # This has a quite different format than other Unixes:
  244. # [vagrant@freebsd-10 ~]$ ldconfig -r
  245. # /var/run/ld-elf.so.hints:
  246. # search directories: /lib:/usr/lib:/usr/lib/compat:...
  247. # 0:-lgeom.5 => /lib/libgeom.so.5
  248. # 184:-lpython2.7.1 => /usr/local/lib/libpython2.7.so.1
  249. ldconfig_arg = '-r'
  250. splitlines_count = 2
  251. pattern = re.compile(r'^\s+\d+:-l(\S+)(\s.*)? => (\S+)')
  252. else:
  253. # Skip first line of the library list because it is just an informative line and might contain localized
  254. # characters. Example of first line with locale set to cs_CZ.UTF-8:
  255. #$ /sbin/ldconfig -p
  256. #V keši „/etc/ld.so.cache“ nalezeno knihoven: 2799
  257. # libzvbi.so.0 (libc6,x86-64) => /lib64/libzvbi.so.0
  258. # libzvbi-chains.so.0 (libc6,x86-64) => /lib64/libzvbi-chains.so.0
  259. ldconfig_arg = '-p'
  260. splitlines_count = 1
  261. pattern = re.compile(r'^\s+(\S+)(\s.*)? => (\S+)')
  262. try:
  263. text = compat.exec_command(ldconfig, ldconfig_arg)
  264. except ExecCommandFailed:
  265. logger.warning("Failed to execute ldconfig. Disabling LD cache.")
  266. LDCONFIG_CACHE = {}
  267. return
  268. text = text.strip().splitlines()[splitlines_count:]
  269. LDCONFIG_CACHE = {}
  270. for line in text:
  271. # :fixme: this assumes library names do not contain whitespace
  272. m = pattern.match(line)
  273. # Sanitize away any abnormal lines of output.
  274. if m is None:
  275. # Warn about it then skip the rest of this iteration.
  276. if re.search("Cache generated by:", line):
  277. # See #5540. This particular line is harmless.
  278. pass
  279. else:
  280. logger.warning("Unrecognised line of output %r from ldconfig", line)
  281. continue
  282. path = m.groups()[-1]
  283. if compat.is_freebsd or compat.is_openbsd:
  284. # Insert `.so` at the end of the lib's basename. soname and filename may have (different) trailing versions.
  285. # We assume the `.so` in the filename to mark the end of the lib's basename.
  286. bname = os.path.basename(path).split('.so', 1)[0]
  287. name = 'lib' + m.group(1)
  288. assert name.startswith(bname)
  289. name = bname + '.so' + name[len(bname):]
  290. else:
  291. name = m.group(1)
  292. # ldconfig may know about several versions of the same lib, e.g., different arch, different libc, etc.
  293. # Use the first entry.
  294. if name not in LDCONFIG_CACHE:
  295. LDCONFIG_CACHE[name] = path