-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmklibs-copy
More file actions
265 lines (224 loc) · 8.31 KB
/
Copy pathmklibs-copy
File metadata and controls
265 lines (224 loc) · 8.31 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#!/usr/bin/python
# mklibs.py: An automated way to create a minimal /lib/ directory.
#
# Copyright 2001 by Falk Hueffner <falk@debian.org>
# & Goswin Brederlow <goswin.brederlow@student.uni-tuebingen.de>
#
# mklibs.sh by Marcus Brinkmann <Marcus.Brinkmann@ruhr-uni-bochum.de>
# used as template
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import re
import sys
import os
import glob
import logging
from stat import *
import subprocess
try:
import mklibs
except ImportError:
sys.path.append('/usr/lib/mklibs/python')
from mklibs.utils.main import MainBase
class Main(MainBase):
pass
main = Main()
logger = logging.getLogger(__name__)
# return a list of lines of output of the command
def command(command, *args):
logger.debug("calling %s %s", command, ' '.join(args))
pipe = os.popen(command + ' ' + ' '.join(args), 'r')
output = pipe.read().strip()
status = pipe.close()
if status is not None and os.WEXITSTATUS(status) != 0:
print "Command failed with status", os.WEXITSTATUS(status), ":", \
command, ' '.join(args)
print "With output:", output
sys.exit(1)
return output.split('\n')
# Filter a list according to a regexp containing a () group. Return
# a set.
def regexpfilter(list, regexp, groupnr = 1):
pattern = re.compile(regexp)
result = set()
for x in list:
match = pattern.match(x)
if match:
result.add(match.group(groupnr))
return result
def elf_header(obj):
if not os.access(obj, os.F_OK):
raise "Cannot find lib: " + obj
output = command("mklibs-readelf", "--print-elf-header", obj)
s = [int(i) for i in output[0].split()]
return {'class': s[0], 'data': s[1], 'machine': s[2], 'flags': s[3]}
# Return a set of rpath strings for the passed object
def rpath(obj):
if not os.access(obj, os.F_OK):
raise "Cannot find lib: " + obj
output = command("mklibs-readelf", "-R", obj)
return [root + "/" + x for x in output if x]
# Return a set of libraries the passed objects depend on.
def library_depends(obj):
if not os.access(obj, os.F_OK):
raise "Cannot find lib: " + obj
return [x for x in command("mklibs-readelf", "-n", obj) if x]
# Return real target of a symlink
def resolve_link(file):
logger.debug("resolving %s", file)
while S_ISLNK(os.lstat(file)[ST_MODE]):
new_file = os.readlink(file)
if new_file[0] != "/":
file = os.path.join(os.path.dirname(file), new_file)
else:
file = new_file
logger.debug("resolved to %s", file)
return file
# Find complete path of a library, by searching in lib_path
def find_lib(lib):
for path in lib_path:
if os.access(path + "/" + lib, os.F_OK):
return path + "/" + lib
return ""
def extract_soname(so_file):
soname_data = command("mklibs-readelf", "-s", so_file)
if soname_data:
return soname_data.pop()
return ""
def multiarch(paths):
devnull = open('/dev/null', 'w')
dpkg_architecture = subprocess.Popen(
['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
stdout=subprocess.PIPE, stderr=devnull)
devnull.close()
deb_host_multiarch, _ = dpkg_architecture.communicate()
if dpkg_architecture.returncode == 0:
deb_host_multiarch = deb_host_multiarch.rstrip('\n')
new_paths = []
for path in paths:
new_paths.append(
path.replace('/lib', '/lib/%s' % deb_host_multiarch, 1))
new_paths.append(path)
return new_paths
else:
return paths
def version(vers):
print "mklibs: version ",vers
print ""
# Clean the environment
vers="0.12"
os.environ['LC_ALL'] = "C"
# some global variables
lib_rpath = []
lib_path = main.options.library_dir
dest_path = main.options.dest_dir
ldlib = main.options.ldlib
default_lib_path = multiarch(["/lib/", "/usr/lib/", "/usr/X11R6/lib/"])
target = ""
root = main.options.root
include_default_lib_path = not main.options.omit_library_dir
proglist = main.files
so_pattern = re.compile("((lib|ld).*)\.so(\..+)*")
if include_default_lib_path:
lib_path.extend(default_lib_path)
objects = {} # map from inode to filename
for prog in proglist:
inode = os.stat(prog)[ST_INO]
if objects.has_key(inode):
logger.debug("%s is a hardlink to %s", prog, objects[inode])
elif so_pattern.match(prog):
logger.debug("%s is a library", prog)
elif open(prog).read(4)[1:] == 'ELF':
objects[inode] = prog
else:
logger.debug("%s is no ELF", prog)
if not ldlib:
for obj in objects.values():
output = command("mklibs-readelf", "-i", obj)
for x in output:
ldlib = x
if ldlib:
break
if not ldlib:
sys.exit("E: Dynamic linker not found, aborting.")
logger.info('Using %s as dynamic linker', ldlib)
# Check for rpaths
for obj in objects.values():
rpath_val = rpath(obj)
if rpath_val:
if root:
for rpath_elem in rpath_val:
if not rpath_elem in lib_rpath:
logger.verbose('Adding rpath %s for %s', rpath_elem, obj)
lib_rpath.append(rpath_elem)
else:
logger.warning('%s may need rpath, but --root not specified', obj)
lib_path.extend(lib_rpath)
passnr = 1
available_libs = []
previous_pass_libraries = set()
while 1:
logger.info("library reduction pass %d", passnr)
passnr = passnr + 1
# Gather all already reduced libraries and treat them as objects as well
small_libs = []
for lib in regexpfilter(os.listdir(dest_path), "(.*-so-stripped)$"):
obj = dest_path + "/" + lib
small_libs.append(obj)
inode = os.stat(obj)[ST_INO]
if objects.has_key(inode):
logger.debug("%s is hardlink to %s", obj, objects[inode])
else:
objects[inode] = obj
for obj in objects.values():
small_libs.append(obj)
logger.verbose('Objects: %r', ' '.join([i[i.rfind('/') + 1:] for i in objects.itervalues()]))
libraries = set()
for obj in objects.values():
libraries.update(library_depends(obj))
if libraries == previous_pass_libraries:
# No progress in last pass.
break
previous_pass_libraries = libraries
# WORKAROUND: Always add libgcc on old-abi arm
header = elf_header(find_lib(libraries.copy().pop()))
if header['machine'] == 40 and header['flags'] & 0xff000000 == 0:
libraries.add('libgcc_s.so.1')
# reduce libraries
for library in libraries:
so_file = find_lib(library)
if root and (re.compile("^" + root).search(so_file)):
logger.verbose("no action required for " + so_file)
if not so_file in available_libs:
logger.verbose("adding %s to available libs", so_file)
available_libs.append(so_file)
continue
so_file_name = os.path.basename(so_file)
if not so_file:
sys.exit("File not found:" + library)
command("cp", so_file, dest_path + "/" + so_file_name + "-so-stripped")
# Finalising libs and cleaning up
for lib in regexpfilter(os.listdir(dest_path), "(.*)-so-stripped$"):
os.rename(dest_path + "/" + lib + "-so-stripped", dest_path + "/" + lib)
for lib in regexpfilter(os.listdir(dest_path), "(.*-so)$"):
os.remove(dest_path + "/" + lib)
# Make sure the dynamic linker is present and is executable
ld_file = find_lib(ldlib)
ld_file_name = os.path.basename(ld_file)
if not os.access(dest_path + "/" + ld_file_name, os.F_OK):
logger.info("stripping and copying dynamic linker.")
command(target + "objcopy", "--strip-unneeded -R .note -R .comment",
ld_file, dest_path + "/" + ld_file_name)
os.chmod(dest_path + "/" + ld_file_name, 0755)