c9857b0493d692e43345519b159dd4f9ca742ccd
[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(int Argc, const char **Argv) {
107   SmallVector<const char *, 20> NewArgv(Argv, Argv + Argc);
108   BumpPtrAllocator Alloc;
109   BumpPtrStringSaver Saver(Alloc);
110   cl::ExpandResponseFiles(Saver, cl::TokenizeWindowsCommandLine, NewArgv);
111   Argv = &NewArgv[0];
112   Argc = static_cast<int>(NewArgv.size());
113
114   LibOptTable Table;
115   unsigned MissingIndex;
116   unsigned MissingCount;
117   std::unique_ptr<llvm::opt::InputArgList> Args(
118       Table.ParseArgs(&Argv[1], &Argv[Argc], MissingIndex, MissingCount));
119   if (MissingCount) {
120     llvm::errs() << "missing arg value for \""
121                  << Args->getArgString(MissingIndex)
122                  << "\", expected " << MissingCount
123                  << (MissingCount == 1 ? " argument.\n" : " arguments.\n");
124     return 1;
125   }
126   for (auto *Arg : Args->filtered(OPT_UNKNOWN))
127     llvm::errs() << "ignoring unknown argument: " << Arg->getSpelling() << "\n";
128
129   if (Args->filtered_begin(OPT_INPUT) == Args->filtered_end()) {
130     llvm::errs() << "no input files.\n";
131     return 1;
132   }
133
134   std::vector<StringRef> SearchPaths = getSearchPaths(Args.get(), Saver);
135
136   std::vector<llvm::NewArchiveIterator> Members;
137   for (auto *Arg : Args->filtered(OPT_INPUT)) {
138     Optional<std::string> Path = findInputFile(Arg->getValue(), SearchPaths);
139     if (!Path.hasValue()) {
140       llvm::errs() << Arg->getValue() << ": no such file or directory\n";
141       return 1;
142     }
143     Members.emplace_back(Saver.save(*Path),
144                          llvm::sys::path::filename(Arg->getValue()));
145   }
146
147   std::pair<StringRef, std::error_code> Result = llvm::writeArchive(
148       getOutputPath(Args.get()), Members, /*WriteSymtab=*/true);
149   if (Result.second) {
150     if (Result.first.empty())
151       Result.first = Argv[0];
152     llvm::errs() << Result.first << ": " << Result.second.message() << "\n";
153     return 1;
154   }
155
156   return 0;
157 }