Coverage Report

Created: 2017-09-21 03:39

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/lld/COFF/Driver.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Driver.cpp ---------------------------------------------------------===//
2
//
3
//                             The LLVM Linker
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
10
#include "Driver.h"
11
#include "Config.h"
12
#include "Error.h"
13
#include "InputFiles.h"
14
#include "Memory.h"
15
#include "SymbolTable.h"
16
#include "Symbols.h"
17
#include "Writer.h"
18
#include "lld/Driver/Driver.h"
19
#include "llvm/ADT/Optional.h"
20
#include "llvm/ADT/StringSwitch.h"
21
#include "llvm/BinaryFormat/Magic.h"
22
#include "llvm/Object/ArchiveWriter.h"
23
#include "llvm/Object/COFFImportFile.h"
24
#include "llvm/Object/COFFModuleDefinition.h"
25
#include "llvm/Option/Arg.h"
26
#include "llvm/Option/ArgList.h"
27
#include "llvm/Option/Option.h"
28
#include "llvm/Support/Debug.h"
29
#include "llvm/Support/Path.h"
30
#include "llvm/Support/Process.h"
31
#include "llvm/Support/TarWriter.h"
32
#include "llvm/Support/TargetSelect.h"
33
#include "llvm/Support/raw_ostream.h"
34
#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
35
#include <algorithm>
36
#include <memory>
37
38
#include <future>
39
40
using namespace llvm;
41
using namespace llvm::object;
42
using namespace llvm::COFF;
43
using llvm::sys::Process;
44
45
namespace lld {
46
namespace coff {
47
48
Configuration *Config;
49
LinkerDriver *Driver;
50
51
BumpPtrAllocator BAlloc;
52
StringSaver Saver{BAlloc};
53
std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
54
55
275
bool link(ArrayRef<const char *> Args, raw_ostream &Diag) {
56
275
  ErrorCount = 0;
57
275
  ErrorOS = &Diag;
58
275
59
275
  Config = make<Configuration>();
60
275
  Config->Argv = {Args.begin(), Args.end()};
61
275
  Config->ColorDiagnostics = ErrorOS->has_colors();
62
275
63
275
  Symtab = make<SymbolTable>();
64
275
65
275
  Driver = make<LinkerDriver>();
66
275
  Driver->link(Args);
67
275
  return !ErrorCount;
68
275
}
69
70
// Drop directory components and replace extension with ".exe" or ".dll".
71
10
static std::string getOutputPath(StringRef Path) {
72
10
  auto P = Path.find_last_of("\\/");
73
10
  StringRef S = (P == StringRef::npos) ? 
Path2
:
Path.substr(P + 1)8
;
74
10
  const char* E = Config->DLL ? 
".dll"2
:
".exe"8
;
75
10
  return (S.substr(0, S.rfind('.')) + E).str();
76
10
}
77
78
// ErrorOr is not default constructible, so it cannot be used as the type
79
// parameter of a future.
80
// FIXME: We could open the file in createFutureForFile and avoid needing to
81
// return an error here, but for the moment that would cost us a file descriptor
82
// (a limited resource on Windows) for the duration that the future is pending.
83
typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
84
85
// Create a std::future that opens and maps a file using the best strategy for
86
// the host platform.
87
365
static std::future<MBErrPair> createFutureForFile(std::string Path) {
88
#if LLVM_ON_WIN32
89
  // On Windows, file I/O is relatively slow so it is best to do this
90
  // asynchronously.
91
  auto Strategy = std::launch::async;
92
#else
93
  auto Strategy = std::launch::deferred;
94
365
#endif
95
365
  return std::async(Strategy, [=]() {
96
365
    auto MBOrErr = MemoryBuffer::getFile(Path);
97
365
    if (!MBOrErr)
98
4
      return MBErrPair{nullptr, MBOrErr.getError()};
99
361
    return MBErrPair{std::move(*MBOrErr), std::error_code()};
100
361
  });
101
365
}
102
103
363
MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
104
363
  MemoryBufferRef MBRef = *MB;
105
363
  make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
106
363
107
363
  if (Driver->Tar)
108
6
    Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
109
6
                        MBRef.getBuffer());
110
363
  return MBRef;
111
363
}
112
113
void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
114
363
                             bool WholeArchive) {
115
363
  MemoryBufferRef MBRef = takeBuffer(std::move(MB));
116
363
117
363
  // File type is detected by contents, not by file extension.
118
363
  file_magic Magic = identify_magic(MBRef.getBuffer());
119
363
  if (
Magic == file_magic::windows_resource363
) {
120
4
    Resources.push_back(MBRef);
121
4
    return;
122
4
  }
123
359
124
359
  FilePaths.push_back(MBRef.getBufferIdentifier());
125
359
  if (
Magic == file_magic::archive359
) {
126
57
    if (
WholeArchive57
) {
127
2
      std::unique_ptr<Archive> File =
128
2
          check(Archive::create(MBRef),
129
2
                MBRef.getBufferIdentifier() + ": failed to parse archive");
130
2
131
2
      for (MemoryBufferRef M : getArchiveMembers(File.get()))
132
2
        addArchiveBuffer(M, "<whole-archive>", MBRef.getBufferIdentifier());
133
2
      return;
134
2
    }
135
55
    Symtab->addFile(make<ArchiveFile>(MBRef));
136
55
    return;
137
55
  }
138
302
139
302
  
if (302
Magic == file_magic::bitcode302
) {
140
40
    Symtab->addFile(make<BitcodeFile>(MBRef));
141
40
    return;
142
40
  }
143
262
144
262
  
if (262
Magic == file_magic::coff_cl_gl_object262
)
145
1
    error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
146
1
          "Recompile without /GL");
147
262
  else
148
261
    Symtab->addFile(make<ObjFile>(MBRef));
149
363
}
150
151
365
void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
152
365
  auto Future =
153
365
      std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
154
365
  std::string PathStr = Path;
155
365
  enqueueTask([=]() {
156
365
    auto MBOrErr = Future->get();
157
365
    if (MBOrErr.second)
158
4
      error("could not open " + PathStr + ": " + MBOrErr.second.message());
159
365
    else
160
361
      Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
161
365
  });
162
365
}
163
164
void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
165
89
                                    StringRef ParentName) {
166
89
  file_magic Magic = identify_magic(MB.getBuffer());
167
89
  if (
Magic == file_magic::coff_import_library89
) {
168
66
    Symtab->addFile(make<ImportFile>(MB));
169
66
    return;
170
66
  }
171
23
172
23
  InputFile *Obj;
173
23
  if (
Magic == file_magic::coff_object23
) {
174
14
    Obj = make<ObjFile>(MB);
175
23
  } else 
if (9
Magic == file_magic::bitcode9
) {
176
9
    Obj = make<BitcodeFile>(MB);
177
9
  } else {
178
0
    error("unknown file type: " + MB.getBufferIdentifier());
179
0
    return;
180
0
  }
181
23
182
23
  Obj->ParentName = ParentName;
183
23
  Symtab->addFile(Obj);
184
23
  log("Loaded " + toString(Obj) + " for " + SymName);
185
23
}
186
187
void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
188
                                        StringRef SymName,
189
87
                                        StringRef ParentName) {
190
87
  if (
!C.getParent()->isThin()87
) {
191
87
    MemoryBufferRef MB = check(
192
87
        C.getMemoryBufferRef(),
193
87
        "could not get the buffer for the member defining symbol " + SymName);
194
87
    enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
195
87
    return;
196
87
  }
197
0
198
0
  auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
199
0
      check(C.getFullName(),
200
0
            "could not get the filename for the member defining symbol " +
201
0
                SymName)));
202
0
  enqueueTask([=]() {
203
0
    auto MBOrErr = Future->get();
204
0
    if (MBOrErr.second)
205
0
      fatal(MBOrErr.second,
206
0
            "could not get the buffer for the member defining " + SymName);
207
0
    Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
208
0
                             ParentName);
209
0
  });
210
87
}
211
212
18
static bool isDecorated(StringRef Sym) {
213
18
  return Sym.startswith("_") || 
Sym.startswith("@")18
||
Sym.startswith("?")18
;
214
18
}
215
216
// Parses .drectve section contents and returns a list of files
217
// specified by /defaultlib.
218
77
void LinkerDriver::parseDirectives(StringRef S) {
219
77
  ArgParser Parser;
220
77
  // .drectve is always tokenized using Windows shell rules.
221
77
  opt::InputArgList Args = Parser.parse(S);
222
77
223
107
  for (auto *Arg : Args) {
224
107
    switch (Arg->getOption().getUnaliasedOption().getID()) {
225
1
    case OPT_aligncomm:
226
1
      parseAligncomm(Arg->getValue());
227
1
      break;
228
1
    case OPT_alternatename:
229
1
      parseAlternateName(Arg->getValue());
230
1
      break;
231
61
    case OPT_defaultlib:
232
61
      if (Optional<StringRef> Path = findLib(Arg->getValue()))
233
1
        enqueuePath(*Path, false);
234
61
      break;
235
37
    case OPT_export: {
236
37
      Export E = parseExport(Arg->getValue());
237
37
      if (
Config->Machine == I386 && 37
Config->MinGW11
) {
238
1
        if (!isDecorated(E.Name))
239
1
          E.Name = Saver.save("_" + E.Name);
240
1
        if (
!E.ExtName.empty() && 1
!isDecorated(E.ExtName)0
)
241
0
          E.ExtName = Saver.save("_" + E.ExtName);
242
1
      }
243
37
      E.Directives = true;
244
37
      Config->Exports.push_back(E);
245
37
      break;
246
107
    }
247
0
    case OPT_failifmismatch:
248
0
      checkFailIfMismatch(Arg->getValue());
249
0
      break;
250
7
    case OPT_incl:
251
7
      addUndefined(Arg->getValue());
252
7
      break;
253
0
    case OPT_merge:
254
0
      parseMerge(Arg->getValue());
255
0
      break;
256
0
    case OPT_nodefaultlib:
257
0
      Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
258
0
      break;
259
0
    case OPT_section:
260
0
      parseSection(Arg->getValue());
261
0
      break;
262
0
    case OPT_editandcontinue:
263
0
    case OPT_fastfail:
264
0
    case OPT_guardsym:
265
0
    case OPT_natvis:
266
0
    case OPT_throwingnew:
267
0
      break;
268
0
    default:
269
0
      error(Arg->getSpelling() + " is not allowed in .drectve");
270
107
    }
271
107
  }
272
77
}
273
274
// Find file from search paths. You can omit ".obj", this function takes
275
// care of that. Note that the returned path is not guaranteed to exist.
276
367
StringRef LinkerDriver::doFindFile(StringRef Filename) {
277
367
  bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
278
367
  if (HasPathSep)
279
334
    return Filename;
280
33
  bool HasExt = Filename.contains('.');
281
42
  for (StringRef Dir : SearchPaths) {
282
42
    SmallString<128> Path = Dir;
283
42
    sys::path::append(Path, Filename);
284
42
    if (sys::fs::exists(Path.str()))
285
29
      return Saver.save(Path.str());
286
13
    
if (13
!HasExt13
) {
287
1
      Path.append(".obj");
288
1
      if (sys::fs::exists(Path.str()))
289
0
        return Saver.save(Path.str());
290
4
    }
291
42
  }
292
4
  return Filename;
293
4
}
294
295
// Resolves a file path. This never returns the same path
296
// (in that case, it returns None).
297
360
Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
298
360
  StringRef Path = doFindFile(Filename);
299
360
  bool Seen = !VisitedFiles.insert(Path.lower()).second;
300
360
  if (Seen)
301
2
    return None;
302
358
  return Path;
303
358
}
304
305
// Find library file from search path.
306
7
StringRef LinkerDriver::doFindLib(StringRef Filename) {
307
7
  // Add ".lib" to Filename if that has no file extension.
308
7
  bool HasExt = Filename.contains('.');
309
7
  if (!HasExt)
310
2
    Filename = Saver.save(Filename + ".lib");
311
7
  return doFindFile(Filename);
312
7
}
313
314
// Resolves a library path. /nodefaultlib options are taken into
315
// consideration. This never returns the same path (in that case,
316
// it returns None).
317
67
Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
318
67
  if (Config->NoDefaultLibAll)
319
60
    return None;
320
7
  
if (7
!VisitedLibs.insert(Filename.lower()).second7
)
321
0
    return None;
322
7
  StringRef Path = doFindLib(Filename);
323
7
  if (Config->NoDefaultLibs.count(Path))
324
0
    return None;
325
7
  
if (7
!VisitedFiles.insert(Path.lower()).second7
)
326
0
    return None;
327
7
  return Path;
328
7
}
329
330
// Parses LIB environment which contains a list of search paths.
331
272
void LinkerDriver::addLibSearchPaths() {
332
272
  Optional<std::string> EnvOpt = Process::GetEnv("LIB");
333
272
  if (!EnvOpt.hasValue())
334
268
    return;
335
4
  StringRef Env = Saver.save(*EnvOpt);
336
8
  while (
!Env.empty()8
) {
337
4
    StringRef Path;
338
4
    std::tie(Path, Env) = Env.split(';');
339
4
    SearchPaths.push_back(Path);
340
4
  }
341
272
}
342
343
382
SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
344
382
  SymbolBody *B = Symtab->addUndefined(Name);
345
382
  Config->GCRoot.insert(B);
346
382
  return B;
347
382
}
348
349
// Symbol names are mangled by appending "_" prefix on x86.
350
2.35k
StringRef LinkerDriver::mangle(StringRef Sym) {
351
2.35k
  assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
352
2.35k
  if (Config->Machine == I386)
353
355
    return Saver.save("_" + Sym);
354
2.00k
  return Sym;
355
2.00k
}
356
357
// Windows specific -- find default entry point name.
358
4
StringRef LinkerDriver::findDefaultEntry() {
359
4
  // User-defined main functions and their corresponding entry points.
360
4
  static const char *Entries[][2] = {
361
4
      {"main", "mainCRTStartup"},
362
4
      {"wmain", "wmainCRTStartup"},
363
4
      {"WinMain", "WinMainCRTStartup"},
364
4
      {"wWinMain", "wWinMainCRTStartup"},
365
4
  };
366
10
  for (auto E : Entries) {
367
10
    StringRef Entry = Symtab->findMangle(mangle(E[0]));
368
10
    if (
!Entry.empty() && 10
!isa<Undefined>(Symtab->find(Entry)->body())4
)
369
4
      return mangle(E[1]);
370
0
  }
371
0
  return "";
372
0
}
373
374
166
WindowsSubsystem LinkerDriver::inferSubsystem() {
375
166
  if (Config->DLL)
376
48
    return IMAGE_SUBSYSTEM_WINDOWS_GUI;
377
118
  
if (118
Symtab->findUnderscore("main") || 118
Symtab->findUnderscore("wmain")3
)
378
116
    return IMAGE_SUBSYSTEM_WINDOWS_CUI;
379
2
  
if (2
Symtab->findUnderscore("WinMain") || 2
Symtab->findUnderscore("wWinMain")1
)
380
2
    return IMAGE_SUBSYSTEM_WINDOWS_GUI;
381
0
  return IMAGE_SUBSYSTEM_UNKNOWN;
382
0
}
383
384
261
static uint64_t getDefaultImageBase() {
385
261
  if (Config->is64())
386
213
    
return Config->DLL ? 213
0x18000000034
:
0x140000000179
;
387
48
  
return Config->DLL ? 48
0x1000000017
:
0x40000031
;
388
261
}
389
390
static std::string createResponseFile(const opt::InputArgList &Args,
391
                                      ArrayRef<StringRef> FilePaths,
392
3
                                      ArrayRef<StringRef> SearchPaths) {
393
3
  SmallString<0> Data;
394
3
  raw_svector_ostream OS(Data);
395
3
396
19
  for (auto *Arg : Args) {
397
19
    switch (Arg->getOption().getID()) {
398
10
    case OPT_linkrepro:
399
10
    case OPT_INPUT:
400
10
    case OPT_defaultlib:
401
10
    case OPT_libpath:
402
10
      break;
403
9
    default:
404
9
      OS << toString(Arg) << "\n";
405
19
    }
406
19
  }
407
3
408
3
  
for (StringRef Path : SearchPaths) 3
{
409
2
    std::string RelPath = relativeToRoot(Path);
410
2
    OS << "/libpath:" << quote(RelPath) << "\n";
411
2
  }
412
3
413
3
  for (StringRef Path : FilePaths)
414
6
    OS << quote(relativeToRoot(Path)) << "\n";
415
3
416
3
  return Data.str();
417
3
}
418
419
40
static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
420
40
  unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
421
40
  if (Args.hasArg(OPT_driver))
422
0
    DebugTypes |= static_cast<unsigned>(DebugType::PData);
423
40
  if (Args.hasArg(OPT_profile))
424
0
    DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
425
40
  return DebugTypes;
426
40
}
427
428
2
static unsigned parseDebugType(StringRef Arg) {
429
2
  SmallVector<StringRef, 3> Types;
430
2
  Arg.split(Types, ',', /*KeepEmpty=*/false);
431
2
432
2
  unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
433
2
  for (StringRef Type : Types)
434
2
    DebugTypes |= StringSwitch<unsigned>(Type.lower())
435
2
                      .Case("cv", static_cast<unsigned>(DebugType::CV))
436
2
                      .Case("pdata", static_cast<unsigned>(DebugType::PData))
437
2
                      .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
438
2
                      .Default(0);
439
2
  return DebugTypes;
440
2
}
441
442
272
static std::string getMapFile(const opt::InputArgList &Args) {
443
272
  auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
444
272
  if (!Arg)
445
265
    return "";
446
7
  
if (7
Arg->getOption().getID() == OPT_lldmap_file7
)
447
6
    return Arg->getValue();
448
1
449
7
  assert(Arg->getOption().getID() == OPT_lldmap);
450
1
  StringRef OutFile = Config->OutputFile;
451
1
  return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
452
1
}
453
454
61
static std::string getImplibPath() {
455
61
  if (!Config->Implib.empty())
456
10
    return Config->Implib;
457
51
  SmallString<128> Out = StringRef(Config->OutputFile);
458
51
  sys::path::replace_extension(Out, ".lib");
459
51
  return Out.str();
460
51
}
461
462
//
463
// The import name is caculated as the following:
464
//
465
//        | LIBRARY w/ ext |   LIBRARY w/o ext   | no LIBRARY
466
//   -----+----------------+---------------------+------------------
467
//   LINK | {value}        | {value}.{.dll/.exe} | {output name}
468
//    LIB | {value}        | {value}.dll         | {output name}.dll
469
//
470
61
static std::string getImportName(bool AsLib) {
471
61
  SmallString<128> Out;
472
61
473
61
  if (
Config->ImportName.empty()61
) {
474
51
    Out.assign(sys::path::filename(Config->OutputFile));
475
51
    if (AsLib)
476
2
      sys::path::replace_extension(Out, ".dll");
477
61
  } else {
478
10
    Out.assign(Config->ImportName);
479
10
    if (!sys::path::has_extension(Out))
480
7
      sys::path::replace_extension(Out,
481
7
                                   (Config->DLL || 
AsLib3
) ?
".dll"6
:
".exe"1
);
482
10
  }
483
61
484
61
  return Out.str();
485
61
}
486
487
61
static void createImportLibrary(bool AsLib) {
488
61
  std::vector<COFFShortExport> Exports;
489
90
  for (Export &E1 : Config->Exports) {
490
90
    COFFShortExport E2;
491
90
    E2.Name = E1.Name;
492
90
    E2.SymbolName = E1.SymbolName;
493
90
    E2.ExtName = E1.ExtName;
494
90
    E2.Ordinal = E1.Ordinal;
495
90
    E2.Noname = E1.Noname;
496
90
    E2.Data = E1.Data;
497
90
    E2.Private = E1.Private;
498
90
    E2.Constant = E1.Constant;
499
90
    Exports.push_back(E2);
500
90
  }
501
61
502
61
  writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports,
503
61
                     Config->Machine, false);
504
61
}
505
506
21
static void parseModuleDefs(StringRef Path) {
507
21
  std::unique_ptr<MemoryBuffer> MB = check(
508
21
    MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
509
21
  COFFModuleDefinition M =
510
21
      check(parseCOFFModuleDefinition(MB->getMemBufferRef(), Config->Machine));
511
21
512
21
  if (Config->OutputFile.empty())
513
2
    Config->OutputFile = Saver.save(M.OutputFile);
514
21
  Config->ImportName = Saver.save(M.ImportName);
515
21
  if (M.ImageBase)
516
0
    Config->ImageBase = M.ImageBase;
517
21
  if (M.StackReserve)
518
2
    Config->StackReserve = M.StackReserve;
519
21
  if (M.StackCommit)
520
1
    Config->StackCommit = M.StackCommit;
521
21
  if (M.HeapReserve)
522
2
    Config->HeapReserve = M.HeapReserve;
523
21
  if (M.HeapCommit)
524
1
    Config->HeapCommit = M.HeapCommit;
525
21
  if (M.MajorImageVersion)
526
0
    Config->MajorImageVersion = M.MajorImageVersion;
527
21
  if (M.MinorImageVersion)
528
0
    Config->MinorImageVersion = M.MinorImageVersion;
529
21
  if (M.MajorOSVersion)
530
0
    Config->MajorOSVersion = M.MajorOSVersion;
531
21
  if (M.MinorOSVersion)
532
0
    Config->MinorOSVersion = M.MinorOSVersion;
533
21
534
17
  for (COFFShortExport E1 : M.Exports) {
535
17
    Export E2;
536
17
    E2.Name = Saver.save(E1.Name);
537
17
    if (E1.isWeak())
538
2
      E2.ExtName = Saver.save(E1.ExtName);
539
17
    E2.Ordinal = E1.Ordinal;
540
17
    E2.Noname = E1.Noname;
541
17
    E2.Data = E1.Data;
542
17
    E2.Private = E1.Private;
543
17
    E2.Constant = E1.Constant;
544
17
    Config->Exports.push_back(E2);
545
17
  }
546
21
}
547
548
// A helper function for filterBitcodeFiles.
549
0
static bool needsRebuilding(MemoryBufferRef MB) {
550
0
  // The MSVC linker doesn't support thin archives, so if it's a thin
551
0
  // archive, we always need to rebuild it.
552
0
  std::unique_ptr<Archive> File =
553
0
      check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
554
0
  if (File->isThin())
555
0
    return true;
556
0
557
0
  // Returns true if the archive contains at least one bitcode file.
558
0
  for (MemoryBufferRef Member : getArchiveMembers(File.get()))
559
0
    
if (0
identify_magic(Member.getBuffer()) == file_magic::bitcode0
)
560
0
      return true;
561
0
  return false;
562
0
}
563
564
// Opens a given path as an archive file and removes bitcode files
565
// from them if exists. This function is to appease the MSVC linker as
566
// their linker doesn't like archive files containing non-native
567
// object files.
568
//
569
// If a given archive doesn't contain bitcode files, the archive path
570
// is returned as-is. Otherwise, a new temporary file is created and
571
// its path is returned.
572
static Optional<std::string>
573
0
filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
574
0
  std::unique_ptr<MemoryBuffer> MB = check(
575
0
      MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
576
0
  MemoryBufferRef MBRef = MB->getMemBufferRef();
577
0
  file_magic Magic = identify_magic(MBRef.getBuffer());
578
0
579
0
  if (Magic == file_magic::bitcode)
580
0
    return None;
581
0
  
if (0
Magic != file_magic::archive0
)
582
0
    return Path.str();
583
0
  
if (0
!needsRebuilding(MBRef)0
)
584
0
    return Path.str();
585
0
586
0
  std::unique_ptr<Archive> File =
587
0
      check(Archive::create(MBRef),
588
0
            MBRef.getBufferIdentifier() + ": failed to parse archive");
589
0
590
0
  std::vector<NewArchiveMember> New;
591
0
  for (MemoryBufferRef Member : getArchiveMembers(File.get()))
592
0
    
if (0
identify_magic(Member.getBuffer()) != file_magic::bitcode0
)
593
0
      New.emplace_back(Member);
594
0
595
0
  if (New.empty())
596
0
    return None;
597
0
598
0
  log("Creating a temporary archive for " + Path + " to remove bitcode files");
599
0
600
0
  SmallString<128> S;
601
0
  if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
602
0
                                             ".lib", S))
603
0
    fatal(EC, "cannot create a temporary file");
604
0
  std::string Temp = S.str();
605
0
  TemporaryFiles.push_back(Temp);
606
0
607
0
  std::error_code EC =
608
0
      llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
609
0
                         /*Deterministics=*/true,
610
0
                         /*Thin=*/false);
611
0
  if (EC)
612
0
    error("failed to create a new archive " + S.str() + ": " + EC.message());
613
0
  return Temp;
614
0
}
615
616
// Create response file contents and invoke the MSVC linker.
617
0
void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
618
0
  std::string Rsp = "/nologo\n";
619
0
  std::vector<std::string> Temps;
620
0
621
0
  // Write out archive members that we used in symbol resolution and pass these
622
0
  // to MSVC before any archives, so that MSVC uses the same objects to satisfy
623
0
  // references.
624
0
  for (ObjFile *Obj : ObjFile::Instances) {
625
0
    if (Obj->ParentName.empty())
626
0
      continue;
627
0
    SmallString<128> S;
628
0
    int Fd;
629
0
    if (auto EC = sys::fs::createTemporaryFile(
630
0
            "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
631
0
      fatal(EC, "cannot create a temporary file");
632
0
    raw_fd_ostream OS(Fd, /*shouldClose*/ true);
633
0
    OS << Obj->MB.getBuffer();
634
0
    Temps.push_back(S.str());
635
0
    Rsp += quote(S) + "\n";
636
0
  }
637
0
638
0
  
for (auto *Arg : Args) 0
{
639
0
    switch (Arg->getOption().getID()) {
640
0
    case OPT_linkrepro:
641
0
    case OPT_lldmap:
642
0
    case OPT_lldmap_file:
643
0
    case OPT_lldsavetemps:
644
0
    case OPT_msvclto:
645
0
      // LLD-specific options are stripped.
646
0
      break;
647
0
    case OPT_opt:
648
0
      if (!StringRef(Arg->getValue()).startswith("lld"))
649
0
        Rsp += toString(Arg) + " ";
650
0
      break;
651
0
    case OPT_INPUT: {
652
0
      if (Optional<StringRef> 
Path0
= doFindFile(Arg->getValue())) {
653
0
        if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
654
0
          Rsp += quote(*S) + "\n";
655
0
        continue;
656
0
      }
657
0
      Rsp += quote(Arg->getValue()) + "\n";
658
0
      break;
659
0
    }
660
0
    default:
661
0
      Rsp += toString(Arg) + "\n";
662
0
    }
663
0
  }
664
0
665
0
  std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
666
0
  runMSVCLinker(Rsp, ObjFiles);
667
0
668
0
  for (StringRef Path : Temps)
669
0
    sys::fs::remove(Path);
670
0
}
671
672
452
void LinkerDriver::enqueueTask(std::function<void()> Task) {
673
452
  TaskQueue.push_back(std::move(Task));
674
452
}
675
676
795
bool LinkerDriver::run() {
677
795
  bool DidWork = !TaskQueue.empty();
678
1.24k
  while (
!TaskQueue.empty()1.24k
) {
679
452
    TaskQueue.front()();
680
452
    TaskQueue.pop_front();
681
452
  }
682
795
  return DidWork;
683
795
}
684
685
275
void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
686
275
  // If the first command line argument is "/lib", link.exe acts like lib.exe.
687
275
  // We call our own implementation of lib.exe that understands bitcode files.
688
275
  if (
ArgsArr.size() > 1 && 275
StringRef(ArgsArr[1]).equals_lower("/lib")273
) {
689
0
    if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
690
0
      fatal("lib failed");
691
0
    return;
692
0
  }
693
275
694
275
  // Needed for LTO.
695
275
  InitializeAllTargetInfos();
696
275
  InitializeAllTargets();
697
275
  InitializeAllTargetMCs();
698
275
  InitializeAllAsmParsers();
699
275
  InitializeAllAsmPrinters();
700
275
  InitializeAllDisassemblers();
701
275
702
275
  // Parse command line options.
703
275
  ArgParser Parser;
704
275
  opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
705
275
706
275
  // Parse and evaluate -mllvm options.
707
275
  std::vector<const char *> V;
708
275
  V.push_back("lld-link (LLVM option parsing)");
709
275
  for (auto *Arg : Args.filtered(OPT_mllvm))
710
1
    V.push_back(Arg->getValue());
711
275
  cl::ParseCommandLineOptions(V.size(), V.data());
712
275
713
275
  // Handle /errorlimit early, because error() depends on it.
714
275
  if (auto *
Arg275
= Args.getLastArg(OPT_errorlimit)) {
715
1
    int N = 20;
716
1
    StringRef S = Arg->getValue();
717
1
    if (S.getAsInteger(10, N))
718
1
      error(Arg->getSpelling() + " number expected, but got " + S);
719
1
    Config->ErrorLimit = N;
720
1
  }
721
275
722
275
  // Handle /help
723
275
  if (
Args.hasArg(OPT_help)275
) {
724
3
    printHelp(ArgsArr[0]);
725
3
    return;
726
3
  }
727
272
728
272
  // Handle /lldmingw early, since it can potentially affect how other
729
272
  // options are handled.
730
272
  Config->MinGW = Args.hasArg(OPT_lldmingw);
731
272
732
272
  if (auto *
Arg272
= Args.getLastArg(OPT_linkrepro)) {
733
3
    SmallString<64> Path = StringRef(Arg->getValue());
734
3
    sys::path::append(Path, "repro.tar");
735
3
736
3
    Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
737
3
        TarWriter::create(Path, "repro");
738
3
739
3
    if (
ErrOrWriter3
) {
740
3
      Tar = std::move(*ErrOrWriter);
741
3
    } else {
742
0
      error("/linkrepro: failed to open " + Path + ": " +
743
0
            toString(ErrOrWriter.takeError()));
744
0
    }
745
3
  }
746
272
747
272
  if (
!Args.hasArg(OPT_INPUT)272
) {
748
7
    if (Args.hasArg(OPT_deffile))
749
7
      Config->NoEntry = true;
750
7
    else
751
0
      fatal("no input files");
752
272
  }
753
272
754
272
  // Construct search path list.
755
272
  SearchPaths.push_back("");
756
272
  for (auto *Arg : Args.filtered(OPT_libpath))
757
7
    SearchPaths.push_back(Arg->getValue());
758
272
  addLibSearchPaths();
759
272
760
272
  // Handle /out
761
272
  if (auto *Arg = Args.getLastArg(OPT_out))
762
259
    Config->OutputFile = Arg->getValue();
763
272
764
272
  // Handle /verbose
765
272
  if (Args.hasArg(OPT_verbose))
766
19
    Config->Verbose = true;
767
272
768
272
  // Handle /force or /force:unresolved
769
272
  if (
Args.hasArg(OPT_force) || 272
Args.hasArg(OPT_force_unresolved)266
)
770
6
    Config->Force = true;
771
272
772
272
  // Handle /debug
773
272
  if (
Args.hasArg(OPT_debug)272
) {
774
42
    Config->Debug = true;
775
42
    if (auto *Arg = Args.getLastArg(OPT_debugtype))
776
2
      Config->DebugTypes = parseDebugType(Arg->getValue());
777
42
    else
778
40
      Config->DebugTypes = getDefaultDebugType(Args);
779
42
  }
780
272
781
272
  // Create a dummy PDB file to satisfy build sytem rules.
782
272
  if (auto *Arg = Args.getLastArg(OPT_pdb))
783
26
    Config->PDBPath = Arg->getValue();
784
272
785
272
  // Handle /noentry
786
272
  if (
Args.hasArg(OPT_noentry)272
) {
787
2
    if (Args.hasArg(OPT_dll))
788
2
      Config->NoEntry = true;
789
2
    else
790
0
      error("/noentry must be specified with /dll");
791
2
  }
792
272
793
272
  // Handle /dll
794
272
  if (
Args.hasArg(OPT_dll)272
) {
795
53
    Config->DLL = true;
796
53
    Config->ManifestID = 2;
797
53
  }
798
272
799
272
  // Handle /fixed
800
272
  if (
Args.hasArg(OPT_fixed)272
) {
801
2
    if (
Args.hasArg(OPT_dynamicbase)2
) {
802
0
      error("/fixed must not be specified with /dynamicbase");
803
2
    } else {
804
2
      Config->Relocatable = false;
805
2
      Config->DynamicBase = false;
806
2
    }
807
2
  }
808
272
809
272
  if (Args.hasArg(OPT_appcontainer))
810
1
    Config->AppContainer = true;
811
272
812
272
  // Handle /machine
813
272
  if (auto *Arg = Args.getLastArg(OPT_machine))
814
17
    Config->Machine = getMachineType(Arg->getValue());
815
272
816
272
  // Handle /nodefaultlib:<filename>
817
272
  for (auto *Arg : Args.filtered(OPT_nodefaultlib))
818
0
    Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
819
272
820
272
  // Handle /nodefaultlib
821
272
  if (Args.hasArg(OPT_nodefaultlib_all))
822
22
    Config->NoDefaultLibAll = true;
823
272
824
272
  // Handle /base
825
272
  if (auto *Arg = Args.getLastArg(OPT_base))
826
2
    parseNumbers(Arg->getValue(), &Config->ImageBase);
827
272
828
272
  // Handle /stack
829
272
  if (auto *Arg = Args.getLastArg(OPT_stack))
830
2
    parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
831
272
832
272
  // Handle /heap
833
272
  if (auto *Arg = Args.getLastArg(OPT_heap))
834
3
    parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
835
272
836
272
  // Handle /version
837
272
  if (auto *Arg = Args.getLastArg(OPT_version))
838
2
    parseVersion(Arg->getValue(), &Config->MajorImageVersion,
839
2
                 &Config->MinorImageVersion);
840
272
841
272
  // Handle /subsystem
842
272
  if (auto *Arg = Args.getLastArg(OPT_subsystem))
843
98
    parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
844
98
                   &Config->MinorOSVersion);
845
272
846
272
  // Handle /alternatename
847
272
  for (auto *Arg : Args.filtered(OPT_alternatename))
848
7
    parseAlternateName(Arg->getValue());
849
272
850
272
  // Handle /include
851
272
  for (auto *Arg : Args.filtered(OPT_incl))
852
13
    addUndefined(Arg->getValue());
853
272
854
272
  // Handle /implib
855
272
  if (auto *Arg = Args.getLastArg(OPT_implib))
856
10
    Config->Implib = Arg->getValue();
857
272
858
272
  // Handle /opt
859
12
  for (auto *Arg : Args.filtered(OPT_opt)) {
860
12
    std::string Str = StringRef(Arg->getValue()).lower();
861
12
    SmallVector<StringRef, 1> Vec;
862
12
    StringRef(Str).split(Vec, ',');
863
13
    for (StringRef S : Vec) {
864
13
      if (
S == "noref"13
) {
865
7
        Config->DoGC = false;
866
7
        Config->DoICF = false;
867
7
        continue;
868
7
      }
869
6
      
if (6
S == "icf" || 6
S.startswith("icf=")6
) {
870
0
        Config->DoICF = true;
871
0
        continue;
872
0
      }
873
6
      
if (6
S == "noicf"6
) {
874
2
        Config->DoICF = false;
875
2
        continue;
876
2
      }
877
4
      
if (4
S.startswith("lldlto=")4
) {
878
2
        StringRef OptLevel = S.substr(7);
879
2
        if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
880
2
            Config->LTOOptLevel > 3)
881
0
          error("/opt:lldlto: invalid optimization level: " + OptLevel);
882
2
        continue;
883
2
      }
884
2
      
if (2
S.startswith("lldltojobs=")2
) {
885
0
        StringRef Jobs = S.substr(11);
886
0
        if (
Jobs.getAsInteger(10, Config->LTOJobs) || 0
Config->LTOJobs == 00
)
887
0
          error("/opt:lldltojobs: invalid job count: " + Jobs);
888
0
        continue;
889
0
      }
890
2
      
if (2
S.startswith("lldltopartitions=")2
) {
891
1
        StringRef N = S.substr(17);
892
1
        if (N.getAsInteger(10, Config->LTOPartitions) ||
893
1
            Config->LTOPartitions == 0)
894
0
          error("/opt:lldltopartitions: invalid partition count: " + N);
895
1
        continue;
896
1
      }
897
1
      
if (1
S != "ref" && 1
S != "lbr"0
&&
S != "nolbr"0
)
898
0
        error("/opt: unknown option: " + S);
899
13
    }
900
12
  }
901
272
902
272
  // Handle /lldsavetemps
903
272
  if (Args.hasArg(OPT_lldsavetemps))
904
2
    Config->SaveTemps = true;
905
272
906
272
  // Handle /lldltocache
907
272
  if (auto *Arg = Args.getLastArg(OPT_lldltocache))
908
1
    Config->LTOCache = Arg->getValue();
909
272
910
272
  // Handle /lldsavecachepolicy
911
272
  if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
912
1
    Config->LTOCachePolicy = check(
913
1
        parseCachePruningPolicy(Arg->getValue()),
914
1
        Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
915
272
916
272
  // Handle /failifmismatch
917
272
  for (auto *Arg : Args.filtered(OPT_failifmismatch))
918
4
    checkFailIfMismatch(Arg->getValue());
919
272
920
272
  // Handle /merge
921
272
  for (auto *Arg : Args.filtered(OPT_merge))
922
2
    parseMerge(Arg->getValue());
923
272
924
272
  // Handle /section
925
272
  for (auto *Arg : Args.filtered(OPT_section))
926
4
    parseSection(Arg->getValue());
927
272
928
272
  // Handle /aligncomm
929
272
  for (auto *Arg : Args.filtered(OPT_aligncomm))
930
0
    parseAligncomm(Arg->getValue());
931
272
932
272
  // Handle /manifestdependency. This enables /manifest unless /manifest:no is
933
272
  // also passed.
934
272
  if (auto *
Arg272
= Args.getLastArg(OPT_manifestdependency)) {
935
2
    Config->ManifestDependency = Arg->getValue();
936
2
    Config->Manifest = Configuration::SideBySide;
937
2
  }
938
272
939
272
  // Handle /manifest and /manifest:
940
272
  if (auto *
Arg272
= Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
941
4
    if (Arg->getOption().getID() == OPT_manifest)
942
4
      Config->Manifest = Configuration::SideBySide;
943
4
    else
944
0
      parseManifest(Arg->getValue());
945
4
  }
946
272
947
272
  // Handle /manifestuac
948
272
  if (auto *Arg = Args.getLastArg(OPT_manifestuac))
949
3
    parseManifestUAC(Arg->getValue());
950
272
951
272
  // Handle /manifestfile
952
272
  if (auto *Arg = Args.getLastArg(OPT_manifestfile))
953
0
    Config->ManifestFile = Arg->getValue();
954
272
955
272
  // Handle /manifestinput
956
272
  for (auto *Arg : Args.filtered(OPT_manifestinput))
957
0
    Config->ManifestInput.push_back(Arg->getValue());
958
272
959
272
  if (!Config->ManifestInput.empty() &&
960
272
      
Config->Manifest != Configuration::Embed0
) {
961
0
    fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED");
962
0
  }
963
272
964
272
  // Handle miscellaneous boolean flags.
965
272
  
if (272
Args.hasArg(OPT_allowbind_no)272
)
966
1
    Config->AllowBind = false;
967
272
  if (Args.hasArg(OPT_allowisolation_no))
968
1
    Config->AllowIsolation = false;
969
272
  if (Args.hasArg(OPT_dynamicbase_no))
970
0
    Config->DynamicBase = false;
971
272
  if (Args.hasArg(OPT_nxcompat_no))
972
1
    Config->NxCompat = false;
973
272
  if (Args.hasArg(OPT_tsaware_no))
974
1
    Config->TerminalServerAware = false;
975
272
  if (Args.hasArg(OPT_nosymtab))
976
1
    Config->WriteSymtab = false;
977
272
978
272
  Config->MapFile = getMapFile(Args);
979
272
980
272
  if (ErrorCount)
981
2
    return;
982
270
983
270
  bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag);
984
270
  // Create a list of input files. Files can be given as arguments
985
270
  // for /defaultlib option.
986
270
  std::vector<MemoryBufferRef> MBs;
987
360
  for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) {
988
360
    switch (Arg->getOption().getID()) {
989
359
    case OPT_INPUT:
990
359
      if (Optional<StringRef> Path = findFile(Arg->getValue()))
991
357
        enqueuePath(*Path, WholeArchiveFlag);
992
359
      break;
993
1
    case OPT_wholearchive_file:
994
1
      if (Optional<StringRef> Path = findFile(Arg->getValue()))
995
1
        enqueuePath(*Path, true);
996
1
      break;
997
270
    }
998
270
  }
999
270
  for (auto *Arg : Args.filtered(OPT_defaultlib))
1000
6
    
if (Optional<StringRef> 6
Path6
= findLib(Arg->getValue()))
1001
6
      enqueuePath(*Path, false);
1002
270
1003
270
  // Windows specific -- Create a resource file containing a manifest file.
1004
270
  if (Config->Manifest == Configuration::Embed)
1005
0
    addBuffer(createManifestRes(), false);
1006
270
1007
270
  // Read all input files given via the command line.
1008
270
  run();
1009
270
1010
270
  // We should have inferred a machine type by now from the input files, but if
1011
270
  // not we assume x64.
1012
270
  if (
Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN270
) {
1013
5
    warn("/machine is not specified. x64 is assumed");
1014
5
    Config->Machine = AMD64;
1015
5
  }
1016
270
1017
270
  // Input files can be Windows resource files (.res files). We use
1018
270
  // WindowsResource to convert resource files to a regular COFF file,
1019
270
  // then link the resulting file normally.
1020
270
  if (!Resources.empty())
1021
2
    addBuffer(convertResToCOFF(Resources), false);
1022
270
1023
270
  if (Tar)
1024
3
    Tar->append("response.txt",
1025
3
                createResponseFile(Args, FilePaths,
1026
3
                                   ArrayRef<StringRef>(SearchPaths).slice(1)));
1027
270
1028
270
  // Handle /largeaddressaware
1029
270
  if (
Config->is64() || 270
Args.hasArg(OPT_largeaddressaware)49
)
1030
222
    Config->LargeAddressAware = true;
1031
270
1032
270
  // Handle /highentropyva
1033
270
  if (
Config->is64() && 270
!Args.hasArg(OPT_highentropyva_no)221
)
1034
220
    Config->HighEntropyVA = true;
1035
270
1036
270
  // Handle /entry and /dll
1037
270
  if (auto *
Arg270
= Args.getLastArg(OPT_entry)) {
1038
232
    Config->Entry = addUndefined(mangle(Arg->getValue()));
1039
270
  } else 
if (38
Args.hasArg(OPT_dll) && 38
!Config->NoEntry30
) {
1040
8
    StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1041
20
                                            : "_DllMainCRTStartup";
1042
28
    Config->Entry = addUndefined(S);
1043
38
  } else 
if (10
!Config->NoEntry10
) {
1044
4
    // Windows specific -- If entry point name is not given, we need to
1045
4
    // infer that from user-defined entry name.
1046
4
    StringRef S = findDefaultEntry();
1047
4
    if (S.empty())
1048
0
      fatal("entry point must be defined");
1049
4
    Config->Entry = addUndefined(S);
1050
4
    log("Entry name inferred: " + S);
1051
4
  }
1052
270
1053
270
  // Handle /export
1054
270
  
for (auto *Arg : Args.filtered(OPT_export)) 270
{
1055
44
    Export E = parseExport(Arg->getValue());
1056
44
    if (
Config->Machine == I38644
) {
1057
14
      if (!isDecorated(E.Name))
1058
14
        E.Name = Saver.save("_" + E.Name);
1059
14
      if (
!E.ExtName.empty() && 14
!isDecorated(E.ExtName)3
)
1060
3
        E.ExtName = Saver.save("_" + E.ExtName);
1061
14
    }
1062
44
    Config->Exports.push_back(E);
1063
44
  }
1064
270
1065
270
  // Handle /def
1066
270
  if (auto *
Arg270
= Args.getLastArg(OPT_deffile)) {
1067
21
    // parseModuleDefs mutates Config object.
1068
21
    parseModuleDefs(Arg->getValue());
1069
21
  }
1070
270
1071
270
  // Handle generation of import library from a def file.
1072
270
  if (
!Args.hasArg(OPT_INPUT)270
) {
1073
7
    fixupExports();
1074
7
    createImportLibrary(/*AsLib=*/true);
1075
7
    exit(0);
1076
7
  }
1077
263
1078
263
  // Handle /delayload
1079
263
  
for (auto *Arg : Args.filtered(OPT_delayload)) 263
{
1080
3
    Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1081
3
    if (
Config->Machine == I3863
) {
1082
1
      Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1083
3
    } else {
1084
2
      Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1085
2
    }
1086
3
  }
1087
263
1088
263
  // Set default image name if neither /out or /def set it.
1089
263
  if (
Config->OutputFile.empty()263
) {
1090
10
    Config->OutputFile =
1091
10
        getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1092
10
  }
1093
263
1094
263
  // Put the PDB next to the image if no /pdb flag was passed.
1095
263
  if (
Config->Debug && 263
Config->PDBPath.empty()42
) {
1096
17
    Config->PDBPath = Config->OutputFile;
1097
17
    sys::path::replace_extension(Config->PDBPath, ".pdb");
1098
17
  }
1099
263
1100
263
  // Disable PDB generation if the user requested it.
1101
263
  if (Args.hasArg(OPT_nopdb))
1102
2
    Config->PDBPath = "";
1103
263
1104
263
  // Set default image base if /base is not given.
1105
263
  if (Config->ImageBase == uint64_t(-1))
1106
261
    Config->ImageBase = getDefaultImageBase();
1107
263
1108
263
  Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1109
263
  if (
Config->Machine == I386263
) {
1110
40
    Symtab->addAbsolute("___safe_se_handler_table", 0);
1111
40
    Symtab->addAbsolute("___safe_se_handler_count", 0);
1112
40
  }
1113
263
1114
263
  // We do not support /guard:cf (control flow protection) yet.
1115
263
  // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
1116
263
  Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1117
263
  Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1118
263
  Symtab->addAbsolute(mangle("__guard_flags"), 0x100);
1119
263
  Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1120
263
  Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1121
263
  Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1122
263
  Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1123
263
1124
263
  // This code may add new undefined symbols to the link, which may enqueue more
1125
263
  // symbol resolution tasks, so we need to continue executing tasks until we
1126
263
  // converge.
1127
267
  do {
1128
267
    // Windows specific -- if entry point is not found,
1129
267
    // search for its mangled names.
1130
267
    if (Config->Entry)
1131
265
      Symtab->mangleMaybe(Config->Entry);
1132
267
1133
267
    // Windows specific -- Make sure we resolve all dllexported symbols.
1134
91
    for (Export &E : Config->Exports) {
1135
91
      if (!E.ForwardTo.empty())
1136
1
        continue;
1137
90
      E.Sym = addUndefined(E.Name);
1138
90
      if (!E.Directives)
1139
52
        Symtab->mangleMaybe(E.Sym);
1140
91
    }
1141
267
1142
267
    // Add weak aliases. Weak aliases is a mechanism to give remaining
1143
267
    // undefined symbols final chance to be resolved successfully.
1144
7
    for (auto Pair : Config->AlternateNames) {
1145
7
      StringRef From = Pair.first;
1146
7
      StringRef To = Pair.second;
1147
7
      Symbol *Sym = Symtab->find(From);
1148
7
      if (!Sym)
1149
1
        continue;
1150
6
      
if (auto *6
U6
= dyn_cast<Undefined>(Sym->body()))
1151
6
        
if (6
!U->WeakAlias6
)
1152
6
          U->WeakAlias = Symtab->addUndefined(To);
1153
7
    }
1154
267
1155
267
    // Windows specific -- if __load_config_used can be resolved, resolve it.
1156
267
    if (Symtab->findUnderscore("_load_config_used"))
1157
5
      addUndefined(mangle("_load_config_used"));
1158
267
  } while (run());
1159
263
1160
263
  if (ErrorCount)
1161
5
    return;
1162
258
1163
258
  // If /msvclto is given, we use the MSVC linker to link LTO output files.
1164
258
  // This is useful because MSVC link.exe can generate complete PDBs.
1165
258
  
if (258
Args.hasArg(OPT_msvclto)258
) {
1166
0
    invokeMSVC(Args);
1167
0
    exit(0);
1168
0
  }
1169
258
1170
258
  // Do LTO by compiling bitcode input files to a set of native COFF files then
1171
258
  // link those files.
1172
258
  Symtab->addCombinedLTOObjects();
1173
258
  run();
1174
258
1175
258
  // Make sure we have resolved all symbols.
1176
258
  Symtab->reportRemainingUndefines();
1177
258
1178
258
  // Windows specific -- if no /subsystem is given, we need to infer
1179
258
  // that from entry point name.
1180
258
  if (
Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN258
) {
1181
166
    Config->Subsystem = inferSubsystem();
1182
166
    if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1183
0
      fatal("subsystem must be defined");
1184
258
  }
1185
258
1186
258
  // Handle /safeseh.
1187
258
  
if (258
Args.hasArg(OPT_safeseh)258
) {
1188
4
    for (ObjFile *File : ObjFile::Instances)
1189
4
      
if (4
!File->SEHCompat4
)
1190
1
        error("/safeseh: " + File->getName() + " is not compatible with SEH");
1191
4
    if (ErrorCount)
1192
1
      return;
1193
257
  }
1194
257
1195
257
  // Windows specific -- when we are creating a .dll file, we also
1196
257
  // need to create a .lib file.
1197
257
  
if (257
!Config->Exports.empty() || 257
Config->DLL218
) {
1198
54
    fixupExports();
1199
54
    createImportLibrary(/*AsLib=*/false);
1200
54
    assignExportOrdinals();
1201
54
  }
1202
257
1203
257
  // Set extra alignment for .comm symbols
1204
1
  for (auto Pair : Config->AlignComm) {
1205
1
    StringRef Name = Pair.first;
1206
1
    uint32_t Alignment = Pair.second;
1207
1
1208
1
    Symbol *Sym = Symtab->find(Name);
1209
1
    if (
!Sym1
) {
1210
0
      warn("/aligncomm symbol " + Name + " not found");
1211
0
      continue;
1212
0
    }
1213
1
1214
1
    auto *DC = dyn_cast<DefinedCommon>(Sym->body());
1215
1
    if (
!DC1
) {
1216
0
      warn("/aligncomm symbol " + Name + " of wrong kind");
1217
0
      continue;
1218
0
    }
1219
1
1220
1
    CommonChunk *C = DC->getChunk();
1221
1
    C->Alignment = std::max(C->Alignment, Alignment);
1222
1
  }
1223
257
1224
257
  // Windows specific -- Create a side-by-side manifest file.
1225
257
  if (Config->Manifest == Configuration::SideBySide)
1226
5
    createSideBySideManifest();
1227
257
1228
257
  // Identify unreferenced COMDAT sections.
1229
257
  if (Config->DoGC)
1230
250
    markLive(Symtab->getChunks());
1231
257
1232
257
  // Identify identical COMDAT sections to merge them.
1233
257
  if (Config->DoICF)
1234
249
    doICF(Symtab->getChunks());
1235
257
1236
257
  // Write the result.
1237
257
  writeResult();
1238
257
1239
257
  if (ErrorCount)
1240
1
    return;
1241
256
1242
256
  // Call exit to avoid calling destructors.
1243
256
  exit(0);
1244
256
}
1245
1246
} // namespace coff
1247
} // namespace lld