LLVM  5.0.0
DlltoolDriver.cpp
Go to the documentation of this file.
1 //===- DlltoolDriver.cpp - dlltool.exe-compatible driver ------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Defines an interface to a dlltool.exe-compatible driver.
11 //
12 //===----------------------------------------------------------------------===//
13 
16 #include "llvm/Object/COFF.h"
19 #include "llvm/Option/Arg.h"
20 #include "llvm/Option/ArgList.h"
21 #include "llvm/Option/Option.h"
22 #include "llvm/Support/Path.h"
23 
24 #include <string>
25 #include <vector>
26 
27 using namespace llvm;
28 using namespace llvm::object;
29 using namespace llvm::COFF;
30 
31 namespace {
32 
33 enum {
34  OPT_INVALID = 0,
35 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
36 #include "Options.inc"
37 #undef OPTION
38 };
39 
40 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
41 #include "Options.inc"
42 #undef PREFIX
43 
44 static const llvm::opt::OptTable::Info infoTable[] = {
45 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
46  {X1, X2, X10, X11, OPT_##ID, llvm::opt::Option::KIND##Class, \
47  X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
48 #include "Options.inc"
49 #undef OPTION
50 };
51 
52 class DllOptTable : public llvm::opt::OptTable {
53 public:
54  DllOptTable() : OptTable(infoTable, false) {}
55 };
56 
57 } // namespace
58 
59 std::vector<std::unique_ptr<MemoryBuffer>> OwningMBs;
60 
61 // Opens a file. Path has to be resolved already.
62 // Newly created memory buffers are owned by this driver.
65 
66  if (std::error_code EC = MB.getError()) {
67  llvm::errs() << "fail openFile: " << EC.message() << "\n";
68  return None;
69  }
70 
71  MemoryBufferRef MBRef = MB.get()->getMemBufferRef();
72  OwningMBs.push_back(std::move(MB.get())); // take ownership
73  return MBRef;
74 }
75 
78  .Case("i386", IMAGE_FILE_MACHINE_I386)
79  .Case("i386:x86-64", IMAGE_FILE_MACHINE_AMD64)
82 }
83 
84 static std::string getImplibPath(std::string Path) {
85  SmallString<128> Out = StringRef("lib");
86  Out.append(Path);
88  return Out.str();
89 }
90 
92  DllOptTable Table;
93  unsigned MissingIndex;
94  unsigned MissingCount;
96  Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount);
97  if (MissingCount) {
98  llvm::errs() << Args.getArgString(MissingIndex) << ": missing argument\n";
99  return 1;
100  }
101 
102  // Handle when no input or output is specified
103  if (Args.hasArgNoClaim(OPT_INPUT) ||
104  (!Args.hasArgNoClaim(OPT_d) && !Args.hasArgNoClaim(OPT_l))) {
105  Table.PrintHelp(outs(), ArgsArr[0], "dlltool", false);
106  llvm::outs() << "\nTARGETS: i386, i386:x86-64, arm\n";
107  return 1;
108  }
109 
110  if (!Args.hasArgNoClaim(OPT_m) && Args.hasArgNoClaim(OPT_d)) {
111  llvm::errs() << "error: no target machine specified\n"
112  << "supported targets: i386, i386:x86-64, arm\n";
113  return 1;
114  }
115 
116  for (auto *Arg : Args.filtered(OPT_UNKNOWN))
117  llvm::errs() << "ignoring unknown argument: " << Arg->getSpelling() << "\n";
118 
119  if (!Args.hasArg(OPT_d)) {
120  llvm::errs() << "no definition file specified\n";
121  return 1;
122  }
123 
125  if (!MB)
126  return 1;
127 
128  if (!MB->getBufferSize()) {
129  llvm::errs() << "definition file empty\n";
130  return 1;
131  }
132 
134  if (auto *Arg = Args.getLastArg(OPT_m))
135  Machine = getEmulation(Arg->getValue());
136 
137  if (Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
138  llvm::errs() << "unknown target\n";
139  return 1;
140  }
141 
143  parseCOFFModuleDefinition(*MB, Machine, true);
144 
145  if (!Def) {
146  llvm::errs() << "error parsing definition\n"
147  << errorToErrorCode(Def.takeError()).message();
148  return 1;
149  }
150 
151  // Do this after the parser because parseCOFFModuleDefinition sets OutputFile.
152  if (auto *Arg = Args.getLastArg(OPT_D))
153  Def->OutputFile = Arg->getValue();
154 
155  if (Def->OutputFile.empty()) {
156  llvm::errs() << "no output file specified\n";
157  return 1;
158  }
159 
160  std::string Path = Args.getLastArgValue(OPT_l);
161  if (Path.empty())
162  Path = getImplibPath(Def->OutputFile);
163 
164  if (Machine == IMAGE_FILE_MACHINE_I386 && Args.getLastArg(OPT_k)) {
165  for (COFFShortExport& E : Def->Exports) {
166  if (E.isWeak() || (!E.Name.empty() && E.Name[0] == '?'))
167  continue;
168  E.SymbolName = E.Name;
169  // Trim off the trailing decoration. Symbols will always have a
170  // starting prefix here (either _ for cdecl/stdcall, @ for fastcall
171  // or ? for C++ functions). (Vectorcall functions also will end up having
172  // a prefix here, even if they shouldn't.)
173  E.Name = E.Name.substr(0, E.Name.find('@', 1));
174  // By making sure E.SymbolName != E.Name for decorated symbols,
175  // writeImportLibrary writes these symbols with the type
176  // IMPORT_NAME_UNDECORATE.
177  }
178  }
179 
180  if (writeImportLibrary(Def->OutputFile, Path, Def->Exports, Machine, true))
181  return 1;
182  return 0;
183 }
const NoneType None
Definition: None.h:24
std::error_code getError() const
Definition: ErrorOr.h:172
Represents either an error or a value T.
Definition: ErrorOr.h:69
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Error takeError()
Take ownership of the stored error.
Definition: Error.h:764
const char * getValue(unsigned N=0) const
Definition: Arg.h:96
Expected< COFFModuleDefinition > parseCOFFModuleDefinition(MemoryBufferRef MB, COFF::MachineTypes Machine, bool MingwDef=false)
const char * getArgString(unsigned Index) const override
getArgString - Return the input argument string at Index.
Definition: ArgList.h:411
static MachineTypes getEmulation(StringRef S)
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array...
Definition: ArrayRef.h:179
LLVM_ATTRIBUTE_ALWAYS_INLINE R Default(const T &Value) const
Definition: StringSwitch.h:244
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
MachineTypes Machine
LLVM_ATTRIBUTE_ALWAYS_INLINE StringSwitch & Case(const char(&S)[N], const T &Value)
Definition: StringSwitch.h:74
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
int dlltoolDriverMain(ArrayRef< const char * > ArgsArr)
void append(in_iter S, in_iter E)
Append from an iterator pair.
Definition: SmallString.h:75
raw_ostream & outs()
This returns a reference to a raw_ostream for standard output.
Function Alias Analysis false
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:43
Provide access to the Option info table.
Definition: OptTable.h:39
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
iterator_range< filtered_iterator< sizeof...(OptSpecifiers)> > filtered(OptSpecifiers...Ids) const
Definition: ArgList.h:209
size_t getBufferSize() const
Definition: MemoryBuffer.h:175
std::error_code writeImportLibrary(StringRef ImportName, StringRef Path, ArrayRef< COFFShortExport > Exports, COFF::MachineTypes Machine, bool MakeWeakAliases)
Optional< MemoryBufferRef > openFile(StringRef Path)
#define E
Definition: LargeTest.cpp:27
void replace_extension(SmallVectorImpl< char > &path, const Twine &extension, Style style=Style::native)
Replace the file extension of path with extension.
Definition: Path.cpp:490
bool hasArgNoClaim(OptSpecifiers...Ids) const
hasArg - Does the arg list contain any option matching Id.
Definition: ArgList.h:244
Arg * getLastArg(OptSpecifiers...Ids) const
Return the last argument matching Id, or null.
Definition: ArgList.h:254
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:267
Defines the llvm::Arg class for parsed arguments.
static std::string getImplibPath(std::string Path)
Entry for a single option instance in the option data table.
Definition: OptTable.h:42
MachineTypes
Definition: COFF.h:94
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
StringRef getLastArgValue(OptSpecifier Id, StringRef Default="") const
getLastArgValue - Return the value of the last argument, or a default.
Definition: ArgList.cpp:86
bool hasArg(OptSpecifiers...Ids) const
Definition: ArgList.h:248
std::vector< std::unique_ptr< MemoryBuffer > > OwningMBs
std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition: Error.cpp:84
reference get()
Definition: ErrorOr.h:169