Coverage Report

Created: 2017-09-21 03:39

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