Coverage Report

Created: 2018-01-17 21:32

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