relocate_sdk.py 8.9 KB

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