1#!/usr/bin/env python3
2
3# Automatically formatted with yapf (https://github.com/google/yapf)
4
5# Fake 'opt' program that can be made to crash on request. For testing
6# the 'reduce_pipeline.py' automatic 'opt' NPM pipeline reducer.
7
8import argparse
9import os
10import shutil
11import signal
12
13parser = argparse.ArgumentParser()
14parser.add_argument('-passes', action='store', dest='passes', required=True)
15parser.add_argument('-print-pipeline-passes',
16                    dest='print_pipeline_passes',
17                    action='store_true')
18parser.add_argument('-crash-seq',
19                    action='store',
20                    dest='crash_seq',
21                    required=True)
22parser.add_argument('-o', action='store', dest='output')
23parser.add_argument('input')
24[args, unknown_args] = parser.parse_known_args()
25
26# Expand pipeline if '-print-pipeline-passes'.
27if args.print_pipeline_passes:
28    if args.passes == 'EXPAND_a_to_f':
29        print('a,b,c,d,e,f')
30    else:
31        print(args.passes)
32    exit(0)
33
34# Parse '-crash-seq'.
35crash_seq = []
36tok = ''
37for c in args.crash_seq:
38    if c == ',':
39        if tok != '':
40            crash_seq.append(tok)
41        tok = ''
42    else:
43        tok += c
44if tok != '':
45    crash_seq.append(tok)
46print(crash_seq)
47
48# Parse '-passes' and see if we need to crash.
49tok = ''
50for c in args.passes:
51    if c == ',':
52        if len(crash_seq) > 0 and crash_seq[0] == tok:
53            crash_seq.pop(0)
54        tok = ''
55    elif c == '(':
56        tok = ''
57    elif c == ')':
58        if len(crash_seq) > 0 and crash_seq[0] == tok:
59            crash_seq.pop(0)
60        tok = ''
61    else:
62        tok += c
63if len(crash_seq) > 0 and crash_seq[0] == tok:
64    crash_seq.pop(0)
65
66# Copy input to output.
67if args.output:
68    shutil.copy(args.input, args.output)
69
70# Crash if all 'crash_seq' passes occurred in right order.
71if len(crash_seq) == 0:
72    print('crash')
73    os.kill(os.getpid(), signal.SIGKILL)
74else:
75    print('no crash')
76    exit(0)
77