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.skipUnless(os.name == "nt", 'Windows-specific test')
110 def test_1703286_A(self):
111 # On winXP 64-bit, advapi32 loads at an address that does
112 # NOT fit into a 32-bit integer. FreeLibrary must be able
113 # to accept this address.
114
115 # These are tests for https://bugs.python.org/issue1703286
116 handle = _ctypes.LoadLibrary("advapi32")
117 _ctypes.FreeLibrary(handle)
118
119 @unittest.skipUnless(os.name == "nt", 'Windows-specific test')
120 def test_1703286_B(self):
121 # Since on winXP 64-bit advapi32 loads like described
122 # above, the (arbitrarily selected) CloseEventLog function
123 # also has a high address. 'call_function' should accept
124 # addresses so large.
125
126 advapi32 = ctypes.windll.advapi32
127 # Calling CloseEventLog with a NULL argument should fail,
128 # but the call should not segfault or so.
129 self.assertEqual(0, advapi32.CloseEventLog(None))
130
131 kernel32 = ctypes.windll.kernel32
132 kernel32.GetProcAddress.argtypes = c_void_p, c_char_p
133 kernel32.GetProcAddress.restype = c_void_p
134 proc = kernel32.GetProcAddress(advapi32._handle, b"CloseEventLog")
135 self.assertTrue(proc)
136
137 # This is the real test: call the function via 'call_function'
138 self.assertEqual(0, _ctypes.call_function(proc, (None,)))
139
140 @unittest.skipUnless(os.name == "nt",
141 'test specific to Windows')
142 def test_load_hasattr(self):
143 # bpo-34816: shouldn't raise OSError
144 self.assertFalse(hasattr(ctypes.windll, 'test'))
145
146 @unittest.skipUnless(os.name == "nt",
147 'test specific to Windows')
148 def test_load_dll_with_flags(self):
149 _sqlite3 = import_helper.import_module("_sqlite3")
150 src = _sqlite3.__file__
151 if os.path.basename(src).partition(".")[0].lower().endswith("_d"):
152 ext = "_d.dll"
153 else:
154 ext = ".dll"
155
156 with os_helper.temp_dir() as tmp:
157 # We copy two files and load _sqlite3.dll (formerly .pyd),
158 # which has a dependency on sqlite3.dll. Then we test
159 # loading it in subprocesses to avoid it starting in memory
160 # for each test.
161 target = os.path.join(tmp, "_sqlite3.dll")
162 shutil.copy(src, target)
163 shutil.copy(os.path.join(os.path.dirname(src), "sqlite3" + ext),
164 os.path.join(tmp, "sqlite3" + ext))
165
166 def should_pass(command):
167 with self.subTest(command):
168 subprocess.check_output(
169 [sys.executable, "-c",
170 "from ctypes import *; import nt;" + command],
171 cwd=tmp
172 )
173
174 def should_fail(command):
175 with self.subTest(command):
176 with self.assertRaises(subprocess.CalledProcessError):
177 subprocess.check_output(
178 [sys.executable, "-c",
179 "from ctypes import *; import nt;" + command],
180 cwd=tmp, stderr=subprocess.STDOUT,
181 )
182
183 # Default load should not find this in CWD
184 should_fail("WinDLL('_sqlite3.dll')")
185
186 # Relative path (but not just filename) should succeed
187 should_pass("WinDLL('./_sqlite3.dll')")
188
189 # Insecure load flags should succeed
190 # Clear the DLL directory to avoid safe search settings propagating
191 should_pass("windll.kernel32.SetDllDirectoryW(None); WinDLL('_sqlite3.dll', winmode=0)")
192
193 # Full path load without DLL_LOAD_DIR shouldn't find dependency
194 should_fail("WinDLL(nt._getfullpathname('_sqlite3.dll'), " +
195 "winmode=nt._LOAD_LIBRARY_SEARCH_SYSTEM32)")
196
197 # Full path load with DLL_LOAD_DIR should succeed
198 should_pass("WinDLL(nt._getfullpathname('_sqlite3.dll'), " +
199 "winmode=nt._LOAD_LIBRARY_SEARCH_SYSTEM32|" +
200 "nt._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)")
201
202 # User-specified directory should succeed
203 should_pass("import os; p = os.add_dll_directory(os.getcwd());" +
204 "WinDLL('_sqlite3.dll'); p.close()")
205
206
207 if __name__ == "__main__":
208 unittest.main()