e441fe84c39b673fdf891f87d17444a9ba3f32b9
[oota-llvm.git] / lib / LibDriver / LibDriver.cpp
1 //===- LibDriver.cpp - lib.exe-compatible driver --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Defines an interface to a lib.exe-compatible driver that also understands
11 // bitcode files. Used by llvm-lib and lld-link2 /lib.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/LibDriver/LibDriver.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Object/ArchiveWriter.h"
18 #include "llvm/Option/Arg.h"
19 #include "llvm/Option/ArgList.h"
20 #include "llvm/Option/Option.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/StringSaver.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/Process.h"
25 #include "llvm/Support/raw_ostream.h"
26
27 using namespace llvm;
28
29 namespace {
30
31 enum {
32   OPT_INVALID = 0,
33 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11) OPT_##ID,
34 #include "Options.inc"
35 #undef OPTION
36 };
37
38 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
39 #include "Options.inc"
40 #undef PREFIX
41
42 static const llvm::opt::OptTable::Info infoTable[] = {
43 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X6, X7, X8, X9, X10)    \
44   {                                                                    \
45     X1, X2, X9, X10, OPT_##ID, llvm::opt::Option::KIND##Class, X8, X7, \
46     OPT_##GROUP, OPT_##ALIAS, X6                                       \
47   },
48 #include "Options.inc"
49 #undef OPTION
50 };
51
52 class LibOptTable : public llvm::opt::OptTable {
53 public:
54   LibOptTable() : OptTable(infoTable, llvm::array_lengthof(infoTable), true) {}
55 };
56
57 } // namespace
58
59 static std::string getOutputPath(llvm::opt::InputArgList *Args) {
60   if (auto *Arg = Args->getLastArg(OPT_out))
61     return Arg->getValue();
62   for (auto *Arg : Args->filtered(OPT_INPUT)) {
63     if (!StringRef(Arg->getValue()).endswith_lower(".obj"))
64       continue;
65     SmallString<128> Val = StringRef(Arg->getValue());
66     llvm::sys::path::replace_extension(Val, ".lib");
67     return Val.str();
68   }
69   llvm_unreachable("internal error");
70 }
71
72 static std::vector<StringRef> getSearchPaths(llvm::opt::InputArgList *Args,
73                                              StringSaver &Saver) {
74   std::vector<StringRef> Ret;
75   // Add current directory as first item of the search path.
76   Ret.push_back("");
77
78   // Add /libpath flags.
79   for (auto *Arg : Args->filtered(OPT_libpath))
80     Ret.push_back(Arg->getValue());
81
82   // Add $LIB.
83   Optional<std::string> EnvOpt = sys::Process::GetEnv("LIB");
84   if (!EnvOpt.hasValue())
85     return Ret;
86   StringRef Env = Saver.save(*EnvOpt);
87   while (!Env.empty()) {
88     StringRef Path;
89     std::tie(Path, Env) = Env.split(';');
90     Ret.push_back(Path);
91   }
92   return Ret;
93 }
94
95 static Optional<std::string> findInputFile(StringRef File,
96                                            ArrayRef<StringRef> Paths) {
97   for (auto Dir : Paths) {
98     SmallString<128> Path = Dir;
99     sys::path::append(Path, File);
100     if (sys::fs::exists(Path))
101       return Path.str().str();
102   }
103   return Optional<std::string>();
104 }
105
106 int llvm::libDriverMain(llvm::ArrayRef<const char*> ArgsArr) {
107   SmallVector<const char *, 20> NewArgs(ArgsArr.begin(), ArgsArr.end());
108   BumpPtrAllocator Alloc;
109   BumpPtrStringSaver Saver(Alloc);
110   cl::ExpandResponseFiles(Saver, cl::TokenizeWindowsCommandLine, NewArgs);
111   ArgsArr = NewArgs;
112
113   LibOptTable Table;
114   unsigned MissingIndex;
115   unsigned MissingCount;
116   std::unique_ptr<llvm::opt::InputArgList> Args(
117       Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount));
118   if (MissingCount) {
119     llvm::errs() << "missing arg value for \""
120                  << Args->getArgString(MissingIndex)
121                  << "\", expected " << MissingCount
122                  << (MissingCount == 1 ? " argument.\n" : " arguments.\n");
123     return 1;
124   }
125   for (auto *Arg : Args->filtered(OPT_UNKNOWN))
126     llvm::errs() << "ignoring unknown argument: " << Arg->getSpelling() << "\n";
127
128   if (Args->filtered_begin(OPT_INPUT) == Args->filtered_end()) {
129     llvm::errs() << "no input files.\n";
130     return 1;
131   }
132
133   std::vector<StringRef> SearchPaths = getSearchPaths(Args.get(), Saver);
134
135   std::vector<llvm::NewArchiveIterator> Members;
136   for (auto *Arg : Args->filtered(OPT_INPUT)) {
137     Optional<std::string> Path = findInputFile(Arg->getValue(), SearchPaths);
138     if (!Path.hasValue()) {
139       llvm::errs() << Arg->getValue() << ": no such file or directory\n";
140       return 1;
141     }
142     Members.emplace_back(Saver.save(*Path),
143                          llvm::sys::path::filename(Arg->getValue()));
144   }
145
146   std::pair<StringRef, std::error_code> Result = llvm::writeArchive(
147       getOutputPath(Args.get()), Members, /*WriteSymtab=*/true);
148   if (Result.second) {
149     if (Result.first.empty())
150       Result.first = ArgsArr[0];
151     llvm::errs() << Result.first << ": " << Result.second.message() << "\n";
152     return 1;
153   }
154
155   return 0;
156 }