1 //===- DriverUtils.cpp ----------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains utility functions for the driver. Because there
11 // are so many small functions, we created this separate file to make
12 // Driver.cpp less cluttered.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "Config.h"
17 #include "Driver.h"
18 #include "Error.h"
19 #include "Symbols.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Object/Archive.h"
23 #include "llvm/Object/ArchiveWriter.h"
24 #include "llvm/Object/COFF.h"
25 #include "llvm/Option/Arg.h"
26 #include "llvm/Option/ArgList.h"
27 #include "llvm/Option/Option.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/FileUtilities.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/Process.h"
32 #include "llvm/Support/Program.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <memory>
35 
36 using namespace llvm::COFF;
37 using namespace llvm;
38 using llvm::cl::ExpandResponseFiles;
39 using llvm::cl::TokenizeWindowsCommandLine;
40 using llvm::sys::Process;
41 
42 namespace lld {
43 namespace coff {
44 namespace {
45 
46 class Executor {
47 public:
48   explicit Executor(StringRef S) : Saver(Alloc), Prog(Saver.save(S)) {}
49   void add(StringRef S)    { Args.push_back(Saver.save(S)); }
50   void add(std::string &S) { Args.push_back(Saver.save(S)); }
51   void add(Twine S)        { Args.push_back(Saver.save(S)); }
52   void add(const char *S)  { Args.push_back(Saver.save(S)); }
53 
54   void run() {
55     ErrorOr<std::string> ExeOrErr = llvm::sys::findProgramByName(Prog);
56     error(ExeOrErr, Twine("unable to find ") + Prog + " in PATH: ");
57     const char *Exe = Saver.save(*ExeOrErr);
58     Args.insert(Args.begin(), Exe);
59     Args.push_back(nullptr);
60     if (llvm::sys::ExecuteAndWait(Args[0], Args.data()) != 0) {
61       for (const char *S : Args)
62         if (S)
63           llvm::errs() << S << " ";
64       error("failed");
65     }
66   }
67 
68 private:
69   llvm::BumpPtrAllocator Alloc;
70   llvm::StringSaver Saver;
71   StringRef Prog;
72   std::vector<const char *> Args;
73 };
74 
75 } // anonymous namespace
76 
77 // Returns /machine's value.
78 MachineTypes getMachineType(StringRef S) {
79   MachineTypes MT = StringSwitch<MachineTypes>(S.lower())
80                         .Case("x64", AMD64)
81                         .Case("amd64", AMD64)
82                         .Case("x86", I386)
83                         .Case("i386", I386)
84                         .Case("arm", ARMNT)
85                         .Default(IMAGE_FILE_MACHINE_UNKNOWN);
86   if (MT != IMAGE_FILE_MACHINE_UNKNOWN)
87     return MT;
88   error(Twine("unknown /machine argument: ") + S);
89 }
90 
91 StringRef machineToStr(MachineTypes MT) {
92   switch (MT) {
93   case ARMNT:
94     return "arm";
95   case AMD64:
96     return "x64";
97   case I386:
98     return "x86";
99   default:
100     llvm_unreachable("unknown machine type");
101   }
102 }
103 
104 // Parses a string in the form of "<integer>[,<integer>]".
105 void parseNumbers(StringRef Arg, uint64_t *Addr, uint64_t *Size) {
106   StringRef S1, S2;
107   std::tie(S1, S2) = Arg.split(',');
108   if (S1.getAsInteger(0, *Addr))
109     error(Twine("invalid number: ") + S1);
110   if (Size && !S2.empty() && S2.getAsInteger(0, *Size))
111     error(Twine("invalid number: ") + S2);
112 }
113 
114 // Parses a string in the form of "<integer>[.<integer>]".
115 // If second number is not present, Minor is set to 0.
116 void parseVersion(StringRef Arg, uint32_t *Major, uint32_t *Minor) {
117   StringRef S1, S2;
118   std::tie(S1, S2) = Arg.split('.');
119   if (S1.getAsInteger(0, *Major))
120     error(Twine("invalid number: ") + S1);
121   *Minor = 0;
122   if (!S2.empty() && S2.getAsInteger(0, *Minor))
123     error(Twine("invalid number: ") + S2);
124 }
125 
126 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
127 void parseSubsystem(StringRef Arg, WindowsSubsystem *Sys, uint32_t *Major,
128                     uint32_t *Minor) {
129   StringRef SysStr, Ver;
130   std::tie(SysStr, Ver) = Arg.split(',');
131   *Sys = StringSwitch<WindowsSubsystem>(SysStr.lower())
132     .Case("boot_application", IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)
133     .Case("console", IMAGE_SUBSYSTEM_WINDOWS_CUI)
134     .Case("efi_application", IMAGE_SUBSYSTEM_EFI_APPLICATION)
135     .Case("efi_boot_service_driver", IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)
136     .Case("efi_rom", IMAGE_SUBSYSTEM_EFI_ROM)
137     .Case("efi_runtime_driver", IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)
138     .Case("native", IMAGE_SUBSYSTEM_NATIVE)
139     .Case("posix", IMAGE_SUBSYSTEM_POSIX_CUI)
140     .Case("windows", IMAGE_SUBSYSTEM_WINDOWS_GUI)
141     .Default(IMAGE_SUBSYSTEM_UNKNOWN);
142   if (*Sys == IMAGE_SUBSYSTEM_UNKNOWN)
143     error(Twine("unknown subsystem: ") + SysStr);
144   if (!Ver.empty())
145     parseVersion(Ver, Major, Minor);
146 }
147 
148 // Parse a string of the form of "<from>=<to>".
149 // Results are directly written to Config.
150 void parseAlternateName(StringRef S) {
151   StringRef From, To;
152   std::tie(From, To) = S.split('=');
153   if (From.empty() || To.empty())
154     error(Twine("/alternatename: invalid argument: ") + S);
155   auto It = Config->AlternateNames.find(From);
156   if (It != Config->AlternateNames.end() && It->second != To)
157     error(Twine("/alternatename: conflicts: ") + S);
158   Config->AlternateNames.insert(It, std::make_pair(From, To));
159 }
160 
161 // Parse a string of the form of "<from>=<to>".
162 // Results are directly written to Config.
163 void parseMerge(StringRef S) {
164   StringRef From, To;
165   std::tie(From, To) = S.split('=');
166   if (From.empty() || To.empty())
167     error(Twine("/merge: invalid argument: ") + S);
168   auto Pair = Config->Merge.insert(std::make_pair(From, To));
169   bool Inserted = Pair.second;
170   if (!Inserted) {
171     StringRef Existing = Pair.first->second;
172     if (Existing != To)
173       llvm::errs() << "warning: " << S << ": already merged into "
174                    << Existing << "\n";
175   }
176 }
177 
178 // Parses a string in the form of "EMBED[,=<integer>]|NO".
179 // Results are directly written to Config.
180 void parseManifest(StringRef Arg) {
181   if (Arg.equals_lower("no")) {
182     Config->Manifest = Configuration::No;
183     return;
184   }
185   if (!Arg.startswith_lower("embed"))
186     error(Twine("Invalid option ") + Arg);
187   Config->Manifest = Configuration::Embed;
188   Arg = Arg.substr(strlen("embed"));
189   if (Arg.empty())
190     return;
191   if (!Arg.startswith_lower(",id="))
192     error(Twine("Invalid option ") + Arg);
193   Arg = Arg.substr(strlen(",id="));
194   if (Arg.getAsInteger(0, Config->ManifestID))
195     error(Twine("Invalid option ") + Arg);
196 }
197 
198 // Parses a string in the form of "level=<string>|uiAccess=<string>|NO".
199 // Results are directly written to Config.
200 void parseManifestUAC(StringRef Arg) {
201   if (Arg.equals_lower("no")) {
202     Config->ManifestUAC = false;
203     return;
204   }
205   for (;;) {
206     Arg = Arg.ltrim();
207     if (Arg.empty())
208       return;
209     if (Arg.startswith_lower("level=")) {
210       Arg = Arg.substr(strlen("level="));
211       std::tie(Config->ManifestLevel, Arg) = Arg.split(" ");
212       continue;
213     }
214     if (Arg.startswith_lower("uiaccess=")) {
215       Arg = Arg.substr(strlen("uiaccess="));
216       std::tie(Config->ManifestUIAccess, Arg) = Arg.split(" ");
217       continue;
218     }
219     error(Twine("Invalid option ") + Arg);
220   }
221 }
222 
223 // Quote each line with "". Existing double-quote is converted
224 // to two double-quotes.
225 static void quoteAndPrint(raw_ostream &Out, StringRef S) {
226   while (!S.empty()) {
227     StringRef Line;
228     std::tie(Line, S) = S.split("\n");
229     if (Line.empty())
230       continue;
231     Out << '\"';
232     for (int I = 0, E = Line.size(); I != E; ++I) {
233       if (Line[I] == '\"') {
234         Out << "\"\"";
235       } else {
236         Out << Line[I];
237       }
238     }
239     Out << "\"\n";
240   }
241 }
242 
243 // Create the default manifest file as a temporary file.
244 static std::string createDefaultXml() {
245   // Create a temporary file.
246   SmallString<128> Path;
247   std::error_code EC = sys::fs::createTemporaryFile("tmp", "manifest", Path);
248   error(EC, "cannot create a temporary file");
249 
250   // Open the temporary file for writing.
251   llvm::raw_fd_ostream OS(Path, EC, sys::fs::F_Text);
252   error(EC, Twine("failed to open ") + Path);
253 
254   // Emit the XML. Note that we do *not* verify that the XML attributes are
255   // syntactically correct. This is intentional for link.exe compatibility.
256   OS << "<?xml version=\"1.0\" standalone=\"yes\"?>\n"
257      << "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n"
258      << "          manifestVersion=\"1.0\">\n";
259   if (Config->ManifestUAC) {
260     OS << "  <trustInfo>\n"
261        << "    <security>\n"
262        << "      <requestedPrivileges>\n"
263        << "         <requestedExecutionLevel level=" << Config->ManifestLevel
264        << " uiAccess=" << Config->ManifestUIAccess << "/>\n"
265        << "      </requestedPrivileges>\n"
266        << "    </security>\n"
267        << "  </trustInfo>\n";
268     if (!Config->ManifestDependency.empty()) {
269       OS << "  <dependency>\n"
270          << "    <dependentAssembly>\n"
271          << "      <assemblyIdentity " << Config->ManifestDependency << " />\n"
272          << "    </dependentAssembly>\n"
273          << "  </dependency>\n";
274     }
275   }
276   OS << "</assembly>\n";
277   OS.close();
278   return StringRef(Path);
279 }
280 
281 static std::string readFile(StringRef Path) {
282   ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = MemoryBuffer::getFile(Path);
283   error(BufOrErr, "Could not open " + Path);
284   std::unique_ptr<MemoryBuffer> Buf(std::move(*BufOrErr));
285   return Buf->getBuffer();
286 }
287 
288 static std::string createManifestXml() {
289   // Create the default manifest file.
290   std::string Path1 = createDefaultXml();
291   if (Config->ManifestInput.empty())
292     return readFile(Path1);
293 
294   // If manifest files are supplied by the user using /MANIFESTINPUT
295   // option, we need to merge them with the default manifest.
296   SmallString<128> Path2;
297   std::error_code EC = sys::fs::createTemporaryFile("tmp", "manifest", Path2);
298   error(EC, "cannot create a temporary file");
299   FileRemover Remover1(Path1);
300   FileRemover Remover2(Path2);
301 
302   Executor E("mt.exe");
303   E.add("/manifest");
304   E.add(Path1);
305   for (StringRef Filename : Config->ManifestInput) {
306     E.add("/manifest");
307     E.add(Filename);
308   }
309   E.add("/nologo");
310   E.add("/out:" + StringRef(Path2));
311   E.run();
312   return readFile(Path2);
313 }
314 
315 // Create a resource file containing a manifest XML.
316 std::unique_ptr<MemoryBuffer> createManifestRes() {
317   // Create a temporary file for the resource script file.
318   SmallString<128> RCPath;
319   std::error_code EC = sys::fs::createTemporaryFile("tmp", "rc", RCPath);
320   error(EC, "cannot create a temporary file");
321   FileRemover RCRemover(RCPath);
322 
323   // Open the temporary file for writing.
324   llvm::raw_fd_ostream Out(RCPath, EC, sys::fs::F_Text);
325   error(EC, Twine("failed to open ") + RCPath);
326 
327   // Write resource script to the RC file.
328   Out << "#define LANG_ENGLISH 9\n"
329       << "#define SUBLANG_DEFAULT 1\n"
330       << "#define APP_MANIFEST " << Config->ManifestID << "\n"
331       << "#define RT_MANIFEST 24\n"
332       << "LANGUAGE LANG_ENGLISH, SUBLANG_DEFAULT\n"
333       << "APP_MANIFEST RT_MANIFEST {\n";
334   quoteAndPrint(Out, createManifestXml());
335   Out << "}\n";
336   Out.close();
337 
338   // Create output resource file.
339   SmallString<128> ResPath;
340   EC = sys::fs::createTemporaryFile("tmp", "res", ResPath);
341   error(EC, "cannot create a temporary file");
342 
343   Executor E("rc.exe");
344   E.add("/fo");
345   E.add(ResPath.str());
346   E.add("/nologo");
347   E.add(RCPath.str());
348   E.run();
349   ErrorOr<std::unique_ptr<MemoryBuffer>> Ret = MemoryBuffer::getFile(ResPath);
350   error(Ret, Twine("Could not open ") + ResPath);
351   return std::move(*Ret);
352 }
353 
354 void createSideBySideManifest() {
355   std::string Path = Config->ManifestFile;
356   if (Path == "")
357     Path = (Twine(Config->OutputFile) + ".manifest").str();
358   std::error_code EC;
359   llvm::raw_fd_ostream Out(Path, EC, llvm::sys::fs::F_Text);
360   error(EC, "failed to create manifest");
361   Out << createManifestXml();
362 }
363 
364 // Parse a string in the form of
365 // "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]"
366 // or "<name>=<dllname>.<name>".
367 // Used for parsing /export arguments.
368 Export parseExport(StringRef Arg) {
369   Export E;
370   StringRef Rest;
371   std::tie(E.Name, Rest) = Arg.split(",");
372   if (E.Name.empty())
373     goto err;
374 
375   if (E.Name.find('=') != StringRef::npos) {
376     StringRef X, Y;
377     std::tie(X, Y) = E.Name.split("=");
378 
379     // If "<name>=<dllname>.<name>".
380     if (Y.find(".") != StringRef::npos) {
381       E.Name = X;
382       E.ForwardTo = Y;
383       return E;
384     }
385 
386     E.ExtName = X;
387     E.Name = Y;
388     if (E.Name.empty())
389       goto err;
390   }
391 
392   // If "<name>=<internalname>[,@ordinal[,NONAME]][,DATA][,PRIVATE]"
393   while (!Rest.empty()) {
394     StringRef Tok;
395     std::tie(Tok, Rest) = Rest.split(",");
396     if (Tok.equals_lower("noname")) {
397       if (E.Ordinal == 0)
398         goto err;
399       E.Noname = true;
400       continue;
401     }
402     if (Tok.equals_lower("data")) {
403       E.Data = true;
404       continue;
405     }
406     if (Tok.equals_lower("private")) {
407       E.Private = true;
408       continue;
409     }
410     if (Tok.startswith("@")) {
411       int32_t Ord;
412       if (Tok.substr(1).getAsInteger(0, Ord))
413         goto err;
414       if (Ord <= 0 || 65535 < Ord)
415         goto err;
416       E.Ordinal = Ord;
417       continue;
418     }
419     goto err;
420   }
421   return E;
422 
423 err:
424   error(Twine("invalid /export: ") + Arg);
425 }
426 
427 static StringRef undecorate(StringRef Sym) {
428   if (Config->Machine != I386)
429     return Sym;
430   return Sym.startswith("_") ? Sym.substr(1) : Sym;
431 }
432 
433 // Performs error checking on all /export arguments.
434 // It also sets ordinals.
435 void fixupExports() {
436   // Symbol ordinals must be unique.
437   std::set<uint16_t> Ords;
438   for (Export &E : Config->Exports) {
439     if (E.Ordinal == 0)
440       continue;
441     if (!Ords.insert(E.Ordinal).second)
442       error("duplicate export ordinal: " + E.Name);
443   }
444 
445   for (Export &E : Config->Exports) {
446     if (!E.ForwardTo.empty()) {
447       E.SymbolName = E.Name;
448     } else if (Undefined *U = cast_or_null<Undefined>(E.Sym->WeakAlias)) {
449       E.SymbolName = U->getName();
450     } else {
451       E.SymbolName = E.Sym->getName();
452     }
453   }
454 
455   for (Export &E : Config->Exports) {
456     if (!E.ForwardTo.empty()) {
457       E.ExportName = undecorate(E.Name);
458     } else {
459       E.ExportName = undecorate(E.ExtName.empty() ? E.Name : E.ExtName);
460     }
461   }
462 
463   // Uniquefy by name.
464   std::map<StringRef, Export *> Map;
465   std::vector<Export> V;
466   for (Export &E : Config->Exports) {
467     auto Pair = Map.insert(std::make_pair(E.ExportName, &E));
468     bool Inserted = Pair.second;
469     if (Inserted) {
470       V.push_back(E);
471       continue;
472     }
473     Export *Existing = Pair.first->second;
474     if (E == *Existing || E.Name != Existing->Name)
475       continue;
476     llvm::errs() << "warning: duplicate /export option: " << E.Name << "\n";
477   }
478   Config->Exports = std::move(V);
479 
480   // Sort by name.
481   std::sort(Config->Exports.begin(), Config->Exports.end(),
482             [](const Export &A, const Export &B) {
483               return A.ExportName < B.ExportName;
484             });
485 }
486 
487 void assignExportOrdinals() {
488   // Assign unique ordinals if default (= 0).
489   uint16_t Max = 0;
490   for (Export &E : Config->Exports)
491     Max = std::max(Max, E.Ordinal);
492   for (Export &E : Config->Exports)
493     if (E.Ordinal == 0)
494       E.Ordinal = ++Max;
495 }
496 
497 // Parses a string in the form of "key=value" and check
498 // if value matches previous values for the same key.
499 void checkFailIfMismatch(StringRef Arg) {
500   StringRef K, V;
501   std::tie(K, V) = Arg.split('=');
502   if (K.empty() || V.empty())
503     error(Twine("/failifmismatch: invalid argument: ") + Arg);
504   StringRef Existing = Config->MustMatch[K];
505   if (!Existing.empty() && V != Existing)
506     error(Twine("/failifmismatch: mismatch detected: ") + Existing + " and " +
507           V + " for key " + K);
508   Config->MustMatch[K] = V;
509 }
510 
511 // Convert Windows resource files (.res files) to a .obj file
512 // using cvtres.exe.
513 std::unique_ptr<MemoryBuffer>
514 convertResToCOFF(const std::vector<MemoryBufferRef> &MBs) {
515   // Create an output file path.
516   SmallString<128> Path;
517   if (llvm::sys::fs::createTemporaryFile("resource", "obj", Path))
518     error("Could not create temporary file");
519 
520   // Execute cvtres.exe.
521   Executor E("cvtres.exe");
522   E.add("/machine:" + machineToStr(Config->Machine));
523   E.add("/readonly");
524   E.add("/nologo");
525   E.add("/out:" + Path);
526   for (MemoryBufferRef MB : MBs)
527     E.add(MB.getBufferIdentifier());
528   E.run();
529   ErrorOr<std::unique_ptr<MemoryBuffer>> Ret = MemoryBuffer::getFile(Path);
530   error(Ret, Twine("Could not open ") + Path);
531   return std::move(*Ret);
532 }
533 
534 static std::string writeToTempFile(StringRef Contents) {
535   SmallString<128> Path;
536   int FD;
537   if (llvm::sys::fs::createTemporaryFile("tmp", "def", FD, Path)) {
538     llvm::errs() << "failed to create a temporary file\n";
539     return "";
540   }
541   llvm::raw_fd_ostream OS(FD, /*shouldClose*/ true);
542   OS << Contents;
543   return Path.str();
544 }
545 
546 void touchFile(StringRef Path) {
547   int FD;
548   std::error_code EC = sys::fs::openFileForWrite(Path, FD, sys::fs::F_Append);
549   error(EC, "failed to create a file");
550   sys::Process::SafelyCloseFileDescriptor(FD);
551 }
552 
553 static std::string getImplibPath() {
554   if (!Config->Implib.empty())
555     return Config->Implib;
556   SmallString<128> Out = StringRef(Config->OutputFile);
557   sys::path::replace_extension(Out, ".lib");
558   return Out.str();
559 }
560 
561 static std::unique_ptr<MemoryBuffer> createEmptyImportLibrary() {
562   std::string S = (Twine("LIBRARY \"") +
563                    llvm::sys::path::filename(Config->OutputFile) + "\"\n")
564                       .str();
565   std::string Path1 = writeToTempFile(S);
566   std::string Path2 = getImplibPath();
567   llvm::FileRemover Remover1(Path1);
568   llvm::FileRemover Remover2(Path2);
569 
570   Executor E("lib.exe");
571   E.add("/nologo");
572   E.add("/machine:" + machineToStr(Config->Machine));
573   E.add(Twine("/def:") + Path1);
574   E.add(Twine("/out:") + Path2);
575   E.run();
576 
577   ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
578       MemoryBuffer::getFile(Path2, -1, false);
579   error(BufOrErr, Twine("Failed to open ") + Path2);
580   return MemoryBuffer::getMemBufferCopy((*BufOrErr)->getBuffer());
581 }
582 
583 static std::vector<NewArchiveIterator>
584 readMembers(const object::Archive &Archive) {
585   std::vector<NewArchiveIterator> V;
586   for (const auto &ChildOrErr : Archive.children()) {
587     error(ChildOrErr, "Archive::Child::getName failed");
588     const object::Archive::Child C(*ChildOrErr);
589     ErrorOr<StringRef> NameOrErr = C.getName();
590     error(NameOrErr, "Archive::Child::getName failed");
591     V.emplace_back(C, *NameOrErr);
592   }
593   return V;
594 }
595 
596 // This class creates short import files which is described in
597 // PE/COFF spec 7. Import Library Format.
598 class ShortImportCreator {
599 public:
600   ShortImportCreator(object::Archive *A, StringRef S) : Parent(A), DLLName(S) {}
601 
602   NewArchiveIterator create(StringRef Sym, uint16_t Ordinal,
603                             ImportNameType NameType, bool isData) {
604     size_t ImpSize = DLLName.size() + Sym.size() + 2; // +2 for NULs
605     size_t Size = sizeof(object::ArchiveMemberHeader) +
606                   sizeof(coff_import_header) + ImpSize;
607     char *Buf = Alloc.Allocate<char>(Size);
608     memset(Buf, 0, Size);
609     char *P = Buf;
610 
611     // Write archive member header
612     auto *Hdr = reinterpret_cast<object::ArchiveMemberHeader *>(P);
613     P += sizeof(*Hdr);
614     sprintf(Hdr->Name, "%-12s", "dummy");
615     sprintf(Hdr->LastModified, "%-12d", 0);
616     sprintf(Hdr->UID, "%-6d", 0);
617     sprintf(Hdr->GID, "%-6d", 0);
618     sprintf(Hdr->AccessMode, "%-8d", 0644);
619     sprintf(Hdr->Size, "%-10d", int(sizeof(coff_import_header) + ImpSize));
620 
621     // Write short import library.
622     auto *Imp = reinterpret_cast<coff_import_header *>(P);
623     P += sizeof(*Imp);
624     Imp->Sig2 = 0xFFFF;
625     Imp->Machine = Config->Machine;
626     Imp->SizeOfData = ImpSize;
627     if (Ordinal > 0)
628       Imp->OrdinalHint = Ordinal;
629     Imp->TypeInfo = (isData ? IMPORT_DATA : IMPORT_CODE);
630     Imp->TypeInfo |= NameType << 2;
631 
632     // Write symbol name and DLL name.
633     memcpy(P, Sym.data(), Sym.size());
634     P += Sym.size() + 1;
635     memcpy(P, DLLName.data(), DLLName.size());
636 
637     std::error_code EC;
638     object::Archive::Child C(Parent, Buf, &EC);
639     assert(!EC && "We created an invalid buffer");
640     return NewArchiveIterator(C, DLLName);
641   }
642 
643 private:
644   BumpPtrAllocator Alloc;
645   object::Archive *Parent;
646   StringRef DLLName;
647 };
648 
649 static ImportNameType getNameType(StringRef Sym, StringRef ExtName) {
650   if (Sym != ExtName)
651     return IMPORT_NAME_UNDECORATE;
652   if (Config->Machine == I386 && Sym.startswith("_"))
653     return IMPORT_NAME_NOPREFIX;
654   return IMPORT_NAME;
655 }
656 
657 static std::string replace(StringRef S, StringRef From, StringRef To) {
658   size_t Pos = S.find(From);
659   assert(Pos != StringRef::npos);
660   return (Twine(S.substr(0, Pos)) + To + S.substr(Pos + From.size())).str();
661 }
662 
663 // Creates an import library for a DLL. In this function, we first
664 // create an empty import library using lib.exe and then adds short
665 // import files to that file.
666 void writeImportLibrary() {
667   std::unique_ptr<MemoryBuffer> Buf = createEmptyImportLibrary();
668   std::error_code EC;
669   object::Archive Archive(Buf->getMemBufferRef(), EC);
670   error(EC, "Error reading an empty import file");
671   std::vector<NewArchiveIterator> Members = readMembers(Archive);
672 
673   std::string DLLName = llvm::sys::path::filename(Config->OutputFile);
674   ShortImportCreator ShortImport(&Archive, DLLName);
675   for (Export &E : Config->Exports) {
676     if (E.Private)
677       continue;
678     if (E.ExtName.empty()) {
679       Members.push_back(ShortImport.create(
680           E.SymbolName, E.Ordinal, getNameType(E.SymbolName, E.Name), E.Data));
681     } else {
682       Members.push_back(ShortImport.create(
683           replace(E.SymbolName, E.Name, E.ExtName), E.Ordinal,
684           getNameType(E.SymbolName, E.Name), E.Data));
685     }
686   }
687 
688   std::string Path = getImplibPath();
689   std::pair<StringRef, std::error_code> Result =
690       writeArchive(Path, Members, /*WriteSymtab*/ true, object::Archive::K_GNU,
691                    /*Deterministic*/ true, /*Thin*/ false);
692   error(Result.second, Twine("Failed to write ") + Path);
693 }
694 
695 // Create OptTable
696 
697 // Create prefix string literals used in Options.td
698 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
699 #include "Options.inc"
700 #undef PREFIX
701 
702 // Create table mapping all options defined in Options.td
703 static const llvm::opt::OptTable::Info infoTable[] = {
704 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X6, X7, X8, X9, X10)    \
705   {                                                                    \
706     X1, X2, X9, X10, OPT_##ID, llvm::opt::Option::KIND##Class, X8, X7, \
707     OPT_##GROUP, OPT_##ALIAS, X6                                       \
708   },
709 #include "Options.inc"
710 #undef OPTION
711 };
712 
713 class COFFOptTable : public llvm::opt::OptTable {
714 public:
715   COFFOptTable() : OptTable(infoTable, true) {}
716 };
717 
718 // Parses a given list of options.
719 llvm::opt::InputArgList ArgParser::parse(ArrayRef<const char *> ArgsArr) {
720   // First, replace respnose files (@<file>-style options).
721   std::vector<const char *> Argv = replaceResponseFiles(ArgsArr);
722 
723   // Make InputArgList from string vectors.
724   COFFOptTable Table;
725   unsigned MissingIndex;
726   unsigned MissingCount;
727   llvm::opt::InputArgList Args =
728       Table.ParseArgs(Argv, MissingIndex, MissingCount);
729 
730   // Print the real command line if response files are expanded.
731   if (Args.hasArg(OPT_verbose) && ArgsArr.size() != Argv.size()) {
732     llvm::outs() << "Command line:";
733     for (const char *S : Argv)
734       llvm::outs() << " " << S;
735     llvm::outs() << "\n";
736   }
737 
738   if (MissingCount)
739     error(Twine("missing arg value for \"") + Args.getArgString(MissingIndex) +
740           "\", expected " + Twine(MissingCount) +
741           (MissingCount == 1 ? " argument." : " arguments."));
742   for (auto *Arg : Args.filtered(OPT_UNKNOWN))
743     llvm::errs() << "ignoring unknown argument: " << Arg->getSpelling() << "\n";
744   return Args;
745 }
746 
747 llvm::opt::InputArgList ArgParser::parseLINK(ArrayRef<const char *> Args) {
748   // Concatenate LINK env and given arguments and parse them.
749   Optional<std::string> Env = Process::GetEnv("LINK");
750   if (!Env)
751     return parse(Args);
752   std::vector<const char *> V = tokenize(*Env);
753   V.insert(V.end(), Args.begin(), Args.end());
754   return parse(V);
755 }
756 
757 std::vector<const char *> ArgParser::tokenize(StringRef S) {
758   SmallVector<const char *, 16> Tokens;
759   StringSaver Saver(AllocAux);
760   llvm::cl::TokenizeWindowsCommandLine(S, Saver, Tokens);
761   return std::vector<const char *>(Tokens.begin(), Tokens.end());
762 }
763 
764 // Creates a new command line by replacing options starting with '@'
765 // character. '@<filename>' is replaced by the file's contents.
766 std::vector<const char *>
767 ArgParser::replaceResponseFiles(std::vector<const char *> Argv) {
768   SmallVector<const char *, 256> Tokens(Argv.data(), Argv.data() + Argv.size());
769   StringSaver Saver(AllocAux);
770   ExpandResponseFiles(Saver, TokenizeWindowsCommandLine, Tokens);
771   return std::vector<const char *>(Tokens.begin(), Tokens.end());
772 }
773 
774 void printHelp(const char *Argv0) {
775   COFFOptTable Table;
776   Table.PrintHelp(llvm::outs(), Argv0, "LLVM Linker", false);
777 }
778 
779 } // namespace coff
780 } // namespace lld
781