retarget_glibc_versions.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. #!/usr/bin/env python3
  2. """Lowers a shared library's glibc requirement for symbols lwe_glibc_compat.c provides.
  3. usage: retarget_glibc_versions.py <floor> <provided symbols, comma separated> <library>...
  4. Every GLIBC_x version a library needs that is newer than <floor> (e.g. 2.35) is rewritten in its version needs
  5. (.gnu.version_r) to GLIBC_2.2.5, which every x86_64 glibc defines, so the loader no longer refuses it on an older
  6. glibc. The symbols bound to that version then can't match libc's own versioned copies and bind to the next
  7. unversioned definition in the global scope, the compat library (add it as a dependency with patchelf). Refuses
  8. when an undefined symbol of such a version isn't in the provided list. Prints the libraries it changed.
  9. """
  10. import struct
  11. import sys
  12. SHT_DYNSYM = 11
  13. SHT_GNU_VERNEED = 0x6FFFFFFE
  14. SHT_GNU_VERSYM = 0x6FFFFFFF
  15. BASE_VERSION = b"GLIBC_2.2.5"
  16. def elf_hash(name):
  17. h = 0
  18. for c in name:
  19. h = (h << 4) + c
  20. g = h & 0xF0000000
  21. if g:
  22. h ^= g >> 24
  23. h &= ~g & 0xFFFFFFFF
  24. return h
  25. def version_tuple(name):
  26. return tuple(int(p) for p in name[len("GLIBC_"):].split("."))
  27. def cstr(data, offset):
  28. return data[offset:data.index(b"\0", offset)]
  29. def retarget(path, floor, provided):
  30. with open(path, "rb") as f:
  31. data = bytearray(f.read())
  32. if data[:4] != b"\x7fELF" or data[4] != 2 or data[5] != 1:
  33. return False
  34. shoff, = struct.unpack_from("<Q", data, 0x28)
  35. shentsize, shnum = struct.unpack_from("<HH", data, 0x3A)
  36. sections = []
  37. for i in range(shnum):
  38. name, stype, flags, addr, offset, size, link, info, align, entsize = struct.unpack_from(
  39. "<IIQQQQIIQQ", data, shoff + i * shentsize)
  40. sections.append({"type": stype, "offset": offset, "size": size, "link": link, "info": info,
  41. "entsize": entsize})
  42. verneed = next((s for s in sections if s["type"] == SHT_GNU_VERNEED), None)
  43. if verneed is None:
  44. return False
  45. strtab = sections[verneed["link"]]["offset"]
  46. # vernaux entries of libc.so.6 newer than the floor, and where GLIBC_2.2.5's name sits in .dynstr
  47. base_name = None
  48. newer = {}
  49. offset = verneed["offset"]
  50. for _ in range(verneed["info"]):
  51. vn_version, vn_cnt, vn_file, vn_aux, vn_next = struct.unpack_from("<HHIII", data, offset)
  52. aux = offset + vn_aux
  53. for _ in range(vn_cnt):
  54. vna_hash, vna_flags, vna_other, vna_name, vna_next = struct.unpack_from("<IHHII", data, aux)
  55. name = cstr(data, strtab + vna_name)
  56. if name == BASE_VERSION:
  57. base_name = vna_name
  58. elif name.startswith(b"GLIBC_") and version_tuple(name.decode()) > floor:
  59. newer[vna_other] = (aux, name.decode())
  60. aux += vna_next
  61. offset += vn_next
  62. if not newer:
  63. return False
  64. if base_name is None:
  65. raise SystemExit(f"{path}: needs {BASE_VERSION.decode()} for the rewrite but doesn't reference it")
  66. dynsym = next(s for s in sections if s["type"] == SHT_DYNSYM)
  67. versym = next(s for s in sections if s["type"] == SHT_GNU_VERSYM)
  68. symstr = sections[dynsym["link"]]["offset"]
  69. for i in range(dynsym["size"] // dynsym["entsize"]):
  70. st_name, st_info, st_other, st_shndx = struct.unpack_from("<IBBH", data, dynsym["offset"] + i * 24)
  71. index, = struct.unpack_from("<H", data, versym["offset"] + i * 2)
  72. index &= 0x7FFF
  73. if index in newer:
  74. symbol = cstr(data, symstr + st_name).decode()
  75. if st_shndx != 0 or symbol not in provided:
  76. raise SystemExit(f"{path}: {symbol}@{newer[index][1]} is newer than GLIBC_{'.'.join(map(str, floor))}"
  77. f" and not in lwe_glibc_compat.c")
  78. for aux, _ in newer.values():
  79. struct.pack_into("<I", data, aux, elf_hash(BASE_VERSION))
  80. struct.pack_into("<I", data, aux + 8, base_name)
  81. with open(path, "wb") as f:
  82. f.write(data)
  83. print(path)
  84. return True
  85. def main():
  86. if len(sys.argv) < 4:
  87. raise SystemExit(__doc__)
  88. floor = version_tuple("GLIBC_" + sys.argv[1])
  89. provided = set(sys.argv[2].split(","))
  90. for path in sys.argv[3:]:
  91. retarget(path, floor, provided)
  92. if __name__ == "__main__":
  93. main()