1 //===- LibDriver.cpp - lib.exe-compatible driver --------------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
37 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
38 #include "Options.inc"
42 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
43 #include "Options.inc"
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"
54 class LibOptTable
: public opt::OptTable
{
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");
70 static std::vector
<StringRef
> getSearchPaths(opt::InputArgList
*Args
,
72 std::vector
<StringRef
> Ret
;
73 // Add current directory as first item of the search path.
76 // Add /libpath flags.
77 for (auto *Arg
: Args
->filtered(OPT_libpath
))
78 Ret
.push_back(Arg
->getValue());
81 Optional
<std::string
> EnvOpt
= sys::Process::GetEnv("LIB");
82 if (!EnvOpt
.hasValue())
84 StringRef Env
= Saver
.save(*EnvOpt
);
85 while (!Env
.empty()) {
87 std::tie(Path
, Env
) = Env
.split(';');
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();
103 static void fatalOpenError(llvm::Error E
, Twine File
) {
106 handleAllErrors(std::move(E
), [&](const llvm::ErrorInfoBase
&EIB
) {
107 llvm::errs() << "error opening '" << File
<< "': " << EIB
.message() << '\n';
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());
127 // lib.exe doesn't print an error if no .lib files are passed.
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
);
154 unsigned MissingIndex
;
155 unsigned MissingCount
;
156 opt::InputArgList Args
=
157 Table
.ParseArgs(ArgsArr
.slice(1), MissingIndex
, MissingCount
);
159 llvm::errs() << "missing arg value for \""
160 << Args
.getArgString(MissingIndex
) << "\", expected "
162 << (MissingCount
== 1 ? " argument.\n" : " arguments.\n");
165 for (auto *Arg
: Args
.filtered(OPT_UNKNOWN
))
166 llvm::errs() << "ignoring unknown argument: " << Arg
->getAsString(Args
)
170 if (Args
.hasArg(OPT_help
)) {
171 Table
.PrintHelp(outs(), "llvm-lib [options] file...", "LLVM Lib");
175 // If no input files, silently do nothing to match lib.exe.
176 if (!Args
.hasArgNoClaim(OPT_INPUT
))
179 if (Args
.hasArg(OPT_lst
)) {
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';
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
);
203 llvm::errs() << Arg
->getValue() << ": no such file or directory\n";
207 Expected
<NewArchiveMember
> MOrErr
=
208 NewArchiveMember::getFile(Saver
.save(Path
), /*Deterministic=*/true);
210 handleAllErrors(MOrErr
.takeError(), [&](const ErrorInfoBase
&EIB
) {
211 llvm::errs() << Arg
->getValue() << ": " << EIB
.message() << "\n";
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";
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
) {
234 object::COFFObjectFile
Obj(*MOrErr
->Buf
, EC
);
236 llvm::errs() << Arg
->getValue() << ": failed to open: " << EC
.message()
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
249 FileMachine
= static_cast<COFF::MachineTypes
>(Machine
);
250 } else if (Magic
== file_magic::bitcode
) {
251 Expected
<std::string
> TripleStr
= getBitcodeTargetTriple(*MOrErr
->Buf
);
253 llvm::errs() << Arg
->getValue()
254 << ": failed to get target triple from bitcode\n";
257 switch (Triple(*TripleStr
).getArch()) {
259 FileMachine
= COFF::IMAGE_FILE_MACHINE_I386
;
262 FileMachine
= COFF::IMAGE_FILE_MACHINE_AMD64
;
265 FileMachine
= COFF::IMAGE_FILE_MACHINE_ARMNT
;
267 case Triple::aarch64
:
268 FileMachine
= COFF::IMAGE_FILE_MACHINE_ARM64
;
271 llvm::errs() << Arg
->getValue() << ": unknown arch in target triple "
272 << *TripleStr
<< '\n';
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';
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
);
308 Member
.MemberName
= Saver
.save(*PathOrErr
);
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";