xref: /llvm-project/llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp (revision c2dd61279764c9e525b73d37dae58ed77b773b1d)
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.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringSet.h"
17 #include "llvm/BinaryFormat/COFF.h"
18 #include "llvm/BinaryFormat/Magic.h"
19 #include "llvm/Bitcode/BitcodeReader.h"
20 #include "llvm/Object/ArchiveWriter.h"
21 #include "llvm/Object/COFF.h"
22 #include "llvm/Object/COFFModuleDefinition.h"
23 #include "llvm/Object/WindowsMachineFlag.h"
24 #include "llvm/Option/Arg.h"
25 #include "llvm/Option/ArgList.h"
26 #include "llvm/Option/OptTable.h"
27 #include "llvm/Option/Option.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/Process.h"
31 #include "llvm/Support/StringSaver.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <optional>
34 
35 using namespace llvm;
36 using namespace llvm::object;
37 
38 namespace {
39 
40 #define OPTTABLE_STR_TABLE_CODE
41 #include "Options.inc"
42 #undef OPTTABLE_STR_TABLE_CODE
43 
44 enum {
45   OPT_INVALID = 0,
46 #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
47 #include "Options.inc"
48 #undef OPTION
49 };
50 
51 #define OPTTABLE_PREFIXES_TABLE_CODE
52 #include "Options.inc"
53 #undef OPTTABLE_PREFIXES_TABLE_CODE
54 
55 using namespace llvm::opt;
56 static constexpr opt::OptTable::Info InfoTable[] = {
57 #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
58 #include "Options.inc"
59 #undef OPTION
60 };
61 
62 class LibOptTable : public opt::GenericOptTable {
63 public:
64   LibOptTable()
65       : opt::GenericOptTable(OptionStrTable, OptionPrefixesTable, InfoTable,
66                              true) {}
67 };
68 } // namespace
69 
70 static std::string getDefaultOutputPath(const NewArchiveMember &FirstMember) {
71   SmallString<128> Val = StringRef(FirstMember.Buf->getBufferIdentifier());
72   sys::path::replace_extension(Val, ".lib");
73   return std::string(Val);
74 }
75 
76 static std::vector<StringRef> getSearchPaths(opt::InputArgList *Args,
77                                              StringSaver &Saver) {
78   std::vector<StringRef> Ret;
79   // Add current directory as first item of the search path.
80   Ret.push_back("");
81 
82   // Add /libpath flags.
83   for (auto *Arg : Args->filtered(OPT_libpath))
84     Ret.push_back(Arg->getValue());
85 
86   // Add $LIB.
87   std::optional<std::string> EnvOpt = sys::Process::GetEnv("LIB");
88   if (!EnvOpt)
89     return Ret;
90   StringRef Env = Saver.save(*EnvOpt);
91   while (!Env.empty()) {
92     StringRef Path;
93     std::tie(Path, Env) = Env.split(';');
94     Ret.push_back(Path);
95   }
96   return Ret;
97 }
98 
99 // Opens a file. Path has to be resolved already. (used for def file)
100 std::unique_ptr<MemoryBuffer> openFile(const Twine &Path) {
101   ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MB =
102       MemoryBuffer::getFile(Path, /*IsText=*/true);
103 
104   if (std::error_code EC = MB.getError()) {
105     llvm::errs() << "cannot open file " << Path << ": " << EC.message() << "\n";
106     return nullptr;
107   }
108 
109   return std::move(*MB);
110 }
111 
112 static std::string findInputFile(StringRef File, ArrayRef<StringRef> Paths) {
113   for (StringRef Dir : Paths) {
114     SmallString<128> Path = Dir;
115     sys::path::append(Path, File);
116     if (sys::fs::exists(Path))
117       return std::string(Path);
118   }
119   return "";
120 }
121 
122 static void fatalOpenError(llvm::Error E, Twine File) {
123   if (!E)
124     return;
125   handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
126     llvm::errs() << "error opening '" << File << "': " << EIB.message() << '\n';
127     exit(1);
128   });
129 }
130 
131 static void doList(opt::InputArgList &Args) {
132   // lib.exe prints the contents of the first archive file.
133   std::unique_ptr<MemoryBuffer> B;
134   for (auto *Arg : Args.filtered(OPT_INPUT)) {
135     // Create or open the archive object.
136     ErrorOr<std::unique_ptr<MemoryBuffer>> MaybeBuf = MemoryBuffer::getFile(
137         Arg->getValue(), /*IsText=*/false, /*RequiresNullTerminator=*/false);
138     fatalOpenError(errorCodeToError(MaybeBuf.getError()), Arg->getValue());
139 
140     if (identify_magic(MaybeBuf.get()->getBuffer()) == file_magic::archive) {
141       B = std::move(MaybeBuf.get());
142       break;
143     }
144   }
145 
146   // lib.exe doesn't print an error if no .lib files are passed.
147   if (!B)
148     return;
149 
150   Error Err = Error::success();
151   object::Archive Archive(B->getMemBufferRef(), Err);
152   fatalOpenError(std::move(Err), B->getBufferIdentifier());
153 
154   std::vector<StringRef> Names;
155   for (auto &C : Archive.children(Err)) {
156     Expected<StringRef> NameOrErr = C.getName();
157     fatalOpenError(NameOrErr.takeError(), B->getBufferIdentifier());
158     Names.push_back(NameOrErr.get());
159   }
160   for (auto Name : reverse(Names))
161     llvm::outs() << Name << '\n';
162   fatalOpenError(std::move(Err), B->getBufferIdentifier());
163 }
164 
165 static Expected<COFF::MachineTypes> getCOFFFileMachine(MemoryBufferRef MB) {
166   std::error_code EC;
167   auto Obj = object::COFFObjectFile::create(MB);
168   if (!Obj)
169     return Obj.takeError();
170 
171   uint16_t Machine = (*Obj)->getMachine();
172   if (Machine != COFF::IMAGE_FILE_MACHINE_I386 &&
173       Machine != COFF::IMAGE_FILE_MACHINE_AMD64 &&
174       Machine != COFF::IMAGE_FILE_MACHINE_ARMNT && !COFF::isAnyArm64(Machine)) {
175     return createStringError(inconvertibleErrorCode(),
176                              "unknown machine: " + std::to_string(Machine));
177   }
178 
179   return static_cast<COFF::MachineTypes>(Machine);
180 }
181 
182 static Expected<COFF::MachineTypes> getBitcodeFileMachine(MemoryBufferRef MB) {
183   Expected<std::string> TripleStr = getBitcodeTargetTriple(MB);
184   if (!TripleStr)
185     return TripleStr.takeError();
186 
187   Triple T(*TripleStr);
188   switch (T.getArch()) {
189   case Triple::x86:
190     return COFF::IMAGE_FILE_MACHINE_I386;
191   case Triple::x86_64:
192     return COFF::IMAGE_FILE_MACHINE_AMD64;
193   case Triple::arm:
194     return COFF::IMAGE_FILE_MACHINE_ARMNT;
195   case Triple::aarch64:
196     return T.isWindowsArm64EC() ? COFF::IMAGE_FILE_MACHINE_ARM64EC
197                                 : COFF::IMAGE_FILE_MACHINE_ARM64;
198   default:
199     return createStringError(inconvertibleErrorCode(),
200                              "unknown arch in target triple: " + *TripleStr);
201   }
202 }
203 
204 static bool machineMatches(COFF::MachineTypes LibMachine,
205                            COFF::MachineTypes FileMachine) {
206   if (LibMachine == FileMachine)
207     return true;
208   // ARM64EC mode allows both pure ARM64, ARM64EC and X64 objects to be mixed in
209   // the archive.
210   switch (LibMachine) {
211   case COFF::IMAGE_FILE_MACHINE_ARM64:
212     return FileMachine == COFF::IMAGE_FILE_MACHINE_ARM64X;
213   case COFF::IMAGE_FILE_MACHINE_ARM64EC:
214   case COFF::IMAGE_FILE_MACHINE_ARM64X:
215     return COFF::isAnyArm64(FileMachine) ||
216            FileMachine == COFF::IMAGE_FILE_MACHINE_AMD64;
217   default:
218     return false;
219   }
220 }
221 
222 static void appendFile(std::vector<NewArchiveMember> &Members,
223                        COFF::MachineTypes &LibMachine,
224                        std::string &LibMachineSource, MemoryBufferRef MB) {
225   file_magic Magic = identify_magic(MB.getBuffer());
226 
227   if (Magic != file_magic::coff_object && Magic != file_magic::bitcode &&
228       Magic != file_magic::archive && Magic != file_magic::windows_resource &&
229       Magic != file_magic::coff_import_library) {
230     llvm::errs() << MB.getBufferIdentifier()
231                  << ": not a COFF object, bitcode, archive, import library or "
232                     "resource file\n";
233     exit(1);
234   }
235 
236   // If a user attempts to add an archive to another archive, llvm-lib doesn't
237   // handle the first archive file as a single file. Instead, it extracts all
238   // members from the archive and add them to the second archive. This behavior
239   // is for compatibility with Microsoft's lib command.
240   if (Magic == file_magic::archive) {
241     Error Err = Error::success();
242     object::Archive Archive(MB, Err);
243     fatalOpenError(std::move(Err), MB.getBufferIdentifier());
244 
245     for (auto &C : Archive.children(Err)) {
246       Expected<MemoryBufferRef> ChildMB = C.getMemoryBufferRef();
247       if (!ChildMB) {
248         handleAllErrors(ChildMB.takeError(), [&](const ErrorInfoBase &EIB) {
249           llvm::errs() << MB.getBufferIdentifier() << ": " << EIB.message()
250                        << "\n";
251         });
252         exit(1);
253       }
254 
255       appendFile(Members, LibMachine, LibMachineSource, *ChildMB);
256     }
257 
258     fatalOpenError(std::move(Err), MB.getBufferIdentifier());
259     return;
260   }
261 
262   // Check that all input files have the same machine type.
263   // Mixing normal objects and LTO bitcode files is fine as long as they
264   // have the same machine type.
265   // Doing this here duplicates the header parsing work that writeArchive()
266   // below does, but it's not a lot of work and it's a bit awkward to do
267   // in writeArchive() which needs to support many tools, can't assume the
268   // input is COFF, and doesn't have a good way to report errors.
269   if (Magic == file_magic::coff_object || Magic == file_magic::bitcode) {
270     Expected<COFF::MachineTypes> MaybeFileMachine =
271         (Magic == file_magic::coff_object) ? getCOFFFileMachine(MB)
272                                            : getBitcodeFileMachine(MB);
273     if (!MaybeFileMachine) {
274       handleAllErrors(MaybeFileMachine.takeError(),
275                       [&](const ErrorInfoBase &EIB) {
276                         llvm::errs() << MB.getBufferIdentifier() << ": "
277                                      << EIB.message() << "\n";
278                       });
279       exit(1);
280     }
281     COFF::MachineTypes FileMachine = *MaybeFileMachine;
282 
283     // FIXME: Once lld-link rejects multiple resource .obj files:
284     // Call convertResToCOFF() on .res files and add the resulting
285     // COFF file to the .lib output instead of adding the .res file, and remove
286     // this check. See PR42180.
287     if (FileMachine != COFF::IMAGE_FILE_MACHINE_UNKNOWN) {
288       if (LibMachine == COFF::IMAGE_FILE_MACHINE_UNKNOWN) {
289         if (FileMachine == COFF::IMAGE_FILE_MACHINE_ARM64EC) {
290             llvm::errs() << MB.getBufferIdentifier() << ": file machine type "
291                          << machineToStr(FileMachine)
292                          << " conflicts with inferred library machine type,"
293                          << " use /machine:arm64ec or /machine:arm64x\n";
294             exit(1);
295         }
296         LibMachine = FileMachine;
297         LibMachineSource =
298             (" (inferred from earlier file '" + MB.getBufferIdentifier() + "')")
299                 .str();
300       } else if (!machineMatches(LibMachine, FileMachine)) {
301         llvm::errs() << MB.getBufferIdentifier() << ": file machine type "
302                      << machineToStr(FileMachine)
303                      << " conflicts with library machine type "
304                      << machineToStr(LibMachine) << LibMachineSource << '\n';
305         exit(1);
306       }
307     }
308   }
309 
310   Members.emplace_back(MB);
311 }
312 
313 int llvm::libDriverMain(ArrayRef<const char *> ArgsArr) {
314   BumpPtrAllocator Alloc;
315   StringSaver Saver(Alloc);
316 
317   // Parse command line arguments.
318   SmallVector<const char *, 20> NewArgs(ArgsArr);
319   cl::ExpandResponseFiles(Saver, cl::TokenizeWindowsCommandLine, NewArgs);
320   ArgsArr = NewArgs;
321 
322   LibOptTable Table;
323   unsigned MissingIndex;
324   unsigned MissingCount;
325   opt::InputArgList Args =
326       Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount);
327   if (MissingCount) {
328     llvm::errs() << "missing arg value for \""
329                  << Args.getArgString(MissingIndex) << "\", expected "
330                  << MissingCount
331                  << (MissingCount == 1 ? " argument.\n" : " arguments.\n");
332     return 1;
333   }
334   for (auto *Arg : Args.filtered(OPT_UNKNOWN))
335     llvm::errs() << "ignoring unknown argument: " << Arg->getAsString(Args)
336                  << "\n";
337 
338   // Handle /help
339   if (Args.hasArg(OPT_help)) {
340     Table.printHelp(outs(), "llvm-lib [options] file...", "LLVM Lib");
341     return 0;
342   }
343 
344   // Parse /ignore:
345   llvm::StringSet<> IgnoredWarnings;
346   for (auto *Arg : Args.filtered(OPT_ignore))
347     IgnoredWarnings.insert(Arg->getValue());
348 
349   // get output library path, if any
350   std::string OutputPath;
351   if (auto *Arg = Args.getLastArg(OPT_out)) {
352     OutputPath = Arg->getValue();
353   }
354 
355   COFF::MachineTypes LibMachine = COFF::IMAGE_FILE_MACHINE_UNKNOWN;
356   std::string LibMachineSource;
357   if (auto *Arg = Args.getLastArg(OPT_machine)) {
358     LibMachine = getMachineType(Arg->getValue());
359     if (LibMachine == COFF::IMAGE_FILE_MACHINE_UNKNOWN) {
360       llvm::errs() << "unknown /machine: arg " << Arg->getValue() << '\n';
361       return 1;
362     }
363     LibMachineSource =
364         std::string(" (from '/machine:") + Arg->getValue() + "' flag)";
365   }
366 
367   // create an import library
368   if (Args.hasArg(OPT_deffile)) {
369 
370     if (OutputPath.empty()) {
371       llvm::errs() << "no output path given\n";
372       return 1;
373     }
374 
375     if (LibMachine == COFF::IMAGE_FILE_MACHINE_UNKNOWN) {
376       llvm::errs() << "/def option requires /machine to be specified" << '\n';
377       return 1;
378     }
379 
380     std::unique_ptr<MemoryBuffer> MB =
381         openFile(Args.getLastArg(OPT_deffile)->getValue());
382     if (!MB)
383       return 1;
384 
385     if (!MB->getBufferSize()) {
386       llvm::errs() << "definition file empty\n";
387       return 1;
388     }
389 
390     Expected<COFFModuleDefinition> Def =
391         parseCOFFModuleDefinition(*MB, LibMachine, /*MingwDef=*/false);
392 
393     if (!Def) {
394       llvm::errs() << "error parsing definition\n"
395                    << errorToErrorCode(Def.takeError()).message();
396       return 1;
397     }
398 
399     std::vector<COFFShortExport> NativeExports;
400     std::string OutputFile = Def->OutputFile;
401 
402     if (isArm64EC(LibMachine) && Args.hasArg(OPT_nativedeffile)) {
403       std::unique_ptr<MemoryBuffer> NativeMB =
404           openFile(Args.getLastArg(OPT_nativedeffile)->getValue());
405       if (!NativeMB)
406         return 1;
407 
408       if (!NativeMB->getBufferSize()) {
409         llvm::errs() << "native definition file empty\n";
410         return 1;
411       }
412 
413       Expected<COFFModuleDefinition> NativeDef =
414           parseCOFFModuleDefinition(*NativeMB, COFF::IMAGE_FILE_MACHINE_ARM64);
415 
416       if (!NativeDef) {
417         llvm::errs() << "error parsing native definition\n"
418                      << errorToErrorCode(NativeDef.takeError()).message();
419         return 1;
420       }
421       NativeExports = std::move(NativeDef->Exports);
422       OutputFile = std::move(NativeDef->OutputFile);
423     }
424 
425     if (Error E =
426             writeImportLibrary(OutputFile, OutputPath, Def->Exports, LibMachine,
427                                /*MinGW=*/false, NativeExports)) {
428       handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
429         llvm::errs() << OutputPath << ": " << EI.message() << "\n";
430       });
431       return 1;
432     }
433     return 0;
434   }
435 
436   // If no input files and not told otherwise, silently do nothing to match
437   // lib.exe
438   if (!Args.hasArgNoClaim(OPT_INPUT) && !Args.hasArg(OPT_llvmlibempty)) {
439     if (!IgnoredWarnings.contains("emptyoutput")) {
440       llvm::errs() << "warning: no input files, not writing output file\n";
441       llvm::errs() << "         pass /llvmlibempty to write empty .lib file,\n";
442       llvm::errs() << "         pass /ignore:emptyoutput to suppress warning\n";
443       if (Args.hasFlag(OPT_WX, OPT_WX_no, false)) {
444         llvm::errs() << "treating warning as error due to /WX\n";
445         return 1;
446       }
447     }
448     return 0;
449   }
450 
451   if (Args.hasArg(OPT_lst)) {
452     doList(Args);
453     return 0;
454   }
455 
456   std::vector<StringRef> SearchPaths = getSearchPaths(&Args, Saver);
457 
458   std::vector<std::unique_ptr<MemoryBuffer>> MBs;
459   StringSet<> Seen;
460   std::vector<NewArchiveMember> Members;
461 
462   // Create a NewArchiveMember for each input file.
463   for (auto *Arg : Args.filtered(OPT_INPUT)) {
464     // Find a file
465     std::string Path = findInputFile(Arg->getValue(), SearchPaths);
466     if (Path.empty()) {
467       llvm::errs() << Arg->getValue() << ": no such file or directory\n";
468       return 1;
469     }
470 
471     // Input files are uniquified by pathname. If you specify the exact same
472     // path more than once, all but the first one are ignored.
473     //
474     // Note that there's a loophole in the rule; you can prepend `.\` or
475     // something like that to a path to make it look different, and they are
476     // handled as if they were different files. This behavior is compatible with
477     // Microsoft lib.exe.
478     if (!Seen.insert(Path).second)
479       continue;
480 
481     // Open a file.
482     ErrorOr<std::unique_ptr<MemoryBuffer>> MOrErr = MemoryBuffer::getFile(
483         Path, /*IsText=*/false, /*RequiresNullTerminator=*/false);
484     fatalOpenError(errorCodeToError(MOrErr.getError()), Path);
485     MemoryBufferRef MBRef = (*MOrErr)->getMemBufferRef();
486 
487     // Append a file.
488     appendFile(Members, LibMachine, LibMachineSource, MBRef);
489 
490     // Take the ownership of the file buffer to keep the file open.
491     MBs.push_back(std::move(*MOrErr));
492   }
493 
494   // Create an archive file.
495   if (OutputPath.empty()) {
496     if (!Members.empty()) {
497       OutputPath = getDefaultOutputPath(Members[0]);
498     } else {
499       llvm::errs() << "no output path given, and cannot infer with no inputs\n";
500       return 1;
501     }
502   }
503   // llvm-lib uses relative paths for both regular and thin archives, unlike
504   // standard GNU ar, which only uses relative paths for thin archives and
505   // basenames for regular archives.
506   for (NewArchiveMember &Member : Members) {
507     if (sys::path::is_relative(Member.MemberName)) {
508       Expected<std::string> PathOrErr =
509           computeArchiveRelativePath(OutputPath, Member.MemberName);
510       if (PathOrErr)
511         Member.MemberName = Saver.save(*PathOrErr);
512     }
513   }
514 
515   // For compatibility with MSVC, reverse member vector after de-duplication.
516   std::reverse(Members.begin(), Members.end());
517 
518   bool Thin = Args.hasArg(OPT_llvmlibthin);
519 
520   auto Symtab = Args.hasFlag(OPT_llvmlibindex, OPT_llvmlibindex_no,
521                              /*default=*/true)
522                     ? SymtabWritingMode::NormalSymtab
523                     : SymtabWritingMode::NoSymtab;
524 
525   if (Error E = writeArchive(
526           OutputPath, Members, Symtab,
527           Thin ? object::Archive::K_GNU : object::Archive::K_COFF,
528           /*Deterministic=*/true, Thin, nullptr, COFF::isArm64EC(LibMachine))) {
529     handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
530       llvm::errs() << OutputPath << ": " << EI.message() << "\n";
531     });
532     return 1;
533   }
534 
535   return 0;
536 }
537