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