xref: /freebsd/contrib/llvm-project/lld/COFF/Driver.h (revision 5e3190f700637fcfc1a52daeaa4a031fdd2557c7)
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 
30 namespace lld::coff {
31 
32 using llvm::COFF::MachineTypes;
33 using llvm::COFF::WindowsSubsystem;
34 using std::optional;
35 
36 class COFFOptTable : public llvm::opt::GenericOptTable {
37 public:
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.
46 struct ParsedDirectives {
47   std::vector<StringRef> exports;
48   std::vector<StringRef> includes;
49   std::vector<StringRef> excludes;
50   llvm::opt::InputArgList args;
51 };
52 
53 class ArgParser {
54 public:
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(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 
68 private:
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 
77 class LinkerDriver {
78 public:
79   LinkerDriver(COFFLinkerContext &ctx) : ctx(ctx) {}
80 
81   void linkerMain(llvm::ArrayRef<const char *> args);
82 
83   // Adds various search paths based on the sysroot.  Must only be called once
84   // config->machine has been set.
85   void addWinSysRootLibSearchPaths();
86 
87   // Used by the resolver to parse .drectve section contents.
88   void parseDirectives(InputFile *file);
89 
90   // Used by ArchiveFile to enqueue members.
91   void enqueueArchiveMember(const Archive::Child &c, const Archive::Symbol &sym,
92                             StringRef parentName);
93 
94   void enqueuePDB(StringRef Path) { enqueuePath(Path, false, false); }
95 
96   MemoryBufferRef takeBuffer(std::unique_ptr<MemoryBuffer> mb);
97 
98   void enqueuePath(StringRef path, bool wholeArchive, bool lazy);
99 
100   std::unique_ptr<llvm::TarWriter> tar; // for /linkrepro
101 
102 private:
103   // Searches a file from search paths.
104   std::optional<StringRef> findFile(StringRef filename);
105   std::optional<StringRef> findLib(StringRef filename);
106   StringRef doFindFile(StringRef filename);
107   StringRef doFindLib(StringRef filename);
108   StringRef doFindLibMinGW(StringRef filename);
109 
110   bool findUnderscoreMangle(StringRef sym);
111 
112   // Determines the location of the sysroot based on `args`, environment, etc.
113   void detectWinSysRoot(const llvm::opt::InputArgList &args);
114 
115   // Symbol names are mangled by prepending "_" on x86.
116   StringRef mangle(StringRef sym);
117 
118   llvm::Triple::ArchType getArch();
119 
120   uint64_t getDefaultImageBase();
121 
122   bool isDecorated(StringRef sym);
123 
124   std::string getMapFile(const llvm::opt::InputArgList &args,
125                          llvm::opt::OptSpecifier os,
126                          llvm::opt::OptSpecifier osFile);
127 
128   std::string getImplibPath();
129 
130   // The import name is calculated as follows:
131   //
132   //        | LIBRARY w/ ext |   LIBRARY w/o ext   | no LIBRARY
133   //   -----+----------------+---------------------+------------------
134   //   LINK | {value}        | {value}.{.dll/.exe} | {output name}
135   //    LIB | {value}        | {value}.dll         | {output name}.dll
136   //
137   std::string getImportName(bool asLib);
138 
139   void createImportLibrary(bool asLib);
140 
141   void parseModuleDefs(StringRef path);
142 
143   // Parse an /order file. If an option is given, the linker places COMDAT
144   // sections int he same order as their names appear in the given file.
145   void parseOrderFile(StringRef arg);
146 
147   void parseCallGraphFile(StringRef path);
148 
149   void parsePDBAltPath();
150 
151   // Parses LIB environment which contains a list of search paths.
152   void addLibSearchPaths();
153 
154   // Library search path. The first element is always "" (current directory).
155   std::vector<StringRef> searchPaths;
156 
157   // Convert resource files and potentially merge input resource object
158   // trees into one resource tree.
159   void convertResources();
160 
161   void maybeExportMinGWSymbols(const llvm::opt::InputArgList &args);
162 
163   // We don't want to add the same file more than once.
164   // Files are uniquified by their filesystem and file number.
165   std::set<llvm::sys::fs::UniqueID> visitedFiles;
166 
167   std::set<std::string> visitedLibs;
168 
169   Symbol *addUndefined(StringRef sym);
170 
171   StringRef mangleMaybe(Symbol *s);
172 
173   // Windows specific -- "main" is not the only main function in Windows.
174   // You can choose one from these four -- {w,}{WinMain,main}.
175   // There are four different entry point functions for them,
176   // {w,}{WinMain,main}CRTStartup, respectively. The linker needs to
177   // choose the right one depending on which "main" function is defined.
178   // This function looks up the symbol table and resolve corresponding
179   // entry point name.
180   StringRef findDefaultEntry();
181   WindowsSubsystem inferSubsystem();
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 
188   void enqueueTask(std::function<void()> task);
189   bool run();
190 
191   std::list<std::function<void()>> taskQueue;
192   std::vector<StringRef> filePaths;
193   std::vector<MemoryBufferRef> resources;
194 
195   llvm::DenseSet<StringRef> directivesExports;
196   llvm::DenseSet<StringRef> excludedSymbols;
197 
198   COFFLinkerContext &ctx;
199 
200   llvm::ToolsetLayout vsLayout = llvm::ToolsetLayout::OlderVS;
201   std::string vcToolChainPath;
202   llvm::SmallString<128> diaPath;
203   bool useWinSysRootLibPath = false;
204   llvm::SmallString<128> universalCRTLibPath;
205   int sdkMajor = 0;
206   llvm::SmallString<128> windowsSdkLibPath;
207 
208   // Functions below this line are defined in DriverUtils.cpp.
209 
210   void printHelp(const char *argv0);
211 
212   // Parses a string in the form of "<integer>[,<integer>]".
213   void parseNumbers(StringRef arg, uint64_t *addr, uint64_t *size = nullptr);
214 
215   void parseGuard(StringRef arg);
216 
217   // Parses a string in the form of "<integer>[.<integer>]".
218   // Minor's default value is 0.
219   void parseVersion(StringRef arg, uint32_t *major, uint32_t *minor);
220 
221   // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
222   void parseSubsystem(StringRef arg, WindowsSubsystem *sys, uint32_t *major,
223                       uint32_t *minor, bool *gotVersion = nullptr);
224 
225   void parseAlternateName(StringRef);
226   void parseMerge(StringRef);
227   void parsePDBPageSize(StringRef);
228   void parseSection(StringRef);
229   void parseAligncomm(StringRef);
230 
231   // Parses a string in the form of "[:<integer>]"
232   void parseFunctionPadMin(llvm::opt::Arg *a);
233 
234   // Parses a string in the form of "EMBED[,=<integer>]|NO".
235   void parseManifest(StringRef arg);
236 
237   // Parses a string in the form of "level=<string>|uiAccess=<string>"
238   void parseManifestUAC(StringRef arg);
239 
240   // Parses a string in the form of "cd|net[,(cd|net)]*"
241   void parseSwaprun(StringRef arg);
242 
243   // Create a resource file containing a manifest XML.
244   std::unique_ptr<MemoryBuffer> createManifestRes();
245   void createSideBySideManifest();
246   std::string createDefaultXml();
247   std::string createManifestXmlWithInternalMt(StringRef defaultXml);
248   std::string createManifestXmlWithExternalMt(StringRef defaultXml);
249   std::string createManifestXml();
250 
251   std::unique_ptr<llvm::WritableMemoryBuffer>
252   createMemoryBufferForManifestRes(size_t manifestRes);
253 
254   // Used for dllexported symbols.
255   Export parseExport(StringRef arg);
256   void fixupExports();
257   void assignExportOrdinals();
258 
259   // Parses a string in the form of "key=value" and check
260   // if value matches previous values for the key.
261   // This feature used in the directive section to reject
262   // incompatible objects.
263   void checkFailIfMismatch(StringRef arg, InputFile *source);
264 
265   // Convert Windows resource files (.res files) to a .obj file.
266   MemoryBufferRef convertResToCOFF(ArrayRef<MemoryBufferRef> mbs,
267                                    ArrayRef<ObjFile *> objs);
268 };
269 
270 // Create enum with OPT_xxx values for each option in Options.td
271 enum {
272   OPT_INVALID = 0,
273 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
274 #include "Options.inc"
275 #undef OPTION
276 };
277 
278 } // namespace lld::coff
279 
280 #endif
281