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/WindowsMachineFlag.h" 23 #include "llvm/Option/Arg.h" 24 #include "llvm/Option/ArgList.h" 25 #include "llvm/Option/Option.h" 26 #include "llvm/Support/CommandLine.h" 27 #include "llvm/Support/Path.h" 28 #include "llvm/Support/Process.h" 29 #include "llvm/Support/StringSaver.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include <optional> 32 33 using namespace llvm; 34 35 namespace { 36 37 enum { 38 OPT_INVALID = 0, 39 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID, 40 #include "Options.inc" 41 #undef OPTION 42 }; 43 44 #define PREFIX(NAME, VALUE) \ 45 static constexpr StringLiteral NAME##_init[] = VALUE; \ 46 static constexpr ArrayRef<StringLiteral> NAME(NAME##_init, \ 47 std::size(NAME##_init) - 1); 48 #include "Options.inc" 49 #undef PREFIX 50 51 static constexpr opt::OptTable::Info InfoTable[] = { 52 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \ 53 {X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \ 54 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12}, 55 #include "Options.inc" 56 #undef OPTION 57 }; 58 59 class LibOptTable : public opt::OptTable { 60 public: 61 LibOptTable() : OptTable(InfoTable, true) {} 62 }; 63 64 } 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 static std::string findInputFile(StringRef File, ArrayRef<StringRef> Paths) { 96 for (StringRef Dir : Paths) { 97 SmallString<128> Path = Dir; 98 sys::path::append(Path, File); 99 if (sys::fs::exists(Path)) 100 return std::string(Path); 101 } 102 return ""; 103 } 104 105 static void fatalOpenError(llvm::Error E, Twine File) { 106 if (!E) 107 return; 108 handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) { 109 llvm::errs() << "error opening '" << File << "': " << EIB.message() << '\n'; 110 exit(1); 111 }); 112 } 113 114 static void doList(opt::InputArgList& Args) { 115 // lib.exe prints the contents of the first archive file. 116 std::unique_ptr<MemoryBuffer> B; 117 for (auto *Arg : Args.filtered(OPT_INPUT)) { 118 // Create or open the archive object. 119 ErrorOr<std::unique_ptr<MemoryBuffer>> MaybeBuf = MemoryBuffer::getFile( 120 Arg->getValue(), /*IsText=*/false, /*RequiresNullTerminator=*/false); 121 fatalOpenError(errorCodeToError(MaybeBuf.getError()), Arg->getValue()); 122 123 if (identify_magic(MaybeBuf.get()->getBuffer()) == file_magic::archive) { 124 B = std::move(MaybeBuf.get()); 125 break; 126 } 127 } 128 129 // lib.exe doesn't print an error if no .lib files are passed. 130 if (!B) 131 return; 132 133 Error Err = Error::success(); 134 object::Archive Archive(B.get()->getMemBufferRef(), Err); 135 fatalOpenError(std::move(Err), B->getBufferIdentifier()); 136 137 for (auto &C : Archive.children(Err)) { 138 Expected<StringRef> NameOrErr = C.getName(); 139 fatalOpenError(NameOrErr.takeError(), B->getBufferIdentifier()); 140 StringRef Name = NameOrErr.get(); 141 llvm::outs() << Name << '\n'; 142 } 143 fatalOpenError(std::move(Err), B->getBufferIdentifier()); 144 } 145 146 static Expected<COFF::MachineTypes> getCOFFFileMachine(MemoryBufferRef MB) { 147 std::error_code EC; 148 auto Obj = object::COFFObjectFile::create(MB); 149 if (!Obj) 150 return Obj.takeError(); 151 152 uint16_t Machine = (*Obj)->getMachine(); 153 if (Machine != COFF::IMAGE_FILE_MACHINE_I386 && 154 Machine != COFF::IMAGE_FILE_MACHINE_AMD64 && 155 Machine != COFF::IMAGE_FILE_MACHINE_ARMNT && 156 Machine != COFF::IMAGE_FILE_MACHINE_ARM64) { 157 return createStringError(inconvertibleErrorCode(), 158 "unknown machine: " + std::to_string(Machine)); 159 } 160 161 return static_cast<COFF::MachineTypes>(Machine); 162 } 163 164 static Expected<COFF::MachineTypes> getBitcodeFileMachine(MemoryBufferRef MB) { 165 Expected<std::string> TripleStr = getBitcodeTargetTriple(MB); 166 if (!TripleStr) 167 return TripleStr.takeError(); 168 169 switch (Triple(*TripleStr).getArch()) { 170 case Triple::x86: 171 return COFF::IMAGE_FILE_MACHINE_I386; 172 case Triple::x86_64: 173 return COFF::IMAGE_FILE_MACHINE_AMD64; 174 case Triple::arm: 175 return COFF::IMAGE_FILE_MACHINE_ARMNT; 176 case Triple::aarch64: 177 return COFF::IMAGE_FILE_MACHINE_ARM64; 178 default: 179 return createStringError(inconvertibleErrorCode(), 180 "unknown arch in target triple: " + *TripleStr); 181 } 182 } 183 184 static void appendFile(std::vector<NewArchiveMember> &Members, 185 COFF::MachineTypes &LibMachine, 186 std::string &LibMachineSource, MemoryBufferRef MB) { 187 file_magic Magic = identify_magic(MB.getBuffer()); 188 189 if (Magic != file_magic::coff_object && Magic != file_magic::bitcode && 190 Magic != file_magic::archive && Magic != file_magic::windows_resource && 191 Magic != file_magic::coff_import_library) { 192 llvm::errs() << MB.getBufferIdentifier() 193 << ": not a COFF object, bitcode, archive, import library or " 194 "resource file\n"; 195 exit(1); 196 } 197 198 // If a user attempts to add an archive to another archive, llvm-lib doesn't 199 // handle the first archive file as a single file. Instead, it extracts all 200 // members from the archive and add them to the second archive. This behavior 201 // is for compatibility with Microsoft's lib command. 202 if (Magic == file_magic::archive) { 203 Error Err = Error::success(); 204 object::Archive Archive(MB, Err); 205 fatalOpenError(std::move(Err), MB.getBufferIdentifier()); 206 207 for (auto &C : Archive.children(Err)) { 208 Expected<MemoryBufferRef> ChildMB = C.getMemoryBufferRef(); 209 if (!ChildMB) { 210 handleAllErrors(ChildMB.takeError(), [&](const ErrorInfoBase &EIB) { 211 llvm::errs() << MB.getBufferIdentifier() << ": " << EIB.message() 212 << "\n"; 213 }); 214 exit(1); 215 } 216 217 appendFile(Members, LibMachine, LibMachineSource, *ChildMB); 218 } 219 220 fatalOpenError(std::move(Err), MB.getBufferIdentifier()); 221 return; 222 } 223 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 if (Magic == file_magic::coff_object || Magic == file_magic::bitcode) { 232 Expected<COFF::MachineTypes> MaybeFileMachine = 233 (Magic == file_magic::coff_object) ? getCOFFFileMachine(MB) 234 : getBitcodeFileMachine(MB); 235 if (!MaybeFileMachine) { 236 handleAllErrors(MaybeFileMachine.takeError(), 237 [&](const ErrorInfoBase &EIB) { 238 llvm::errs() << MB.getBufferIdentifier() << ": " 239 << EIB.message() << "\n"; 240 }); 241 exit(1); 242 } 243 COFF::MachineTypes FileMachine = *MaybeFileMachine; 244 245 // FIXME: Once lld-link rejects multiple resource .obj files: 246 // Call convertResToCOFF() on .res files and add the resulting 247 // COFF file to the .lib output instead of adding the .res file, and remove 248 // this check. See PR42180. 249 if (FileMachine != COFF::IMAGE_FILE_MACHINE_UNKNOWN) { 250 if (LibMachine == COFF::IMAGE_FILE_MACHINE_UNKNOWN) { 251 LibMachine = FileMachine; 252 LibMachineSource = 253 (" (inferred from earlier file '" + MB.getBufferIdentifier() + "')") 254 .str(); 255 } else if (LibMachine != FileMachine) { 256 llvm::errs() << MB.getBufferIdentifier() << ": file machine type " 257 << machineToStr(FileMachine) 258 << " conflicts with library machine type " 259 << machineToStr(LibMachine) << LibMachineSource << '\n'; 260 exit(1); 261 } 262 } 263 } 264 265 Members.emplace_back(MB); 266 } 267 268 int llvm::libDriverMain(ArrayRef<const char *> ArgsArr) { 269 BumpPtrAllocator Alloc; 270 StringSaver Saver(Alloc); 271 272 // Parse command line arguments. 273 SmallVector<const char *, 20> NewArgs(ArgsArr.begin(), ArgsArr.end()); 274 cl::ExpandResponseFiles(Saver, cl::TokenizeWindowsCommandLine, NewArgs); 275 ArgsArr = NewArgs; 276 277 LibOptTable Table; 278 unsigned MissingIndex; 279 unsigned MissingCount; 280 opt::InputArgList Args = 281 Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount); 282 if (MissingCount) { 283 llvm::errs() << "missing arg value for \"" 284 << Args.getArgString(MissingIndex) << "\", expected " 285 << MissingCount 286 << (MissingCount == 1 ? " argument.\n" : " arguments.\n"); 287 return 1; 288 } 289 for (auto *Arg : Args.filtered(OPT_UNKNOWN)) 290 llvm::errs() << "ignoring unknown argument: " << Arg->getAsString(Args) 291 << "\n"; 292 293 // Handle /help 294 if (Args.hasArg(OPT_help)) { 295 Table.printHelp(outs(), "llvm-lib [options] file...", "LLVM Lib"); 296 return 0; 297 } 298 299 // Parse /ignore: 300 llvm::StringSet<> IgnoredWarnings; 301 for (auto *Arg : Args.filtered(OPT_ignore)) 302 IgnoredWarnings.insert(Arg->getValue()); 303 304 // If no input files and not told otherwise, silently do nothing to match 305 // lib.exe 306 if (!Args.hasArgNoClaim(OPT_INPUT) && !Args.hasArg(OPT_llvmlibempty)) { 307 if (!IgnoredWarnings.contains("emptyoutput")) { 308 llvm::errs() << "warning: no input files, not writing output file\n"; 309 llvm::errs() << " pass /llvmlibempty to write empty .lib file,\n"; 310 llvm::errs() << " pass /ignore:emptyoutput to suppress warning\n"; 311 if (Args.hasFlag(OPT_WX, OPT_WX_no, false)) { 312 llvm::errs() << "treating warning as error due to /WX\n"; 313 return 1; 314 } 315 } 316 return 0; 317 } 318 319 if (Args.hasArg(OPT_lst)) { 320 doList(Args); 321 return 0; 322 } 323 324 std::vector<StringRef> SearchPaths = getSearchPaths(&Args, Saver); 325 326 COFF::MachineTypes LibMachine = COFF::IMAGE_FILE_MACHINE_UNKNOWN; 327 std::string LibMachineSource; 328 if (auto *Arg = Args.getLastArg(OPT_machine)) { 329 LibMachine = getMachineType(Arg->getValue()); 330 if (LibMachine == COFF::IMAGE_FILE_MACHINE_UNKNOWN) { 331 llvm::errs() << "unknown /machine: arg " << Arg->getValue() << '\n'; 332 return 1; 333 } 334 LibMachineSource = 335 std::string(" (from '/machine:") + Arg->getValue() + "' flag)"; 336 } 337 338 std::vector<std::unique_ptr<MemoryBuffer>> MBs; 339 StringSet<> Seen; 340 std::vector<NewArchiveMember> Members; 341 342 // Create a NewArchiveMember for each input file. 343 for (auto *Arg : Args.filtered(OPT_INPUT)) { 344 // Find a file 345 std::string Path = findInputFile(Arg->getValue(), SearchPaths); 346 if (Path.empty()) { 347 llvm::errs() << Arg->getValue() << ": no such file or directory\n"; 348 return 1; 349 } 350 351 // Input files are uniquified by pathname. If you specify the exact same 352 // path more than once, all but the first one are ignored. 353 // 354 // Note that there's a loophole in the rule; you can prepend `.\` or 355 // something like that to a path to make it look different, and they are 356 // handled as if they were different files. This behavior is compatible with 357 // Microsoft lib.exe. 358 if (!Seen.insert(Path).second) 359 continue; 360 361 // Open a file. 362 ErrorOr<std::unique_ptr<MemoryBuffer>> MOrErr = MemoryBuffer::getFile( 363 Path, /*IsText=*/false, /*RequiresNullTerminator=*/false); 364 fatalOpenError(errorCodeToError(MOrErr.getError()), Path); 365 MemoryBufferRef MBRef = (*MOrErr)->getMemBufferRef(); 366 367 // Append a file. 368 appendFile(Members, LibMachine, LibMachineSource, MBRef); 369 370 // Take the ownership of the file buffer to keep the file open. 371 MBs.push_back(std::move(*MOrErr)); 372 } 373 374 // Create an archive file. 375 std::string OutputPath; 376 if (auto *Arg = Args.getLastArg(OPT_out)) { 377 OutputPath = Arg->getValue(); 378 } else if (!Members.empty()) { 379 OutputPath = getDefaultOutputPath(Members[0]); 380 } else { 381 llvm::errs() << "no output path given, and cannot infer with no inputs\n"; 382 return 1; 383 } 384 // llvm-lib uses relative paths for both regular and thin archives, unlike 385 // standard GNU ar, which only uses relative paths for thin archives and 386 // basenames for regular archives. 387 for (NewArchiveMember &Member : Members) { 388 if (sys::path::is_relative(Member.MemberName)) { 389 Expected<std::string> PathOrErr = 390 computeArchiveRelativePath(OutputPath, Member.MemberName); 391 if (PathOrErr) 392 Member.MemberName = Saver.save(*PathOrErr); 393 } 394 } 395 396 if (Error E = 397 writeArchive(OutputPath, Members, 398 /*WriteSymtab=*/true, object::Archive::K_GNU, 399 /*Deterministic*/ true, Args.hasArg(OPT_llvmlibthin))) { 400 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) { 401 llvm::errs() << OutputPath << ": " << EI.message() << "\n"; 402 }); 403 return 1; 404 } 405 406 return 0; 407 } 408