Skip to content

Commit 6ac578c

Browse files
picnixzgrgalexZeroIntensityencukou
authored
[3.12] gh-126554: ctypes: Correctly handle NULL dlsym values (GH-126555) (GH-127764)
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: George 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 073b52b commit 6ac578c

File tree

4 files changed

+216
-30
lines changed

4 files changed

+216
-30
lines changed

Lib/test/test_ctypes/test_dlerror.py

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: 60 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());
801799
#endif
802-
return NULL;
800+
if (address) {
801+
return PyCData_AtAddress(type, address);
802+
}
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();
803815
}
804-
#endif
805-
return PyCData_AtAddress(type, address);
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,
@@ -3603,6 +3617,7 @@ PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
36033617
return NULL;
36043618
}
36053619

3620+
#undef USE_DLERROR
36063621
#ifdef MS_WIN32
36073622
address = FindAddress(handle, name, (PyObject *)type);
36083623
if (!address) {
@@ -3618,20 +3633,40 @@ PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
36183633
return NULL;
36193634
}
36203635
#else
3636+
#ifdef __CYGWIN__
3637+
//dlerror() isn't very helpful on cygwin */
3638+
#else
3639+
#define USE_DLERROR
3640+
/* dlerror() always returns the latest error.
3641+
*
3642+
* Clear the previous value before calling dlsym(),
3643+
* to ensure we can tell if our call resulted in an error.
3644+
*/
3645+
(void)dlerror();
3646+
#endif
36213647
address = (PPROC)dlsym(handle, name);
36223648
if (!address) {
3623-
#ifdef __CYGWIN__
3624-
/* dlerror() isn't very helpful on cygwin */
3625-
PyErr_Format(PyExc_AttributeError,
3626-
"function '%s' not found",
3627-
name);
3628-
#else
3629-
PyErr_SetString(PyExc_AttributeError, dlerror());
3630-
#endif
3649+
#ifdef USE_DLERROR
3650+
const char *dlerr = dlerror();
3651+
if (dlerr) {
3652+
PyObject *message = PyUnicode_DecodeLocale(dlerr, "surrogateescape");
3653+
if (message) {
3654+
PyErr_SetObject(PyExc_AttributeError, message);
3655+
Py_DECREF(ftuple);
3656+
Py_DECREF(message);
3657+
return NULL;
3658+
}
3659+
// Ignore errors from PyUnicode_DecodeLocale,
3660+
// fall back to the generic error below.
3661+
PyErr_Clear();
3662+
}
3663+
#endif
3664+
PyErr_Format(PyExc_AttributeError, "function '%s' not found", name);
36313665
Py_DECREF(ftuple);
36323666
return NULL;
36333667
}
36343668
#endif
3669+
#undef USE_DLERROR
36353670
if (!_validate_paramflags(type, paramflags)) {
36363671
Py_DECREF(ftuple);
36373672
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)