relocate_sdk.py 8.9 KB

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