Skip to content

Commit 583e01a

Browse files
grgalexZeroIntensitypicnixzencukou
committed
pythongh-126554: ctypes: Correctly handle NULL dlsym values (pythonGH-126555)
For dlsym(), a return value of NULL does not necessarily indicate an error [1]. Therefore, to avoid using stale (or NULL) dlerror() values, we must: 1. clear the previous error state by calling dlerror() 2. call dlsym() 3. call dlerror() If the return value of dlerror() is not NULL, an error occured. In ctypes we choose to treat a NULL return value from dlsym() as a "not found" error. This is the same as the fallback message we use on Windows, Cygwin or when getting/formatting the error reason fails. [1]: https://man7.org/linux/man-pages/man3/dlsym.3.html Signed-off-by: Georgios Alexopoulos <[email protected]> Signed-off-by: Georgios Alexopoulos <[email protected]> Co-authored-by: Peter Bierma <[email protected]> Co-authored-by: Bénédikt Tran <[email protected]> Co-authored-by: Petr Viktorin <[email protected]>
1 parent abc7a52 commit 583e01a

File tree

4 files changed

+220
-31
lines changed

4 files changed

+220
-31
lines changed

Lib/test/test_ctypes/test_dlerror.py

+123
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import os
2+
import sys
3+
import unittest
4+
import platform
5+
6+
FOO_C = r"""
7+
#include <unistd.h>
8+
9+
/* This is a 'GNU indirect function' (IFUNC) that will be called by
10+
dlsym() to resolve the symbol "foo" to an address. Typically, such
11+
a function would return the address of an actual function, but it
12+
can also just return NULL. For some background on IFUNCs, see
13+
https://willnewton.name/uncategorized/using-gnu-indirect-functions.
14+
15+
Adapted from Michael Kerrisk's answer: https://stackoverflow.com/a/53590014.
16+
*/
17+
18+
asm (".type foo STT_GNU_IFUNC");
19+
20+
void *foo(void)
21+
{
22+
write($DESCRIPTOR, "OK", 2);
23+
return NULL;
24+
}
25+
"""
26+
27+
28+
@unittest.skipUnless(sys.platform.startswith('linux'),
29+
'Test only valid for Linux')
30+
class TestNullDlsym(unittest.TestCase):
31+
"""GH-126554: Ensure that we catch NULL dlsym return values
32+
33+
In rare cases, such as when using GNU IFUNCs, dlsym(),
34+
the C function that ctypes' CDLL uses to get the address
35+
of symbols, can return NULL.
36+
37+
The objective way of telling if an error during symbol
38+
lookup happened is to call glibc's dlerror() and check
39+
for a non-NULL return value.
40+
41+
However, there can be cases where dlsym() returns NULL
42+
and dlerror() is also NULL, meaning that glibc did not
43+
encounter any error.
44+
45+
In the case of ctypes, we subjectively treat that as
46+
an error, and throw a relevant exception.
47+
48+
This test case ensures that we correctly enforce
49+
this 'dlsym returned NULL -> throw Error' rule.
50+
"""
51+
52+
def test_null_dlsym(self):
53+
import subprocess
54+
import tempfile
55+
56+
# To avoid ImportErrors on Windows, where _ctypes does not have
57+
# dlopen and dlsym,
58+
# import here, i.e., inside the test function.
59+
# The skipUnless('linux') decorator ensures that we're on linux
60+
# if we're executing these statements.
61+
from ctypes import CDLL, c_int
62+
from _ctypes import dlopen, dlsym
63+
64+
retcode = subprocess.call(["gcc", "--version"],
65+
stdout=subprocess.DEVNULL,
66+
stderr=subprocess.DEVNULL)
67+
if retcode != 0:
68+
self.skipTest("gcc is missing")
69+
70+
pipe_r, pipe_w = os.pipe()
71+
self.addCleanup(os.close, pipe_r)
72+
self.addCleanup(os.close, pipe_w)
73+
74+
with tempfile.TemporaryDirectory() as d:
75+
# Create a C file with a GNU Indirect Function (FOO_C)
76+
# and compile it into a shared library.
77+
srcname = os.path.join(d, 'foo.c')
78+
dstname = os.path.join(d, 'libfoo.so')
79+
with open(srcname, 'w') as f:
80+
f.write(FOO_C.replace('$DESCRIPTOR', str(pipe_w)))
81+
args = ['gcc', '-fPIC', '-shared', '-o', dstname, srcname]
82+
p = subprocess.run(args, capture_output=True)
83+
84+
if p.returncode != 0:
85+
# IFUNC is not supported on all architectures.
86+
if platform.machine() == 'x86_64':
87+
# It should be supported here. Something else went wrong.
88+
p.check_returncode()
89+
else:
90+
# IFUNC might not be supported on this machine.
91+
self.skipTest(f"could not compile indirect function: {p}")
92+
93+
# Case #1: Test 'PyCFuncPtr_FromDll' from Modules/_ctypes/_ctypes.c
94+
L = CDLL(dstname)
95+
with self.assertRaisesRegex(AttributeError, "function 'foo' not found"):
96+
# Try accessing the 'foo' symbol.
97+
# It should resolve via dlsym() to NULL,
98+
# and since we subjectively treat NULL
99+
# addresses as errors, we should get
100+
# an error.
101+
L.foo
102+
103+
# Assert that the IFUNC was called
104+
self.assertEqual(os.read(pipe_r, 2), b'OK')
105+
106+
# Case #2: Test 'CDataType_in_dll_impl' from Modules/_ctypes/_ctypes.c
107+
with self.assertRaisesRegex(ValueError, "symbol 'foo' not found"):
108+
c_int.in_dll(L, "foo")
109+
110+
# Assert that the IFUNC was called
111+
self.assertEqual(os.read(pipe_r, 2), b'OK')
112+
113+
# Case #3: Test 'py_dl_sym' from Modules/_ctypes/callproc.c
114+
L = dlopen(dstname)
115+
with self.assertRaisesRegex(OSError, "symbol 'foo' not found"):
116+
dlsym(L, "foo")
117+
118+
# Assert that the IFUNC was called
119+
self.assertEqual(os.read(pipe_r, 2), b'OK')
120+
121+
122+
if __name__ == "__main__":
123+
unittest.main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix error handling in :class:`ctypes.CDLL` objects
2+
which could result in a crash in rare situations.

Modules/_ctypes/_ctypes.c

+64-26
Original file line numberDiff line numberDiff line change
@@ -956,32 +956,48 @@ CDataType_in_dll_impl(PyObject *type, PyTypeObject *cls, PyObject *dll,
956956
return NULL;
957957
}
958958

959+
#undef USE_DLERROR
959960
#ifdef MS_WIN32
960961
Py_BEGIN_ALLOW_THREADS
961962
address = (void *)GetProcAddress(handle, name);
962963
Py_END_ALLOW_THREADS
963-
if (!address) {
964-
PyErr_Format(PyExc_ValueError,
965-
"symbol '%s' not found",
966-
name);
967-
return NULL;
968-
}
969964
#else
965+
#ifdef __CYGWIN__
966+
// dlerror() isn't very helpful on cygwin
967+
#else
968+
#define USE_DLERROR
969+
/* dlerror() always returns the latest error.
970+
*
971+
* Clear the previous value before calling dlsym(),
972+
* to ensure we can tell if our call resulted in an error.
973+
*/
974+
(void)dlerror();
975+
#endif
970976
address = (void *)dlsym(handle, name);
971-
if (!address) {
972-
#ifdef __CYGWIN__
973-
/* dlerror() isn't very helpful on cygwin */
974-
PyErr_Format(PyExc_ValueError,
975-
"symbol '%s' not found",
976-
name);
977-
#else
978-
PyErr_SetString(PyExc_ValueError, dlerror());
979977
#endif
980-
return NULL;
978+
979+
if (address) {
980+
ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
981+
return PyCData_AtAddress(st, type, address);
981982
}
982-
#endif
983-
ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
984-
return PyCData_AtAddress(st, type, address);
983+
984+
#ifdef USE_DLERROR
985+
const char *dlerr = dlerror();
986+
if (dlerr) {
987+
PyObject *message = PyUnicode_DecodeLocale(dlerr, "surrogateescape");
988+
if (message) {
989+
PyErr_SetObject(PyExc_ValueError, message);
990+
Py_DECREF(message);
991+
return NULL;
992+
}
993+
// Ignore errors from PyUnicode_DecodeLocale,
994+
// fall back to the generic error below.
995+
PyErr_Clear();
996+
}
997+
#endif
998+
#undef USE_DLERROR
999+
PyErr_Format(PyExc_ValueError, "symbol '%s' not found", name);
1000+
return NULL;
9851001
}
9861002

9871003
/*[clinic input]
@@ -3759,6 +3775,7 @@ PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
37593775
return NULL;
37603776
}
37613777

3778+
#undef USE_DLERROR
37623779
#ifdef MS_WIN32
37633780
address = FindAddress(handle, name, (PyObject *)type);
37643781
if (!address) {
@@ -3774,20 +3791,41 @@ PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
37743791
return NULL;
37753792
}
37763793
#else
3794+
#ifdef __CYGWIN__
3795+
//dlerror() isn't very helpful on cygwin */
3796+
#else
3797+
#define USE_DLERROR
3798+
/* dlerror() always returns the latest error.
3799+
*
3800+
* Clear the previous value before calling dlsym(),
3801+
* to ensure we can tell if our call resulted in an error.
3802+
*/
3803+
(void)dlerror();
3804+
#endif
37773805
address = (PPROC)dlsym(handle, name);
3806+
37783807
if (!address) {
3779-
#ifdef __CYGWIN__
3780-
/* dlerror() isn't very helpful on cygwin */
3781-
PyErr_Format(PyExc_AttributeError,
3782-
"function '%s' not found",
3783-
name);
3784-
#else
3785-
PyErr_SetString(PyExc_AttributeError, dlerror());
3786-
#endif
3808+
#ifdef USE_DLERROR
3809+
const char *dlerr = dlerror();
3810+
if (dlerr) {
3811+
PyObject *message = PyUnicode_DecodeLocale(dlerr, "surrogateescape");
3812+
if (message) {
3813+
PyErr_SetObject(PyExc_AttributeError, message);
3814+
Py_DECREF(ftuple);
3815+
Py_DECREF(message);
3816+
return NULL;
3817+
}
3818+
// Ignore errors from PyUnicode_DecodeLocale,
3819+
// fall back to the generic error below.
3820+
PyErr_Clear();
3821+
}
3822+
#endif
3823+
PyErr_Format(PyExc_AttributeError, "function '%s' not found", name);
37873824
Py_DECREF(ftuple);
37883825
return NULL;
37893826
}
37903827
#endif
3828+
#undef USE_DLERROR
37913829
ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
37923830
if (!_validate_paramflags(st, type, paramflags)) {
37933831
Py_DECREF(ftuple);

Modules/_ctypes/callproc.c

+31-5
Original file line numberDiff line numberDiff line change
@@ -1623,13 +1623,39 @@ static PyObject *py_dl_sym(PyObject *self, PyObject *args)
16231623
if (PySys_Audit("ctypes.dlsym/handle", "O", args) < 0) {
16241624
return NULL;
16251625
}
1626+
#undef USE_DLERROR
1627+
#ifdef __CYGWIN__
1628+
// dlerror() isn't very helpful on cygwin
1629+
#else
1630+
#define USE_DLERROR
1631+
/* dlerror() always returns the latest error.
1632+
*
1633+
* Clear the previous value before calling dlsym(),
1634+
* to ensure we can tell if our call resulted in an error.
1635+
*/
1636+
(void)dlerror();
1637+
#endif
16261638
ptr = dlsym((void*)handle, name);
1627-
if (!ptr) {
1628-
PyErr_SetString(PyExc_OSError,
1629-
dlerror());
1630-
return NULL;
1639+
if (ptr) {
1640+
return PyLong_FromVoidPtr(ptr);
1641+
}
1642+
#ifdef USE_DLERROR
1643+
const char *dlerr = dlerror();
1644+
if (dlerr) {
1645+
PyObject *message = PyUnicode_DecodeLocale(dlerr, "surrogateescape");
1646+
if (message) {
1647+
PyErr_SetObject(PyExc_OSError, message);
1648+
Py_DECREF(message);
1649+
return NULL;
1650+
}
1651+
// Ignore errors from PyUnicode_DecodeLocale,
1652+
// fall back to the generic error below.
1653+
PyErr_Clear();
16311654
}
1632-
return PyLong_FromVoidPtr(ptr);
1655+
#endif
1656+
#undef USE_DLERROR
1657+
PyErr_Format(PyExc_OSError, "symbol '%s' not found", name);
1658+
return NULL;
16331659
}
16341660
#endif
16351661

0 commit comments

Comments
 (0)