retarget_glibc_versions.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. parts = name[len("GLIBC_"):].split(".")
  27. if not all(p.isdigit() for p in parts):
  28. return None
  29. return tuple(int(p) for p in parts)
  30. def cstr(data, offset):
  31. return data[offset:data.index(b"\0", offset)]
  32. def retarget(path, floor, provided):
  33. with open(path, "rb") as f:
  34. data = bytearray(f.read())
  35. if data[:4] != b"\x7fELF" or data[4] != 2 or data[5] != 1:
  36. return False
  37. shoff, = struct.unpack_from("<Q", data, 0x28)
  38. shentsize, shnum = struct.unpack_from("<HH", data, 0x3A)
  39. sections = []
  40. for i in range(shnum):
  41. name, stype, flags, addr, offset, size, link, info, align, entsize = struct.unpack_from(
  42. "<IIQQQQIIQQ", data, shoff + i * shentsize)
  43. sections.append({"type": stype, "offset": offset, "size": size, "link": link, "info": info,
  44. "entsize": entsize})
  45. verneed = next((s for s in sections if s["type"] == SHT_GNU_VERNEED), None)
  46. if verneed is None:
  47. return False
  48. strtab = sections[verneed["link"]]["offset"]
  49. base_name = None
  50. newer = {}
  51. offset = verneed["offset"]
  52. for _ in range(verneed["info"]):
  53. vn_version, vn_cnt, vn_file, vn_aux, vn_next = struct.unpack_from("<HHIII", data, offset)
  54. aux = offset + vn_aux
  55. for _ in range(vn_cnt):
  56. vna_hash, vna_flags, vna_other, vna_name, vna_next = struct.unpack_from("<IHHII", data, aux)
  57. name = cstr(data, strtab + vna_name)
  58. if name == BASE_VERSION:
  59. base_name = vna_name
  60. elif name.startswith(b"GLIBC_"):
  61. version = version_tuple(name.decode())
  62. if version is not None and version > floor:
  63. newer[vna_other] = (aux, name.decode())
  64. aux += vna_next
  65. offset += vn_next
  66. if not newer:
  67. return False
  68. if base_name is None:
  69. raise SystemExit(f"{path}: needs {BASE_VERSION.decode()} for the rewrite but doesn't reference it")
  70. dynsym = next(s for s in sections if s["type"] == SHT_DYNSYM)
  71. versym = next(s for s in sections if s["type"] == SHT_GNU_VERSYM)
  72. symstr = sections[dynsym["link"]]["offset"]
  73. for i in range(dynsym["size"] // dynsym["entsize"]):
  74. st_name, st_info, st_other, st_shndx = struct.unpack_from("<IBBH", data, dynsym["offset"] + i * 24)
  75. index, = struct.unpack_from("<H", data, versym["offset"] + i * 2)
  76. index &= 0x7FFF
  77. if index in newer:
  78. symbol = cstr(data, symstr + st_name).decode()
  79. if st_shndx != 0 or symbol not in provided:
  80. raise SystemExit(f"{path}: {symbol}@{newer[index][1]} is newer than GLIBC_{'.'.join(map(str, floor))}"
  81. f" and not in lwe_glibc_compat.c")
  82. for aux, _ in newer.values():
  83. struct.pack_into("<I", data, aux, elf_hash(BASE_VERSION))
  84. struct.pack_into("<I", data, aux + 8, base_name)
  85. with open(path, "wb") as f:
  86. f.write(data)
  87. print(path)
  88. return True
  89. def main():
  90. if len(sys.argv) < 4:
  91. raise SystemExit(__doc__)
  92. floor = version_tuple("GLIBC_" + sys.argv[1])
  93. if floor is None:
  94. raise SystemExit(__doc__)
  95. provided = set(sys.argv[2].split(","))
  96. for path in sys.argv[3:]:
  97. retarget(path, floor, provided)
  98. if __name__ == "__main__":
  99. main()