relocate_sdk.py 9.7 KB

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