Skip to content

Commit 1c543d9

Browse files
grgalexZeroIntensitypicnixzencukou
committed
gh-126554: ctypes: Correctly handle NULL dlsym values (GH-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 87f912a commit 1c543d9

File tree

4 files changed

+217
-30
lines changed

4 files changed

+217
-30
lines changed
Lines changed: 123 additions & 0 deletions
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()
Lines changed: 2 additions & 0 deletions
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

Lines changed: 61 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -778,31 +778,45 @@ CDataType_in_dll(PyObject *type, PyObject *args)
778778
return NULL;
779779
}
780780

781+
#undef USE_DLERROR
781782
#ifdef MS_WIN32
782783
Py_BEGIN_ALLOW_THREADS
783784
address = (void *)GetProcAddress(handle, name);
784785
Py_END_ALLOW_THREADS
785-
if (!address) {
786-
PyErr_Format(PyExc_ValueError,
787-
"symbol '%s' not found",
788-
name);
789-
return NULL;
790-
}
791786
#else
787+
#ifdef __CYGWIN__
788+
// dlerror() isn't very helpful on cygwin
789+
#else
790+
#define USE_DLERROR
791+
/* dlerror() always returns the latest error.
792+
*
793+
* Clear the previous value before calling dlsym(),
794+
* to ensure we can tell if our call resulted in an error.
795+
*/
796+
(void)dlerror();
797+
#endif
792798
address = (void *)dlsym(handle, name);
793-
if (!address) {
794-
#ifdef __CYGWIN__
795-
/* dlerror() isn't very helpful on cygwin */
796-
PyErr_Format(PyExc_ValueError,
797-
"symbol '%s' not found",
798-
name);
799-
#else
800-
PyErr_SetString(PyExc_ValueError, dlerror());
801-
#endif
802-
return NULL;
799+
if (address) {
800+
return PyCData_AtAddress(type, address);
803801
}
804802
#endif
805-
return PyCData_AtAddress(type, address);
803+
#ifdef USE_DLERROR
804+
const char *dlerr = dlerror();
805+
if (dlerr) {
806+
PyObject *message = PyUnicode_DecodeLocale(dlerr, "surrogateescape");
807+
if (message) {
808+
PyErr_SetObject(PyExc_ValueError, message);
809+
Py_DECREF(message);
810+
return NULL;
811+
}
812+
// Ignore errors from PyUnicode_DecodeLocale,
813+
// fall back to the generic error below.
814+
PyErr_Clear();
815+
}
816+
#endif
817+
#undef USE_DLERROR
818+
PyErr_Format(PyExc_ValueError, "symbol '%s' not found", name);
819+
return NULL;
806820
}
807821

808822
PyDoc_STRVAR(from_param_doc,
@@ -3583,6 +3597,7 @@ PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
35833597
return NULL;
35843598
}
35853599

3600+
#undef USE_DLERROR
35863601
#ifdef MS_WIN32
35873602
address = FindAddress(handle, name, (PyObject *)type);
35883603
if (!address) {
@@ -3598,20 +3613,41 @@ PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
35983613
return NULL;
35993614
}
36003615
#else
3616+
#ifdef __CYGWIN__
3617+
//dlerror() isn't very helpful on cygwin */
3618+
#else
3619+
#define USE_DLERROR
3620+
/* dlerror() always returns the latest error.
3621+
*
3622+
* Clear the previous value before calling dlsym(),
3623+
* to ensure we can tell if our call resulted in an error.
3624+
*/
3625+
(void)dlerror();
3626+
#endif
36013627
address = (PPROC)dlsym(handle, name);
3628+
36023629
if (!address) {
3603-
#ifdef __CYGWIN__
3604-
/* dlerror() isn't very helpful on cygwin */
3605-
PyErr_Format(PyExc_AttributeError,
3606-
"function '%s' not found",
3607-
name);
3608-
#else
3609-
PyErr_SetString(PyExc_AttributeError, dlerror());
3610-
#endif
3630+
#ifdef USE_DLERROR
3631+
const char *dlerr = dlerror();
3632+
if (dlerr) {
3633+
PyObject *message = PyUnicode_DecodeLocale(dlerr, "surrogateescape");
3634+
if (message) {
3635+
PyErr_SetObject(PyExc_AttributeError, message);
3636+
Py_DECREF(ftuple);
3637+
Py_DECREF(message);
3638+
return NULL;
3639+
}
3640+
// Ignore errors from PyUnicode_DecodeLocale,
3641+
// fall back to the generic error below.
3642+
PyErr_Clear();
3643+
}
3644+
#endif
3645+
PyErr_Format(PyExc_AttributeError, "function '%s' not found", name);
36113646
Py_DECREF(ftuple);
36123647
return NULL;
36133648
}
36143649
#endif
3650+
#undef USE_DLERROR
36153651
if (!_validate_paramflags(type, paramflags)) {
36163652
Py_DECREF(ftuple);
36173653
return NULL;

Modules/_ctypes/callproc.c

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1585,13 +1585,39 @@ static PyObject *py_dl_sym(PyObject *self, PyObject *args)
15851585
if (PySys_Audit("ctypes.dlsym/handle", "O", args) < 0) {
15861586
return NULL;
15871587
}
1588+
#undef USE_DLERROR
1589+
#ifdef __CYGWIN__
1590+
// dlerror() isn't very helpful on cygwin
1591+
#else
1592+
#define USE_DLERROR
1593+
/* dlerror() always returns the latest error.
1594+
*
1595+
* Clear the previous value before calling dlsym(),
1596+
* to ensure we can tell if our call resulted in an error.
1597+
*/
1598+
(void)dlerror();
1599+
#endif
15881600
ptr = dlsym((void*)handle, name);
1589-
if (!ptr) {
1590-
PyErr_SetString(PyExc_OSError,
1591-
dlerror());
1592-
return NULL;
1601+
if (ptr) {
1602+
return PyLong_FromVoidPtr(ptr);
1603+
}
1604+
#ifdef USE_DLERROR
1605+
const char *dlerr = dlerror();
1606+
if (dlerr) {
1607+
PyObject *message = PyUnicode_DecodeLocale(dlerr, "surrogateescape");
1608+
if (message) {
1609+
PyErr_SetObject(PyExc_OSError, message);
1610+
Py_DECREF(message);
1611+
return NULL;
1612+
}
1613+
// Ignore errors from PyUnicode_DecodeLocale,
1614+
// fall back to the generic error below.
1615+
PyErr_Clear();
15931616
}
1594-
return PyLong_FromVoidPtr(ptr);
1617+
#endif
1618+
#undef USE_DLERROR
1619+
PyErr_Format(PyExc_OSError, "symbol '%s' not found", name);
1620+
return NULL;
15951621
}
15961622
#endif
15971623

0 commit comments

Comments
 (0)