relocate_sdk.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. break
  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. def change_dl_sysdirs(elf_file_name):
  93. if arch == 32:
  94. sh_fmt = "<IIIIIIIIII"
  95. else:
  96. sh_fmt = "<IIQQQQIIQQ"
  97. """ read section string table """
  98. f.seek(e_shoff + e_shstrndx * e_shentsize)
  99. sh_hdr = f.read(e_shentsize)
  100. if arch == 32:
  101. sh_offset, sh_size = struct.unpack("<16xII16x", sh_hdr)
  102. else:
  103. sh_offset, sh_size = struct.unpack("<24xQQ24x", sh_hdr)
  104. f.seek(sh_offset)
  105. sh_strtab = f.read(sh_size)
  106. sysdirs = sysdirs_len = ""
  107. """ change ld.so.cache path and default libs path for dynamic loader """
  108. for i in range(0,e_shnum):
  109. f.seek(e_shoff + i * e_shentsize)
  110. sh_hdr = f.read(e_shentsize)
  111. sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size, sh_link,\
  112. sh_info, sh_addralign, sh_entsize = struct.unpack(sh_fmt, sh_hdr)
  113. name = sh_strtab[sh_name:sh_strtab.find(b("\0"), sh_name)]
  114. """ look only into SHT_PROGBITS sections """
  115. if sh_type == 1:
  116. f.seek(sh_offset)
  117. """ default library paths cannot be changed on the fly because """
  118. """ the string lengths have to be changed too. """
  119. if name == b(".sysdirs"):
  120. sysdirs = f.read(sh_size)
  121. sysdirs_off = sh_offset
  122. sysdirs_sect_size = sh_size
  123. elif name == b(".sysdirslen"):
  124. sysdirslen = f.read(sh_size)
  125. sysdirslen_off = sh_offset
  126. elif name == b(".ldsocache"):
  127. ldsocache_path = f.read(sh_size)
  128. new_ldsocache_path = old_prefix.sub(new_prefix, ldsocache_path)
  129. new_ldsocache_path = new_ldsocache_path.rstrip(b("\0"))
  130. if (len(new_ldsocache_path) >= sh_size):
  131. print("ERROR: could not relocate %s, .ldsocache section size = %i and %i is needed." \
  132. % (elf_file_name, sh_size, len(new_ldsocache_path)))
  133. sys.exit(-1)
  134. # pad with zeros
  135. new_ldsocache_path += b("\0") * (sh_size - len(new_ldsocache_path))
  136. # write it back
  137. f.seek(sh_offset)
  138. f.write(new_ldsocache_path)
  139. elif name == b(".gccrelocprefix"):
  140. offset = 0
  141. while (offset + 4096) <= sh_size:
  142. path = f.read(4096)
  143. new_path = old_prefix.sub(new_prefix, path)
  144. new_path = new_path.rstrip(b("\0"))
  145. if (len(new_path) >= 4096):
  146. print("ERROR: could not relocate %s, max path size = 4096 and %i is needed." \
  147. % (elf_file_name, len(new_path)))
  148. sys.exit(-1)
  149. # pad with zeros
  150. new_path += b("\0") * (4096 - len(new_path))
  151. #print "Changing %s to %s at %s" % (str(path), str(new_path), str(offset))
  152. # write it back
  153. f.seek(sh_offset + offset)
  154. f.write(new_path)
  155. offset = offset + 4096
  156. if sysdirs != "" and sysdirslen != "":
  157. paths = sysdirs.split(b("\0"))
  158. sysdirs = b("")
  159. sysdirslen = b("")
  160. for path in paths:
  161. """ exit the loop when we encounter first empty string """
  162. if path == b(""):
  163. break
  164. new_path = old_prefix.sub(new_prefix, path)
  165. sysdirs += new_path + b("\0")
  166. if arch == 32:
  167. sysdirslen += struct.pack("<L", len(new_path))
  168. else:
  169. sysdirslen += struct.pack("<Q", len(new_path))
  170. """ pad with zeros """
  171. sysdirs += b("\0") * (sysdirs_sect_size - len(sysdirs))
  172. """ write the sections back """
  173. f.seek(sysdirs_off)
  174. f.write(sysdirs)
  175. f.seek(sysdirslen_off)
  176. f.write(sysdirslen)
  177. # MAIN
  178. if len(sys.argv) < 4:
  179. sys.exit(-1)
  180. # In python > 3, strings may also contain Unicode characters. So, convert
  181. # them to bytes
  182. if sys.version_info < (3,):
  183. new_prefix = sys.argv[1]
  184. new_dl_path = sys.argv[2]
  185. else:
  186. new_prefix = sys.argv[1].encode()
  187. new_dl_path = sys.argv[2].encode()
  188. executables_list = sys.argv[3:]
  189. for e in executables_list:
  190. perms = os.stat(e)[stat.ST_MODE]
  191. if os.access(e, os.W_OK|os.R_OK):
  192. perms = None
  193. else:
  194. os.chmod(e, perms|stat.S_IRWXU)
  195. try:
  196. f = open(e, "r+b")
  197. except IOError:
  198. exctype, ioex = sys.exc_info()[:2]
  199. if ioex.errno == errno.ETXTBSY:
  200. print("Could not open %s. File used by another process.\nPlease "\
  201. "make sure you exit all processes that might use any SDK "\
  202. "binaries." % e)
  203. else:
  204. print("Could not open %s: %s(%d)" % (e, ioex.strerror, ioex.errno))
  205. sys.exit(-1)
  206. # Save old size and do a size check at the end. Just a safety measure.
  207. old_size = os.path.getsize(e)
  208. if old_size >= 64:
  209. arch = get_arch()
  210. if arch:
  211. parse_elf_header()
  212. change_interpreter(e)
  213. change_dl_sysdirs(e)
  214. """ change permissions back """
  215. if perms:
  216. os.chmod(e, perms)
  217. f.close()
  218. if old_size != os.path.getsize(e):
  219. print("New file size for %s is different. Looks like a relocation error!", e)
  220. sys.exit(-1)