Coverage Report

Created: 2018-08-19 14:04

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