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::GenericOptTable {
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
87 // Used by ArchiveFile to enqueue members.
88 void enqueueArchiveMember(const Archive::Child &c, const Archive::Symbol &sym,
89 StringRef parentName);
90
91 enum class InputOpt { None, DefaultLib, WholeArchive };
92 void enqueuePDB(StringRef Path) { enqueuePath(path: Path, lazy: false); }
93
94 MemoryBufferRef takeBuffer(std::unique_ptr<MemoryBuffer> mb);
95
96 void enqueuePath(StringRef path, bool lazy,
97 InputOpt inputOpt = InputOpt::None);
98
99 // Returns a list of chunks of selected symbols.
100 std::vector<Chunk *> getChunks() const;
101
102 std::unique_ptr<llvm::TarWriter> tar; // for /linkrepro
103
104 void pullArm64ECIcallHelper();
105
106private:
107 // Searches a file from search paths.
108 std::optional<StringRef> findFileIfNew(StringRef filename);
109 std::optional<StringRef> findLibIfNew(StringRef filename);
110 StringRef findFile(StringRef filename);
111 StringRef findLib(StringRef filename);
112 StringRef findLibMinGW(StringRef filename);
113
114 // Determines the location of the sysroot based on `args`, environment, etc.
115 void detectWinSysRoot(const llvm::opt::InputArgList &args);
116
117 // Adds various search paths based on the sysroot. Must only be called once
118 // config.machine has been set.
119 void addWinSysRootLibSearchPaths();
120
121 void setMachine(llvm::COFF::MachineTypes machine);
122 llvm::Triple::ArchType getArch();
123
124 uint64_t getDefaultImageBase();
125
126 bool isDecorated(StringRef sym);
127
128 std::string getMapFile(const llvm::opt::InputArgList &args,
129 llvm::opt::OptSpecifier os,
130 llvm::opt::OptSpecifier osFile);
131
132 std::string getImplibPath();
133
134 // The import name is calculated as follows:
135 //
136 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
137 // -----+----------------+---------------------+------------------
138 // LINK | {value} | {value}.{.dll/.exe} | {output name}
139 // LIB | {value} | {value}.dll | {output name}.dll
140 //
141 std::string getImportName(bool asLib);
142
143 // Write fullly resolved path to repro file if /linkreprofullpathrsp
144 // is specified.
145 void handleReproFile(StringRef path, InputOpt inputOpt);
146
147 void createImportLibrary(bool asLib);
148
149 // Used by the resolver to parse .drectve section contents.
150 void parseDirectives(InputFile *file);
151
152 // Parse an /order file. If an option is given, the linker places COMDAT
153 // sections int he same order as their names appear in the given file.
154 void parseOrderFile(StringRef arg);
155
156 void parseCallGraphFile(StringRef path);
157
158 void parsePDBAltPath();
159
160 // Parses LIB environment which contains a list of search paths.
161 void addLibSearchPaths();
162
163 // Library search path. The first element is always "" (current directory).
164 std::vector<StringRef> searchPaths;
165
166 // Convert resource files and potentially merge input resource object
167 // trees into one resource tree.
168 void convertResources();
169
170 void maybeExportMinGWSymbols(const llvm::opt::InputArgList &args);
171
172 // We don't want to add the same file more than once.
173 // Files are uniquified by their filesystem and file number.
174 std::set<llvm::sys::fs::UniqueID> visitedFiles;
175
176 std::set<std::string> visitedLibs;
177
178 void addBuffer(std::unique_ptr<MemoryBuffer> mb, bool wholeArchive,
179 bool lazy);
180 void addArchiveBuffer(MemoryBufferRef mbref, StringRef symName,
181 StringRef parentName, uint64_t offsetInArchive,
182 bool lazy);
183 void addThinArchiveBuffer(MemoryBufferRef mbref, StringRef symName,
184 bool lazy);
185
186 void enqueueTask(std::function<void()> task);
187 bool run();
188
189 std::list<std::function<void()>> taskQueue;
190 std::vector<MemoryBufferRef> resources;
191
192 llvm::DenseSet<StringRef> excludedSymbols;
193
194 COFFLinkerContext &ctx;
195
196 llvm::ToolsetLayout vsLayout = llvm::ToolsetLayout::OlderVS;
197 std::string vcToolChainPath;
198 llvm::SmallString<128> diaPath;
199 bool useWinSysRootLibPath = false;
200 llvm::SmallString<128> universalCRTLibPath;
201 int sdkMajor = 0;
202 llvm::SmallString<128> windowsSdkLibPath;
203
204 // For linkreprofullpathrsp
205 std::unique_ptr<llvm::raw_fd_ostream> reproFile;
206
207 // Functions below this line are defined in DriverUtils.cpp.
208
209 void printHelp(const char *argv0);
210
211 // Parses a string in the form of "<integer>[,<integer>]".
212 void parseNumbers(StringRef arg, uint64_t *addr, uint64_t *size = nullptr);
213
214 void parseGuard(StringRef arg);
215
216 // Parses a string in the form of "<integer>[.<integer>]".
217 // Minor's default value is 0.
218 void parseVersion(StringRef arg, uint32_t *major, uint32_t *minor);
219
220 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
221 void parseSubsystem(StringRef arg, WindowsSubsystem *sys, uint32_t *major,
222 uint32_t *minor, bool *gotVersion = nullptr);
223
224 void parseMerge(StringRef);
225 void parsePDBPageSize(StringRef);
226 void parseSection(StringRef);
227 void parseSectionLayout(StringRef);
228
229 void parseSameAddress(StringRef);
230
231 // Parses a MS-DOS stub file
232 void parseDosStub(StringRef path);
233
234 // Parses a string in the form of "[:<integer>]"
235 void parseFunctionPadMin(llvm::opt::Arg *a);
236
237 // Parses a string in the form of "[:<integer>]"
238 void parseDependentLoadFlags(llvm::opt::Arg *a);
239
240 // Parses a string in the form of "EMBED[,=<integer>]|NO".
241 void parseManifest(StringRef arg);
242
243 // Parses a string in the form of "level=<string>|uiAccess=<string>"
244 void parseManifestUAC(StringRef arg);
245
246 // Parses a string in the form of "cd|net[,(cd|net)]*"
247 void parseSwaprun(StringRef arg);
248
249 // Create a resource file containing a manifest XML.
250 std::unique_ptr<MemoryBuffer> createManifestRes();
251 void createSideBySideManifest();
252 std::string createDefaultXml();
253 std::string createManifestXmlWithInternalMt(StringRef defaultXml);
254 std::string createManifestXmlWithExternalMt(StringRef defaultXml);
255 std::string createManifestXml();
256
257 std::unique_ptr<llvm::WritableMemoryBuffer>
258 createMemoryBufferForManifestRes(size_t manifestRes);
259
260 // Used for dllexported symbols.
261 Export parseExport(StringRef arg);
262
263 // Parses a string in the form of "key=value" and check
264 // if value matches previous values for the key.
265 // This feature used in the directive section to reject
266 // incompatible objects.
267 void checkFailIfMismatch(StringRef arg, InputFile *source);
268
269 // Convert Windows resource files (.res files) to a .obj file.
270 MemoryBufferRef convertResToCOFF(ArrayRef<MemoryBufferRef> mbs,
271 ArrayRef<ObjFile *> objs);
272
273 // Create export thunks for exported and patchable Arm64EC function symbols.
274 void createECExportThunks();
275 void maybeCreateECExportThunk(StringRef name, Symbol *&sym);
276
277 bool ltoCompilationDone = false;
278};
279
280// Create enum with OPT_xxx values for each option in Options.td
281enum {
282 OPT_INVALID = 0,
283#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
284#include "Options.inc"
285#undef OPTION
286};
287
288} // namespace lld::coff
289
290#endif
291