Coverage Report

Created: 2018-10-20 12:32

/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
545
bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
60
545
  errorHandler().LogName = args::getFilenameWithoutExe(Args[0]);
61
545
  errorHandler().ErrorOS = &Diag;
62
545
  errorHandler().ColorDiagnostics = Diag.has_colors();
63
545
  errorHandler().ErrorLimitExceededMsg =
64
545
      "too many errors emitted, stopping now"
65
545
      " (use /errorlimit:0 to see all errors)";
66
545
  errorHandler().ExitEarly = CanExitEarly;
67
545
  Config = make<Configuration>();
68
545
69
545
  Symtab = make<SymbolTable>();
70
545
71
545
  Driver = make<LinkerDriver>();
72
545
  Driver->link(Args);
73
545
74
545
  // Call exit() if we can to avoid calling destructors.
75
545
  if (CanExitEarly)
76
0
    exitLld(errorCount() ? 1 : 0);
77
545
78
545
  freeArena();
79
545
  ObjFile::Instances.clear();
80
545
  ImportFile::Instances.clear();
81
545
  BitcodeFile::Instances.clear();
82
545
  return !errorCount();
83
545
}
84
85
// Drop directory components and replace extension with ".exe" or ".dll".
86
21
static std::string getOutputPath(StringRef Path) {
87
21
  auto P = Path.find_last_of("\\/");
88
21
  StringRef S = (P == StringRef::npos) ? 
Path2
:
Path.substr(P + 1)19
;
89
21
  const char* E = Config->DLL ? 
".dll"2
:
".exe"19
;
90
21
  return (S.substr(0, S.rfind('.')) + E).str();
91
21
}
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
765
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
765
#endif
110
765
  return std::async(Strategy, [=]() {
111
765
    auto MBOrErr = MemoryBuffer::getFile(Path,
112
765
                                         /*FileSize*/ -1,
113
765
                                         /*RequiresNullTerminator*/ false);
114
765
    if (!MBOrErr)
115
63
      return MBErrPair{nullptr, MBOrErr.getError()};
116
702
    return MBErrPair{std::move(*MBOrErr), std::error_code()};
117
702
  });
118
765
}
119
120
// Symbol names are mangled by prepending "_" on x86.
121
6.05k
static StringRef mangle(StringRef Sym) {
122
6.05k
  assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
123
6.05k
  if (Config->Machine == I386)
124
1.04k
    return Saver.save("_" + Sym);
125
5.01k
  return Sym;
126
5.01k
}
127
128
884
static bool findUnderscoreMangle(StringRef Sym) {
129
884
  StringRef Entry = Symtab->findMangle(mangle(Sym));
130
884
  return !Entry.empty() && 
!isa<Undefined>(Symtab->find(Entry))227
;
131
884
}
132
133
707
MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
134
707
  MemoryBufferRef MBRef = *MB;
135
707
  make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
136
707
137
707
  if (Driver->Tar)
138
7
    Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
139
7
                        MBRef.getBuffer());
140
707
  return MBRef;
141
707
}
142
143
void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
144
703
                             bool WholeArchive) {
145
703
  StringRef Filename = MB->getBufferIdentifier();
146
703
147
703
  MemoryBufferRef MBRef = takeBuffer(std::move(MB));
148
703
  FilePaths.push_back(Filename);
149
703
150
703
  // File type is detected by contents, not by file extension.
151
703
  switch (identify_magic(MBRef.getBuffer())) {
152
703
  case file_magic::windows_resource:
153
6
    Resources.push_back(MBRef);
154
6
    break;
155
703
  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
45
    Symtab->addFile(make<BitcodeFile>(MBRef));
168
45
    break;
169
561
  case file_magic::coff_object:
170
561
  case file_magic::coff_import_library:
171
561
    Symtab->addFile(make<ObjFile>(MBRef));
172
561
    break;
173
561
  case file_magic::coff_cl_gl_object:
174
1
    error(Filename + ": is not a native COFF file. Recompile without /GL");
175
1
    break;
176
561
  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
703
  }
187
703
}
188
189
765
void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
190
765
  auto Future =
191
765
      std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
192
765
  std::string PathStr = Path;
193
765
  enqueueTask([=]() {
194
765
    auto MBOrErr = Future->get();
195
765
    if (MBOrErr.second)
196
63
      error("could not open " + PathStr + ": " + MBOrErr.second.message());
197
702
    else
198
702
      Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
199
765
  });
200
765
}
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
152
void LinkerDriver::parseDirectives(StringRef S) {
258
152
  ArgParser Parser;
259
152
  // .drectve is always tokenized using Windows shell rules.
260
152
  // /EXPORT: option can appear too many times, processing in fastpath.
261
152
  opt::InputArgList Args;
262
152
  std::vector<StringRef> Exports;
263
152
  std::tie(Args, Exports) = Parser.parseDirectives(S);
264
152
265
152
  for (StringRef E : Exports) {
266
101
    // If a common header file contains dllexported function
267
101
    // declarations, many object files may end up with having the
268
101
    // same /EXPORT options. In order to save cost of parsing them,
269
101
    // we dedup them first.
270
101
    if (!DirectivesExports.insert(E).second)
271
0
      continue;
272
101
273
101
    Export Exp = parseExport(E);
274
101
    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
101
    Exp.Directives = true;
281
101
    Config->Exports.push_back(Exp);
282
101
  }
283
152
284
152
  for (auto *Arg : Args) {
285
124
    switch (Arg->getOption().getUnaliasedOption().getID()) {
286
124
    case OPT_aligncomm:
287
2
      parseAligncomm(Arg->getValue());
288
2
      break;
289
124
    case OPT_alternatename:
290
2
      parseAlternateName(Arg->getValue());
291
2
      break;
292
124
    case OPT_defaultlib:
293
111
      if (Optional<StringRef> Path = findLib(Arg->getValue()))
294
1
        enqueuePath(*Path, false);
295
111
      break;
296
124
    case OPT_entry:
297
1
      Config->Entry = addUndefined(mangle(Arg->getValue()));
298
1
      break;
299
124
    case OPT_failifmismatch:
300
0
      checkFailIfMismatch(Arg->getValue());
301
0
      break;
302
124
    case OPT_incl:
303
7
      addUndefined(Arg->getValue());
304
7
      break;
305
124
    case OPT_merge:
306
0
      parseMerge(Arg->getValue());
307
0
      break;
308
124
    case OPT_nodefaultlib:
309
0
      Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
310
0
      break;
311
124
    case OPT_section:
312
0
      parseSection(Arg->getValue());
313
0
      break;
314
124
    case OPT_subsystem:
315
1
      parseSubsystem(Arg->getValue(), &Config->Subsystem,
316
1
                     &Config->MajorOSVersion, &Config->MinorOSVersion);
317
1
      break;
318
124
    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
124
    }
327
124
  }
328
152
}
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
778
StringRef LinkerDriver::doFindFile(StringRef Filename) {
333
778
  bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
334
778
  if (HasPathSep)
335
672
    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.52k
static Optional<sys::fs::UniqueID> getUniqueID(StringRef Path) {
352
1.52k
  sys::fs::UniqueID Ret;
353
1.52k
  if (sys::fs::getUniqueID(Path, Ret))
354
124
    return None;
355
1.40k
  return Ret;
356
1.40k
}
357
358
// Resolves a file path. This never returns the same path
359
// (in that case, it returns None).
360
761
Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
361
761
  StringRef Path = doFindFile(Filename);
362
761
363
761
  if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) {
364
700
    bool Seen = !VisitedFiles.insert(*ID).second;
365
700
    if (Seen)
366
4
      return None;
367
757
  }
368
757
369
757
  if (Path.endswith_lower(".lib"))
370
74
    VisitedLibs.insert(sys::path::filename(Path));
371
757
  return Path;
372
757
}
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
120
Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
404
120
  if (Config->NoDefaultLibAll)
405
110
    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
540
void LinkerDriver::addLibSearchPaths() {
421
540
  Optional<std::string> EnvOpt = Process::GetEnv("LIB");
422
540
  if (!EnvOpt.hasValue())
423
536
    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
719
Symbol *LinkerDriver::addUndefined(StringRef Name) {
433
719
  Symbol *B = Symtab->addUndefined(Name);
434
719
  if (!B->IsGCRoot) {
435
701
    B->IsGCRoot = true;
436
701
    Config->GCRoot.push_back(B);
437
701
  }
438
719
  return B;
439
719
}
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
38
StringRef LinkerDriver::findDefaultEntry() {
447
38
  assert(Config->Subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
448
38
         "must handle /subsystem before calling this");
449
38
450
38
  if (Config->MinGW)
451
6
    return mangle(Config->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
452
6
                      ? 
"WinMainCRTStartup"1
453
6
                      : 
"mainCRTStartup"5
);
454
32
455
32
  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
19
  }
463
19
  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
19
  
return mangle("mainCRTStartup")14
;
469
19
}
470
471
355
WindowsSubsystem LinkerDriver::inferSubsystem() {
472
355
  if (Config->DLL)
473
128
    return IMAGE_SUBSYSTEM_WINDOWS_GUI;
474
227
  if (Config->MinGW)
475
17
    return IMAGE_SUBSYSTEM_WINDOWS_CUI;
476
210
  // Note that link.exe infers the subsystem from the presence of these
477
210
  // functions even if /entry: or /nodefaultlib are passed which causes them
478
210
  // to not be called.
479
210
  bool HaveMain = findUnderscoreMangle("main");
480
210
  bool HaveWMain = findUnderscoreMangle("wmain");
481
210
  bool HaveWinMain = findUnderscoreMangle("WinMain");
482
210
  bool HaveWWinMain = findUnderscoreMangle("wWinMain");
483
210
  if (HaveMain || 
HaveWMain15
) {
484
199
    if (HaveWinMain || 
HaveWWinMain198
) {
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
199
    return IMAGE_SUBSYSTEM_WINDOWS_CUI;
490
199
  }
491
11
  if (HaveWinMain || 
HaveWWinMain4
)
492
11
    return IMAGE_SUBSYSTEM_WINDOWS_GUI;
493
0
  return IMAGE_SUBSYSTEM_UNKNOWN;
494
0
}
495
496
502
static uint64_t getDefaultImageBase() {
497
502
  if (Config->is64())
498
399
    return Config->DLL ? 
0x180000000102
:
0x140000000297
;
499
103
  return Config->DLL ? 
0x1000000031
:
0x40000072
;
500
103
}
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
540
static DebugKind parseDebugKind(const opt::InputArgList &Args) {
540
540
  auto *A = Args.getLastArg(OPT_debug, OPT_debug_opt);
541
540
  if (!A)
542
439
    return DebugKind::None;
543
101
  if (A->getNumValues() == 0)
544
84
    return DebugKind::Full;
545
17
546
17
  DebugKind Debug = StringSwitch<DebugKind>(A->getValue())
547
17
                     .CaseLower("none", DebugKind::None)
548
17
                     .CaseLower("full", DebugKind::Full)
549
17
                     .CaseLower("fastlink", DebugKind::FastLink)
550
17
                     // LLD extensions
551
17
                     .CaseLower("ghash", DebugKind::GHash)
552
17
                     .CaseLower("dwarf", DebugKind::Dwarf)
553
17
                     .CaseLower("symtab", DebugKind::Symtab)
554
17
                     .Default(DebugKind::Unknown);
555
17
556
17
  if (Debug == DebugKind::FastLink) {
557
1
    warn("/debug:fastlink unsupported; using /debug:full");
558
1
    return DebugKind::Full;
559
1
  }
560
16
  if (Debug == DebugKind::Unknown) {
561
1
    error("/debug: unknown option: " + Twine(A->getValue()));
562
1
    return DebugKind::None;
563
1
  }
564
15
  return Debug;
565
15
}
566
567
540
static unsigned parseDebugTypes(const opt::InputArgList &Args) {
568
540
  unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
569
540
570
540
  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
538
589
538
  // Default debug types
590
538
  DebugTypes = static_cast<unsigned>(DebugType::CV);
591
538
  if (Args.hasArg(OPT_driver))
592
0
    DebugTypes |= static_cast<unsigned>(DebugType::PData);
593
538
  if (Args.hasArg(OPT_profile))
594
7
    DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
595
538
596
538
  return DebugTypes;
597
538
}
598
599
540
static std::string getMapFile(const opt::InputArgList &Args) {
600
540
  auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
601
540
  if (!Arg)
602
526
    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
145
static std::string getImplibPath() {
612
145
  if (!Config->Implib.empty())
613
27
    return Config->Implib;
614
118
  SmallString<128> Out = StringRef(Config->OutputFile);
615
118
  sys::path::replace_extension(Out, ".lib");
616
118
  return Out.str();
617
118
}
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
145
static std::string getImportName(bool AsLib) {
628
145
  SmallString<128> Out;
629
145
630
145
  if (Config->ImportName.empty()) {
631
131
    Out.assign(sys::path::filename(Config->OutputFile));
632
131
    if (AsLib)
633
2
      sys::path::replace_extension(Out, ".dll");
634
131
  } 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
145
641
145
  return Out.str();
642
145
}
643
644
145
static void createImportLibrary(bool AsLib) {
645
145
  std::vector<COFFShortExport> Exports;
646
198
  for (Export &E1 : Config->Exports) {
647
198
    COFFShortExport E2;
648
198
    E2.Name = E1.Name;
649
198
    E2.SymbolName = E1.SymbolName;
650
198
    E2.ExtName = E1.ExtName;
651
198
    E2.Ordinal = E1.Ordinal;
652
198
    E2.Noname = E1.Noname;
653
198
    E2.Data = E1.Data;
654
198
    E2.Private = E1.Private;
655
198
    E2.Constant = E1.Constant;
656
198
    Exports.push_back(E2);
657
198
  }
658
145
659
145
  auto HandleError = [](Error &&E) {
660
137
    handleAllErrors(std::move(E),
661
137
                    [](ErrorInfoBase &EIB) 
{ error(EIB.message()); }0
);
662
137
  };
663
145
  std::string LibName = getImportName(AsLib);
664
145
  std::string Path = getImplibPath();
665
145
666
145
  if (!Config->Incremental) {
667
126
    HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
668
126
                                   Config->MinGW));
669
126
    return;
670
126
  }
671
19
672
19
  // If the import library already exists, replace it only if the contents
673
19
  // have changed.
674
19
  ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(
675
19
      Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
676
19
  if (!OldBuf) {
677
10
    HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
678
10
                                   Config->MinGW));
679
10
    return;
680
10
  }
681
9
682
9
  SmallString<128> TmpName;
683
9
  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
9
688
9
  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
9
694
9
  std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(
695
9
      TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
696
9
  if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
697
1
    OldBuf->reset();
698
1
    HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
699
8
  } else {
700
8
    sys::fs::remove(TmpName);
701
8
  }
702
9
}
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
903
void LinkerDriver::enqueueTask(std::function<void()> Task) {
756
903
  TaskQueue.push_back(std::move(Task));
757
903
}
758
759
1.59k
bool LinkerDriver::run() {
760
1.59k
  ScopedTimer T(InputFileTimer);
761
1.59k
762
1.59k
  bool DidWork = !TaskQueue.empty();
763
2.49k
  while (!TaskQueue.empty()) {
764
903
    TaskQueue.front()();
765
903
    TaskQueue.pop_front();
766
903
  }
767
1.59k
  return DidWork;
768
1.59k
}
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
8
static void parseOrderFile(StringRef Arg) {
774
8
  // For some reason, the MSVC linker requires a filename to be
775
8
  // preceded by "@".
776
8
  if (!Arg.startswith("@")) {
777
0
    error("malformed /order option: '@' missing");
778
0
    return;
779
0
  }
780
8
781
8
  // Get a list of all comdat sections for error checking.
782
8
  DenseSet<StringRef> Set;
783
8
  for (Chunk *C : Symtab->getChunks())
784
24
    if (auto *Sec = dyn_cast<SectionChunk>(C))
785
24
      if (Sec->Sym)
786
20
        Set.insert(Sec->Sym->getName());
787
8
788
8
  // Open a file.
789
8
  StringRef Path = Arg.substr(1);
790
8
  std::unique_ptr<MemoryBuffer> MB = CHECK(
791
8
      MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
792
8
793
8
  // Parse a file. An order file contains one symbol per line.
794
8
  // All symbols that were not present in a given order file are
795
8
  // considered to have the lowest priority 0 and are placed at
796
8
  // end of an output section.
797
16
  for (std::string S : args::getLines(MB->getMemBufferRef())) {
798
16
    if (Config->Machine == I386 && 
!isDecorated(S)2
)
799
2
      S = "_" + S;
800
16
801
16
    if (Set.count(S) == 0) {
802
2
      if (Config->WarnMissingOrderSymbol)
803
1
        warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]");
804
2
    }
805
14
    else
806
14
      Config->Order[S] = INT_MIN + Config->Order.size();
807
16
  }
808
8
}
809
810
4.25k
static void markAddrsig(Symbol *S) {
811
4.25k
  if (auto *D = dyn_cast_or_null<Defined>(S))
812
2.70k
    if (Chunk *C = D->getChunk())
813
2.61k
      C->KeepUnique = true;
814
4.25k
}
815
816
359
static void findKeepUniqueSections() {
817
359
  // Exported symbols could be address-significant in other executables or DSOs,
818
359
  // so we conservatively mark them as address-significant.
819
359
  for (Export &R : Config->Exports)
820
166
    markAddrsig(R.Sym);
821
359
822
359
  // Visit the address-significance table in each object file and mark each
823
359
  // referenced symbol as address-significant.
824
456
  for (ObjFile *Obj : ObjFile::Instances) {
825
456
    ArrayRef<Symbol *> Syms = Obj->getSymbols();
826
456
    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
454
    } else {
842
454
      // If an object file does not have an address-significance table,
843
454
      // conservatively mark all of its symbols as address-significant.
844
454
      for (Symbol *S : Syms)
845
4.08k
        markAddrsig(S);
846
454
    }
847
456
  }
848
359
}
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
545
void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
902
545
  // If the first command line argument is "/lib", link.exe acts like lib.exe.
903
545
  // We call our own implementation of lib.exe that understands bitcode files.
904
545
  if (ArgsArr.size() > 1 && 
StringRef(ArgsArr[1]).equals_lower("/lib")543
) {
905
1
    if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
906
0
      fatal("lib failed");
907
1
    return;
908
1
  }
909
544
910
544
  // Needed for LTO.
911
544
  InitializeAllTargetInfos();
912
544
  InitializeAllTargets();
913
544
  InitializeAllTargetMCs();
914
544
  InitializeAllAsmParsers();
915
544
  InitializeAllAsmPrinters();
916
544
917
544
  // Parse command line options.
918
544
  ArgParser Parser;
919
544
  opt::InputArgList Args = Parser.parseLINK(ArgsArr);
920
544
921
544
  // Parse and evaluate -mllvm options.
922
544
  std::vector<const char *> V;
923
544
  V.push_back("lld-link (LLVM option parsing)");
924
544
  for (auto *Arg : Args.filtered(OPT_mllvm))
925
1
    V.push_back(Arg->getValue());
926
544
  cl::ParseCommandLineOptions(V.size(), V.data());
927
544
928
544
  // Handle /errorlimit early, because error() depends on it.
929
544
  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
544
937
544
  // Handle /help
938
544
  if (Args.hasArg(OPT_help)) {
939
3
    printHelp(ArgsArr[0]);
940
3
    return;
941
3
  }
942
541
943
541
  if (Args.hasArg(OPT_show_timing))
944
0
    Config->ShowTiming = true;
945
541
946
541
  ScopedTimer T(Timer::root());
947
541
  // Handle --version, which is an lld extension. This option is a bit odd
948
541
  // because it doesn't start with "/", but we deliberately chose "--" to
949
541
  // avoid conflict with /version and for compatibility with clang-cl.
950
541
  if (Args.hasArg(OPT_dash_dash_version)) {
951
1
    outs() << getLLDVersion() << "\n";
952
1
    return;
953
1
  }
954
540
955
540
  // Handle /lldmingw early, since it can potentially affect how other
956
540
  // options are handled.
957
540
  Config->MinGW = Args.hasArg(OPT_lldmingw);
958
540
959
540
  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
540
974
540
  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
540
  }
980
540
981
540
  // Construct search path list.
982
540
  SearchPaths.push_back("");
983
540
  for (auto *Arg : Args.filtered(OPT_libpath))
984
12
    SearchPaths.push_back(Arg->getValue());
985
540
  addLibSearchPaths();
986
540
987
540
  // Handle /ignore
988
540
  for (auto *Arg : Args.filtered(OPT_ignore)) {
989
3
    if (StringRef(Arg->getValue()) == "4037")
990
2
      Config->WarnMissingOrderSymbol = false;
991
1
    else if (StringRef(Arg->getValue()) == "4217")
992
1
      Config->WarnLocallyDefinedImported = false;
993
3
    // Other warning numbers are ignored.
994
3
  }
995
540
996
540
  // Handle /out
997
540
  if (auto *Arg = Args.getLastArg(OPT_out))
998
507
    Config->OutputFile = Arg->getValue();
999
540
1000
540
  // Handle /verbose
1001
540
  if (Args.hasArg(OPT_verbose))
1002
49
    Config->Verbose = true;
1003
540
  errorHandler().Verbose = Config->Verbose;
1004
540
1005
540
  // Handle /force or /force:unresolved
1006
540
  if (Args.hasArg(OPT_force, OPT_force_unresolved))
1007
8
    Config->ForceUnresolved = true;
1008
540
1009
540
  // Handle /force or /force:multiple
1010
540
  if (Args.hasArg(OPT_force, OPT_force_multiple))
1011
9
    Config->ForceMultiple = true;
1012
540
1013
540
  // Handle /debug
1014
540
  DebugKind Debug = parseDebugKind(Args);
1015
540
  if (Debug == DebugKind::Full || 
Debug == DebugKind::Dwarf455
||
1016
540
      
Debug == DebugKind::GHash445
) {
1017
97
    Config->Debug = true;
1018
97
    Config->Incremental = true;
1019
97
  }
1020
540
1021
540
  // Handle /debugtype
1022
540
  Config->DebugTypes = parseDebugTypes(Args);
1023
540
1024
540
  // Handle /pdb
1025
540
  bool ShouldCreatePDB =
1026
540
      (Debug == DebugKind::Full || 
Debug == DebugKind::GHash455
);
1027
540
  if (ShouldCreatePDB) {
1028
87
    if (auto *Arg = Args.getLastArg(OPT_pdb))
1029
39
      Config->PDBPath = Arg->getValue();
1030
87
    if (auto *Arg = Args.getLastArg(OPT_pdbaltpath))
1031
13
      Config->PDBAltPath = Arg->getValue();
1032
87
    if (Args.hasArg(OPT_natvis))
1033
0
      Config->NatvisFiles = Args.getAllArgValues(OPT_natvis);
1034
87
1035
87
    if (auto *Arg = Args.getLastArg(OPT_pdb_source_path))
1036
2
      Config->PDBSourcePath = Arg->getValue();
1037
87
  }
1038
540
1039
540
  // Handle /noentry
1040
540
  if (Args.hasArg(OPT_noentry)) {
1041
11
    if (Args.hasArg(OPT_dll))
1042
11
      Config->NoEntry = true;
1043
0
    else
1044
0
      error("/noentry must be specified with /dll");
1045
11
  }
1046
540
1047
540
  // Handle /dll
1048
540
  if (Args.hasArg(OPT_dll)) {
1049
137
    Config->DLL = true;
1050
137
    Config->ManifestID = 2;
1051
137
  }
1052
540
1053
540
  // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1054
540
  // because we need to explicitly check whether that option or its inverse was
1055
540
  // present in the argument list in order to handle /fixed.
1056
540
  auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1057
540
  if (DynamicBaseArg &&
1058
540
      
DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no2
)
1059
2
    Config->DynamicBase = false;
1060
540
1061
540
  // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1062
540
  // default setting for any other project type.", but link.exe defaults to
1063
540
  // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1064
540
  bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1065
540
  if (Fixed) {
1066
6
    if (DynamicBaseArg &&
1067
6
        
DynamicBaseArg->getOption().getID() == OPT_dynamicbase0
) {
1068
0
      error("/fixed must not be specified with /dynamicbase");
1069
6
    } else {
1070
6
      Config->Relocatable = false;
1071
6
      Config->DynamicBase = false;
1072
6
    }
1073
6
  }
1074
540
1075
540
  // Handle /appcontainer
1076
540
  Config->AppContainer =
1077
540
      Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1078
540
1079
540
  // Handle /machine
1080
540
  if (auto *Arg = Args.getLastArg(OPT_machine))
1081
21
    Config->Machine = getMachineType(Arg->getValue());
1082
540
1083
540
  // Handle /nodefaultlib:<filename>
1084
540
  for (auto *Arg : Args.filtered(OPT_nodefaultlib))
1085
2
    Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
1086
540
1087
540
  // Handle /nodefaultlib
1088
540
  if (Args.hasArg(OPT_nodefaultlib_all))
1089
55
    Config->NoDefaultLibAll = true;
1090
540
1091
540
  // Handle /base
1092
540
  if (auto *Arg = Args.getLastArg(OPT_base))
1093
5
    parseNumbers(Arg->getValue(), &Config->ImageBase);
1094
540
1095
540
  // Handle /stack
1096
540
  if (auto *Arg = Args.getLastArg(OPT_stack))
1097
2
    parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
1098
540
1099
540
  // Handle /guard:cf
1100
540
  if (auto *Arg = Args.getLastArg(OPT_guard))
1101
11
    parseGuard(Arg->getValue());
1102
540
1103
540
  // Handle /heap
1104
540
  if (auto *Arg = Args.getLastArg(OPT_heap))
1105
3
    parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
1106
540
1107
540
  // Handle /version
1108
540
  if (auto *Arg = Args.getLastArg(OPT_version))
1109
2
    parseVersion(Arg->getValue(), &Config->MajorImageVersion,
1110
2
                 &Config->MinorImageVersion);
1111
540
1112
540
  // Handle /subsystem
1113
540
  if (auto *Arg = Args.getLastArg(OPT_subsystem))
1114
159
    parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
1115
159
                   &Config->MinorOSVersion);
1116
540
1117
540
  // Handle /timestamp
1118
540
  if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) {
1119
5
    if (Arg->getOption().getID() == OPT_repro) {
1120
4
      Config->Timestamp = 0;
1121
4
      Config->Repro = true;
1122
4
    } else {
1123
1
      Config->Repro = false;
1124
1
      StringRef Value(Arg->getValue());
1125
1
      if (Value.getAsInteger(0, Config->Timestamp))
1126
0
        fatal(Twine("invalid timestamp: ") + Value +
1127
0
              ".  Expected 32-bit integer");
1128
535
    }
1129
535
  } else {
1130
535
    Config->Repro = false;
1131
535
    Config->Timestamp = time(nullptr);
1132
535
  }
1133
540
1134
540
  // Handle /alternatename
1135
540
  for (auto *Arg : Args.filtered(OPT_alternatename))
1136
8
    parseAlternateName(Arg->getValue());
1137
540
1138
540
  // Handle /include
1139
540
  for (auto *Arg : Args.filtered(OPT_incl))
1140
21
    addUndefined(Arg->getValue());
1141
540
1142
540
  // Handle /implib
1143
540
  if (auto *Arg = Args.getLastArg(OPT_implib))
1144
27
    Config->Implib = Arg->getValue();
1145
540
1146
540
  // Handle /opt.
1147
540
  bool DoGC = Debug == DebugKind::None || 
Args.hasArg(OPT_profile)99
;
1148
540
  unsigned ICFLevel =
1149
540
      Args.hasArg(OPT_profile) ? 
07
:
1533
; // 0: off, 1: limited, 2: on
1150
540
  unsigned TailMerge = 1;
1151
540
  for (auto *Arg : Args.filtered(OPT_opt)) {
1152
68
    std::string Str = StringRef(Arg->getValue()).lower();
1153
68
    SmallVector<StringRef, 1> Vec;
1154
68
    StringRef(Str).split(Vec, ',');
1155
84
    for (StringRef S : Vec) {
1156
84
      if (S == "ref") {
1157
15
        DoGC = true;
1158
69
      } else if (S == "noref") {
1159
35
        DoGC = false;
1160
35
      } else 
if (34
S == "icf"34
||
S.startswith("icf=")22
) {
1161
12
        ICFLevel = 2;
1162
22
      } else if (S == "noicf") {
1163
17
        ICFLevel = 0;
1164
17
      } else 
if (5
S == "lldtailmerge"5
) {
1165
1
        TailMerge = 2;
1166
4
      } else if (S == "nolldtailmerge") {
1167
1
        TailMerge = 0;
1168
3
      } else if (S.startswith("lldlto=")) {
1169
2
        StringRef OptLevel = S.substr(7);
1170
2
        if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3)
1171
0
          error("/opt:lldlto: invalid optimization level: " + OptLevel);
1172
2
      } else 
if (1
S.startswith("lldltojobs=")1
) {
1173
0
        StringRef Jobs = S.substr(11);
1174
0
        if (Jobs.getAsInteger(10, Config->ThinLTOJobs) ||
1175
0
            Config->ThinLTOJobs == 0)
1176
0
          error("/opt:lldltojobs: invalid job count: " + Jobs);
1177
1
      } else if (S.startswith("lldltopartitions=")) {
1178
1
        StringRef N = S.substr(17);
1179
1
        if (N.getAsInteger(10, Config->LTOPartitions) ||
1180
1
            Config->LTOPartitions == 0)
1181
0
          error("/opt:lldltopartitions: invalid partition count: " + N);
1182
1
      } else 
if (0
S != "lbr"0
&&
S != "nolbr"0
)
1183
0
        error("/opt: unknown option: " + S);
1184
84
    }
1185
68
  }
1186
540
1187
540
  // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1188
540
  // explicitly.
1189
540
  // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1190
540
  // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1191
540
  // comdat readonly data.
1192
540
  if (ICFLevel == 1 && 
!DoGC508
)
1193
100
    ICFLevel = 0;
1194
540
  Config->DoGC = DoGC;
1195
540
  Config->DoICF = ICFLevel > 0;
1196
540
  Config->TailMerge = (TailMerge == 1 && 
Config->DoICF538
) ||
TailMerge == 2121
;
1197
540
1198
540
  // Handle /lldsavetemps
1199
540
  if (Args.hasArg(OPT_lldsavetemps))
1200
3
    Config->SaveTemps = true;
1201
540
1202
540
  // Handle /kill-at
1203
540
  if (Args.hasArg(OPT_kill_at))
1204
2
    Config->KillAt = true;
1205
540
1206
540
  // Handle /lldltocache
1207
540
  if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1208
1
    Config->LTOCache = Arg->getValue();
1209
540
1210
540
  // Handle /lldsavecachepolicy
1211
540
  if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
1212
1
    Config->LTOCachePolicy = CHECK(
1213
540
        parseCachePruningPolicy(Arg->getValue()),
1214
540
        Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1215
540
1216
540
  // Handle /failifmismatch
1217
540
  for (auto *Arg : Args.filtered(OPT_failifmismatch))
1218
4
    checkFailIfMismatch(Arg->getValue());
1219
540
1220
540
  // Handle /merge
1221
540
  for (auto *Arg : Args.filtered(OPT_merge))
1222
10
    parseMerge(Arg->getValue());
1223
540
1224
540
  // Add default section merging rules after user rules. User rules take
1225
540
  // precedence, but we will emit a warning if there is a conflict.
1226
540
  parseMerge(".idata=.rdata");
1227
540
  parseMerge(".didat=.rdata");
1228
540
  parseMerge(".edata=.rdata");
1229
540
  parseMerge(".xdata=.rdata");
1230
540
  parseMerge(".bss=.data");
1231
540
1232
540
  if (Config->MinGW) {
1233
40
    parseMerge(".ctors=.rdata");
1234
40
    parseMerge(".dtors=.rdata");
1235
40
    parseMerge(".CRT=.rdata");
1236
40
  }
1237
540
1238
540
  // Handle /section
1239
540
  for (auto *Arg : Args.filtered(OPT_section))
1240
6
    parseSection(Arg->getValue());
1241
540
1242
540
  // Handle /aligncomm
1243
540
  for (auto *Arg : Args.filtered(OPT_aligncomm))
1244
0
    parseAligncomm(Arg->getValue());
1245
540
1246
540
  // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1247
540
  // also passed.
1248
540
  if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1249
2
    Config->ManifestDependency = Arg->getValue();
1250
2
    Config->Manifest = Configuration::SideBySide;
1251
2
  }
1252
540
1253
540
  // Handle /manifest and /manifest:
1254
540
  if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1255
5
    if (Arg->getOption().getID() == OPT_manifest)
1256
4
      Config->Manifest = Configuration::SideBySide;
1257
1
    else
1258
1
      parseManifest(Arg->getValue());
1259
5
  }
1260
540
1261
540
  // Handle /manifestuac
1262
540
  if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1263
4
    parseManifestUAC(Arg->getValue());
1264
540
1265
540
  // Handle /manifestfile
1266
540
  if (auto *Arg = Args.getLastArg(OPT_manifestfile))
1267
0
    Config->ManifestFile = Arg->getValue();
1268
540
1269
540
  // Handle /manifestinput
1270
540
  for (auto *Arg : Args.filtered(OPT_manifestinput))
1271
1
    Config->ManifestInput.push_back(Arg->getValue());
1272
540
1273
540
  if (!Config->ManifestInput.empty() &&
1274
540
      
Config->Manifest != Configuration::Embed1
) {
1275
0
    fatal("/manifestinput: requires /manifest:embed");
1276
0
  }
1277
540
1278
540
  // Handle miscellaneous boolean flags.
1279
540
  Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1280
540
  Config->AllowIsolation =
1281
540
      Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1282
540
  Config->Incremental =
1283
540
      Args.hasFlag(OPT_incremental, OPT_incremental_no,
1284
540
                   !Config->DoGC && 
!Config->DoICF119
&&
!Args.hasArg(OPT_order)112
&&
1285
540
                       
!Args.hasArg(OPT_profile)104
);
1286
540
  Config->IntegrityCheck =
1287
540
      Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1288
540
  Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1289
540
  Config->TerminalServerAware =
1290
540
      !Config->DLL && 
Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true)403
;
1291
540
  Config->DebugDwarf = Debug == DebugKind::Dwarf;
1292
540
  Config->DebugGHashes = Debug == DebugKind::GHash;
1293
540
  Config->DebugSymtab = Debug == DebugKind::Symtab;
1294
540
1295
540
  Config->MapFile = getMapFile(Args);
1296
540
1297
540
  if (Config->Incremental && 
Args.hasArg(OPT_profile)107
) {
1298
2
    warn("ignoring '/incremental' due to '/profile' specification");
1299
2
    Config->Incremental = false;
1300
2
  }
1301
540
1302
540
  if (Config->Incremental && 
Args.hasArg(OPT_order)105
) {
1303
2
    warn("ignoring '/incremental' due to '/order' specification");
1304
2
    Config->Incremental = false;
1305
2
  }
1306
540
1307
540
  if (Config->Incremental && 
Config->DoGC103
) {
1308
4
    warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1309
4
         "disable");
1310
4
    Config->Incremental = false;
1311
4
  }
1312
540
1313
540
  if (Config->Incremental && 
Config->DoICF99
) {
1314
2
    warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1315
2
         "disable");
1316
2
    Config->Incremental = false;
1317
2
  }
1318
540
1319
540
  if (errorCount())
1320
5
    return;
1321
535
1322
535
  std::set<sys::fs::UniqueID> WholeArchives;
1323
535
  AutoExporter Exporter;
1324
535
  for (auto *Arg : Args.filtered(OPT_wholearchive_file)) {
1325
4
    if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
1326
4
      if (Optional<sys::fs::UniqueID> ID = getUniqueID(*Path))
1327
4
        WholeArchives.insert(*ID);
1328
4
      Exporter.addWholeArchive(*Path);
1329
4
    }
1330
4
  }
1331
535
1332
535
  // A predicate returning true if a given path is an argument for
1333
535
  // /wholearchive:, or /wholearchive is enabled globally.
1334
535
  // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1335
535
  // needs to be handled as "/wholearchive:foo.obj foo.obj".
1336
757
  auto IsWholeArchive = [&](StringRef Path) -> bool {
1337
757
    if (Args.hasArg(OPT_wholearchive_flag))
1338
2
      return true;
1339
755
    if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
1340
694
      return WholeArchives.count(*ID);
1341
61
    return false;
1342
61
  };
1343
535
1344
535
  // Create a list of input files. Files can be given as arguments
1345
535
  // for /defaultlib option.
1346
535
  for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file))
1347
761
    if (Optional<StringRef> Path = findFile(Arg->getValue()))
1348
757
      enqueuePath(*Path, IsWholeArchive(*Path));
1349
535
1350
535
  for (auto *Arg : Args.filtered(OPT_defaultlib))
1351
9
    if (Optional<StringRef> Path = findLib(Arg->getValue()))
1352
7
      enqueuePath(*Path, false);
1353
535
1354
535
  // Windows specific -- Create a resource file containing a manifest file.
1355
535
  if (Config->Manifest == Configuration::Embed)
1356
1
    addBuffer(createManifestRes(), false);
1357
535
1358
535
  // Read all input files given via the command line.
1359
535
  run();
1360
535
1361
535
  if (errorCount())
1362
20
    return;
1363
515
1364
515
  // We should have inferred a machine type by now from the input files, but if
1365
515
  // not we assume x64.
1366
515
  if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1367
2
    warn("/machine is not specified. x64 is assumed");
1368
2
    Config->Machine = AMD64;
1369
2
  }
1370
515
  Config->Wordsize = Config->is64() ? 
8411
:
4104
;
1371
515
1372
515
  // Input files can be Windows resource files (.res files). We use
1373
515
  // WindowsResource to convert resource files to a regular COFF file,
1374
515
  // then link the resulting file normally.
1375
515
  if (!Resources.empty())
1376
4
    Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
1377
515
1378
515
  if (Tar)
1379
4
    Tar->append("response.txt",
1380
4
                createResponseFile(Args, FilePaths,
1381
4
                                   ArrayRef<StringRef>(SearchPaths).slice(1)));
1382
515
1383
515
  // Handle /largeaddressaware
1384
515
  Config->LargeAddressAware = Args.hasFlag(
1385
515
      OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
1386
515
1387
515
  // Handle /highentropyva
1388
515
  Config->HighEntropyVA =
1389
515
      Config->is64() &&
1390
515
      
Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true)411
;
1391
515
1392
515
  if (!Config->DynamicBase &&
1393
515
      
(7
Config->Machine == ARMNT7
||
Config->Machine == ARM646
))
1394
2
    error("/dynamicbase:no is not compatible with " +
1395
2
          machineToStr(Config->Machine));
1396
515
1397
515
  // Handle /export
1398
515
  for (auto *Arg : Args.filtered(OPT_export)) {
1399
49
    Export E = parseExport(Arg->getValue());
1400
49
    if (Config->Machine == I386) {
1401
16
      if (!isDecorated(E.Name))
1402
16
        E.Name = Saver.save("_" + E.Name);
1403
16
      if (!E.ExtName.empty() && 
!isDecorated(E.ExtName)3
)
1404
3
        E.ExtName = Saver.save("_" + E.ExtName);
1405
16
    }
1406
49
    Config->Exports.push_back(E);
1407
49
  }
1408
515
1409
515
  // Handle /def
1410
515
  if (auto *Arg = Args.getLastArg(OPT_deffile)) {
1411
28
    // parseModuleDefs mutates Config object.
1412
28
    parseModuleDefs(Arg->getValue());
1413
28
  }
1414
515
1415
515
  // Handle generation of import library from a def file.
1416
515
  if (!Args.hasArg(OPT_INPUT)) {
1417
8
    fixupExports();
1418
8
    createImportLibrary(/*AsLib=*/true);
1419
8
    return;
1420
8
  }
1421
507
1422
507
  // Windows specific -- if no /subsystem is given, we need to infer
1423
507
  // that from entry point name.  Must happen before /entry handling,
1424
507
  // and after the early return when just writing an import library.
1425
507
  if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1426
355
    Config->Subsystem = inferSubsystem();
1427
355
    if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1428
0
      fatal("subsystem must be defined");
1429
507
  }
1430
507
1431
507
  // Handle /entry and /dll
1432
507
  if (auto *Arg = Args.getLastArg(OPT_entry)) {
1433
393
    Config->Entry = addUndefined(mangle(Arg->getValue()));
1434
393
  } else 
if (114
!Config->Entry114
&&
!Config->NoEntry113
) {
1435
102
    if (Args.hasArg(OPT_dll)) {
1436
64
      StringRef S = (Config->Machine == I386) ? 
"__DllMainCRTStartup@12"10
1437
64
                                              : 
"_DllMainCRTStartup"54
;
1438
64
      Config->Entry = addUndefined(S);
1439
64
    } else {
1440
38
      // Windows specific -- If entry point name is not given, we need to
1441
38
      // infer that from user-defined entry name.
1442
38
      StringRef S = findDefaultEntry();
1443
38
      if (S.empty())
1444
0
        fatal("entry point must be defined");
1445
38
      Config->Entry = addUndefined(S);
1446
38
      log("Entry name inferred: " + S);
1447
38
    }
1448
102
  }
1449
507
1450
507
  // Handle /delayload
1451
507
  for (auto *Arg : Args.filtered(OPT_delayload)) {
1452
4
    Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1453
4
    if (Config->Machine == I386) {
1454
1
      Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1455
3
    } else {
1456
3
      Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1457
3
    }
1458
4
  }
1459
507
1460
507
  // Set default image name if neither /out or /def set it.
1461
507
  if (Config->OutputFile.empty()) {
1462
21
    Config->OutputFile =
1463
21
        getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1464
21
  }
1465
507
1466
507
  if (ShouldCreatePDB) {
1467
87
    // Put the PDB next to the image if no /pdb flag was passed.
1468
87
    if (Config->PDBPath.empty()) {
1469
48
      Config->PDBPath = Config->OutputFile;
1470
48
      sys::path::replace_extension(Config->PDBPath, ".pdb");
1471
48
    }
1472
87
1473
87
    // The embedded PDB path should be the absolute path to the PDB if no
1474
87
    // /pdbaltpath flag was passed.
1475
87
    if (Config->PDBAltPath.empty()) {
1476
74
      Config->PDBAltPath = Config->PDBPath;
1477
74
1478
74
      // It's important to make the path absolute and remove dots.  This path
1479
74
      // will eventually be written into the PE header, and certain Microsoft
1480
74
      // tools won't work correctly if these assumptions are not held.
1481
74
      sys::fs::make_absolute(Config->PDBAltPath);
1482
74
      sys::path::remove_dots(Config->PDBAltPath);
1483
74
    } else {
1484
13
      // Don't do this earlier, so that Config->OutputFile is ready.
1485
13
      parsePDBAltPath(Config->PDBAltPath);
1486
13
    }
1487
87
  }
1488
507
1489
507
  // Set default image base if /base is not given.
1490
507
  if (Config->ImageBase == uint64_t(-1))
1491
502
    Config->ImageBase = getDefaultImageBase();
1492
507
1493
507
  Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1494
507
  if (Config->Machine == I386) {
1495
87
    Symtab->addAbsolute("___safe_se_handler_table", 0);
1496
87
    Symtab->addAbsolute("___safe_se_handler_count", 0);
1497
87
  }
1498
507
1499
507
  Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1500
507
  Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1501
507
  Symtab->addAbsolute(mangle("__guard_flags"), 0);
1502
507
  Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1503
507
  Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1504
507
  Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1505
507
  Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1506
507
  // Needed for MSVC 2017 15.5 CRT.
1507
507
  Symtab->addAbsolute(mangle("__enclave_config"), 0);
1508
507
1509
507
  if (Config->MinGW) {
1510
39
    Symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
1511
39
    Symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
1512
39
    Symtab->addAbsolute(mangle("__CTOR_LIST__"), 0);
1513
39
    Symtab->addAbsolute(mangle("__DTOR_LIST__"), 0);
1514
39
  }
1515
507
1516
507
  // This code may add new undefined symbols to the link, which may enqueue more
1517
507
  // symbol resolution tasks, so we need to continue executing tasks until we
1518
507
  // converge.
1519
512
  do {
1520
512
    // Windows specific -- if entry point is not found,
1521
512
    // search for its mangled names.
1522
512
    if (Config->Entry)
1523
501
      Symtab->mangleMaybe(Config->Entry);
1524
512
1525
512
    // Windows specific -- Make sure we resolve all dllexported symbols.
1526
512
    for (Export &E : Config->Exports) {
1527
175
      if (!E.ForwardTo.empty())
1528
2
        continue;
1529
173
      E.Sym = addUndefined(E.Name);
1530
173
      if (!E.Directives)
1531
72
        Symtab->mangleMaybe(E.Sym);
1532
173
    }
1533
512
1534
512
    // Add weak aliases. Weak aliases is a mechanism to give remaining
1535
512
    // undefined symbols final chance to be resolved successfully.
1536
512
    for (auto Pair : Config->AlternateNames) {
1537
9
      StringRef From = Pair.first;
1538
9
      StringRef To = Pair.second;
1539
9
      Symbol *Sym = Symtab->find(From);
1540
9
      if (!Sym)
1541
2
        continue;
1542
7
      if (auto *U = dyn_cast<Undefined>(Sym))
1543
7
        if (!U->WeakAlias)
1544
7
          U->WeakAlias = Symtab->addUndefined(To);
1545
7
    }
1546
512
1547
512
    // Windows specific -- if __load_config_used can be resolved, resolve it.
1548
512
    if (Symtab->findUnderscore("_load_config_used"))
1549
18
      addUndefined(mangle("_load_config_used"));
1550
512
  } while (run());
1551
507
1552
507
  if (errorCount())
1553
2
    return;
1554
505
1555
505
  // Do LTO by compiling bitcode input files to a set of native COFF files then
1556
505
  // link those files.
1557
505
  Symtab->addCombinedLTOObjects();
1558
505
  run();
1559
505
1560
505
  if (Config->MinGW) {
1561
39
    // Load any further object files that might be needed for doing automatic
1562
39
    // imports.
1563
39
    //
1564
39
    // For cases with no automatically imported symbols, this iterates once
1565
39
    // over the symbol table and doesn't do anything.
1566
39
    //
1567
39
    // For the normal case with a few automatically imported symbols, this
1568
39
    // should only need to be run once, since each new object file imported
1569
39
    // is an import library and wouldn't add any new undefined references,
1570
39
    // but there's nothing stopping the __imp_ symbols from coming from a
1571
39
    // normal object file as well (although that won't be used for the
1572
39
    // actual autoimport later on). If this pass adds new undefined references,
1573
39
    // we won't iterate further to resolve them.
1574
39
    Symtab->loadMinGWAutomaticImports();
1575
39
    run();
1576
39
  }
1577
505
1578
505
  // Make sure we have resolved all symbols.
1579
505
  Symtab->reportRemainingUndefines();
1580
505
  if (errorCount())
1581
25
    return;
1582
480
1583
480
  // Handle /safeseh.
1584
480
  if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
1585
7
    for (ObjFile *File : ObjFile::Instances)
1586
7
      if (!File->hasSafeSEH())
1587
1
        error("/safeseh: " + File->getName() + " is not compatible with SEH");
1588
7
    if (errorCount())
1589
1
      return;
1590
479
  }
1591
479
1592
479
  // In MinGW, all symbols are automatically exported if no symbols
1593
479
  // are chosen to be exported.
1594
479
  if (Config->DLL && 
(133
(133
Config->MinGW133
&&
Config->Exports.empty()17
) ||
1595
133
                      
Args.hasArg(OPT_export_all_symbols)120
)) {
1596
14
    Exporter.initSymbolExcludes();
1597
14
1598
247
    Symtab->forEachSymbol([=](Symbol *S) {
1599
247
      auto *Def = dyn_cast<Defined>(S);
1600
247
      if (!Exporter.shouldExport(Def))
1601
223
        return;
1602
24
      Export E;
1603
24
      E.Name = Def->getName();
1604
24
      E.Sym = Def;
1605
24
      if (Def->getChunk() &&
1606
24
          !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1607
7
        E.Data = true;
1608
24
      Config->Exports.push_back(E);
1609
24
    });
1610
14
  }
1611
479
1612
479
  // Windows specific -- when we are creating a .dll file, we also
1613
479
  // need to create a .lib file.
1614
479
  if (!Config->Exports.empty() || 
Config->DLL375
) {
1615
137
    fixupExports();
1616
137
    createImportLibrary(/*AsLib=*/false);
1617
137
    assignExportOrdinals();
1618
137
  }
1619
479
1620
479
  // Handle /output-def (MinGW specific).
1621
479
  if (auto *Arg = Args.getLastArg(OPT_output_def))
1622
4
    writeDefFile(Arg->getValue());
1623
479
1624
479
  // Set extra alignment for .comm symbols
1625
479
  for (auto Pair : Config->AlignComm) {
1626
2
    StringRef Name = Pair.first;
1627
2
    uint32_t Alignment = Pair.second;
1628
2
1629
2
    Symbol *Sym = Symtab->find(Name);
1630
2
    if (!Sym) {
1631
0
      warn("/aligncomm symbol " + Name + " not found");
1632
0
      continue;
1633
0
    }
1634
2
1635
2
    // If the symbol isn't common, it must have been replaced with a regular
1636
2
    // symbol, which will carry its own alignment.
1637
2
    auto *DC = dyn_cast<DefinedCommon>(Sym);
1638
2
    if (!DC)
1639
1
      continue;
1640
1
1641
1
    CommonChunk *C = DC->getChunk();
1642
1
    C->Alignment = std::max(C->Alignment, Alignment);
1643
1
  }
1644
479
1645
479
  // Windows specific -- Create a side-by-side manifest file.
1646
479
  if (Config->Manifest == Configuration::SideBySide)
1647
5
    createSideBySideManifest();
1648
479
1649
479
  // Handle /order. We want to do this at this moment because we
1650
479
  // need a complete list of comdat sections to warn on nonexistent
1651
479
  // functions.
1652
479
  if (auto *Arg = Args.getLastArg(OPT_order))
1653
8
    parseOrderFile(Arg->getValue());
1654
479
1655
479
  // Identify unreferenced COMDAT sections.
1656
479
  if (Config->DoGC)
1657
360
    markLive(Symtab->getChunks());
1658
479
1659
479
  // Identify identical COMDAT sections to merge them.
1660
479
  if (Config->DoICF) {
1661
359
    findKeepUniqueSections();
1662
359
    doICF(Symtab->getChunks());
1663
359
  }
1664
479
1665
479
  // Write the result.
1666
479
  writeResult();
1667
479
1668
479
  // Stop early so we can print the results.
1669
479
  Timer::root().stop();
1670
479
  if (Config->ShowTiming)
1671
0
    Timer::root().print();
1672
479
}
1673
1674
} // namespace coff
1675
} // namespace lld