Coverage Report

Created: 2018-06-25 02:00

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/COFF/DriverUtils.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- DriverUtils.cpp ----------------------------------------------------===//
2
//
3
//                             The LLVM Linker
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// This file contains utility functions for the driver. Because there
11
// are so many small functions, we created this separate file to make
12
// Driver.cpp less cluttered.
13
//
14
//===----------------------------------------------------------------------===//
15
16
#include "Config.h"
17
#include "Driver.h"
18
#include "Symbols.h"
19
#include "lld/Common/ErrorHandler.h"
20
#include "lld/Common/Memory.h"
21
#include "llvm/ADT/Optional.h"
22
#include "llvm/ADT/StringSwitch.h"
23
#include "llvm/BinaryFormat/COFF.h"
24
#include "llvm/Object/COFF.h"
25
#include "llvm/Object/WindowsResource.h"
26
#include "llvm/Option/Arg.h"
27
#include "llvm/Option/ArgList.h"
28
#include "llvm/Option/Option.h"
29
#include "llvm/Support/CommandLine.h"
30
#include "llvm/Support/FileUtilities.h"
31
#include "llvm/Support/MathExtras.h"
32
#include "llvm/Support/Process.h"
33
#include "llvm/Support/Program.h"
34
#include "llvm/Support/raw_ostream.h"
35
#include "llvm/WindowsManifest/WindowsManifestMerger.h"
36
#include <memory>
37
38
using namespace llvm::COFF;
39
using namespace llvm;
40
using llvm::sys::Process;
41
42
namespace lld {
43
namespace coff {
44
namespace {
45
46
const uint16_t SUBLANG_ENGLISH_US = 0x0409;
47
const uint16_t RT_MANIFEST = 24;
48
49
class Executor {
50
public:
51
0
  explicit Executor(StringRef S) : Prog(Saver.save(S)) {}
52
0
  void add(StringRef S) { Args.push_back(Saver.save(S)); }
53
0
  void add(std::string &S) { Args.push_back(Saver.save(S)); }
54
0
  void add(Twine S) { Args.push_back(Saver.save(S)); }
55
0
  void add(const char *S) { Args.push_back(Saver.save(S)); }
56
57
0
  void run() {
58
0
    ErrorOr<std::string> ExeOrErr = sys::findProgramByName(Prog);
59
0
    if (auto EC = ExeOrErr.getError())
60
0
      fatal("unable to find " + Prog + " in PATH: " + EC.message());
61
0
    StringRef Exe = Saver.save(*ExeOrErr);
62
0
    Args.insert(Args.begin(), Exe);
63
0
64
0
    if (sys::ExecuteAndWait(Args[0], Args) != 0)
65
0
      fatal("ExecuteAndWait failed: " +
66
0
            llvm::join(Args.begin(), Args.end(), " "));
67
0
  }
68
69
private:
70
  StringRef Prog;
71
  std::vector<StringRef> Args;
72
};
73
74
} // anonymous namespace
75
76
// Returns /machine's value.
77
21
MachineTypes getMachineType(StringRef S) {
78
21
  MachineTypes MT = StringSwitch<MachineTypes>(S.lower())
79
21
                        .Cases("x64", "amd64", AMD64)
80
21
                        .Cases("x86", "i386", I386)
81
21
                        .Case("arm", ARMNT)
82
21
                        .Case("arm64", ARM64)
83
21
                        .Default(IMAGE_FILE_MACHINE_UNKNOWN);
84
21
  if (MT != IMAGE_FILE_MACHINE_UNKNOWN)
85
21
    return MT;
86
0
  fatal("unknown /machine argument: " + S);
87
0
}
88
89
6
StringRef machineToStr(MachineTypes MT) {
90
6
  switch (MT) {
91
6
  case ARMNT:
92
1
    return "arm";
93
6
  case ARM64:
94
1
    return "arm64";
95
6
  case AMD64:
96
2
    return "x64";
97
6
  case I386:
98
2
    return "x86";
99
6
  default:
100
0
    llvm_unreachable("unknown machine type");
101
6
  }
102
6
}
103
104
// Parses a string in the form of "<integer>[,<integer>]".
105
7
void parseNumbers(StringRef Arg, uint64_t *Addr, uint64_t *Size) {
106
7
  StringRef S1, S2;
107
7
  std::tie(S1, S2) = Arg.split(',');
108
7
  if (S1.getAsInteger(0, *Addr))
109
0
    fatal("invalid number: " + S1);
110
7
  if (Size && 
!S2.empty()5
&&
S2.getAsInteger(0, *Size)2
)
111
0
    fatal("invalid number: " + S2);
112
7
}
113
114
// Parses a string in the form of "<integer>[.<integer>]".
115
// If second number is not present, Minor is set to 0.
116
4
void parseVersion(StringRef Arg, uint32_t *Major, uint32_t *Minor) {
117
4
  StringRef S1, S2;
118
4
  std::tie(S1, S2) = Arg.split('.');
119
4
  if (S1.getAsInteger(0, *Major))
120
0
    fatal("invalid number: " + S1);
121
4
  *Minor = 0;
122
4
  if (!S2.empty() && 
S2.getAsInteger(0, *Minor)3
)
123
0
    fatal("invalid number: " + S2);
124
4
}
125
126
8
void parseGuard(StringRef FullArg) {
127
8
  SmallVector<StringRef, 1> SplitArgs;
128
8
  FullArg.split(SplitArgs, ",");
129
8
  for (StringRef Arg : SplitArgs) {
130
8
    if (Arg.equals_lower("no"))
131
0
      Config->GuardCF = GuardCFLevel::Off;
132
8
    else if (Arg.equals_lower("nolongjmp"))
133
6
      Config->GuardCF = GuardCFLevel::NoLongJmp;
134
2
    else if (Arg.equals_lower("cf") || 
Arg.equals_lower("longjmp")0
)
135
2
      Config->GuardCF = GuardCFLevel::Full;
136
0
    else
137
0
      fatal("invalid argument to /guard: " + Arg);
138
8
  }
139
8
}
140
141
// Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
142
void parseSubsystem(StringRef Arg, WindowsSubsystem *Sys, uint32_t *Major,
143
133
                    uint32_t *Minor) {
144
133
  StringRef SysStr, Ver;
145
133
  std::tie(SysStr, Ver) = Arg.split(',');
146
133
  *Sys = StringSwitch<WindowsSubsystem>(SysStr.lower())
147
133
    .Case("boot_application", IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)
148
133
    .Case("console", IMAGE_SUBSYSTEM_WINDOWS_CUI)
149
133
    .Case("efi_application", IMAGE_SUBSYSTEM_EFI_APPLICATION)
150
133
    .Case("efi_boot_service_driver", IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)
151
133
    .Case("efi_rom", IMAGE_SUBSYSTEM_EFI_ROM)
152
133
    .Case("efi_runtime_driver", IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)
153
133
    .Case("native", IMAGE_SUBSYSTEM_NATIVE)
154
133
    .Case("posix", IMAGE_SUBSYSTEM_POSIX_CUI)
155
133
    .Case("windows", IMAGE_SUBSYSTEM_WINDOWS_GUI)
156
133
    .Default(IMAGE_SUBSYSTEM_UNKNOWN);
157
133
  if (*Sys == IMAGE_SUBSYSTEM_UNKNOWN)
158
0
    fatal("unknown subsystem: " + SysStr);
159
133
  if (!Ver.empty())
160
2
    parseVersion(Ver, Major, Minor);
161
133
}
162
163
// Parse a string of the form of "<from>=<to>".
164
// Results are directly written to Config.
165
9
void parseAlternateName(StringRef S) {
166
9
  StringRef From, To;
167
9
  std::tie(From, To) = S.split('=');
168
9
  if (From.empty() || To.empty())
169
0
    fatal("/alternatename: invalid argument: " + S);
170
9
  auto It = Config->AlternateNames.find(From);
171
9
  if (It != Config->AlternateNames.end() && 
It->second != To1
)
172
0
    fatal("/alternatename: conflicts: " + S);
173
9
  Config->AlternateNames.insert(It, std::make_pair(From, To));
174
9
}
175
176
// Parse a string of the form of "<from>=<to>".
177
// Results are directly written to Config.
178
2.11k
void parseMerge(StringRef S) {
179
2.11k
  StringRef From, To;
180
2.11k
  std::tie(From, To) = S.split('=');
181
2.11k
  if (From.empty() || To.empty())
182
0
    fatal("/merge: invalid argument: " + S);
183
2.11k
  if (From == ".rsrc" || To == ".rsrc")
184
0
    fatal("/merge: cannot merge '.rsrc' with any section");
185
2.11k
  if (From == ".reloc" || To == ".reloc")
186
0
    fatal("/merge: cannot merge '.reloc' with any section");
187
2.11k
  auto Pair = Config->Merge.insert(std::make_pair(From, To));
188
2.11k
  bool Inserted = Pair.second;
189
2.11k
  if (!Inserted) {
190
3
    StringRef Existing = Pair.first->second;
191
3
    if (Existing != To)
192
2
      warn(S + ": already merged into " + Existing);
193
3
  }
194
2.11k
}
195
196
6
static uint32_t parseSectionAttributes(StringRef S) {
197
6
  uint32_t Ret = 0;
198
10
  for (char C : S.lower()) {
199
10
    switch (C) {
200
10
    case 'd':
201
0
      Ret |= IMAGE_SCN_MEM_DISCARDABLE;
202
0
      break;
203
10
    case 'e':
204
3
      Ret |= IMAGE_SCN_MEM_EXECUTE;
205
3
      break;
206
10
    case 'k':
207
0
      Ret |= IMAGE_SCN_MEM_NOT_CACHED;
208
0
      break;
209
10
    case 'p':
210
0
      Ret |= IMAGE_SCN_MEM_NOT_PAGED;
211
0
      break;
212
10
    case 'r':
213
3
      Ret |= IMAGE_SCN_MEM_READ;
214
3
      break;
215
10
    case 's':
216
1
      Ret |= IMAGE_SCN_MEM_SHARED;
217
1
      break;
218
10
    case 'w':
219
3
      Ret |= IMAGE_SCN_MEM_WRITE;
220
3
      break;
221
10
    default:
222
0
      fatal("/section: invalid argument: " + S);
223
10
    }
224
10
  }
225
6
  return Ret;
226
6
}
227
228
// Parses /section option argument.
229
6
void parseSection(StringRef S) {
230
6
  StringRef Name, Attrs;
231
6
  std::tie(Name, Attrs) = S.split(',');
232
6
  if (Name.empty() || Attrs.empty())
233
0
    fatal("/section: invalid argument: " + S);
234
6
  Config->Section[Name] = parseSectionAttributes(Attrs);
235
6
}
236
237
// Parses /aligncomm option argument.
238
1
void parseAligncomm(StringRef S) {
239
1
  StringRef Name, Align;
240
1
  std::tie(Name, Align) = S.split(',');
241
1
  if (Name.empty() || Align.empty()) {
242
0
    error("/aligncomm: invalid argument: " + S);
243
0
    return;
244
0
  }
245
1
  int V;
246
1
  if (Align.getAsInteger(0, V)) {
247
0
    error("/aligncomm: invalid argument: " + S);
248
0
    return;
249
0
  }
250
1
  Config->AlignComm[Name] = std::max(Config->AlignComm[Name], 1 << V);
251
1
}
252
253
// Parses a string in the form of "EMBED[,=<integer>]|NO".
254
// Results are directly written to Config.
255
1
void parseManifest(StringRef Arg) {
256
1
  if (Arg.equals_lower("no")) {
257
0
    Config->Manifest = Configuration::No;
258
0
    return;
259
0
  }
260
1
  if (!Arg.startswith_lower("embed"))
261
0
    fatal("invalid option " + Arg);
262
1
  Config->Manifest = Configuration::Embed;
263
1
  Arg = Arg.substr(strlen("embed"));
264
1
  if (Arg.empty())
265
1
    return;
266
0
  if (!Arg.startswith_lower(",id="))
267
0
    fatal("invalid option " + Arg);
268
0
  Arg = Arg.substr(strlen(",id="));
269
0
  if (Arg.getAsInteger(0, Config->ManifestID))
270
0
    fatal("invalid option " + Arg);
271
0
}
272
273
// Parses a string in the form of "level=<string>|uiAccess=<string>|NO".
274
// Results are directly written to Config.
275
4
void parseManifestUAC(StringRef Arg) {
276
4
  if (Arg.equals_lower("no")) {
277
2
    Config->ManifestUAC = false;
278
2
    return;
279
2
  }
280
5
  
for (;;)2
{
281
5
    Arg = Arg.ltrim();
282
5
    if (Arg.empty())
283
2
      return;
284
3
    if (Arg.startswith_lower("level=")) {
285
2
      Arg = Arg.substr(strlen("level="));
286
2
      std::tie(Config->ManifestLevel, Arg) = Arg.split(" ");
287
2
      continue;
288
2
    }
289
1
    if (Arg.startswith_lower("uiaccess=")) {
290
1
      Arg = Arg.substr(strlen("uiaccess="));
291
1
      std::tie(Config->ManifestUIAccess, Arg) = Arg.split(" ");
292
1
      continue;
293
1
    }
294
0
    fatal("invalid option " + Arg);
295
0
  }
296
2
}
297
298
// An RAII temporary file class that automatically removes a temporary file.
299
namespace {
300
class TemporaryFile {
301
public:
302
0
  TemporaryFile(StringRef Prefix, StringRef Extn, StringRef Contents = "") {
303
0
    SmallString<128> S;
304
0
    if (auto EC = sys::fs::createTemporaryFile("lld-" + Prefix, Extn, S))
305
0
      fatal("cannot create a temporary file: " + EC.message());
306
0
    Path = S.str();
307
0
308
0
    if (!Contents.empty()) {
309
0
      std::error_code EC;
310
0
      raw_fd_ostream OS(Path, EC, sys::fs::F_None);
311
0
      if (EC)
312
0
        fatal("failed to open " + Path + ": " + EC.message());
313
0
      OS << Contents;
314
0
    }
315
0
  }
316
317
0
  TemporaryFile(TemporaryFile &&Obj) {
318
0
    std::swap(Path, Obj.Path);
319
0
  }
320
321
0
  ~TemporaryFile() {
322
0
    if (Path.empty())
323
0
      return;
324
0
    if (sys::fs::remove(Path))
325
0
      fatal("failed to remove " + Path);
326
0
  }
327
328
  // Returns a memory buffer of this temporary file.
329
  // Note that this function does not leave the file open,
330
  // so it is safe to remove the file immediately after this function
331
  // is called (you cannot remove an opened file on Windows.)
332
0
  std::unique_ptr<MemoryBuffer> getMemoryBuffer() {
333
0
    // IsVolatileSize=true forces MemoryBuffer to not use mmap().
334
0
    return CHECK(MemoryBuffer::getFile(Path, /*FileSize=*/-1,
335
0
                                       /*RequiresNullTerminator=*/false,
336
0
                                       /*IsVolatileSize=*/true),
337
0
                 "could not open " + Path);
338
0
  }
339
340
  std::string Path;
341
};
342
}
343
344
6
static std::string createDefaultXml() {
345
6
  std::string Ret;
346
6
  raw_string_ostream OS(Ret);
347
6
348
6
  // Emit the XML. Note that we do *not* verify that the XML attributes are
349
6
  // syntactically correct. This is intentional for link.exe compatibility.
350
6
  OS << "<?xml version=\"1.0\" standalone=\"yes\"?>\n"
351
6
     << "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n"
352
6
     << "          manifestVersion=\"1.0\">\n";
353
6
  if (Config->ManifestUAC) {
354
4
    OS << "  <trustInfo>\n"
355
4
       << "    <security>\n"
356
4
       << "      <requestedPrivileges>\n"
357
4
       << "         <requestedExecutionLevel level=" << Config->ManifestLevel
358
4
       << " uiAccess=" << Config->ManifestUIAccess << "/>\n"
359
4
       << "      </requestedPrivileges>\n"
360
4
       << "    </security>\n"
361
4
       << "  </trustInfo>\n";
362
4
  }
363
6
  if (!Config->ManifestDependency.empty()) {
364
2
    OS << "  <dependency>\n"
365
2
       << "    <dependentAssembly>\n"
366
2
       << "      <assemblyIdentity " << Config->ManifestDependency << " />\n"
367
2
       << "    </dependentAssembly>\n"
368
2
       << "  </dependency>\n";
369
2
  }
370
6
  OS << "</assembly>\n";
371
6
  return OS.str();
372
6
}
373
374
1
static std::string createManifestXmlWithInternalMt(StringRef DefaultXml) {
375
1
  std::unique_ptr<MemoryBuffer> DefaultXmlCopy =
376
1
      MemoryBuffer::getMemBufferCopy(DefaultXml);
377
1
378
1
  windows_manifest::WindowsManifestMerger Merger;
379
1
  if (auto E = Merger.merge(*DefaultXmlCopy.get()))
380
0
    fatal("internal manifest tool failed on default xml: " +
381
0
          toString(std::move(E)));
382
1
383
1
  for (StringRef Filename : Config->ManifestInput) {
384
1
    std::unique_ptr<MemoryBuffer> Manifest =
385
1
        check(MemoryBuffer::getFile(Filename));
386
1
    if (auto E = Merger.merge(*Manifest.get()))
387
0
      fatal("internal manifest tool failed on file " + Filename + ": " +
388
0
            toString(std::move(E)));
389
1
  }
390
1
391
1
  return Merger.getMergedManifest().get()->getBuffer();
392
1
}
393
394
0
static std::string createManifestXmlWithExternalMt(StringRef DefaultXml) {
395
0
  // Create the default manifest file as a temporary file.
396
0
  TemporaryFile Default("defaultxml", "manifest");
397
0
  std::error_code EC;
398
0
  raw_fd_ostream OS(Default.Path, EC, sys::fs::F_Text);
399
0
  if (EC)
400
0
    fatal("failed to open " + Default.Path + ": " + EC.message());
401
0
  OS << DefaultXml;
402
0
  OS.close();
403
0
404
0
  // Merge user-supplied manifests if they are given.  Since libxml2 is not
405
0
  // enabled, we must shell out to Microsoft's mt.exe tool.
406
0
  TemporaryFile User("user", "manifest");
407
0
408
0
  Executor E("mt.exe");
409
0
  E.add("/manifest");
410
0
  E.add(Default.Path);
411
0
  for (StringRef Filename : Config->ManifestInput) {
412
0
    E.add("/manifest");
413
0
    E.add(Filename);
414
0
  }
415
0
  E.add("/nologo");
416
0
  E.add("/out:" + StringRef(User.Path));
417
0
  E.run();
418
0
419
0
  return CHECK(MemoryBuffer::getFile(User.Path), "could not open " + User.Path)
420
0
      .get()
421
0
      ->getBuffer();
422
0
}
423
424
6
static std::string createManifestXml() {
425
6
  std::string DefaultXml = createDefaultXml();
426
6
  if (Config->ManifestInput.empty())
427
5
    return DefaultXml;
428
1
429
1
  if (windows_manifest::isAvailable())
430
1
    return createManifestXmlWithInternalMt(DefaultXml);
431
0
432
0
  return createManifestXmlWithExternalMt(DefaultXml);
433
0
}
434
435
static std::unique_ptr<WritableMemoryBuffer>
436
1
createMemoryBufferForManifestRes(size_t ManifestSize) {
437
1
  size_t ResSize = alignTo(
438
1
      object::WIN_RES_MAGIC_SIZE + object::WIN_RES_NULL_ENTRY_SIZE +
439
1
          sizeof(object::WinResHeaderPrefix) + sizeof(object::WinResIDs) +
440
1
          sizeof(object::WinResHeaderSuffix) + ManifestSize,
441
1
      object::WIN_RES_DATA_ALIGNMENT);
442
1
  return WritableMemoryBuffer::getNewMemBuffer(ResSize, Config->OutputFile +
443
1
                                                            ".manifest.res");
444
1
}
445
446
1
static void writeResFileHeader(char *&Buf) {
447
1
  memcpy(Buf, COFF::WinResMagic, sizeof(COFF::WinResMagic));
448
1
  Buf += sizeof(COFF::WinResMagic);
449
1
  memset(Buf, 0, object::WIN_RES_NULL_ENTRY_SIZE);
450
1
  Buf += object::WIN_RES_NULL_ENTRY_SIZE;
451
1
}
452
453
1
static void writeResEntryHeader(char *&Buf, size_t ManifestSize) {
454
1
  // Write the prefix.
455
1
  auto *Prefix = reinterpret_cast<object::WinResHeaderPrefix *>(Buf);
456
1
  Prefix->DataSize = ManifestSize;
457
1
  Prefix->HeaderSize = sizeof(object::WinResHeaderPrefix) +
458
1
                       sizeof(object::WinResIDs) +
459
1
                       sizeof(object::WinResHeaderSuffix);
460
1
  Buf += sizeof(object::WinResHeaderPrefix);
461
1
462
1
  // Write the Type/Name IDs.
463
1
  auto *IDs = reinterpret_cast<object::WinResIDs *>(Buf);
464
1
  IDs->setType(RT_MANIFEST);
465
1
  IDs->setName(Config->ManifestID);
466
1
  Buf += sizeof(object::WinResIDs);
467
1
468
1
  // Write the suffix.
469
1
  auto *Suffix = reinterpret_cast<object::WinResHeaderSuffix *>(Buf);
470
1
  Suffix->DataVersion = 0;
471
1
  Suffix->MemoryFlags = object::WIN_RES_PURE_MOVEABLE;
472
1
  Suffix->Language = SUBLANG_ENGLISH_US;
473
1
  Suffix->Version = 0;
474
1
  Suffix->Characteristics = 0;
475
1
  Buf += sizeof(object::WinResHeaderSuffix);
476
1
}
477
478
// Create a resource file containing a manifest XML.
479
1
std::unique_ptr<MemoryBuffer> createManifestRes() {
480
1
  std::string Manifest = createManifestXml();
481
1
482
1
  std::unique_ptr<WritableMemoryBuffer> Res =
483
1
      createMemoryBufferForManifestRes(Manifest.size());
484
1
485
1
  char *Buf = Res->getBufferStart();
486
1
  writeResFileHeader(Buf);
487
1
  writeResEntryHeader(Buf, Manifest.size());
488
1
489
1
  // Copy the manifest data into the .res file.
490
1
  std::copy(Manifest.begin(), Manifest.end(), Buf);
491
1
  return std::move(Res);
492
1
}
493
494
5
void createSideBySideManifest() {
495
5
  std::string Path = Config->ManifestFile;
496
5
  if (Path == "")
497
5
    Path = Config->OutputFile + ".manifest";
498
5
  std::error_code EC;
499
5
  raw_fd_ostream Out(Path, EC, sys::fs::F_Text);
500
5
  if (EC)
501
0
    fatal("failed to create manifest: " + EC.message());
502
5
  Out << createManifestXml();
503
5
}
504
505
// Parse a string in the form of
506
// "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]"
507
// or "<name>=<dllname>.<name>".
508
// Used for parsing /export arguments.
509
142
Export parseExport(StringRef Arg) {
510
142
  Export E;
511
142
  StringRef Rest;
512
142
  std::tie(E.Name, Rest) = Arg.split(",");
513
142
  if (E.Name.empty())
514
0
    goto err;
515
142
516
142
  if (E.Name.contains('=')) {
517
6
    StringRef X, Y;
518
6
    std::tie(X, Y) = E.Name.split("=");
519
6
520
6
    // If "<name>=<dllname>.<name>".
521
6
    if (Y.contains(".")) {
522
1
      E.Name = X;
523
1
      E.ForwardTo = Y;
524
1
      return E;
525
1
    }
526
5
527
5
    E.ExtName = X;
528
5
    E.Name = Y;
529
5
    if (E.Name.empty())
530
0
      goto err;
531
141
  }
532
141
533
141
  // If "<name>=<internalname>[,@ordinal[,NONAME]][,DATA][,PRIVATE]"
534
153
  
while (141
!Rest.empty()) {
535
12
    StringRef Tok;
536
12
    std::tie(Tok, Rest) = Rest.split(",");
537
12
    if (Tok.equals_lower("noname")) {
538
2
      if (E.Ordinal == 0)
539
0
        goto err;
540
2
      E.Noname = true;
541
2
      continue;
542
2
    }
543
10
    if (Tok.equals_lower("data")) {
544
2
      E.Data = true;
545
2
      continue;
546
2
    }
547
8
    if (Tok.equals_lower("constant")) {
548
2
      E.Constant = true;
549
2
      continue;
550
2
    }
551
6
    if (Tok.equals_lower("private")) {
552
0
      E.Private = true;
553
0
      continue;
554
0
    }
555
6
    if (Tok.startswith("@")) {
556
6
      int32_t Ord;
557
6
      if (Tok.substr(1).getAsInteger(0, Ord))
558
0
        goto err;
559
6
      if (Ord <= 0 || 65535 < Ord)
560
0
        goto err;
561
6
      E.Ordinal = Ord;
562
6
      continue;
563
6
    }
564
0
    goto err;
565
0
  }
566
141
  return E;
567
0
568
0
err:
569
0
  fatal("invalid /export: " + Arg);
570
141
}
571
572
188
static StringRef undecorate(StringRef Sym) {
573
188
  if (Config->Machine != I386)
574
129
    return Sym;
575
59
  // In MSVC mode, a fully decorated stdcall function is exported
576
59
  // as-is with the leading underscore (with type IMPORT_NAME).
577
59
  // In MinGW mode, a decorated stdcall function gets the underscore
578
59
  // removed, just like normal cdecl functions.
579
59
  if (Sym.startswith("_") && 
Sym.contains('@')49
&&
!Config->MinGW6
)
580
2
    return Sym;
581
57
  return Sym.startswith("_") ? 
Sym.substr(1)47
:
Sym10
;
582
57
}
583
584
// Convert stdcall/fastcall style symbols into unsuffixed symbols,
585
// with or without a leading underscore. (MinGW specific.)
586
32
static StringRef killAt(StringRef Sym, bool Prefix) {
587
32
  if (Sym.empty())
588
8
    return Sym;
589
24
  // Strip any trailing stdcall suffix
590
24
  Sym = Sym.substr(0, Sym.find('@', 1));
591
24
  if (!Sym.startswith("@")) {
592
18
    if (Prefix && 
!Sym.startswith("_")12
)
593
4
      return Saver.save("_" + Sym);
594
14
    return Sym;
595
14
  }
596
6
  // For fastcall, remove the leading @ and replace it with an
597
6
  // underscore, if prefixes are used.
598
6
  Sym = Sym.substr(1);
599
6
  if (Prefix)
600
4
    Sym = Saver.save("_" + Sym);
601
6
  return Sym;
602
6
}
603
604
// Performs error checking on all /export arguments.
605
// It also sets ordinals.
606
125
void fixupExports() {
607
125
  // Symbol ordinals must be unique.
608
125
  std::set<uint16_t> Ords;
609
188
  for (Export &E : Config->Exports) {
610
188
    if (E.Ordinal == 0)
611
176
      continue;
612
12
    if (!Ords.insert(E.Ordinal).second)
613
0
      fatal("duplicate export ordinal: " + E.Name);
614
12
  }
615
125
616
188
  
for (Export &E : Config->Exports)125
{
617
188
    Symbol *Sym = E.Sym;
618
188
    if (!E.ForwardTo.empty() || 
!Sym186
) {
619
12
      E.SymbolName = E.Name;
620
176
    } else {
621
176
      if (auto *U = dyn_cast<Undefined>(Sym))
622
0
        if (U->WeakAlias)
623
0
          Sym = U->WeakAlias;
624
176
      E.SymbolName = Sym->getName();
625
176
    }
626
188
  }
627
125
628
188
  for (Export &E : Config->Exports) {
629
188
    if (!E.ForwardTo.empty()) {
630
2
      E.ExportName = undecorate(E.Name);
631
186
    } else {
632
186
      E.ExportName = undecorate(E.ExtName.empty() ? 
E.Name178
:
E.ExtName8
);
633
186
    }
634
188
  }
635
125
636
125
  if (Config->KillAt && 
Config->Machine == I3862
) {
637
8
    for (Export &E : Config->Exports) {
638
8
      E.Name = killAt(E.Name, true);
639
8
      E.ExportName = killAt(E.ExportName, false);
640
8
      E.ExtName = killAt(E.ExtName, true);
641
8
      E.SymbolName = killAt(E.SymbolName, true);
642
8
    }
643
2
  }
644
125
645
125
  // Uniquefy by name.
646
125
  DenseMap<StringRef, Export *> Map(Config->Exports.size());
647
125
  std::vector<Export> V;
648
188
  for (Export &E : Config->Exports) {
649
188
    auto Pair = Map.insert(std::make_pair(E.ExportName, &E));
650
188
    bool Inserted = Pair.second;
651
188
    if (Inserted) {
652
180
      V.push_back(E);
653
180
      continue;
654
180
    }
655
8
    Export *Existing = Pair.first->second;
656
8
    if (E == *Existing || 
E.Name != Existing->Name2
)
657
6
      continue;
658
2
    warn("duplicate /export option: " + E.Name);
659
2
  }
660
125
  Config->Exports = std::move(V);
661
125
662
125
  // Sort by name.
663
125
  std::sort(Config->Exports.begin(), Config->Exports.end(),
664
125
            [](const Export &A, const Export &B) {
665
113
              return A.ExportName < B.ExportName;
666
113
            });
667
125
}
668
669
117
void assignExportOrdinals() {
670
117
  // Assign unique ordinals if default (= 0).
671
117
  uint16_t Max = 0;
672
117
  for (Export &E : Config->Exports)
673
170
    Max = std::max(Max, E.Ordinal);
674
117
  for (Export &E : Config->Exports)
675
170
    if (E.Ordinal == 0)
676
160
      E.Ordinal = ++Max;
677
117
}
678
679
// Parses a string in the form of "key=value" and check
680
// if value matches previous values for the same key.
681
4
void checkFailIfMismatch(StringRef Arg) {
682
4
  StringRef K, V;
683
4
  std::tie(K, V) = Arg.split('=');
684
4
  if (K.empty() || V.empty())
685
0
    fatal("/failifmismatch: invalid argument: " + Arg);
686
4
  StringRef Existing = Config->MustMatch[K];
687
4
  if (!Existing.empty() && 
V != Existing1
)
688
0
    fatal("/failifmismatch: mismatch detected: " + Existing + " and " + V +
689
0
          " for key " + K);
690
4
  Config->MustMatch[K] = V;
691
4
}
692
693
// Convert Windows resource files (.res files) to a .obj file.
694
4
MemoryBufferRef convertResToCOFF(ArrayRef<MemoryBufferRef> MBs) {
695
4
  object::WindowsResourceParser Parser;
696
4
697
6
  for (MemoryBufferRef MB : MBs) {
698
6
    std::unique_ptr<object::Binary> Bin = check(object::createBinary(MB));
699
6
    object::WindowsResource *RF = dyn_cast<object::WindowsResource>(Bin.get());
700
6
    if (!RF)
701
0
      fatal("cannot compile non-resource file as resource");
702
6
    if (auto EC = Parser.parse(RF))
703
0
      fatal("failed to parse .res file: " + toString(std::move(EC)));
704
6
  }
705
4
706
4
  Expected<std::unique_ptr<MemoryBuffer>> E =
707
4
      llvm::object::writeWindowsResourceCOFF(Config->Machine, Parser);
708
4
  if (!E)
709
0
    fatal("failed to write .res to COFF: " + toString(E.takeError()));
710
4
711
4
  MemoryBufferRef MBRef = **E;
712
4
  make<std::unique_ptr<MemoryBuffer>>(std::move(*E)); // take ownership
713
4
  return MBRef;
714
4
}
715
716
// Run MSVC link.exe for given in-memory object files.
717
// Command line options are copied from those given to LLD.
718
// This is for the /msvclto option.
719
0
void runMSVCLinker(std::string Rsp, ArrayRef<StringRef> Objects) {
720
0
  // Write the in-memory object files to disk.
721
0
  std::vector<TemporaryFile> Temps;
722
0
  for (StringRef S : Objects) {
723
0
    Temps.emplace_back("lto", "obj", S);
724
0
    Rsp += quote(Temps.back().Path) + "\n";
725
0
  }
726
0
727
0
  log("link.exe " + Rsp);
728
0
729
0
  // Run MSVC link.exe.
730
0
  Temps.emplace_back("lto", "rsp", Rsp);
731
0
  Executor E("link.exe");
732
0
  E.add(Twine("@" + Temps.back().Path));
733
0
  E.run();
734
0
}
735
736
// Create OptTable
737
738
// Create prefix string literals used in Options.td
739
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
740
#include "Options.inc"
741
#undef PREFIX
742
743
// Create table mapping all options defined in Options.td
744
static const llvm::opt::OptTable::Info InfoTable[] = {
745
#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12)      \
746
  {X1, X2, X10,         X11,         OPT_##ID, llvm::opt::Option::KIND##Class, \
747
   X9, X8, OPT_##GROUP, OPT_##ALIAS, X7,       X12},
748
#include "Options.inc"
749
#undef OPTION
750
};
751
752
567
COFFOptTable::COFFOptTable() : OptTable(InfoTable, true) {}
753
754
// Set color diagnostics according to --color-diagnostics={auto,always,never}
755
// or --no-color-diagnostics flags.
756
425
static void handleColorDiagnostics(opt::InputArgList &Args) {
757
425
  auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
758
425
                              OPT_no_color_diagnostics);
759
425
  if (!Arg)
760
425
    return;
761
0
  if (Arg->getOption().getID() == OPT_color_diagnostics) {
762
0
    errorHandler().ColorDiagnostics = true;
763
0
  } else if (Arg->getOption().getID() == OPT_no_color_diagnostics) {
764
0
    errorHandler().ColorDiagnostics = false;
765
0
  } else {
766
0
    StringRef S = Arg->getValue();
767
0
    if (S == "always")
768
0
      errorHandler().ColorDiagnostics = true;
769
0
    else if (S == "never")
770
0
      errorHandler().ColorDiagnostics = false;
771
0
    else if (S != "auto")
772
0
      error("unknown option: --color-diagnostics=" + S);
773
0
  }
774
0
}
775
776
425
static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) {
777
425
  if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) {
778
1
    StringRef S = Arg->getValue();
779
1
    if (S != "windows" && S != "posix")
780
1
      error("invalid response file quoting: " + S);
781
1
    if (S == "windows")
782
0
      return cl::TokenizeWindowsCommandLine;
783
1
    return cl::TokenizeGNUCommandLine;
784
1
  }
785
424
  // The COFF linker always defaults to Windows quoting.
786
424
  return cl::TokenizeWindowsCommandLine;
787
424
}
788
789
// Parses a given list of options.
790
425
opt::InputArgList ArgParser::parse(ArrayRef<const char *> Argv) {
791
425
  // Make InputArgList from string vectors.
792
425
  unsigned MissingIndex;
793
425
  unsigned MissingCount;
794
425
  SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
795
425
796
425
  // We need to get the quoting style for response files before parsing all
797
425
  // options so we parse here before and ignore all the options but
798
425
  // --rsp-quoting.
799
425
  opt::InputArgList Args = Table.ParseArgs(Vec, MissingIndex, MissingCount);
800
425
801
425
  // Expand response files (arguments in the form of @<filename>)
802
425
  // and then parse the argument again.
803
425
  cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec);
804
425
  Args = Table.ParseArgs(Vec, MissingIndex, MissingCount);
805
425
806
425
  // Print the real command line if response files are expanded.
807
425
  if (Args.hasArg(OPT_verbose) && 
Argv.size() != Vec.size()32
) {
808
0
    std::string Msg = "Command line:";
809
0
    for (const char *S : Vec)
810
0
      Msg += " " + std::string(S);
811
0
    message(Msg);
812
0
  }
813
425
814
425
  // Handle /WX early since it converts missing argument warnings to errors.
815
425
  errorHandler().FatalWarnings = Args.hasFlag(OPT_WX, OPT_WX_no, false);
816
425
817
425
  if (MissingCount)
818
0
    fatal(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
819
425
820
425
  handleColorDiagnostics(Args);
821
425
822
425
  for (auto *Arg : Args.filtered(OPT_UNKNOWN))
823
4
    warn("ignoring unknown argument: " + Arg->getSpelling());
824
425
  return Args;
825
425
}
826
827
// Tokenizes and parses a given string as command line in .drective section.
828
// /EXPORT options are processed in fastpath.
829
std::pair<opt::InputArgList, std::vector<StringRef>>
830
139
ArgParser::parseDirectives(StringRef S) {
831
139
  std::vector<StringRef> Exports;
832
139
  SmallVector<const char *, 16> Rest;
833
139
834
196
  for (StringRef Tok : tokenize(S)) {
835
196
    if (Tok.startswith_lower("/export:") || 
Tok.startswith_lower("-export:")119
)
836
95
      Exports.push_back(Tok.substr(strlen("/export:")));
837
101
    else
838
101
      Rest.push_back(Tok.data());
839
196
  }
840
139
841
139
  // Make InputArgList from unparsed string vectors.
842
139
  unsigned MissingIndex;
843
139
  unsigned MissingCount;
844
139
845
139
  opt::InputArgList Args = Table.ParseArgs(Rest, MissingIndex, MissingCount);
846
139
847
139
  if (MissingCount)
848
0
    fatal(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
849
139
  for (auto *Arg : Args.filtered(OPT_UNKNOWN))
850
0
    warn("ignoring unknown argument: " + Arg->getSpelling());
851
139
  return {std::move(Args), std::move(Exports)};
852
139
}
853
854
// link.exe has an interesting feature. If LINK or _LINK_ environment
855
// variables exist, their contents are handled as command line strings.
856
// So you can pass extra arguments using them.
857
425
opt::InputArgList ArgParser::parseLINK(std::vector<const char *> Argv) {
858
425
  // Concatenate LINK env and command line arguments, and then parse them.
859
425
  if (Optional<std::string> S = Process::GetEnv("LINK")) {
860
1
    std::vector<const char *> V = tokenize(*S);
861
1
    Argv.insert(Argv.begin(), V.begin(), V.end());
862
1
  }
863
425
  if (Optional<std::string> S = Process::GetEnv("_LINK_")) {
864
1
    std::vector<const char *> V = tokenize(*S);
865
1
    Argv.insert(Argv.begin(), V.begin(), V.end());
866
1
  }
867
425
  return parse(Argv);
868
425
}
869
870
141
std::vector<const char *> ArgParser::tokenize(StringRef S) {
871
141
  SmallVector<const char *, 16> Tokens;
872
141
  cl::TokenizeWindowsCommandLine(S, Saver, Tokens);
873
141
  return std::vector<const char *>(Tokens.begin(), Tokens.end());
874
141
}
875
876
3
void printHelp(const char *Argv0) {
877
3
  COFFOptTable().PrintHelp(outs(), Argv0, "LLVM Linker", false);
878
3
}
879
880
} // namespace coff
881
} // namespace lld