generate_c_testbench.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/env python
  2. import argparse
  3. import re
  4. import random
  5. import string
  6. def parse_memory_trace(input_file, output_file):
  7. active_memory_requests = {}
  8. malloc_pattern = re.compile(r'dmmlib - m (0x\w+) (\d+)')
  9. free_pattern = re.compile(r'dmmlib - f (0x\w+)')
  10. for line in input_file:
  11. malloc_match = malloc_pattern.search(line)
  12. if malloc_match:
  13. if malloc_match.group(1) not in active_memory_requests:
  14. active_memory_requests[malloc_match.group(1)] = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(6))
  15. variable_declaration = ''.join([' void *var_', active_memory_requests[malloc_match.group(1)], ';\n'])
  16. output_file.write(variable_declaration)
  17. new_line = ''.join([' var_', active_memory_requests[malloc_match.group(1)], ' = malloc(', malloc_match.group(2), ');\n'])
  18. output_file.write(new_line)
  19. free_match = free_pattern.search(line)
  20. if free_match:
  21. if free_match.group(1) in active_memory_requests:
  22. new_line = ''.join([' free(var_', active_memory_requests[free_match.group(1)], ');\n'])
  23. del active_memory_requests[free_match.group(1)]
  24. output_file.write(new_line)
  25. else:
  26. print "Warning: free call without an actual allocation beforehands"
  27. input_file.close()
  28. def main():
  29. parser = argparse.ArgumentParser(
  30. description='''Generate a C file of dynamic memory operations from a dmmlib
  31. trace''')
  32. parser.add_argument('tracefile', type=argparse.FileType('rt'),
  33. help='dmmlib trace from the application')
  34. parser.add_argument('-o', '--output', metavar='outputfile', type=argparse.FileType('wt'),
  35. help='generated C file, will use output.c if not available')
  36. try:
  37. args = parser.parse_args()
  38. except IOError, msg:
  39. parser.error(str(msg))
  40. if args.output is None:
  41. args.output = open('output.c', 'wt')
  42. template_file = open('benchmark_template.c', 'rt')
  43. for line in template_file:
  44. if line == '$instructions\n':
  45. parse_memory_trace(args.tracefile, args.output)
  46. else:
  47. args.output.write(line)
  48. args.output.close()
  49. if __name__ == "__main__":
  50. main()