1 #!/usr/bin/python 2 3 import sys 4 import re 5 6 header = '''// This file was extracted from the TCG Published 7 // Trusted Platform Module Library 8 // Part 3: Commands 9 // Family "2.0" 10 // Level 00 Revision 01.16 11 // October 30, 2014 12 13 ''' 14 15 head_spaces = re.compile('^\s*[0-9]+\s{0,4}') 16 source_lines = open(sys.argv[1], 'r').read().splitlines() 17 18 def strip_line_num(line): 19 line = head_spaces.sub('', line) 20 return line 21 22 def postprocess_lines(buffer): 23 # get rid of heading line numbers and spaces. 24 buffer = [head_spaces.sub('', x) for x in buffer] 25 26 # Drop the file level conditional compilation statement. 27 for i in range(len(buffer)): 28 if buffer[i].startswith('#include'): 29 continue 30 if buffer[i].startswith( 31 '#ifdef TPM_CC') and buffer[-1].startswith( 32 '#endif // CC_'): 33 buffer = buffer[:i] + buffer[i + 1:-1] 34 break 35 return header + '\n'.join(buffer) + '\n' 36 37 text = [] 38 for line in source_lines: 39 text.append(line) 40 if line == '' and text[-2].startswith('') and text[-5] == '': 42 text = text[:-5] 43 44 func_file = None 45 func_name = '' 46 prev_num = 0 47 line_buffer = [] 48 output_buffer = [] 49 for line in text: 50 f = re.match('^\s*[0-9]+\.[0-9]+\s+(\S+)$', line) 51 if f: 52 func_name = re.sub('^TPM2_', '', f.groups(0)[0]) 53 54 num = re.match('^\s*([0-9]+)[$ ]', line + ' ') 55 if num: 56 line_num = int(num.groups(0)[0]) 57 if line_num == 1: 58 # this is the first line of a file 59 if func_file: 60 func_file.write(postprocess_lines(output_buffer)) 61 func_file.close() 62 func_file = open('%s.c' % func_name, 'w') 63 output_buffer = [line,] 64 prev_num = 1 65 line_buffer = [] 66 continue 67 if line_num == prev_num + 1: 68 if line_buffer: 69 output_buffer.append('\n'.join(line_buffer)) 70 line_buffer = [] 71 output_buffer.append(line) 72 prev_num = line_num 73 continue 74 line_buffer.append('//' + line) 75 76 func_file.write(postprocess_lines(output_buffer)) 77 func_file.close() 78