Coverage Report

Created: 2019-05-22 02:55

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