Coverage Report

Created: 2018-06-18 20:01

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/COFF/Driver.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Driver.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
#include "Driver.h"
11
#include "Config.h"
12
#include "ICF.h"
13
#include "InputFiles.h"
14
#include "MarkLive.h"
15
#include "MinGW.h"
16
#include "SymbolTable.h"
17
#include "Symbols.h"
18
#include "Writer.h"
19
#include "lld/Common/Args.h"
20
#include "lld/Common/Driver.h"
21
#include "lld/Common/ErrorHandler.h"
22
#include "lld/Common/Memory.h"
23
#include "lld/Common/Timer.h"
24
#include "lld/Common/Version.h"
25
#include "llvm/ADT/Optional.h"
26
#include "llvm/ADT/StringSwitch.h"
27
#include "llvm/BinaryFormat/Magic.h"
28
#include "llvm/Object/ArchiveWriter.h"
29
#include "llvm/Object/COFFImportFile.h"
30
#include "llvm/Object/COFFModuleDefinition.h"
31
#include "llvm/Option/Arg.h"
32
#include "llvm/Option/ArgList.h"
33
#include "llvm/Option/Option.h"
34
#include "llvm/Support/Debug.h"
35
#include "llvm/Support/Path.h"
36
#include "llvm/Support/Process.h"
37
#include "llvm/Support/TarWriter.h"
38
#include "llvm/Support/TargetSelect.h"
39
#include "llvm/Support/raw_ostream.h"
40
#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
41
#include <algorithm>
42
#include <future>
43
#include <memory>
44
45
using namespace llvm;
46
using namespace llvm::object;
47
using namespace llvm::COFF;
48
using llvm::sys::Process;
49
50
namespace lld {
51
namespace coff {
52
53
static Timer InputFileTimer("Input File Reading", Timer::root());
54
55
Configuration *Config;
56
LinkerDriver *Driver;
57
58
425
bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
59
425
  errorHandler().LogName = Args[0];
60
425
  errorHandler().ErrorOS = &Diag;
61
425
  errorHandler().ColorDiagnostics = Diag.has_colors();
62
425
  errorHandler().ErrorLimitExceededMsg =
63
425
      "too many errors emitted, stopping now"
64
425
      " (use /errorlimit:0 to see all errors)";
65
425
  errorHandler().ExitEarly = CanExitEarly;
66
425
  Config = make<Configuration>();
67
425
  Config->Argv = {Args.begin(), Args.end()};
68
425
69
425
  Symtab = make<SymbolTable>();
70
425
71
425
  Driver = make<LinkerDriver>();
72
425
  Driver->link(Args);
73
425
74
425
  // Call exit() if we can to avoid calling destructors.
75
425
  if (CanExitEarly)
76
0
    exitLld(errorCount() ? 1 : 0);
77
425
78
425
  freeArena();
79
425
  return !errorCount();
80
425
}
81
82
// Drop directory components and replace extension with ".exe" or ".dll".
83
18
static std::string getOutputPath(StringRef Path) {
84
18
  auto P = Path.find_last_of("\\/");
85
18
  StringRef S = (P == StringRef::npos) ? 
Path2
:
Path.substr(P + 1)16
;
86
18
  const char* E = Config->DLL ? 
".dll"2
:
".exe"16
;
87
18
  return (S.substr(0, S.rfind('.')) + E).str();
88
18
}
89
90
// ErrorOr is not default constructible, so it cannot be used as the type
91
// parameter of a future.
92
// FIXME: We could open the file in createFutureForFile and avoid needing to
93
// return an error here, but for the moment that would cost us a file descriptor
94
// (a limited resource on Windows) for the duration that the future is pending.
95
typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
96
97
// Create a std::future that opens and maps a file using the best strategy for
98
// the host platform.
99
538
static std::future<MBErrPair> createFutureForFile(std::string Path) {
100
#if _WIN32
101
  // On Windows, file I/O is relatively slow so it is best to do this
102
  // asynchronously.
103
  auto Strategy = std::launch::async;
104
#else
105
  auto Strategy = std::launch::deferred;
106
538
#endif
107
538
  return std::async(Strategy, [=]() {
108
538
    auto MBOrErr = MemoryBuffer::getFile(Path,
109
538
                                         /*FileSize*/ -1,
110
538
                                         /*RequiresNullTerminator*/ false);
111
538
    if (!MBOrErr)
112
4
      return MBErrPair{nullptr, MBOrErr.getError()};
113
534
    return MBErrPair{std::move(*MBOrErr), std::error_code()};
114
534
  });
115
538
}
116
117
536
MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
118
536
  MemoryBufferRef MBRef = *MB;
119
536
  make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
120
536
121
536
  if (Driver->Tar)
122
7
    Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
123
7
                        MBRef.getBuffer());
124
536
  return MBRef;
125
536
}
126
127
void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
128
535
                             bool WholeArchive) {
129
535
  StringRef Filename = MB->getBufferIdentifier();
130
535
131
535
  MemoryBufferRef MBRef = takeBuffer(std::move(MB));
132
535
  FilePaths.push_back(Filename);
133
535
134
535
  // File type is detected by contents, not by file extension.
135
535
  switch (identify_magic(MBRef.getBuffer())) {
136
535
  case file_magic::windows_resource:
137
6
    Resources.push_back(MBRef);
138
6
    break;
139
535
  case file_magic::archive:
140
68
    if (WholeArchive) {
141
4
      std::unique_ptr<Archive> File =
142
4
          CHECK(Archive::create(MBRef), Filename + ": failed to parse archive");
143
4
144
4
      for (MemoryBufferRef M : getArchiveMembers(File.get()))
145
4
        addArchiveBuffer(M, "<whole-archive>", Filename);
146
4
      return;
147
4
    }
148
64
    Symtab->addFile(make<ArchiveFile>(MBRef));
149
64
    break;
150
64
  case file_magic::bitcode:
151
43
    Symtab->addFile(make<BitcodeFile>(MBRef));
152
43
    break;
153
417
  case file_magic::coff_object:
154
417
  case file_magic::coff_import_library:
155
417
    Symtab->addFile(make<ObjFile>(MBRef));
156
417
    break;
157
417
  case file_magic::coff_cl_gl_object:
158
1
    error(Filename + ": is not a native COFF file. Recompile without /GL");
159
1
    break;
160
417
  case file_magic::pecoff_executable:
161
0
    if (Filename.endswith_lower(".dll")) {
162
0
      error(Filename + ": bad file type. Did you specify a DLL instead of an "
163
0
                       "import library?");
164
0
      break;
165
0
    }
166
0
    LLVM_FALLTHROUGH;
167
0
  default:
168
0
    error(MBRef.getBufferIdentifier() + ": unknown file type");
169
0
    break;
170
535
  }
171
535
}
172
173
538
void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
174
538
  auto Future =
175
538
      std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
176
538
  std::string PathStr = Path;
177
538
  enqueueTask([=]() {
178
538
    auto MBOrErr = Future->get();
179
538
    if (MBOrErr.second)
180
4
      error("could not open " + PathStr + ": " + MBOrErr.second.message());
181
534
    else
182
534
      Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
183
538
  });
184
538
}
185
186
void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
187
105
                                    StringRef ParentName) {
188
105
  file_magic Magic = identify_magic(MB.getBuffer());
189
105
  if (Magic == file_magic::coff_import_library) {
190
78
    Symtab->addFile(make<ImportFile>(MB));
191
78
    return;
192
78
  }
193
27
194
27
  InputFile *Obj;
195
27
  if (Magic == file_magic::coff_object) {
196
18
    Obj = make<ObjFile>(MB);
197
18
  } else 
if (9
Magic == file_magic::bitcode9
) {
198
9
    Obj = make<BitcodeFile>(MB);
199
9
  } else {
200
0
    error("unknown file type: " + MB.getBufferIdentifier());
201
0
    return;
202
0
  }
203
27
204
27
  Obj->ParentName = ParentName;
205
27
  Symtab->addFile(Obj);
206
27
  log("Loaded " + toString(Obj) + " for " + SymName);
207
27
}
208
209
void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
210
                                        StringRef SymName,
211
101
                                        StringRef ParentName) {
212
101
  if (!C.getParent()->isThin()) {
213
101
    MemoryBufferRef MB = CHECK(
214
101
        C.getMemoryBufferRef(),
215
101
        "could not get the buffer for the member defining symbol " + SymName);
216
101
    enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
217
101
    return;
218
101
  }
219
0
220
0
  auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
221
0
      CHECK(C.getFullName(),
222
0
            "could not get the filename for the member defining symbol " +
223
0
                SymName)));
224
0
  enqueueTask([=]() {
225
0
    auto MBOrErr = Future->get();
226
0
    if (MBOrErr.second)
227
0
      fatal("could not get the buffer for the member defining " + SymName +
228
0
            ": " + MBOrErr.second.message());
229
0
    Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
230
0
                             ParentName);
231
0
  });
232
0
}
233
234
23
static bool isDecorated(StringRef Sym) {
235
23
  return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
236
23
         (!Config->MinGW && 
Sym.contains('@')21
);
237
23
}
238
239
// Parses .drectve section contents and returns a list of files
240
// specified by /defaultlib.
241
139
void LinkerDriver::parseDirectives(StringRef S) {
242
139
  ArgParser Parser;
243
139
  // .drectve is always tokenized using Windows shell rules.
244
139
  // /EXPORT: option can appear too many times, processing in fastpath.
245
139
  opt::InputArgList Args;
246
139
  std::vector<StringRef> Exports;
247
139
  std::tie(Args, Exports) = Parser.parseDirectives(S);
248
139
249
139
  for (StringRef E : Exports) {
250
95
    // If a common header file contains dllexported function
251
95
    // declarations, many object files may end up with having the
252
95
    // same /EXPORT options. In order to save cost of parsing them,
253
95
    // we dedup them first.
254
95
    if (!DirectivesExports.insert(E).second)
255
0
      continue;
256
95
257
95
    Export Exp = parseExport(E);
258
95
    if (Config->Machine == I386 && 
Config->MinGW18
) {
259
2
      if (!isDecorated(Exp.Name))
260
2
        Exp.Name = Saver.save("_" + Exp.Name);
261
2
      if (!Exp.ExtName.empty() && 
!isDecorated(Exp.ExtName)0
)
262
0
        Exp.ExtName = Saver.save("_" + Exp.ExtName);
263
2
    }
264
95
    Exp.Directives = true;
265
95
    Config->Exports.push_back(Exp);
266
95
  }
267
139
268
139
  for (auto *Arg : Args) {
269
101
    switch (Arg->getOption().getUnaliasedOption().getID()) {
270
101
    case OPT_aligncomm:
271
1
      parseAligncomm(Arg->getValue());
272
1
      break;
273
101
    case OPT_alternatename:
274
2
      parseAlternateName(Arg->getValue());
275
2
      break;
276
101
    case OPT_defaultlib:
277
89
      if (Optional<StringRef> Path = findLib(Arg->getValue()))
278
1
        enqueuePath(*Path, false);
279
89
      break;
280
101
    case OPT_entry:
281
1
      Config->Entry = addUndefined(mangle(Arg->getValue()));
282
1
      break;
283
101
    case OPT_failifmismatch:
284
0
      checkFailIfMismatch(Arg->getValue());
285
0
      break;
286
101
    case OPT_incl:
287
7
      addUndefined(Arg->getValue());
288
7
      break;
289
101
    case OPT_merge:
290
0
      parseMerge(Arg->getValue());
291
0
      break;
292
101
    case OPT_nodefaultlib:
293
0
      Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
294
0
      break;
295
101
    case OPT_section:
296
0
      parseSection(Arg->getValue());
297
0
      break;
298
101
    case OPT_subsystem:
299
1
      parseSubsystem(Arg->getValue(), &Config->Subsystem,
300
1
                     &Config->MajorOSVersion, &Config->MinorOSVersion);
301
1
      break;
302
101
    case OPT_editandcontinue:
303
0
    case OPT_fastfail:
304
0
    case OPT_guardsym:
305
0
    case OPT_natvis:
306
0
    case OPT_throwingnew:
307
0
      break;
308
0
    default:
309
0
      error(Arg->getSpelling() + " is not allowed in .drectve");
310
101
    }
311
101
  }
312
139
}
313
314
// Find file from search paths. You can omit ".obj", this function takes
315
// care of that. Note that the returned path is not guaranteed to exist.
316
549
StringRef LinkerDriver::doFindFile(StringRef Filename) {
317
549
  bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
318
549
  if (HasPathSep)
319
506
    return Filename;
320
43
  bool HasExt = Filename.contains('.');
321
60
  for (StringRef Dir : SearchPaths) {
322
60
    SmallString<128> Path = Dir;
323
60
    sys::path::append(Path, Filename);
324
60
    if (sys::fs::exists(Path.str()))
325
39
      return Saver.save(Path.str());
326
21
    if (!HasExt) {
327
1
      Path.append(".obj");
328
1
      if (sys::fs::exists(Path.str()))
329
0
        return Saver.save(Path.str());
330
1
    }
331
21
  }
332
43
  
return Filename4
;
333
43
}
334
335
1.07k
static Optional<sys::fs::UniqueID> getUniqueID(StringRef Path) {
336
1.07k
  sys::fs::UniqueID Ret;
337
1.07k
  if (sys::fs::getUniqueID(Path, Ret))
338
6
    return None;
339
1.06k
  return Ret;
340
1.06k
}
341
342
// Resolves a file path. This never returns the same path
343
// (in that case, it returns None).
344
535
Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
345
535
  StringRef Path = doFindFile(Filename);
346
535
347
535
  if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) {
348
533
    bool Seen = !VisitedFiles.insert(*ID).second;
349
533
    if (Seen)
350
4
      return None;
351
531
  }
352
531
353
531
  if (Path.endswith_lower(".lib"))
354
63
    VisitedLibs.insert(sys::path::filename(Path));
355
531
  return Path;
356
531
}
357
358
// Find library file from search path.
359
11
StringRef LinkerDriver::doFindLib(StringRef Filename) {
360
11
  // Add ".lib" to Filename if that has no file extension.
361
11
  bool HasExt = Filename.contains('.');
362
11
  if (!HasExt)
363
3
    Filename = Saver.save(Filename + ".lib");
364
11
  return doFindFile(Filename);
365
11
}
366
367
// Resolves a library path. /nodefaultlib options are taken into
368
// consideration. This never returns the same path (in that case,
369
// it returns None).
370
97
Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
371
97
  if (Config->NoDefaultLibAll)
372
88
    return None;
373
9
  if (!VisitedLibs.insert(Filename.lower()).second)
374
0
    return None;
375
9
376
9
  StringRef Path = doFindLib(Filename);
377
9
  if (Config->NoDefaultLibs.count(Path))
378
2
    return None;
379
7
380
7
  if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
381
5
    if (!VisitedFiles.insert(*ID).second)
382
0
      return None;
383
7
  return Path;
384
7
}
385
386
// Parses LIB environment which contains a list of search paths.
387
421
void LinkerDriver::addLibSearchPaths() {
388
421
  Optional<std::string> EnvOpt = Process::GetEnv("LIB");
389
421
  if (!EnvOpt.hasValue())
390
417
    return;
391
4
  StringRef Env = Saver.save(*EnvOpt);
392
8
  while (!Env.empty()) {
393
4
    StringRef Path;
394
4
    std::tie(Path, Env) = Env.split(';');
395
4
    SearchPaths.push_back(Path);
396
4
  }
397
4
}
398
399
613
Symbol *LinkerDriver::addUndefined(StringRef Name) {
400
613
  Symbol *B = Symtab->addUndefined(Name);
401
613
  if (!B->IsGCRoot) {
402
595
    B->IsGCRoot = true;
403
595
    Config->GCRoot.push_back(B);
404
595
  }
405
613
  return B;
406
613
}
407
408
// Symbol names are mangled by appending "_" prefix on x86.
409
4.06k
StringRef LinkerDriver::mangle(StringRef Sym) {
410
4.06k
  assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
411
4.06k
  if (Config->Machine == I386)
412
647
    return Saver.save("_" + Sym);
413
3.41k
  return Sym;
414
3.41k
}
415
416
// Windows specific -- find default entry point name.
417
13
StringRef LinkerDriver::findDefaultEntry() {
418
13
  // User-defined main functions and their corresponding entry points.
419
13
  static const char *Entries[][2] = {
420
13
      {"main", "mainCRTStartup"},
421
13
      {"wmain", "wmainCRTStartup"},
422
13
      {"WinMain", "WinMainCRTStartup"},
423
13
      {"wWinMain", "wWinMainCRTStartup"},
424
13
  };
425
29
  for (auto E : Entries) {
426
29
    StringRef Entry = Symtab->findMangle(mangle(E[0]));
427
29
    if (!Entry.empty() && 
!isa<Undefined>(Symtab->find(Entry))13
)
428
13
      return mangle(E[1]);
429
29
  }
430
13
  
return ""0
;
431
13
}
432
433
265
WindowsSubsystem LinkerDriver::inferSubsystem() {
434
265
  if (Config->DLL)
435
110
    return IMAGE_SUBSYSTEM_WINDOWS_GUI;
436
155
  if (Symtab->findUnderscore("main") || 
Symtab->findUnderscore("wmain")3
)
437
153
    return IMAGE_SUBSYSTEM_WINDOWS_CUI;
438
2
  if (Symtab->findUnderscore("WinMain") || 
Symtab->findUnderscore("wWinMain")1
)
439
2
    return IMAGE_SUBSYSTEM_WINDOWS_GUI;
440
0
  return IMAGE_SUBSYSTEM_UNKNOWN;
441
0
}
442
443
407
static uint64_t getDefaultImageBase() {
444
407
  if (Config->is64())
445
333
    return Config->DLL ? 
0x18000000087
:
0x140000000246
;
446
74
  return Config->DLL ? 
0x1000000027
:
0x40000047
;
447
74
}
448
449
static std::string createResponseFile(const opt::InputArgList &Args,
450
                                      ArrayRef<StringRef> FilePaths,
451
4
                                      ArrayRef<StringRef> SearchPaths) {
452
4
  SmallString<0> Data;
453
4
  raw_svector_ostream OS(Data);
454
4
455
25
  for (auto *Arg : Args) {
456
25
    switch (Arg->getOption().getID()) {
457
25
    case OPT_linkrepro:
458
12
    case OPT_INPUT:
459
12
    case OPT_defaultlib:
460
12
    case OPT_libpath:
461
12
    case OPT_manifest:
462
12
    case OPT_manifest_colon:
463
12
    case OPT_manifestdependency:
464
12
    case OPT_manifestfile:
465
12
    case OPT_manifestinput:
466
12
    case OPT_manifestuac:
467
12
      break;
468
13
    default:
469
13
      OS << toString(*Arg) << "\n";
470
25
    }
471
25
  }
472
4
473
4
  for (StringRef Path : SearchPaths) {
474
2
    std::string RelPath = relativeToRoot(Path);
475
2
    OS << "/libpath:" << quote(RelPath) << "\n";
476
2
  }
477
4
478
4
  for (StringRef Path : FilePaths)
479
7
    OS << quote(relativeToRoot(Path)) << "\n";
480
4
481
4
  return Data.str();
482
4
}
483
484
74
static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
485
74
  unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
486
74
  if (Args.hasArg(OPT_driver))
487
0
    DebugTypes |= static_cast<unsigned>(DebugType::PData);
488
74
  if (Args.hasArg(OPT_profile))
489
1
    DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
490
74
  return DebugTypes;
491
74
}
492
493
2
static unsigned parseDebugType(StringRef Arg) {
494
2
  SmallVector<StringRef, 3> Types;
495
2
  Arg.split(Types, ',', /*KeepEmpty=*/false);
496
2
497
2
  unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
498
2
  for (StringRef Type : Types)
499
2
    DebugTypes |= StringSwitch<unsigned>(Type.lower())
500
2
                      .Case("cv", static_cast<unsigned>(DebugType::CV))
501
2
                      .Case("pdata", static_cast<unsigned>(DebugType::PData))
502
2
                      .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
503
2
                      .Default(0);
504
2
  return DebugTypes;
505
2
}
506
507
421
static std::string getMapFile(const opt::InputArgList &Args) {
508
421
  auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
509
421
  if (!Arg)
510
407
    return "";
511
14
  if (Arg->getOption().getID() == OPT_lldmap_file)
512
13
    return Arg->getValue();
513
1
514
1
  assert(Arg->getOption().getID() == OPT_lldmap);
515
1
  StringRef OutFile = Config->OutputFile;
516
1
  return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
517
1
}
518
519
125
static std::string getImplibPath() {
520
125
  if (!Config->Implib.empty())
521
20
    return Config->Implib;
522
105
  SmallString<128> Out = StringRef(Config->OutputFile);
523
105
  sys::path::replace_extension(Out, ".lib");
524
105
  return Out.str();
525
105
}
526
527
//
528
// The import name is caculated as the following:
529
//
530
//        | LIBRARY w/ ext |   LIBRARY w/o ext   | no LIBRARY
531
//   -----+----------------+---------------------+------------------
532
//   LINK | {value}        | {value}.{.dll/.exe} | {output name}
533
//    LIB | {value}        | {value}.dll         | {output name}.dll
534
//
535
125
static std::string getImportName(bool AsLib) {
536
125
  SmallString<128> Out;
537
125
538
125
  if (Config->ImportName.empty()) {
539
111
    Out.assign(sys::path::filename(Config->OutputFile));
540
111
    if (AsLib)
541
2
      sys::path::replace_extension(Out, ".dll");
542
111
  } else {
543
14
    Out.assign(Config->ImportName);
544
14
    if (!sys::path::has_extension(Out))
545
11
      sys::path::replace_extension(Out,
546
11
                                   (Config->DLL || 
AsLib4
) ?
".dll"10
:
".exe"1
);
547
14
  }
548
125
549
125
  return Out.str();
550
125
}
551
552
125
static void createImportLibrary(bool AsLib) {
553
125
  std::vector<COFFShortExport> Exports;
554
180
  for (Export &E1 : Config->Exports) {
555
180
    COFFShortExport E2;
556
180
    E2.Name = E1.Name;
557
180
    E2.SymbolName = E1.SymbolName;
558
180
    E2.ExtName = E1.ExtName;
559
180
    E2.Ordinal = E1.Ordinal;
560
180
    E2.Noname = E1.Noname;
561
180
    E2.Data = E1.Data;
562
180
    E2.Private = E1.Private;
563
180
    E2.Constant = E1.Constant;
564
180
    Exports.push_back(E2);
565
180
  }
566
125
567
125
  auto HandleError = [](Error &&E) {
568
118
    handleAllErrors(std::move(E),
569
118
                    [](ErrorInfoBase &EIB) 
{ error(EIB.message()); }0
);
570
118
  };
571
125
  std::string LibName = getImportName(AsLib);
572
125
  std::string Path = getImplibPath();
573
125
574
125
  if (!Config->Incremental) {
575
107
    HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
576
107
                                   Config->MinGW));
577
107
    return;
578
107
  }
579
18
580
18
  // If the import library already exists, replace it only if the contents
581
18
  // have changed.
582
18
  ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(
583
18
      Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
584
18
  if (!OldBuf) {
585
10
    HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
586
10
                                   Config->MinGW));
587
10
    return;
588
10
  }
589
8
590
8
  SmallString<128> TmpName;
591
8
  if (std::error_code EC =
592
0
          sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName))
593
0
    fatal("cannot create temporary file for import library " + Path + ": " +
594
0
          EC.message());
595
8
596
8
  if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine,
597
0
                                   Config->MinGW)) {
598
0
    HandleError(std::move(E));
599
0
    return;
600
0
  }
601
8
602
8
  std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(
603
8
      TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
604
8
  if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
605
1
    OldBuf->reset();
606
1
    HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
607
7
  } else {
608
7
    sys::fs::remove(TmpName);
609
7
  }
610
8
}
611
612
28
static void parseModuleDefs(StringRef Path) {
613
28
  std::unique_ptr<MemoryBuffer> MB = CHECK(
614
28
      MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
615
28
  COFFModuleDefinition M = check(parseCOFFModuleDefinition(
616
28
      MB->getMemBufferRef(), Config->Machine, Config->MinGW));
617
28
618
28
  if (Config->OutputFile.empty())
619
3
    Config->OutputFile = Saver.save(M.OutputFile);
620
28
  Config->ImportName = Saver.save(M.ImportName);
621
28
  if (M.ImageBase)
622
0
    Config->ImageBase = M.ImageBase;
623
28
  if (M.StackReserve)
624
2
    Config->StackReserve = M.StackReserve;
625
28
  if (M.StackCommit)
626
1
    Config->StackCommit = M.StackCommit;
627
28
  if (M.HeapReserve)
628
2
    Config->HeapReserve = M.HeapReserve;
629
28
  if (M.HeapCommit)
630
1
    Config->HeapCommit = M.HeapCommit;
631
28
  if (M.MajorImageVersion)
632
0
    Config->MajorImageVersion = M.MajorImageVersion;
633
28
  if (M.MinorImageVersion)
634
0
    Config->MinorImageVersion = M.MinorImageVersion;
635
28
  if (M.MajorOSVersion)
636
0
    Config->MajorOSVersion = M.MajorOSVersion;
637
28
  if (M.MinorOSVersion)
638
0
    Config->MinorOSVersion = M.MinorOSVersion;
639
28
640
34
  for (COFFShortExport E1 : M.Exports) {
641
34
    Export E2;
642
34
    // In simple cases, only Name is set. Renamed exports are parsed
643
34
    // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
644
34
    // it shouldn't be a normal exported function but a forward to another
645
34
    // DLL instead. This is supported by both MS and GNU linkers.
646
34
    if (E1.ExtName != E1.Name && StringRef(E1.Name).contains('.')) {
647
1
      E2.Name = Saver.save(E1.ExtName);
648
1
      E2.ForwardTo = Saver.save(E1.Name);
649
1
      Config->Exports.push_back(E2);
650
1
      continue;
651
1
    }
652
33
    E2.Name = Saver.save(E1.Name);
653
33
    E2.ExtName = Saver.save(E1.ExtName);
654
33
    E2.Ordinal = E1.Ordinal;
655
33
    E2.Noname = E1.Noname;
656
33
    E2.Data = E1.Data;
657
33
    E2.Private = E1.Private;
658
33
    E2.Constant = E1.Constant;
659
33
    Config->Exports.push_back(E2);
660
33
  }
661
28
}
662
663
// A helper function for filterBitcodeFiles.
664
0
static bool needsRebuilding(MemoryBufferRef MB) {
665
0
  // The MSVC linker doesn't support thin archives, so if it's a thin
666
0
  // archive, we always need to rebuild it.
667
0
  std::unique_ptr<Archive> File =
668
0
      CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
669
0
  if (File->isThin())
670
0
    return true;
671
0
672
0
  // Returns true if the archive contains at least one bitcode file.
673
0
  for (MemoryBufferRef Member : getArchiveMembers(File.get()))
674
0
    if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
675
0
      return true;
676
0
  return false;
677
0
}
678
679
// Opens a given path as an archive file and removes bitcode files
680
// from them if exists. This function is to appease the MSVC linker as
681
// their linker doesn't like archive files containing non-native
682
// object files.
683
//
684
// If a given archive doesn't contain bitcode files, the archive path
685
// is returned as-is. Otherwise, a new temporary file is created and
686
// its path is returned.
687
static Optional<std::string>
688
0
filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
689
0
  std::unique_ptr<MemoryBuffer> MB = CHECK(
690
0
      MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
691
0
  MemoryBufferRef MBRef = MB->getMemBufferRef();
692
0
  file_magic Magic = identify_magic(MBRef.getBuffer());
693
0
694
0
  if (Magic == file_magic::bitcode)
695
0
    return None;
696
0
  if (Magic != file_magic::archive)
697
0
    return Path.str();
698
0
  if (!needsRebuilding(MBRef))
699
0
    return Path.str();
700
0
701
0
  std::unique_ptr<Archive> File =
702
0
      CHECK(Archive::create(MBRef),
703
0
            MBRef.getBufferIdentifier() + ": failed to parse archive");
704
0
705
0
  std::vector<NewArchiveMember> New;
706
0
  for (MemoryBufferRef Member : getArchiveMembers(File.get()))
707
0
    if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
708
0
      New.emplace_back(Member);
709
0
710
0
  if (New.empty())
711
0
    return None;
712
0
713
0
  log("Creating a temporary archive for " + Path + " to remove bitcode files");
714
0
715
0
  SmallString<128> S;
716
0
  if (std::error_code EC = sys::fs::createTemporaryFile(
717
0
          "lld-" + sys::path::stem(Path), ".lib", S))
718
0
    fatal("cannot create a temporary file: " + EC.message());
719
0
  std::string Temp = S.str();
720
0
  TemporaryFiles.push_back(Temp);
721
0
722
0
  Error E =
723
0
      llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
724
0
                         /*Deterministics=*/true,
725
0
                         /*Thin=*/false);
726
0
  handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
727
0
    error("failed to create a new archive " + S.str() + ": " + EI.message());
728
0
  });
729
0
  return Temp;
730
0
}
731
732
// Create response file contents and invoke the MSVC linker.
733
0
void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
734
0
  std::string Rsp = "/nologo\n";
735
0
  std::vector<std::string> Temps;
736
0
737
0
  // Write out archive members that we used in symbol resolution and pass these
738
0
  // to MSVC before any archives, so that MSVC uses the same objects to satisfy
739
0
  // references.
740
0
  for (ObjFile *Obj : ObjFile::Instances) {
741
0
    if (Obj->ParentName.empty())
742
0
      continue;
743
0
    SmallString<128> S;
744
0
    int Fd;
745
0
    if (auto EC = sys::fs::createTemporaryFile(
746
0
            "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
747
0
      fatal("cannot create a temporary file: " + EC.message());
748
0
    raw_fd_ostream OS(Fd, /*shouldClose*/ true);
749
0
    OS << Obj->MB.getBuffer();
750
0
    Temps.push_back(S.str());
751
0
    Rsp += quote(S) + "\n";
752
0
  }
753
0
754
0
  for (auto *Arg : Args) {
755
0
    switch (Arg->getOption().getID()) {
756
0
    case OPT_linkrepro:
757
0
    case OPT_lldmap:
758
0
    case OPT_lldmap_file:
759
0
    case OPT_lldsavetemps:
760
0
    case OPT_msvclto:
761
0
      // LLD-specific options are stripped.
762
0
      break;
763
0
    case OPT_opt:
764
0
      if (!StringRef(Arg->getValue()).startswith("lld"))
765
0
        Rsp += toString(*Arg) + " ";
766
0
      break;
767
0
    case OPT_INPUT: {
768
0
      if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
769
0
        if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
770
0
          Rsp += quote(*S) + "\n";
771
0
        continue;
772
0
      }
773
0
      Rsp += quote(Arg->getValue()) + "\n";
774
0
      break;
775
0
    }
776
0
    default:
777
0
      Rsp += toString(*Arg) + "\n";
778
0
    }
779
0
  }
780
0
781
0
  std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
782
0
  runMSVCLinker(Rsp, ObjFiles);
783
0
784
0
  for (StringRef Path : Temps)
785
0
    sys::fs::remove(Path);
786
0
}
787
788
639
void LinkerDriver::enqueueTask(std::function<void()> Task) {
789
639
  TaskQueue.push_back(std::move(Task));
790
639
}
791
792
1.23k
bool LinkerDriver::run() {
793
1.23k
  ScopedTimer T(InputFileTimer);
794
1.23k
795
1.23k
  bool DidWork = !TaskQueue.empty();
796
1.87k
  while (!TaskQueue.empty()) {
797
639
    TaskQueue.front()();
798
639
    TaskQueue.pop_front();
799
639
  }
800
1.23k
  return DidWork;
801
1.23k
}
802
803
// Parse an /order file. If an option is given, the linker places
804
// COMDAT sections in the same order as their names appear in the
805
// given file.
806
8
static void parseOrderFile(StringRef Arg) {
807
8
  // For some reason, the MSVC linker requires a filename to be
808
8
  // preceded by "@".
809
8
  if (!Arg.startswith("@")) {
810
0
    error("malformed /order option: '@' missing");
811
0
    return;
812
0
  }
813
8
814
8
  // Get a list of all comdat sections for error checking.
815
8
  DenseSet<StringRef> Set;
816
8
  for (Chunk *C : Symtab->getChunks())
817
24
    if (auto *Sec = dyn_cast<SectionChunk>(C))
818
24
      if (Sec->Sym)
819
20
        Set.insert(Sec->Sym->getName());
820
8
821
8
  // Open a file.
822
8
  StringRef Path = Arg.substr(1);
823
8
  std::unique_ptr<MemoryBuffer> MB = CHECK(
824
8
      MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
825
8
826
8
  // Parse a file. An order file contains one symbol per line.
827
8
  // All symbols that were not present in a given order file are
828
8
  // considered to have the lowest priority 0 and are placed at
829
8
  // end of an output section.
830
16
  for (std::string S : args::getLines(MB->getMemBufferRef())) {
831
16
    if (Config->Machine == I386 && 
!isDecorated(S)2
)
832
2
      S = "_" + S;
833
16
834
16
    if (Set.count(S) == 0) {
835
2
      if (Config->WarnMissingOrderSymbol)
836
1
        warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]");
837
2
    }
838
14
    else
839
14
      Config->Order[S] = INT_MIN + Config->Order.size();
840
16
  }
841
8
}
842
843
425
void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
844
425
  // If the first command line argument is "/lib", link.exe acts like lib.exe.
845
425
  // We call our own implementation of lib.exe that understands bitcode files.
846
425
  if (ArgsArr.size() > 1 && 
StringRef(ArgsArr[1]).equals_lower("/lib")423
) {
847
0
    if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
848
0
      fatal("lib failed");
849
0
    return;
850
0
  }
851
425
852
425
  // Needed for LTO.
853
425
  InitializeAllTargetInfos();
854
425
  InitializeAllTargets();
855
425
  InitializeAllTargetMCs();
856
425
  InitializeAllAsmParsers();
857
425
  InitializeAllAsmPrinters();
858
425
859
425
  // Parse command line options.
860
425
  ArgParser Parser;
861
425
  opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
862
425
863
425
  // Parse and evaluate -mllvm options.
864
425
  std::vector<const char *> V;
865
425
  V.push_back("lld-link (LLVM option parsing)");
866
425
  for (auto *Arg : Args.filtered(OPT_mllvm))
867
1
    V.push_back(Arg->getValue());
868
425
  cl::ParseCommandLineOptions(V.size(), V.data());
869
425
870
425
  // Handle /errorlimit early, because error() depends on it.
871
425
  if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
872
1
    int N = 20;
873
1
    StringRef S = Arg->getValue();
874
1
    if (S.getAsInteger(10, N))
875
1
      error(Arg->getSpelling() + " number expected, but got " + S);
876
1
    errorHandler().ErrorLimit = N;
877
1
  }
878
425
879
425
  // Handle /help
880
425
  if (Args.hasArg(OPT_help)) {
881
3
    printHelp(ArgsArr[0]);
882
3
    return;
883
3
  }
884
422
885
422
  if (Args.hasArg(OPT_show_timing))
886
0
    Config->ShowTiming = true;
887
422
888
422
  ScopedTimer T(Timer::root());
889
422
  // Handle --version, which is an lld extension. This option is a bit odd
890
422
  // because it doesn't start with "/", but we deliberately chose "--" to
891
422
  // avoid conflict with /version and for compatibility with clang-cl.
892
422
  if (Args.hasArg(OPT_dash_dash_version)) {
893
1
    outs() << getLLDVersion() << "\n";
894
1
    return;
895
1
  }
896
421
897
421
  // Handle /lldmingw early, since it can potentially affect how other
898
421
  // options are handled.
899
421
  Config->MinGW = Args.hasArg(OPT_lldmingw);
900
421
901
421
  if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
902
4
    SmallString<64> Path = StringRef(Arg->getValue());
903
4
    sys::path::append(Path, "repro.tar");
904
4
905
4
    Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
906
4
        TarWriter::create(Path, "repro");
907
4
908
4
    if (ErrOrWriter) {
909
4
      Tar = std::move(*ErrOrWriter);
910
4
    } else {
911
0
      error("/linkrepro: failed to open " + Path + ": " +
912
0
            toString(ErrOrWriter.takeError()));
913
0
    }
914
4
  }
915
421
916
421
  if (!Args.hasArg(OPT_INPUT)) {
917
8
    if (Args.hasArg(OPT_deffile))
918
8
      Config->NoEntry = true;
919
0
    else
920
0
      fatal("no input files");
921
421
  }
922
421
923
421
  // Construct search path list.
924
421
  SearchPaths.push_back("");
925
421
  for (auto *Arg : Args.filtered(OPT_libpath))
926
11
    SearchPaths.push_back(Arg->getValue());
927
421
  addLibSearchPaths();
928
421
929
421
  // Handle /ignore
930
421
  for (auto *Arg : Args.filtered(OPT_ignore)) {
931
3
    if (StringRef(Arg->getValue()) == "4037")
932
2
      Config->WarnMissingOrderSymbol = false;
933
1
    else if (StringRef(Arg->getValue()) == "4217")
934
1
      Config->WarnLocallyDefinedImported = false;
935
3
    // Other warning numbers are ignored.
936
3
  }
937
421
938
421
  // Handle /out
939
421
  if (auto *Arg = Args.getLastArg(OPT_out))
940
399
    Config->OutputFile = Arg->getValue();
941
421
942
421
  // Handle /verbose
943
421
  if (Args.hasArg(OPT_verbose))
944
32
    Config->Verbose = true;
945
421
  errorHandler().Verbose = Config->Verbose;
946
421
947
421
  // Handle /force or /force:unresolved
948
421
  if (Args.hasArg(OPT_force, OPT_force_unresolved))
949
7
    Config->Force = true;
950
421
951
421
  // Handle /debug
952
421
  if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
953
76
    Config->Debug = true;
954
76
    Config->Incremental = true;
955
76
    if (auto *Arg = Args.getLastArg(OPT_debugtype))
956
2
      Config->DebugTypes = parseDebugType(Arg->getValue());
957
74
    else
958
74
      Config->DebugTypes = getDefaultDebugType(Args);
959
76
  }
960
421
961
421
  // Handle /pdb
962
421
  bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
963
421
  if (ShouldCreatePDB) {
964
68
    if (auto *Arg = Args.getLastArg(OPT_pdb))
965
30
      Config->PDBPath = Arg->getValue();
966
68
    if (auto *Arg = Args.getLastArg(OPT_pdbaltpath))
967
4
      Config->PDBAltPath = Arg->getValue();
968
68
    if (Args.hasArg(OPT_natvis))
969
0
      Config->NatvisFiles = Args.getAllArgValues(OPT_natvis);
970
68
  }
971
421
972
421
  // Handle /noentry
973
421
  if (Args.hasArg(OPT_noentry)) {
974
9
    if (Args.hasArg(OPT_dll))
975
9
      Config->NoEntry = true;
976
0
    else
977
0
      error("/noentry must be specified with /dll");
978
9
  }
979
421
980
421
  // Handle /dll
981
421
  if (Args.hasArg(OPT_dll)) {
982
116
    Config->DLL = true;
983
116
    Config->ManifestID = 2;
984
116
  }
985
421
986
421
  // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
987
421
  // because we need to explicitly check whether that option or its inverse was
988
421
  // present in the argument list in order to handle /fixed.
989
421
  auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
990
421
  if (DynamicBaseArg &&
991
421
      
DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no2
)
992
2
    Config->DynamicBase = false;
993
421
994
421
  // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
995
421
  // default setting for any other project type.", but link.exe defaults to
996
421
  // /FIXED:NO for exe outputs as well. Match behavior, not docs.
997
421
  bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
998
421
  if (Fixed) {
999
5
    if (DynamicBaseArg &&
1000
5
        
DynamicBaseArg->getOption().getID() == OPT_dynamicbase0
) {
1001
0
      error("/fixed must not be specified with /dynamicbase");
1002
5
    } else {
1003
5
      Config->Relocatable = false;
1004
5
      Config->DynamicBase = false;
1005
5
    }
1006
5
  }
1007
421
1008
421
  // Handle /appcontainer
1009
421
  Config->AppContainer =
1010
421
      Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1011
421
1012
421
  // Handle /machine
1013
421
  if (auto *Arg = Args.getLastArg(OPT_machine))
1014
21
    Config->Machine = getMachineType(Arg->getValue());
1015
421
1016
421
  // Handle /nodefaultlib:<filename>
1017
421
  for (auto *Arg : Args.filtered(OPT_nodefaultlib))
1018
2
    Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
1019
421
1020
421
  // Handle /nodefaultlib
1021
421
  if (Args.hasArg(OPT_nodefaultlib_all))
1022
32
    Config->NoDefaultLibAll = true;
1023
421
1024
421
  // Handle /base
1025
421
  if (auto *Arg = Args.getLastArg(OPT_base))
1026
2
    parseNumbers(Arg->getValue(), &Config->ImageBase);
1027
421
1028
421
  // Handle /stack
1029
421
  if (auto *Arg = Args.getLastArg(OPT_stack))
1030
2
    parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
1031
421
1032
421
  // Handle /guard:cf
1033
421
  if (auto *Arg = Args.getLastArg(OPT_guard))
1034
8
    parseGuard(Arg->getValue());
1035
421
1036
421
  // Handle /heap
1037
421
  if (auto *Arg = Args.getLastArg(OPT_heap))
1038
3
    parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
1039
421
1040
421
  // Handle /version
1041
421
  if (auto *Arg = Args.getLastArg(OPT_version))
1042
2
    parseVersion(Arg->getValue(), &Config->MajorImageVersion,
1043
2
                 &Config->MinorImageVersion);
1044
421
1045
421
  // Handle /subsystem
1046
421
  if (auto *Arg = Args.getLastArg(OPT_subsystem))
1047
132
    parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
1048
132
                   &Config->MinorOSVersion);
1049
421
1050
421
  // Handle /timestamp
1051
421
  if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) {
1052
3
    if (Arg->getOption().getID() == OPT_repro) {
1053
2
      Config->Timestamp = 0;
1054
2
      Config->Repro = true;
1055
2
    } else {
1056
1
      Config->Repro = false;
1057
1
      StringRef Value(Arg->getValue());
1058
1
      if (Value.getAsInteger(0, Config->Timestamp))
1059
0
        fatal(Twine("invalid timestamp: ") + Value +
1060
0
              ".  Expected 32-bit integer");
1061
418
    }
1062
418
  } else {
1063
418
    Config->Repro = false;
1064
418
    Config->Timestamp = time(nullptr);
1065
418
  }
1066
421
1067
421
  // Handle /alternatename
1068
421
  for (auto *Arg : Args.filtered(OPT_alternatename))
1069
7
    parseAlternateName(Arg->getValue());
1070
421
1071
421
  // Handle /include
1072
421
  for (auto *Arg : Args.filtered(OPT_incl))
1073
19
    addUndefined(Arg->getValue());
1074
421
1075
421
  // Handle /implib
1076
421
  if (auto *Arg = Args.getLastArg(OPT_implib))
1077
20
    Config->Implib = Arg->getValue();
1078
421
1079
421
  // Handle /opt.
1080
421
  bool DoGC = !Args.hasArg(OPT_debug) || 
Args.hasArg(OPT_profile)66
;
1081
421
  unsigned ICFLevel =
1082
421
      Args.hasArg(OPT_profile) ? 
07
:
1414
; // 0: off, 1: limited, 2: on
1083
421
  unsigned TailMerge = 1;
1084
421
  for (auto *Arg : Args.filtered(OPT_opt)) {
1085
63
    std::string Str = StringRef(Arg->getValue()).lower();
1086
63
    SmallVector<StringRef, 1> Vec;
1087
63
    StringRef(Str).split(Vec, ',');
1088
77
    for (StringRef S : Vec) {
1089
77
      if (S == "ref") {
1090
14
        DoGC = true;
1091
63
      } else if (S == "noref") {
1092
31
        DoGC = false;
1093
32
      } else if (S == "icf" || 
S.startswith("icf=")22
) {
1094
10
        ICFLevel = 2;
1095
22
      } else if (S == "noicf") {
1096
17
        ICFLevel = 0;
1097
17
      } else 
if (5
S == "lldtailmerge"5
) {
1098
1
        TailMerge = 2;
1099
4
      } else if (S == "nolldtailmerge") {
1100
1
        TailMerge = 0;
1101
3
      } else if (S.startswith("lldlto=")) {
1102
2
        StringRef OptLevel = S.substr(7);
1103
2
        if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3)
1104
0
          error("/opt:lldlto: invalid optimization level: " + OptLevel);
1105
2
      } else 
if (1
S.startswith("lldltojobs=")1
) {
1106
0
        StringRef Jobs = S.substr(11);
1107
0
        if (Jobs.getAsInteger(10, Config->ThinLTOJobs) ||
1108
0
            Config->ThinLTOJobs == 0)
1109
0
          error("/opt:lldltojobs: invalid job count: " + Jobs);
1110
1
      } else if (S.startswith("lldltopartitions=")) {
1111
1
        StringRef N = S.substr(17);
1112
1
        if (N.getAsInteger(10, Config->LTOPartitions) ||
1113
1
            Config->LTOPartitions == 0)
1114
0
          error("/opt:lldltopartitions: invalid partition count: " + N);
1115
1
      } else 
if (0
S != "lbr"0
&&
S != "nolbr"0
)
1116
0
        error("/opt: unknown option: " + S);
1117
77
    }
1118
63
  }
1119
421
1120
421
  // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1121
421
  // explicitly.
1122
421
  // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1123
421
  // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1124
421
  // comdat readonly data.
1125
421
  if (ICFLevel == 1 && 
!DoGC391
)
1126
70
    ICFLevel = 0;
1127
421
  Config->DoGC = DoGC;
1128
421
  Config->DoICF = ICFLevel > 0;
1129
421
  Config->TailMerge = (TailMerge == 1 && 
Config->DoICF419
) ||
TailMerge == 291
;
1130
421
1131
421
  // Handle /lldsavetemps
1132
421
  if (Args.hasArg(OPT_lldsavetemps))
1133
2
    Config->SaveTemps = true;
1134
421
1135
421
  // Handle /kill-at
1136
421
  if (Args.hasArg(OPT_kill_at))
1137
2
    Config->KillAt = true;
1138
421
1139
421
  // Handle /lldltocache
1140
421
  if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1141
1
    Config->LTOCache = Arg->getValue();
1142
421
1143
421
  // Handle /lldsavecachepolicy
1144
421
  if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
1145
1
    Config->LTOCachePolicy = CHECK(
1146
421
        parseCachePruningPolicy(Arg->getValue()),
1147
421
        Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1148
421
1149
421
  // Handle /failifmismatch
1150
421
  for (auto *Arg : Args.filtered(OPT_failifmismatch))
1151
4
    checkFailIfMismatch(Arg->getValue());
1152
421
1153
421
  // Handle /merge
1154
421
  for (auto *Arg : Args.filtered(OPT_merge))
1155
10
    parseMerge(Arg->getValue());
1156
421
1157
421
  // Add default section merging rules after user rules. User rules take
1158
421
  // precedence, but we will emit a warning if there is a conflict.
1159
421
  parseMerge(".idata=.rdata");
1160
421
  parseMerge(".didat=.rdata");
1161
421
  parseMerge(".edata=.rdata");
1162
421
  parseMerge(".xdata=.rdata");
1163
421
  parseMerge(".bss=.data");
1164
421
1165
421
  // Handle /section
1166
421
  for (auto *Arg : Args.filtered(OPT_section))
1167
6
    parseSection(Arg->getValue());
1168
421
1169
421
  // Handle /aligncomm
1170
421
  for (auto *Arg : Args.filtered(OPT_aligncomm))
1171
0
    parseAligncomm(Arg->getValue());
1172
421
1173
421
  // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1174
421
  // also passed.
1175
421
  if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1176
2
    Config->ManifestDependency = Arg->getValue();
1177
2
    Config->Manifest = Configuration::SideBySide;
1178
2
  }
1179
421
1180
421
  // Handle /manifest and /manifest:
1181
421
  if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1182
5
    if (Arg->getOption().getID() == OPT_manifest)
1183
4
      Config->Manifest = Configuration::SideBySide;
1184
1
    else
1185
1
      parseManifest(Arg->getValue());
1186
5
  }
1187
421
1188
421
  // Handle /manifestuac
1189
421
  if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1190
4
    parseManifestUAC(Arg->getValue());
1191
421
1192
421
  // Handle /manifestfile
1193
421
  if (auto *Arg = Args.getLastArg(OPT_manifestfile))
1194
0
    Config->ManifestFile = Arg->getValue();
1195
421
1196
421
  // Handle /manifestinput
1197
421
  for (auto *Arg : Args.filtered(OPT_manifestinput))
1198
1
    Config->ManifestInput.push_back(Arg->getValue());
1199
421
1200
421
  if (!Config->ManifestInput.empty() &&
1201
421
      
Config->Manifest != Configuration::Embed1
) {
1202
0
    fatal("/manifestinput: requires /manifest:embed");
1203
0
  }
1204
421
1205
421
  // Handle miscellaneous boolean flags.
1206
421
  Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1207
421
  Config->AllowIsolation =
1208
421
      Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1209
421
  Config->Incremental =
1210
421
      Args.hasFlag(OPT_incremental, OPT_incremental_no,
1211
421
                   !Config->DoGC && 
!Config->DoICF87
&&
!Args.hasArg(OPT_order)82
&&
1212
421
                       
!Args.hasArg(OPT_profile)74
);
1213
421
  Config->IntegrityCheck =
1214
421
      Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1215
421
  Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1216
421
  Config->TerminalServerAware =
1217
421
      !Config->DLL && 
Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true)305
;
1218
421
  Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
1219
421
  Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
1220
421
1221
421
  Config->MapFile = getMapFile(Args);
1222
421
1223
421
  if (Config->Incremental && 
Args.hasArg(OPT_profile)77
) {
1224
2
    warn("ignoring '/incremental' due to '/profile' specification");
1225
2
    Config->Incremental = false;
1226
2
  }
1227
421
1228
421
  if (Config->Incremental && 
Args.hasArg(OPT_order)75
) {
1229
2
    warn("ignoring '/incremental' due to '/order' specification");
1230
2
    Config->Incremental = false;
1231
2
  }
1232
421
1233
421
  if (Config->Incremental && 
Config->DoGC73
) {
1234
4
    warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1235
4
         "disable");
1236
4
    Config->Incremental = false;
1237
4
  }
1238
421
1239
421
  if (Config->Incremental && 
Config->DoICF69
) {
1240
2
    warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1241
2
         "disable");
1242
2
    Config->Incremental = false;
1243
2
  }
1244
421
1245
421
  if (errorCount())
1246
4
    return;
1247
417
1248
417
  std::set<sys::fs::UniqueID> WholeArchives;
1249
417
  for (auto *Arg : Args.filtered(OPT_wholearchive_file))
1250
3
    if (Optional<StringRef> Path = doFindFile(Arg->getValue()))
1251
3
      if (Optional<sys::fs::UniqueID> ID = getUniqueID(*Path))
1252
3
        WholeArchives.insert(*ID);
1253
417
1254
417
  // A predicate returning true if a given path is an argument for
1255
417
  // /wholearchive:, or /wholearchive is enabled globally.
1256
417
  // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1257
417
  // needs to be handled as "/wholearchive:foo.obj foo.obj".
1258
531
  auto IsWholeArchive = [&](StringRef Path) -> bool {
1259
531
    if (Args.hasArg(OPT_wholearchive_flag))
1260
2
      return true;
1261
529
    if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
1262
527
      return WholeArchives.count(*ID);
1263
2
    return false;
1264
2
  };
1265
417
1266
417
  // Create a list of input files. Files can be given as arguments
1267
417
  // for /defaultlib option.
1268
417
  for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file))
1269
535
    if (Optional<StringRef> Path = findFile(Arg->getValue()))
1270
531
      enqueuePath(*Path, IsWholeArchive(*Path));
1271
417
1272
417
  for (auto *Arg : Args.filtered(OPT_defaultlib))
1273
8
    if (Optional<StringRef> Path = findLib(Arg->getValue()))
1274
6
      enqueuePath(*Path, false);
1275
417
1276
417
  // Windows specific -- Create a resource file containing a manifest file.
1277
417
  if (Config->Manifest == Configuration::Embed)
1278
1
    addBuffer(createManifestRes(), false);
1279
417
1280
417
  // Read all input files given via the command line.
1281
417
  run();
1282
417
1283
417
  // We should have inferred a machine type by now from the input files, but if
1284
417
  // not we assume x64.
1285
417
  if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1286
5
    warn("/machine is not specified. x64 is assumed");
1287
5
    Config->Machine = AMD64;
1288
5
  }
1289
417
1290
417
  // Input files can be Windows resource files (.res files). We use
1291
417
  // WindowsResource to convert resource files to a regular COFF file,
1292
417
  // then link the resulting file normally.
1293
417
  if (!Resources.empty())
1294
4
    Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
1295
417
1296
417
  if (Tar)
1297
4
    Tar->append("response.txt",
1298
4
                createResponseFile(Args, FilePaths,
1299
4
                                   ArrayRef<StringRef>(SearchPaths).slice(1)));
1300
417
1301
417
  // Handle /largeaddressaware
1302
417
  Config->LargeAddressAware = Args.hasFlag(
1303
417
      OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
1304
417
1305
417
  // Handle /highentropyva
1306
417
  Config->HighEntropyVA =
1307
417
      Config->is64() &&
1308
417
      
Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true)342
;
1309
417
1310
417
  if (!Config->DynamicBase &&
1311
417
      
(7
Config->Machine == ARMNT7
||
Config->Machine == ARM646
))
1312
2
    error("/dynamicbase:no is not compatible with " +
1313
2
          machineToStr(Config->Machine));
1314
417
1315
417
  // Handle /entry and /dll
1316
417
  if (auto *Arg = Args.getLastArg(OPT_entry)) {
1317
324
    Config->Entry = addUndefined(mangle(Arg->getValue()));
1318
324
  } else 
if (93
!Config->Entry93
&&
!Config->NoEntry92
) {
1319
78
    if (Args.hasArg(OPT_dll)) {
1320
65
      StringRef S = (Config->Machine == I386) ? 
"__DllMainCRTStartup@12"10
1321
65
                                              : 
"_DllMainCRTStartup"55
;
1322
65
      Config->Entry = addUndefined(S);
1323
65
    } else {
1324
13
      // Windows specific -- If entry point name is not given, we need to
1325
13
      // infer that from user-defined entry name.
1326
13
      StringRef S = findDefaultEntry();
1327
13
      if (S.empty())
1328
0
        fatal("entry point must be defined");
1329
13
      Config->Entry = addUndefined(S);
1330
13
      log("Entry name inferred: " + S);
1331
13
    }
1332
78
  }
1333
417
1334
417
  // Handle /export
1335
417
  for (auto *Arg : Args.filtered(OPT_export)) {
1336
47
    Export E = parseExport(Arg->getValue());
1337
47
    if (Config->Machine == I386) {
1338
16
      if (!isDecorated(E.Name))
1339
16
        E.Name = Saver.save("_" + E.Name);
1340
16
      if (!E.ExtName.empty() && 
!isDecorated(E.ExtName)3
)
1341
3
        E.ExtName = Saver.save("_" + E.ExtName);
1342
16
    }
1343
47
    Config->Exports.push_back(E);
1344
47
  }
1345
417
1346
417
  // Handle /def
1347
417
  if (auto *Arg = Args.getLastArg(OPT_deffile)) {
1348
28
    // parseModuleDefs mutates Config object.
1349
28
    parseModuleDefs(Arg->getValue());
1350
28
  }
1351
417
1352
417
  // Handle generation of import library from a def file.
1353
417
  if (!Args.hasArg(OPT_INPUT)) {
1354
8
    fixupExports();
1355
8
    createImportLibrary(/*AsLib=*/true);
1356
8
    return;
1357
8
  }
1358
409
1359
409
  // Handle /delayload
1360
409
  for (auto *Arg : Args.filtered(OPT_delayload)) {
1361
3
    Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1362
3
    if (Config->Machine == I386) {
1363
1
      Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1364
2
    } else {
1365
2
      Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1366
2
    }
1367
3
  }
1368
409
1369
409
  // Set default image name if neither /out or /def set it.
1370
409
  if (Config->OutputFile.empty()) {
1371
18
    Config->OutputFile =
1372
18
        getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1373
18
  }
1374
409
1375
409
  if (ShouldCreatePDB) {
1376
68
    // Put the PDB next to the image if no /pdb flag was passed.
1377
68
    if (Config->PDBPath.empty()) {
1378
38
      Config->PDBPath = Config->OutputFile;
1379
38
      sys::path::replace_extension(Config->PDBPath, ".pdb");
1380
38
    }
1381
68
1382
68
    // The embedded PDB path should be the absolute path to the PDB if no
1383
68
    // /pdbaltpath flag was passed.
1384
68
    if (Config->PDBAltPath.empty()) {
1385
64
      Config->PDBAltPath = Config->PDBPath;
1386
64
      sys::fs::make_absolute(Config->PDBAltPath);
1387
64
    }
1388
68
  }
1389
409
1390
409
  // Set default image base if /base is not given.
1391
409
  if (Config->ImageBase == uint64_t(-1))
1392
407
    Config->ImageBase = getDefaultImageBase();
1393
409
1394
409
  Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1395
409
  if (Config->Machine == I386) {
1396
65
    Symtab->addAbsolute("___safe_se_handler_table", 0);
1397
65
    Symtab->addAbsolute("___safe_se_handler_count", 0);
1398
65
  }
1399
409
1400
409
  Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1401
409
  Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1402
409
  Symtab->addAbsolute(mangle("__guard_flags"), 0);
1403
409
  Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1404
409
  Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1405
409
  Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1406
409
  Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1407
409
  // Needed for MSVC 2017 15.5 CRT.
1408
409
  Symtab->addAbsolute(mangle("__enclave_config"), 0);
1409
409
1410
409
  // This code may add new undefined symbols to the link, which may enqueue more
1411
409
  // symbol resolution tasks, so we need to continue executing tasks until we
1412
409
  // converge.
1413
414
  do {
1414
414
    // Windows specific -- if entry point is not found,
1415
414
    // search for its mangled names.
1416
414
    if (Config->Entry)
1417
405
      Symtab->mangleMaybe(Config->Entry);
1418
414
1419
414
    // Windows specific -- Make sure we resolve all dllexported symbols.
1420
414
    for (Export &E : Config->Exports) {
1421
168
      if (!E.ForwardTo.empty())
1422
2
        continue;
1423
166
      E.Sym = addUndefined(E.Name);
1424
166
      if (!E.Directives)
1425
70
        Symtab->mangleMaybe(E.Sym);
1426
166
    }
1427
414
1428
414
    // Add weak aliases. Weak aliases is a mechanism to give remaining
1429
414
    // undefined symbols final chance to be resolved successfully.
1430
414
    for (auto Pair : Config->AlternateNames) {
1431
8
      StringRef From = Pair.first;
1432
8
      StringRef To = Pair.second;
1433
8
      Symbol *Sym = Symtab->find(From);
1434
8
      if (!Sym)
1435
2
        continue;
1436
6
      if (auto *U = dyn_cast<Undefined>(Sym))
1437
6
        if (!U->WeakAlias)
1438
6
          U->WeakAlias = Symtab->addUndefined(To);
1439
6
    }
1440
414
1441
414
    // Windows specific -- if __load_config_used can be resolved, resolve it.
1442
414
    if (Symtab->findUnderscore("_load_config_used"))
1443
15
      addUndefined(mangle("_load_config_used"));
1444
414
  } while (run());
1445
409
1446
409
  if (errorCount())
1447
9
    return;
1448
400
1449
400
  // If /msvclto is given, we use the MSVC linker to link LTO output files.
1450
400
  // This is useful because MSVC link.exe can generate complete PDBs.
1451
400
  if (Args.hasArg(OPT_msvclto)) {
1452
0
    invokeMSVC(Args);
1453
0
    return;
1454
0
  }
1455
400
1456
400
  // Do LTO by compiling bitcode input files to a set of native COFF files then
1457
400
  // link those files.
1458
400
  Symtab->addCombinedLTOObjects();
1459
400
  run();
1460
400
1461
400
  // Make sure we have resolved all symbols.
1462
400
  Symtab->reportRemainingUndefines();
1463
400
  if (errorCount())
1464
14
    return;
1465
386
1466
386
  // Windows specific -- if no /subsystem is given, we need to infer
1467
386
  // that from entry point name.
1468
386
  if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1469
265
    Config->Subsystem = inferSubsystem();
1470
265
    if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1471
0
      fatal("subsystem must be defined");
1472
386
  }
1473
386
1474
386
  // Handle /safeseh.
1475
386
  if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
1476
7
    for (ObjFile *File : ObjFile::Instances)
1477
7
      if (!File->hasSafeSEH())
1478
1
        error("/safeseh: " + File->getName() + " is not compatible with SEH");
1479
7
    if (errorCount())
1480
1
      return;
1481
385
  }
1482
385
1483
385
  // In MinGW, all symbols are automatically exported if no symbols
1484
385
  // are chosen to be exported.
1485
385
  if (Config->DLL && 
(113
(113
Config->MinGW113
&&
Config->Exports.empty()8
) ||
1486
113
                      
Args.hasArg(OPT_export_all_symbols)109
)) {
1487
5
    AutoExporter Exporter;
1488
5
1489
78
    Symtab->forEachSymbol([=](Symbol *S) {
1490
78
      auto *Def = dyn_cast<Defined>(S);
1491
78
      if (!Exporter.shouldExport(Def))
1492
64
        return;
1493
14
      Export E;
1494
14
      E.Name = Def->getName();
1495
14
      E.Sym = Def;
1496
14
      if (Def->getChunk() &&
1497
14
          !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1498
1
        E.Data = true;
1499
14
      Config->Exports.push_back(E);
1500
14
    });
1501
5
  }
1502
385
1503
385
  // Windows specific -- when we are creating a .dll file, we also
1504
385
  // need to create a .lib file.
1505
385
  if (!Config->Exports.empty() || 
Config->DLL292
) {
1506
117
    fixupExports();
1507
117
    createImportLibrary(/*AsLib=*/false);
1508
117
    assignExportOrdinals();
1509
117
  }
1510
385
1511
385
  // Handle /output-def (MinGW specific).
1512
385
  if (auto *Arg = Args.getLastArg(OPT_output_def))
1513
3
    writeDefFile(Arg->getValue());
1514
385
1515
385
  // Set extra alignment for .comm symbols
1516
385
  for (auto Pair : Config->AlignComm) {
1517
1
    StringRef Name = Pair.first;
1518
1
    uint32_t Alignment = Pair.second;
1519
1
1520
1
    Symbol *Sym = Symtab->find(Name);
1521
1
    if (!Sym) {
1522
0
      warn("/aligncomm symbol " + Name + " not found");
1523
0
      continue;
1524
0
    }
1525
1
1526
1
    auto *DC = dyn_cast<DefinedCommon>(Sym);
1527
1
    if (!DC) {
1528
0
      warn("/aligncomm symbol " + Name + " of wrong kind");
1529
0
      continue;
1530
0
    }
1531
1
1532
1
    CommonChunk *C = DC->getChunk();
1533
1
    C->Alignment = std::max(C->Alignment, Alignment);
1534
1
  }
1535
385
1536
385
  // Windows specific -- Create a side-by-side manifest file.
1537
385
  if (Config->Manifest == Configuration::SideBySide)
1538
5
    createSideBySideManifest();
1539
385
1540
385
  // Handle /order. We want to do this at this moment because we
1541
385
  // need a complete list of comdat sections to warn on nonexistent
1542
385
  // functions.
1543
385
  if (auto *Arg = Args.getLastArg(OPT_order))
1544
8
    parseOrderFile(Arg->getValue());
1545
385
1546
385
  // Identify unreferenced COMDAT sections.
1547
385
  if (Config->DoGC)
1548
298
    markLive(Symtab->getChunks());
1549
385
1550
385
  // Identify identical COMDAT sections to merge them.
1551
385
  if (Config->DoICF)
1552
295
    doICF(Symtab->getChunks());
1553
385
1554
385
  // Write the result.
1555
385
  writeResult();
1556
385
1557
385
  // Stop early so we can print the results.
1558
385
  Timer::root().stop();
1559
385
  if (Config->ShowTiming)
1560
0
    Timer::root().print();
1561
385
}
1562
1563
} // namespace coff
1564
} // namespace lld