Coverage Report

Created: 2017-10-03 07:32

/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
  auto E = writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports,
503
61
                              Config->Machine, false);
504
61
  handleAllErrors(std::move(E),
505
0
                  [&](ErrorInfoBase &EIB) { error(EIB.message()); });
506
61
}
507
508
21
static void parseModuleDefs(StringRef Path) {
509
21
  std::unique_ptr<MemoryBuffer> MB = check(
510
21
    MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
511
21
  COFFModuleDefinition M =
512
21
      check(parseCOFFModuleDefinition(MB->getMemBufferRef(), Config->Machine));
513
21
514
21
  if (Config->OutputFile.empty())
515
2
    Config->OutputFile = Saver.save(M.OutputFile);
516
21
  Config->ImportName = Saver.save(M.ImportName);
517
21
  if (M.ImageBase)
518
0
    Config->ImageBase = M.ImageBase;
519
21
  if (M.StackReserve)
520
2
    Config->StackReserve = M.StackReserve;
521
21
  if (M.StackCommit)
522
1
    Config->StackCommit = M.StackCommit;
523
21
  if (M.HeapReserve)
524
2
    Config->HeapReserve = M.HeapReserve;
525
21
  if (M.HeapCommit)
526
1
    Config->HeapCommit = M.HeapCommit;
527
21
  if (M.MajorImageVersion)
528
0
    Config->MajorImageVersion = M.MajorImageVersion;
529
21
  if (M.MinorImageVersion)
530
0
    Config->MinorImageVersion = M.MinorImageVersion;
531
21
  if (M.MajorOSVersion)
532
0
    Config->MajorOSVersion = M.MajorOSVersion;
533
21
  if (M.MinorOSVersion)
534
0
    Config->MinorOSVersion = M.MinorOSVersion;
535
21
536
17
  for (COFFShortExport E1 : M.Exports) {
537
17
    Export E2;
538
17
    E2.Name = Saver.save(E1.Name);
539
17
    if (E1.isWeak())
540
2
      E2.ExtName = Saver.save(E1.ExtName);
541
17
    E2.Ordinal = E1.Ordinal;
542
17
    E2.Noname = E1.Noname;
543
17
    E2.Data = E1.Data;
544
17
    E2.Private = E1.Private;
545
17
    E2.Constant = E1.Constant;
546
17
    Config->Exports.push_back(E2);
547
17
  }
548
21
}
549
550
// A helper function for filterBitcodeFiles.
551
0
static bool needsRebuilding(MemoryBufferRef MB) {
552
0
  // The MSVC linker doesn't support thin archives, so if it's a thin
553
0
  // archive, we always need to rebuild it.
554
0
  std::unique_ptr<Archive> File =
555
0
      check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
556
0
  if (File->isThin())
557
0
    return true;
558
0
559
0
  // Returns true if the archive contains at least one bitcode file.
560
0
  for (MemoryBufferRef Member : getArchiveMembers(File.get()))
561
0
    
if (0
identify_magic(Member.getBuffer()) == file_magic::bitcode0
)
562
0
      return true;
563
0
  return false;
564
0
}
565
566
// Opens a given path as an archive file and removes bitcode files
567
// from them if exists. This function is to appease the MSVC linker as
568
// their linker doesn't like archive files containing non-native
569
// object files.
570
//
571
// If a given archive doesn't contain bitcode files, the archive path
572
// is returned as-is. Otherwise, a new temporary file is created and
573
// its path is returned.
574
static Optional<std::string>
575
0
filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
576
0
  std::unique_ptr<MemoryBuffer> MB = check(
577
0
      MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
578
0
  MemoryBufferRef MBRef = MB->getMemBufferRef();
579
0
  file_magic Magic = identify_magic(MBRef.getBuffer());
580
0
581
0
  if (Magic == file_magic::bitcode)
582
0
    return None;
583
0
  
if (0
Magic != file_magic::archive0
)
584
0
    return Path.str();
585
0
  
if (0
!needsRebuilding(MBRef)0
)
586
0
    return Path.str();
587
0
588
0
  std::unique_ptr<Archive> File =
589
0
      check(Archive::create(MBRef),
590
0
            MBRef.getBufferIdentifier() + ": failed to parse archive");
591
0
592
0
  std::vector<NewArchiveMember> New;
593
0
  for (MemoryBufferRef Member : getArchiveMembers(File.get()))
594
0
    
if (0
identify_magic(Member.getBuffer()) != file_magic::bitcode0
)
595
0
      New.emplace_back(Member);
596
0
597
0
  if (New.empty())
598
0
    return None;
599
0
600
0
  log("Creating a temporary archive for " + Path + " to remove bitcode files");
601
0
602
0
  SmallString<128> S;
603
0
  if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
604
0
                                             ".lib", S))
605
0
    fatal(EC, "cannot create a temporary file");
606
0
  std::string Temp = S.str();
607
0
  TemporaryFiles.push_back(Temp);
608
0
609
0
  Error E =
610
0
      llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
611
0
                         /*Deterministics=*/true,
612
0
                         /*Thin=*/false);
613
0
  handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
614
0
    error("failed to create a new archive " + S.str() + ": " + EI.message());
615
0
  });
616
0
  return Temp;
617
0
}
618
619
// Create response file contents and invoke the MSVC linker.
620
0
void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
621
0
  std::string Rsp = "/nologo\n";
622
0
  std::vector<std::string> Temps;
623
0
624
0
  // Write out archive members that we used in symbol resolution and pass these
625
0
  // to MSVC before any archives, so that MSVC uses the same objects to satisfy
626
0
  // references.
627
0
  for (ObjFile *Obj : ObjFile::Instances) {
628
0
    if (Obj->ParentName.empty())
629
0
      continue;
630
0
    SmallString<128> S;
631
0
    int Fd;
632
0
    if (auto EC = sys::fs::createTemporaryFile(
633
0
            "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
634
0
      fatal(EC, "cannot create a temporary file");
635
0
    raw_fd_ostream OS(Fd, /*shouldClose*/ true);
636
0
    OS << Obj->MB.getBuffer();
637
0
    Temps.push_back(S.str());
638
0
    Rsp += quote(S) + "\n";
639
0
  }
640
0
641
0
  
for (auto *Arg : Args) 0
{
642
0
    switch (Arg->getOption().getID()) {
643
0
    case OPT_linkrepro:
644
0
    case OPT_lldmap:
645
0
    case OPT_lldmap_file:
646
0
    case OPT_lldsavetemps:
647
0
    case OPT_msvclto:
648
0
      // LLD-specific options are stripped.
649
0
      break;
650
0
    case OPT_opt:
651
0
      if (!StringRef(Arg->getValue()).startswith("lld"))
652
0
        Rsp += toString(Arg) + " ";
653
0
      break;
654
0
    case OPT_INPUT: {
655
0
      if (Optional<StringRef> 
Path0
= doFindFile(Arg->getValue())) {
656
0
        if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
657
0
          Rsp += quote(*S) + "\n";
658
0
        continue;
659
0
      }
660
0
      Rsp += quote(Arg->getValue()) + "\n";
661
0
      break;
662
0
    }
663
0
    default:
664
0
      Rsp += toString(Arg) + "\n";
665
0
    }
666
0
  }
667
0
668
0
  std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
669
0
  runMSVCLinker(Rsp, ObjFiles);
670
0
671
0
  for (StringRef Path : Temps)
672
0
    sys::fs::remove(Path);
673
0
}
674
675
452
void LinkerDriver::enqueueTask(std::function<void()> Task) {
676
452
  TaskQueue.push_back(std::move(Task));
677
452
}
678
679
795
bool LinkerDriver::run() {
680
795
  bool DidWork = !TaskQueue.empty();
681
1.24k
  while (
!TaskQueue.empty()1.24k
) {
682
452
    TaskQueue.front()();
683
452
    TaskQueue.pop_front();
684
452
  }
685
795
  return DidWork;
686
795
}
687
688
275
void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
689
275
  // If the first command line argument is "/lib", link.exe acts like lib.exe.
690
275
  // We call our own implementation of lib.exe that understands bitcode files.
691
275
  if (
ArgsArr.size() > 1 && 275
StringRef(ArgsArr[1]).equals_lower("/lib")273
) {
692
0
    if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
693
0
      fatal("lib failed");
694
0
    return;
695
0
  }
696
275
697
275
  // Needed for LTO.
698
275
  InitializeAllTargetInfos();
699
275
  InitializeAllTargets();
700
275
  InitializeAllTargetMCs();
701
275
  InitializeAllAsmParsers();
702
275
  InitializeAllAsmPrinters();
703
275
  InitializeAllDisassemblers();
704
275
705
275
  // Parse command line options.
706
275
  ArgParser Parser;
707
275
  opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
708
275
709
275
  // Parse and evaluate -mllvm options.
710
275
  std::vector<const char *> V;
711
275
  V.push_back("lld-link (LLVM option parsing)");
712
275
  for (auto *Arg : Args.filtered(OPT_mllvm))
713
1
    V.push_back(Arg->getValue());
714
275
  cl::ParseCommandLineOptions(V.size(), V.data());
715
275
716
275
  // Handle /errorlimit early, because error() depends on it.
717
275
  if (auto *
Arg275
= Args.getLastArg(OPT_errorlimit)) {
718
1
    int N = 20;
719
1
    StringRef S = Arg->getValue();
720
1
    if (S.getAsInteger(10, N))
721
1
      error(Arg->getSpelling() + " number expected, but got " + S);
722
1
    Config->ErrorLimit = N;
723
1
  }
724
275
725
275
  // Handle /help
726
275
  if (
Args.hasArg(OPT_help)275
) {
727
3
    printHelp(ArgsArr[0]);
728
3
    return;
729
3
  }
730
272
731
272
  // Handle /lldmingw early, since it can potentially affect how other
732
272
  // options are handled.
733
272
  Config->MinGW = Args.hasArg(OPT_lldmingw);
734
272
735
272
  if (auto *
Arg272
= Args.getLastArg(OPT_linkrepro)) {
736
3
    SmallString<64> Path = StringRef(Arg->getValue());
737
3
    sys::path::append(Path, "repro.tar");
738
3
739
3
    Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
740
3
        TarWriter::create(Path, "repro");
741
3
742
3
    if (
ErrOrWriter3
) {
743
3
      Tar = std::move(*ErrOrWriter);
744
3
    } else {
745
0
      error("/linkrepro: failed to open " + Path + ": " +
746
0
            toString(ErrOrWriter.takeError()));
747
0
    }
748
3
  }
749
272
750
272
  if (
!Args.hasArg(OPT_INPUT)272
) {
751
7
    if (Args.hasArg(OPT_deffile))
752
7
      Config->NoEntry = true;
753
7
    else
754
0
      fatal("no input files");
755
272
  }
756
272
757
272
  // Construct search path list.
758
272
  SearchPaths.push_back("");
759
272
  for (auto *Arg : Args.filtered(OPT_libpath))
760
7
    SearchPaths.push_back(Arg->getValue());
761
272
  addLibSearchPaths();
762
272
763
272
  // Handle /out
764
272
  if (auto *Arg = Args.getLastArg(OPT_out))
765
259
    Config->OutputFile = Arg->getValue();
766
272
767
272
  // Handle /verbose
768
272
  if (Args.hasArg(OPT_verbose))
769
19
    Config->Verbose = true;
770
272
771
272
  // Handle /force or /force:unresolved
772
272
  if (
Args.hasArg(OPT_force) || 272
Args.hasArg(OPT_force_unresolved)266
)
773
6
    Config->Force = true;
774
272
775
272
  // Handle /debug
776
272
  if (
Args.hasArg(OPT_debug)272
) {
777
42
    Config->Debug = true;
778
42
    if (auto *Arg = Args.getLastArg(OPT_debugtype))
779
2
      Config->DebugTypes = parseDebugType(Arg->getValue());
780
42
    else
781
40
      Config->DebugTypes = getDefaultDebugType(Args);
782
42
  }
783
272
784
272
  // Create a dummy PDB file to satisfy build sytem rules.
785
272
  if (auto *Arg = Args.getLastArg(OPT_pdb))
786
26
    Config->PDBPath = Arg->getValue();
787
272
788
272
  // Handle /noentry
789
272
  if (
Args.hasArg(OPT_noentry)272
) {
790
2
    if (Args.hasArg(OPT_dll))
791
2
      Config->NoEntry = true;
792
2
    else
793
0
      error("/noentry must be specified with /dll");
794
2
  }
795
272
796
272
  // Handle /dll
797
272
  if (
Args.hasArg(OPT_dll)272
) {
798
53
    Config->DLL = true;
799
53
    Config->ManifestID = 2;
800
53
  }
801
272
802
272
  // Handle /fixed
803
272
  if (
Args.hasArg(OPT_fixed)272
) {
804
2
    if (
Args.hasArg(OPT_dynamicbase)2
) {
805
0
      error("/fixed must not be specified with /dynamicbase");
806
2
    } else {
807
2
      Config->Relocatable = false;
808
2
      Config->DynamicBase = false;
809
2
    }
810
2
  }
811
272
812
272
  if (Args.hasArg(OPT_appcontainer))
813
1
    Config->AppContainer = true;
814
272
815
272
  // Handle /machine
816
272
  if (auto *Arg = Args.getLastArg(OPT_machine))
817
17
    Config->Machine = getMachineType(Arg->getValue());
818
272
819
272
  // Handle /nodefaultlib:<filename>
820
272
  for (auto *Arg : Args.filtered(OPT_nodefaultlib))
821
0
    Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
822
272
823
272
  // Handle /nodefaultlib
824
272
  if (Args.hasArg(OPT_nodefaultlib_all))
825
22
    Config->NoDefaultLibAll = true;
826
272
827
272
  // Handle /base
828
272
  if (auto *Arg = Args.getLastArg(OPT_base))
829
2
    parseNumbers(Arg->getValue(), &Config->ImageBase);
830
272
831
272
  // Handle /stack
832
272
  if (auto *Arg = Args.getLastArg(OPT_stack))
833
2
    parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
834
272
835
272
  // Handle /heap
836
272
  if (auto *Arg = Args.getLastArg(OPT_heap))
837
3
    parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
838
272
839
272
  // Handle /version
840
272
  if (auto *Arg = Args.getLastArg(OPT_version))
841
2
    parseVersion(Arg->getValue(), &Config->MajorImageVersion,
842
2
                 &Config->MinorImageVersion);
843
272
844
272
  // Handle /subsystem
845
272
  if (auto *Arg = Args.getLastArg(OPT_subsystem))
846
98
    parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
847
98
                   &Config->MinorOSVersion);
848
272
849
272
  // Handle /alternatename
850
272
  for (auto *Arg : Args.filtered(OPT_alternatename))
851
7
    parseAlternateName(Arg->getValue());
852
272
853
272
  // Handle /include
854
272
  for (auto *Arg : Args.filtered(OPT_incl))
855
13
    addUndefined(Arg->getValue());
856
272
857
272
  // Handle /implib
858
272
  if (auto *Arg = Args.getLastArg(OPT_implib))
859
10
    Config->Implib = Arg->getValue();
860
272
861
272
  // Handle /opt
862
12
  for (auto *Arg : Args.filtered(OPT_opt)) {
863
12
    std::string Str = StringRef(Arg->getValue()).lower();
864
12
    SmallVector<StringRef, 1> Vec;
865
12
    StringRef(Str).split(Vec, ',');
866
13
    for (StringRef S : Vec) {
867
13
      if (
S == "noref"13
) {
868
7
        Config->DoGC = false;
869
7
        Config->DoICF = false;
870
7
        continue;
871
7
      }
872
6
      
if (6
S == "icf" || 6
S.startswith("icf=")6
) {
873
0
        Config->DoICF = true;
874
0
        continue;
875
0
      }
876
6
      
if (6
S == "noicf"6
) {
877
2
        Config->DoICF = false;
878
2
        continue;
879
2
      }
880
4
      
if (4
S.startswith("lldlto=")4
) {
881
2
        StringRef OptLevel = S.substr(7);
882
2
        if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
883
2
            Config->LTOOptLevel > 3)
884
0
          error("/opt:lldlto: invalid optimization level: " + OptLevel);
885
2
        continue;
886
2
      }
887
2
      
if (2
S.startswith("lldltojobs=")2
) {
888
0
        StringRef Jobs = S.substr(11);
889
0
        if (
Jobs.getAsInteger(10, Config->LTOJobs) || 0
Config->LTOJobs == 00
)
890
0
          error("/opt:lldltojobs: invalid job count: " + Jobs);
891
0
        continue;
892
0
      }
893
2
      
if (2
S.startswith("lldltopartitions=")2
) {
894
1
        StringRef N = S.substr(17);
895
1
        if (N.getAsInteger(10, Config->LTOPartitions) ||
896
1
            Config->LTOPartitions == 0)
897
0
          error("/opt:lldltopartitions: invalid partition count: " + N);
898
1
        continue;
899
1
      }
900
1
      
if (1
S != "ref" && 1
S != "lbr"0
&&
S != "nolbr"0
)
901
0
        error("/opt: unknown option: " + S);
902
13
    }
903
12
  }
904
272
905
272
  // Handle /lldsavetemps
906
272
  if (Args.hasArg(OPT_lldsavetemps))
907
2
    Config->SaveTemps = true;
908
272
909
272
  // Handle /lldltocache
910
272
  if (auto *Arg = Args.getLastArg(OPT_lldltocache))
911
1
    Config->LTOCache = Arg->getValue();
912
272
913
272
  // Handle /lldsavecachepolicy
914
272
  if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
915
1
    Config->LTOCachePolicy = check(
916
1
        parseCachePruningPolicy(Arg->getValue()),
917
1
        Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
918
272
919
272
  // Handle /failifmismatch
920
272
  for (auto *Arg : Args.filtered(OPT_failifmismatch))
921
4
    checkFailIfMismatch(Arg->getValue());
922
272
923
272
  // Handle /merge
924
272
  for (auto *Arg : Args.filtered(OPT_merge))
925
2
    parseMerge(Arg->getValue());
926
272
927
272
  // Handle /section
928
272
  for (auto *Arg : Args.filtered(OPT_section))
929
4
    parseSection(Arg->getValue());
930
272
931
272
  // Handle /aligncomm
932
272
  for (auto *Arg : Args.filtered(OPT_aligncomm))
933
0
    parseAligncomm(Arg->getValue());
934
272
935
272
  // Handle /manifestdependency. This enables /manifest unless /manifest:no is
936
272
  // also passed.
937
272
  if (auto *
Arg272
= Args.getLastArg(OPT_manifestdependency)) {
938
2
    Config->ManifestDependency = Arg->getValue();
939
2
    Config->Manifest = Configuration::SideBySide;
940
2
  }
941
272
942
272
  // Handle /manifest and /manifest:
943
272
  if (auto *
Arg272
= Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
944
4
    if (Arg->getOption().getID() == OPT_manifest)
945
4
      Config->Manifest = Configuration::SideBySide;
946
4
    else
947
0
      parseManifest(Arg->getValue());
948
4
  }
949
272
950
272
  // Handle /manifestuac
951
272
  if (auto *Arg = Args.getLastArg(OPT_manifestuac))
952
3
    parseManifestUAC(Arg->getValue());
953
272
954
272
  // Handle /manifestfile
955
272
  if (auto *Arg = Args.getLastArg(OPT_manifestfile))
956
0
    Config->ManifestFile = Arg->getValue();
957
272
958
272
  // Handle /manifestinput
959
272
  for (auto *Arg : Args.filtered(OPT_manifestinput))
960
0
    Config->ManifestInput.push_back(Arg->getValue());
961
272
962
272
  if (!Config->ManifestInput.empty() &&
963
272
      
Config->Manifest != Configuration::Embed0
) {
964
0
    fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED");
965
0
  }
966
272
967
272
  // Handle miscellaneous boolean flags.
968
272
  
if (272
Args.hasArg(OPT_allowbind_no)272
)
969
1
    Config->AllowBind = false;
970
272
  if (Args.hasArg(OPT_allowisolation_no))
971
1
    Config->AllowIsolation = false;
972
272
  if (Args.hasArg(OPT_dynamicbase_no))
973
0
    Config->DynamicBase = false;
974
272
  if (Args.hasArg(OPT_nxcompat_no))
975
1
    Config->NxCompat = false;
976
272
  if (Args.hasArg(OPT_tsaware_no))
977
1
    Config->TerminalServerAware = false;
978
272
  if (Args.hasArg(OPT_nosymtab))
979
1
    Config->WriteSymtab = false;
980
272
981
272
  Config->MapFile = getMapFile(Args);
982
272
983
272
  if (ErrorCount)
984
2
    return;
985
270
986
270
  bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag);
987
270
  // Create a list of input files. Files can be given as arguments
988
270
  // for /defaultlib option.
989
270
  std::vector<MemoryBufferRef> MBs;
990
360
  for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) {
991
360
    switch (Arg->getOption().getID()) {
992
359
    case OPT_INPUT:
993
359
      if (Optional<StringRef> Path = findFile(Arg->getValue()))
994
357
        enqueuePath(*Path, WholeArchiveFlag);
995
359
      break;
996
1
    case OPT_wholearchive_file:
997
1
      if (Optional<StringRef> Path = findFile(Arg->getValue()))
998
1
        enqueuePath(*Path, true);
999
1
      break;
1000
270
    }
1001
270
  }
1002
270
  for (auto *Arg : Args.filtered(OPT_defaultlib))
1003
6
    
if (Optional<StringRef> 6
Path6
= findLib(Arg->getValue()))
1004
6
      enqueuePath(*Path, false);
1005
270
1006
270
  // Windows specific -- Create a resource file containing a manifest file.
1007
270
  if (Config->Manifest == Configuration::Embed)
1008
0
    addBuffer(createManifestRes(), false);
1009
270
1010
270
  // Read all input files given via the command line.
1011
270
  run();
1012
270
1013
270
  // We should have inferred a machine type by now from the input files, but if
1014
270
  // not we assume x64.
1015
270
  if (
Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN270
) {
1016
5
    warn("/machine is not specified. x64 is assumed");
1017
5
    Config->Machine = AMD64;
1018
5
  }
1019
270
1020
270
  // Input files can be Windows resource files (.res files). We use
1021
270
  // WindowsResource to convert resource files to a regular COFF file,
1022
270
  // then link the resulting file normally.
1023
270
  if (!Resources.empty())
1024
2
    addBuffer(convertResToCOFF(Resources), false);
1025
270
1026
270
  if (Tar)
1027
3
    Tar->append("response.txt",
1028
3
                createResponseFile(Args, FilePaths,
1029
3
                                   ArrayRef<StringRef>(SearchPaths).slice(1)));
1030
270
1031
270
  // Handle /largeaddressaware
1032
270
  if (
Config->is64() || 270
Args.hasArg(OPT_largeaddressaware)49
)
1033
222
    Config->LargeAddressAware = true;
1034
270
1035
270
  // Handle /highentropyva
1036
270
  if (
Config->is64() && 270
!Args.hasArg(OPT_highentropyva_no)221
)
1037
220
    Config->HighEntropyVA = true;
1038
270
1039
270
  // Handle /entry and /dll
1040
270
  if (auto *
Arg270
= Args.getLastArg(OPT_entry)) {
1041
232
    Config->Entry = addUndefined(mangle(Arg->getValue()));
1042
270
  } else 
if (38
Args.hasArg(OPT_dll) && 38
!Config->NoEntry30
) {
1043
8
    StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1044
20
                                            : "_DllMainCRTStartup";
1045
28
    Config->Entry = addUndefined(S);
1046
38
  } else 
if (10
!Config->NoEntry10
) {
1047
4
    // Windows specific -- If entry point name is not given, we need to
1048
4
    // infer that from user-defined entry name.
1049
4
    StringRef S = findDefaultEntry();
1050
4
    if (S.empty())
1051
0
      fatal("entry point must be defined");
1052
4
    Config->Entry = addUndefined(S);
1053
4
    log("Entry name inferred: " + S);
1054
4
  }
1055
270
1056
270
  // Handle /export
1057
270
  
for (auto *Arg : Args.filtered(OPT_export)) 270
{
1058
44
    Export E = parseExport(Arg->getValue());
1059
44
    if (
Config->Machine == I38644
) {
1060
14
      if (!isDecorated(E.Name))
1061
14
        E.Name = Saver.save("_" + E.Name);
1062
14
      if (
!E.ExtName.empty() && 14
!isDecorated(E.ExtName)3
)
1063
3
        E.ExtName = Saver.save("_" + E.ExtName);
1064
14
    }
1065
44
    Config->Exports.push_back(E);
1066
44
  }
1067
270
1068
270
  // Handle /def
1069
270
  if (auto *
Arg270
= Args.getLastArg(OPT_deffile)) {
1070
21
    // parseModuleDefs mutates Config object.
1071
21
    parseModuleDefs(Arg->getValue());
1072
21
  }
1073
270
1074
270
  // Handle generation of import library from a def file.
1075
270
  if (
!Args.hasArg(OPT_INPUT)270
) {
1076
7
    fixupExports();
1077
7
    createImportLibrary(/*AsLib=*/true);
1078
7
    exit(0);
1079
7
  }
1080
263
1081
263
  // Handle /delayload
1082
263
  
for (auto *Arg : Args.filtered(OPT_delayload)) 263
{
1083
3
    Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1084
3
    if (
Config->Machine == I3863
) {
1085
1
      Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1086
3
    } else {
1087
2
      Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1088
2
    }
1089
3
  }
1090
263
1091
263
  // Set default image name if neither /out or /def set it.
1092
263
  if (
Config->OutputFile.empty()263
) {
1093
10
    Config->OutputFile =
1094
10
        getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1095
10
  }
1096
263
1097
263
  // Put the PDB next to the image if no /pdb flag was passed.
1098
263
  if (
Config->Debug && 263
Config->PDBPath.empty()42
) {
1099
17
    Config->PDBPath = Config->OutputFile;
1100
17
    sys::path::replace_extension(Config->PDBPath, ".pdb");
1101
17
  }
1102
263
1103
263
  // Disable PDB generation if the user requested it.
1104
263
  if (Args.hasArg(OPT_nopdb))
1105
2
    Config->PDBPath = "";
1106
263
1107
263
  // Set default image base if /base is not given.
1108
263
  if (Config->ImageBase == uint64_t(-1))
1109
261
    Config->ImageBase = getDefaultImageBase();
1110
263
1111
263
  Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1112
263
  if (
Config->Machine == I386263
) {
1113
40
    Symtab->addAbsolute("___safe_se_handler_table", 0);
1114
40
    Symtab->addAbsolute("___safe_se_handler_count", 0);
1115
40
  }
1116
263
1117
263
  // We do not support /guard:cf (control flow protection) yet.
1118
263
  // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
1119
263
  Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1120
263
  Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1121
263
  Symtab->addAbsolute(mangle("__guard_flags"), 0x100);
1122
263
  Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1123
263
  Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1124
263
  Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1125
263
  Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1126
263
1127
263
  // This code may add new undefined symbols to the link, which may enqueue more
1128
263
  // symbol resolution tasks, so we need to continue executing tasks until we
1129
263
  // converge.
1130
267
  do {
1131
267
    // Windows specific -- if entry point is not found,
1132
267
    // search for its mangled names.
1133
267
    if (Config->Entry)
1134
265
      Symtab->mangleMaybe(Config->Entry);
1135
267
1136
267
    // Windows specific -- Make sure we resolve all dllexported symbols.
1137
91
    for (Export &E : Config->Exports) {
1138
91
      if (!E.ForwardTo.empty())
1139
1
        continue;
1140
90
      E.Sym = addUndefined(E.Name);
1141
90
      if (!E.Directives)
1142
52
        Symtab->mangleMaybe(E.Sym);
1143
91
    }
1144
267
1145
267
    // Add weak aliases. Weak aliases is a mechanism to give remaining
1146
267
    // undefined symbols final chance to be resolved successfully.
1147
7
    for (auto Pair : Config->AlternateNames) {
1148
7
      StringRef From = Pair.first;
1149
7
      StringRef To = Pair.second;
1150
7
      Symbol *Sym = Symtab->find(From);
1151
7
      if (!Sym)
1152
1
        continue;
1153
6
      
if (auto *6
U6
= dyn_cast<Undefined>(Sym->body()))
1154
6
        
if (6
!U->WeakAlias6
)
1155
6
          U->WeakAlias = Symtab->addUndefined(To);
1156
7
    }
1157
267
1158
267
    // Windows specific -- if __load_config_used can be resolved, resolve it.
1159
267
    if (Symtab->findUnderscore("_load_config_used"))
1160
5
      addUndefined(mangle("_load_config_used"));
1161
267
  } while (run());
1162
263
1163
263
  if (ErrorCount)
1164
5
    return;
1165
258
1166
258
  // If /msvclto is given, we use the MSVC linker to link LTO output files.
1167
258
  // This is useful because MSVC link.exe can generate complete PDBs.
1168
258
  
if (258
Args.hasArg(OPT_msvclto)258
) {
1169
0
    invokeMSVC(Args);
1170
0
    exit(0);
1171
0
  }
1172
258
1173
258
  // Do LTO by compiling bitcode input files to a set of native COFF files then
1174
258
  // link those files.
1175
258
  Symtab->addCombinedLTOObjects();
1176
258
  run();
1177
258
1178
258
  // Make sure we have resolved all symbols.
1179
258
  Symtab->reportRemainingUndefines();
1180
258
1181
258
  // Windows specific -- if no /subsystem is given, we need to infer
1182
258
  // that from entry point name.
1183
258
  if (
Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN258
) {
1184
166
    Config->Subsystem = inferSubsystem();
1185
166
    if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1186
0
      fatal("subsystem must be defined");
1187
258
  }
1188
258
1189
258
  // Handle /safeseh.
1190
258
  
if (258
Args.hasArg(OPT_safeseh)258
) {
1191
4
    for (ObjFile *File : ObjFile::Instances)
1192
4
      
if (4
!File->SEHCompat4
)
1193
1
        error("/safeseh: " + File->getName() + " is not compatible with SEH");
1194
4
    if (ErrorCount)
1195
1
      return;
1196
257
  }
1197
257
1198
257
  // Windows specific -- when we are creating a .dll file, we also
1199
257
  // need to create a .lib file.
1200
257
  
if (257
!Config->Exports.empty() || 257
Config->DLL218
) {
1201
54
    fixupExports();
1202
54
    createImportLibrary(/*AsLib=*/false);
1203
54
    assignExportOrdinals();
1204
54
  }
1205
257
1206
257
  // Set extra alignment for .comm symbols
1207
1
  for (auto Pair : Config->AlignComm) {
1208
1
    StringRef Name = Pair.first;
1209
1
    uint32_t Alignment = Pair.second;
1210
1
1211
1
    Symbol *Sym = Symtab->find(Name);
1212
1
    if (
!Sym1
) {
1213
0
      warn("/aligncomm symbol " + Name + " not found");
1214
0
      continue;
1215
0
    }
1216
1
1217
1
    auto *DC = dyn_cast<DefinedCommon>(Sym->body());
1218
1
    if (
!DC1
) {
1219
0
      warn("/aligncomm symbol " + Name + " of wrong kind");
1220
0
      continue;
1221
0
    }
1222
1
1223
1
    CommonChunk *C = DC->getChunk();
1224
1
    C->Alignment = std::max(C->Alignment, Alignment);
1225
1
  }
1226
257
1227
257
  // Windows specific -- Create a side-by-side manifest file.
1228
257
  if (Config->Manifest == Configuration::SideBySide)
1229
5
    createSideBySideManifest();
1230
257
1231
257
  // Identify unreferenced COMDAT sections.
1232
257
  if (Config->DoGC)
1233
250
    markLive(Symtab->getChunks());
1234
257
1235
257
  // Identify identical COMDAT sections to merge them.
1236
257
  if (Config->DoICF)
1237
249
    doICF(Symtab->getChunks());
1238
257
1239
257
  // Write the result.
1240
257
  writeResult();
1241
257
1242
257
  if (ErrorCount)
1243
1
    return;
1244
256
1245
256
  // Call exit to avoid calling destructors.
1246
256
  exit(0);
1247
256
}
1248
1249
} // namespace coff
1250
} // namespace lld