pupy/client/gen_resource_header.py

94 lines
2.4 KiB
Python
Raw Normal View History

2015-09-21 19:53:37 +00:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
2015-09-21 19:53:37 +00:00
import sys
import binascii
import pylzma
import struct
import os
2015-09-21 19:53:37 +00:00
MAX_CHAR_PER_LINE = 50
2015-09-21 19:53:37 +00:00
ReflectiveLoaderSymName = 'ReflectiveLoader'
if __name__ == "__main__":
h_file = ""
file_bytes = b""
output = os.path.basename(sys.argv[2]).replace('.', '_')
2019-09-07 15:51:30 +00:00
reflective_loader = None
2017-07-02 13:23:33 +00:00
with open(sys.argv[1], "rb") as f:
file_bytes = f.read()
2017-07-02 13:23:33 +00:00
2019-09-07 15:51:30 +00:00
try:
image_base = 0
with open(sys.argv[1]+'.map') as f:
for line in f:
line = line.strip().split()
if len(line) < 4:
continue
if line[1] == '__ImageBase':
image_base = int(line[2], 16)
continue
if line[1] in (ReflectiveLoaderSymName, '_' + ReflectiveLoaderSymName + '@4'):
2019-09-07 15:51:30 +00:00
reflective_loader = int(line[2], 16) - image_base
break
except (OSError, IOError):
pass
compressed = int(sys.argv[3])
2017-07-02 13:23:33 +00:00
attribute = ''
pragma = ''
if len(sys.argv) > 5:
compiler = sys.argv[4]
if compiler == 'cl':
print "USING MSVC pragmas, const_seg: {}".format(sys.argv[5])
attribute = '\n#pragma const_seg(push, stack1, "{}")\n'.format(
sys.argv[5])
pragma = '\n#pragma const_seg(pop, stack1)'
else:
attribute = '\n'.join([
'__attribute__(({}))'.format(x) for x in sys.argv[5:]
])
2017-07-02 13:23:33 +00:00
payload_len = len(file_bytes)
payload = struct.pack('>I', payload_len) + (
pylzma.compress(
file_bytes, dictionary=24, fastBytes=255
) if compressed else file_bytes
)
2019-09-07 15:51:30 +00:00
if reflective_loader:
h_file += "static const size_t %s_loader = 0x%x;\n" % (
output, reflective_loader)
with open(sys.argv[2].rsplit('.', 1)[0] + '.loader', 'w') as w:
w.write(struct.pack('>I', reflective_loader))
h_file += "static const int %s_size = %s;" % (output, len(payload))
2017-07-02 13:23:33 +00:00
h_file += attribute
h_file += "\nstatic const char %s_start[] = {\n" % (output)
current_size = 0
2017-07-02 13:23:33 +00:00
for c in payload:
h_file += "'\\x%s'," % binascii.hexlify(c)
current_size += 1
if current_size > MAX_CHAR_PER_LINE:
current_size = 0
h_file += "\n"
2017-07-02 13:23:33 +00:00
h_file += "'\\x00' };\n"
h_file += pragma
2017-07-02 13:23:33 +00:00
with open(sys.argv[2], 'w') as w:
2017-07-02 13:23:33 +00:00
w.write(h_file)