relocate_sdk.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. #!/usr/bin/env python
  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():
  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. # pad with zeros
  139. new_ldsocache_path += b("\0") * (sh_size - len(new_ldsocache_path))
  140. # write it back
  141. f.seek(sh_offset)
  142. f.write(new_ldsocache_path)
  143. if sysdirs != "" and sysdirslen != "":
  144. paths = sysdirs.split(b("\0"))
  145. sysdirs = b("")
  146. sysdirslen = b("")
  147. for path in paths:
  148. """ exit the loop when we encounter first empty string """
  149. if path == b(""):
  150. break
  151. new_path = old_prefix.sub(new_prefix, path)
  152. sysdirs += new_path + b("\0")
  153. if arch == 32:
  154. sysdirslen += struct.pack("<L", len(new_path))
  155. else:
  156. sysdirslen += struct.pack("<Q", len(new_path))
  157. """ pad with zeros """
  158. sysdirs += b("\0") * (sysdirs_sect_size - len(sysdirs))
  159. """ write the sections back """
  160. f.seek(sysdirs_off)
  161. f.write(sysdirs)
  162. f.seek(sysdirslen_off)
  163. f.write(sysdirslen)
  164. # MAIN
  165. if len(sys.argv) < 4:
  166. sys.exit(-1)
  167. # In python > 3, strings may also contain Unicode characters. So, convert
  168. # them to bytes
  169. if sys.version_info < (3,):
  170. new_prefix = sys.argv[1]
  171. new_dl_path = sys.argv[2]
  172. else:
  173. new_prefix = sys.argv[1].encode()
  174. new_dl_path = sys.argv[2].encode()
  175. executables_list = sys.argv[3:]
  176. for e in executables_list:
  177. perms = os.stat(e)[stat.ST_MODE]
  178. if os.access(e, os.W_OK|os.R_OK):
  179. perms = None
  180. else:
  181. os.chmod(e, perms|stat.S_IRWXU)
  182. try:
  183. f = open(e, "r+b")
  184. except IOError:
  185. exctype, ioex = sys.exc_info()[:2]
  186. if ioex.errno == errno.ETXTBSY:
  187. print("Could not open %s. File used by another process.\nPlease "\
  188. "make sure you exit all processes that might use any SDK "\
  189. "binaries." % e)
  190. else:
  191. print("Could not open %s: %s(%d)" % (e, ioex.strerror, ioex.errno))
  192. sys.exit(-1)
  193. # Save old size and do a size check at the end. Just a safety measure.
  194. old_size = os.path.getsize(e)
  195. if old_size >= 64:
  196. arch = get_arch()
  197. if arch:
  198. parse_elf_header()
  199. change_interpreter(e)
  200. change_dl_sysdirs()
  201. """ change permissions back """
  202. if perms:
  203. os.chmod(e, perms)
  204. f.close()
  205. if old_size != os.path.getsize(e):
  206. print("New file size for %s is different. Looks like a relocation error!", e)
  207. sys.exit(-1)