Coverage Report

Created: 2019-07-24 05:18

/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
244
  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
376
                                            bool upwardDylib) {
117
376
  if (ctx.logInputFiles())
118
3
    message(path);
119
376
120
376
  ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = ctx.getMemoryBuffer(path);
121
376
  if (std::error_code ec = mbOrErr.getError())
122
57
    return makeErrorFile(path, ec);
123
319
  ErrorOr<std::unique_ptr<File>> fileOrErr =
124
319
      ctx.registry().loadFile(std::move(mbOrErr.get()));
125
319
  if (std::error_code ec = fileOrErr.getError())
126
7
    return makeErrorFile(path, ec);
127
312
  std::unique_ptr<File> &file = fileOrErr.get();
128
312
129
312
  // If file is a dylib, inform LinkingContext about it.
130
312
  if (SharedLibraryFile *shl = dyn_cast<SharedLibraryFile>(file.get())) {
131
117
    if (std::error_code ec = shl->parse())
132
0
      return makeErrorFile(path, ec);
133
117
    ctx.registerDylib(reinterpret_cast<mach_o::MachODylibFile *>(shl),
134
117
                      upwardDylib);
135
117
  }
136
312
  if (wholeArchive)
137
5
    return parseMemberFiles(std::move(file));
138
307
  std::vector<std::unique_ptr<File>> files;
139
307
  files.push_back(std::move(file));
140
307
  return files;
141
307
}
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
376
                    bool loadWholeArchive, bool upwardDylib) {
160
376
  std::vector<std::unique_ptr<File>> files =
161
376
      loadFile(ctx, path, loadWholeArchive, upwardDylib);
162
376
  for (std::unique_ptr<File> &file : files)
163
376
    ctx.getNodes().push_back(llvm::make_unique<FileNode>(std::move(file)));
164
376
}
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
227
static void parseLLVMOptions(const LinkingContext &ctx) {
302
227
  // Honor -mllvm
303
227
  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
227
}
313
314
namespace lld {
315
namespace mach_o {
316
317
244
bool parse(llvm::ArrayRef<const char *> args, MachOLinkingContext &ctx) {
318
244
  // Parse command line options using DarwinLdOptions.td
319
244
  DarwinLdOptTable table;
320
244
  unsigned missingIndex;
321
244
  unsigned missingCount;
322
244
  llvm::opt::InputArgList parsedArgs =
323
244
      table.ParseArgs(args.slice(1), missingIndex, missingCount);
324
244
  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
244
331
244
  for (auto unknownArg : parsedArgs.filtered(OPT_UNKNOWN)) {
332
1
    warn("ignoring unknown argument: " +
333
1
         Twine(unknownArg->getAsString(parsedArgs)));
334
1
  }
335
244
336
244
  errorHandler().verbose = parsedArgs.hasArg(OPT_v);
337
244
  errorHandler().errorLimit = args::getInteger(parsedArgs, OPT_error_limit, 20);
338
244
339
244
  // Figure out output kind ( -dylib, -r, -bundle, -preload, or -static )
340
244
  llvm::MachO::HeaderFileType fileType = llvm::MachO::MH_EXECUTE;
341
244
  bool isStaticExecutable = false;
342
244
  if (llvm::opt::Arg *kind = parsedArgs.getLastArg(
343
161
          OPT_dylib, OPT_relocatable, OPT_bundle, OPT_static, OPT_preload)) {
344
161
    switch (kind->getOption().getID()) {
345
161
    case OPT_dylib:
346
51
      fileType = llvm::MachO::MH_DYLIB;
347
51
      break;
348
161
    case OPT_relocatable:
349
90
      fileType = llvm::MachO::MH_OBJECT;
350
90
      break;
351
161
    case OPT_bundle:
352
9
      fileType = llvm::MachO::MH_BUNDLE;
353
9
      break;
354
161
    case OPT_static:
355
10
      fileType = llvm::MachO::MH_EXECUTE;
356
10
      isStaticExecutable = true;
357
10
      break;
358
161
    case OPT_preload:
359
1
      fileType = llvm::MachO::MH_PRELOAD;
360
1
      break;
361
244
    }
362
244
  }
363
244
364
244
  // Handle -arch xxx
365
244
  MachOLinkingContext::Arch arch = MachOLinkingContext::arch_unknown;
366
244
  if (llvm::opt::Arg *archStr = parsedArgs.getLastArg(OPT_arch)) {
367
237
    arch = MachOLinkingContext::archFromName(archStr->getValue());
368
237
    if (arch == MachOLinkingContext::arch_unknown) {
369
0
      error("unknown arch named '" + Twine(archStr->getValue()) + "'");
370
0
      return false;
371
0
    }
372
244
  }
373
244
  // If no -arch specified, scan input files to find first non-fat .o file.
374
244
  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
243
  }
394
243
395
243
  // Handle -macosx_version_min or -ios_version_min
396
243
  MachOLinkingContext::OS os = MachOLinkingContext::OS::unknown;
397
243
  uint32_t minOSVersion = 0;
398
243
  if (llvm::opt::Arg *minOS =
399
65
          parsedArgs.getLastArg(OPT_macosx_version_min, OPT_ios_version_min,
400
65
                                OPT_ios_simulator_version_min)) {
401
65
    switch (minOS->getOption().getID()) {
402
65
    case OPT_macosx_version_min:
403
57
      os = MachOLinkingContext::OS::macOSX;
404
57
      if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
405
57
                                                  minOSVersion)) {
406
0
        error("malformed macosx_version_min value");
407
0
        return false;
408
0
      }
409
57
      break;
410
57
    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
243
431
243
  // Handle export_dynamic
432
243
  // FIXME: Should we warn when this applies to something other than a static
433
243
  // executable or dylib?  Those are the only cases where this has an effect.
434
243
  // Note, this has to come before ctx.configure() so that we get the correct
435
243
  // value for _globalsAreDeadStripRoots.
436
243
  bool exportDynamicSymbols = parsedArgs.hasArg(OPT_export_dynamic);
437
243
438
243
  // Now that there's enough information parsed in, let the linking context
439
243
  // set up default values.
440
243
  ctx.configure(fileType, arch, os, minOSVersion, exportDynamicSymbols);
441
243
442
243
  // Handle -e xxx
443
243
  if (llvm::opt::Arg *entry = parsedArgs.getLastArg(OPT_entry))
444
5
    ctx.setEntrySymbolName(entry->getValue());
445
243
446
243
  // Handle -o xxx
447
243
  if (llvm::opt::Arg *outpath = parsedArgs.getLastArg(OPT_output))
448
179
    ctx.setOutputPath(outpath->getValue());
449
64
  else
450
64
    ctx.setOutputPath("a.out");
451
243
452
243
  // Handle -image_base XXX and -seg1addr XXXX
453
243
  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
243
470
243
  // Handle -dead_strip
471
243
  
if (240
parsedArgs.getLastArg(OPT_dead_strip)240
)
472
14
    ctx.setDeadStripping(true);
473
240
474
240
  bool globalWholeArchive = false;
475
240
  // Handle -all_load
476
240
  if (parsedArgs.getLastArg(OPT_all_load))
477
1
    globalWholeArchive = true;
478
240
479
240
  // Handle -install_name
480
240
  if (llvm::opt::Arg *installName = parsedArgs.getLastArg(OPT_install_name))
481
7
    ctx.setInstallName(installName->getValue());
482
233
  else
483
233
    ctx.setInstallName(ctx.outputPath());
484
240
485
240
  // Handle -mark_dead_strippable_dylib
486
240
  if (parsedArgs.getLastArg(OPT_mark_dead_strippable_dylib))
487
2
    ctx.setDeadStrippableDylib(true);
488
240
489
240
  // Handle -compatibility_version and -current_version
490
240
  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
240
503
240
  
if (llvm::opt::Arg *238
vers238
= 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
238
516
238
  // Handle -bundle_loader
517
238
  
if (llvm::opt::Arg *236
loader236
= parsedArgs.getLastArg(OPT_bundle_loader))
518
2
    ctx.setBundleLoader(loader->getValue());
519
236
520
236
  // Handle -sectalign segname sectname align
521
236
  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
236
546
236
  // Handle -mllvm
547
236
  for (auto &llvmArg : parsedArgs.filtered(OPT_mllvm)) {
548
0
    ctx.appendLLVMOption(llvmArg->getValue());
549
0
  }
550
236
551
236
  // Handle -print_atoms
552
236
  if (parsedArgs.getLastArg(OPT_print_atoms))
553
61
    ctx.setPrintAtoms();
554
236
555
236
  // Handle -t (trace) option.
556
236
  if (parsedArgs.getLastArg(OPT_t))
557
1
    ctx.setLogInputFiles(true);
558
236
559
236
  // Handle -demangle option.
560
236
  if (parsedArgs.getLastArg(OPT_demangle))
561
1
    ctx.setDemangleSymbols(true);
562
236
563
236
  // Handle -keep_private_externs
564
236
  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
236
570
236
  // Handle -dependency_info <path> used by Xcode.
571
236
  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
236
576
236
  // In -test_file_usage mode, we'll be given an explicit list of paths that
577
236
  // exist. We'll also be expected to print out information about how we located
578
236
  // libraries and so on that the user specified, but not to actually do any
579
236
  // linking.
580
236
  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
236
592
236
  // Register possible input file parsers.
593
236
  if (!ctx.doNothing()) {
594
225
    ctx.registry().addSupportMachOObjects(ctx);
595
225
    ctx.registry().addSupportArchives(ctx.logInputFiles());
596
225
    ctx.registry().addSupportYamlFiles();
597
225
  }
598
236
599
236
  // Now construct the set of library search directories, following ld64's
600
236
  // baroque set of accumulated hacks. Mostly, the algorithm constructs
601
236
  //     { syslibroots } x { libpaths }
602
236
  //
603
236
  // Unfortunately, there are numerous exceptions:
604
236
  //   1. Only absolute paths get modified by syslibroot options.
605
236
  //   2. If there is just 1 -syslibroot, system paths not found in it are
606
236
  //      skipped.
607
236
  //   3. If the last -syslibroot is "/", all of them are ignored entirely.
608
236
  //   4. If { syslibroots } x path ==  {}, the original path is kept.
609
236
  std::vector<StringRef> sysLibRoots;
610
236
  for (auto syslibRoot : parsedArgs.filtered(OPT_syslibroot)) {
611
8
    sysLibRoots.push_back(syslibRoot->getValue());
612
8
  }
613
236
  if (!sysLibRoots.empty()) {
614
6
    // Ignore all if last -syslibroot is "/".
615
6
    if (sysLibRoots.back() != "/")
616
5
      ctx.setSysLibRoots(sysLibRoots);
617
6
  }
618
236
619
236
  // Paths specified with -L come first, and are not considered system paths for
620
236
  // the case where there is precisely 1 -syslibroot.
621
236
  for (auto libPath : parsedArgs.filtered(OPT_L)) {
622
8
    ctx.addModifiedSearchDir(libPath->getValue());
623
8
  }
624
236
625
236
  // Process -F directories (where to look for frameworks).
626
236
  for (auto fwPath : parsedArgs.filtered(OPT_F)) {
627
5
    ctx.addFrameworkSearchDir(fwPath->getValue());
628
5
  }
629
236
630
236
  // -Z suppresses the standard search paths.
631
236
  if (!parsedArgs.hasArg(OPT_Z)) {
632
235
    ctx.addModifiedSearchDir("/usr/lib", true);
633
235
    ctx.addModifiedSearchDir("/usr/local/lib", true);
634
235
    ctx.addFrameworkSearchDir("/Library/Frameworks", true);
635
235
    ctx.addFrameworkSearchDir("/System/Library/Frameworks", true);
636
235
  }
637
236
638
236
  // Now that we've constructed the final set of search paths, print out those
639
236
  // search paths in verbose mode.
640
236
  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
236
651
236
  // Handle -exported_symbols_list <file>
652
236
  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
236
666
236
  // Handle -exported_symbol <symbol>
667
236
  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
236
677
236
  // Handle -unexported_symbols_list <file>
678
236
  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
236
692
236
  // Handle -unexported_symbol <symbol>
693
236
  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
236
703
236
  // Handle obosolete -multi_module and -single_module
704
236
  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
236
713
236
  // Handle obsolete ObjC options: -objc_gc_compaction, -objc_gc, -objc_gc_only
714
236
  if (parsedArgs.getLastArg(OPT_objc_gc_compaction)) {
715
1
    error("-objc_gc_compaction is not supported");
716
1
    return false;
717
1
  }
718
235
719
235
  if (parsedArgs.getLastArg(OPT_objc_gc)) {
720
1
    error("-objc_gc is not supported");
721
1
    return false;
722
1
  }
723
234
724
234
  if (parsedArgs.getLastArg(OPT_objc_gc_only)) {
725
1
    error("-objc_gc_only is not supported");
726
1
    return false;
727
1
  }
728
233
729
233
  // Handle -pie or -no_pie
730
233
  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
233
    }
771
233
  }
772
233
773
233
  // Handle -version_load_command or -no_version_load_command
774
233
  {
775
233
    bool flagOn = false;
776
233
    bool flagOff = false;
777
233
    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
233
783
233
    // default to adding version load command for dynamic code,
784
233
    // static code must opt-in
785
233
    switch (ctx.outputMachOType()) {
786
233
      case llvm::MachO::MH_OBJECT:
787
90
        ctx.setGenerateVersionLoadCommand(false);
788
90
        break;
789
233
      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
233
      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
56
      case llvm::MachO::MH_DYLINKER:
806
56
      case llvm::MachO::MH_DYLIB:
807
56
      case llvm::MachO::MH_BUNDLE:
808
56
        if (!flagOff)
809
55
          ctx.setGenerateVersionLoadCommand(true);
810
56
        break;
811
56
      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
233
    }
819
233
  }
820
233
821
233
  // Handle -function_starts or -no_function_starts
822
233
  {
823
233
    bool flagOn = false;
824
233
    bool flagOff = false;
825
233
    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
233
831
233
    // default to adding functions start for dynamic code, static code must
832
233
    // opt-in
833
233
    switch (ctx.outputMachOType()) {
834
233
      case llvm::MachO::MH_OBJECT:
835
90
        ctx.setGenerateFunctionStartsLoadCommand(false);
836
90
        break;
837
233
      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
233
      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
56
      case llvm::MachO::MH_DYLINKER:
854
56
      case llvm::MachO::MH_DYLIB:
855
56
      case llvm::MachO::MH_BUNDLE:
856
56
        if (!flagOff)
857
55
          ctx.setGenerateFunctionStartsLoadCommand(true);
858
56
        break;
859
56
      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
233
    }
867
233
  }
868
233
869
233
  // Handle -data_in_code_info or -no_data_in_code_info
870
233
  {
871
233
    bool flagOn = false;
872
233
    bool flagOff = false;
873
233
    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
233
879
233
    // default to adding data in code for dynamic code, static code must
880
233
    // opt-in
881
233
    switch (ctx.outputMachOType()) {
882
233
      case llvm::MachO::MH_OBJECT:
883
90
        if (!flagOff)
884
89
          ctx.setGenerateDataInCodeLoadCommand(true);
885
90
        break;
886
233
      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
233
      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
56
      case llvm::MachO::MH_DYLINKER:
903
56
      case llvm::MachO::MH_DYLIB:
904
56
      case llvm::MachO::MH_BUNDLE:
905
56
        if (!flagOff)
906
55
          ctx.setGenerateDataInCodeLoadCommand(true);
907
56
        break;
908
56
      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
233
    }
916
233
  }
917
233
918
233
  // Handle sdk_version
919
233
  if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_sdk_version)) {
920
3
    uint32_t sdkVersion = 0;
921
3
    if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
922
3
                                                sdkVersion)) {
923
1
      error("malformed sdkVersion value");
924
1
      return false;
925
1
    }
926
2
    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
233
937
233
  // Handle source_version
938
233
  
if (llvm::opt::Arg *232
arg232
= 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
232
948
232
  // Handle stack_size
949
232
  
if (llvm::opt::Arg *231
stackSize231
= 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
231
964
231
  // Handle debug info handling options: -S
965
231
  
if (229
parsedArgs.hasArg(OPT_S)229
)
966
0
    ctx.setDebugInfoMode(MachOLinkingContext::DebugInfoMode::noDebugMap);
967
229
968
229
  // Handle -order_file <file>
969
229
  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
229
977
229
  // Handle -flat_namespace.
978
229
  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
229
984
229
  // Handle -undefined
985
229
  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
229
1020
229
  // Handle -no_objc_category_merging.
1021
229
  
if (227
parsedArgs.getLastArg(OPT_no_objc_category_merging)227
)
1022
0
    ctx.setMergeObjCCategories(false);
1023
227
1024
227
  // Handle -rpath <path>
1025
227
  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
227
1049
227
  // Parse the LLVM options before we process files in case the file handling
1050
227
  // makes use of things like LLVM_DEBUG().
1051
227
  parseLLVMOptions(ctx);
1052
227
1053
227
  // Handle input files and sectcreate.
1054
1.26k
  for (auto &arg : parsedArgs) {
1055
1.26k
    bool upward;
1056
1.26k
    llvm::Optional<StringRef> resolvedPath;
1057
1.26k
    switch (arg->getOption().getID()) {
1058
1.26k
    default:
1059
891
      continue;
1060
1.26k
    case OPT_INPUT:
1061
344
      addFile(arg->getValue(), ctx, globalWholeArchive, false);
1062
344
      break;
1063
1.26k
    case OPT_upward_library:
1064
2
      addFile(arg->getValue(), ctx, false, true);
1065
2
      break;
1066
1.26k
    case OPT_force_load:
1067
2
      addFile(arg->getValue(), ctx, true, false);
1068
2
      break;
1069
1.26k
    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.26k
    }
1122
1.26k
  }
1123
227
1124
227
  
if (226
ctx.getNodes().empty()226
) {
1125
0
    error("No input files");
1126
0
    return false;
1127
0
  }
1128
226
1129
226
  // Validate the combination of options used.
1130
226
  return ctx.validate();
1131
226
}
1132
1133
368
static void createFiles(MachOLinkingContext &ctx, bool Implicit) {
1134
368
  std::vector<std::unique_ptr<File>> Files;
1135
368
  if (Implicit)
1136
184
    ctx.createImplicitFiles(Files);
1137
184
  else
1138
184
    ctx.createInternalFiles(Files);
1139
690
  for (auto i = Files.rbegin(), e = Files.rend(); i != e; 
++i322
) {
1140
322
    auto &members = ctx.getNodes();
1141
322
    members.insert(members.begin(), llvm::make_unique<FileNode>(std::move(*i)));
1142
322
  }
1143
368
}
1144
1145
/// This is where the link is actually performed.
1146
bool link(llvm::ArrayRef<const char *> args, bool CanExitEarly,
1147
208
          raw_ostream &Error) {
1148
208
  errorHandler().logName = args::getFilenameWithoutExe(args[0]);
1149
208
  errorHandler().errorLimitExceededMsg =
1150
208
      "too many errors emitted, stopping now (use "
1151
208
      "'-error-limit 0' to see all errors)";
1152
208
  errorHandler().errorOS = &Error;
1153
208
  errorHandler().exitEarly = CanExitEarly;
1154
208
  errorHandler().colorDiagnostics = Error.has_colors();
1155
208
1156
208
  MachOLinkingContext ctx;
1157
208
  if (!parse(args, ctx))
1158
14
    return false;
1159
194
  if (ctx.doNothing())
1160
10
    return true;
1161
184
  if (ctx.getNodes().empty())
1162
0
    return false;
1163
184
1164
184
  for (std::unique_ptr<Node> &ie : ctx.getNodes())
1165
319
    if (FileNode *node = dyn_cast<FileNode>(ie.get()))
1166
319
      node->getFile()->parse();
1167
184
1168
184
  createFiles(ctx, false /* Implicit */);
1169
184
1170
184
  // Give target a chance to add files
1171
184
  createFiles(ctx, true /* Implicit */);
1172
184
1173
184
  // Give target a chance to postprocess input files.
1174
184
  // Mach-O uses this chance to move all object files before library files.
1175
184
  ctx.finalizeInputFiles();
1176
184
1177
184
  // Do core linking.
1178
184
  ScopedTask resolveTask(getDefaultDomain(), "Resolve");
1179
184
  Resolver resolver(ctx);
1180
184
  if (!resolver.resolve())
1181
14
    return false;
1182
170
  SimpleFile *merged = nullptr;
1183
170
  {
1184
170
    std::unique_ptr<SimpleFile> mergedFile = resolver.resultFile();
1185
170
    merged = mergedFile.get();
1186
170
    auto &members = ctx.getNodes();
1187
170
    members.insert(members.begin(),
1188
170
                   llvm::make_unique<FileNode>(std::move(mergedFile)));
1189
170
  }
1190
170
  resolveTask.end();
1191
170
1192
170
  // Run passes on linked atoms.
1193
170
  ScopedTask passTask(getDefaultDomain(), "Passes");
1194
170
  PassManager pm;
1195
170
  ctx.addPasses(pm);
1196
170
  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
169
1206
169
  passTask.end();
1207
169
1208
169
  // Give linked atoms to Writer to generate output file.
1209
169
  ScopedTask writeTask(getDefaultDomain(), "Write");
1210
169
  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
168
1220
168
  // Call exit() if we can to avoid calling destructors.
1221
168
  if (CanExitEarly)
1222
0
    exitLld(errorCount() ? 1 : 0);
1223
168
1224
168
1225
168
  return true;
1226
168
}
1227
1228
} // end namespace mach_o
1229
} // end namespace lld