Coverage Report

Created: 2019-01-18 03:29

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