1. Problem
When building c/cpp project, shared lib is frequently used. I need a script to check whether shared libs and their dependent libs can be found by ld.
2. Code
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Usage: python checklib.py [libpath_name1] [libpath_name2] ...
'''
import os
import commands
import re
def get_libname(filename):
return filename#[3:filename.find('.')]
def checklib(argv):
# get all libs
roots = []
all_libs = []
all_libs_list = []
for lib_path in argv[1:]:
root = lib_path
if not lib_path.endswith('/'):
root += '/'
files = os.listdir(lib_path)
libs = []
for f in files:
if not os.path.isfile(os.path.join(root,f)): # ignore dir
continue
#if 'lib' not in f: # check lib*.xx # ld-linux.so
# continue
if '.so' not in f:
continue
libname = get_libname(f)
if libname not in libs:
libs.append(libname)
libs = sorted(libs)
roots.append(root)
all_libs.append(libs)
all_libs_list += libs
# find dependent lib
for index in xrange(0, len(roots)):
libs = all_libs[index]
for lib in libs:
(status, output) = commands.getstatusoutput('readelf -d {}/{} | grep Shared'.format(roots[index], lib))
if status == 0:
output = output.split('\n')
libs_dep = [x[58:-1] for x in output]
for lib_dep in libs_dep:
if lib_dep not in all_libs_list:
print "{} not found, needed by {}".format(lib_dep, roots[index]+lib)
print "Please add more lib path"
return
print "checking {}".format(lib)
else:
# two type: non shared lib, have no shared dependent lib
#print roots[index], lib
#print status, output
pass
print 'Done!'
def main():
import sys
if len(sys.argv) < 2:
print(__doc__)
return
checklib(sys.argv)
if __name__ == "__main__":
main()