Coverage Report

Created: 2018-06-25 02:00

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/lib/Driver/DarwinLdDriver.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- lib/Driver/DarwinLdDriver.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
/// \file
11
///
12
/// Concrete instance of the Driver for darwin's ld.
13
///
14
//===----------------------------------------------------------------------===//
15
16
#include "lld/Common/Args.h"
17
#include "lld/Common/ErrorHandler.h"
18
#include "lld/Common/LLVM.h"
19
#include "lld/Core/ArchiveLibraryFile.h"
20
#include "lld/Core/Error.h"
21
#include "lld/Core/File.h"
22
#include "lld/Core/Instrumentation.h"
23
#include "lld/Core/LinkingContext.h"
24
#include "lld/Core/Node.h"
25
#include "lld/Core/PassManager.h"
26
#include "lld/Core/Resolver.h"
27
#include "lld/Core/SharedLibraryFile.h"
28
#include "lld/Core/Simple.h"
29
#include "lld/ReaderWriter/MachOLinkingContext.h"
30
#include "llvm/ADT/ArrayRef.h"
31
#include "llvm/ADT/Optional.h"
32
#include "llvm/ADT/STLExtras.h"
33
#include "llvm/ADT/SmallString.h"
34
#include "llvm/ADT/StringExtras.h"
35
#include "llvm/ADT/StringRef.h"
36
#include "llvm/ADT/Twine.h"
37
#include "llvm/BinaryFormat/MachO.h"
38
#include "llvm/Option/Arg.h"
39
#include "llvm/Option/ArgList.h"
40
#include "llvm/Option/OptTable.h"
41
#include "llvm/Option/Option.h"
42
#include "llvm/Support/Casting.h"
43
#include "llvm/Support/CommandLine.h"
44
#include "llvm/Support/Error.h"
45
#include "llvm/Support/ErrorOr.h"
46
#include "llvm/Support/Format.h"
47
#include "llvm/Support/MathExtras.h"
48
#include "llvm/Support/MemoryBuffer.h"
49
#include "llvm/Support/Path.h"
50
#include "llvm/Support/raw_ostream.h"
51
#include <algorithm>
52
#include <cstdint>
53
#include <memory>
54
#include <string>
55
#include <system_error>
56
#include <utility>
57
#include <vector>
58
59
using namespace lld;
60
61
namespace {
62
63
// Create enum with OPT_xxx values for each option in DarwinLdOptions.td
64
enum {
65
  OPT_INVALID = 0,
66
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
67
               HELP, META, VALUES)                                             \
68
  OPT_##ID,
69
#include "DarwinLdOptions.inc"
70
#undef OPTION
71
};
72
73
// Create prefix string literals used in DarwinLdOptions.td
74
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
75
#include "DarwinLdOptions.inc"
76
#undef PREFIX
77
78
// Create table mapping all options defined in DarwinLdOptions.td
79
static const llvm::opt::OptTable::Info InfoTable[] = {
80
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
81
               HELPTEXT, METAVAR, VALUES)                                      \
82
  {PREFIX,      NAME,      HELPTEXT,                                           \
83
   METAVAR,     OPT_##ID,  llvm::opt::Option::KIND##Class,                     \
84
   PARAM,       FLAGS,     OPT_##GROUP,                                        \
85
   OPT_##ALIAS, ALIASARGS, VALUES},
86
#include "DarwinLdOptions.inc"
87
#undef OPTION
88
};
89
90
// Create OptTable class for parsing actual command line arguments
91
class DarwinLdOptTable : public llvm::opt::OptTable {
92
public:
93
243
  DarwinLdOptTable() : OptTable(InfoTable) {}
94
};
95
96
static std::vector<std::unique_ptr<File>>
97
64
makeErrorFile(StringRef path, std::error_code ec) {
98
64
  std::vector<std::unique_ptr<File>> result;
99
64
  result.push_back(llvm::make_unique<ErrorFile>(path, ec));
100
64
  return result;
101
64
}
102
103
static std::vector<std::unique_ptr<File>>
104
5
parseMemberFiles(std::unique_ptr<File> file) {
105
5
  std::vector<std::unique_ptr<File>> members;
106
5
  if (auto *archive = dyn_cast<ArchiveLibraryFile>(file.get())) {
107
2
    if (std::error_code ec = archive->parseAllMembers(members))
108
0
      return makeErrorFile(file->path(), ec);
109
3
  } else {
110
3
    members.push_back(std::move(file));
111
3
  }
112
5
  return members;
113
5
}
114
115
std::vector<std::unique_ptr<File>> loadFile(MachOLinkingContext &ctx,
116
                                            StringRef path, bool wholeArchive,
117
374
                                            bool upwardDylib) {
118
374
  if (ctx.logInputFiles())
119
3
    message(path);
120
374
121
374
  ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = ctx.getMemoryBuffer(path);
122
374
  if (std::error_code ec = mbOrErr.getError())
123
57
    return makeErrorFile(path, ec);
124
317
  ErrorOr<std::unique_ptr<File>> fileOrErr =
125
317
      ctx.registry().loadFile(std::move(mbOrErr.get()));
126
317
  if (std::error_code ec = fileOrErr.getError())
127
7
    return makeErrorFile(path, ec);
128
310
  std::unique_ptr<File> &file = fileOrErr.get();
129
310
130
310
  // If file is a dylib, inform LinkingContext about it.
131
310
  if (SharedLibraryFile *shl = dyn_cast<SharedLibraryFile>(file.get())) {
132
116
    if (std::error_code ec = shl->parse())
133
0
      return makeErrorFile(path, ec);
134
116
    ctx.registerDylib(reinterpret_cast<mach_o::MachODylibFile *>(shl),
135
116
                      upwardDylib);
136
116
  }
137
310
  if (wholeArchive)
138
5
    return parseMemberFiles(std::move(file));
139
305
  std::vector<std::unique_ptr<File>> files;
140
305
  files.push_back(std::move(file));
141
305
  return files;
142
305
}
143
144
} // end anonymous namespace
145
146
// Test may be running on Windows. Canonicalize the path
147
// separator to '/' to get consistent outputs for tests.
148
24
static std::string canonicalizePath(StringRef path) {
149
24
  char sep = llvm::sys::path::get_separator().front();
150
24
  if (sep != '/') {
151
0
    std::string fixedPath = path;
152
0
    std::replace(fixedPath.begin(), fixedPath.end(), sep, '/');
153
0
    return fixedPath;
154
24
  } else {
155
24
    return path;
156
24
  }
157
24
}
158
159
static void addFile(StringRef path, MachOLinkingContext &ctx,
160
374
                    bool loadWholeArchive, bool upwardDylib) {
161
374
  std::vector<std::unique_ptr<File>> files =
162
374
      loadFile(ctx, path, loadWholeArchive, upwardDylib);
163
374
  for (std::unique_ptr<File> &file : files)
164
374
    ctx.getNodes().push_back(llvm::make_unique<FileNode>(std::move(file)));
165
374
}
166
167
// Export lists are one symbol per line.  Blank lines are ignored.
168
// Trailing comments start with #.
169
static std::error_code parseExportsList(StringRef exportFilePath,
170
2
                                        MachOLinkingContext &ctx) {
171
2
  // Map in export list file.
172
2
  ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
173
2
                                   MemoryBuffer::getFileOrSTDIN(exportFilePath);
174
2
  if (std::error_code ec = mb.getError())
175
0
    return ec;
176
2
  ctx.addInputFileDependency(exportFilePath);
177
2
  StringRef buffer = mb->get()->getBuffer();
178
14
  while (!buffer.empty()) {
179
12
    // Split off each line in the file.
180
12
    std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
181
12
    StringRef line = lineAndRest.first;
182
12
    // Ignore trailing # comments.
183
12
    std::pair<StringRef, StringRef> symAndComment = line.split('#');
184
12
    StringRef sym = symAndComment.first.trim();
185
12
    if (!sym.empty())
186
4
      ctx.addExportSymbol(sym);
187
12
    buffer = lineAndRest.second;
188
12
  }
189
2
  return std::error_code();
190
2
}
191
192
/// Order files are one symbol per line. Blank lines are ignored.
193
/// Trailing comments start with #. Symbol names can be prefixed with an
194
/// architecture name and/or .o leaf name.  Examples:
195
///     _foo
196
///     bar.o:_bar
197
///     libfrob.a(bar.o):_bar
198
///     x86_64:_foo64
199
static std::error_code parseOrderFile(StringRef orderFilePath,
200
1
                                      MachOLinkingContext &ctx) {
201
1
  // Map in order file.
202
1
  ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
203
1
                                   MemoryBuffer::getFileOrSTDIN(orderFilePath);
204
1
  if (std::error_code ec = mb.getError())
205
0
    return ec;
206
1
  ctx.addInputFileDependency(orderFilePath);
207
1
  StringRef buffer = mb->get()->getBuffer();
208
12
  while (!buffer.empty()) {
209
11
    // Split off each line in the file.
210
11
    std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
211
11
    StringRef line = lineAndRest.first;
212
11
    buffer = lineAndRest.second;
213
11
    // Ignore trailing # comments.
214
11
    std::pair<StringRef, StringRef> symAndComment = line.split('#');
215
11
    if (symAndComment.first.empty())
216
4
      continue;
217
7
    StringRef sym = symAndComment.first.trim();
218
7
    if (sym.empty())
219
0
      continue;
220
7
    // Check for prefix.
221
7
    StringRef prefix;
222
7
    std::pair<StringRef, StringRef> prefixAndSym = sym.split(':');
223
7
    if (!prefixAndSym.second.empty()) {
224
3
      sym = prefixAndSym.second;
225
3
      prefix = prefixAndSym.first;
226
3
      if (!prefix.endswith(".o") && !prefix.endswith(".o)")) {
227
2
        // If arch name prefix does not match arch being linked, ignore symbol.
228
2
        if (!ctx.archName().equals(prefix))
229
2
          continue;
230
0
        prefix = "";
231
0
      }
232
3
    } else
233
4
     sym = prefixAndSym.first;
234
7
    
if (5
!sym.empty()5
) {
235
5
      ctx.appendOrderedSymbol(sym, prefix);
236
5
      //llvm::errs() << sym << ", prefix=" << prefix << "\n";
237
5
    }
238
5
  }
239
1
  return std::error_code();
240
1
}
241
242
//
243
// There are two variants of the  -filelist option:
244
//
245
//   -filelist <path>
246
// In this variant, the path is to a text file which contains one file path
247
// per line.  There are no comments or trimming of whitespace.
248
//
249
//   -fileList <path>,<dir>
250
// In this variant, the path is to a text file which contains a partial path
251
// per line. The <dir> prefix is prepended to each partial path.
252
//
253
static llvm::Error loadFileList(StringRef fileListPath,
254
2
                                MachOLinkingContext &ctx, bool forceLoad) {
255
2
  // If there is a comma, split off <dir>.
256
2
  std::pair<StringRef, StringRef> opt = fileListPath.split(',');
257
2
  StringRef filePath = opt.first;
258
2
  StringRef dirName = opt.second;
259
2
  ctx.addInputFileDependency(filePath);
260
2
  // Map in file list file.
261
2
  ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
262
2
                                        MemoryBuffer::getFileOrSTDIN(filePath);
263
2
  if (std::error_code ec = mb.getError())
264
0
    return llvm::errorCodeToError(ec);
265
2
  StringRef buffer = mb->get()->getBuffer();
266
8
  while (!buffer.empty()) {
267
6
    // Split off each line in the file.
268
6
    std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
269
6
    StringRef line = lineAndRest.first;
270
6
    StringRef path;
271
6
    if (!dirName.empty()) {
272
3
      // If there is a <dir> then prepend dir to each line.
273
3
      SmallString<256> fullPath;
274
3
      fullPath.assign(dirName);
275
3
      llvm::sys::path::append(fullPath, Twine(line));
276
3
      path = ctx.copy(fullPath.str());
277
3
    } else {
278
3
      // No <dir> use whole line as input file path.
279
3
      path = ctx.copy(line);
280
3
    }
281
6
    if (!ctx.pathExists(path)) {
282
0
      return llvm::make_error<GenericError>(Twine("File not found '")
283
0
                                            + path
284
0
                                            + "'");
285
0
    }
286
6
    if (ctx.testingFileUsage()) {
287
6
      message("Found filelist entry " + canonicalizePath(path));
288
6
    }
289
6
    addFile(path, ctx, forceLoad, false);
290
6
    buffer = lineAndRest.second;
291
6
  }
292
2
  return llvm::Error::success();
293
2
}
294
295
/// Parse number assuming it is base 16, but allow 0x prefix.
296
7
static bool parseNumberBase16(StringRef numStr, uint64_t &baseAddress) {
297
7
  if (numStr.startswith_lower("0x"))
298
2
    numStr = numStr.drop_front(2);
299
7
  return numStr.getAsInteger(16, baseAddress);
300
7
}
301
302
226
static void parseLLVMOptions(const LinkingContext &ctx) {
303
226
  // Honor -mllvm
304
226
  if (!ctx.llvmOptions().empty()) {
305
0
    unsigned numArgs = ctx.llvmOptions().size();
306
0
    auto **args = new const char *[numArgs + 2];
307
0
    args[0] = "lld (LLVM option parsing)";
308
0
    for (unsigned i = 0; i != numArgs; ++i)
309
0
      args[i + 1] = ctx.llvmOptions()[i];
310
0
    args[numArgs + 1] = nullptr;
311
0
    llvm::cl::ParseCommandLineOptions(numArgs + 1, args);
312
0
  }
313
226
}
314
315
namespace lld {
316
namespace mach_o {
317
318
243
bool parse(llvm::ArrayRef<const char *> args, MachOLinkingContext &ctx) {
319
243
  // Parse command line options using DarwinLdOptions.td
320
243
  DarwinLdOptTable table;
321
243
  unsigned missingIndex;
322
243
  unsigned missingCount;
323
243
  llvm::opt::InputArgList parsedArgs =
324
243
      table.ParseArgs(args.slice(1), missingIndex, missingCount);
325
243
  if (missingCount) {
326
0
    error("missing arg value for '" +
327
0
          Twine(parsedArgs.getArgString(missingIndex)) + "' expected " +
328
0
          Twine(missingCount) + " argument(s).");
329
0
    return false;
330
0
  }
331
243
332
243
  for (auto unknownArg : parsedArgs.filtered(OPT_UNKNOWN)) {
333
1
    warn("ignoring unknown argument: " +
334
1
         Twine(unknownArg->getAsString(parsedArgs)));
335
1
  }
336
243
337
243
  errorHandler().Verbose = parsedArgs.hasArg(OPT_v);
338
243
  errorHandler().ErrorLimit = args::getInteger(parsedArgs, OPT_error_limit, 20);
339
243
340
243
  // Figure out output kind ( -dylib, -r, -bundle, -preload, or -static )
341
243
  llvm::MachO::HeaderFileType fileType = llvm::MachO::MH_EXECUTE;
342
243
  bool isStaticExecutable = false;
343
243
  if (llvm::opt::Arg *kind = parsedArgs.getLastArg(
344
160
          OPT_dylib, OPT_relocatable, OPT_bundle, OPT_static, OPT_preload)) {
345
160
    switch (kind->getOption().getID()) {
346
160
    case OPT_dylib:
347
50
      fileType = llvm::MachO::MH_DYLIB;
348
50
      break;
349
160
    case OPT_relocatable:
350
90
      fileType = llvm::MachO::MH_OBJECT;
351
90
      break;
352
160
    case OPT_bundle:
353
9
      fileType = llvm::MachO::MH_BUNDLE;
354
9
      break;
355
160
    case OPT_static:
356
10
      fileType = llvm::MachO::MH_EXECUTE;
357
10
      isStaticExecutable = true;
358
10
      break;
359
160
    case OPT_preload:
360
1
      fileType = llvm::MachO::MH_PRELOAD;
361
1
      break;
362
243
    }
363
243
  }
364
243
365
243
  // Handle -arch xxx
366
243
  MachOLinkingContext::Arch arch = MachOLinkingContext::arch_unknown;
367
243
  if (llvm::opt::Arg *archStr = parsedArgs.getLastArg(OPT_arch)) {
368
236
    arch = MachOLinkingContext::archFromName(archStr->getValue());
369
236
    if (arch == MachOLinkingContext::arch_unknown) {
370
0
      error("unknown arch named '" + Twine(archStr->getValue()) + "'");
371
0
      return false;
372
0
    }
373
243
  }
374
243
  // If no -arch specified, scan input files to find first non-fat .o file.
375
243
  if (arch == MachOLinkingContext::arch_unknown) {
376
7
    for (auto &inFile : parsedArgs.filtered(OPT_INPUT)) {
377
1
      // This is expensive because it opens and maps the file.  But that is
378
1
      // ok because no -arch is rare.
379
1
      if (MachOLinkingContext::isThinObjectFile(inFile->getValue(), arch))
380
1
        break;
381
1
    }
382
7
    if (arch == MachOLinkingContext::arch_unknown &&
383
7
        
!parsedArgs.getLastArg(OPT_test_file_usage)6
) {
384
1
      // If no -arch and no options at all, print usage message.
385
1
      if (parsedArgs.size() == 0)
386
1
        table.PrintHelp(llvm::outs(), args[0], "LLVM Linker", false);
387
0
      else
388
0
        error("-arch not specified and could not be inferred");
389
1
      return false;
390
1
    }
391
242
  }
392
242
393
242
  // Handle -macosx_version_min or -ios_version_min
394
242
  MachOLinkingContext::OS os = MachOLinkingContext::OS::unknown;
395
242
  uint32_t minOSVersion = 0;
396
242
  if (llvm::opt::Arg *minOS =
397
64
          parsedArgs.getLastArg(OPT_macosx_version_min, OPT_ios_version_min,
398
64
                                OPT_ios_simulator_version_min)) {
399
64
    switch (minOS->getOption().getID()) {
400
64
    case OPT_macosx_version_min:
401
56
      os = MachOLinkingContext::OS::macOSX;
402
56
      if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
403
56
                                                  minOSVersion)) {
404
0
        error("malformed macosx_version_min value");
405
0
        return false;
406
0
      }
407
56
      break;
408
56
    case OPT_ios_version_min:
409
2
      os = MachOLinkingContext::OS::iOS;
410
2
      if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
411
2
                                                  minOSVersion)) {
412
0
        error("malformed ios_version_min value");
413
0
        return false;
414
0
      }
415
2
      break;
416
6
    case OPT_ios_simulator_version_min:
417
6
      os = MachOLinkingContext::OS::iOS_simulator;
418
6
      if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
419
6
                                                  minOSVersion)) {
420
0
        error("malformed ios_simulator_version_min value");
421
0
        return false;
422
0
      }
423
6
      break;
424
178
    }
425
178
  } else {
426
178
    // No min-os version on command line, check environment variables
427
178
  }
428
242
429
242
  // Handle export_dynamic
430
242
  // FIXME: Should we warn when this applies to something other than a static
431
242
  // executable or dylib?  Those are the only cases where this has an effect.
432
242
  // Note, this has to come before ctx.configure() so that we get the correct
433
242
  // value for _globalsAreDeadStripRoots.
434
242
  bool exportDynamicSymbols = parsedArgs.hasArg(OPT_export_dynamic);
435
242
436
242
  // Now that there's enough information parsed in, let the linking context
437
242
  // set up default values.
438
242
  ctx.configure(fileType, arch, os, minOSVersion, exportDynamicSymbols);
439
242
440
242
  // Handle -e xxx
441
242
  if (llvm::opt::Arg *entry = parsedArgs.getLastArg(OPT_entry))
442
5
    ctx.setEntrySymbolName(entry->getValue());
443
242
444
242
  // Handle -o xxx
445
242
  if (llvm::opt::Arg *outpath = parsedArgs.getLastArg(OPT_output))
446
178
    ctx.setOutputPath(outpath->getValue());
447
64
  else
448
64
    ctx.setOutputPath("a.out");
449
242
450
242
  // Handle -image_base XXX and -seg1addr XXXX
451
242
  if (llvm::opt::Arg *imageBase = parsedArgs.getLastArg(OPT_image_base)) {
452
4
    uint64_t baseAddress;
453
4
    if (parseNumberBase16(imageBase->getValue(), baseAddress)) {
454
1
      error("image_base expects a hex number");
455
1
      return false;
456
3
    } else if (baseAddress < ctx.pageZeroSize()) {
457
1
      error("image_base overlaps with __PAGEZERO");
458
1
      return false;
459
2
    } else if (baseAddress % ctx.pageSize()) {
460
1
      error("image_base must be a multiple of page size (0x" +
461
1
            llvm::utohexstr(ctx.pageSize()) + ")");
462
1
      return false;
463
1
    }
464
1
465
1
    ctx.setBaseAddress(baseAddress);
466
1
  }
467
242
468
242
  // Handle -dead_strip
469
242
  
if (239
parsedArgs.getLastArg(OPT_dead_strip)239
)
470
14
    ctx.setDeadStripping(true);
471
239
472
239
  bool globalWholeArchive = false;
473
239
  // Handle -all_load
474
239
  if (parsedArgs.getLastArg(OPT_all_load))
475
1
    globalWholeArchive = true;
476
239
477
239
  // Handle -install_name
478
239
  if (llvm::opt::Arg *installName = parsedArgs.getLastArg(OPT_install_name))
479
6
    ctx.setInstallName(installName->getValue());
480
233
  else
481
233
    ctx.setInstallName(ctx.outputPath());
482
239
483
239
  // Handle -mark_dead_strippable_dylib
484
239
  if (parsedArgs.getLastArg(OPT_mark_dead_strippable_dylib))
485
2
    ctx.setDeadStrippableDylib(true);
486
239
487
239
  // Handle -compatibility_version and -current_version
488
239
  if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_compatibility_version)) {
489
6
    if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
490
2
      error("-compatibility_version can only be used with -dylib");
491
2
      return false;
492
2
    }
493
4
    uint32_t parsedVers;
494
4
    if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
495
0
      error("-compatibility_version value is malformed");
496
0
      return false;
497
0
    }
498
4
    ctx.setCompatibilityVersion(parsedVers);
499
4
  }
500
239
501
239
  
if (llvm::opt::Arg *237
vers237
= parsedArgs.getLastArg(OPT_current_version)) {
502
6
    if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
503
2
      error("-current_version can only be used with -dylib");
504
2
      return false;
505
2
    }
506
4
    uint32_t parsedVers;
507
4
    if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
508
0
      error("-current_version value is malformed");
509
0
      return false;
510
0
    }
511
4
    ctx.setCurrentVersion(parsedVers);
512
4
  }
513
237
514
237
  // Handle -bundle_loader
515
237
  
if (llvm::opt::Arg *235
loader235
= parsedArgs.getLastArg(OPT_bundle_loader))
516
2
    ctx.setBundleLoader(loader->getValue());
517
235
518
235
  // Handle -sectalign segname sectname align
519
235
  for (auto &alignArg : parsedArgs.filtered(OPT_sectalign)) {
520
3
    const char* segName   = alignArg->getValue(0);
521
3
    const char* sectName  = alignArg->getValue(1);
522
3
    const char* alignStr  = alignArg->getValue(2);
523
3
    if ((alignStr[0] == '0') && (alignStr[1] == 'x'))
524
3
      alignStr += 2;
525
3
    unsigned long long alignValue;
526
3
    if (llvm::getAsUnsignedInteger(alignStr, 16, alignValue)) {
527
0
      error("-sectalign alignment value '" + Twine(alignStr) +
528
0
            "' not a valid number");
529
0
      return false;
530
0
    }
531
3
    uint16_t align = 1 << llvm::countTrailingZeros(alignValue);
532
3
    if (!llvm::isPowerOf2_64(alignValue)) {
533
0
      std::string Msg;
534
0
      llvm::raw_string_ostream OS(Msg);
535
0
      OS << "alignment for '-sectalign " << segName << " " << sectName
536
0
         << llvm::format(" 0x%llX", alignValue)
537
0
         << "' is not a power of two, using " << llvm::format("0x%08X", align);
538
0
      OS.flush();
539
0
      warn(Msg);
540
0
    }
541
3
    ctx.addSectionAlignment(segName, sectName, align);
542
3
  }
543
235
544
235
  // Handle -mllvm
545
235
  for (auto &llvmArg : parsedArgs.filtered(OPT_mllvm)) {
546
0
    ctx.appendLLVMOption(llvmArg->getValue());
547
0
  }
548
235
549
235
  // Handle -print_atoms
550
235
  if (parsedArgs.getLastArg(OPT_print_atoms))
551
61
    ctx.setPrintAtoms();
552
235
553
235
  // Handle -t (trace) option.
554
235
  if (parsedArgs.getLastArg(OPT_t))
555
1
    ctx.setLogInputFiles(true);
556
235
557
235
  // Handle -demangle option.
558
235
  if (parsedArgs.getLastArg(OPT_demangle))
559
1
    ctx.setDemangleSymbols(true);
560
235
561
235
  // Handle -keep_private_externs
562
235
  if (parsedArgs.getLastArg(OPT_keep_private_externs)) {
563
2
    ctx.setKeepPrivateExterns(true);
564
2
    if (ctx.outputMachOType() != llvm::MachO::MH_OBJECT)
565
0
      warn("-keep_private_externs only used in -r mode");
566
2
  }
567
235
568
235
  // Handle -dependency_info <path> used by Xcode.
569
235
  if (llvm::opt::Arg *depInfo = parsedArgs.getLastArg(OPT_dependency_info))
570
1
    if (std::error_code ec = ctx.createDependencyFile(depInfo->getValue()))
571
0
      warn(ec.message() + ", processing '-dependency_info " +
572
0
           depInfo->getValue());
573
235
574
235
  // In -test_file_usage mode, we'll be given an explicit list of paths that
575
235
  // exist. We'll also be expected to print out information about how we located
576
235
  // libraries and so on that the user specified, but not to actually do any
577
235
  // linking.
578
235
  if (parsedArgs.getLastArg(OPT_test_file_usage)) {
579
11
    ctx.setTestingFileUsage();
580
11
581
11
    // With paths existing by fiat, linking is not going to end well.
582
11
    ctx.setDoNothing(true);
583
11
584
11
    // Only bother looking for an existence override if we're going to use it.
585
65
    for (auto existingPath : parsedArgs.filtered(OPT_path_exists)) {
586
65
      ctx.addExistingPathForDebug(existingPath->getValue());
587
65
    }
588
11
  }
589
235
590
235
  // Register possible input file parsers.
591
235
  if (!ctx.doNothing()) {
592
224
    ctx.registry().addSupportMachOObjects(ctx);
593
224
    ctx.registry().addSupportArchives(ctx.logInputFiles());
594
224
    ctx.registry().addSupportYamlFiles();
595
224
  }
596
235
597
235
  // Now construct the set of library search directories, following ld64's
598
235
  // baroque set of accumulated hacks. Mostly, the algorithm constructs
599
235
  //     { syslibroots } x { libpaths }
600
235
  //
601
235
  // Unfortunately, there are numerous exceptions:
602
235
  //   1. Only absolute paths get modified by syslibroot options.
603
235
  //   2. If there is just 1 -syslibroot, system paths not found in it are
604
235
  //      skipped.
605
235
  //   3. If the last -syslibroot is "/", all of them are ignored entirely.
606
235
  //   4. If { syslibroots } x path ==  {}, the original path is kept.
607
235
  std::vector<StringRef> sysLibRoots;
608
235
  for (auto syslibRoot : parsedArgs.filtered(OPT_syslibroot)) {
609
8
    sysLibRoots.push_back(syslibRoot->getValue());
610
8
  }
611
235
  if (!sysLibRoots.empty()) {
612
6
    // Ignore all if last -syslibroot is "/".
613
6
    if (sysLibRoots.back() != "/")
614
5
      ctx.setSysLibRoots(sysLibRoots);
615
6
  }
616
235
617
235
  // Paths specified with -L come first, and are not considered system paths for
618
235
  // the case where there is precisely 1 -syslibroot.
619
235
  for (auto libPath : parsedArgs.filtered(OPT_L)) {
620
8
    ctx.addModifiedSearchDir(libPath->getValue());
621
8
  }
622
235
623
235
  // Process -F directories (where to look for frameworks).
624
235
  for (auto fwPath : parsedArgs.filtered(OPT_F)) {
625
5
    ctx.addFrameworkSearchDir(fwPath->getValue());
626
5
  }
627
235
628
235
  // -Z suppresses the standard search paths.
629
235
  if (!parsedArgs.hasArg(OPT_Z)) {
630
234
    ctx.addModifiedSearchDir("/usr/lib", true);
631
234
    ctx.addModifiedSearchDir("/usr/local/lib", true);
632
234
    ctx.addFrameworkSearchDir("/Library/Frameworks", true);
633
234
    ctx.addFrameworkSearchDir("/System/Library/Frameworks", true);
634
234
  }
635
235
636
235
  // Now that we've constructed the final set of search paths, print out those
637
235
  // search paths in verbose mode.
638
235
  if (errorHandler().Verbose) {
639
8
    message("Library search paths:");
640
15
    for (auto path : ctx.searchDirs()) {
641
15
      message("    " + path);
642
15
    }
643
8
    message("Framework search paths:");
644
8
    for (auto path : ctx.frameworkDirs()) {
645
5
      message("    " + path);
646
5
    }
647
8
  }
648
235
649
235
  // Handle -exported_symbols_list <file>
650
235
  for (auto expFile : parsedArgs.filtered(OPT_exported_symbols_list)) {
651
2
    if (ctx.exportMode() == MachOLinkingContext::ExportMode::blackList) {
652
0
      error("-exported_symbols_list cannot be combined with "
653
0
            "-unexported_symbol[s_list]");
654
0
      return false;
655
0
    }
656
2
    ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
657
2
    if (std::error_code ec = parseExportsList(expFile->getValue(), ctx)) {
658
0
      error(ec.message() + ", processing '-exported_symbols_list " +
659
0
            expFile->getValue());
660
0
      return false;
661
0
    }
662
2
  }
663
235
664
235
  // Handle -exported_symbol <symbol>
665
235
  for (auto symbol : parsedArgs.filtered(OPT_exported_symbol)) {
666
7
    if (ctx.exportMode() == MachOLinkingContext::ExportMode::blackList) {
667
0
      error("-exported_symbol cannot be combined with "
668
0
            "-unexported_symbol[s_list]");
669
0
      return false;
670
0
    }
671
7
    ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
672
7
    ctx.addExportSymbol(symbol->getValue());
673
7
  }
674
235
675
235
  // Handle -unexported_symbols_list <file>
676
235
  for (auto expFile : parsedArgs.filtered(OPT_unexported_symbols_list)) {
677
0
    if (ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) {
678
0
      error("-unexported_symbols_list cannot be combined with "
679
0
            "-exported_symbol[s_list]");
680
0
      return false;
681
0
    }
682
0
    ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
683
0
    if (std::error_code ec = parseExportsList(expFile->getValue(), ctx)) {
684
0
      error(ec.message() + ", processing '-unexported_symbols_list " +
685
0
            expFile->getValue());
686
0
      return false;
687
0
    }
688
0
  }
689
235
690
235
  // Handle -unexported_symbol <symbol>
691
235
  for (auto symbol : parsedArgs.filtered(OPT_unexported_symbol)) {
692
2
    if (ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) {
693
0
      error("-unexported_symbol cannot be combined with "
694
0
            "-exported_symbol[s_list]");
695
0
      return false;
696
0
    }
697
2
    ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
698
2
    ctx.addExportSymbol(symbol->getValue());
699
2
  }
700
235
701
235
  // Handle obosolete -multi_module and -single_module
702
235
  if (llvm::opt::Arg *mod =
703
1
          parsedArgs.getLastArg(OPT_multi_module, OPT_single_module)) {
704
1
    if (mod->getOption().getID() == OPT_multi_module)
705
0
      warn("-multi_module is obsolete and being ignored");
706
1
    else if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB)
707
0
      warn("-single_module being ignored. It is only for use when producing a "
708
0
           "dylib");
709
1
  }
710
235
711
235
  // Handle obsolete ObjC options: -objc_gc_compaction, -objc_gc, -objc_gc_only
712
235
  if (parsedArgs.getLastArg(OPT_objc_gc_compaction)) {
713
1
    error("-objc_gc_compaction is not supported");
714
1
    return false;
715
1
  }
716
234
717
234
  if (parsedArgs.getLastArg(OPT_objc_gc)) {
718
1
    error("-objc_gc is not supported");
719
1
    return false;
720
1
  }
721
233
722
233
  if (parsedArgs.getLastArg(OPT_objc_gc_only)) {
723
1
    error("-objc_gc_only is not supported");
724
1
    return false;
725
1
  }
726
232
727
232
  // Handle -pie or -no_pie
728
232
  if (llvm::opt::Arg *pie = parsedArgs.getLastArg(OPT_pie, OPT_no_pie)) {
729
2
    switch (ctx.outputMachOType()) {
730
2
    case llvm::MachO::MH_EXECUTE:
731
2
      switch (ctx.os()) {
732
2
      case MachOLinkingContext::OS::macOSX:
733
2
        if ((minOSVersion < 0x000A0500) &&
734
2
            
(pie->getOption().getID() == OPT_pie)0
) {
735
0
          error("-pie can only be used when targeting Mac OS X 10.5 or later");
736
0
          return false;
737
0
        }
738
2
        break;
739
2
      case MachOLinkingContext::OS::iOS:
740
0
        if ((minOSVersion < 0x00040200) &&
741
0
            (pie->getOption().getID() == OPT_pie)) {
742
0
          error("-pie can only be used when targeting iOS 4.2 or later");
743
0
          return false;
744
0
        }
745
0
        break;
746
0
      case MachOLinkingContext::OS::iOS_simulator:
747
0
        if (pie->getOption().getID() == OPT_no_pie) {
748
0
          error("iOS simulator programs must be built PIE");
749
0
          return false;
750
0
        }
751
0
        break;
752
0
      case MachOLinkingContext::OS::unknown:
753
0
        break;
754
2
      }
755
2
      ctx.setPIE(pie->getOption().getID() == OPT_pie);
756
2
      break;
757
2
    case llvm::MachO::MH_PRELOAD:
758
0
      break;
759
2
    case llvm::MachO::MH_DYLIB:
760
0
    case llvm::MachO::MH_BUNDLE:
761
0
      warn(pie->getSpelling() +
762
0
           " being ignored. It is only used when linking main executables");
763
0
      break;
764
0
    default:
765
0
      error(pie->getSpelling() +
766
0
            " can only used when linking main executables");
767
0
      return false;
768
232
    }
769
232
  }
770
232
771
232
  // Handle -version_load_command or -no_version_load_command
772
232
  {
773
232
    bool flagOn = false;
774
232
    bool flagOff = false;
775
232
    if (auto *arg = parsedArgs.getLastArg(OPT_version_load_command,
776
3
                                          OPT_no_version_load_command)) {
777
3
      flagOn = arg->getOption().getID() == OPT_version_load_command;
778
3
      flagOff = arg->getOption().getID() == OPT_no_version_load_command;
779
3
    }
780
232
781
232
    // default to adding version load command for dynamic code,
782
232
    // static code must opt-in
783
232
    switch (ctx.outputMachOType()) {
784
232
      case llvm::MachO::MH_OBJECT:
785
90
        ctx.setGenerateVersionLoadCommand(false);
786
90
        break;
787
232
      case llvm::MachO::MH_EXECUTE:
788
86
        // dynamic executables default to generating a version load command,
789
86
        // while static exectuables only generate it if required.
790
86
        if (isStaticExecutable) {
791
10
          if (flagOn)
792
1
            ctx.setGenerateVersionLoadCommand(true);
793
76
        } else {
794
76
          if (!flagOff)
795
76
            ctx.setGenerateVersionLoadCommand(true);
796
76
        }
797
86
        break;
798
232
      case llvm::MachO::MH_PRELOAD:
799
1
      case llvm::MachO::MH_KEXT_BUNDLE:
800
1
        if (flagOn)
801
0
          ctx.setGenerateVersionLoadCommand(true);
802
1
        break;
803
55
      case llvm::MachO::MH_DYLINKER:
804
55
      case llvm::MachO::MH_DYLIB:
805
55
      case llvm::MachO::MH_BUNDLE:
806
55
        if (!flagOff)
807
54
          ctx.setGenerateVersionLoadCommand(true);
808
55
        break;
809
55
      case llvm::MachO::MH_FVMLIB:
810
0
      case llvm::MachO::MH_DYLDLINK:
811
0
      case llvm::MachO::MH_DYLIB_STUB:
812
0
      case llvm::MachO::MH_DSYM:
813
0
        // We don't generate load commands for these file types, even if
814
0
        // forced on.
815
0
        break;
816
232
    }
817
232
  }
818
232
819
232
  // Handle -function_starts or -no_function_starts
820
232
  {
821
232
    bool flagOn = false;
822
232
    bool flagOff = false;
823
232
    if (auto *arg = parsedArgs.getLastArg(OPT_function_starts,
824
3
                                          OPT_no_function_starts)) {
825
3
      flagOn = arg->getOption().getID() == OPT_function_starts;
826
3
      flagOff = arg->getOption().getID() == OPT_no_function_starts;
827
3
    }
828
232
829
232
    // default to adding functions start for dynamic code, static code must
830
232
    // opt-in
831
232
    switch (ctx.outputMachOType()) {
832
232
      case llvm::MachO::MH_OBJECT:
833
90
        ctx.setGenerateFunctionStartsLoadCommand(false);
834
90
        break;
835
232
      case llvm::MachO::MH_EXECUTE:
836
86
        // dynamic executables default to generating a version load command,
837
86
        // while static exectuables only generate it if required.
838
86
        if (isStaticExecutable) {
839
10
          if (flagOn)
840
1
            ctx.setGenerateFunctionStartsLoadCommand(true);
841
76
        } else {
842
76
          if (!flagOff)
843
76
            ctx.setGenerateFunctionStartsLoadCommand(true);
844
76
        }
845
86
        break;
846
232
      case llvm::MachO::MH_PRELOAD:
847
1
      case llvm::MachO::MH_KEXT_BUNDLE:
848
1
        if (flagOn)
849
0
          ctx.setGenerateFunctionStartsLoadCommand(true);
850
1
        break;
851
55
      case llvm::MachO::MH_DYLINKER:
852
55
      case llvm::MachO::MH_DYLIB:
853
55
      case llvm::MachO::MH_BUNDLE:
854
55
        if (!flagOff)
855
54
          ctx.setGenerateFunctionStartsLoadCommand(true);
856
55
        break;
857
55
      case llvm::MachO::MH_FVMLIB:
858
0
      case llvm::MachO::MH_DYLDLINK:
859
0
      case llvm::MachO::MH_DYLIB_STUB:
860
0
      case llvm::MachO::MH_DSYM:
861
0
        // We don't generate load commands for these file types, even if
862
0
        // forced on.
863
0
        break;
864
232
    }
865
232
  }
866
232
867
232
  // Handle -data_in_code_info or -no_data_in_code_info
868
232
  {
869
232
    bool flagOn = false;
870
232
    bool flagOff = false;
871
232
    if (auto *arg = parsedArgs.getLastArg(OPT_data_in_code_info,
872
5
                                          OPT_no_data_in_code_info)) {
873
5
      flagOn = arg->getOption().getID() == OPT_data_in_code_info;
874
5
      flagOff = arg->getOption().getID() == OPT_no_data_in_code_info;
875
5
    }
876
232
877
232
    // default to adding data in code for dynamic code, static code must
878
232
    // opt-in
879
232
    switch (ctx.outputMachOType()) {
880
232
      case llvm::MachO::MH_OBJECT:
881
90
        if (!flagOff)
882
89
          ctx.setGenerateDataInCodeLoadCommand(true);
883
90
        break;
884
232
      case llvm::MachO::MH_EXECUTE:
885
86
        // dynamic executables default to generating a version load command,
886
86
        // while static exectuables only generate it if required.
887
86
        if (isStaticExecutable) {
888
10
          if (flagOn)
889
1
            ctx.setGenerateDataInCodeLoadCommand(true);
890
76
        } else {
891
76
          if (!flagOff)
892
76
            ctx.setGenerateDataInCodeLoadCommand(true);
893
76
        }
894
86
        break;
895
232
      case llvm::MachO::MH_PRELOAD:
896
1
      case llvm::MachO::MH_KEXT_BUNDLE:
897
1
        if (flagOn)
898
0
          ctx.setGenerateDataInCodeLoadCommand(true);
899
1
        break;
900
55
      case llvm::MachO::MH_DYLINKER:
901
55
      case llvm::MachO::MH_DYLIB:
902
55
      case llvm::MachO::MH_BUNDLE:
903
55
        if (!flagOff)
904
54
          ctx.setGenerateDataInCodeLoadCommand(true);
905
55
        break;
906
55
      case llvm::MachO::MH_FVMLIB:
907
0
      case llvm::MachO::MH_DYLDLINK:
908
0
      case llvm::MachO::MH_DYLIB_STUB:
909
0
      case llvm::MachO::MH_DSYM:
910
0
        // We don't generate load commands for these file types, even if
911
0
        // forced on.
912
0
        break;
913
232
    }
914
232
  }
915
232
916
232
  // Handle sdk_version
917
232
  if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_sdk_version)) {
918
2
    uint32_t sdkVersion = 0;
919
2
    if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
920
2
                                                sdkVersion)) {
921
1
      error("malformed sdkVersion value");
922
1
      return false;
923
1
    }
924
1
    ctx.setSdkVersion(sdkVersion);
925
230
  } else if (ctx.generateVersionLoadCommand()) {
926
129
    // If we don't have an sdk version, but were going to emit a load command
927
129
    // with min_version, then we need to give an warning as we have no sdk
928
129
    // version to put in that command.
929
129
    // FIXME: We need to decide whether to make this an error.
930
129
    warn("-sdk_version is required when emitting min version load command.  "
931
129
         "Setting sdk version to match provided min version");
932
129
    ctx.setSdkVersion(ctx.osMinVersion());
933
129
  }
934
232
935
232
  // Handle source_version
936
232
  
if (llvm::opt::Arg *231
arg231
= parsedArgs.getLastArg(OPT_source_version)) {
937
2
    uint64_t version = 0;
938
2
    if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
939
2
                                                version)) {
940
1
      error("malformed source_version value");
941
1
      return false;
942
1
    }
943
1
    ctx.setSourceVersion(version);
944
1
  }
945
231
946
231
  // Handle stack_size
947
231
  
if (llvm::opt::Arg *230
stackSize230
= parsedArgs.getLastArg(OPT_stack_size)) {
948
3
    uint64_t stackSizeVal;
949
3
    if (parseNumberBase16(stackSize->getValue(), stackSizeVal)) {
950
1
      error("stack_size expects a hex number");
951
1
      return false;
952
1
    }
953
2
    if ((stackSizeVal % ctx.pageSize()) != 0) {
954
1
      error("stack_size must be a multiple of page size (0x" +
955
1
            llvm::utohexstr(ctx.pageSize()) + ")");
956
1
      return false;
957
1
    }
958
1
959
1
    ctx.setStackSize(stackSizeVal);
960
1
  }
961
230
962
230
  // Handle debug info handling options: -S
963
230
  
if (228
parsedArgs.hasArg(OPT_S)228
)
964
0
    ctx.setDebugInfoMode(MachOLinkingContext::DebugInfoMode::noDebugMap);
965
228
966
228
  // Handle -order_file <file>
967
228
  for (auto orderFile : parsedArgs.filtered(OPT_order_file)) {
968
1
    if (std::error_code ec = parseOrderFile(orderFile->getValue(), ctx)) {
969
0
      error(ec.message() + ", processing '-order_file " + orderFile->getValue()
970
0
            + "'");
971
0
      return false;
972
0
    }
973
1
  }
974
228
975
228
  // Handle -flat_namespace.
976
228
  if (llvm::opt::Arg *ns =
977
5
          parsedArgs.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace)) {
978
5
    if (ns->getOption().getID() == OPT_flat_namespace)
979
2
      ctx.setUseFlatNamespace(true);
980
5
  }
981
228
982
228
  // Handle -undefined
983
228
  if (llvm::opt::Arg *undef = parsedArgs.getLastArg(OPT_undefined)) {
984
5
    MachOLinkingContext::UndefinedMode UndefMode;
985
5
    if (StringRef(undef->getValue()).equals("error"))
986
1
      UndefMode = MachOLinkingContext::UndefinedMode::error;
987
4
    else if (StringRef(undef->getValue()).equals("warning"))
988
1
      UndefMode = MachOLinkingContext::UndefinedMode::warning;
989
3
    else if (StringRef(undef->getValue()).equals("suppress"))
990
2
      UndefMode = MachOLinkingContext::UndefinedMode::suppress;
991
1
    else if (StringRef(undef->getValue()).equals("dynamic_lookup"))
992
1
      UndefMode = MachOLinkingContext::UndefinedMode::dynamicLookup;
993
0
    else {
994
0
      error("invalid option to -undefined [ warning | error | suppress | "
995
0
            "dynamic_lookup ]");
996
0
      return false;
997
0
    }
998
5
999
5
    if (ctx.useFlatNamespace()) {
1000
2
      // If we're using -flat_namespace then 'warning', 'suppress' and
1001
2
      // 'dynamic_lookup' are all equivalent, so map them to 'suppress'.
1002
2
      if (UndefMode != MachOLinkingContext::UndefinedMode::error)
1003
1
        UndefMode = MachOLinkingContext::UndefinedMode::suppress;
1004
3
    } else {
1005
3
      // If we're using -twolevel_namespace then 'warning' and 'suppress' are
1006
3
      // illegal. Emit a diagnostic if they've been (mis)used.
1007
3
      if (UndefMode == MachOLinkingContext::UndefinedMode::warning ||
1008
3
          
UndefMode == MachOLinkingContext::UndefinedMode::suppress2
) {
1009
2
        error("can't use -undefined warning or suppress with "
1010
2
              "-twolevel_namespace");
1011
2
        return false;
1012
2
      }
1013
3
    }
1014
3
1015
3
    ctx.setUndefinedMode(UndefMode);
1016
3
  }
1017
228
1018
228
  // Handle -no_objc_category_merging.
1019
228
  
if (226
parsedArgs.getLastArg(OPT_no_objc_category_merging)226
)
1020
0
    ctx.setMergeObjCCategories(false);
1021
226
1022
226
  // Handle -rpath <path>
1023
226
  if (parsedArgs.hasArg(OPT_rpath)) {
1024
1
    switch (ctx.outputMachOType()) {
1025
1
      case llvm::MachO::MH_EXECUTE:
1026
1
      case llvm::MachO::MH_DYLIB:
1027
1
      case llvm::MachO::MH_BUNDLE:
1028
1
        if (!ctx.minOS("10.5", "2.0")) {
1029
0
          if (ctx.os() == MachOLinkingContext::OS::macOSX)
1030
0
            error("-rpath can only be used when targeting OS X 10.5 or later");
1031
0
          else
1032
0
            error("-rpath can only be used when targeting iOS 2.0 or later");
1033
0
          return false;
1034
0
        }
1035
1
        break;
1036
1
      default:
1037
0
        error("-rpath can only be used when creating a dynamic final linked "
1038
0
              "image");
1039
0
        return false;
1040
1
    }
1041
1
1042
1
    for (auto rPath : parsedArgs.filtered(OPT_rpath)) {
1043
1
      ctx.addRpath(rPath->getValue());
1044
1
    }
1045
1
  }
1046
226
1047
226
  // Parse the LLVM options before we process files in case the file handling
1048
226
  // makes use of things like LLVM_DEBUG().
1049
226
  parseLLVMOptions(ctx);
1050
226
1051
226
  // Handle input files and sectcreate.
1052
1.25k
  for (auto &arg : parsedArgs) {
1053
1.25k
    bool upward;
1054
1.25k
    llvm::Optional<StringRef> resolvedPath;
1055
1.25k
    switch (arg->getOption().getID()) {
1056
1.25k
    default:
1057
885
      continue;
1058
1.25k
    case OPT_INPUT:
1059
342
      addFile(arg->getValue(), ctx, globalWholeArchive, false);
1060
342
      break;
1061
1.25k
    case OPT_upward_library:
1062
2
      addFile(arg->getValue(), ctx, false, true);
1063
2
      break;
1064
1.25k
    case OPT_force_load:
1065
2
      addFile(arg->getValue(), ctx, true, false);
1066
2
      break;
1067
1.25k
    case OPT_l:
1068
16
    case OPT_upward_l:
1069
16
      upward = (arg->getOption().getID() == OPT_upward_l);
1070
16
      resolvedPath = ctx.searchLibrary(arg->getValue());
1071
16
      if (!resolvedPath) {
1072
1
        error("Unable to find library for " + arg->getSpelling() +
1073
1
              arg->getValue());
1074
1
        return false;
1075
15
      } else if (ctx.testingFileUsage()) {
1076
11
        message(Twine("Found ") + (upward ? 
"upward "1
:
" "10
) + "library " +
1077
11
                canonicalizePath(resolvedPath.getValue()));
1078
11
      }
1079
16
      addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
1080
15
      break;
1081
16
    case OPT_framework:
1082
7
    case OPT_upward_framework:
1083
7
      upward = (arg->getOption().getID() == OPT_upward_framework);
1084
7
      resolvedPath = ctx.findPathForFramework(arg->getValue());
1085
7
      if (!resolvedPath) {
1086
0
        error("Unable to find framework for " + arg->getSpelling() + " " +
1087
0
              arg->getValue());
1088
0
        return false;
1089
7
      } else if (ctx.testingFileUsage()) {
1090
7
        message(Twine("Found ") + (upward ? 
"upward "1
:
" "6
) + "framework " +
1091
7
                canonicalizePath(resolvedPath.getValue()));
1092
7
      }
1093
7
      addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
1094
7
      break;
1095
7
    case OPT_filelist:
1096
2
      if (auto ec = loadFileList(arg->getValue(), ctx, globalWholeArchive)) {
1097
0
        handleAllErrors(std::move(ec), [&](const llvm::ErrorInfoBase &EI) {
1098
0
          error(EI.message() + ", processing '-filelist " + arg->getValue());
1099
0
        });
1100
0
        return false;
1101
0
      }
1102
2
      break;
1103
2
    case OPT_sectcreate: {
1104
1
        const char* seg  = arg->getValue(0);
1105
1
        const char* sect = arg->getValue(1);
1106
1
        const char* fileName = arg->getValue(2);
1107
1
1108
1
        ErrorOr<std::unique_ptr<MemoryBuffer>> contentOrErr =
1109
1
          MemoryBuffer::getFile(fileName);
1110
1
1111
1
        if (!contentOrErr) {
1112
0
          error("can't open -sectcreate file " + Twine(fileName));
1113
0
          return false;
1114
0
        }
1115
1
1116
1
        ctx.addSectCreateSection(seg, sect, std::move(*contentOrErr));
1117
1
      }
1118
1
      break;
1119
1.25k
    }
1120
1.25k
  }
1121
226
1122
226
  
if (225
ctx.getNodes().empty()225
) {
1123
0
    error("No input files");
1124
0
    return false;
1125
0
  }
1126
225
1127
225
  // Validate the combination of options used.
1128
225
  return ctx.validate();
1129
225
}
1130
1131
366
static void createFiles(MachOLinkingContext &ctx, bool Implicit) {
1132
366
  std::vector<std::unique_ptr<File>> Files;
1133
366
  if (Implicit)
1134
183
    ctx.createImplicitFiles(Files);
1135
183
  else
1136
183
    ctx.createInternalFiles(Files);
1137
686
  for (auto i = Files.rbegin(), e = Files.rend(); i != e; 
++i320
) {
1138
320
    auto &members = ctx.getNodes();
1139
320
    members.insert(members.begin(), llvm::make_unique<FileNode>(std::move(*i)));
1140
320
  }
1141
366
}
1142
1143
/// This is where the link is actually performed.
1144
bool link(llvm::ArrayRef<const char *> args, bool CanExitEarly,
1145
207
          raw_ostream &Error) {
1146
207
  errorHandler().LogName = args[0];
1147
207
  errorHandler().ErrorLimitExceededMsg =
1148
207
      "too many errors emitted, stopping now (use "
1149
207
      "'-error-limit 0' to see all errors)";
1150
207
  errorHandler().ErrorOS = &Error;
1151
207
  errorHandler().ExitEarly = CanExitEarly;
1152
207
  errorHandler().ColorDiagnostics = Error.has_colors();
1153
207
1154
207
  MachOLinkingContext ctx;
1155
207
  if (!parse(args, ctx))
1156
14
    return false;
1157
193
  if (ctx.doNothing())
1158
10
    return true;
1159
183
  if (ctx.getNodes().empty())
1160
0
    return false;
1161
183
1162
183
  for (std::unique_ptr<Node> &ie : ctx.getNodes())
1163
317
    if (FileNode *node = dyn_cast<FileNode>(ie.get()))
1164
317
      node->getFile()->parse();
1165
183
1166
183
  createFiles(ctx, false /* Implicit */);
1167
183
1168
183
  // Give target a chance to add files
1169
183
  createFiles(ctx, true /* Implicit */);
1170
183
1171
183
  // Give target a chance to postprocess input files.
1172
183
  // Mach-O uses this chance to move all object files before library files.
1173
183
  ctx.finalizeInputFiles();
1174
183
1175
183
  // Do core linking.
1176
183
  ScopedTask resolveTask(getDefaultDomain(), "Resolve");
1177
183
  Resolver resolver(ctx);
1178
183
  if (!resolver.resolve())
1179
14
    return false;
1180
169
  SimpleFile *merged = nullptr;
1181
169
  {
1182
169
    std::unique_ptr<SimpleFile> mergedFile = resolver.resultFile();
1183
169
    merged = mergedFile.get();
1184
169
    auto &members = ctx.getNodes();
1185
169
    members.insert(members.begin(),
1186
169
                   llvm::make_unique<FileNode>(std::move(mergedFile)));
1187
169
  }
1188
169
  resolveTask.end();
1189
169
1190
169
  // Run passes on linked atoms.
1191
169
  ScopedTask passTask(getDefaultDomain(), "Passes");
1192
169
  PassManager pm;
1193
169
  ctx.addPasses(pm);
1194
169
  if (auto ec = pm.runOnFile(*merged)) {
1195
1
    // FIXME: This should be passed to logAllUnhandledErrors but it needs
1196
1
    // to be passed a Twine instead of a string.
1197
1
    *errorHandler().ErrorOS << "Failed to run passes on file '"
1198
1
                            << ctx.outputPath() << "': ";
1199
1
    logAllUnhandledErrors(std::move(ec), *errorHandler().ErrorOS,
1200
1
                          std::string());
1201
1
    return false;
1202
1
  }
1203
168
1204
168
  passTask.end();
1205
168
1206
168
  // Give linked atoms to Writer to generate output file.
1207
168
  ScopedTask writeTask(getDefaultDomain(), "Write");
1208
168
  if (auto ec = ctx.writeFile(*merged)) {
1209
1
    // FIXME: This should be passed to logAllUnhandledErrors but it needs
1210
1
    // to be passed a Twine instead of a string.
1211
1
    *errorHandler().ErrorOS << "Failed to write file '" << ctx.outputPath()
1212
1
                            << "': ";
1213
1
    logAllUnhandledErrors(std::move(ec), *errorHandler().ErrorOS,
1214
1
                          std::string());
1215
1
    return false;
1216
1
  }
1217
167
1218
167
  // Call exit() if we can to avoid calling destructors.
1219
167
  if (CanExitEarly)
1220
0
    exitLld(errorCount() ? 1 : 0);
1221
167
1222
167
1223
167
  return true;
1224
167
}
1225
1226
} // end namespace mach_o
1227
} // end namespace lld