relocate_sdk.py 8.5 KB

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