Coverage Report

Created: 2018-01-17 21:32

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