blob: c752fa2c6192c9246dce89bf5c68244d54482e9a [file] [log] [blame]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001#!/usr/bin/env python3
Patrick Williamsc124f4f2015-09-15 14:41:29 -05002#
3# Copyright (c) 2012 Intel Corporation
4#
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License version 2 as
7# published by the Free Software Foundation.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12# See the GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program; if not, write to the Free Software
16# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17#
18# DESCRIPTION
19# This script is called by the SDK installer script. It replaces the dynamic
20# loader path in all binaries and also fixes the SYSDIR paths/lengths and the
21# location of ld.so.cache in the dynamic loader binary
22#
23# AUTHORS
24# Laurentiu Palcu <laurentiu.palcu@intel.com>
25#
26
27import struct
28import sys
29import stat
30import os
31import re
32import errno
33
34if sys.version < '3':
35 def b(x):
36 return x
37else:
38 def b(x):
39 return x.encode(sys.getfilesystemencoding())
40
41old_prefix = re.compile(b("##DEFAULT_INSTALL_DIR##"))
42
43def get_arch():
44 f.seek(0)
45 e_ident =f.read(16)
46 ei_mag0,ei_mag1_3,ei_class = struct.unpack("<B3sB11x", e_ident)
47
48 if (ei_mag0 != 0x7f and ei_mag1_3 != "ELF") or ei_class == 0:
49 return 0
50
51 if ei_class == 1:
52 return 32
53 elif ei_class == 2:
54 return 64
55
56def parse_elf_header():
57 global e_type, e_machine, e_version, e_entry, e_phoff, e_shoff, e_flags,\
58 e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum, e_shstrndx
59
60 f.seek(0)
61 elf_header = f.read(64)
62
63 if arch == 32:
64 # 32bit
65 hdr_fmt = "<HHILLLIHHHHHH"
66 hdr_size = 52
67 else:
68 # 64bit
69 hdr_fmt = "<HHIQQQIHHHHHH"
70 hdr_size = 64
71
72 e_type, e_machine, e_version, e_entry, e_phoff, e_shoff, e_flags,\
73 e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum, e_shstrndx =\
74 struct.unpack(hdr_fmt, elf_header[16:hdr_size])
75
76def change_interpreter(elf_file_name):
77 if arch == 32:
78 ph_fmt = "<IIIIIIII"
79 else:
80 ph_fmt = "<IIQQQQQQ"
81
82 """ look for PT_INTERP section """
83 for i in range(0,e_phnum):
84 f.seek(e_phoff + i * e_phentsize)
85 ph_hdr = f.read(e_phentsize)
86 if arch == 32:
87 # 32bit
88 p_type, p_offset, p_vaddr, p_paddr, p_filesz,\
89 p_memsz, p_flags, p_align = struct.unpack(ph_fmt, ph_hdr)
90 else:
91 # 64bit
92 p_type, p_flags, p_offset, p_vaddr, p_paddr, \
93 p_filesz, p_memsz, p_align = struct.unpack(ph_fmt, ph_hdr)
94
95 """ change interpreter """
96 if p_type == 3:
97 # PT_INTERP section
98 f.seek(p_offset)
99 # External SDKs with mixed pre-compiled binaries should not get
100 # relocated so look for some variant of /lib
101 fname = f.read(11)
102 if fname.startswith(b("/lib/")) or fname.startswith(b("/lib64/")) or \
103 fname.startswith(b("/lib32/")) or fname.startswith(b("/usr/lib32/")) or \
104 fname.startswith(b("/usr/lib32/")) or fname.startswith(b("/usr/lib64/")):
105 break
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500106 if p_filesz == 0:
107 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500108 if (len(new_dl_path) >= p_filesz):
109 print("ERROR: could not relocate %s, interp size = %i and %i is needed." \
110 % (elf_file_name, p_memsz, len(new_dl_path) + 1))
111 break
112 dl_path = new_dl_path + b("\0") * (p_filesz - len(new_dl_path))
113 f.seek(p_offset)
114 f.write(dl_path)
115 break
116
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500117def change_dl_sysdirs(elf_file_name):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500118 if arch == 32:
119 sh_fmt = "<IIIIIIIIII"
120 else:
121 sh_fmt = "<IIQQQQIIQQ"
122
123 """ read section string table """
124 f.seek(e_shoff + e_shstrndx * e_shentsize)
125 sh_hdr = f.read(e_shentsize)
126 if arch == 32:
127 sh_offset, sh_size = struct.unpack("<16xII16x", sh_hdr)
128 else:
129 sh_offset, sh_size = struct.unpack("<24xQQ24x", sh_hdr)
130
131 f.seek(sh_offset)
132 sh_strtab = f.read(sh_size)
133
134 sysdirs = sysdirs_len = ""
135
136 """ change ld.so.cache path and default libs path for dynamic loader """
137 for i in range(0,e_shnum):
138 f.seek(e_shoff + i * e_shentsize)
139 sh_hdr = f.read(e_shentsize)
140
141 sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size, sh_link,\
142 sh_info, sh_addralign, sh_entsize = struct.unpack(sh_fmt, sh_hdr)
143
144 name = sh_strtab[sh_name:sh_strtab.find(b("\0"), sh_name)]
145
146 """ look only into SHT_PROGBITS sections """
147 if sh_type == 1:
148 f.seek(sh_offset)
149 """ default library paths cannot be changed on the fly because """
150 """ the string lengths have to be changed too. """
151 if name == b(".sysdirs"):
152 sysdirs = f.read(sh_size)
153 sysdirs_off = sh_offset
154 sysdirs_sect_size = sh_size
155 elif name == b(".sysdirslen"):
156 sysdirslen = f.read(sh_size)
157 sysdirslen_off = sh_offset
158 elif name == b(".ldsocache"):
159 ldsocache_path = f.read(sh_size)
160 new_ldsocache_path = old_prefix.sub(new_prefix, ldsocache_path)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500161 new_ldsocache_path = new_ldsocache_path.rstrip(b("\0"))
162 if (len(new_ldsocache_path) >= sh_size):
163 print("ERROR: could not relocate %s, .ldsocache section size = %i and %i is needed." \
164 % (elf_file_name, sh_size, len(new_ldsocache_path)))
165 sys.exit(-1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500166 # pad with zeros
167 new_ldsocache_path += b("\0") * (sh_size - len(new_ldsocache_path))
168 # write it back
169 f.seek(sh_offset)
170 f.write(new_ldsocache_path)
171 elif name == b(".gccrelocprefix"):
172 offset = 0
173 while (offset + 4096) <= sh_size:
174 path = f.read(4096)
175 new_path = old_prefix.sub(new_prefix, path)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500176 new_path = new_path.rstrip(b("\0"))
177 if (len(new_path) >= 4096):
178 print("ERROR: could not relocate %s, max path size = 4096 and %i is needed." \
179 % (elf_file_name, len(new_path)))
180 sys.exit(-1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500181 # pad with zeros
182 new_path += b("\0") * (4096 - len(new_path))
183 #print "Changing %s to %s at %s" % (str(path), str(new_path), str(offset))
184 # write it back
185 f.seek(sh_offset + offset)
186 f.write(new_path)
187 offset = offset + 4096
188 if sysdirs != "" and sysdirslen != "":
189 paths = sysdirs.split(b("\0"))
190 sysdirs = b("")
191 sysdirslen = b("")
192 for path in paths:
193 """ exit the loop when we encounter first empty string """
194 if path == b(""):
195 break
196
197 new_path = old_prefix.sub(new_prefix, path)
198 sysdirs += new_path + b("\0")
199
200 if arch == 32:
201 sysdirslen += struct.pack("<L", len(new_path))
202 else:
203 sysdirslen += struct.pack("<Q", len(new_path))
204
205 """ pad with zeros """
206 sysdirs += b("\0") * (sysdirs_sect_size - len(sysdirs))
207
208 """ write the sections back """
209 f.seek(sysdirs_off)
210 f.write(sysdirs)
211 f.seek(sysdirslen_off)
212 f.write(sysdirslen)
213
214# MAIN
215if len(sys.argv) < 4:
216 sys.exit(-1)
217
218# In python > 3, strings may also contain Unicode characters. So, convert
219# them to bytes
220if sys.version_info < (3,):
221 new_prefix = sys.argv[1]
222 new_dl_path = sys.argv[2]
223else:
224 new_prefix = sys.argv[1].encode()
225 new_dl_path = sys.argv[2].encode()
226
227executables_list = sys.argv[3:]
228
229for e in executables_list:
230 perms = os.stat(e)[stat.ST_MODE]
231 if os.access(e, os.W_OK|os.R_OK):
232 perms = None
233 else:
234 os.chmod(e, perms|stat.S_IRWXU)
235
236 try:
237 f = open(e, "r+b")
238 except IOError:
239 exctype, ioex = sys.exc_info()[:2]
240 if ioex.errno == errno.ETXTBSY:
241 print("Could not open %s. File used by another process.\nPlease "\
242 "make sure you exit all processes that might use any SDK "\
243 "binaries." % e)
244 else:
245 print("Could not open %s: %s(%d)" % (e, ioex.strerror, ioex.errno))
246 sys.exit(-1)
247
248 # Save old size and do a size check at the end. Just a safety measure.
249 old_size = os.path.getsize(e)
250 if old_size >= 64:
251 arch = get_arch()
252 if arch:
253 parse_elf_header()
254 change_interpreter(e)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500255 change_dl_sysdirs(e)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500256
257 """ change permissions back """
258 if perms:
259 os.chmod(e, perms)
260
261 f.close()
262
263 if old_size != os.path.getsize(e):
264 print("New file size for %s is different. Looks like a relocation error!", e)
265 sys.exit(-1)
266