#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/BinaryFormat/COFF.h"
#include "llvm/BinaryFormat/Magic.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/Object/ArchiveWriter.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/WindowsMachineFlag.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/StringSaver.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
enum {
OPT_INVALID = 0,
#define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
#include "Options.inc"
#undef OPTION
};
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "Options.inc"
#undef PREFIX
static const opt::OptTable::Info InfoTable[] = {
#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
{X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
#include "Options.inc"
#undef OPTION
};
class LibOptTable : public opt::OptTable {
public:
LibOptTable() : OptTable(InfoTable, true) {}
};
}
static std::string getDefaultOutputPath(const NewArchiveMember &FirstMember) {
SmallString<128> Val = StringRef(FirstMember.Buf->getBufferIdentifier());
sys::path::replace_extension(Val, ".lib");
return std::string(Val.str());
}
static std::vector<StringRef> getSearchPaths(opt::InputArgList *Args,
StringSaver &Saver) {
std::vector<StringRef> Ret;
Ret.push_back("");
for (auto *Arg : Args->filtered(OPT_libpath))
Ret.push_back(Arg->getValue());
Optional<std::string> EnvOpt = sys::Process::GetEnv("LIB");
if (!EnvOpt)
return Ret;
StringRef Env = Saver.save(*EnvOpt);
while (!Env.empty()) {
StringRef Path;
std::tie(Path, Env) = Env.split(';');
Ret.push_back(Path);
}
return Ret;
}
static std::string findInputFile(StringRef File, ArrayRef<StringRef> Paths) {
for (StringRef Dir : Paths) {
SmallString<128> Path = Dir;
sys::path::append(Path, File);
if (sys::fs::exists(Path))
return std::string(Path);
}
return "";
}
static void fatalOpenError(llvm::Error E, Twine File) {
if (!E)
return;
handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
llvm::errs() << "error opening '" << File << "': " << EIB.message() << '\n';
exit(1);
});
}
static void doList(opt::InputArgList& Args) {
std::unique_ptr<MemoryBuffer> B;
for (auto *Arg : Args.filtered(OPT_INPUT)) {
ErrorOr<std::unique_ptr<MemoryBuffer>> MaybeBuf = MemoryBuffer::getFile(
Arg->getValue(), false, false);
fatalOpenError(errorCodeToError(MaybeBuf.getError()), Arg->getValue());
if (identify_magic(MaybeBuf.get()->getBuffer()) == file_magic::archive) {
B = std::move(MaybeBuf.get());
break;
}
}
if (!B)
return;
Error Err = Error::success();
object::Archive Archive(B.get()->getMemBufferRef(), Err);
fatalOpenError(std::move(Err), B->getBufferIdentifier());
for (auto &C : Archive.children(Err)) {
Expected<StringRef> NameOrErr = C.getName();
fatalOpenError(NameOrErr.takeError(), B->getBufferIdentifier());
StringRef Name = NameOrErr.get();
llvm::outs() << Name << '\n';
}
fatalOpenError(std::move(Err), B->getBufferIdentifier());
}
static Expected<COFF::MachineTypes> getCOFFFileMachine(MemoryBufferRef MB) {
std::error_code EC;
auto Obj = object::COFFObjectFile::create(MB);
if (!Obj)
return Obj.takeError();
uint16_t Machine = (*Obj)->getMachine();
if (Machine != COFF::IMAGE_FILE_MACHINE_I386 &&
Machine != COFF::IMAGE_FILE_MACHINE_AMD64 &&
Machine != COFF::IMAGE_FILE_MACHINE_ARMNT &&
Machine != COFF::IMAGE_FILE_MACHINE_ARM64) {
return createStringError(inconvertibleErrorCode(),
"unknown machine: " + std::to_string(Machine));
}
return static_cast<COFF::MachineTypes>(Machine);
}
static Expected<COFF::MachineTypes> getBitcodeFileMachine(MemoryBufferRef MB) {
Expected<std::string> TripleStr = getBitcodeTargetTriple(MB);
if (!TripleStr)
return TripleStr.takeError();
switch (Triple(*TripleStr).getArch()) {
case Triple::x86:
return COFF::IMAGE_FILE_MACHINE_I386;
case Triple::x86_64:
return COFF::IMAGE_FILE_MACHINE_AMD64;
case Triple::arm:
return COFF::IMAGE_FILE_MACHINE_ARMNT;
case Triple::aarch64:
return COFF::IMAGE_FILE_MACHINE_ARM64;
default:
return createStringError(inconvertibleErrorCode(),
"unknown arch in target triple: " + *TripleStr);
}
}
static void appendFile(std::vector<NewArchiveMember> &Members,
COFF::MachineTypes &LibMachine,
std::string &LibMachineSource, MemoryBufferRef MB) {
file_magic Magic = identify_magic(MB.getBuffer());
if (Magic != file_magic::coff_object && Magic != file_magic::bitcode &&
Magic != file_magic::archive && Magic != file_magic::windows_resource &&
Magic != file_magic::coff_import_library) {
llvm::errs() << MB.getBufferIdentifier()
<< ": not a COFF object, bitcode, archive, import library or "
"resource file\n";
exit(1);
}
if (Magic == file_magic::archive) {
Error Err = Error::success();
object::Archive Archive(MB, Err);
fatalOpenError(std::move(Err), MB.getBufferIdentifier());
for (auto &C : Archive.children(Err)) {
Expected<MemoryBufferRef> ChildMB = C.getMemoryBufferRef();
if (!ChildMB) {
handleAllErrors(ChildMB.takeError(), [&](const ErrorInfoBase &EIB) {
llvm::errs() << MB.getBufferIdentifier() << ": " << EIB.message()
<< "\n";
});
exit(1);
}
appendFile(Members, LibMachine, LibMachineSource, *ChildMB);
}
fatalOpenError(std::move(Err), MB.getBufferIdentifier());
return;
}
if (Magic == file_magic::coff_object || Magic == file_magic::bitcode) {
Expected<COFF::MachineTypes> MaybeFileMachine =
(Magic == file_magic::coff_object) ? getCOFFFileMachine(MB)
: getBitcodeFileMachine(MB);
if (!MaybeFileMachine) {
handleAllErrors(MaybeFileMachine.takeError(),
[&](const ErrorInfoBase &EIB) {
llvm::errs() << MB.getBufferIdentifier() << ": "
<< EIB.message() << "\n";
});
exit(1);
}
COFF::MachineTypes FileMachine = *MaybeFileMachine;
if (FileMachine != COFF::IMAGE_FILE_MACHINE_UNKNOWN) {
if (LibMachine == COFF::IMAGE_FILE_MACHINE_UNKNOWN) {
LibMachine = FileMachine;
LibMachineSource =
(" (inferred from earlier file '" + MB.getBufferIdentifier() + "')")
.str();
} else if (LibMachine != FileMachine) {
llvm::errs() << MB.getBufferIdentifier() << ": file machine type "
<< machineToStr(FileMachine)
<< " conflicts with library machine type "
<< machineToStr(LibMachine) << LibMachineSource << '\n';
exit(1);
}
}
}
Members.emplace_back(MB);
}
int llvm::libDriverMain(ArrayRef<const char *> ArgsArr) {
BumpPtrAllocator Alloc;
StringSaver Saver(Alloc);
SmallVector<const char *, 20> NewArgs(ArgsArr.begin(), ArgsArr.end());
cl::ExpandResponseFiles(Saver, cl::TokenizeWindowsCommandLine, NewArgs);
ArgsArr = NewArgs;
LibOptTable Table;
unsigned MissingIndex;
unsigned MissingCount;
opt::InputArgList Args =
Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount);
if (MissingCount) {
llvm::errs() << "missing arg value for \""
<< Args.getArgString(MissingIndex) << "\", expected "
<< MissingCount
<< (MissingCount == 1 ? " argument.\n" : " arguments.\n");
return 1;
}
for (auto *Arg : Args.filtered(OPT_UNKNOWN))
llvm::errs() << "ignoring unknown argument: " << Arg->getAsString(Args)
<< "\n";
if (Args.hasArg(OPT_help)) {
Table.printHelp(outs(), "llvm-lib [options] file...", "LLVM Lib");
return 0;
}
llvm::StringSet<> IgnoredWarnings;
for (auto *Arg : Args.filtered(OPT_ignore))
IgnoredWarnings.insert(Arg->getValue());
if (!Args.hasArgNoClaim(OPT_INPUT) && !Args.hasArg(OPT_llvmlibempty)) {
if (!IgnoredWarnings.contains("emptyoutput")) {
llvm::errs() << "warning: no input files, not writing output file\n";
llvm::errs() << " pass /llvmlibempty to write empty .lib file,\n";
llvm::errs() << " pass /ignore:emptyoutput to suppress warning\n";
if (Args.hasFlag(OPT_WX, OPT_WX_no, false)) {
llvm::errs() << "treating warning as error due to /WX\n";
return 1;
}
}
return 0;
}
if (Args.hasArg(OPT_lst)) {
doList(Args);
return 0;
}
std::vector<StringRef> SearchPaths = getSearchPaths(&Args, Saver);
COFF::MachineTypes LibMachine = COFF::IMAGE_FILE_MACHINE_UNKNOWN;
std::string LibMachineSource;
if (auto *Arg = Args.getLastArg(OPT_machine)) {
LibMachine = getMachineType(Arg->getValue());
if (LibMachine == COFF::IMAGE_FILE_MACHINE_UNKNOWN) {
llvm::errs() << "unknown /machine: arg " << Arg->getValue() << '\n';
return 1;
}
LibMachineSource =
std::string(" (from '/machine:") + Arg->getValue() + "' flag)";
}
std::vector<std::unique_ptr<MemoryBuffer>> MBs;
StringSet<> Seen;
std::vector<NewArchiveMember> Members;
for (auto *Arg : Args.filtered(OPT_INPUT)) {
std::string Path = findInputFile(Arg->getValue(), SearchPaths);
if (Path.empty()) {
llvm::errs() << Arg->getValue() << ": no such file or directory\n";
return 1;
}
if (!Seen.insert(Path).second)
continue;
ErrorOr<std::unique_ptr<MemoryBuffer>> MOrErr = MemoryBuffer::getFile(
Path, false, false);
fatalOpenError(errorCodeToError(MOrErr.getError()), Path);
MemoryBufferRef MBRef = (*MOrErr)->getMemBufferRef();
appendFile(Members, LibMachine, LibMachineSource, MBRef);
MBs.push_back(std::move(*MOrErr));
}
std::string OutputPath;
if (auto *Arg = Args.getLastArg(OPT_out)) {
OutputPath = Arg->getValue();
} else if (!Members.empty()) {
OutputPath = getDefaultOutputPath(Members[0]);
} else {
llvm::errs() << "no output path given, and cannot infer with no inputs\n";
return 1;
}
for (NewArchiveMember &Member : Members) {
if (sys::path::is_relative(Member.MemberName)) {
Expected<std::string> PathOrErr =
computeArchiveRelativePath(OutputPath, Member.MemberName);
if (PathOrErr)
Member.MemberName = Saver.save(*PathOrErr);
}
}
if (Error E =
writeArchive(OutputPath, Members,
true, object::Archive::K_GNU,
true, Args.hasArg(OPT_llvmlibthin))) {
handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
llvm::errs() << OutputPath << ": " << EI.message() << "\n";
});
return 1;
}
return 0;
}