Coverage Report

Created: 2018-10-23 15:26

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