Coverage Report

Created: 2019-01-21 03:01

/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
243
  DarwinLdOptTable() : OptTable(InfoTable) {}
93
};
94
95
static std::vector<std::unique_ptr<File>>
96
64
makeErrorFile(StringRef path, std::error_code ec) {
97
64
  std::vector<std::unique_ptr<File>> result;
98
64
  result.push_back(llvm::make_unique<ErrorFile>(path, ec));
99
64
  return result;
100
64
}
101
102
static std::vector<std::unique_ptr<File>>
103
5
parseMemberFiles(std::unique_ptr<File> file) {
104
5
  std::vector<std::unique_ptr<File>> members;
105
5
  if (auto *archive = dyn_cast<ArchiveLibraryFile>(file.get())) {
106
2
    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
5
  return members;
112
5
}
113
114
std::vector<std::unique_ptr<File>> loadFile(MachOLinkingContext &ctx,
115
                                            StringRef path, bool wholeArchive,
116
374
                                            bool upwardDylib) {
117
374
  if (ctx.logInputFiles())
118
3
    message(path);
119
374
120
374
  ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = ctx.getMemoryBuffer(path);
121
374
  if (std::error_code ec = mbOrErr.getError())
122
57
    return makeErrorFile(path, ec);
123
317
  ErrorOr<std::unique_ptr<File>> fileOrErr =
124
317
      ctx.registry().loadFile(std::move(mbOrErr.get()));
125
317
  if (std::error_code ec = fileOrErr.getError())
126
7
    return makeErrorFile(path, ec);
127
310
  std::unique_ptr<File> &file = fileOrErr.get();
128
310
129
310
  // If file is a dylib, inform LinkingContext about it.
130
310
  if (SharedLibraryFile *shl = dyn_cast<SharedLibraryFile>(file.get())) {
131
116
    if (std::error_code ec = shl->parse())
132
0
      return makeErrorFile(path, ec);
133
116
    ctx.registerDylib(reinterpret_cast<mach_o::MachODylibFile *>(shl),
134
116
                      upwardDylib);
135
116
  }
136
310
  if (wholeArchive)
137
5
    return parseMemberFiles(std::move(file));
138
305
  std::vector<std::unique_ptr<File>> files;
139
305
  files.push_back(std::move(file));
140
305
  return files;
141
305
}
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
24
static std::string canonicalizePath(StringRef path) {
148
24
  char sep = llvm::sys::path::get_separator().front();
149
24
  if (sep != '/') {
150
0
    std::string fixedPath = path;
151
0
    std::replace(fixedPath.begin(), fixedPath.end(), sep, '/');
152
0
    return fixedPath;
153
24
  } else {
154
24
    return path;
155
24
  }
156
24
}
157
158
static void addFile(StringRef path, MachOLinkingContext &ctx,
159
374
                    bool loadWholeArchive, bool upwardDylib) {
160
374
  std::vector<std::unique_ptr<File>> files =
161
374
      loadFile(ctx, path, loadWholeArchive, upwardDylib);
162
374
  for (std::unique_ptr<File> &file : files)
163
374
    ctx.getNodes().push_back(llvm::make_unique<FileNode>(std::move(file)));
164
374
}
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
1
                                      MachOLinkingContext &ctx) {
200
1
  // Map in order file.
201
1
  ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
202
1
                                   MemoryBuffer::getFileOrSTDIN(orderFilePath);
203
1
  if (std::error_code ec = mb.getError())
204
0
    return ec;
205
1
  ctx.addInputFileDependency(orderFilePath);
206
1
  StringRef buffer = mb->get()->getBuffer();
207
12
  while (!buffer.empty()) {
208
11
    // Split off each line in the file.
209
11
    std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
210
11
    StringRef line = lineAndRest.first;
211
11
    buffer = lineAndRest.second;
212
11
    // Ignore trailing # comments.
213
11
    std::pair<StringRef, StringRef> symAndComment = line.split('#');
214
11
    if (symAndComment.first.empty())
215
4
      continue;
216
7
    StringRef sym = symAndComment.first.trim();
217
7
    if (sym.empty())
218
0
      continue;
219
7
    // Check for prefix.
220
7
    StringRef prefix;
221
7
    std::pair<StringRef, StringRef> prefixAndSym = sym.split(':');
222
7
    if (!prefixAndSym.second.empty()) {
223
3
      sym = prefixAndSym.second;
224
3
      prefix = prefixAndSym.first;
225
3
      if (!prefix.endswith(".o") && !prefix.endswith(".o)")) {
226
2
        // If arch name prefix does not match arch being linked, ignore symbol.
227
2
        if (!ctx.archName().equals(prefix))
228
2
          continue;
229
0
        prefix = "";
230
0
      }
231
3
    } else
232
4
     sym = prefixAndSym.first;
233
7
    
if (5
!sym.empty()5
) {
234
5
      ctx.appendOrderedSymbol(sym, prefix);
235
5
      //llvm::errs() << sym << ", prefix=" << prefix << "\n";
236
5
    }
237
5
  }
238
1
  return std::error_code();
239
1
}
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
2
                                MachOLinkingContext &ctx, bool forceLoad) {
254
2
  // If there is a comma, split off <dir>.
255
2
  std::pair<StringRef, StringRef> opt = fileListPath.split(',');
256
2
  StringRef filePath = opt.first;
257
2
  StringRef dirName = opt.second;
258
2
  ctx.addInputFileDependency(filePath);
259
2
  // Map in file list file.
260
2
  ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
261
2
                                        MemoryBuffer::getFileOrSTDIN(filePath);
262
2
  if (std::error_code ec = mb.getError())
263
0
    return llvm::errorCodeToError(ec);
264
2
  StringRef buffer = mb->get()->getBuffer();
265
8
  while (!buffer.empty()) {
266
6
    // Split off each line in the file.
267
6
    std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
268
6
    StringRef line = lineAndRest.first;
269
6
    StringRef path;
270
6
    if (!dirName.empty()) {
271
3
      // If there is a <dir> then prepend dir to each line.
272
3
      SmallString<256> fullPath;
273
3
      fullPath.assign(dirName);
274
3
      llvm::sys::path::append(fullPath, Twine(line));
275
3
      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
6
    if (!ctx.pathExists(path)) {
281
0
      return llvm::make_error<GenericError>(Twine("File not found '")
282
0
                                            + path
283
0
                                            + "'");
284
0
    }
285
6
    if (ctx.testingFileUsage()) {
286
6
      message("Found filelist entry " + canonicalizePath(path));
287
6
    }
288
6
    addFile(path, ctx, forceLoad, false);
289
6
    buffer = lineAndRest.second;
290
6
  }
291
2
  return llvm::Error::success();
292
2
}
293
294
/// Parse number assuming it is base 16, but allow 0x prefix.
295
7
static bool parseNumberBase16(StringRef numStr, uint64_t &baseAddress) {
296
7
  if (numStr.startswith_lower("0x"))
297
2
    numStr = numStr.drop_front(2);
298
7
  return numStr.getAsInteger(16, baseAddress);
299
7
}
300
301
226
static void parseLLVMOptions(const LinkingContext &ctx) {
302
226
  // Honor -mllvm
303
226
  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
226
}
313
314
namespace lld {
315
namespace mach_o {
316
317
243
bool parse(llvm::ArrayRef<const char *> args, MachOLinkingContext &ctx) {
318
243
  // Parse command line options using DarwinLdOptions.td
319
243
  DarwinLdOptTable table;
320
243
  unsigned missingIndex;
321
243
  unsigned missingCount;
322
243
  llvm::opt::InputArgList parsedArgs =
323
243
      table.ParseArgs(args.slice(1), missingIndex, missingCount);
324
243
  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
243
331
243
  for (auto unknownArg : parsedArgs.filtered(OPT_UNKNOWN)) {
332
1
    warn("ignoring unknown argument: " +
333
1
         Twine(unknownArg->getAsString(parsedArgs)));
334
1
  }
335
243
336
243
  errorHandler().Verbose = parsedArgs.hasArg(OPT_v);
337
243
  errorHandler().ErrorLimit = args::getInteger(parsedArgs, OPT_error_limit, 20);
338
243
339
243
  // Figure out output kind ( -dylib, -r, -bundle, -preload, or -static )
340
243
  llvm::MachO::HeaderFileType fileType = llvm::MachO::MH_EXECUTE;
341
243
  bool isStaticExecutable = false;
342
243
  if (llvm::opt::Arg *kind = parsedArgs.getLastArg(
343
160
          OPT_dylib, OPT_relocatable, OPT_bundle, OPT_static, OPT_preload)) {
344
160
    switch (kind->getOption().getID()) {
345
160
    case OPT_dylib:
346
50
      fileType = llvm::MachO::MH_DYLIB;
347
50
      break;
348
160
    case OPT_relocatable:
349
90
      fileType = llvm::MachO::MH_OBJECT;
350
90
      break;
351
160
    case OPT_bundle:
352
9
      fileType = llvm::MachO::MH_BUNDLE;
353
9
      break;
354
160
    case OPT_static:
355
10
      fileType = llvm::MachO::MH_EXECUTE;
356
10
      isStaticExecutable = true;
357
10
      break;
358
160
    case OPT_preload:
359
1
      fileType = llvm::MachO::MH_PRELOAD;
360
1
      break;
361
243
    }
362
243
  }
363
243
364
243
  // Handle -arch xxx
365
243
  MachOLinkingContext::Arch arch = MachOLinkingContext::arch_unknown;
366
243
  if (llvm::opt::Arg *archStr = parsedArgs.getLastArg(OPT_arch)) {
367
236
    arch = MachOLinkingContext::archFromName(archStr->getValue());
368
236
    if (arch == MachOLinkingContext::arch_unknown) {
369
0
      error("unknown arch named '" + Twine(archStr->getValue()) + "'");
370
0
      return false;
371
0
    }
372
243
  }
373
243
  // If no -arch specified, scan input files to find first non-fat .o file.
374
243
  if (arch == MachOLinkingContext::arch_unknown) {
375
7
    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
7
    if (arch == MachOLinkingContext::arch_unknown &&
382
7
        
!parsedArgs.getLastArg(OPT_test_file_usage)6
) {
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
242
  }
394
242
395
242
  // Handle -macosx_version_min or -ios_version_min
396
242
  MachOLinkingContext::OS os = MachOLinkingContext::OS::unknown;
397
242
  uint32_t minOSVersion = 0;
398
242
  if (llvm::opt::Arg *minOS =
399
64
          parsedArgs.getLastArg(OPT_macosx_version_min, OPT_ios_version_min,
400
64
                                OPT_ios_simulator_version_min)) {
401
64
    switch (minOS->getOption().getID()) {
402
64
    case OPT_macosx_version_min:
403
56
      os = MachOLinkingContext::OS::macOSX;
404
56
      if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
405
56
                                                  minOSVersion)) {
406
0
        error("malformed macosx_version_min value");
407
0
        return false;
408
0
      }
409
56
      break;
410
56
    case OPT_ios_version_min:
411
2
      os = MachOLinkingContext::OS::iOS;
412
2
      if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
413
2
                                                  minOSVersion)) {
414
0
        error("malformed ios_version_min value");
415
0
        return false;
416
0
      }
417
2
      break;
418
6
    case OPT_ios_simulator_version_min:
419
6
      os = MachOLinkingContext::OS::iOS_simulator;
420
6
      if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
421
6
                                                  minOSVersion)) {
422
0
        error("malformed ios_simulator_version_min value");
423
0
        return false;
424
0
      }
425
6
      break;
426
178
    }
427
178
  } else {
428
178
    // No min-os version on command line, check environment variables
429
178
  }
430
242
431
242
  // Handle export_dynamic
432
242
  // FIXME: Should we warn when this applies to something other than a static
433
242
  // executable or dylib?  Those are the only cases where this has an effect.
434
242
  // Note, this has to come before ctx.configure() so that we get the correct
435
242
  // value for _globalsAreDeadStripRoots.
436
242
  bool exportDynamicSymbols = parsedArgs.hasArg(OPT_export_dynamic);
437
242
438
242
  // Now that there's enough information parsed in, let the linking context
439
242
  // set up default values.
440
242
  ctx.configure(fileType, arch, os, minOSVersion, exportDynamicSymbols);
441
242
442
242
  // Handle -e xxx
443
242
  if (llvm::opt::Arg *entry = parsedArgs.getLastArg(OPT_entry))
444
5
    ctx.setEntrySymbolName(entry->getValue());
445
242
446
242
  // Handle -o xxx
447
242
  if (llvm::opt::Arg *outpath = parsedArgs.getLastArg(OPT_output))
448
178
    ctx.setOutputPath(outpath->getValue());
449
64
  else
450
64
    ctx.setOutputPath("a.out");
451
242
452
242
  // Handle -image_base XXX and -seg1addr XXXX
453
242
  if (llvm::opt::Arg *imageBase = parsedArgs.getLastArg(OPT_image_base)) {
454
4
    uint64_t baseAddress;
455
4
    if (parseNumberBase16(imageBase->getValue(), baseAddress)) {
456
1
      error("image_base expects a hex number");
457
1
      return false;
458
3
    } else if (baseAddress < ctx.pageZeroSize()) {
459
1
      error("image_base overlaps with __PAGEZERO");
460
1
      return false;
461
2
    } else if (baseAddress % ctx.pageSize()) {
462
1
      error("image_base must be a multiple of page size (0x" +
463
1
            llvm::utohexstr(ctx.pageSize()) + ")");
464
1
      return false;
465
1
    }
466
1
467
1
    ctx.setBaseAddress(baseAddress);
468
1
  }
469
242
470
242
  // Handle -dead_strip
471
242
  
if (239
parsedArgs.getLastArg(OPT_dead_strip)239
)
472
14
    ctx.setDeadStripping(true);
473
239
474
239
  bool globalWholeArchive = false;
475
239
  // Handle -all_load
476
239
  if (parsedArgs.getLastArg(OPT_all_load))
477
1
    globalWholeArchive = true;
478
239
479
239
  // Handle -install_name
480
239
  if (llvm::opt::Arg *installName = parsedArgs.getLastArg(OPT_install_name))
481
6
    ctx.setInstallName(installName->getValue());
482
233
  else
483
233
    ctx.setInstallName(ctx.outputPath());
484
239
485
239
  // Handle -mark_dead_strippable_dylib
486
239
  if (parsedArgs.getLastArg(OPT_mark_dead_strippable_dylib))
487
2
    ctx.setDeadStrippableDylib(true);
488
239
489
239
  // Handle -compatibility_version and -current_version
490
239
  if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_compatibility_version)) {
491
6
    if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
492
2
      error("-compatibility_version can only be used with -dylib");
493
2
      return false;
494
2
    }
495
4
    uint32_t parsedVers;
496
4
    if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
497
0
      error("-compatibility_version value is malformed");
498
0
      return false;
499
0
    }
500
4
    ctx.setCompatibilityVersion(parsedVers);
501
4
  }
502
239
503
239
  
if (llvm::opt::Arg *237
vers237
= parsedArgs.getLastArg(OPT_current_version)) {
504
6
    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
4
    uint32_t parsedVers;
509
4
    if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
510
0
      error("-current_version value is malformed");
511
0
      return false;
512
0
    }
513
4
    ctx.setCurrentVersion(parsedVers);
514
4
  }
515
237
516
237
  // Handle -bundle_loader
517
237
  
if (llvm::opt::Arg *235
loader235
= parsedArgs.getLastArg(OPT_bundle_loader))
518
2
    ctx.setBundleLoader(loader->getValue());
519
235
520
235
  // Handle -sectalign segname sectname align
521
235
  for (auto &alignArg : parsedArgs.filtered(OPT_sectalign)) {
522
3
    const char* segName   = alignArg->getValue(0);
523
3
    const char* sectName  = alignArg->getValue(1);
524
3
    const char* alignStr  = alignArg->getValue(2);
525
3
    if ((alignStr[0] == '0') && (alignStr[1] == 'x'))
526
3
      alignStr += 2;
527
3
    unsigned long long alignValue;
528
3
    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
3
    uint16_t align = 1 << llvm::countTrailingZeros(alignValue);
534
3
    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
3
    ctx.addSectionAlignment(segName, sectName, align);
544
3
  }
545
235
546
235
  // Handle -mllvm
547
235
  for (auto &llvmArg : parsedArgs.filtered(OPT_mllvm)) {
548
0
    ctx.appendLLVMOption(llvmArg->getValue());
549
0
  }
550
235
551
235
  // Handle -print_atoms
552
235
  if (parsedArgs.getLastArg(OPT_print_atoms))
553
61
    ctx.setPrintAtoms();
554
235
555
235
  // Handle -t (trace) option.
556
235
  if (parsedArgs.getLastArg(OPT_t))
557
1
    ctx.setLogInputFiles(true);
558
235
559
235
  // Handle -demangle option.
560
235
  if (parsedArgs.getLastArg(OPT_demangle))
561
1
    ctx.setDemangleSymbols(true);
562
235
563
235
  // Handle -keep_private_externs
564
235
  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
235
570
235
  // Handle -dependency_info <path> used by Xcode.
571
235
  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
235
576
235
  // In -test_file_usage mode, we'll be given an explicit list of paths that
577
235
  // exist. We'll also be expected to print out information about how we located
578
235
  // libraries and so on that the user specified, but not to actually do any
579
235
  // linking.
580
235
  if (parsedArgs.getLastArg(OPT_test_file_usage)) {
581
11
    ctx.setTestingFileUsage();
582
11
583
11
    // With paths existing by fiat, linking is not going to end well.
584
11
    ctx.setDoNothing(true);
585
11
586
11
    // Only bother looking for an existence override if we're going to use it.
587
65
    for (auto existingPath : parsedArgs.filtered(OPT_path_exists)) {
588
65
      ctx.addExistingPathForDebug(existingPath->getValue());
589
65
    }
590
11
  }
591
235
592
235
  // Register possible input file parsers.
593
235
  if (!ctx.doNothing()) {
594
224
    ctx.registry().addSupportMachOObjects(ctx);
595
224
    ctx.registry().addSupportArchives(ctx.logInputFiles());
596
224
    ctx.registry().addSupportYamlFiles();
597
224
  }
598
235
599
235
  // Now construct the set of library search directories, following ld64's
600
235
  // baroque set of accumulated hacks. Mostly, the algorithm constructs
601
235
  //     { syslibroots } x { libpaths }
602
235
  //
603
235
  // Unfortunately, there are numerous exceptions:
604
235
  //   1. Only absolute paths get modified by syslibroot options.
605
235
  //   2. If there is just 1 -syslibroot, system paths not found in it are
606
235
  //      skipped.
607
235
  //   3. If the last -syslibroot is "/", all of them are ignored entirely.
608
235
  //   4. If { syslibroots } x path ==  {}, the original path is kept.
609
235
  std::vector<StringRef> sysLibRoots;
610
235
  for (auto syslibRoot : parsedArgs.filtered(OPT_syslibroot)) {
611
8
    sysLibRoots.push_back(syslibRoot->getValue());
612
8
  }
613
235
  if (!sysLibRoots.empty()) {
614
6
    // Ignore all if last -syslibroot is "/".
615
6
    if (sysLibRoots.back() != "/")
616
5
      ctx.setSysLibRoots(sysLibRoots);
617
6
  }
618
235
619
235
  // Paths specified with -L come first, and are not considered system paths for
620
235
  // the case where there is precisely 1 -syslibroot.
621
235
  for (auto libPath : parsedArgs.filtered(OPT_L)) {
622
8
    ctx.addModifiedSearchDir(libPath->getValue());
623
8
  }
624
235
625
235
  // Process -F directories (where to look for frameworks).
626
235
  for (auto fwPath : parsedArgs.filtered(OPT_F)) {
627
5
    ctx.addFrameworkSearchDir(fwPath->getValue());
628
5
  }
629
235
630
235
  // -Z suppresses the standard search paths.
631
235
  if (!parsedArgs.hasArg(OPT_Z)) {
632
234
    ctx.addModifiedSearchDir("/usr/lib", true);
633
234
    ctx.addModifiedSearchDir("/usr/local/lib", true);
634
234
    ctx.addFrameworkSearchDir("/Library/Frameworks", true);
635
234
    ctx.addFrameworkSearchDir("/System/Library/Frameworks", true);
636
234
  }
637
235
638
235
  // Now that we've constructed the final set of search paths, print out those
639
235
  // search paths in verbose mode.
640
235
  if (errorHandler().Verbose) {
641
8
    message("Library search paths:");
642
15
    for (auto path : ctx.searchDirs()) {
643
15
      message("    " + path);
644
15
    }
645
8
    message("Framework search paths:");
646
8
    for (auto path : ctx.frameworkDirs()) {
647
5
      message("    " + path);
648
5
    }
649
8
  }
650
235
651
235
  // Handle -exported_symbols_list <file>
652
235
  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
235
666
235
  // Handle -exported_symbol <symbol>
667
235
  for (auto symbol : parsedArgs.filtered(OPT_exported_symbol)) {
668
7
    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
7
    ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
674
7
    ctx.addExportSymbol(symbol->getValue());
675
7
  }
676
235
677
235
  // Handle -unexported_symbols_list <file>
678
235
  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
235
692
235
  // Handle -unexported_symbol <symbol>
693
235
  for (auto symbol : parsedArgs.filtered(OPT_unexported_symbol)) {
694
2
    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
2
    ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
700
2
    ctx.addExportSymbol(symbol->getValue());
701
2
  }
702
235
703
235
  // Handle obosolete -multi_module and -single_module
704
235
  if (llvm::opt::Arg *mod =
705
1
          parsedArgs.getLastArg(OPT_multi_module, OPT_single_module)) {
706
1
    if (mod->getOption().getID() == OPT_multi_module)
707
0
      warn("-multi_module is obsolete and being ignored");
708
1
    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
1
  }
712
235
713
235
  // Handle obsolete ObjC options: -objc_gc_compaction, -objc_gc, -objc_gc_only
714
235
  if (parsedArgs.getLastArg(OPT_objc_gc_compaction)) {
715
1
    error("-objc_gc_compaction is not supported");
716
1
    return false;
717
1
  }
718
234
719
234
  if (parsedArgs.getLastArg(OPT_objc_gc)) {
720
1
    error("-objc_gc is not supported");
721
1
    return false;
722
1
  }
723
233
724
233
  if (parsedArgs.getLastArg(OPT_objc_gc_only)) {
725
1
    error("-objc_gc_only is not supported");
726
1
    return false;
727
1
  }
728
232
729
232
  // Handle -pie or -no_pie
730
232
  if (llvm::opt::Arg *pie = parsedArgs.getLastArg(OPT_pie, OPT_no_pie)) {
731
2
    switch (ctx.outputMachOType()) {
732
2
    case llvm::MachO::MH_EXECUTE:
733
2
      switch (ctx.os()) {
734
2
      case MachOLinkingContext::OS::macOSX:
735
2
        if ((minOSVersion < 0x000A0500) &&
736
2
            
(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
2
        break;
741
2
      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
2
      }
757
2
      ctx.setPIE(pie->getOption().getID() == OPT_pie);
758
2
      break;
759
2
    case llvm::MachO::MH_PRELOAD:
760
0
      break;
761
2
    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
232
    }
771
232
  }
772
232
773
232
  // Handle -version_load_command or -no_version_load_command
774
232
  {
775
232
    bool flagOn = false;
776
232
    bool flagOff = false;
777
232
    if (auto *arg = parsedArgs.getLastArg(OPT_version_load_command,
778
3
                                          OPT_no_version_load_command)) {
779
3
      flagOn = arg->getOption().getID() == OPT_version_load_command;
780
3
      flagOff = arg->getOption().getID() == OPT_no_version_load_command;
781
3
    }
782
232
783
232
    // default to adding version load command for dynamic code,
784
232
    // static code must opt-in
785
232
    switch (ctx.outputMachOType()) {
786
232
      case llvm::MachO::MH_OBJECT:
787
90
        ctx.setGenerateVersionLoadCommand(false);
788
90
        break;
789
232
      case llvm::MachO::MH_EXECUTE:
790
86
        // dynamic executables default to generating a version load command,
791
86
        // while static exectuables only generate it if required.
792
86
        if (isStaticExecutable) {
793
10
          if (flagOn)
794
1
            ctx.setGenerateVersionLoadCommand(true);
795
76
        } else {
796
76
          if (!flagOff)
797
76
            ctx.setGenerateVersionLoadCommand(true);
798
76
        }
799
86
        break;
800
232
      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
55
      case llvm::MachO::MH_DYLINKER:
806
55
      case llvm::MachO::MH_DYLIB:
807
55
      case llvm::MachO::MH_BUNDLE:
808
55
        if (!flagOff)
809
54
          ctx.setGenerateVersionLoadCommand(true);
810
55
        break;
811
55
      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
232
    }
819
232
  }
820
232
821
232
  // Handle -function_starts or -no_function_starts
822
232
  {
823
232
    bool flagOn = false;
824
232
    bool flagOff = false;
825
232
    if (auto *arg = parsedArgs.getLastArg(OPT_function_starts,
826
3
                                          OPT_no_function_starts)) {
827
3
      flagOn = arg->getOption().getID() == OPT_function_starts;
828
3
      flagOff = arg->getOption().getID() == OPT_no_function_starts;
829
3
    }
830
232
831
232
    // default to adding functions start for dynamic code, static code must
832
232
    // opt-in
833
232
    switch (ctx.outputMachOType()) {
834
232
      case llvm::MachO::MH_OBJECT:
835
90
        ctx.setGenerateFunctionStartsLoadCommand(false);
836
90
        break;
837
232
      case llvm::MachO::MH_EXECUTE:
838
86
        // dynamic executables default to generating a version load command,
839
86
        // while static exectuables only generate it if required.
840
86
        if (isStaticExecutable) {
841
10
          if (flagOn)
842
1
            ctx.setGenerateFunctionStartsLoadCommand(true);
843
76
        } else {
844
76
          if (!flagOff)
845
76
            ctx.setGenerateFunctionStartsLoadCommand(true);
846
76
        }
847
86
        break;
848
232
      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
55
      case llvm::MachO::MH_DYLINKER:
854
55
      case llvm::MachO::MH_DYLIB:
855
55
      case llvm::MachO::MH_BUNDLE:
856
55
        if (!flagOff)
857
54
          ctx.setGenerateFunctionStartsLoadCommand(true);
858
55
        break;
859
55
      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
232
    }
867
232
  }
868
232
869
232
  // Handle -data_in_code_info or -no_data_in_code_info
870
232
  {
871
232
    bool flagOn = false;
872
232
    bool flagOff = false;
873
232
    if (auto *arg = parsedArgs.getLastArg(OPT_data_in_code_info,
874
5
                                          OPT_no_data_in_code_info)) {
875
5
      flagOn = arg->getOption().getID() == OPT_data_in_code_info;
876
5
      flagOff = arg->getOption().getID() == OPT_no_data_in_code_info;
877
5
    }
878
232
879
232
    // default to adding data in code for dynamic code, static code must
880
232
    // opt-in
881
232
    switch (ctx.outputMachOType()) {
882
232
      case llvm::MachO::MH_OBJECT:
883
90
        if (!flagOff)
884
89
          ctx.setGenerateDataInCodeLoadCommand(true);
885
90
        break;
886
232
      case llvm::MachO::MH_EXECUTE:
887
86
        // dynamic executables default to generating a version load command,
888
86
        // while static exectuables only generate it if required.
889
86
        if (isStaticExecutable) {
890
10
          if (flagOn)
891
1
            ctx.setGenerateDataInCodeLoadCommand(true);
892
76
        } else {
893
76
          if (!flagOff)
894
76
            ctx.setGenerateDataInCodeLoadCommand(true);
895
76
        }
896
86
        break;
897
232
      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
55
      case llvm::MachO::MH_DYLINKER:
903
55
      case llvm::MachO::MH_DYLIB:
904
55
      case llvm::MachO::MH_BUNDLE:
905
55
        if (!flagOff)
906
54
          ctx.setGenerateDataInCodeLoadCommand(true);
907
55
        break;
908
55
      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
232
    }
916
232
  }
917
232
918
232
  // Handle sdk_version
919
232
  if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_sdk_version)) {
920
2
    uint32_t sdkVersion = 0;
921
2
    if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
922
2
                                                sdkVersion)) {
923
1
      error("malformed sdkVersion value");
924
1
      return false;
925
1
    }
926
1
    ctx.setSdkVersion(sdkVersion);
927
230
  } else if (ctx.generateVersionLoadCommand()) {
928
129
    // If we don't have an sdk version, but were going to emit a load command
929
129
    // with min_version, then we need to give an warning as we have no sdk
930
129
    // version to put in that command.
931
129
    // FIXME: We need to decide whether to make this an error.
932
129
    warn("-sdk_version is required when emitting min version load command.  "
933
129
         "Setting sdk version to match provided min version");
934
129
    ctx.setSdkVersion(ctx.osMinVersion());
935
129
  }
936
232
937
232
  // Handle source_version
938
232
  
if (llvm::opt::Arg *231
arg231
= 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
231
948
231
  // Handle stack_size
949
231
  
if (llvm::opt::Arg *230
stackSize230
= parsedArgs.getLastArg(OPT_stack_size)) {
950
3
    uint64_t stackSizeVal;
951
3
    if (parseNumberBase16(stackSize->getValue(), stackSizeVal)) {
952
1
      error("stack_size expects a hex number");
953
1
      return false;
954
1
    }
955
2
    if ((stackSizeVal % ctx.pageSize()) != 0) {
956
1
      error("stack_size must be a multiple of page size (0x" +
957
1
            llvm::utohexstr(ctx.pageSize()) + ")");
958
1
      return false;
959
1
    }
960
1
961
1
    ctx.setStackSize(stackSizeVal);
962
1
  }
963
230
964
230
  // Handle debug info handling options: -S
965
230
  
if (228
parsedArgs.hasArg(OPT_S)228
)
966
0
    ctx.setDebugInfoMode(MachOLinkingContext::DebugInfoMode::noDebugMap);
967
228
968
228
  // Handle -order_file <file>
969
228
  for (auto orderFile : parsedArgs.filtered(OPT_order_file)) {
970
1
    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
1
  }
976
228
977
228
  // Handle -flat_namespace.
978
228
  if (llvm::opt::Arg *ns =
979
5
          parsedArgs.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace)) {
980
5
    if (ns->getOption().getID() == OPT_flat_namespace)
981
2
      ctx.setUseFlatNamespace(true);
982
5
  }
983
228
984
228
  // Handle -undefined
985
228
  if (llvm::opt::Arg *undef = parsedArgs.getLastArg(OPT_undefined)) {
986
5
    MachOLinkingContext::UndefinedMode UndefMode;
987
5
    if (StringRef(undef->getValue()).equals("error"))
988
1
      UndefMode = MachOLinkingContext::UndefinedMode::error;
989
4
    else if (StringRef(undef->getValue()).equals("warning"))
990
1
      UndefMode = MachOLinkingContext::UndefinedMode::warning;
991
3
    else if (StringRef(undef->getValue()).equals("suppress"))
992
2
      UndefMode = MachOLinkingContext::UndefinedMode::suppress;
993
1
    else if (StringRef(undef->getValue()).equals("dynamic_lookup"))
994
1
      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
5
1001
5
    if (ctx.useFlatNamespace()) {
1002
2
      // If we're using -flat_namespace then 'warning', 'suppress' and
1003
2
      // 'dynamic_lookup' are all equivalent, so map them to 'suppress'.
1004
2
      if (UndefMode != MachOLinkingContext::UndefinedMode::error)
1005
1
        UndefMode = MachOLinkingContext::UndefinedMode::suppress;
1006
3
    } else {
1007
3
      // If we're using -twolevel_namespace then 'warning' and 'suppress' are
1008
3
      // illegal. Emit a diagnostic if they've been (mis)used.
1009
3
      if (UndefMode == MachOLinkingContext::UndefinedMode::warning ||
1010
3
          
UndefMode == MachOLinkingContext::UndefinedMode::suppress2
) {
1011
2
        error("can't use -undefined warning or suppress with "
1012
2
              "-twolevel_namespace");
1013
2
        return false;
1014
2
      }
1015
3
    }
1016
3
1017
3
    ctx.setUndefinedMode(UndefMode);
1018
3
  }
1019
228
1020
228
  // Handle -no_objc_category_merging.
1021
228
  
if (226
parsedArgs.getLastArg(OPT_no_objc_category_merging)226
)
1022
0
    ctx.setMergeObjCCategories(false);
1023
226
1024
226
  // Handle -rpath <path>
1025
226
  if (parsedArgs.hasArg(OPT_rpath)) {
1026
1
    switch (ctx.outputMachOType()) {
1027
1
      case llvm::MachO::MH_EXECUTE:
1028
1
      case llvm::MachO::MH_DYLIB:
1029
1
      case llvm::MachO::MH_BUNDLE:
1030
1
        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
1
        break;
1038
1
      default:
1039
0
        error("-rpath can only be used when creating a dynamic final linked "
1040
0
              "image");
1041
0
        return false;
1042
1
    }
1043
1
1044
1
    for (auto rPath : parsedArgs.filtered(OPT_rpath)) {
1045
1
      ctx.addRpath(rPath->getValue());
1046
1
    }
1047
1
  }
1048
226
1049
226
  // Parse the LLVM options before we process files in case the file handling
1050
226
  // makes use of things like LLVM_DEBUG().
1051
226
  parseLLVMOptions(ctx);
1052
226
1053
226
  // Handle input files and sectcreate.
1054
1.25k
  for (auto &arg : parsedArgs) {
1055
1.25k
    bool upward;
1056
1.25k
    llvm::Optional<StringRef> resolvedPath;
1057
1.25k
    switch (arg->getOption().getID()) {
1058
1.25k
    default:
1059
885
      continue;
1060
1.25k
    case OPT_INPUT:
1061
342
      addFile(arg->getValue(), ctx, globalWholeArchive, false);
1062
342
      break;
1063
1.25k
    case OPT_upward_library:
1064
2
      addFile(arg->getValue(), ctx, false, true);
1065
2
      break;
1066
1.25k
    case OPT_force_load:
1067
2
      addFile(arg->getValue(), ctx, true, false);
1068
2
      break;
1069
1.25k
    case OPT_l:
1070
16
    case OPT_upward_l:
1071
16
      upward = (arg->getOption().getID() == OPT_upward_l);
1072
16
      resolvedPath = ctx.searchLibrary(arg->getValue());
1073
16
      if (!resolvedPath) {
1074
1
        error("Unable to find library for " + arg->getSpelling() +
1075
1
              arg->getValue());
1076
1
        return false;
1077
15
      } else if (ctx.testingFileUsage()) {
1078
11
        message(Twine("Found ") + (upward ? 
"upward "1
:
" "10
) + "library " +
1079
11
                canonicalizePath(resolvedPath.getValue()));
1080
11
      }
1081
16
      addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
1082
15
      break;
1083
16
    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
2
      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
2
      break;
1105
2
    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
1.25k
    }
1122
1.25k
  }
1123
226
1124
226
  
if (225
ctx.getNodes().empty()225
) {
1125
0
    error("No input files");
1126
0
    return false;
1127
0
  }
1128
225
1129
225
  // Validate the combination of options used.
1130
225
  return ctx.validate();
1131
225
}
1132
1133
366
static void createFiles(MachOLinkingContext &ctx, bool Implicit) {
1134
366
  std::vector<std::unique_ptr<File>> Files;
1135
366
  if (Implicit)
1136
183
    ctx.createImplicitFiles(Files);
1137
183
  else
1138
183
    ctx.createInternalFiles(Files);
1139
686
  for (auto i = Files.rbegin(), e = Files.rend(); i != e; 
++i320
) {
1140
320
    auto &members = ctx.getNodes();
1141
320
    members.insert(members.begin(), llvm::make_unique<FileNode>(std::move(*i)));
1142
320
  }
1143
366
}
1144
1145
/// This is where the link is actually performed.
1146
bool link(llvm::ArrayRef<const char *> args, bool CanExitEarly,
1147
207
          raw_ostream &Error) {
1148
207
  errorHandler().LogName = args::getFilenameWithoutExe(args[0]);
1149
207
  errorHandler().ErrorLimitExceededMsg =
1150
207
      "too many errors emitted, stopping now (use "
1151
207
      "'-error-limit 0' to see all errors)";
1152
207
  errorHandler().ErrorOS = &Error;
1153
207
  errorHandler().ExitEarly = CanExitEarly;
1154
207
  errorHandler().ColorDiagnostics = Error.has_colors();
1155
207
1156
207
  MachOLinkingContext ctx;
1157
207
  if (!parse(args, ctx))
1158
14
    return false;
1159
193
  if (ctx.doNothing())
1160
10
    return true;
1161
183
  if (ctx.getNodes().empty())
1162
0
    return false;
1163
183
1164
183
  for (std::unique_ptr<Node> &ie : ctx.getNodes())
1165
317
    if (FileNode *node = dyn_cast<FileNode>(ie.get()))
1166
317
      node->getFile()->parse();
1167
183
1168
183
  createFiles(ctx, false /* Implicit */);
1169
183
1170
183
  // Give target a chance to add files
1171
183
  createFiles(ctx, true /* Implicit */);
1172
183
1173
183
  // Give target a chance to postprocess input files.
1174
183
  // Mach-O uses this chance to move all object files before library files.
1175
183
  ctx.finalizeInputFiles();
1176
183
1177
183
  // Do core linking.
1178
183
  ScopedTask resolveTask(getDefaultDomain(), "Resolve");
1179
183
  Resolver resolver(ctx);
1180
183
  if (!resolver.resolve())
1181
14
    return false;
1182
169
  SimpleFile *merged = nullptr;
1183
169
  {
1184
169
    std::unique_ptr<SimpleFile> mergedFile = resolver.resultFile();
1185
169
    merged = mergedFile.get();
1186
169
    auto &members = ctx.getNodes();
1187
169
    members.insert(members.begin(),
1188
169
                   llvm::make_unique<FileNode>(std::move(mergedFile)));
1189
169
  }
1190
169
  resolveTask.end();
1191
169
1192
169
  // Run passes on linked atoms.
1193
169
  ScopedTask passTask(getDefaultDomain(), "Passes");
1194
169
  PassManager pm;
1195
169
  ctx.addPasses(pm);
1196
169
  if (auto ec = pm.runOnFile(*merged)) {
1197
1
    // FIXME: This should be passed to logAllUnhandledErrors but it needs
1198
1
    // to be passed a Twine instead of a string.
1199
1
    *errorHandler().ErrorOS << "Failed to run passes on file '"
1200
1
                            << ctx.outputPath() << "': ";
1201
1
    logAllUnhandledErrors(std::move(ec), *errorHandler().ErrorOS,
1202
1
                          std::string());
1203
1
    return false;
1204
1
  }
1205
168
1206
168
  passTask.end();
1207
168
1208
168
  // Give linked atoms to Writer to generate output file.
1209
168
  ScopedTask writeTask(getDefaultDomain(), "Write");
1210
168
  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
167
1220
167
  // Call exit() if we can to avoid calling destructors.
1221
167
  if (CanExitEarly)
1222
0
    exitLld(errorCount() ? 1 : 0);
1223
167
1224
167
1225
167
  return true;
1226
167
}
1227
1228
} // end namespace mach_o
1229
} // end namespace lld