Coverage Report

Created: 2019-06-16 23:17

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