【问题标题】:Why do I get a segmentation fault when I try to call functions from libc using CDLL in python?当我尝试在 python 中使用 CDLL 从 libc 调用函数时,为什么会出现分段错误?
【发布时间】:2021-12-23 18:26:23
【问题描述】:

我正在尝试使用CDLLlibc 库调用srand 函数,但在实际调用srand 之前出现Segmentation fault 错误。

我的代码如下所示:

from ctypes import CDLL
import time

libc = CDLL("./libc.so.6")
libc.srand(int(time.time()))
print(libc.rand())

我遇到的错误是:

> python3 ex.py                    
[1]    70111 segmentation fault (core dumped)  python3 ex.py

我还查看了 dmesg 消息:

[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.

我还尝试为 libc 放置完整路径,因为我认为相对路径可能存在一些问题,但在这种情况下它也不起作用。

【问题讨论】:

    标签: python-3.x libc


    【解决方案1】:

    经过一些调查和许多使用 CDLL 的代码示例后,我找到了一种调用 srand 函数的方法。

    解决方案:

    from ctypes import CDLL
    import time
    
    libc = CDLL("libc.so.6")
    libc.srand(int(time.time()))
    print(libc.rand())
    

    libc.so.6 库必须在同一目录中。我认为CDLL 的相对路径和完整路径存在问题,但此配置有效。我也试过python2,错误是一样的。我认为这是CDLL 的错误。

    【讨论】:

      【解决方案2】:

      问题在于默认加载库搜索路径。它在/etc/ld.so.conf 中定义。例如,在我的机器上:

      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
      

      【讨论】:

      • 好的,那么解决方案应该是什么?我不明白你的回答。我的期望是为 libc 版本提供一条路径。
      • 解决方案应该是修复/etc/ld.so.conf。这需要管理员权限。我同意人们应该期望libc 的路径已经存在。我不熟悉您的系统,因此无法解释为什么不是这样。您可以在man7.org/linux/man-pages/man8/ld.so.8.html 找到有关此主题的更多信息。还有一种解决方法——将libc的路径添加到LD_LIBRARY_PATH环境变量中,
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多