Skip to content

Instantly share code, notes, and snippets.

@michaelsproul
Created February 16, 2016 05:34
Show Gist options
  • Save michaelsproul/aa5ed6fc515d45f778ba to your computer and use it in GitHub Desktop.
Save michaelsproul/aa5ed6fc515d45f778ba to your computer and use it in GitHub Desktop.
Insert code after C main function...
#!/usr/bin/env python3
# You probably shouldn't use this, it is guaranteed awful... Although it did work for me...
import re
import os
import sys
MAIN_REGEX = re.compile(rb".*int.*main.*\(.*int.*argc.*\).*")
BRACE_REGEX = re.compile(rb".*{.*")
PREFIX = b'#include "version.h"\n'
PAYLOAD = b"""\tprint_commit_info(argc, argv);\n"""
def main():
filename = sys.argv[1]
looking_for_brace = False
replacement_made = False
result = b""
with open(filename, "rb") as f:
for line in f:
result += line
if MAIN_REGEX.match(line):
looking_for_brace = True
if looking_for_brace and BRACE_REGEX.match(line):
looking_for_brace = False
replacement_made = True
result += PAYLOAD
if replacement_made:
print("Rewriting: " + filename, file=sys.stdout)
with open(filename, "wb") as f:
f.write(PREFIX + result)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment