blob: 80531c0806a7f1f4cdb9ee062ec5d1901c1bf1c2 [file] [log] [blame]
Mikhail Glushenkovb90cd832008-05-06 16:34:12 +00001//===--- Tools.h - The LLVM Compiler Driver ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open
6// Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Action class - implementation and auxiliary functions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Action.h"
15
16#include "llvm/Support/CommandLine.h"
17#include "llvm/System/Program.h"
18
19#include <iostream>
20#include <stdexcept>
21
22using namespace llvm;
Mikhail Glushenkovbe9d9a12008-05-06 18:08:59 +000023using namespace llvmc;
Mikhail Glushenkovb90cd832008-05-06 16:34:12 +000024
25extern cl::opt<bool> VerboseMode;
26
27namespace {
28 int ExecuteProgram(const std::string& name,
Mikhail Glushenkovbe9d9a12008-05-06 18:08:59 +000029 const StringVector& args) {
Mikhail Glushenkovb90cd832008-05-06 16:34:12 +000030 sys::Path prog = sys::Program::FindProgramByName(name);
31
32 if (prog.isEmpty())
33 throw std::runtime_error("Can't find program '" + name + "'");
34 if (!prog.canExecute())
35 throw std::runtime_error("Program '" + name + "' is not executable.");
36
Mikhail Glushenkov87416b42008-05-06 18:10:53 +000037 // Build the command line vector and the redirects array.
Mikhail Glushenkovbe9d9a12008-05-06 18:08:59 +000038 const sys::Path* redirects[3] = {0,0,0};
39 sys::Path stdout_redirect;
Mikhail Glushenkovb90cd832008-05-06 16:34:12 +000040
Mikhail Glushenkovbe9d9a12008-05-06 18:08:59 +000041 std::vector<const char*> argv;
42 argv.reserve((args.size()+2));
43 argv.push_back(name.c_str());
44
45 for (StringVector::const_iterator B = args.begin(), E = args.end();
46 B!=E; ++B) {
47 if (*B == ">") {
48 ++B;
49 stdout_redirect.set(*B);
50 redirects[1] = &stdout_redirect;
51 }
52 else {
53 argv.push_back((*B).c_str());
54 }
55 }
56 argv.push_back(0); // null terminate list.
57
Mikhail Glushenkov35a85e82008-05-06 18:10:20 +000058 // Invoke the program.
Mikhail Glushenkovbe9d9a12008-05-06 18:08:59 +000059 return sys::Program::ExecuteAndWait(prog, &argv[0], 0, &redirects[0]);
Mikhail Glushenkovb90cd832008-05-06 16:34:12 +000060 }
61
62 void print_string (const std::string& str) {
63 std::cerr << str << ' ';
64 }
65}
66
Mikhail Glushenkovbe9d9a12008-05-06 18:08:59 +000067int llvmc::Action::Execute() const {
Mikhail Glushenkovb90cd832008-05-06 16:34:12 +000068 if (VerboseMode) {
69 std::cerr << Command_ << " ";
70 std::for_each(Args_.begin(), Args_.end(), print_string);
71 std::cerr << '\n';
72 }
73 return ExecuteProgram(Command_, Args_);
74}