Debian Codegraph @

Lib/test/test_ctypes/test_loading.py

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