ctypes.util.test() fails: _dlopen does not handle ld scripts

"Sebastian M. Ernst" <[email protected]> Thu, 29 Jun 2017 21:31:17 +0200
Newsgroups gmane.comp.python.ctypes
Message-ID <[email protected]>
Hi all,

the test routine in ctypes.util fails - across multiple Python versions.
I am studying ctypes code to better understand it and found it this way.
The problem occurs in CPython 2.7, 3.4 and 3.6(.1) - I attached two
examples below this email. The error is identical:
OSError: /usr/lib64/libm.so: invalid ELF header

I am running openSUSE Leap 42.2. Looking deeper, my libm.so does not
have an ELF header. In my case, it happens to be an ASCII file with the
following contents:

/* GNU ld script
*/
OUTPUT_FORMAT(elf64-x86-64)
GROUP ( /lib64/libm.so.6  AS_NEEDED ( /usr/lib64/libmvec_nonshared.a
/lib64/libmvec.so.1 ) )

I am bit surprised as I have not seen this concept before. For my
understanding: Is the (in-)correct handling of ld scripts a bug or
simply a missing feature in ctypes? Could it be solved within ctypes
(instead of writing workaround code on the application side)?

There are some fairly old discussions on ctypes mailing lists, like this
one, 14 years old, describing this very behavior:
https://sourceforge.net/p/ctypes/mailman/message/4444162/

Thanks,
Sebastian



--------------------

Python 2.7.13 (default, Mar 22 2017, 12:31:17) [GCC] on linux2



Type "help", "copyright", "credits" or "license" for more information.



>>> from ctypes import util
>>> util.test()
libm.so.6
libc.so.6
libbz2.so.1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/ctypes/util.py", line 303, in test
    print cdll.LoadLibrary("libm.so")
  File "/usr/lib64/python2.7/ctypes/__init__.py", line 440, in LoadLibrary
    return self._dlltype(name)
  File "/usr/lib64/python2.7/ctypes/__init__.py", line 362, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: /usr/lib64/libm.so: invalid ELF header

Python 3.4.6 (default, Mar 22 2017, 12:26:13) [GCC] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import util
>>> util.test()
libm.so.6
libc.so.6
libbz2.so.1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.4/ctypes/util.py", line 262, in test
    print(cdll.LoadLibrary("libm.so"))
  File "/usr/lib64/python3.4/ctypes/__init__.py", line 429, in LoadLibrary
    return self._dlltype(name)
  File "/usr/lib64/python3.4/ctypes/__init__.py", line 351, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: /usr/lib64/libm.so: invalid ELF header

------------------------------------------------------------------------------
Check out the vibrant tech community on one of the world's most
engaging tech sites, Slashdot.org! http://sdm.link/slashdot