xref: /freebsd/contrib/llvm-project/lld/COFF/Driver.h (revision 9768746b)
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 "COFFLinkerContext.h"
13 #include "Config.h"
14 #include "SymbolTable.h"
15 #include "lld/Common/LLVM.h"
16 #include "lld/Common/Reproduce.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/StringSet.h"
20 #include "llvm/Object/Archive.h"
21 #include "llvm/Object/COFF.h"
22 #include "llvm/Option/Arg.h"
23 #include "llvm/Option/ArgList.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/TarWriter.h"
26 #include "llvm/WindowsDriver/MSVCPaths.h"
27 #include <memory>
28 #include <set>
29 #include <vector>
30 
31 namespace lld {
32 namespace coff {
33 
34 extern std::unique_ptr<class LinkerDriver> driver;
35 
36 using llvm::COFF::MachineTypes;
37 using llvm::COFF::WindowsSubsystem;
38 using llvm::Optional;
39 
40 class COFFOptTable : public llvm::opt::OptTable {
41 public:
42   COFFOptTable();
43 };
44 
45 // Constructing the option table is expensive. Use a global table to avoid doing
46 // it more than once.
47 extern COFFOptTable optTable;
48 
49 // The result of parsing the .drective section. The /export: and /include:
50 // options are handled separately because they reference symbols, and the number
51 // of symbols can be quite large. The LLVM Option library will perform at least
52 // one memory allocation per argument, and that is prohibitively slow for
53 // parsing directives.
54 struct ParsedDirectives {
55   std::vector<StringRef> exports;
56   std::vector<StringRef> includes;
57   std::vector<StringRef> excludes;
58   llvm::opt::InputArgList args;
59 };
60 
61 class ArgParser {
62 public:
63   // Parses command line options.
64   llvm::opt::InputArgList parse(llvm::ArrayRef<const char *> args);
65 
66   // Tokenizes a given string and then parses as command line options.
67   llvm::opt::InputArgList parse(StringRef s) { return parse(tokenize(s)); }
68 
69   // Tokenizes a given string and then parses as command line options in
70   // .drectve section. /EXPORT options are returned in second element
71   // to be processed in fastpath.
72   ParsedDirectives parseDirectives(StringRef s);
73 
74 private:
75   // Concatenate LINK environment variable.
76   void addLINK(SmallVector<const char *, 256> &argv);
77 
78   std::vector<const char *> tokenize(StringRef s);
79 };
80 
81 class LinkerDriver {
82 public:
83   LinkerDriver(COFFLinkerContext &c) : ctx(c) {}
84 
85   void linkerMain(llvm::ArrayRef<const char *> args);
86 
87   // Adds various search paths based on the sysroot.  Must only be called once
88   // config->machine has been set.
89   void addWinSysRootLibSearchPaths();
90 
91   // Used by the resolver to parse .drectve section contents.
92   void parseDirectives(InputFile *file);
93 
94   // Used by ArchiveFile to enqueue members.
95   void enqueueArchiveMember(const Archive::Child &c, const Archive::Symbol &sym,
96                             StringRef parentName);
97 
98   void enqueuePDB(StringRef Path) { enqueuePath(Path, false, false); }
99 
100   MemoryBufferRef takeBuffer(std::unique_ptr<MemoryBuffer> mb);
101 
102   void enqueuePath(StringRef path, bool wholeArchive, bool lazy);
103 
104   std::unique_ptr<llvm::TarWriter> tar; // for /linkrepro
105 
106 private:
107   // Searches a file from search paths.
108   Optional<StringRef> findFile(StringRef filename);
109   Optional<StringRef> findLib(StringRef filename);
110   StringRef doFindFile(StringRef filename);
111   StringRef doFindLib(StringRef filename);
112   StringRef doFindLibMinGW(StringRef filename);
113 
114   bool findUnderscoreMangle(StringRef sym);
115 
116   // Determines the location of the sysroot based on `args`, environment, etc.
117   void detectWinSysRoot(const llvm::opt::InputArgList &args);
118 
119   // Parses LIB environment which contains a list of search paths.
120   void addLibSearchPaths();
121 
122   // Library search path. The first element is always "" (current directory).
123   std::vector<StringRef> searchPaths;
124 
125   // Convert resource files and potentially merge input resource object
126   // trees into one resource tree.
127   void convertResources();
128 
129   void maybeExportMinGWSymbols(const llvm::opt::InputArgList &args);
130 
131   // We don't want to add the same file more than once.
132   // Files are uniquified by their filesystem and file number.
133   std::set<llvm::sys::fs::UniqueID> visitedFiles;
134 
135   std::set<std::string> visitedLibs;
136 
137   Symbol *addUndefined(StringRef sym);
138 
139   StringRef mangleMaybe(Symbol *s);
140 
141   // Windows specific -- "main" is not the only main function in Windows.
142   // You can choose one from these four -- {w,}{WinMain,main}.
143   // There are four different entry point functions for them,
144   // {w,}{WinMain,main}CRTStartup, respectively. The linker needs to
145   // choose the right one depending on which "main" function is defined.
146   // This function looks up the symbol table and resolve corresponding
147   // entry point name.
148   StringRef findDefaultEntry();
149   WindowsSubsystem inferSubsystem();
150 
151   void addBuffer(std::unique_ptr<MemoryBuffer> mb, bool wholeArchive,
152                  bool lazy);
153   void addArchiveBuffer(MemoryBufferRef mbref, StringRef symName,
154                         StringRef parentName, uint64_t offsetInArchive);
155 
156   void enqueueTask(std::function<void()> task);
157   bool run();
158 
159   std::list<std::function<void()>> taskQueue;
160   std::vector<StringRef> filePaths;
161   std::vector<MemoryBufferRef> resources;
162 
163   llvm::DenseSet<StringRef> directivesExports;
164   llvm::DenseSet<StringRef> excludedSymbols;
165 
166   COFFLinkerContext &ctx;
167 
168   llvm::ToolsetLayout vsLayout = llvm::ToolsetLayout::OlderVS;
169   std::string vcToolChainPath;
170   llvm::SmallString<128> diaPath;
171   bool useWinSysRootLibPath = false;
172   llvm::SmallString<128> universalCRTLibPath;
173   int sdkMajor = 0;
174   llvm::SmallString<128> windowsSdkLibPath;
175 };
176 
177 // Functions below this line are defined in DriverUtils.cpp.
178 
179 void printHelp(const char *argv0);
180 
181 // Parses a string in the form of "<integer>[,<integer>]".
182 void parseNumbers(StringRef arg, uint64_t *addr, uint64_t *size = nullptr);
183 
184 void parseGuard(StringRef arg);
185 
186 // Parses a string in the form of "<integer>[.<integer>]".
187 // Minor's default value is 0.
188 void parseVersion(StringRef arg, uint32_t *major, uint32_t *minor);
189 
190 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
191 void parseSubsystem(StringRef arg, WindowsSubsystem *sys, uint32_t *major,
192                     uint32_t *minor, bool *gotVersion = nullptr);
193 
194 void parseAlternateName(StringRef);
195 void parseMerge(StringRef);
196 void parsePDBPageSize(StringRef);
197 void parseSection(StringRef);
198 void parseAligncomm(StringRef);
199 
200 // Parses a string in the form of "[:<integer>]"
201 void parseFunctionPadMin(llvm::opt::Arg *a, llvm::COFF::MachineTypes machine);
202 
203 // Parses a string in the form of "EMBED[,=<integer>]|NO".
204 void parseManifest(StringRef arg);
205 
206 // Parses a string in the form of "level=<string>|uiAccess=<string>"
207 void parseManifestUAC(StringRef arg);
208 
209 // Parses a string in the form of "cd|net[,(cd|net)]*"
210 void parseSwaprun(StringRef arg);
211 
212 // Create a resource file containing a manifest XML.
213 std::unique_ptr<MemoryBuffer> createManifestRes();
214 void createSideBySideManifest();
215 
216 // Used for dllexported symbols.
217 Export parseExport(StringRef arg);
218 void fixupExports();
219 void assignExportOrdinals();
220 
221 // Parses a string in the form of "key=value" and check
222 // if value matches previous values for the key.
223 // This feature used in the directive section to reject
224 // incompatible objects.
225 void checkFailIfMismatch(StringRef arg, InputFile *source);
226 
227 // Convert Windows resource files (.res files) to a .obj file.
228 MemoryBufferRef convertResToCOFF(ArrayRef<MemoryBufferRef> mbs,
229                                  ArrayRef<ObjFile *> objs);
230 
231 // Create enum with OPT_xxx values for each option in Options.td
232 enum {
233   OPT_INVALID = 0,
234 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
235 #include "Options.inc"
236 #undef OPTION
237 };
238 
239 } // namespace coff
240 } // namespace lld
241 
242 #endif
243