Debian Codegraph @

lib-python/3/ctypes/test/test_loading.py

raw symbols SCIP
1 from ctypes import *
2 import os
3 import shutil
4 import subprocess
5 import sys
6 import unittest
7 import test.support
8 from test.support import import_helper
9 from test.support import os_helper
10 from ctypes.util import find_library
11
12 libc_name = None
13
14 def setUpModule():
15 global libc_name
16 if os.name == "nt":
17 libc_name = find_library("c")
18 elif sys.platform == "cygwin":
19 libc_name = "cygwin1.dll"
20 else:
21 libc_name = find_library("c")
22
23 if test.support.verbose:
24 print("libc_name is", libc_name)
25
26 class LoaderTest(unittest.TestCase):
27
28 unknowndll = "xxrandomnamexx"
29
30 def test_load(self):
31 if libc_name is None:
32 self.skipTest('could not find libc')
33 CDLL(libc_name)
34 CDLL(os.path.basename(libc_name))
35 self.assertRaises(OSError, CDLL, self.unknowndll)
36
37 def test_load_version(self):
38 if libc_name is None:
39 self.skipTest('could not find libc')
40 if os.path.basename(libc_name) != 'libc.so.6':
41 self.skipTest('wrong libc path for test')
42 cdll.LoadLibrary("libc.so.6")
43 # linux uses version, libc 9 should not exist
44 self.assertRaises(OSError, cdll.LoadLibrary, "libc.so.9")
45 self.assertRaises(OSError, cdll.LoadLibrary, self.unknowndll)
46
47 def test_find(self):
48 found = False
49 for name in ("c", "m"):
50 lib = find_library(name)
51 if lib:
52 found = True
53 cdll.LoadLibrary(lib)
54 CDLL(lib)
55 if not found:
56 self.skipTest("Could not find c and m libraries")
57
58 @unittest.skipUnless(os.name == "nt",
59 'test specific to Windows')
60 def test_load_library(self):
61 # CRT is no longer directly loadable. See issue23606 for the
62 # discussion about alternative approaches.
63 #self.assertIsNotNone(libc_name)
64 if test.support.verbose:
65 print(find_library("kernel32"))
66 print(find_library("user32"))
67
68 if os.name == "nt":
69 windll.kernel32.GetModuleHandleW
70 windll["kernel32"].GetModuleHandleW
71 windll.LoadLibrary("kernel32").GetModuleHandleW
72 WinDLL("kernel32").GetModuleHandleW
73 # embedded null character
74 self.assertRaises(ValueError, windll.LoadLibrary, "kernel32\0")
75
76 @unittest.skipUnless(os.name == "nt",
77 'test specific to Windows')
78 def test_load_ordinal_functions(self):
79 import _ctypes_test
80 dll = WinDLL(_ctypes_test.__file__)
81 # We load the same function both via ordinal and name
82 func_ord = dll[2]
83 func_name = dll.GetString
84 # addressof gets the address where the function pointer is stored
85 a_ord = addressof(func_ord)
86 a_name = addressof(func_name)
87 f_ord_addr = c_void_p.from_address(a_ord).value
88 f_name_addr = c_void_p.from_address(a_name).value
89 self.assertEqual(hex(f_ord_addr), hex(f_name_addr))
90
91 self.assertRaises(AttributeError, dll.__getitem__, 1234)
92
93 @unittest.skipUnless(os.name == "nt", 'Windows-specific test')
94 def test_1703286_A(self):
95 from _ctypes import LoadLibrary, FreeLibrary
96 # On winXP 64-bit, advapi32 loads at an address that does
97 # NOT fit into a 32-bit integer. FreeLibrary must be able
98 # to accept this address.
99
100 # These are tests for https://www.python.org/sf/1703286
101 handle = LoadLibrary("advapi32")
102 FreeLibrary(handle)
103
104 @unittest.skipUnless(os.name == "nt", 'Windows-specific test')
105 def test_1703286_B(self):
106 # Since on winXP 64-bit advapi32 loads like described
107 # above, the (arbitrarily selected) CloseEventLog function
108 # also has a high address. 'call_function' should accept
109 # addresses so large.
110 from _ctypes import call_function
111 advapi32 = windll.advapi32
112 # Calling CloseEventLog with a NULL argument should fail,
113 # but the call should not segfault or so.
114 self.assertEqual(0, advapi32.CloseEventLog(None))
115 windll.kernel32.GetProcAddress.argtypes = c_void_p, c_char_p
116 windll.kernel32.GetProcAddress.restype = c_void_p
117 proc = windll.kernel32.GetProcAddress(advapi32._handle,
118 b"CloseEventLog")
119 self.assertTrue(proc)
120 # This is the real test: call the function via 'call_function'
121 self.assertEqual(0, call_function(proc, (None,)))
122
123 @unittest.skipUnless(os.name == "nt",
124 'test specific to Windows')
125 def test_load_dll_with_flags(self):
126 _sqlite3 = import_helper.import_module("_sqlite3")
127 src = _sqlite3.__file__
128 if src.lower().endswith("_d.pyd"):
129 ext = "_d.dll"
130 else:
131 ext = ".dll"
132
133 with os_helper.temp_dir() as tmp:
134 # We copy two files and load _sqlite3.dll (formerly .pyd),
135 # which has a dependency on sqlite3.dll. Then we test
136 # loading it in subprocesses to avoid it starting in memory
137 # for each test.
138 target = os.path.join(tmp, "_sqlite3.dll")
139 shutil.copy(src, target)
140 shutil.copy(os.path.join(os.path.dirname(src), "sqlite3" + ext),
141 os.path.join(tmp, "sqlite3" + ext))
142
143 def should_pass(command):
144 with self.subTest(command):
145 subprocess.check_output(
146 [sys.executable, "-c",
147 "from ctypes import *; import nt;" + command],
148 cwd=tmp
149 )
150
151 def should_fail(command):
152 with self.subTest(command):
153 with self.assertRaises(subprocess.CalledProcessError):
154 subprocess.check_output(
155 [sys.executable, "-c",
156 "from ctypes import *; import nt;" + command],
157 cwd=tmp, stderr=subprocess.STDOUT,
158 )
159
160 # Default load should not find this in CWD
161 should_fail("WinDLL('_sqlite3.dll')")
162
163 # Relative path (but not just filename) should succeed
164 should_pass("WinDLL('./_sqlite3.dll')")
165
166 # Insecure load flags should succeed
167 # Clear the DLL directory to avoid safe search settings propagating
168 should_pass("windll.kernel32.SetDllDirectoryW(None); WinDLL('_sqlite3.dll', winmode=0)")
169
170 # Full path load without DLL_LOAD_DIR shouldn't find dependency
171 should_fail("WinDLL(nt._getfullpathname('_sqlite3.dll'), " +
172 "winmode=nt._LOAD_LIBRARY_SEARCH_SYSTEM32)")
173
174 # Full path load with DLL_LOAD_DIR should succeed
175 should_pass("WinDLL(nt._getfullpathname('_sqlite3.dll'), " +
176 "winmode=nt._LOAD_LIBRARY_SEARCH_SYSTEM32|" +
177 "nt._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)")
178
179 # User-specified directory should succeed
180 should_pass("import os; p = os.add_dll_directory(os.getcwd());" +
181 "WinDLL('_sqlite3.dll'); p.close()")
182
183
184
185 if __name__ == "__main__":
186 unittest.main()