gen_header.py 2.1 KB
Newer Older
J
jiakai 已提交
1 2 3 4
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
J
jiakai 已提交
5
import sys
J
jiakai 已提交
6
import subprocess
J
jiakai 已提交
7

J
jiakai 已提交
8
MAGIC = 'midout_trace v1\n'
J
jiakai 已提交
9 10 11 12 13 14 15 16 17 18 19

class MidoutHeaderGen:
    _tag_names = None
    _region_names = None

    def __init__(self):
        self._tag_names = set()
        self._region_names = set()

    def add_item(self, name: str):
        prefix = 'midout::Region<midout::tags::'
J
jiakai 已提交
20
        assert name.startswith(prefix), 'bad name: {!r}'.format(name)
J
jiakai 已提交
21 22 23 24 25
        comma = name.find(',', len(prefix))
        self._tag_names.add(name[len(prefix):comma])
        self._region_names.add(name)

    def write(self, fout):
J
jiakai 已提交
26 27
        print('#define MIDOUT_GENERATED \\', file=fout)
        print('namespace midout { namespace tags { \\', file=fout)
J
jiakai 已提交
28
        for i in sorted(self._tag_names):
J
jiakai 已提交
29 30
            print('class {}; \\'.format(i), file=fout)
        print('} \\', file=fout)
J
jiakai 已提交
31 32 33

        for i in self._region_names:
            i = i.replace('midout::', '')
J
jiakai 已提交
34
            i = i.replace('__ndk1::', '')
J
jiakai 已提交
35 36
            print('template<> \\', file=fout)
            print('struct {} {{ static constexpr bool enable = true; }}; \\'.
J
jiakai 已提交
37 38 39 40 41 42 43 44 45
                  format(i), file=fout)

        print('}', file=fout)


def main():
    parser = argparse.ArgumentParser(
        description='generate header file from midout traces',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
J
jiakai 已提交
46 47
    parser.add_argument('-o', '--output',
                        help='output header file; default to stdout')
J
jiakai 已提交
48 49 50 51 52
    parser.add_argument('inputs', nargs='+', help='input trace files')
    args = parser.parse_args()
    gen = MidoutHeaderGen()
    for i in args.inputs:
        with open(i) as fin:
J
jiakai 已提交
53
            assert fin.read(len(MAGIC)) == MAGIC, 'bad trace file'
J
jiakai 已提交
54 55 56 57 58 59
            demangle = subprocess.check_output(
                ['c++filt', '-t'], input='\n'.join(list(fin)).encode('utf-8'))
            for line in demangle.decode('utf-8').split('\n'):
                line = line.strip()
                if line:
                    gen.add_item(line)
J
jiakai 已提交
60

J
jiakai 已提交
61 62 63 64 65
    if not args.output:
        gen.write(sys.stdout)
    else:
        with open(args.output, 'w') as fout:
            gen.write(fout)
J
jiakai 已提交
66 67 68

if __name__ == '__main__':
    main()