1//===- Driver.h -------------------------------------------------*- C++ -*-===//
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#ifndef LLD_COFF_DRIVER_H
10#define LLD_COFF_DRIVER_H
11
12#include "Config.h"
13#include "SymbolTable.h"
14#include "lld/Common/LLVM.h"
15#include "lld/Common/Reproduce.h"
16#include "llvm/ADT/StringRef.h"
17#include "llvm/ADT/StringSet.h"
18#include "llvm/Object/Archive.h"
19#include "llvm/Object/COFF.h"
20#include "llvm/Option/Arg.h"
21#include "llvm/Option/ArgList.h"
22#include "llvm/Support/FileSystem.h"
23#include "llvm/Support/TarWriter.h"
24#include "llvm/WindowsDriver/MSVCPaths.h"
25#include <memory>
26#include <optional>
27#include <set>
28#include <vector>
29
30namespace lld::coff {
31
32using llvm::COFF::MachineTypes;
33using llvm::COFF::WindowsSubsystem;
34using std::optional;
35
36class COFFOptTable : public llvm::opt::OptTable {
37public:
38 COFFOptTable();
39};
40
41// The result of parsing the .drective section. The /export: and /include:
42// options are handled separately because they reference symbols, and the number
43// of symbols can be quite large. The LLVM Option library will perform at least
44// one memory allocation per argument, and that is prohibitively slow for
45// parsing directives.
46struct ParsedDirectives {
47 std::vector<StringRef> exports;
48 std::vector<StringRef> includes;
49 std::vector<StringRef> excludes;
50 llvm::opt::InputArgList args;
51};
52
53class ArgParser {
54public:
55 ArgParser(COFFLinkerContext &ctx);
56
57 // Parses command line options.
58 llvm::opt::InputArgList parse(llvm::ArrayRef<const char *> args);
59
60 // Tokenizes a given string and then parses as command line options.
61 llvm::opt::InputArgList parse(StringRef s) { return parse(args: tokenize(s)); }
62
63 // Tokenizes a given string and then parses as command line options in
64 // .drectve section. /EXPORT options are returned in second element
65 // to be processed in fastpath.
66 ParsedDirectives parseDirectives(StringRef s);
67
68private:
69 // Concatenate LINK environment variable.
70 void addLINK(SmallVector<const char *, 256> &argv);
71
72 std::vector<const char *> tokenize(StringRef s);
73
74 COFFLinkerContext &ctx;
75};
76
77class LinkerDriver {
78public:
79 LinkerDriver(COFFLinkerContext &ctx) : ctx(ctx) {}
80
81 void linkerMain(llvm::ArrayRef<const char *> args);
82
83 void addFile(InputFile *file);
84
85 void addClangLibSearchPaths(const std::string &argv0);
86 void addClangPerTargetRuntimeDirSearchPaths();
87
88 // Used by ArchiveFile to enqueue members.
89 void enqueueArchiveMember(const Archive::Child &c, const Archive::Symbol &sym,
90 StringRef parentName);
91
92 enum class InputOpt { None, DefaultLib, WholeArchive };
93 void enqueuePDB(StringRef Path) { enqueuePath(path: Path, lazy: false); }
94
95 MemoryBufferRef takeBuffer(std::unique_ptr<MemoryBuffer> mb);
96
97 void enqueuePath(StringRef path, bool lazy,
98 InputOpt inputOpt = InputOpt::None);
99
100 // Returns a list of chunks of selected symbols.
101 std::vector<Chunk *> getChunks() const;
102
103 std::unique_ptr<llvm::TarWriter> tar; // for /linkrepro
104
105 void pullArm64ECIcallHelper();
106
107private:
108 // Searches a file from search paths.
109 std::optional<StringRef> findFileIfNew(StringRef filename);
110 std::optional<StringRef> findLibIfNew(StringRef filename);
111 StringRef findFile(StringRef filename);
112 StringRef findLib(StringRef filename);
113 StringRef findLibMinGW(StringRef filename);
114
115 // Determines the location of the sysroot based on `args`, environment, etc.
116 void detectWinSysRoot(const llvm::opt::InputArgList &args);
117
118 // Adds various search paths based on the sysroot. Must only be called once
119 // config.machine has been set.
120 void addWinSysRootLibSearchPaths();
121
122 void setMachine(llvm::COFF::MachineTypes machine);
123 llvm::Triple::ArchType getArch();
124
125 uint64_t getDefaultImageBase();
126
127 bool isDecorated(StringRef sym);
128
129 InputFile *addObjectFile(COFFLinkerContext &ctx, MemoryBufferRef mb,
130 StringRef archiveName, uint64_t offsetInArchive,
131 bool lazy);
132
133 std::string getMapFile(const llvm::opt::InputArgList &args,
134 llvm::opt::OptSpecifier os,
135 llvm::opt::OptSpecifier osFile);
136
137 std::string getImplibPath();
138
139 // The import name is calculated as follows:
140 //
141 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
142 // -----+----------------+---------------------+------------------
143 // LINK | {value} | {value}.{.dll/.exe} | {output name}
144 // LIB | {value} | {value}.dll | {output name}.dll
145 //
146 std::string getImportName(bool asLib);
147
148 // Write fullly resolved path to repro file if /linkreprofullpathrsp
149 // is specified.
150 void handleReproFile(StringRef path, InputOpt inputOpt);
151
152 void createImportLibrary(bool asLib);
153
154 // Used by the resolver to parse .drectve section contents.
155 void parseDirectives(InputFile *file);
156
157 // Parse an /order file. If an option is given, the linker places COMDAT
158 // sections int he same order as their names appear in the given file.
159 void parseOrderFile(StringRef arg);
160
161 void parseCallGraphFile(StringRef path);
162
163 void parsePDBAltPath();
164
165 // Parses LIB environment which contains a list of search paths.
166 void addLibSearchPaths();
167
168 // Library search path. The first element is always "" (current directory).
169 std::vector<StringRef> searchPaths;
170
171 // Convert resource files and potentially merge input resource object
172 // trees into one resource tree.
173 void convertResources();
174
175 void maybeExportMinGWSymbols(const llvm::opt::InputArgList &args);
176
177 // We don't want to add the same file more than once.
178 // Files are uniquified by their filesystem and file number.
179 std::set<llvm::sys::fs::UniqueID> visitedFiles;
180
181 std::set<std::string> visitedLibs;
182
183 void addBuffer(std::unique_ptr<MemoryBuffer> mb, bool wholeArchive,
184 bool lazy);
185 void addArchiveBuffer(MemoryBufferRef mbref, StringRef symName,
186 StringRef parentName, uint64_t offsetInArchive,
187 bool lazy);
188 void addThinArchiveBuffer(MemoryBufferRef mbref, StringRef symName,
189 bool lazy);
190
191 void enqueueTask(std::function<void()> task);
192 bool run();
193
194 std::list<std::function<void()>> taskQueue;
195 std::vector<MemoryBufferRef> resources;
196
197 llvm::DenseSet<StringRef> excludedSymbols;
198
199 COFFLinkerContext &ctx;
200
201 llvm::ToolsetLayout vsLayout = llvm::ToolsetLayout::OlderVS;
202 std::string vcToolChainPath;
203 llvm::SmallString<128> diaPath;
204 bool useWinSysRootLibPath = false;
205 llvm::SmallString<128> universalCRTLibPath;
206 int sdkMajor = 0;
207 llvm::SmallString<128> windowsSdkLibPath;
208 std::string clangRuntimeLibDir;
209
210 // For linkreprofullpathrsp
211 std::unique_ptr<llvm::raw_fd_ostream> reproFile;
212
213 // Functions below this line are defined in DriverUtils.cpp.
214
215 void printHelp(const char *argv0);
216
217 // Parses a string in the form of "<integer>[,<integer>]".
218 void parseNumbers(StringRef arg, uint64_t *addr, uint64_t *size = nullptr);
219
220 void parseGuard(StringRef arg);
221
222 // Parses a string in the form of "<integer>[.<integer>]".
223 // Minor's default value is 0.
224 void parseVersion(StringRef arg, uint32_t *major, uint32_t *minor);
225
226 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
227 void parseSubsystem(StringRef arg, WindowsSubsystem *sys, uint32_t *major,
228 uint32_t *minor, bool *gotVersion = nullptr);
229
230 void parseMerge(StringRef);
231 void parsePDBPageSize(StringRef);
232 void parseSection(StringRef);
233 void parseSectionLayout(StringRef);
234
235 void parseSameAddress(StringRef);
236
237 // Parses a MS-DOS stub file
238 void parseDosStub(StringRef path);
239
240 // Parses a string in the form of "[:<integer>]"
241 void parseFunctionPadMin(llvm::opt::Arg *a);
242
243 // Parses a string in the form of "[:<integer>]"
244 void parseDependentLoadFlags(llvm::opt::Arg *a);
245
246 // Parses a string in the form of "EMBED[,=<integer>]|NO".
247 void parseManifest(StringRef arg);
248
249 // Parses a string in the form of "level=<string>|uiAccess=<string>"
250 void parseManifestUAC(StringRef arg);
251
252 // Parses a string in the form of "cd|net[,(cd|net)]*"
253 void parseSwaprun(StringRef arg);
254
255 // Create a resource file containing a manifest XML.
256 std::unique_ptr<MemoryBuffer> createManifestRes();
257 void createSideBySideManifest();
258 std::string createDefaultXml();
259 std::string createManifestXmlWithInternalMt(StringRef defaultXml);
260 std::string createManifestXmlWithExternalMt(StringRef defaultXml);
261 std::string createManifestXml();
262
263 std::unique_ptr<llvm::WritableMemoryBuffer>
264 createMemoryBufferForManifestRes(size_t manifestRes);
265
266 // Used for dllexported symbols.
267 Export parseExport(StringRef arg);
268
269 // Parses a string in the form of "key=value" and check
270 // if value matches previous values for the key.
271 // This feature used in the directive section to reject
272 // incompatible objects.
273 void checkFailIfMismatch(StringRef arg, InputFile *source);
274
275 // Convert Windows resource files (.res files) to a .obj file.
276 MemoryBufferRef convertResToCOFF(ArrayRef<MemoryBufferRef> mbs,
277 ArrayRef<ObjFile *> objs);
278
279 // Create export thunks for exported and patchable Arm64EC function symbols.
280 void createECExportThunks();
281 void maybeCreateECExportThunk(StringRef name, Symbol *&sym);
282
283 bool ltoCompilationDone = false;
284};
285
286// Create enum with OPT_xxx values for each option in Options.td
287enum {
288 OPT_INVALID = 0,
289#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
290#include "Options.inc"
291#undef OPTION
292};
293
294} // namespace lld::coff
295
296#endif
297