bin: add emerald-alignfix

Fixes static executables to be able to run on device

Signed-off-by: PeroSar <perosar1111@gmail.com>
This commit is contained in:
PeroSar 2022-05-13 16:31:41 +05:30
parent 5d27e221b7
commit 15255af004
Signed by: PeroSar
GPG Key ID: 5C2D258445DA8B58
2 changed files with 57 additions and 0 deletions

View File

@ -46,4 +46,5 @@ Compiled executables should run properly on Android 8 and above.
- Patches from [its-pointless](https://github.com/its-pointless)
- Patches from [Android GCC 4.9](https://android.googlesource.com/toolchain/gcc)
- Sysroot from [NDK](https://github.com/android/ndk)
- Align fix script from [termux-ndk](https://github.com/Lzhiyong/termux-ndk/blob/master/patches/align_fix.py)
- Wiki pages from [Termux](https://github.com/termux)

56
bin/emerald-alignfix Executable file
View File

@ -0,0 +1,56 @@
#!/usr/bin/env python3
import struct
import sys
import os
if len(sys.argv) < 2:
print('Usage: ' + os.path.basename(sys.argv[0]) + ' input_file')
exit()
with open(sys.argv[1], 'r+b') as f:
f.seek(0)
hdr = f.read(16)
if hdr[0] != 0x7f or hdr[1] != ord('E') or hdr[2] != ord('L') or hdr[3] != ord('F'):
raise Exception('Not an elf file')
if hdr[4] == 1:
# 32 bit code
f.seek(28)
offset = struct.unpack('<I', f.read(4))[0]
f.seek(42)
phsize = struct.unpack('<H', f.read(2))[0]
phnum = struct.unpack('<H', f.read(2))[0]
for i in range(0, phnum):
f.seek(offset + i * phsize)
t = struct.unpack('<I', f.read(4))[0]
if t == 7:
f.seek(28 - 4, 1)
align = struct.unpack('<I', f.read(4))[0]
print('Found TLS segment with align = ' + str(align))
if (align < 32):
print('TLS segment is underaligned, patching')
f.seek(-4, 1)
f.write(struct.pack('<I', 32))
elif hdr[4] == 2:
# 64 bit code
f.seek(32)
offset = struct.unpack('<Q', f.read(8))[0]
f.seek(54)
phsize = struct.unpack('<H', f.read(2))[0]
phnum = struct.unpack('<H', f.read(2))[0]
for i in range(0, phnum):
f.seek(offset + i * phsize)
t = struct.unpack('<I', f.read(4))[0]
if t == 7:
f.seek(48 - 4, 1)
align = struct.unpack('<Q', f.read(8))[0]
print('Found TLS segment with align = ' + str(align))
if (align < 64):
print('TLS segment is underaligned, patching')
f.seek(-8, 1)
f.write(struct.pack('<H', 64))
else:
raise Exception('Unknown file class')