[DWARF] Fix referencing Range List Tables from CUs for DWARF64.
[llvm-complete.git] / lib / ToolDrivers / llvm-lib / LibDriver.cpp
blob18ab6637305ef629db5ddaeb82867330c749a9e0
1 //===- LibDriver.cpp - lib.exe-compatible driver --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Defines an interface to a lib.exe-compatible driver that also understands
10 // bitcode files. Used by llvm-lib and lld-link /lib.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/BinaryFormat/COFF.h"
17 #include "llvm/BinaryFormat/Magic.h"
18 #include "llvm/Bitcode/BitcodeReader.h"
19 #include "llvm/Object/ArchiveWriter.h"
20 #include "llvm/Object/COFF.h"
21 #include "llvm/Object/WindowsMachineFlag.h"
22 #include "llvm/Option/Arg.h"
23 #include "llvm/Option/ArgList.h"
24 #include "llvm/Option/Option.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/Process.h"
28 #include "llvm/Support/StringSaver.h"
29 #include "llvm/Support/raw_ostream.h"
31 using namespace llvm;
33 namespace {
35 enum {
36 OPT_INVALID = 0,
37 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
38 #include "Options.inc"
39 #undef OPTION
42 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
43 #include "Options.inc"
44 #undef PREFIX
46 static const opt::OptTable::Info InfoTable[] = {
47 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
48 {X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
49 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
50 #include "Options.inc"
51 #undef OPTION
54 class LibOptTable : public opt::OptTable {
55 public:
56 LibOptTable() : OptTable(InfoTable, true) {}
61 static std::string getOutputPath(opt::InputArgList *Args,
62 const NewArchiveMember &FirstMember) {
63 if (auto *Arg = Args->getLastArg(OPT_out))
64 return Arg->getValue();
65 SmallString<128> Val = StringRef(FirstMember.Buf->getBufferIdentifier());
66 sys::path::replace_extension(Val, ".lib");
67 return Val.str();
70 static std::vector<StringRef> getSearchPaths(opt::InputArgList *Args,
71 StringSaver &Saver) {
72 std::vector<StringRef> Ret;
73 // Add current directory as first item of the search path.
74 Ret.push_back("");
76 // Add /libpath flags.
77 for (auto *Arg : Args->filtered(OPT_libpath))
78 Ret.push_back(Arg->getValue());
80 // Add $LIB.
81 Optional<std::string> EnvOpt = sys::Process::GetEnv("LIB");
82 if (!EnvOpt.hasValue())
83 return Ret;
84 StringRef Env = Saver.save(*EnvOpt);
85 while (!Env.empty()) {
86 StringRef Path;
87 std::tie(Path, Env) = Env.split(';');
88 Ret.push_back(Path);
90 return Ret;
93 static std::string findInputFile(StringRef File, ArrayRef<StringRef> Paths) {
94 for (StringRef Dir : Paths) {
95 SmallString<128> Path = Dir;
96 sys::path::append(Path, File);
97 if (sys::fs::exists(Path))
98 return Path.str().str();
100 return "";
103 static void fatalOpenError(llvm::Error E, Twine File) {
104 if (!E)
105 return;
106 handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
107 llvm::errs() << "error opening '" << File << "': " << EIB.message() << '\n';
108 exit(1);
112 static void doList(opt::InputArgList& Args) {
113 // lib.exe prints the contents of the first archive file.
114 std::unique_ptr<MemoryBuffer> B;
115 for (auto *Arg : Args.filtered(OPT_INPUT)) {
116 // Create or open the archive object.
117 ErrorOr<std::unique_ptr<MemoryBuffer>> MaybeBuf =
118 MemoryBuffer::getFile(Arg->getValue(), -1, false);
119 fatalOpenError(errorCodeToError(MaybeBuf.getError()), Arg->getValue());
121 if (identify_magic(MaybeBuf.get()->getBuffer()) == file_magic::archive) {
122 B = std::move(MaybeBuf.get());
123 break;
127 // lib.exe doesn't print an error if no .lib files are passed.
128 if (!B)
129 return;
131 Error Err = Error::success();
132 object::Archive Archive(B.get()->getMemBufferRef(), Err);
133 fatalOpenError(std::move(Err), B->getBufferIdentifier());
135 for (auto &C : Archive.children(Err)) {
136 Expected<StringRef> NameOrErr = C.getName();
137 fatalOpenError(NameOrErr.takeError(), B->getBufferIdentifier());
138 StringRef Name = NameOrErr.get();
139 llvm::outs() << Name << '\n';
141 fatalOpenError(std::move(Err), B->getBufferIdentifier());
144 int llvm::libDriverMain(ArrayRef<const char *> ArgsArr) {
145 BumpPtrAllocator Alloc;
146 StringSaver Saver(Alloc);
148 // Parse command line arguments.
149 SmallVector<const char *, 20> NewArgs(ArgsArr.begin(), ArgsArr.end());
150 cl::ExpandResponseFiles(Saver, cl::TokenizeWindowsCommandLine, NewArgs);
151 ArgsArr = NewArgs;
153 LibOptTable Table;
154 unsigned MissingIndex;
155 unsigned MissingCount;
156 opt::InputArgList Args =
157 Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount);
158 if (MissingCount) {
159 llvm::errs() << "missing arg value for \""
160 << Args.getArgString(MissingIndex) << "\", expected "
161 << MissingCount
162 << (MissingCount == 1 ? " argument.\n" : " arguments.\n");
163 return 1;
165 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
166 llvm::errs() << "ignoring unknown argument: " << Arg->getAsString(Args)
167 << "\n";
169 // Handle /help
170 if (Args.hasArg(OPT_help)) {
171 Table.PrintHelp(outs(), "llvm-lib [options] file...", "LLVM Lib");
172 return 0;
175 // If no input files, silently do nothing to match lib.exe.
176 if (!Args.hasArgNoClaim(OPT_INPUT))
177 return 0;
179 if (Args.hasArg(OPT_lst)) {
180 doList(Args);
181 return 0;
184 std::vector<StringRef> SearchPaths = getSearchPaths(&Args, Saver);
186 COFF::MachineTypes LibMachine = COFF::IMAGE_FILE_MACHINE_UNKNOWN;
187 std::string LibMachineSource;
188 if (auto *Arg = Args.getLastArg(OPT_machine)) {
189 LibMachine = getMachineType(Arg->getValue());
190 if (LibMachine == COFF::IMAGE_FILE_MACHINE_UNKNOWN) {
191 llvm::errs() << "unknown /machine: arg " << Arg->getValue() << '\n';
192 return 1;
194 LibMachineSource =
195 std::string(" (from '/machine:") + Arg->getValue() + "' flag)";
198 // Create a NewArchiveMember for each input file.
199 std::vector<NewArchiveMember> Members;
200 for (auto *Arg : Args.filtered(OPT_INPUT)) {
201 std::string Path = findInputFile(Arg->getValue(), SearchPaths);
202 if (Path.empty()) {
203 llvm::errs() << Arg->getValue() << ": no such file or directory\n";
204 return 1;
207 Expected<NewArchiveMember> MOrErr =
208 NewArchiveMember::getFile(Saver.save(Path), /*Deterministic=*/true);
209 if (!MOrErr) {
210 handleAllErrors(MOrErr.takeError(), [&](const ErrorInfoBase &EIB) {
211 llvm::errs() << Arg->getValue() << ": " << EIB.message() << "\n";
213 return 1;
216 file_magic Magic = identify_magic(MOrErr->Buf->getBuffer());
217 if (Magic != file_magic::coff_object && Magic != file_magic::bitcode &&
218 Magic != file_magic::windows_resource) {
219 llvm::errs() << Arg->getValue()
220 << ": not a COFF object, bitcode or resource file\n";
221 return 1;
224 // Check that all input files have the same machine type.
225 // Mixing normal objects and LTO bitcode files is fine as long as they
226 // have the same machine type.
227 // Doing this here duplicates the header parsing work that writeArchive()
228 // below does, but it's not a lot of work and it's a bit awkward to do
229 // in writeArchive() which needs to support many tools, can't assume the
230 // input is COFF, and doesn't have a good way to report errors.
231 COFF::MachineTypes FileMachine = COFF::IMAGE_FILE_MACHINE_UNKNOWN;
232 if (Magic == file_magic::coff_object) {
233 std::error_code EC;
234 object::COFFObjectFile Obj(*MOrErr->Buf, EC);
235 if (EC) {
236 llvm::errs() << Arg->getValue() << ": failed to open: " << EC.message()
237 << '\n';
238 return 1;
240 uint16_t Machine = Obj.getMachine();
241 if (Machine != COFF::IMAGE_FILE_MACHINE_I386 &&
242 Machine != COFF::IMAGE_FILE_MACHINE_AMD64 &&
243 Machine != COFF::IMAGE_FILE_MACHINE_ARMNT &&
244 Machine != COFF::IMAGE_FILE_MACHINE_ARM64) {
245 llvm::errs() << Arg->getValue() << ": unknown machine: " << Machine
246 << '\n';
247 return 1;
249 FileMachine = static_cast<COFF::MachineTypes>(Machine);
250 } else if (Magic == file_magic::bitcode) {
251 Expected<std::string> TripleStr = getBitcodeTargetTriple(*MOrErr->Buf);
252 if (!TripleStr) {
253 llvm::errs() << Arg->getValue()
254 << ": failed to get target triple from bitcode\n";
255 return 1;
257 switch (Triple(*TripleStr).getArch()) {
258 case Triple::x86:
259 FileMachine = COFF::IMAGE_FILE_MACHINE_I386;
260 break;
261 case Triple::x86_64:
262 FileMachine = COFF::IMAGE_FILE_MACHINE_AMD64;
263 break;
264 case Triple::arm:
265 FileMachine = COFF::IMAGE_FILE_MACHINE_ARMNT;
266 break;
267 case Triple::aarch64:
268 FileMachine = COFF::IMAGE_FILE_MACHINE_ARM64;
269 break;
270 default:
271 llvm::errs() << Arg->getValue() << ": unknown arch in target triple "
272 << *TripleStr << '\n';
273 return 1;
277 // FIXME: Once lld-link rejects multiple resource .obj files:
278 // Call convertResToCOFF() on .res files and add the resulting
279 // COFF file to the .lib output instead of adding the .res file, and remove
280 // this check. See PR42180.
281 if (FileMachine != COFF::IMAGE_FILE_MACHINE_UNKNOWN) {
282 if (LibMachine == COFF::IMAGE_FILE_MACHINE_UNKNOWN) {
283 LibMachine = FileMachine;
284 LibMachineSource = std::string(" (inferred from earlier file '") +
285 Arg->getValue() + "')";
286 } else if (LibMachine != FileMachine) {
287 llvm::errs() << Arg->getValue() << ": file machine type "
288 << machineToStr(FileMachine)
289 << " conflicts with library machine type "
290 << machineToStr(LibMachine) << LibMachineSource << '\n';
291 return 1;
295 Members.emplace_back(std::move(*MOrErr));
298 // Create an archive file.
299 std::string OutputPath = getOutputPath(&Args, Members[0]);
300 // llvm-lib uses relative paths for both regular and thin archives, unlike
301 // standard GNU ar, which only uses relative paths for thin archives and
302 // basenames for regular archives.
303 for (NewArchiveMember &Member : Members) {
304 if (sys::path::is_relative(Member.MemberName)) {
305 Expected<std::string> PathOrErr =
306 computeArchiveRelativePath(OutputPath, Member.MemberName);
307 if (PathOrErr)
308 Member.MemberName = Saver.save(*PathOrErr);
312 if (Error E =
313 writeArchive(OutputPath, Members,
314 /*WriteSymtab=*/true, object::Archive::K_GNU,
315 /*Deterministic*/ true, Args.hasArg(OPT_llvmlibthin))) {
316 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
317 llvm::errs() << OutputPath << ": " << EI.message() << "\n";
319 return 1;
322 return 0;