#!/usr/bin/env python1#2# Patches the malloc() function in libmalloc.so to allocate more than the3# specified number of bytes. This is needed to work around issues with the4# compiler occasionally crashing.5#6# This script replaces the "move a1, a0" (00 80 28 25) instruction with7# "addiu a1, a0, n" (24 85 nn nn), which causes the malloc function to add n to8# the size parameter that was passed in.910import hashlib11import os.path12import sys1314# file to patch15filename = 'tools/ido5.3_compiler/lib/libmalloc.so'16# Expected (unpatched) hash of file17filehash = 'adde672b5d79b52ca3cce9a47c7cb648'18# location in file to patch19address = 0xAB42021# Get parameter22if len(sys.argv) != 2:23print('Usage: ' + sys.argv[0] + ' n\n where n is the number of extra bytes to allocate in malloc()')24exit(1)25n = int(sys.argv[1])2627# Original instruction "move a1, a0"28oldinsn = bytearray([0x00, 0x80, 0x28, 0x25])2930# New instruction "addiu a1, a0, n"31newinsn = bytearray([0x24, 0x85, (n >> 8) & 0xFF, (n & 0xFF)])3233# Patch the file34try:35with open(filename, 'rb+') as f:36# Read file contents37contents = bytearray(f.read())3839# Unpatch the file by restoring original instruction40contents[address:address+4] = oldinsn4142# Verify the (unpatched) hash of the file43md5 = hashlib.md5()44md5.update(contents)45if md5.hexdigest() != filehash:46print('Error: ' + filename + ' does not appear to be the correct version.')47exit(1)4849# Patch the file50if n != 0:51contents[address:address+4] = newinsn5253# Write file54f.seek(0, os.SEEK_SET)55f.write(contents)56except IOError as e:57print('Error: Could not open library file for writing: ' + str(e))585960