150
|
1 //===- Driver.cpp ---------------------------------------------------------===//
|
|
2 //
|
|
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
4 // See https://llvm.org/LICENSE.txt for license information.
|
|
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
|
6 //
|
|
7 //===----------------------------------------------------------------------===//
|
|
8
|
|
9 #include "Driver.h"
|
|
10 #include "Config.h"
|
|
11 #include "DebugTypes.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/Filesystem.h"
|
|
23 #include "lld/Common/Memory.h"
|
|
24 #include "lld/Common/Timer.h"
|
|
25 #include "lld/Common/Version.h"
|
|
26 #include "llvm/ADT/Optional.h"
|
|
27 #include "llvm/ADT/StringSwitch.h"
|
|
28 #include "llvm/BinaryFormat/Magic.h"
|
207
|
29 #include "llvm/Config/llvm-config.h"
|
150
|
30 #include "llvm/LTO/LTO.h"
|
|
31 #include "llvm/Object/ArchiveWriter.h"
|
|
32 #include "llvm/Object/COFFImportFile.h"
|
|
33 #include "llvm/Object/COFFModuleDefinition.h"
|
|
34 #include "llvm/Object/WindowsMachineFlag.h"
|
|
35 #include "llvm/Option/Arg.h"
|
|
36 #include "llvm/Option/ArgList.h"
|
|
37 #include "llvm/Option/Option.h"
|
207
|
38 #include "llvm/Support/BinaryStreamReader.h"
|
150
|
39 #include "llvm/Support/CommandLine.h"
|
|
40 #include "llvm/Support/Debug.h"
|
|
41 #include "llvm/Support/LEB128.h"
|
|
42 #include "llvm/Support/MathExtras.h"
|
173
|
43 #include "llvm/Support/Parallel.h"
|
150
|
44 #include "llvm/Support/Path.h"
|
|
45 #include "llvm/Support/Process.h"
|
|
46 #include "llvm/Support/TarWriter.h"
|
|
47 #include "llvm/Support/TargetSelect.h"
|
|
48 #include "llvm/Support/raw_ostream.h"
|
|
49 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
|
|
50 #include <algorithm>
|
|
51 #include <future>
|
|
52 #include <memory>
|
|
53
|
|
54 using namespace llvm;
|
|
55 using namespace llvm::object;
|
|
56 using namespace llvm::COFF;
|
207
|
57 using namespace llvm::sys;
|
150
|
58
|
|
59 namespace lld {
|
|
60 namespace coff {
|
|
61
|
|
62 static Timer inputFileTimer("Input File Reading", Timer::root());
|
|
63
|
|
64 Configuration *config;
|
|
65 LinkerDriver *driver;
|
|
66
|
|
67 bool link(ArrayRef<const char *> args, bool canExitEarly, raw_ostream &stdoutOS,
|
|
68 raw_ostream &stderrOS) {
|
|
69 lld::stdoutOS = &stdoutOS;
|
|
70 lld::stderrOS = &stderrOS;
|
|
71
|
207
|
72 errorHandler().cleanupCallback = []() {
|
|
73 TpiSource::clear();
|
|
74 freeArena();
|
|
75 ObjFile::instances.clear();
|
|
76 PDBInputFile::instances.clear();
|
|
77 ImportFile::instances.clear();
|
|
78 BitcodeFile::instances.clear();
|
|
79 memset(MergeChunk::instances, 0, sizeof(MergeChunk::instances));
|
|
80 OutputSection::clear();
|
|
81 };
|
|
82
|
150
|
83 errorHandler().logName = args::getFilenameWithoutExe(args[0]);
|
|
84 errorHandler().errorLimitExceededMsg =
|
|
85 "too many errors emitted, stopping now"
|
|
86 " (use /errorlimit:0 to see all errors)";
|
|
87 errorHandler().exitEarly = canExitEarly;
|
|
88 stderrOS.enable_colors(stderrOS.has_colors());
|
|
89
|
|
90 config = make<Configuration>();
|
|
91 symtab = make<SymbolTable>();
|
|
92 driver = make<LinkerDriver>();
|
|
93
|
207
|
94 driver->linkerMain(args);
|
150
|
95
|
|
96 // Call exit() if we can to avoid calling destructors.
|
|
97 if (canExitEarly)
|
|
98 exitLld(errorCount() ? 1 : 0);
|
|
99
|
207
|
100 bool ret = errorCount() == 0;
|
|
101 if (!canExitEarly)
|
|
102 errorHandler().reset();
|
|
103 return ret;
|
150
|
104 }
|
|
105
|
|
106 // Parse options of the form "old;new".
|
|
107 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
|
|
108 unsigned id) {
|
|
109 auto *arg = args.getLastArg(id);
|
|
110 if (!arg)
|
|
111 return {"", ""};
|
|
112
|
|
113 StringRef s = arg->getValue();
|
|
114 std::pair<StringRef, StringRef> ret = s.split(';');
|
|
115 if (ret.second.empty())
|
|
116 error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
|
|
117 return ret;
|
|
118 }
|
|
119
|
|
120 // Drop directory components and replace extension with
|
|
121 // ".exe", ".dll" or ".sys".
|
|
122 static std::string getOutputPath(StringRef path) {
|
|
123 StringRef ext = ".exe";
|
|
124 if (config->dll)
|
|
125 ext = ".dll";
|
|
126 else if (config->driver)
|
|
127 ext = ".sys";
|
|
128
|
|
129 return (sys::path::stem(path) + ext).str();
|
|
130 }
|
|
131
|
|
132 // Returns true if S matches /crtend.?\.o$/.
|
|
133 static bool isCrtend(StringRef s) {
|
|
134 if (!s.endswith(".o"))
|
|
135 return false;
|
|
136 s = s.drop_back(2);
|
|
137 if (s.endswith("crtend"))
|
|
138 return true;
|
|
139 return !s.empty() && s.drop_back().endswith("crtend");
|
|
140 }
|
|
141
|
|
142 // ErrorOr is not default constructible, so it cannot be used as the type
|
|
143 // parameter of a future.
|
|
144 // FIXME: We could open the file in createFutureForFile and avoid needing to
|
|
145 // return an error here, but for the moment that would cost us a file descriptor
|
|
146 // (a limited resource on Windows) for the duration that the future is pending.
|
|
147 using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
|
|
148
|
|
149 // Create a std::future that opens and maps a file using the best strategy for
|
|
150 // the host platform.
|
|
151 static std::future<MBErrPair> createFutureForFile(std::string path) {
|
|
152 #if _WIN32
|
|
153 // On Windows, file I/O is relatively slow so it is best to do this
|
|
154 // asynchronously.
|
|
155 auto strategy = std::launch::async;
|
|
156 #else
|
|
157 auto strategy = std::launch::deferred;
|
|
158 #endif
|
|
159 return std::async(strategy, [=]() {
|
207
|
160 auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
|
|
161 /*RequiresNullTerminator=*/false);
|
150
|
162 if (!mbOrErr)
|
|
163 return MBErrPair{nullptr, mbOrErr.getError()};
|
|
164 return MBErrPair{std::move(*mbOrErr), std::error_code()};
|
|
165 });
|
|
166 }
|
|
167
|
|
168 // Symbol names are mangled by prepending "_" on x86.
|
|
169 static StringRef mangle(StringRef sym) {
|
|
170 assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN);
|
|
171 if (config->machine == I386)
|
|
172 return saver.save("_" + sym);
|
|
173 return sym;
|
|
174 }
|
|
175
|
|
176 static bool findUnderscoreMangle(StringRef sym) {
|
|
177 Symbol *s = symtab->findMangle(mangle(sym));
|
|
178 return s && !isa<Undefined>(s);
|
|
179 }
|
|
180
|
|
181 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
|
|
182 MemoryBufferRef mbref = *mb;
|
|
183 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
|
|
184
|
|
185 if (driver->tar)
|
|
186 driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()),
|
|
187 mbref.getBuffer());
|
|
188 return mbref;
|
|
189 }
|
|
190
|
|
191 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
|
|
192 bool wholeArchive, bool lazy) {
|
|
193 StringRef filename = mb->getBufferIdentifier();
|
|
194
|
|
195 MemoryBufferRef mbref = takeBuffer(std::move(mb));
|
|
196 filePaths.push_back(filename);
|
|
197
|
|
198 // File type is detected by contents, not by file extension.
|
|
199 switch (identify_magic(mbref.getBuffer())) {
|
|
200 case file_magic::windows_resource:
|
|
201 resources.push_back(mbref);
|
|
202 break;
|
|
203 case file_magic::archive:
|
|
204 if (wholeArchive) {
|
|
205 std::unique_ptr<Archive> file =
|
|
206 CHECK(Archive::create(mbref), filename + ": failed to parse archive");
|
|
207 Archive *archive = file.get();
|
|
208 make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
|
|
209
|
|
210 int memberIndex = 0;
|
|
211 for (MemoryBufferRef m : getArchiveMembers(archive))
|
|
212 addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
|
|
213 return;
|
|
214 }
|
|
215 symtab->addFile(make<ArchiveFile>(mbref));
|
|
216 break;
|
|
217 case file_magic::bitcode:
|
|
218 if (lazy)
|
|
219 symtab->addFile(make<LazyObjFile>(mbref));
|
|
220 else
|
|
221 symtab->addFile(make<BitcodeFile>(mbref, "", 0));
|
|
222 break;
|
|
223 case file_magic::coff_object:
|
|
224 case file_magic::coff_import_library:
|
|
225 if (lazy)
|
|
226 symtab->addFile(make<LazyObjFile>(mbref));
|
|
227 else
|
|
228 symtab->addFile(make<ObjFile>(mbref));
|
|
229 break;
|
|
230 case file_magic::pdb:
|
173
|
231 symtab->addFile(make<PDBInputFile>(mbref));
|
150
|
232 break;
|
|
233 case file_magic::coff_cl_gl_object:
|
|
234 error(filename + ": is not a native COFF file. Recompile without /GL");
|
|
235 break;
|
|
236 case file_magic::pecoff_executable:
|
|
237 if (filename.endswith_lower(".dll")) {
|
|
238 error(filename + ": bad file type. Did you specify a DLL instead of an "
|
|
239 "import library?");
|
|
240 break;
|
|
241 }
|
|
242 LLVM_FALLTHROUGH;
|
|
243 default:
|
|
244 error(mbref.getBufferIdentifier() + ": unknown file type");
|
|
245 break;
|
|
246 }
|
|
247 }
|
|
248
|
|
249 void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
|
|
250 auto future = std::make_shared<std::future<MBErrPair>>(
|
|
251 createFutureForFile(std::string(path)));
|
|
252 std::string pathStr = std::string(path);
|
|
253 enqueueTask([=]() {
|
|
254 auto mbOrErr = future->get();
|
|
255 if (mbOrErr.second) {
|
|
256 std::string msg =
|
|
257 "could not open '" + pathStr + "': " + mbOrErr.second.message();
|
|
258 // Check if the filename is a typo for an option flag. OptTable thinks
|
|
259 // that all args that are not known options and that start with / are
|
|
260 // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
|
|
261 // the option `/nodefaultlib` than a reference to a file in the root
|
|
262 // directory.
|
|
263 std::string nearest;
|
173
|
264 if (optTable.findNearest(pathStr, nearest) > 1)
|
150
|
265 error(msg);
|
|
266 else
|
|
267 error(msg + "; did you mean '" + nearest + "'");
|
|
268 } else
|
|
269 driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy);
|
|
270 });
|
|
271 }
|
|
272
|
|
273 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
|
|
274 StringRef parentName,
|
|
275 uint64_t offsetInArchive) {
|
|
276 file_magic magic = identify_magic(mb.getBuffer());
|
|
277 if (magic == file_magic::coff_import_library) {
|
|
278 InputFile *imp = make<ImportFile>(mb);
|
|
279 imp->parentName = parentName;
|
|
280 symtab->addFile(imp);
|
|
281 return;
|
|
282 }
|
|
283
|
|
284 InputFile *obj;
|
|
285 if (magic == file_magic::coff_object) {
|
|
286 obj = make<ObjFile>(mb);
|
|
287 } else if (magic == file_magic::bitcode) {
|
|
288 obj = make<BitcodeFile>(mb, parentName, offsetInArchive);
|
|
289 } else {
|
|
290 error("unknown file type: " + mb.getBufferIdentifier());
|
|
291 return;
|
|
292 }
|
|
293
|
|
294 obj->parentName = parentName;
|
|
295 symtab->addFile(obj);
|
|
296 log("Loaded " + toString(obj) + " for " + symName);
|
|
297 }
|
|
298
|
|
299 void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
|
|
300 const Archive::Symbol &sym,
|
|
301 StringRef parentName) {
|
|
302
|
|
303 auto reportBufferError = [=](Error &&e, StringRef childName) {
|
|
304 fatal("could not get the buffer for the member defining symbol " +
|
|
305 toCOFFString(sym) + ": " + parentName + "(" + childName + "): " +
|
|
306 toString(std::move(e)));
|
|
307 };
|
|
308
|
|
309 if (!c.getParent()->isThin()) {
|
|
310 uint64_t offsetInArchive = c.getChildOffset();
|
|
311 Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
|
|
312 if (!mbOrErr)
|
|
313 reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
|
|
314 MemoryBufferRef mb = mbOrErr.get();
|
|
315 enqueueTask([=]() {
|
|
316 driver->addArchiveBuffer(mb, toCOFFString(sym), parentName,
|
|
317 offsetInArchive);
|
|
318 });
|
|
319 return;
|
|
320 }
|
|
321
|
|
322 std::string childName = CHECK(
|
|
323 c.getFullName(),
|
|
324 "could not get the filename for the member defining symbol " +
|
|
325 toCOFFString(sym));
|
|
326 auto future = std::make_shared<std::future<MBErrPair>>(
|
|
327 createFutureForFile(childName));
|
|
328 enqueueTask([=]() {
|
|
329 auto mbOrErr = future->get();
|
|
330 if (mbOrErr.second)
|
|
331 reportBufferError(errorCodeToError(mbOrErr.second), childName);
|
|
332 // Pass empty string as archive name so that the original filename is
|
|
333 // used as the buffer identifier.
|
|
334 driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
|
|
335 toCOFFString(sym), "", /*OffsetInArchive=*/0);
|
|
336 });
|
|
337 }
|
|
338
|
|
339 static bool isDecorated(StringRef sym) {
|
|
340 return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") ||
|
|
341 (!config->mingw && sym.contains('@'));
|
|
342 }
|
|
343
|
|
344 // Parses .drectve section contents and returns a list of files
|
|
345 // specified by /defaultlib.
|
|
346 void LinkerDriver::parseDirectives(InputFile *file) {
|
|
347 StringRef s = file->getDirectives();
|
|
348 if (s.empty())
|
|
349 return;
|
|
350
|
|
351 log("Directives: " + toString(file) + ": " + s);
|
|
352
|
|
353 ArgParser parser;
|
|
354 // .drectve is always tokenized using Windows shell rules.
|
|
355 // /EXPORT: option can appear too many times, processing in fastpath.
|
173
|
356 ParsedDirectives directives = parser.parseDirectives(s);
|
150
|
357
|
173
|
358 for (StringRef e : directives.exports) {
|
150
|
359 // If a common header file contains dllexported function
|
|
360 // declarations, many object files may end up with having the
|
|
361 // same /EXPORT options. In order to save cost of parsing them,
|
|
362 // we dedup them first.
|
|
363 if (!directivesExports.insert(e).second)
|
|
364 continue;
|
|
365
|
|
366 Export exp = parseExport(e);
|
|
367 if (config->machine == I386 && config->mingw) {
|
|
368 if (!isDecorated(exp.name))
|
|
369 exp.name = saver.save("_" + exp.name);
|
|
370 if (!exp.extName.empty() && !isDecorated(exp.extName))
|
|
371 exp.extName = saver.save("_" + exp.extName);
|
|
372 }
|
|
373 exp.directives = true;
|
|
374 config->exports.push_back(exp);
|
|
375 }
|
|
376
|
173
|
377 // Handle /include: in bulk.
|
|
378 for (StringRef inc : directives.includes)
|
|
379 addUndefined(inc);
|
|
380
|
|
381 for (auto *arg : directives.args) {
|
150
|
382 switch (arg->getOption().getID()) {
|
|
383 case OPT_aligncomm:
|
|
384 parseAligncomm(arg->getValue());
|
|
385 break;
|
|
386 case OPT_alternatename:
|
|
387 parseAlternateName(arg->getValue());
|
|
388 break;
|
|
389 case OPT_defaultlib:
|
|
390 if (Optional<StringRef> path = findLib(arg->getValue()))
|
|
391 enqueuePath(*path, false, false);
|
|
392 break;
|
|
393 case OPT_entry:
|
|
394 config->entry = addUndefined(mangle(arg->getValue()));
|
|
395 break;
|
|
396 case OPT_failifmismatch:
|
|
397 checkFailIfMismatch(arg->getValue(), file);
|
|
398 break;
|
|
399 case OPT_incl:
|
|
400 addUndefined(arg->getValue());
|
|
401 break;
|
|
402 case OPT_merge:
|
|
403 parseMerge(arg->getValue());
|
|
404 break;
|
|
405 case OPT_nodefaultlib:
|
|
406 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
|
|
407 break;
|
|
408 case OPT_section:
|
|
409 parseSection(arg->getValue());
|
|
410 break;
|
207
|
411 case OPT_stack:
|
|
412 parseNumbers(arg->getValue(), &config->stackReserve,
|
|
413 &config->stackCommit);
|
|
414 break;
|
|
415 case OPT_subsystem: {
|
|
416 bool gotVersion = false;
|
150
|
417 parseSubsystem(arg->getValue(), &config->subsystem,
|
207
|
418 &config->majorSubsystemVersion,
|
|
419 &config->minorSubsystemVersion, &gotVersion);
|
|
420 if (gotVersion) {
|
|
421 config->majorOSVersion = config->majorSubsystemVersion;
|
|
422 config->minorOSVersion = config->minorSubsystemVersion;
|
|
423 }
|
150
|
424 break;
|
207
|
425 }
|
150
|
426 // Only add flags here that link.exe accepts in
|
|
427 // `#pragma comment(linker, "/flag")`-generated sections.
|
|
428 case OPT_editandcontinue:
|
|
429 case OPT_guardsym:
|
|
430 case OPT_throwingnew:
|
|
431 break;
|
|
432 default:
|
|
433 error(arg->getSpelling() + " is not allowed in .drectve");
|
|
434 }
|
|
435 }
|
|
436 }
|
|
437
|
|
438 // Find file from search paths. You can omit ".obj", this function takes
|
|
439 // care of that. Note that the returned path is not guaranteed to exist.
|
|
440 StringRef LinkerDriver::doFindFile(StringRef filename) {
|
|
441 bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos);
|
|
442 if (hasPathSep)
|
|
443 return filename;
|
|
444 bool hasExt = filename.contains('.');
|
|
445 for (StringRef dir : searchPaths) {
|
|
446 SmallString<128> path = dir;
|
|
447 sys::path::append(path, filename);
|
|
448 if (sys::fs::exists(path.str()))
|
|
449 return saver.save(path.str());
|
|
450 if (!hasExt) {
|
|
451 path.append(".obj");
|
|
452 if (sys::fs::exists(path.str()))
|
|
453 return saver.save(path.str());
|
|
454 }
|
|
455 }
|
|
456 return filename;
|
|
457 }
|
|
458
|
|
459 static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
|
|
460 sys::fs::UniqueID ret;
|
|
461 if (sys::fs::getUniqueID(path, ret))
|
|
462 return None;
|
|
463 return ret;
|
|
464 }
|
|
465
|
|
466 // Resolves a file path. This never returns the same path
|
|
467 // (in that case, it returns None).
|
|
468 Optional<StringRef> LinkerDriver::findFile(StringRef filename) {
|
|
469 StringRef path = doFindFile(filename);
|
|
470
|
|
471 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) {
|
|
472 bool seen = !visitedFiles.insert(*id).second;
|
|
473 if (seen)
|
|
474 return None;
|
|
475 }
|
|
476
|
|
477 if (path.endswith_lower(".lib"))
|
|
478 visitedLibs.insert(std::string(sys::path::filename(path)));
|
|
479 return path;
|
|
480 }
|
|
481
|
|
482 // MinGW specific. If an embedded directive specified to link to
|
|
483 // foo.lib, but it isn't found, try libfoo.a instead.
|
|
484 StringRef LinkerDriver::doFindLibMinGW(StringRef filename) {
|
|
485 if (filename.contains('/') || filename.contains('\\'))
|
|
486 return filename;
|
|
487
|
|
488 SmallString<128> s = filename;
|
|
489 sys::path::replace_extension(s, ".a");
|
|
490 StringRef libName = saver.save("lib" + s.str());
|
|
491 return doFindFile(libName);
|
|
492 }
|
|
493
|
|
494 // Find library file from search path.
|
|
495 StringRef LinkerDriver::doFindLib(StringRef filename) {
|
|
496 // Add ".lib" to Filename if that has no file extension.
|
|
497 bool hasExt = filename.contains('.');
|
|
498 if (!hasExt)
|
|
499 filename = saver.save(filename + ".lib");
|
|
500 StringRef ret = doFindFile(filename);
|
|
501 // For MinGW, if the find above didn't turn up anything, try
|
|
502 // looking for a MinGW formatted library name.
|
|
503 if (config->mingw && ret == filename)
|
|
504 return doFindLibMinGW(filename);
|
|
505 return ret;
|
|
506 }
|
|
507
|
|
508 // Resolves a library path. /nodefaultlib options are taken into
|
|
509 // consideration. This never returns the same path (in that case,
|
|
510 // it returns None).
|
|
511 Optional<StringRef> LinkerDriver::findLib(StringRef filename) {
|
|
512 if (config->noDefaultLibAll)
|
|
513 return None;
|
|
514 if (!visitedLibs.insert(filename.lower()).second)
|
|
515 return None;
|
|
516
|
|
517 StringRef path = doFindLib(filename);
|
|
518 if (config->noDefaultLibs.count(path.lower()))
|
|
519 return None;
|
|
520
|
|
521 if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
|
|
522 if (!visitedFiles.insert(*id).second)
|
|
523 return None;
|
|
524 return path;
|
|
525 }
|
|
526
|
|
527 // Parses LIB environment which contains a list of search paths.
|
|
528 void LinkerDriver::addLibSearchPaths() {
|
|
529 Optional<std::string> envOpt = Process::GetEnv("LIB");
|
|
530 if (!envOpt.hasValue())
|
|
531 return;
|
|
532 StringRef env = saver.save(*envOpt);
|
|
533 while (!env.empty()) {
|
|
534 StringRef path;
|
|
535 std::tie(path, env) = env.split(';');
|
|
536 searchPaths.push_back(path);
|
|
537 }
|
|
538 }
|
|
539
|
|
540 Symbol *LinkerDriver::addUndefined(StringRef name) {
|
|
541 Symbol *b = symtab->addUndefined(name);
|
|
542 if (!b->isGCRoot) {
|
|
543 b->isGCRoot = true;
|
|
544 config->gcroot.push_back(b);
|
|
545 }
|
|
546 return b;
|
|
547 }
|
|
548
|
|
549 StringRef LinkerDriver::mangleMaybe(Symbol *s) {
|
|
550 // If the plain symbol name has already been resolved, do nothing.
|
|
551 Undefined *unmangled = dyn_cast<Undefined>(s);
|
|
552 if (!unmangled)
|
|
553 return "";
|
|
554
|
|
555 // Otherwise, see if a similar, mangled symbol exists in the symbol table.
|
|
556 Symbol *mangled = symtab->findMangle(unmangled->getName());
|
|
557 if (!mangled)
|
|
558 return "";
|
|
559
|
|
560 // If we find a similar mangled symbol, make this an alias to it and return
|
|
561 // its name.
|
|
562 log(unmangled->getName() + " aliased to " + mangled->getName());
|
|
563 unmangled->weakAlias = symtab->addUndefined(mangled->getName());
|
|
564 return mangled->getName();
|
|
565 }
|
|
566
|
|
567 // Windows specific -- find default entry point name.
|
|
568 //
|
|
569 // There are four different entry point functions for Windows executables,
|
|
570 // each of which corresponds to a user-defined "main" function. This function
|
|
571 // infers an entry point from a user-defined "main" function.
|
|
572 StringRef LinkerDriver::findDefaultEntry() {
|
|
573 assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
|
|
574 "must handle /subsystem before calling this");
|
|
575
|
|
576 if (config->mingw)
|
|
577 return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
|
|
578 ? "WinMainCRTStartup"
|
|
579 : "mainCRTStartup");
|
|
580
|
|
581 if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
|
|
582 if (findUnderscoreMangle("wWinMain")) {
|
|
583 if (!findUnderscoreMangle("WinMain"))
|
|
584 return mangle("wWinMainCRTStartup");
|
|
585 warn("found both wWinMain and WinMain; using latter");
|
|
586 }
|
|
587 return mangle("WinMainCRTStartup");
|
|
588 }
|
|
589 if (findUnderscoreMangle("wmain")) {
|
|
590 if (!findUnderscoreMangle("main"))
|
|
591 return mangle("wmainCRTStartup");
|
|
592 warn("found both wmain and main; using latter");
|
|
593 }
|
|
594 return mangle("mainCRTStartup");
|
|
595 }
|
|
596
|
|
597 WindowsSubsystem LinkerDriver::inferSubsystem() {
|
|
598 if (config->dll)
|
|
599 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
|
|
600 if (config->mingw)
|
|
601 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
|
|
602 // Note that link.exe infers the subsystem from the presence of these
|
|
603 // functions even if /entry: or /nodefaultlib are passed which causes them
|
|
604 // to not be called.
|
|
605 bool haveMain = findUnderscoreMangle("main");
|
|
606 bool haveWMain = findUnderscoreMangle("wmain");
|
|
607 bool haveWinMain = findUnderscoreMangle("WinMain");
|
|
608 bool haveWWinMain = findUnderscoreMangle("wWinMain");
|
|
609 if (haveMain || haveWMain) {
|
|
610 if (haveWinMain || haveWWinMain) {
|
|
611 warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
|
|
612 (haveWinMain ? "WinMain" : "wWinMain") +
|
|
613 "; defaulting to /subsystem:console");
|
|
614 }
|
|
615 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
|
|
616 }
|
|
617 if (haveWinMain || haveWWinMain)
|
|
618 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
|
|
619 return IMAGE_SUBSYSTEM_UNKNOWN;
|
|
620 }
|
|
621
|
|
622 static uint64_t getDefaultImageBase() {
|
|
623 if (config->is64())
|
|
624 return config->dll ? 0x180000000 : 0x140000000;
|
|
625 return config->dll ? 0x10000000 : 0x400000;
|
|
626 }
|
|
627
|
207
|
628 static std::string rewritePath(StringRef s) {
|
|
629 if (fs::exists(s))
|
|
630 return relativeToRoot(s);
|
|
631 return std::string(s);
|
|
632 }
|
|
633
|
|
634 // Reconstructs command line arguments so that so that you can re-run
|
|
635 // the same command with the same inputs. This is for --reproduce.
|
150
|
636 static std::string createResponseFile(const opt::InputArgList &args,
|
|
637 ArrayRef<StringRef> filePaths,
|
|
638 ArrayRef<StringRef> searchPaths) {
|
|
639 SmallString<0> data;
|
|
640 raw_svector_ostream os(data);
|
|
641
|
|
642 for (auto *arg : args) {
|
|
643 switch (arg->getOption().getID()) {
|
|
644 case OPT_linkrepro:
|
|
645 case OPT_reproduce:
|
|
646 case OPT_INPUT:
|
|
647 case OPT_defaultlib:
|
|
648 case OPT_libpath:
|
|
649 case OPT_manifest:
|
|
650 case OPT_manifest_colon:
|
|
651 case OPT_manifestdependency:
|
|
652 case OPT_manifestfile:
|
|
653 case OPT_manifestinput:
|
|
654 case OPT_manifestuac:
|
|
655 break;
|
207
|
656 case OPT_call_graph_ordering_file:
|
|
657 case OPT_deffile:
|
|
658 case OPT_natvis:
|
|
659 os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n';
|
|
660 break;
|
|
661 case OPT_order: {
|
|
662 StringRef orderFile = arg->getValue();
|
|
663 orderFile.consume_front("@");
|
|
664 os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n';
|
|
665 break;
|
|
666 }
|
|
667 case OPT_pdbstream: {
|
|
668 const std::pair<StringRef, StringRef> nameFile =
|
|
669 StringRef(arg->getValue()).split("=");
|
|
670 os << arg->getSpelling() << nameFile.first << '='
|
|
671 << quote(rewritePath(nameFile.second)) << '\n';
|
|
672 break;
|
|
673 }
|
150
|
674 case OPT_implib:
|
|
675 case OPT_pdb:
|
|
676 case OPT_pdbstripped:
|
|
677 case OPT_out:
|
|
678 os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
|
|
679 break;
|
|
680 default:
|
|
681 os << toString(*arg) << "\n";
|
|
682 }
|
|
683 }
|
|
684
|
|
685 for (StringRef path : searchPaths) {
|
|
686 std::string relPath = relativeToRoot(path);
|
|
687 os << "/libpath:" << quote(relPath) << "\n";
|
|
688 }
|
|
689
|
|
690 for (StringRef path : filePaths)
|
|
691 os << quote(relativeToRoot(path)) << "\n";
|
|
692
|
|
693 return std::string(data.str());
|
|
694 }
|
|
695
|
207
|
696 enum class DebugKind {
|
|
697 Unknown,
|
|
698 None,
|
|
699 Full,
|
|
700 FastLink,
|
|
701 GHash,
|
|
702 NoGHash,
|
|
703 Dwarf,
|
|
704 Symtab
|
|
705 };
|
150
|
706
|
|
707 static DebugKind parseDebugKind(const opt::InputArgList &args) {
|
|
708 auto *a = args.getLastArg(OPT_debug, OPT_debug_opt);
|
|
709 if (!a)
|
|
710 return DebugKind::None;
|
|
711 if (a->getNumValues() == 0)
|
|
712 return DebugKind::Full;
|
|
713
|
|
714 DebugKind debug = StringSwitch<DebugKind>(a->getValue())
|
207
|
715 .CaseLower("none", DebugKind::None)
|
|
716 .CaseLower("full", DebugKind::Full)
|
|
717 .CaseLower("fastlink", DebugKind::FastLink)
|
|
718 // LLD extensions
|
|
719 .CaseLower("ghash", DebugKind::GHash)
|
|
720 .CaseLower("noghash", DebugKind::NoGHash)
|
|
721 .CaseLower("dwarf", DebugKind::Dwarf)
|
|
722 .CaseLower("symtab", DebugKind::Symtab)
|
|
723 .Default(DebugKind::Unknown);
|
150
|
724
|
|
725 if (debug == DebugKind::FastLink) {
|
|
726 warn("/debug:fastlink unsupported; using /debug:full");
|
|
727 return DebugKind::Full;
|
|
728 }
|
|
729 if (debug == DebugKind::Unknown) {
|
|
730 error("/debug: unknown option: " + Twine(a->getValue()));
|
|
731 return DebugKind::None;
|
|
732 }
|
|
733 return debug;
|
|
734 }
|
|
735
|
|
736 static unsigned parseDebugTypes(const opt::InputArgList &args) {
|
|
737 unsigned debugTypes = static_cast<unsigned>(DebugType::None);
|
|
738
|
|
739 if (auto *a = args.getLastArg(OPT_debugtype)) {
|
|
740 SmallVector<StringRef, 3> types;
|
|
741 StringRef(a->getValue())
|
|
742 .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
|
|
743
|
|
744 for (StringRef type : types) {
|
|
745 unsigned v = StringSwitch<unsigned>(type.lower())
|
|
746 .Case("cv", static_cast<unsigned>(DebugType::CV))
|
|
747 .Case("pdata", static_cast<unsigned>(DebugType::PData))
|
|
748 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
|
|
749 .Default(0);
|
|
750 if (v == 0) {
|
|
751 warn("/debugtype: unknown option '" + type + "'");
|
|
752 continue;
|
|
753 }
|
|
754 debugTypes |= v;
|
|
755 }
|
|
756 return debugTypes;
|
|
757 }
|
|
758
|
|
759 // Default debug types
|
|
760 debugTypes = static_cast<unsigned>(DebugType::CV);
|
|
761 if (args.hasArg(OPT_driver))
|
|
762 debugTypes |= static_cast<unsigned>(DebugType::PData);
|
|
763 if (args.hasArg(OPT_profile))
|
|
764 debugTypes |= static_cast<unsigned>(DebugType::Fixup);
|
|
765
|
|
766 return debugTypes;
|
|
767 }
|
|
768
|
173
|
769 static std::string getMapFile(const opt::InputArgList &args,
|
|
770 opt::OptSpecifier os, opt::OptSpecifier osFile) {
|
|
771 auto *arg = args.getLastArg(os, osFile);
|
150
|
772 if (!arg)
|
|
773 return "";
|
173
|
774 if (arg->getOption().getID() == osFile.getID())
|
150
|
775 return arg->getValue();
|
|
776
|
173
|
777 assert(arg->getOption().getID() == os.getID());
|
150
|
778 StringRef outFile = config->outputFile;
|
|
779 return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
|
|
780 }
|
|
781
|
|
782 static std::string getImplibPath() {
|
|
783 if (!config->implib.empty())
|
|
784 return std::string(config->implib);
|
|
785 SmallString<128> out = StringRef(config->outputFile);
|
|
786 sys::path::replace_extension(out, ".lib");
|
|
787 return std::string(out.str());
|
|
788 }
|
|
789
|
|
790 // The import name is calculated as follows:
|
|
791 //
|
|
792 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
|
|
793 // -----+----------------+---------------------+------------------
|
|
794 // LINK | {value} | {value}.{.dll/.exe} | {output name}
|
|
795 // LIB | {value} | {value}.dll | {output name}.dll
|
|
796 //
|
|
797 static std::string getImportName(bool asLib) {
|
|
798 SmallString<128> out;
|
|
799
|
|
800 if (config->importName.empty()) {
|
|
801 out.assign(sys::path::filename(config->outputFile));
|
|
802 if (asLib)
|
|
803 sys::path::replace_extension(out, ".dll");
|
|
804 } else {
|
|
805 out.assign(config->importName);
|
|
806 if (!sys::path::has_extension(out))
|
|
807 sys::path::replace_extension(out,
|
|
808 (config->dll || asLib) ? ".dll" : ".exe");
|
|
809 }
|
|
810
|
|
811 return std::string(out.str());
|
|
812 }
|
|
813
|
|
814 static void createImportLibrary(bool asLib) {
|
|
815 std::vector<COFFShortExport> exports;
|
|
816 for (Export &e1 : config->exports) {
|
|
817 COFFShortExport e2;
|
|
818 e2.Name = std::string(e1.name);
|
|
819 e2.SymbolName = std::string(e1.symbolName);
|
|
820 e2.ExtName = std::string(e1.extName);
|
|
821 e2.Ordinal = e1.ordinal;
|
|
822 e2.Noname = e1.noname;
|
|
823 e2.Data = e1.data;
|
|
824 e2.Private = e1.isPrivate;
|
|
825 e2.Constant = e1.constant;
|
|
826 exports.push_back(e2);
|
|
827 }
|
|
828
|
|
829 auto handleError = [](Error &&e) {
|
|
830 handleAllErrors(std::move(e),
|
|
831 [](ErrorInfoBase &eib) { error(eib.message()); });
|
|
832 };
|
|
833 std::string libName = getImportName(asLib);
|
|
834 std::string path = getImplibPath();
|
|
835
|
|
836 if (!config->incremental) {
|
|
837 handleError(writeImportLibrary(libName, path, exports, config->machine,
|
|
838 config->mingw));
|
|
839 return;
|
|
840 }
|
|
841
|
|
842 // If the import library already exists, replace it only if the contents
|
|
843 // have changed.
|
|
844 ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
|
207
|
845 path, /*IsText=*/false, /*RequiresNullTerminator=*/false);
|
150
|
846 if (!oldBuf) {
|
|
847 handleError(writeImportLibrary(libName, path, exports, config->machine,
|
|
848 config->mingw));
|
|
849 return;
|
|
850 }
|
|
851
|
|
852 SmallString<128> tmpName;
|
|
853 if (std::error_code ec =
|
|
854 sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
|
|
855 fatal("cannot create temporary file for import library " + path + ": " +
|
|
856 ec.message());
|
|
857
|
|
858 if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine,
|
|
859 config->mingw)) {
|
|
860 handleError(std::move(e));
|
|
861 return;
|
|
862 }
|
|
863
|
|
864 std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
|
207
|
865 tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false));
|
150
|
866 if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
|
|
867 oldBuf->reset();
|
|
868 handleError(errorCodeToError(sys::fs::rename(tmpName, path)));
|
|
869 } else {
|
|
870 sys::fs::remove(tmpName);
|
|
871 }
|
|
872 }
|
|
873
|
|
874 static void parseModuleDefs(StringRef path) {
|
207
|
875 std::unique_ptr<MemoryBuffer> mb =
|
|
876 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
|
|
877 /*RequiresNullTerminator=*/false,
|
|
878 /*IsVolatile=*/true),
|
|
879 "could not open " + path);
|
150
|
880 COFFModuleDefinition m = check(parseCOFFModuleDefinition(
|
|
881 mb->getMemBufferRef(), config->machine, config->mingw));
|
|
882
|
207
|
883 // Include in /reproduce: output if applicable.
|
|
884 driver->takeBuffer(std::move(mb));
|
|
885
|
150
|
886 if (config->outputFile.empty())
|
|
887 config->outputFile = std::string(saver.save(m.OutputFile));
|
|
888 config->importName = std::string(saver.save(m.ImportName));
|
|
889 if (m.ImageBase)
|
|
890 config->imageBase = m.ImageBase;
|
|
891 if (m.StackReserve)
|
|
892 config->stackReserve = m.StackReserve;
|
|
893 if (m.StackCommit)
|
|
894 config->stackCommit = m.StackCommit;
|
|
895 if (m.HeapReserve)
|
|
896 config->heapReserve = m.HeapReserve;
|
|
897 if (m.HeapCommit)
|
|
898 config->heapCommit = m.HeapCommit;
|
|
899 if (m.MajorImageVersion)
|
|
900 config->majorImageVersion = m.MajorImageVersion;
|
|
901 if (m.MinorImageVersion)
|
|
902 config->minorImageVersion = m.MinorImageVersion;
|
|
903 if (m.MajorOSVersion)
|
|
904 config->majorOSVersion = m.MajorOSVersion;
|
|
905 if (m.MinorOSVersion)
|
|
906 config->minorOSVersion = m.MinorOSVersion;
|
|
907
|
|
908 for (COFFShortExport e1 : m.Exports) {
|
|
909 Export e2;
|
|
910 // In simple cases, only Name is set. Renamed exports are parsed
|
|
911 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
|
|
912 // it shouldn't be a normal exported function but a forward to another
|
|
913 // DLL instead. This is supported by both MS and GNU linkers.
|
173
|
914 if (!e1.ExtName.empty() && e1.ExtName != e1.Name &&
|
|
915 StringRef(e1.Name).contains('.')) {
|
150
|
916 e2.name = saver.save(e1.ExtName);
|
|
917 e2.forwardTo = saver.save(e1.Name);
|
|
918 config->exports.push_back(e2);
|
|
919 continue;
|
|
920 }
|
|
921 e2.name = saver.save(e1.Name);
|
|
922 e2.extName = saver.save(e1.ExtName);
|
|
923 e2.ordinal = e1.Ordinal;
|
|
924 e2.noname = e1.Noname;
|
|
925 e2.data = e1.Data;
|
|
926 e2.isPrivate = e1.Private;
|
|
927 e2.constant = e1.Constant;
|
|
928 config->exports.push_back(e2);
|
|
929 }
|
|
930 }
|
|
931
|
|
932 void LinkerDriver::enqueueTask(std::function<void()> task) {
|
|
933 taskQueue.push_back(std::move(task));
|
|
934 }
|
|
935
|
|
936 bool LinkerDriver::run() {
|
|
937 ScopedTimer t(inputFileTimer);
|
|
938
|
|
939 bool didWork = !taskQueue.empty();
|
|
940 while (!taskQueue.empty()) {
|
|
941 taskQueue.front()();
|
|
942 taskQueue.pop_front();
|
|
943 }
|
|
944 return didWork;
|
|
945 }
|
|
946
|
|
947 // Parse an /order file. If an option is given, the linker places
|
|
948 // COMDAT sections in the same order as their names appear in the
|
|
949 // given file.
|
|
950 static void parseOrderFile(StringRef arg) {
|
|
951 // For some reason, the MSVC linker requires a filename to be
|
|
952 // preceded by "@".
|
|
953 if (!arg.startswith("@")) {
|
|
954 error("malformed /order option: '@' missing");
|
|
955 return;
|
|
956 }
|
|
957
|
|
958 // Get a list of all comdat sections for error checking.
|
|
959 DenseSet<StringRef> set;
|
|
960 for (Chunk *c : symtab->getChunks())
|
|
961 if (auto *sec = dyn_cast<SectionChunk>(c))
|
|
962 if (sec->sym)
|
|
963 set.insert(sec->sym->getName());
|
|
964
|
|
965 // Open a file.
|
|
966 StringRef path = arg.substr(1);
|
207
|
967 std::unique_ptr<MemoryBuffer> mb =
|
|
968 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
|
|
969 /*RequiresNullTerminator=*/false,
|
|
970 /*IsVolatile=*/true),
|
|
971 "could not open " + path);
|
150
|
972
|
|
973 // Parse a file. An order file contains one symbol per line.
|
|
974 // All symbols that were not present in a given order file are
|
|
975 // considered to have the lowest priority 0 and are placed at
|
|
976 // end of an output section.
|
|
977 for (StringRef arg : args::getLines(mb->getMemBufferRef())) {
|
|
978 std::string s(arg);
|
|
979 if (config->machine == I386 && !isDecorated(s))
|
|
980 s = "_" + s;
|
|
981
|
|
982 if (set.count(s) == 0) {
|
|
983 if (config->warnMissingOrderSymbol)
|
|
984 warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
|
|
985 }
|
|
986 else
|
|
987 config->order[s] = INT_MIN + config->order.size();
|
|
988 }
|
207
|
989
|
|
990 // Include in /reproduce: output if applicable.
|
|
991 driver->takeBuffer(std::move(mb));
|
|
992 }
|
|
993
|
|
994 static void parseCallGraphFile(StringRef path) {
|
|
995 std::unique_ptr<MemoryBuffer> mb =
|
|
996 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
|
|
997 /*RequiresNullTerminator=*/false,
|
|
998 /*IsVolatile=*/true),
|
|
999 "could not open " + path);
|
|
1000
|
|
1001 // Build a map from symbol name to section.
|
|
1002 DenseMap<StringRef, Symbol *> map;
|
|
1003 for (ObjFile *file : ObjFile::instances)
|
|
1004 for (Symbol *sym : file->getSymbols())
|
|
1005 if (sym)
|
|
1006 map[sym->getName()] = sym;
|
|
1007
|
|
1008 auto findSection = [&](StringRef name) -> SectionChunk * {
|
|
1009 Symbol *sym = map.lookup(name);
|
|
1010 if (!sym) {
|
|
1011 if (config->warnMissingOrderSymbol)
|
|
1012 warn(path + ": no such symbol: " + name);
|
|
1013 return nullptr;
|
|
1014 }
|
|
1015
|
|
1016 if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym))
|
|
1017 return dyn_cast_or_null<SectionChunk>(dr->getChunk());
|
|
1018 return nullptr;
|
|
1019 };
|
|
1020
|
|
1021 for (StringRef line : args::getLines(*mb)) {
|
|
1022 SmallVector<StringRef, 3> fields;
|
|
1023 line.split(fields, ' ');
|
|
1024 uint64_t count;
|
|
1025
|
|
1026 if (fields.size() != 3 || !to_integer(fields[2], count)) {
|
|
1027 error(path + ": parse error");
|
|
1028 return;
|
|
1029 }
|
|
1030
|
|
1031 if (SectionChunk *from = findSection(fields[0]))
|
|
1032 if (SectionChunk *to = findSection(fields[1]))
|
|
1033 config->callGraphProfile[{from, to}] += count;
|
|
1034 }
|
|
1035
|
|
1036 // Include in /reproduce: output if applicable.
|
|
1037 driver->takeBuffer(std::move(mb));
|
|
1038 }
|
|
1039
|
|
1040 static void readCallGraphsFromObjectFiles() {
|
|
1041 for (ObjFile *obj : ObjFile::instances) {
|
|
1042 if (obj->callgraphSec) {
|
|
1043 ArrayRef<uint8_t> contents;
|
|
1044 cantFail(
|
|
1045 obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents));
|
|
1046 BinaryStreamReader reader(contents, support::little);
|
|
1047 while (!reader.empty()) {
|
|
1048 uint32_t fromIndex, toIndex;
|
|
1049 uint64_t count;
|
|
1050 if (Error err = reader.readInteger(fromIndex))
|
|
1051 fatal(toString(obj) + ": Expected 32-bit integer");
|
|
1052 if (Error err = reader.readInteger(toIndex))
|
|
1053 fatal(toString(obj) + ": Expected 32-bit integer");
|
|
1054 if (Error err = reader.readInteger(count))
|
|
1055 fatal(toString(obj) + ": Expected 64-bit integer");
|
|
1056 auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex));
|
|
1057 auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex));
|
|
1058 if (!fromSym || !toSym)
|
|
1059 continue;
|
|
1060 auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk());
|
|
1061 auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk());
|
|
1062 if (from && to)
|
|
1063 config->callGraphProfile[{from, to}] += count;
|
|
1064 }
|
|
1065 }
|
|
1066 }
|
150
|
1067 }
|
|
1068
|
|
1069 static void markAddrsig(Symbol *s) {
|
|
1070 if (auto *d = dyn_cast_or_null<Defined>(s))
|
|
1071 if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
|
|
1072 c->keepUnique = true;
|
|
1073 }
|
|
1074
|
|
1075 static void findKeepUniqueSections() {
|
|
1076 // Exported symbols could be address-significant in other executables or DSOs,
|
|
1077 // so we conservatively mark them as address-significant.
|
|
1078 for (Export &r : config->exports)
|
|
1079 markAddrsig(r.sym);
|
|
1080
|
|
1081 // Visit the address-significance table in each object file and mark each
|
|
1082 // referenced symbol as address-significant.
|
|
1083 for (ObjFile *obj : ObjFile::instances) {
|
|
1084 ArrayRef<Symbol *> syms = obj->getSymbols();
|
|
1085 if (obj->addrsigSec) {
|
|
1086 ArrayRef<uint8_t> contents;
|
|
1087 cantFail(
|
|
1088 obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
|
|
1089 const uint8_t *cur = contents.begin();
|
|
1090 while (cur != contents.end()) {
|
|
1091 unsigned size;
|
|
1092 const char *err;
|
|
1093 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
|
|
1094 if (err)
|
|
1095 fatal(toString(obj) + ": could not decode addrsig section: " + err);
|
|
1096 if (symIndex >= syms.size())
|
|
1097 fatal(toString(obj) + ": invalid symbol index in addrsig section");
|
|
1098 markAddrsig(syms[symIndex]);
|
|
1099 cur += size;
|
|
1100 }
|
|
1101 } else {
|
|
1102 // If an object file does not have an address-significance table,
|
|
1103 // conservatively mark all of its symbols as address-significant.
|
|
1104 for (Symbol *s : syms)
|
|
1105 markAddrsig(s);
|
|
1106 }
|
|
1107 }
|
|
1108 }
|
|
1109
|
|
1110 // link.exe replaces each %foo% in altPath with the contents of environment
|
|
1111 // variable foo, and adds the two magic env vars _PDB (expands to the basename
|
|
1112 // of pdb's output path) and _EXT (expands to the extension of the output
|
|
1113 // binary).
|
|
1114 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
|
|
1115 // vars.
|
|
1116 static void parsePDBAltPath(StringRef altPath) {
|
|
1117 SmallString<128> buf;
|
|
1118 StringRef pdbBasename =
|
|
1119 sys::path::filename(config->pdbPath, sys::path::Style::windows);
|
|
1120 StringRef binaryExtension =
|
|
1121 sys::path::extension(config->outputFile, sys::path::Style::windows);
|
|
1122 if (!binaryExtension.empty())
|
|
1123 binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
|
|
1124
|
|
1125 // Invariant:
|
|
1126 // +--------- cursor ('a...' might be the empty string).
|
|
1127 // | +----- firstMark
|
|
1128 // | | +- secondMark
|
|
1129 // v v v
|
|
1130 // a...%...%...
|
|
1131 size_t cursor = 0;
|
|
1132 while (cursor < altPath.size()) {
|
|
1133 size_t firstMark, secondMark;
|
|
1134 if ((firstMark = altPath.find('%', cursor)) == StringRef::npos ||
|
|
1135 (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) {
|
|
1136 // Didn't find another full fragment, treat rest of string as literal.
|
|
1137 buf.append(altPath.substr(cursor));
|
|
1138 break;
|
|
1139 }
|
|
1140
|
|
1141 // Found a full fragment. Append text in front of first %, and interpret
|
|
1142 // text between first and second % as variable name.
|
|
1143 buf.append(altPath.substr(cursor, firstMark - cursor));
|
|
1144 StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1);
|
|
1145 if (var.equals_lower("%_pdb%"))
|
|
1146 buf.append(pdbBasename);
|
|
1147 else if (var.equals_lower("%_ext%"))
|
|
1148 buf.append(binaryExtension);
|
|
1149 else {
|
|
1150 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " +
|
|
1151 var + " as literal");
|
|
1152 buf.append(var);
|
|
1153 }
|
|
1154
|
|
1155 cursor = secondMark + 1;
|
|
1156 }
|
|
1157
|
|
1158 config->pdbAltPath = buf;
|
|
1159 }
|
|
1160
|
|
1161 /// Convert resource files and potentially merge input resource object
|
|
1162 /// trees into one resource tree.
|
|
1163 /// Call after ObjFile::Instances is complete.
|
|
1164 void LinkerDriver::convertResources() {
|
|
1165 std::vector<ObjFile *> resourceObjFiles;
|
|
1166
|
|
1167 for (ObjFile *f : ObjFile::instances) {
|
|
1168 if (f->isResourceObjFile())
|
|
1169 resourceObjFiles.push_back(f);
|
|
1170 }
|
|
1171
|
|
1172 if (!config->mingw &&
|
|
1173 (resourceObjFiles.size() > 1 ||
|
|
1174 (resourceObjFiles.size() == 1 && !resources.empty()))) {
|
|
1175 error((!resources.empty() ? "internal .obj file created from .res files"
|
|
1176 : toString(resourceObjFiles[1])) +
|
|
1177 ": more than one resource obj file not allowed, already got " +
|
|
1178 toString(resourceObjFiles.front()));
|
|
1179 return;
|
|
1180 }
|
|
1181
|
|
1182 if (resources.empty() && resourceObjFiles.size() <= 1) {
|
|
1183 // No resources to convert, and max one resource object file in
|
|
1184 // the input. Keep that preconverted resource section as is.
|
|
1185 for (ObjFile *f : resourceObjFiles)
|
|
1186 f->includeResourceChunks();
|
|
1187 return;
|
|
1188 }
|
|
1189 ObjFile *f = make<ObjFile>(convertResToCOFF(resources, resourceObjFiles));
|
|
1190 symtab->addFile(f);
|
|
1191 f->includeResourceChunks();
|
|
1192 }
|
|
1193
|
|
1194 // In MinGW, if no symbols are chosen to be exported, then all symbols are
|
|
1195 // automatically exported by default. This behavior can be forced by the
|
|
1196 // -export-all-symbols option, so that it happens even when exports are
|
|
1197 // explicitly specified. The automatic behavior can be disabled using the
|
|
1198 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
|
|
1199 // than MinGW in the case that nothing is explicitly exported.
|
|
1200 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
|
|
1201 if (!config->dll)
|
|
1202 return;
|
|
1203
|
|
1204 if (!args.hasArg(OPT_export_all_symbols)) {
|
|
1205 if (!config->exports.empty())
|
|
1206 return;
|
|
1207 if (args.hasArg(OPT_exclude_all_symbols))
|
|
1208 return;
|
|
1209 }
|
|
1210
|
|
1211 AutoExporter exporter;
|
|
1212
|
|
1213 for (auto *arg : args.filtered(OPT_wholearchive_file))
|
|
1214 if (Optional<StringRef> path = doFindFile(arg->getValue()))
|
|
1215 exporter.addWholeArchive(*path);
|
|
1216
|
|
1217 symtab->forEachSymbol([&](Symbol *s) {
|
|
1218 auto *def = dyn_cast<Defined>(s);
|
|
1219 if (!exporter.shouldExport(def))
|
|
1220 return;
|
|
1221
|
207
|
1222 if (!def->isGCRoot) {
|
|
1223 def->isGCRoot = true;
|
|
1224 config->gcroot.push_back(def);
|
|
1225 }
|
|
1226
|
150
|
1227 Export e;
|
|
1228 e.name = def->getName();
|
|
1229 e.sym = def;
|
|
1230 if (Chunk *c = def->getChunk())
|
|
1231 if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
|
|
1232 e.data = true;
|
207
|
1233 s->isUsedInRegularObj = true;
|
150
|
1234 config->exports.push_back(e);
|
|
1235 });
|
|
1236 }
|
|
1237
|
|
1238 // lld has a feature to create a tar file containing all input files as well as
|
|
1239 // all command line options, so that other people can run lld again with exactly
|
|
1240 // the same inputs. This feature is accessible via /linkrepro and /reproduce.
|
|
1241 //
|
|
1242 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
|
|
1243 // name while /reproduce takes a full path. We have /linkrepro for compatibility
|
|
1244 // with Microsoft link.exe.
|
|
1245 Optional<std::string> getReproduceFile(const opt::InputArgList &args) {
|
|
1246 if (auto *arg = args.getLastArg(OPT_reproduce))
|
|
1247 return std::string(arg->getValue());
|
|
1248
|
|
1249 if (auto *arg = args.getLastArg(OPT_linkrepro)) {
|
|
1250 SmallString<64> path = StringRef(arg->getValue());
|
|
1251 sys::path::append(path, "repro.tar");
|
|
1252 return std::string(path);
|
|
1253 }
|
|
1254
|
207
|
1255 // This is intentionally not guarded by OPT_lldignoreenv since writing
|
|
1256 // a repro tar file doesn't affect the main output.
|
|
1257 if (auto *path = getenv("LLD_REPRODUCE"))
|
|
1258 return std::string(path);
|
|
1259
|
150
|
1260 return None;
|
|
1261 }
|
|
1262
|
207
|
1263 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
|
173
|
1264 ScopedTimer rootTimer(Timer::root());
|
|
1265
|
150
|
1266 // Needed for LTO.
|
|
1267 InitializeAllTargetInfos();
|
|
1268 InitializeAllTargets();
|
|
1269 InitializeAllTargetMCs();
|
|
1270 InitializeAllAsmParsers();
|
|
1271 InitializeAllAsmPrinters();
|
|
1272
|
|
1273 // If the first command line argument is "/lib", link.exe acts like lib.exe.
|
|
1274 // We call our own implementation of lib.exe that understands bitcode files.
|
207
|
1275 if (argsArr.size() > 1 && (StringRef(argsArr[1]).equals_lower("/lib") ||
|
|
1276 StringRef(argsArr[1]).equals_lower("-lib"))) {
|
150
|
1277 if (llvm::libDriverMain(argsArr.slice(1)) != 0)
|
|
1278 fatal("lib failed");
|
|
1279 return;
|
|
1280 }
|
|
1281
|
|
1282 // Parse command line options.
|
|
1283 ArgParser parser;
|
|
1284 opt::InputArgList args = parser.parse(argsArr);
|
|
1285
|
|
1286 // Parse and evaluate -mllvm options.
|
|
1287 std::vector<const char *> v;
|
|
1288 v.push_back("lld-link (LLVM option parsing)");
|
|
1289 for (auto *arg : args.filtered(OPT_mllvm))
|
|
1290 v.push_back(arg->getValue());
|
207
|
1291 cl::ResetAllOptionOccurrences();
|
150
|
1292 cl::ParseCommandLineOptions(v.size(), v.data());
|
|
1293
|
|
1294 // Handle /errorlimit early, because error() depends on it.
|
|
1295 if (auto *arg = args.getLastArg(OPT_errorlimit)) {
|
|
1296 int n = 20;
|
|
1297 StringRef s = arg->getValue();
|
|
1298 if (s.getAsInteger(10, n))
|
|
1299 error(arg->getSpelling() + " number expected, but got " + s);
|
|
1300 errorHandler().errorLimit = n;
|
|
1301 }
|
|
1302
|
|
1303 // Handle /help
|
|
1304 if (args.hasArg(OPT_help)) {
|
|
1305 printHelp(argsArr[0]);
|
|
1306 return;
|
|
1307 }
|
|
1308
|
173
|
1309 // /threads: takes a positive integer and provides the default value for
|
|
1310 // /opt:lldltojobs=.
|
|
1311 if (auto *arg = args.getLastArg(OPT_threads)) {
|
|
1312 StringRef v(arg->getValue());
|
|
1313 unsigned threads = 0;
|
|
1314 if (!llvm::to_integer(v, threads, 0) || threads == 0)
|
|
1315 error(arg->getSpelling() + ": expected a positive integer, but got '" +
|
|
1316 arg->getValue() + "'");
|
|
1317 parallel::strategy = hardware_concurrency(threads);
|
|
1318 config->thinLTOJobs = v.str();
|
|
1319 }
|
150
|
1320
|
|
1321 if (args.hasArg(OPT_show_timing))
|
|
1322 config->showTiming = true;
|
|
1323
|
|
1324 config->showSummary = args.hasArg(OPT_summary);
|
|
1325
|
|
1326 // Handle --version, which is an lld extension. This option is a bit odd
|
|
1327 // because it doesn't start with "/", but we deliberately chose "--" to
|
|
1328 // avoid conflict with /version and for compatibility with clang-cl.
|
|
1329 if (args.hasArg(OPT_dash_dash_version)) {
|
207
|
1330 message(getLLDVersion());
|
150
|
1331 return;
|
|
1332 }
|
|
1333
|
|
1334 // Handle /lldmingw early, since it can potentially affect how other
|
|
1335 // options are handled.
|
|
1336 config->mingw = args.hasArg(OPT_lldmingw);
|
|
1337
|
|
1338 // Handle /linkrepro and /reproduce.
|
|
1339 if (Optional<std::string> path = getReproduceFile(args)) {
|
|
1340 Expected<std::unique_ptr<TarWriter>> errOrWriter =
|
|
1341 TarWriter::create(*path, sys::path::stem(*path));
|
|
1342
|
|
1343 if (errOrWriter) {
|
|
1344 tar = std::move(*errOrWriter);
|
|
1345 } else {
|
|
1346 error("/linkrepro: failed to open " + *path + ": " +
|
|
1347 toString(errOrWriter.takeError()));
|
|
1348 }
|
|
1349 }
|
|
1350
|
|
1351 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
|
|
1352 if (args.hasArg(OPT_deffile))
|
|
1353 config->noEntry = true;
|
|
1354 else
|
|
1355 fatal("no input files");
|
|
1356 }
|
|
1357
|
|
1358 // Construct search path list.
|
|
1359 searchPaths.push_back("");
|
|
1360 for (auto *arg : args.filtered(OPT_libpath))
|
|
1361 searchPaths.push_back(arg->getValue());
|
|
1362 if (!args.hasArg(OPT_lldignoreenv))
|
|
1363 addLibSearchPaths();
|
|
1364
|
|
1365 // Handle /ignore
|
|
1366 for (auto *arg : args.filtered(OPT_ignore)) {
|
|
1367 SmallVector<StringRef, 8> vec;
|
|
1368 StringRef(arg->getValue()).split(vec, ',');
|
|
1369 for (StringRef s : vec) {
|
|
1370 if (s == "4037")
|
|
1371 config->warnMissingOrderSymbol = false;
|
|
1372 else if (s == "4099")
|
|
1373 config->warnDebugInfoUnusable = false;
|
|
1374 else if (s == "4217")
|
|
1375 config->warnLocallyDefinedImported = false;
|
|
1376 else if (s == "longsections")
|
|
1377 config->warnLongSectionNames = false;
|
|
1378 // Other warning numbers are ignored.
|
|
1379 }
|
|
1380 }
|
|
1381
|
|
1382 // Handle /out
|
|
1383 if (auto *arg = args.getLastArg(OPT_out))
|
|
1384 config->outputFile = arg->getValue();
|
|
1385
|
|
1386 // Handle /verbose
|
|
1387 if (args.hasArg(OPT_verbose))
|
|
1388 config->verbose = true;
|
|
1389 errorHandler().verbose = config->verbose;
|
|
1390
|
|
1391 // Handle /force or /force:unresolved
|
|
1392 if (args.hasArg(OPT_force, OPT_force_unresolved))
|
|
1393 config->forceUnresolved = true;
|
|
1394
|
|
1395 // Handle /force or /force:multiple
|
|
1396 if (args.hasArg(OPT_force, OPT_force_multiple))
|
|
1397 config->forceMultiple = true;
|
|
1398
|
|
1399 // Handle /force or /force:multipleres
|
|
1400 if (args.hasArg(OPT_force, OPT_force_multipleres))
|
|
1401 config->forceMultipleRes = true;
|
|
1402
|
|
1403 // Handle /debug
|
|
1404 DebugKind debug = parseDebugKind(args);
|
|
1405 if (debug == DebugKind::Full || debug == DebugKind::Dwarf ||
|
207
|
1406 debug == DebugKind::GHash || debug == DebugKind::NoGHash) {
|
150
|
1407 config->debug = true;
|
|
1408 config->incremental = true;
|
|
1409 }
|
|
1410
|
|
1411 // Handle /demangle
|
|
1412 config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no);
|
|
1413
|
|
1414 // Handle /debugtype
|
|
1415 config->debugTypes = parseDebugTypes(args);
|
|
1416
|
|
1417 // Handle /driver[:uponly|:wdm].
|
|
1418 config->driverUponly = args.hasArg(OPT_driver_uponly) ||
|
|
1419 args.hasArg(OPT_driver_uponly_wdm) ||
|
|
1420 args.hasArg(OPT_driver_wdm_uponly);
|
|
1421 config->driverWdm = args.hasArg(OPT_driver_wdm) ||
|
|
1422 args.hasArg(OPT_driver_uponly_wdm) ||
|
|
1423 args.hasArg(OPT_driver_wdm_uponly);
|
|
1424 config->driver =
|
|
1425 config->driverUponly || config->driverWdm || args.hasArg(OPT_driver);
|
|
1426
|
|
1427 // Handle /pdb
|
|
1428 bool shouldCreatePDB =
|
207
|
1429 (debug == DebugKind::Full || debug == DebugKind::GHash ||
|
|
1430 debug == DebugKind::NoGHash);
|
150
|
1431 if (shouldCreatePDB) {
|
|
1432 if (auto *arg = args.getLastArg(OPT_pdb))
|
|
1433 config->pdbPath = arg->getValue();
|
|
1434 if (auto *arg = args.getLastArg(OPT_pdbaltpath))
|
|
1435 config->pdbAltPath = arg->getValue();
|
|
1436 if (args.hasArg(OPT_natvis))
|
|
1437 config->natvisFiles = args.getAllArgValues(OPT_natvis);
|
173
|
1438 if (args.hasArg(OPT_pdbstream)) {
|
|
1439 for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) {
|
|
1440 const std::pair<StringRef, StringRef> nameFile = value.split("=");
|
|
1441 const StringRef name = nameFile.first;
|
|
1442 const std::string file = nameFile.second.str();
|
|
1443 config->namedStreams[name] = file;
|
|
1444 }
|
|
1445 }
|
150
|
1446
|
|
1447 if (auto *arg = args.getLastArg(OPT_pdb_source_path))
|
|
1448 config->pdbSourcePath = arg->getValue();
|
|
1449 }
|
|
1450
|
|
1451 // Handle /pdbstripped
|
|
1452 if (args.hasArg(OPT_pdbstripped))
|
|
1453 warn("ignoring /pdbstripped flag, it is not yet supported");
|
|
1454
|
|
1455 // Handle /noentry
|
|
1456 if (args.hasArg(OPT_noentry)) {
|
|
1457 if (args.hasArg(OPT_dll))
|
|
1458 config->noEntry = true;
|
|
1459 else
|
|
1460 error("/noentry must be specified with /dll");
|
|
1461 }
|
|
1462
|
|
1463 // Handle /dll
|
|
1464 if (args.hasArg(OPT_dll)) {
|
|
1465 config->dll = true;
|
|
1466 config->manifestID = 2;
|
|
1467 }
|
|
1468
|
|
1469 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
|
|
1470 // because we need to explicitly check whether that option or its inverse was
|
|
1471 // present in the argument list in order to handle /fixed.
|
|
1472 auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
|
|
1473 if (dynamicBaseArg &&
|
|
1474 dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
|
|
1475 config->dynamicBase = false;
|
|
1476
|
|
1477 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
|
|
1478 // default setting for any other project type.", but link.exe defaults to
|
|
1479 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
|
|
1480 bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
|
|
1481 if (fixed) {
|
|
1482 if (dynamicBaseArg &&
|
|
1483 dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
|
|
1484 error("/fixed must not be specified with /dynamicbase");
|
|
1485 } else {
|
|
1486 config->relocatable = false;
|
|
1487 config->dynamicBase = false;
|
|
1488 }
|
|
1489 }
|
|
1490
|
|
1491 // Handle /appcontainer
|
|
1492 config->appContainer =
|
|
1493 args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
|
|
1494
|
|
1495 // Handle /machine
|
|
1496 if (auto *arg = args.getLastArg(OPT_machine)) {
|
|
1497 config->machine = getMachineType(arg->getValue());
|
|
1498 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
|
|
1499 fatal(Twine("unknown /machine argument: ") + arg->getValue());
|
|
1500 }
|
|
1501
|
|
1502 // Handle /nodefaultlib:<filename>
|
|
1503 for (auto *arg : args.filtered(OPT_nodefaultlib))
|
|
1504 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
|
|
1505
|
|
1506 // Handle /nodefaultlib
|
|
1507 if (args.hasArg(OPT_nodefaultlib_all))
|
|
1508 config->noDefaultLibAll = true;
|
|
1509
|
|
1510 // Handle /base
|
|
1511 if (auto *arg = args.getLastArg(OPT_base))
|
|
1512 parseNumbers(arg->getValue(), &config->imageBase);
|
|
1513
|
|
1514 // Handle /filealign
|
|
1515 if (auto *arg = args.getLastArg(OPT_filealign)) {
|
|
1516 parseNumbers(arg->getValue(), &config->fileAlign);
|
|
1517 if (!isPowerOf2_64(config->fileAlign))
|
|
1518 error("/filealign: not a power of two: " + Twine(config->fileAlign));
|
|
1519 }
|
|
1520
|
|
1521 // Handle /stack
|
|
1522 if (auto *arg = args.getLastArg(OPT_stack))
|
|
1523 parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
|
|
1524
|
|
1525 // Handle /guard:cf
|
|
1526 if (auto *arg = args.getLastArg(OPT_guard))
|
|
1527 parseGuard(arg->getValue());
|
|
1528
|
|
1529 // Handle /heap
|
|
1530 if (auto *arg = args.getLastArg(OPT_heap))
|
|
1531 parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
|
|
1532
|
|
1533 // Handle /version
|
|
1534 if (auto *arg = args.getLastArg(OPT_version))
|
|
1535 parseVersion(arg->getValue(), &config->majorImageVersion,
|
|
1536 &config->minorImageVersion);
|
|
1537
|
|
1538 // Handle /subsystem
|
|
1539 if (auto *arg = args.getLastArg(OPT_subsystem))
|
207
|
1540 parseSubsystem(arg->getValue(), &config->subsystem,
|
|
1541 &config->majorSubsystemVersion,
|
|
1542 &config->minorSubsystemVersion);
|
|
1543
|
|
1544 // Handle /osversion
|
|
1545 if (auto *arg = args.getLastArg(OPT_osversion)) {
|
|
1546 parseVersion(arg->getValue(), &config->majorOSVersion,
|
|
1547 &config->minorOSVersion);
|
|
1548 } else {
|
|
1549 config->majorOSVersion = config->majorSubsystemVersion;
|
|
1550 config->minorOSVersion = config->minorSubsystemVersion;
|
|
1551 }
|
150
|
1552
|
|
1553 // Handle /timestamp
|
|
1554 if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
|
|
1555 if (arg->getOption().getID() == OPT_repro) {
|
|
1556 config->timestamp = 0;
|
|
1557 config->repro = true;
|
|
1558 } else {
|
|
1559 config->repro = false;
|
|
1560 StringRef value(arg->getValue());
|
|
1561 if (value.getAsInteger(0, config->timestamp))
|
|
1562 fatal(Twine("invalid timestamp: ") + value +
|
|
1563 ". Expected 32-bit integer");
|
|
1564 }
|
|
1565 } else {
|
|
1566 config->repro = false;
|
|
1567 config->timestamp = time(nullptr);
|
|
1568 }
|
|
1569
|
|
1570 // Handle /alternatename
|
|
1571 for (auto *arg : args.filtered(OPT_alternatename))
|
|
1572 parseAlternateName(arg->getValue());
|
|
1573
|
|
1574 // Handle /include
|
|
1575 for (auto *arg : args.filtered(OPT_incl))
|
|
1576 addUndefined(arg->getValue());
|
|
1577
|
|
1578 // Handle /implib
|
|
1579 if (auto *arg = args.getLastArg(OPT_implib))
|
|
1580 config->implib = arg->getValue();
|
|
1581
|
|
1582 // Handle /opt.
|
|
1583 bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile);
|
207
|
1584 Optional<ICFLevel> icfLevel = None;
|
|
1585 if (args.hasArg(OPT_profile))
|
|
1586 icfLevel = ICFLevel::None;
|
150
|
1587 unsigned tailMerge = 1;
|
207
|
1588 bool ltoNewPM = LLVM_ENABLE_NEW_PASS_MANAGER;
|
|
1589 bool ltoDebugPM = false;
|
150
|
1590 for (auto *arg : args.filtered(OPT_opt)) {
|
|
1591 std::string str = StringRef(arg->getValue()).lower();
|
|
1592 SmallVector<StringRef, 1> vec;
|
|
1593 StringRef(str).split(vec, ',');
|
|
1594 for (StringRef s : vec) {
|
|
1595 if (s == "ref") {
|
|
1596 doGC = true;
|
|
1597 } else if (s == "noref") {
|
|
1598 doGC = false;
|
|
1599 } else if (s == "icf" || s.startswith("icf=")) {
|
207
|
1600 icfLevel = ICFLevel::All;
|
|
1601 } else if (s == "safeicf") {
|
|
1602 icfLevel = ICFLevel::Safe;
|
150
|
1603 } else if (s == "noicf") {
|
207
|
1604 icfLevel = ICFLevel::None;
|
150
|
1605 } else if (s == "lldtailmerge") {
|
|
1606 tailMerge = 2;
|
|
1607 } else if (s == "nolldtailmerge") {
|
|
1608 tailMerge = 0;
|
207
|
1609 } else if (s == "ltonewpassmanager") {
|
|
1610 ltoNewPM = true;
|
|
1611 } else if (s == "noltonewpassmanager") {
|
|
1612 ltoNewPM = false;
|
|
1613 } else if (s == "ltodebugpassmanager") {
|
|
1614 ltoDebugPM = true;
|
|
1615 } else if (s == "noltodebugpassmanager") {
|
|
1616 ltoDebugPM = false;
|
150
|
1617 } else if (s.startswith("lldlto=")) {
|
|
1618 StringRef optLevel = s.substr(7);
|
|
1619 if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3)
|
|
1620 error("/opt:lldlto: invalid optimization level: " + optLevel);
|
|
1621 } else if (s.startswith("lldltojobs=")) {
|
|
1622 StringRef jobs = s.substr(11);
|
173
|
1623 if (!get_threadpool_strategy(jobs))
|
150
|
1624 error("/opt:lldltojobs: invalid job count: " + jobs);
|
173
|
1625 config->thinLTOJobs = jobs.str();
|
150
|
1626 } else if (s.startswith("lldltopartitions=")) {
|
|
1627 StringRef n = s.substr(17);
|
|
1628 if (n.getAsInteger(10, config->ltoPartitions) ||
|
|
1629 config->ltoPartitions == 0)
|
|
1630 error("/opt:lldltopartitions: invalid partition count: " + n);
|
|
1631 } else if (s != "lbr" && s != "nolbr")
|
|
1632 error("/opt: unknown option: " + s);
|
|
1633 }
|
|
1634 }
|
|
1635
|
207
|
1636 if (!icfLevel)
|
|
1637 icfLevel = doGC ? ICFLevel::All : ICFLevel::None;
|
150
|
1638 config->doGC = doGC;
|
207
|
1639 config->doICF = icfLevel.getValue();
|
|
1640 config->tailMerge =
|
|
1641 (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2;
|
|
1642 config->ltoNewPassManager = ltoNewPM;
|
|
1643 config->ltoDebugPassManager = ltoDebugPM;
|
150
|
1644
|
|
1645 // Handle /lldsavetemps
|
|
1646 if (args.hasArg(OPT_lldsavetemps))
|
|
1647 config->saveTemps = true;
|
|
1648
|
|
1649 // Handle /kill-at
|
|
1650 if (args.hasArg(OPT_kill_at))
|
|
1651 config->killAt = true;
|
|
1652
|
|
1653 // Handle /lldltocache
|
|
1654 if (auto *arg = args.getLastArg(OPT_lldltocache))
|
|
1655 config->ltoCache = arg->getValue();
|
|
1656
|
|
1657 // Handle /lldsavecachepolicy
|
|
1658 if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
|
|
1659 config->ltoCachePolicy = CHECK(
|
|
1660 parseCachePruningPolicy(arg->getValue()),
|
|
1661 Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
|
|
1662
|
|
1663 // Handle /failifmismatch
|
|
1664 for (auto *arg : args.filtered(OPT_failifmismatch))
|
|
1665 checkFailIfMismatch(arg->getValue(), nullptr);
|
|
1666
|
|
1667 // Handle /merge
|
|
1668 for (auto *arg : args.filtered(OPT_merge))
|
|
1669 parseMerge(arg->getValue());
|
|
1670
|
|
1671 // Add default section merging rules after user rules. User rules take
|
|
1672 // precedence, but we will emit a warning if there is a conflict.
|
|
1673 parseMerge(".idata=.rdata");
|
|
1674 parseMerge(".didat=.rdata");
|
|
1675 parseMerge(".edata=.rdata");
|
|
1676 parseMerge(".xdata=.rdata");
|
|
1677 parseMerge(".bss=.data");
|
|
1678
|
|
1679 if (config->mingw) {
|
|
1680 parseMerge(".ctors=.rdata");
|
|
1681 parseMerge(".dtors=.rdata");
|
|
1682 parseMerge(".CRT=.rdata");
|
|
1683 }
|
|
1684
|
|
1685 // Handle /section
|
|
1686 for (auto *arg : args.filtered(OPT_section))
|
|
1687 parseSection(arg->getValue());
|
|
1688
|
|
1689 // Handle /align
|
|
1690 if (auto *arg = args.getLastArg(OPT_align)) {
|
|
1691 parseNumbers(arg->getValue(), &config->align);
|
|
1692 if (!isPowerOf2_64(config->align))
|
|
1693 error("/align: not a power of two: " + StringRef(arg->getValue()));
|
|
1694 if (!args.hasArg(OPT_driver))
|
|
1695 warn("/align specified without /driver; image may not run");
|
|
1696 }
|
|
1697
|
|
1698 // Handle /aligncomm
|
|
1699 for (auto *arg : args.filtered(OPT_aligncomm))
|
|
1700 parseAligncomm(arg->getValue());
|
|
1701
|
|
1702 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
|
|
1703 // also passed.
|
|
1704 if (auto *arg = args.getLastArg(OPT_manifestdependency)) {
|
|
1705 config->manifestDependency = arg->getValue();
|
|
1706 config->manifest = Configuration::SideBySide;
|
|
1707 }
|
|
1708
|
|
1709 // Handle /manifest and /manifest:
|
|
1710 if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
|
|
1711 if (arg->getOption().getID() == OPT_manifest)
|
|
1712 config->manifest = Configuration::SideBySide;
|
|
1713 else
|
|
1714 parseManifest(arg->getValue());
|
|
1715 }
|
|
1716
|
|
1717 // Handle /manifestuac
|
|
1718 if (auto *arg = args.getLastArg(OPT_manifestuac))
|
|
1719 parseManifestUAC(arg->getValue());
|
|
1720
|
|
1721 // Handle /manifestfile
|
|
1722 if (auto *arg = args.getLastArg(OPT_manifestfile))
|
|
1723 config->manifestFile = arg->getValue();
|
|
1724
|
|
1725 // Handle /manifestinput
|
|
1726 for (auto *arg : args.filtered(OPT_manifestinput))
|
|
1727 config->manifestInput.push_back(arg->getValue());
|
|
1728
|
|
1729 if (!config->manifestInput.empty() &&
|
|
1730 config->manifest != Configuration::Embed) {
|
|
1731 fatal("/manifestinput: requires /manifest:embed");
|
|
1732 }
|
|
1733
|
|
1734 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
|
|
1735 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
|
|
1736 args.hasArg(OPT_thinlto_index_only_arg);
|
|
1737 config->thinLTOIndexOnlyArg =
|
|
1738 args.getLastArgValue(OPT_thinlto_index_only_arg);
|
|
1739 config->thinLTOPrefixReplace =
|
|
1740 getOldNewOptions(args, OPT_thinlto_prefix_replace);
|
|
1741 config->thinLTOObjectSuffixReplace =
|
|
1742 getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
|
|
1743 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path);
|
207
|
1744 config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
|
|
1745 config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
|
150
|
1746 // Handle miscellaneous boolean flags.
|
|
1747 config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
|
|
1748 config->allowIsolation =
|
|
1749 args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
|
|
1750 config->incremental =
|
|
1751 args.hasFlag(OPT_incremental, OPT_incremental_no,
|
207
|
1752 !config->doGC && config->doICF == ICFLevel::None &&
|
|
1753 !args.hasArg(OPT_order) && !args.hasArg(OPT_profile));
|
150
|
1754 config->integrityCheck =
|
|
1755 args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
|
173
|
1756 config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false);
|
150
|
1757 config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
|
|
1758 for (auto *arg : args.filtered(OPT_swaprun))
|
|
1759 parseSwaprun(arg->getValue());
|
|
1760 config->terminalServerAware =
|
|
1761 !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
|
|
1762 config->debugDwarf = debug == DebugKind::Dwarf;
|
207
|
1763 config->debugGHashes = debug == DebugKind::GHash || debug == DebugKind::Full;
|
150
|
1764 config->debugSymtab = debug == DebugKind::Symtab;
|
173
|
1765 config->autoImport =
|
|
1766 args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw);
|
|
1767 config->pseudoRelocs = args.hasFlag(
|
|
1768 OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw);
|
207
|
1769 config->callGraphProfileSort = args.hasFlag(
|
|
1770 OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true);
|
150
|
1771
|
207
|
1772 // Don't warn about long section names, such as .debug_info, for mingw or
|
|
1773 // when -debug:dwarf is requested.
|
150
|
1774 if (config->mingw || config->debugDwarf)
|
|
1775 config->warnLongSectionNames = false;
|
|
1776
|
173
|
1777 config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file);
|
|
1778 config->mapFile = getMapFile(args, OPT_map, OPT_map_file);
|
|
1779
|
|
1780 if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) {
|
|
1781 warn("/lldmap and /map have the same output file '" + config->mapFile +
|
|
1782 "'.\n>>> ignoring /lldmap");
|
|
1783 config->lldmapFile.clear();
|
|
1784 }
|
150
|
1785
|
|
1786 if (config->incremental && args.hasArg(OPT_profile)) {
|
|
1787 warn("ignoring '/incremental' due to '/profile' specification");
|
|
1788 config->incremental = false;
|
|
1789 }
|
|
1790
|
|
1791 if (config->incremental && args.hasArg(OPT_order)) {
|
|
1792 warn("ignoring '/incremental' due to '/order' specification");
|
|
1793 config->incremental = false;
|
|
1794 }
|
|
1795
|
|
1796 if (config->incremental && config->doGC) {
|
|
1797 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
|
|
1798 "disable");
|
|
1799 config->incremental = false;
|
|
1800 }
|
|
1801
|
207
|
1802 if (config->incremental && config->doICF != ICFLevel::None) {
|
150
|
1803 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
|
|
1804 "disable");
|
|
1805 config->incremental = false;
|
|
1806 }
|
|
1807
|
|
1808 if (errorCount())
|
|
1809 return;
|
|
1810
|
|
1811 std::set<sys::fs::UniqueID> wholeArchives;
|
|
1812 for (auto *arg : args.filtered(OPT_wholearchive_file))
|
|
1813 if (Optional<StringRef> path = doFindFile(arg->getValue()))
|
|
1814 if (Optional<sys::fs::UniqueID> id = getUniqueID(*path))
|
|
1815 wholeArchives.insert(*id);
|
|
1816
|
|
1817 // A predicate returning true if a given path is an argument for
|
|
1818 // /wholearchive:, or /wholearchive is enabled globally.
|
|
1819 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
|
|
1820 // needs to be handled as "/wholearchive:foo.obj foo.obj".
|
|
1821 auto isWholeArchive = [&](StringRef path) -> bool {
|
|
1822 if (args.hasArg(OPT_wholearchive_flag))
|
|
1823 return true;
|
|
1824 if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
|
|
1825 return wholeArchives.count(*id);
|
|
1826 return false;
|
|
1827 };
|
|
1828
|
|
1829 // Create a list of input files. These can be given as OPT_INPUT options
|
|
1830 // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
|
|
1831 // and OPT_end_lib.
|
|
1832 bool inLib = false;
|
|
1833 for (auto *arg : args) {
|
|
1834 switch (arg->getOption().getID()) {
|
|
1835 case OPT_end_lib:
|
|
1836 if (!inLib)
|
|
1837 error("stray " + arg->getSpelling());
|
|
1838 inLib = false;
|
|
1839 break;
|
|
1840 case OPT_start_lib:
|
|
1841 if (inLib)
|
|
1842 error("nested " + arg->getSpelling());
|
|
1843 inLib = true;
|
|
1844 break;
|
|
1845 case OPT_wholearchive_file:
|
|
1846 if (Optional<StringRef> path = findFile(arg->getValue()))
|
|
1847 enqueuePath(*path, true, inLib);
|
|
1848 break;
|
|
1849 case OPT_INPUT:
|
|
1850 if (Optional<StringRef> path = findFile(arg->getValue()))
|
|
1851 enqueuePath(*path, isWholeArchive(*path), inLib);
|
|
1852 break;
|
|
1853 default:
|
|
1854 // Ignore other options.
|
|
1855 break;
|
|
1856 }
|
|
1857 }
|
|
1858
|
|
1859 // Process files specified as /defaultlib. These should be enequeued after
|
|
1860 // other files, which is why they are in a separate loop.
|
|
1861 for (auto *arg : args.filtered(OPT_defaultlib))
|
|
1862 if (Optional<StringRef> path = findLib(arg->getValue()))
|
|
1863 enqueuePath(*path, false, false);
|
|
1864
|
|
1865 // Windows specific -- Create a resource file containing a manifest file.
|
|
1866 if (config->manifest == Configuration::Embed)
|
|
1867 addBuffer(createManifestRes(), false, false);
|
|
1868
|
|
1869 // Read all input files given via the command line.
|
|
1870 run();
|
|
1871
|
|
1872 if (errorCount())
|
|
1873 return;
|
|
1874
|
|
1875 // We should have inferred a machine type by now from the input files, but if
|
|
1876 // not we assume x64.
|
|
1877 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
|
|
1878 warn("/machine is not specified. x64 is assumed");
|
|
1879 config->machine = AMD64;
|
|
1880 }
|
|
1881 config->wordsize = config->is64() ? 8 : 4;
|
|
1882
|
|
1883 // Handle /safeseh, x86 only, on by default, except for mingw.
|
207
|
1884 if (config->machine == I386) {
|
|
1885 config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw);
|
|
1886 config->noSEH = args.hasArg(OPT_noseh);
|
|
1887 }
|
150
|
1888
|
|
1889 // Handle /functionpadmin
|
|
1890 for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
|
|
1891 parseFunctionPadMin(arg, config->machine);
|
|
1892
|
|
1893 if (tar)
|
|
1894 tar->append("response.txt",
|
|
1895 createResponseFile(args, filePaths,
|
|
1896 ArrayRef<StringRef>(searchPaths).slice(1)));
|
|
1897
|
|
1898 // Handle /largeaddressaware
|
|
1899 config->largeAddressAware = args.hasFlag(
|
|
1900 OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
|
|
1901
|
|
1902 // Handle /highentropyva
|
|
1903 config->highEntropyVA =
|
|
1904 config->is64() &&
|
|
1905 args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
|
|
1906
|
|
1907 if (!config->dynamicBase &&
|
|
1908 (config->machine == ARMNT || config->machine == ARM64))
|
|
1909 error("/dynamicbase:no is not compatible with " +
|
|
1910 machineToStr(config->machine));
|
|
1911
|
|
1912 // Handle /export
|
|
1913 for (auto *arg : args.filtered(OPT_export)) {
|
|
1914 Export e = parseExport(arg->getValue());
|
|
1915 if (config->machine == I386) {
|
|
1916 if (!isDecorated(e.name))
|
|
1917 e.name = saver.save("_" + e.name);
|
|
1918 if (!e.extName.empty() && !isDecorated(e.extName))
|
|
1919 e.extName = saver.save("_" + e.extName);
|
|
1920 }
|
|
1921 config->exports.push_back(e);
|
|
1922 }
|
|
1923
|
|
1924 // Handle /def
|
|
1925 if (auto *arg = args.getLastArg(OPT_deffile)) {
|
|
1926 // parseModuleDefs mutates Config object.
|
|
1927 parseModuleDefs(arg->getValue());
|
|
1928 }
|
|
1929
|
|
1930 // Handle generation of import library from a def file.
|
|
1931 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
|
|
1932 fixupExports();
|
|
1933 createImportLibrary(/*asLib=*/true);
|
|
1934 return;
|
|
1935 }
|
|
1936
|
|
1937 // Windows specific -- if no /subsystem is given, we need to infer
|
|
1938 // that from entry point name. Must happen before /entry handling,
|
|
1939 // and after the early return when just writing an import library.
|
|
1940 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
|
|
1941 config->subsystem = inferSubsystem();
|
|
1942 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
|
|
1943 fatal("subsystem must be defined");
|
|
1944 }
|
|
1945
|
|
1946 // Handle /entry and /dll
|
|
1947 if (auto *arg = args.getLastArg(OPT_entry)) {
|
|
1948 config->entry = addUndefined(mangle(arg->getValue()));
|
|
1949 } else if (!config->entry && !config->noEntry) {
|
|
1950 if (args.hasArg(OPT_dll)) {
|
|
1951 StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
|
|
1952 : "_DllMainCRTStartup";
|
|
1953 config->entry = addUndefined(s);
|
|
1954 } else if (config->driverWdm) {
|
|
1955 // /driver:wdm implies /entry:_NtProcessStartup
|
|
1956 config->entry = addUndefined(mangle("_NtProcessStartup"));
|
|
1957 } else {
|
|
1958 // Windows specific -- If entry point name is not given, we need to
|
|
1959 // infer that from user-defined entry name.
|
|
1960 StringRef s = findDefaultEntry();
|
|
1961 if (s.empty())
|
|
1962 fatal("entry point must be defined");
|
|
1963 config->entry = addUndefined(s);
|
|
1964 log("Entry name inferred: " + s);
|
|
1965 }
|
|
1966 }
|
|
1967
|
|
1968 // Handle /delayload
|
|
1969 for (auto *arg : args.filtered(OPT_delayload)) {
|
|
1970 config->delayLoads.insert(StringRef(arg->getValue()).lower());
|
|
1971 if (config->machine == I386) {
|
|
1972 config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
|
|
1973 } else {
|
|
1974 config->delayLoadHelper = addUndefined("__delayLoadHelper2");
|
|
1975 }
|
|
1976 }
|
|
1977
|
|
1978 // Set default image name if neither /out or /def set it.
|
|
1979 if (config->outputFile.empty()) {
|
|
1980 config->outputFile = getOutputPath(
|
|
1981 (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue());
|
|
1982 }
|
|
1983
|
|
1984 // Fail early if an output file is not writable.
|
|
1985 if (auto e = tryCreateFile(config->outputFile)) {
|
|
1986 error("cannot open output file " + config->outputFile + ": " + e.message());
|
|
1987 return;
|
|
1988 }
|
|
1989
|
|
1990 if (shouldCreatePDB) {
|
|
1991 // Put the PDB next to the image if no /pdb flag was passed.
|
|
1992 if (config->pdbPath.empty()) {
|
|
1993 config->pdbPath = config->outputFile;
|
|
1994 sys::path::replace_extension(config->pdbPath, ".pdb");
|
|
1995 }
|
|
1996
|
|
1997 // The embedded PDB path should be the absolute path to the PDB if no
|
|
1998 // /pdbaltpath flag was passed.
|
|
1999 if (config->pdbAltPath.empty()) {
|
|
2000 config->pdbAltPath = config->pdbPath;
|
|
2001
|
|
2002 // It's important to make the path absolute and remove dots. This path
|
|
2003 // will eventually be written into the PE header, and certain Microsoft
|
|
2004 // tools won't work correctly if these assumptions are not held.
|
|
2005 sys::fs::make_absolute(config->pdbAltPath);
|
|
2006 sys::path::remove_dots(config->pdbAltPath);
|
|
2007 } else {
|
|
2008 // Don't do this earlier, so that Config->OutputFile is ready.
|
|
2009 parsePDBAltPath(config->pdbAltPath);
|
|
2010 }
|
|
2011 }
|
|
2012
|
|
2013 // Set default image base if /base is not given.
|
|
2014 if (config->imageBase == uint64_t(-1))
|
|
2015 config->imageBase = getDefaultImageBase();
|
|
2016
|
|
2017 symtab->addSynthetic(mangle("__ImageBase"), nullptr);
|
|
2018 if (config->machine == I386) {
|
|
2019 symtab->addAbsolute("___safe_se_handler_table", 0);
|
|
2020 symtab->addAbsolute("___safe_se_handler_count", 0);
|
|
2021 }
|
|
2022
|
|
2023 symtab->addAbsolute(mangle("__guard_fids_count"), 0);
|
|
2024 symtab->addAbsolute(mangle("__guard_fids_table"), 0);
|
|
2025 symtab->addAbsolute(mangle("__guard_flags"), 0);
|
|
2026 symtab->addAbsolute(mangle("__guard_iat_count"), 0);
|
|
2027 symtab->addAbsolute(mangle("__guard_iat_table"), 0);
|
|
2028 symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
|
|
2029 symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
|
|
2030 // Needed for MSVC 2017 15.5 CRT.
|
|
2031 symtab->addAbsolute(mangle("__enclave_config"), 0);
|
207
|
2032 // Needed for MSVC 2019 16.8 CRT.
|
|
2033 symtab->addAbsolute(mangle("__guard_eh_cont_count"), 0);
|
|
2034 symtab->addAbsolute(mangle("__guard_eh_cont_table"), 0);
|
150
|
2035
|
173
|
2036 if (config->pseudoRelocs) {
|
150
|
2037 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
|
|
2038 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
|
173
|
2039 }
|
|
2040 if (config->mingw) {
|
150
|
2041 symtab->addAbsolute(mangle("__CTOR_LIST__"), 0);
|
|
2042 symtab->addAbsolute(mangle("__DTOR_LIST__"), 0);
|
|
2043 }
|
|
2044
|
|
2045 // This code may add new undefined symbols to the link, which may enqueue more
|
|
2046 // symbol resolution tasks, so we need to continue executing tasks until we
|
|
2047 // converge.
|
|
2048 do {
|
|
2049 // Windows specific -- if entry point is not found,
|
|
2050 // search for its mangled names.
|
|
2051 if (config->entry)
|
|
2052 mangleMaybe(config->entry);
|
|
2053
|
|
2054 // Windows specific -- Make sure we resolve all dllexported symbols.
|
|
2055 for (Export &e : config->exports) {
|
|
2056 if (!e.forwardTo.empty())
|
|
2057 continue;
|
|
2058 e.sym = addUndefined(e.name);
|
|
2059 if (!e.directives)
|
|
2060 e.symbolName = mangleMaybe(e.sym);
|
|
2061 }
|
|
2062
|
|
2063 // Add weak aliases. Weak aliases is a mechanism to give remaining
|
|
2064 // undefined symbols final chance to be resolved successfully.
|
|
2065 for (auto pair : config->alternateNames) {
|
|
2066 StringRef from = pair.first;
|
|
2067 StringRef to = pair.second;
|
|
2068 Symbol *sym = symtab->find(from);
|
|
2069 if (!sym)
|
|
2070 continue;
|
|
2071 if (auto *u = dyn_cast<Undefined>(sym))
|
|
2072 if (!u->weakAlias)
|
|
2073 u->weakAlias = symtab->addUndefined(to);
|
|
2074 }
|
|
2075
|
|
2076 // If any inputs are bitcode files, the LTO code generator may create
|
|
2077 // references to library functions that are not explicit in the bitcode
|
|
2078 // file's symbol table. If any of those library functions are defined in a
|
|
2079 // bitcode file in an archive member, we need to arrange to use LTO to
|
|
2080 // compile those archive members by adding them to the link beforehand.
|
|
2081 if (!BitcodeFile::instances.empty())
|
|
2082 for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
|
|
2083 symtab->addLibcall(s);
|
|
2084
|
|
2085 // Windows specific -- if __load_config_used can be resolved, resolve it.
|
|
2086 if (symtab->findUnderscore("_load_config_used"))
|
|
2087 addUndefined(mangle("_load_config_used"));
|
|
2088 } while (run());
|
|
2089
|
|
2090 if (args.hasArg(OPT_include_optional)) {
|
|
2091 // Handle /includeoptional
|
|
2092 for (auto *arg : args.filtered(OPT_include_optional))
|
|
2093 if (dyn_cast_or_null<LazyArchive>(symtab->find(arg->getValue())))
|
|
2094 addUndefined(arg->getValue());
|
|
2095 while (run());
|
|
2096 }
|
|
2097
|
207
|
2098 // Create wrapped symbols for -wrap option.
|
|
2099 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
|
|
2100 // Load more object files that might be needed for wrapped symbols.
|
|
2101 if (!wrapped.empty())
|
|
2102 while (run());
|
|
2103
|
173
|
2104 if (config->autoImport) {
|
|
2105 // MinGW specific.
|
150
|
2106 // Load any further object files that might be needed for doing automatic
|
|
2107 // imports.
|
|
2108 //
|
|
2109 // For cases with no automatically imported symbols, this iterates once
|
|
2110 // over the symbol table and doesn't do anything.
|
|
2111 //
|
|
2112 // For the normal case with a few automatically imported symbols, this
|
|
2113 // should only need to be run once, since each new object file imported
|
|
2114 // is an import library and wouldn't add any new undefined references,
|
|
2115 // but there's nothing stopping the __imp_ symbols from coming from a
|
|
2116 // normal object file as well (although that won't be used for the
|
|
2117 // actual autoimport later on). If this pass adds new undefined references,
|
|
2118 // we won't iterate further to resolve them.
|
|
2119 symtab->loadMinGWAutomaticImports();
|
|
2120 run();
|
|
2121 }
|
|
2122
|
|
2123 // At this point, we should not have any symbols that cannot be resolved.
|
|
2124 // If we are going to do codegen for link-time optimization, check for
|
|
2125 // unresolvable symbols first, so we don't spend time generating code that
|
|
2126 // will fail to link anyway.
|
|
2127 if (!BitcodeFile::instances.empty() && !config->forceUnresolved)
|
|
2128 symtab->reportUnresolvable();
|
|
2129 if (errorCount())
|
|
2130 return;
|
|
2131
|
207
|
2132 config->hadExplicitExports = !config->exports.empty();
|
|
2133 if (config->mingw) {
|
|
2134 // In MinGW, all symbols are automatically exported if no symbols
|
|
2135 // are chosen to be exported.
|
|
2136 maybeExportMinGWSymbols(args);
|
|
2137 }
|
|
2138
|
150
|
2139 // Do LTO by compiling bitcode input files to a set of native COFF files then
|
|
2140 // link those files (unless -thinlto-index-only was given, in which case we
|
|
2141 // resolve symbols and write indices, but don't generate native code or link).
|
|
2142 symtab->addCombinedLTOObjects();
|
|
2143
|
|
2144 // If -thinlto-index-only is given, we should create only "index
|
|
2145 // files" and not object files. Index file creation is already done
|
|
2146 // in addCombinedLTOObject, so we are done if that's the case.
|
|
2147 if (config->thinLTOIndexOnly)
|
|
2148 return;
|
|
2149
|
|
2150 // If we generated native object files from bitcode files, this resolves
|
|
2151 // references to the symbols we use from them.
|
|
2152 run();
|
|
2153
|
207
|
2154 // Apply symbol renames for -wrap.
|
|
2155 if (!wrapped.empty())
|
|
2156 wrapSymbols(wrapped);
|
|
2157
|
150
|
2158 // Resolve remaining undefined symbols and warn about imported locals.
|
|
2159 symtab->resolveRemainingUndefines();
|
|
2160 if (errorCount())
|
|
2161 return;
|
|
2162
|
|
2163 if (config->mingw) {
|
|
2164 // Make sure the crtend.o object is the last object file. This object
|
|
2165 // file can contain terminating section chunks that need to be placed
|
|
2166 // last. GNU ld processes files and static libraries explicitly in the
|
|
2167 // order provided on the command line, while lld will pull in needed
|
|
2168 // files from static libraries only after the last object file on the
|
|
2169 // command line.
|
|
2170 for (auto i = ObjFile::instances.begin(), e = ObjFile::instances.end();
|
|
2171 i != e; i++) {
|
|
2172 ObjFile *file = *i;
|
|
2173 if (isCrtend(file->getName())) {
|
|
2174 ObjFile::instances.erase(i);
|
|
2175 ObjFile::instances.push_back(file);
|
|
2176 break;
|
|
2177 }
|
|
2178 }
|
|
2179 }
|
|
2180
|
|
2181 // Windows specific -- when we are creating a .dll file, we also
|
|
2182 // need to create a .lib file. In MinGW mode, we only do that when the
|
|
2183 // -implib option is given explicitly, for compatibility with GNU ld.
|
|
2184 if (!config->exports.empty() || config->dll) {
|
|
2185 fixupExports();
|
|
2186 if (!config->mingw || !config->implib.empty())
|
|
2187 createImportLibrary(/*asLib=*/false);
|
|
2188 assignExportOrdinals();
|
|
2189 }
|
|
2190
|
|
2191 // Handle /output-def (MinGW specific).
|
|
2192 if (auto *arg = args.getLastArg(OPT_output_def))
|
|
2193 writeDefFile(arg->getValue());
|
|
2194
|
|
2195 // Set extra alignment for .comm symbols
|
|
2196 for (auto pair : config->alignComm) {
|
|
2197 StringRef name = pair.first;
|
|
2198 uint32_t alignment = pair.second;
|
|
2199
|
|
2200 Symbol *sym = symtab->find(name);
|
|
2201 if (!sym) {
|
|
2202 warn("/aligncomm symbol " + name + " not found");
|
|
2203 continue;
|
|
2204 }
|
|
2205
|
|
2206 // If the symbol isn't common, it must have been replaced with a regular
|
|
2207 // symbol, which will carry its own alignment.
|
|
2208 auto *dc = dyn_cast<DefinedCommon>(sym);
|
|
2209 if (!dc)
|
|
2210 continue;
|
|
2211
|
|
2212 CommonChunk *c = dc->getChunk();
|
|
2213 c->setAlignment(std::max(c->getAlignment(), alignment));
|
|
2214 }
|
|
2215
|
|
2216 // Windows specific -- Create a side-by-side manifest file.
|
|
2217 if (config->manifest == Configuration::SideBySide)
|
|
2218 createSideBySideManifest();
|
|
2219
|
|
2220 // Handle /order. We want to do this at this moment because we
|
|
2221 // need a complete list of comdat sections to warn on nonexistent
|
|
2222 // functions.
|
207
|
2223 if (auto *arg = args.getLastArg(OPT_order)) {
|
|
2224 if (args.hasArg(OPT_call_graph_ordering_file))
|
|
2225 error("/order and /call-graph-order-file may not be used together");
|
150
|
2226 parseOrderFile(arg->getValue());
|
207
|
2227 config->callGraphProfileSort = false;
|
|
2228 }
|
|
2229
|
|
2230 // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on).
|
|
2231 if (config->callGraphProfileSort) {
|
|
2232 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) {
|
|
2233 parseCallGraphFile(arg->getValue());
|
|
2234 }
|
|
2235 readCallGraphsFromObjectFiles();
|
|
2236 }
|
|
2237
|
|
2238 // Handle /print-symbol-order.
|
|
2239 if (auto *arg = args.getLastArg(OPT_print_symbol_order))
|
|
2240 config->printSymbolOrder = arg->getValue();
|
150
|
2241
|
|
2242 // Identify unreferenced COMDAT sections.
|
207
|
2243 if (config->doGC) {
|
|
2244 if (config->mingw) {
|
|
2245 // markLive doesn't traverse .eh_frame, but the personality function is
|
|
2246 // only reached that way. The proper solution would be to parse and
|
|
2247 // traverse the .eh_frame section, like the ELF linker does.
|
|
2248 // For now, just manually try to retain the known possible personality
|
|
2249 // functions. This doesn't bring in more object files, but only marks
|
|
2250 // functions that already have been included to be retained.
|
|
2251 for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0"}) {
|
|
2252 Defined *d = dyn_cast_or_null<Defined>(symtab->findUnderscore(n));
|
|
2253 if (d && !d->isGCRoot) {
|
|
2254 d->isGCRoot = true;
|
|
2255 config->gcroot.push_back(d);
|
|
2256 }
|
|
2257 }
|
|
2258 }
|
|
2259
|
150
|
2260 markLive(symtab->getChunks());
|
207
|
2261 }
|
150
|
2262
|
|
2263 // Needs to happen after the last call to addFile().
|
|
2264 convertResources();
|
|
2265
|
|
2266 // Identify identical COMDAT sections to merge them.
|
207
|
2267 if (config->doICF != ICFLevel::None) {
|
150
|
2268 findKeepUniqueSections();
|
207
|
2269 doICF(symtab->getChunks(), config->doICF);
|
150
|
2270 }
|
|
2271
|
|
2272 // Write the result.
|
|
2273 writeResult();
|
|
2274
|
|
2275 // Stop early so we can print the results.
|
173
|
2276 rootTimer.stop();
|
150
|
2277 if (config->showTiming)
|
|
2278 Timer::root().print();
|
|
2279 }
|
|
2280
|
|
2281 } // namespace coff
|
|
2282 } // namespace lld
|