1#!/usr/bin/env python
2
3"""
4Run llvm-mc interactively.
5
6"""
7
8import os
9import sys
10from optparse import OptionParser
11
12def is_exe(fpath):
13    """Check whether fpath is an executable."""
14    return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
15
16def which(program):
17    """Find the full path to a program, or return None."""
18    fpath, fname = os.path.split(program)
19    if fpath:
20        if is_exe(program):
21            return program
22    else:
23        for path in os.environ["PATH"].split(os.pathsep):
24            exe_file = os.path.join(path, program)
25            if is_exe(exe_file):
26                return exe_file
27    return None
28
29def llvm_mc_loop(mc, mc_options):
30    contents = []
31    fname = 'mc-input.txt'
32    sys.stdout.write("Enter your input to llvm-mc.  A line starting with 'END' terminates the current batch of input.\n")
33    sys.stdout.write("Enter 'quit' or Ctrl-D to quit the program.\n")
34    while True:
35        sys.stdout.write("> ")
36        next = sys.stdin.readline()
37        # EOF => terminate this llvm-mc shell
38        if not next or next.startswith('quit'):
39            sys.stdout.write('\n')
40            sys.exit(0)
41        # 'END' => send the current batch of input to llvm-mc
42        if next.startswith('END'):
43            # Write contents to our file and clear the contents.
44            with open(fname, 'w') as f:
45                f.writelines(contents)
46                # Clear the list: replace all items with an empty list.
47                contents[:] = []
48
49            # Invoke llvm-mc with our newly created file.
50            mc_cmd = '%s %s %s' % (mc, mc_options, fname)
51            sys.stdout.write("Executing command: %s\n" % mc_cmd)
52            os.system(mc_cmd)
53        else:
54            # Keep accumulating our input.
55            contents.append(next)
56
57def main():
58    # This is to set up the Python path to include the pexpect-2.4 dir.
59    # Remember to update this when/if things change.
60    scriptPath = sys.path[0]
61    sys.path.append(os.path.join(scriptPath, os.pardir, os.pardir, 'test', 'pexpect-2.4'))
62
63    parser = OptionParser(usage="""\
64Do llvm-mc interactively within a shell-like environment.  A batch of input is
65submitted to llvm-mc to execute whenever you terminate the current batch by
66inputing a line which starts with 'END'.  Quit the program by either 'quit' or
67Ctrl-D.
68
69Usage: %prog [options]
70""")
71    parser.add_option('-m', '--llvm-mc',
72                      type='string', action='store',
73                      dest='llvm_mc',
74                      help="""The llvm-mc executable full path, if specified.
75                      Otherwise, it must be present in your PATH environment.""")
76
77    parser.add_option('-o', '--options',
78                      type='string', action='store',
79                      dest='llvm_mc_options',
80                      help="""The options passed to 'llvm-mc' command if specified.""")
81
82    opts, args = parser.parse_args()
83
84    llvm_mc = opts.llvm_mc if opts.llvm_mc else which('llvm-mc')
85    if not llvm_mc:
86        parser.print_help()
87        sys.exit(1)
88
89    # This is optional.  For example:
90    # --options='-disassemble -triple=arm-apple-darwin -debug-only=arm-disassembler'
91    llvm_mc_options = opts.llvm_mc_options
92
93    # We have parsed the options.
94    print "llvm-mc:", llvm_mc
95    print "llvm-mc options:", llvm_mc_options
96
97    llvm_mc_loop(llvm_mc, llvm_mc_options)
98
99if __name__ == '__main__':
100    main()
101