relocate_sdk.py 8.8 KB

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