Linux常用命令之--ldd

背景

ldd是用于查看可执行文件的动态链接库依赖。(也可使用pmap进行查看)
Q:什么是动态链接呢?

  • 有动态链接就有静态链接。静态链接是把依赖的第三方库函数打包到一起,其最后生成的可执行文件非常大。动态链接并不将那些库文件直接拿过来,而是在运行时,发现用到某些库中的某些函数时,再从第三方库中读取自己所需的方法。
  • 动态链接库,linux下的后缀为so(Shared Object),windows下的后缀为dll(Dynamic Link Libaray)。

    注:更多动态链接相关内容可参考下述文章:
    https://zhuanlan.zhihu.com/p/235551437

使用

可以使用ldd查看文件的动态链接依赖,如查看ls依赖的结果如下:

1
2
3
4
5
6
7
8
9
10
11
(venvStudy) [root@node1 build_so]# ldd /bin/ls
linux-vdso.so.1 => (0x00007ffef8adb000)
libselinux.so.1 => /lib64/libselinux.so.1 (0x00007f3809d7d000)
libcap.so.2 => /lib64/libcap.so.2 (0x00007f3809b78000)
libacl.so.1 => /lib64/libacl.so.1 (0x00007f380996f000)
libc.so.6 => /lib64/libc.so.6 (0x00007f38095a1000)
libpcre.so.1 => /lib64/libpcre.so.1 (0x00007f380933f000)
libdl.so.2 => /lib64/libdl.so.2 (0x00007f380913b000)
/lib64/ld-linux-x86-64.so.2 (0x00007f3809fa4000)
libattr.so.1 => /lib64/libattr.so.1 (0x00007f3808f36000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f3808d1a000)

通常安装某软件若是报错缺失某个依赖文件时,再结合apt-file查看文件所在包,然后使用apt进行安装。

注:Ubuntu下使用apt-file涉及到的命令如下:

  • apt install apt-file
  • apt-file update
  • apt-file search libpthread.so.0

CentOS下使用命令yum provides libpthread.so.0

扩展

在技术交流群看到其他人为了防止python代码泄露,有把python代码打包成动态链接库so的,自己不知道还可以这样操作,在此进行记录下。需要先安装Cython,该库是通过类似python的语法去编写c扩展并可以被python调用。其即具备了python快速开发的特点,又可以让代码运行起来像c一样快,同时还可以方便的调用c library。安装命令如下:
pip install Cython -i [https://pypi.mirrors.ustc.edu.cn/simple](https://pypi.mirrors.ustc.edu.cn/simple)

快速开始

新建文件hello.py,该文件为被打包的目标文件:

1
2
def hello(name):
print(f"hello, {name}")

新建文件setup.py,该文件是调用Cython进行打包的文件:

1
2
3
4
5
6
7
8
9
from distutils.core import setup
from Cython.Build import cythonize

if __name__ == '__main__':
file_name = 'hello.py' # 文件名
build_dir = '' # 文件目录
build_tmp_dir = 'temp' # 编译的临时文件目录
setup(ext_modules=cythonize(file_name), script_args=["build_ext", "-b", build_dir, "-t", build_tmp_dir])

接下来直接执行python setup.py,可以看到打包编译的过程,如果没有报错的话结果输出如下:

1
2
3
4
5
6
7
8
(venvStudy) [root@node1 build_so]# ll
total 284
drwxr-xr-x 3 root root 4096 Oct 2 11:53 build
-rw-r--r-- 1 root root 140877 Oct 2 11:53 hello.c
-rwxr-xr-x 1 root root 130968 Oct 2 11:53 hello.cpython-37m-x86_64-linux-gnu.so
-rw-r--r-- 1 root root 46 Oct 2 11:40 hello.py
-rw-r--r-- 1 root root 428 Oct 2 11:53 setup.py
-rw-r--r-- 1 root root 37 Oct 2 11:38 test.py

此时已经生成了动态链接库so文件,可以将hello.py删除,也可以正常调用hello,build目录下是生成的临时文件。到这里只是大概了解了如何将python代码打包为so文件,想要更好的工程实践见下一部分内容。

工程实践

可使用下述代码进行打包,来自[https://github.com/ArvinMei/py2so/blob/master/py2so.py](https://github.com/ArvinMei/py2so/blob/master/py2so.py)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import sys, os, shutil, time
from distutils.core import setup
from Cython.Build import cythonize

starttime = time.time()
setupfile= os.path.join(os.path.abspath('.'), __file__)

def getpy(basepath=os.path.abspath('.'), parentpath='', name='', build_dir="build",
excepts=(), copyOther=False, delC=False):
"""
获取py文件的路径
:param basepath: 根路径
:param parentpath: 父路径
:param name: 文件/夹
:param excepts: 排除文件
:param copy: 是否copy其他文件
:return: py文件的迭代器
"""
fullpath = os.path.join(basepath, parentpath, name)
for fname in os.listdir(fullpath):
ffile = os.path.join(fullpath, fname)
if os.path.isdir(ffile) and ffile != os.path.join(basepath, build_dir) and not fname.startswith('.'):
for f in getpy(basepath, os.path.join(parentpath, name), fname, build_dir, excepts, copyOther, delC):
yield f
elif os.path.isfile(ffile):
# print("\t", basepath, parentpath, name, ffile)
ext = os.path.splitext(fname)[1]
if ext == ".c":
if delC and os.stat(ffile).st_mtime > starttime:
os.remove(ffile)
elif ffile not in excepts and ext not in('.pyc', '.pyx'):
# print("\t\t", basepath, parentpath, name, ffile)
if ext in('.py', '.pyx') and not fname.startswith('__'):
yield os.path.join(parentpath, name, fname)
elif copyOther:
dstdir = os.path.join(basepath, build_dir, parentpath, name)
if not os.path.isdir(dstdir): os.makedirs(dstdir)
shutil.copyfile(ffile, os.path.join(dstdir, fname))
else:
pass

if __name__ == "__main__":
currdir = os.path.abspath('.')
parentpath = sys.argv[1] if len(sys.argv)>1 else "."

currdir, parentpath = os.path.split(currdir if parentpath == "." else os.path.abspath(parentpath))
build_dir = os.path.join(parentpath, "build")
build_tmp_dir = os.path.join(build_dir, "temp")
print("start:", currdir, parentpath, build_dir)
os.chdir(currdir)
try:
#获取py列表
module_list = list(getpy(basepath=currdir,parentpath=parentpath, build_dir=build_dir, excepts=(setupfile)))
print(module_list)
setup(ext_modules = cythonize(module_list),script_args=["build_ext", "-b", build_dir, "-t", build_tmp_dir])
module_list = list(getpy(basepath=currdir, parentpath=parentpath, build_dir=build_dir, excepts=(setupfile), copyOther=True))
except Exception as ex:
print("error! ", ex)
finally:
print("cleaning...")
module_list = list(getpy(basepath=currdir, parentpath=parentpath, build_dir=build_dir, excepts=(setupfile), delC=True))
if os.path.exists(build_tmp_dir): shutil.rmtree(build_tmp_dir)

print("complate! time:", time.time()-starttime, 's')