I am trying to call srand
function from libc
library using CDLL
, but I got a Segmentation fault
error before actually calling srand
.
My code looks like this:
from ctypes import CDLL
import time
libc = CDLL("./libc.so.6")
libc.srand(int(time.time()))
print(libc.rand())
The error that I have is:
> python3 ex.py
[1] 70111 segmentation fault (core dumped) python3 ex.py
I also looked at the dmesg messages:
[31553.069657] python3[70111]: segfault at 0 ip 0000000000000000 sp 00007fffbd1f58e8 error 14 in python3.8[400000 23000]
[31553.069662] Code: Unable to access opcode bytes at RIP 0xffffffffffffffd6.
I tried also to put the full path for libc because I thought that it may be some problems with the relative path but it didn't work in this case either.
CodePudding user response:
After a few investigations and many examples of code that used CDLL I found a way to call srand
function.
Solution:
from ctypes import CDLL
import time
libc = CDLL("libc.so.6")
libc.srand(int(time.time()))
print(libc.rand())
The libc.so.6
library must be in the same directory. I think it's a problem with relative and full path for CDLL
but this configuration worked. I tried also with python2
and the error was the same. I think it's a bug with CDLL
.
CodePudding user response:
The problem is in default load library search path. It is defined in /etc/ld.so.conf
. For example, on my machine:
cat /etc/ld.so.conf
include /etc/ld.so.conf.d/*.conf
cat /etc/ld.so.conf.d/*.conf
/usr/lib/x86_64-linux-gnu/libfakeroot
# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [automount]
# ldconfig = false
/usr/lib/wsl/lib# libc default configuration
/usr/local/lib
# Multiarch support
/usr/local/lib/x86_64-linux-gnu
/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu
ls -lL /lib/x86_64-linux-gnu/libc.so.6
-rwxr-xr-x 1 root root 2029224 Dec 16 2020 /lib/x86_64-linux-gnu/libc.so.6