ยปCore Development>Code coverage>Lib/ctypes/util.py

Python code coverage for Lib/ctypes/util.py

#countcontent
1n/aimport os
2n/aimport shutil
3n/aimport subprocess
4n/aimport sys
5n/a
6n/a# find_library(name) returns the pathname of a library, or None.
7n/aif os.name == "nt":
8n/a
9n/a def _get_build_version():
10n/a """Return the version of MSVC that was used to build Python.
11n/a
12n/a For Python 2.3 and up, the version number is included in
13n/a sys.version. For earlier versions, assume the compiler is MSVC 6.
14n/a """
15n/a # This function was copied from Lib/distutils/msvccompiler.py
16n/a prefix = "MSC v."
17n/a i = sys.version.find(prefix)
18n/a if i == -1:
19n/a return 6
20n/a i = i + len(prefix)
21n/a s, rest = sys.version[i:].split(" ", 1)
22n/a majorVersion = int(s[:-2]) - 6
23n/a if majorVersion >= 13:
24n/a majorVersion += 1
25n/a minorVersion = int(s[2:3]) / 10.0
26n/a # I don't think paths are affected by minor version in version 6
27n/a if majorVersion == 6:
28n/a minorVersion = 0
29n/a if majorVersion >= 6:
30n/a return majorVersion + minorVersion
31n/a # else we don't know what version of the compiler this is
32n/a return None
33n/a
34n/a def find_msvcrt():
35n/a """Return the name of the VC runtime dll"""
36n/a version = _get_build_version()
37n/a if version is None:
38n/a # better be safe than sorry
39n/a return None
40n/a if version <= 6:
41n/a clibname = 'msvcrt'
42n/a elif version <= 13:
43n/a clibname = 'msvcr%d' % (version * 10)
44n/a else:
45n/a # CRT is no longer directly loadable. See issue23606 for the
46n/a # discussion about alternative approaches.
47n/a return None
48n/a
49n/a # If python was built with in debug mode
50n/a import importlib.machinery
51n/a if '_d.pyd' in importlib.machinery.EXTENSION_SUFFIXES:
52n/a clibname += 'd'
53n/a return clibname+'.dll'
54n/a
55n/a def find_library(name):
56n/a if name in ('c', 'm'):
57n/a return find_msvcrt()
58n/a # See MSDN for the REAL search order.
59n/a for directory in os.environ['PATH'].split(os.pathsep):
60n/a fname = os.path.join(directory, name)
61n/a if os.path.isfile(fname):
62n/a return fname
63n/a if fname.lower().endswith(".dll"):
64n/a continue
65n/a fname = fname + ".dll"
66n/a if os.path.isfile(fname):
67n/a return fname
68n/a return None
69n/a
70n/aif os.name == "posix" and sys.platform == "darwin":
71n/a from ctypes.macholib.dyld import dyld_find as _dyld_find
72n/a def find_library(name):
73n/a possible = ['lib%s.dylib' % name,
74n/a '%s.dylib' % name,
75n/a '%s.framework/%s' % (name, name)]
76n/a for name in possible:
77n/a try:
78n/a return _dyld_find(name)
79n/a except ValueError:
80n/a continue
81n/a return None
82n/a
83n/aelif os.name == "posix":
84n/a # Andreas Degert's find functions, using gcc, /sbin/ldconfig, objdump
85n/a import re, tempfile
86n/a
87n/a def _findLib_gcc(name):
88n/a # Run GCC's linker with the -t (aka --trace) option and examine the
89n/a # library name it prints out. The GCC command will fail because we
90n/a # haven't supplied a proper program with main(), but that does not
91n/a # matter.
92n/a expr = os.fsencode(r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name))
93n/a
94n/a c_compiler = shutil.which('gcc')
95n/a if not c_compiler:
96n/a c_compiler = shutil.which('cc')
97n/a if not c_compiler:
98n/a # No C compiler available, give up
99n/a return None
100n/a
101n/a temp = tempfile.NamedTemporaryFile()
102n/a try:
103n/a args = [c_compiler, '-Wl,-t', '-o', temp.name, '-l' + name]
104n/a
105n/a env = dict(os.environ)
106n/a env['LC_ALL'] = 'C'
107n/a env['LANG'] = 'C'
108n/a try:
109n/a proc = subprocess.Popen(args,
110n/a stdout=subprocess.PIPE,
111n/a stderr=subprocess.STDOUT,
112n/a env=env)
113n/a except OSError: # E.g. bad executable
114n/a return None
115n/a with proc:
116n/a trace = proc.stdout.read()
117n/a finally:
118n/a try:
119n/a temp.close()
120n/a except FileNotFoundError:
121n/a # Raised if the file was already removed, which is the normal
122n/a # behaviour of GCC if linking fails
123n/a pass
124n/a res = re.search(expr, trace)
125n/a if not res:
126n/a return None
127n/a return os.fsdecode(res.group(0))
128n/a
129n/a
130n/a if sys.platform == "sunos5":
131n/a # use /usr/ccs/bin/dump on solaris
132n/a def _get_soname(f):
133n/a if not f:
134n/a return None
135n/a
136n/a try:
137n/a proc = subprocess.Popen(("/usr/ccs/bin/dump", "-Lpv", f),
138n/a stdout=subprocess.PIPE,
139n/a stderr=subprocess.DEVNULL)
140n/a except OSError: # E.g. command not found
141n/a return None
142n/a with proc:
143n/a data = proc.stdout.read()
144n/a res = re.search(br'\[.*\]\sSONAME\s+([^\s]+)', data)
145n/a if not res:
146n/a return None
147n/a return os.fsdecode(res.group(1))
148n/a else:
149n/a def _get_soname(f):
150n/a # assuming GNU binutils / ELF
151n/a if not f:
152n/a return None
153n/a objdump = shutil.which('objdump')
154n/a if not objdump:
155n/a # objdump is not available, give up
156n/a return None
157n/a
158n/a try:
159n/a proc = subprocess.Popen((objdump, '-p', '-j', '.dynamic', f),
160n/a stdout=subprocess.PIPE,
161n/a stderr=subprocess.DEVNULL)
162n/a except OSError: # E.g. bad executable
163n/a return None
164n/a with proc:
165n/a dump = proc.stdout.read()
166n/a res = re.search(br'\sSONAME\s+([^\s]+)', dump)
167n/a if not res:
168n/a return None
169n/a return os.fsdecode(res.group(1))
170n/a
171n/a if sys.platform.startswith(("freebsd", "openbsd", "dragonfly")):
172n/a
173n/a def _num_version(libname):
174n/a # "libxyz.so.MAJOR.MINOR" => [ MAJOR, MINOR ]
175n/a parts = libname.split(b".")
176n/a nums = []
177n/a try:
178n/a while parts:
179n/a nums.insert(0, int(parts.pop()))
180n/a except ValueError:
181n/a pass
182n/a return nums or [sys.maxsize]
183n/a
184n/a def find_library(name):
185n/a ename = re.escape(name)
186n/a expr = r':-l%s\.\S+ => \S*/(lib%s\.\S+)' % (ename, ename)
187n/a expr = os.fsencode(expr)
188n/a
189n/a try:
190n/a proc = subprocess.Popen(('/sbin/ldconfig', '-r'),
191n/a stdout=subprocess.PIPE,
192n/a stderr=subprocess.DEVNULL)
193n/a except OSError: # E.g. command not found
194n/a data = b''
195n/a else:
196n/a with proc:
197n/a data = proc.stdout.read()
198n/a
199n/a res = re.findall(expr, data)
200n/a if not res:
201n/a return _get_soname(_findLib_gcc(name))
202n/a res.sort(key=_num_version)
203n/a return os.fsdecode(res[-1])
204n/a
205n/a elif sys.platform == "sunos5":
206n/a
207n/a def _findLib_crle(name, is64):
208n/a if not os.path.exists('/usr/bin/crle'):
209n/a return None
210n/a
211n/a env = dict(os.environ)
212n/a env['LC_ALL'] = 'C'
213n/a
214n/a if is64:
215n/a args = ('/usr/bin/crle', '-64')
216n/a else:
217n/a args = ('/usr/bin/crle',)
218n/a
219n/a paths = None
220n/a try:
221n/a proc = subprocess.Popen(args,
222n/a stdout=subprocess.PIPE,
223n/a stderr=subprocess.DEVNULL,
224n/a env=env)
225n/a except OSError: # E.g. bad executable
226n/a return None
227n/a with proc:
228n/a for line in proc.stdout:
229n/a line = line.strip()
230n/a if line.startswith(b'Default Library Path (ELF):'):
231n/a paths = os.fsdecode(line).split()[4]
232n/a
233n/a if not paths:
234n/a return None
235n/a
236n/a for dir in paths.split(":"):
237n/a libfile = os.path.join(dir, "lib%s.so" % name)
238n/a if os.path.exists(libfile):
239n/a return libfile
240n/a
241n/a return None
242n/a
243n/a def find_library(name, is64 = False):
244n/a return _get_soname(_findLib_crle(name, is64) or _findLib_gcc(name))
245n/a
246n/a else:
247n/a
248n/a def _findSoname_ldconfig(name):
249n/a import struct
250n/a if struct.calcsize('l') == 4:
251n/a machine = os.uname().machine + '-32'
252n/a else:
253n/a machine = os.uname().machine + '-64'
254n/a mach_map = {
255n/a 'x86_64-64': 'libc6,x86-64',
256n/a 'ppc64-64': 'libc6,64bit',
257n/a 'sparc64-64': 'libc6,64bit',
258n/a 's390x-64': 'libc6,64bit',
259n/a 'ia64-64': 'libc6,IA-64',
260n/a }
261n/a abi_type = mach_map.get(machine, 'libc6')
262n/a
263n/a # XXX assuming GLIBC's ldconfig (with option -p)
264n/a regex = r'\s+(lib%s\.[^\s]+)\s+\(%s'
265n/a regex = os.fsencode(regex % (re.escape(name), abi_type))
266n/a try:
267n/a with subprocess.Popen(['/sbin/ldconfig', '-p'],
268n/a stdin=subprocess.DEVNULL,
269n/a stderr=subprocess.DEVNULL,
270n/a stdout=subprocess.PIPE,
271n/a env={'LC_ALL': 'C', 'LANG': 'C'}) as p:
272n/a res = re.search(regex, p.stdout.read())
273n/a if res:
274n/a return os.fsdecode(res.group(1))
275n/a except OSError:
276n/a pass
277n/a
278n/a def _findLib_ld(name):
279n/a # See issue #9998 for why this is needed
280n/a expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name)
281n/a cmd = ['ld', '-t']
282n/a libpath = os.environ.get('LD_LIBRARY_PATH')
283n/a if libpath:
284n/a for d in libpath.split(':'):
285n/a cmd.extend(['-L', d])
286n/a cmd.extend(['-o', os.devnull, '-l%s' % name])
287n/a result = None
288n/a try:
289n/a p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
290n/a stderr=subprocess.PIPE,
291n/a universal_newlines=True)
292n/a out, _ = p.communicate()
293n/a res = re.search(expr, os.fsdecode(out))
294n/a if res:
295n/a result = res.group(0)
296n/a except Exception as e:
297n/a pass # result will be None
298n/a return result
299n/a
300n/a def find_library(name):
301n/a # See issue #9998
302n/a return _findSoname_ldconfig(name) or \
303n/a _get_soname(_findLib_gcc(name) or _findLib_ld(name))
304n/a
305n/a################################################################
306n/a# test code
307n/a
308n/adef test():
309n/a from ctypes import cdll
310n/a if os.name == "nt":
311n/a print(cdll.msvcrt)
312n/a print(cdll.load("msvcrt"))
313n/a print(find_library("msvcrt"))
314n/a
315n/a if os.name == "posix":
316n/a # find and load_version
317n/a print(find_library("m"))
318n/a print(find_library("c"))
319n/a print(find_library("bz2"))
320n/a
321n/a # load
322n/a if sys.platform == "darwin":
323n/a print(cdll.LoadLibrary("libm.dylib"))
324n/a print(cdll.LoadLibrary("libcrypto.dylib"))
325n/a print(cdll.LoadLibrary("libSystem.dylib"))
326n/a print(cdll.LoadLibrary("System.framework/System"))
327n/a else:
328n/a print(cdll.LoadLibrary("libm.so"))
329n/a print(cdll.LoadLibrary("libcrypt.so"))
330n/a print(find_library("crypt"))
331n/a
332n/aif __name__ == "__main__":
333n/a test()