Coverage Report

Created: 2019-05-19 14:56

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