Coverage Report

Created: 2019-05-19 14:56

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