Coverage Report

Created: 2017-09-21 03:39

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/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/Core/ArchiveLibraryFile.h"
17
#include "lld/Core/Error.h"
18
#include "lld/Core/File.h"
19
#include "lld/Core/Instrumentation.h"
20
#include "lld/Core/LLVM.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
242
  DarwinLdOptTable() : OptTable(InfoTable) {}
92
};
93
94
static std::vector<std::unique_ptr<File>>
95
64
makeErrorFile(StringRef path, std::error_code ec) {
96
64
  std::vector<std::unique_ptr<File>> result;
97
64
  result.push_back(llvm::make_unique<ErrorFile>(path, ec));
98
64
  return result;
99
64
}
100
101
static std::vector<std::unique_ptr<File>>
102
5
parseMemberFiles(std::unique_ptr<File> file) {
103
5
  std::vector<std::unique_ptr<File>> members;
104
5
  if (auto *
archive5
= dyn_cast<ArchiveLibraryFile>(file.get())) {
105
2
    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
5
  return members;
111
5
}
112
113
std::vector<std::unique_ptr<File>>
114
loadFile(MachOLinkingContext &ctx, StringRef path,
115
373
         raw_ostream &diag, bool wholeArchive, bool upwardDylib) {
116
373
  if (ctx.logInputFiles())
117
3
    diag << path << "\n";
118
373
119
373
  ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = ctx.getMemoryBuffer(path);
120
373
  if (std::error_code ec = mbOrErr.getError())
121
57
    return makeErrorFile(path, ec);
122
316
  ErrorOr<std::unique_ptr<File>> fileOrErr =
123
316
      ctx.registry().loadFile(std::move(mbOrErr.get()));
124
316
  if (std::error_code ec = fileOrErr.getError())
125
7
    return makeErrorFile(path, ec);
126
309
  std::unique_ptr<File> &file = fileOrErr.get();
127
309
128
309
  // If file is a dylib, inform LinkingContext about it.
129
309
  if (SharedLibraryFile *
shl309
= dyn_cast<SharedLibraryFile>(file.get())) {
130
116
    if (std::error_code ec = shl->parse())
131
0
      return makeErrorFile(path, ec);
132
116
    ctx.registerDylib(reinterpret_cast<mach_o::MachODylibFile *>(shl),
133
116
                      upwardDylib);
134
116
  }
135
309
  
if (309
wholeArchive309
)
136
5
    return parseMemberFiles(std::move(file));
137
304
  std::vector<std::unique_ptr<File>> files;
138
304
  files.push_back(std::move(file));
139
304
  return files;
140
304
}
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
24
static std::string canonicalizePath(StringRef path) {
147
24
  char sep = llvm::sys::path::get_separator().front();
148
24
  if (
sep != '/'24
) {
149
0
    std::string fixedPath = path;
150
0
    std::replace(fixedPath.begin(), fixedPath.end(), sep, '/');
151
0
    return fixedPath;
152
0
  } else {
153
24
    return path;
154
24
  }
155
0
}
156
157
static void addFile(StringRef path, MachOLinkingContext &ctx,
158
                    bool loadWholeArchive,
159
373
                    bool upwardDylib, raw_ostream &diag) {
160
373
  std::vector<std::unique_ptr<File>> files =
161
373
      loadFile(ctx, path, diag, loadWholeArchive, upwardDylib);
162
373
  for (std::unique_ptr<File> &file : files)
163
373
    ctx.getNodes().push_back(llvm::make_unique<FileNode>(std::move(file)));
164
373
}
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
2
                                        raw_ostream &diagnostics) {
171
2
  // Map in export list file.
172
2
  ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
173
2
                                   MemoryBuffer::getFileOrSTDIN(exportFilePath);
174
2
  if (std::error_code ec = mb.getError())
175
0
    return ec;
176
2
  ctx.addInputFileDependency(exportFilePath);
177
2
  StringRef buffer = mb->get()->getBuffer();
178
14
  while (
!buffer.empty()14
) {
179
12
    // Split off each line in the file.
180
12
    std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
181
12
    StringRef line = lineAndRest.first;
182
12
    // Ignore trailing # comments.
183
12
    std::pair<StringRef, StringRef> symAndComment = line.split('#');
184
12
    StringRef sym = symAndComment.first.trim();
185
12
    if (!sym.empty())
186
4
      ctx.addExportSymbol(sym);
187
12
    buffer = lineAndRest.second;
188
12
  }
189
2
  return std::error_code();
190
2
}
191
192
/// Order files are one symbol per line. Blank lines are ignored.
193
/// Trailing comments start with #. Symbol names can be prefixed with an
194
/// architecture name and/or .o leaf name.  Examples:
195
///     _foo
196
///     bar.o:_bar
197
///     libfrob.a(bar.o):_bar
198
///     x86_64:_foo64
199
static std::error_code parseOrderFile(StringRef orderFilePath,
200
                                      MachOLinkingContext &ctx,
201
1
                                      raw_ostream &diagnostics) {
202
1
  // Map in order file.
203
1
  ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
204
1
                                   MemoryBuffer::getFileOrSTDIN(orderFilePath);
205
1
  if (std::error_code ec = mb.getError())
206
0
    return ec;
207
1
  ctx.addInputFileDependency(orderFilePath);
208
1
  StringRef buffer = mb->get()->getBuffer();
209
12
  while (
!buffer.empty()12
) {
210
11
    // Split off each line in the file.
211
11
    std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
212
11
    StringRef line = lineAndRest.first;
213
11
    buffer = lineAndRest.second;
214
11
    // Ignore trailing # comments.
215
11
    std::pair<StringRef, StringRef> symAndComment = line.split('#');
216
11
    if (symAndComment.first.empty())
217
4
      continue;
218
7
    StringRef sym = symAndComment.first.trim();
219
7
    if (sym.empty())
220
0
      continue;
221
7
    // Check for prefix.
222
7
    StringRef prefix;
223
7
    std::pair<StringRef, StringRef> prefixAndSym = sym.split(':');
224
7
    if (
!prefixAndSym.second.empty()7
) {
225
3
      sym = prefixAndSym.second;
226
3
      prefix = prefixAndSym.first;
227
3
      if (
!prefix.endswith(".o") && 3
!prefix.endswith(".o)")3
) {
228
2
        // If arch name prefix does not match arch being linked, ignore symbol.
229
2
        if (!ctx.archName().equals(prefix))
230
2
          continue;
231
0
        prefix = "";
232
0
      }
233
3
    } else
234
4
     sym = prefixAndSym.first;
235
5
    
if (5
!sym.empty()5
) {
236
5
      ctx.appendOrderedSymbol(sym, prefix);
237
5
      //llvm::errs() << sym << ", prefix=" << prefix << "\n";
238
5
    }
239
11
  }
240
1
  return std::error_code();
241
1
}
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
2
                                raw_ostream &diagnostics) {
257
2
  // If there is a comma, split off <dir>.
258
2
  std::pair<StringRef, StringRef> opt = fileListPath.split(',');
259
2
  StringRef filePath = opt.first;
260
2
  StringRef dirName = opt.second;
261
2
  ctx.addInputFileDependency(filePath);
262
2
  // Map in file list file.
263
2
  ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
264
2
                                        MemoryBuffer::getFileOrSTDIN(filePath);
265
2
  if (std::error_code ec = mb.getError())
266
0
    return llvm::errorCodeToError(ec);
267
2
  StringRef buffer = mb->get()->getBuffer();
268
8
  while (
!buffer.empty()8
) {
269
6
    // Split off each line in the file.
270
6
    std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
271
6
    StringRef line = lineAndRest.first;
272
6
    StringRef path;
273
6
    if (
!dirName.empty()6
) {
274
3
      // If there is a <dir> then prepend dir to each line.
275
3
      SmallString<256> fullPath;
276
3
      fullPath.assign(dirName);
277
3
      llvm::sys::path::append(fullPath, Twine(line));
278
3
      path = ctx.copy(fullPath.str());
279
6
    } else {
280
3
      // No <dir> use whole line as input file path.
281
3
      path = ctx.copy(line);
282
3
    }
283
6
    if (
!ctx.pathExists(path)6
) {
284
0
      return llvm::make_error<GenericError>(Twine("File not found '")
285
0
                                            + path
286
0
                                            + "'");
287
0
    }
288
6
    
if (6
ctx.testingFileUsage()6
) {
289
6
      diagnostics << "Found filelist entry " << canonicalizePath(path) << '\n';
290
6
    }
291
6
    addFile(path, ctx, forceLoad, false, diagnostics);
292
6
    buffer = lineAndRest.second;
293
6
  }
294
2
  return llvm::Error::success();
295
2
}
296
297
/// Parse number assuming it is base 16, but allow 0x prefix.
298
7
static bool parseNumberBase16(StringRef numStr, uint64_t &baseAddress) {
299
7
  if (numStr.startswith_lower("0x"))
300
2
    numStr = numStr.drop_front(2);
301
7
  return numStr.getAsInteger(16, baseAddress);
302
7
}
303
304
225
static void parseLLVMOptions(const LinkingContext &ctx) {
305
225
  // Honor -mllvm
306
225
  if (
!ctx.llvmOptions().empty()225
) {
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 != numArgs0
;
++i0
)
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
225
}
316
317
namespace lld {
318
namespace mach_o {
319
320
bool parse(llvm::ArrayRef<const char *> args, MachOLinkingContext &ctx,
321
242
           raw_ostream &diagnostics) {
322
242
  // Parse command line options using DarwinLdOptions.td
323
242
  DarwinLdOptTable table;
324
242
  unsigned missingIndex;
325
242
  unsigned missingCount;
326
242
  llvm::opt::InputArgList parsedArgs =
327
242
      table.ParseArgs(args.slice(1), missingIndex, missingCount);
328
242
  if (
missingCount242
) {
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
242
335
242
  
for (auto unknownArg : parsedArgs.filtered(OPT_UNKNOWN)) 242
{
336
0
    diagnostics << "warning: ignoring unknown argument: "
337
0
                << unknownArg->getAsString(parsedArgs) << "\n";
338
0
  }
339
242
340
242
  // Figure out output kind ( -dylib, -r, -bundle, -preload, or -static )
341
242
  llvm::MachO::HeaderFileType fileType = llvm::MachO::MH_EXECUTE;
342
242
  bool isStaticExecutable = false;
343
242
  if (llvm::opt::Arg *kind = parsedArgs.getLastArg(
344
159
          OPT_dylib, OPT_relocatable, OPT_bundle, OPT_static, OPT_preload)) {
345
159
    switch (kind->getOption().getID()) {
346
50
    case OPT_dylib:
347
50
      fileType = llvm::MachO::MH_DYLIB;
348
50
      break;
349
89
    case OPT_relocatable:
350
89
      fileType = llvm::MachO::MH_OBJECT;
351
89
      break;
352
9
    case OPT_bundle:
353
9
      fileType = llvm::MachO::MH_BUNDLE;
354
9
      break;
355
10
    case OPT_static:
356
10
      fileType = llvm::MachO::MH_EXECUTE;
357
10
      isStaticExecutable = true;
358
10
      break;
359
1
    case OPT_preload:
360
1
      fileType = llvm::MachO::MH_PRELOAD;
361
1
      break;
362
242
    }
363
242
  }
364
242
365
242
  // Handle -arch xxx
366
242
  MachOLinkingContext::Arch arch = MachOLinkingContext::arch_unknown;
367
242
  if (llvm::opt::Arg *
archStr242
= parsedArgs.getLastArg(OPT_arch)) {
368
235
    arch = MachOLinkingContext::archFromName(archStr->getValue());
369
235
    if (
arch == MachOLinkingContext::arch_unknown235
) {
370
0
      diagnostics << "error: unknown arch named '" << archStr->getValue()
371
0
                  << "'\n";
372
0
      return false;
373
0
    }
374
242
  }
375
242
  // If no -arch specified, scan input files to find first non-fat .o file.
376
242
  
if (242
arch == MachOLinkingContext::arch_unknown242
) {
377
1
    for (auto &inFile : parsedArgs.filtered(OPT_INPUT)) {
378
1
      // This is expensive because it opens and maps the file.  But that is
379
1
      // ok because no -arch is rare.
380
1
      if (MachOLinkingContext::isThinObjectFile(inFile->getValue(), arch))
381
1
        break;
382
7
    }
383
7
    if (arch == MachOLinkingContext::arch_unknown &&
384
7
        
!parsedArgs.getLastArg(OPT_test_file_usage)6
) {
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
1
      else
389
0
        diagnostics << "error: -arch not specified and could not be inferred\n";
390
1
      return false;
391
1
    }
392
241
  }
393
241
394
241
  // Handle -macosx_version_min or -ios_version_min
395
241
  MachOLinkingContext::OS os = MachOLinkingContext::OS::unknown;
396
241
  uint32_t minOSVersion = 0;
397
241
  if (llvm::opt::Arg *minOS =
398
241
          parsedArgs.getLastArg(OPT_macosx_version_min, OPT_ios_version_min,
399
64
                                OPT_ios_simulator_version_min)) {
400
64
    switch (minOS->getOption().getID()) {
401
56
    case OPT_macosx_version_min:
402
56
      os = MachOLinkingContext::OS::macOSX;
403
56
      if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
404
56
                                                  minOSVersion)) {
405
0
        diagnostics << "error: malformed macosx_version_min value\n";
406
0
        return false;
407
0
      }
408
56
      break;
409
2
    case OPT_ios_version_min:
410
2
      os = MachOLinkingContext::OS::iOS;
411
2
      if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
412
2
                                                  minOSVersion)) {
413
0
        diagnostics << "error: malformed ios_version_min value\n";
414
0
        return false;
415
0
      }
416
2
      break;
417
6
    case OPT_ios_simulator_version_min:
418
6
      os = MachOLinkingContext::OS::iOS_simulator;
419
6
      if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
420
6
                                                  minOSVersion)) {
421
0
        diagnostics << "error: malformed ios_simulator_version_min value\n";
422
0
        return false;
423
0
      }
424
6
      break;
425
64
    }
426
0
  } else {
427
177
    // No min-os version on command line, check environment variables
428
177
  }
429
241
430
241
  // Handle export_dynamic
431
241
  // FIXME: Should we warn when this applies to something other than a static
432
241
  // executable or dylib?  Those are the only cases where this has an effect.
433
241
  // Note, this has to come before ctx.configure() so that we get the correct
434
241
  // value for _globalsAreDeadStripRoots.
435
241
  bool exportDynamicSymbols = parsedArgs.hasArg(OPT_export_dynamic);
436
241
437
241
  // Now that there's enough information parsed in, let the linking context
438
241
  // set up default values.
439
241
  ctx.configure(fileType, arch, os, minOSVersion, exportDynamicSymbols);
440
241
441
241
  // Handle -e xxx
442
241
  if (llvm::opt::Arg *entry = parsedArgs.getLastArg(OPT_entry))
443
5
    ctx.setEntrySymbolName(entry->getValue());
444
241
445
241
  // Handle -o xxx
446
241
  if (llvm::opt::Arg *outpath = parsedArgs.getLastArg(OPT_output))
447
178
    ctx.setOutputPath(outpath->getValue());
448
241
  else
449
63
    ctx.setOutputPath("a.out");
450
241
451
241
  // Handle -image_base XXX and -seg1addr XXXX
452
241
  if (llvm::opt::Arg *
imageBase241
= parsedArgs.getLastArg(OPT_image_base)) {
453
4
    uint64_t baseAddress;
454
4
    if (
parseNumberBase16(imageBase->getValue(), baseAddress)4
) {
455
1
      diagnostics << "error: image_base expects a hex number\n";
456
1
      return false;
457
3
    } else 
if (3
baseAddress < ctx.pageZeroSize()3
) {
458
1
      diagnostics << "error: image_base overlaps with __PAGEZERO\n";
459
1
      return false;
460
2
    } else 
if (2
baseAddress % ctx.pageSize()2
) {
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
241
469
241
  // Handle -dead_strip
470
238
  
if (238
parsedArgs.getLastArg(OPT_dead_strip)238
)
471
14
    ctx.setDeadStripping(true);
472
238
473
238
  bool globalWholeArchive = false;
474
238
  // Handle -all_load
475
238
  if (parsedArgs.getLastArg(OPT_all_load))
476
1
    globalWholeArchive = true;
477
238
478
238
  // Handle -install_name
479
238
  if (llvm::opt::Arg *installName = parsedArgs.getLastArg(OPT_install_name))
480
6
    ctx.setInstallName(installName->getValue());
481
238
  else
482
232
    ctx.setInstallName(ctx.outputPath());
483
238
484
238
  // Handle -mark_dead_strippable_dylib
485
238
  if (parsedArgs.getLastArg(OPT_mark_dead_strippable_dylib))
486
2
    ctx.setDeadStrippableDylib(true);
487
238
488
238
  // Handle -compatibility_version and -current_version
489
238
  if (llvm::opt::Arg *
vers238
= parsedArgs.getLastArg(OPT_compatibility_version)) {
490
6
    if (
ctx.outputMachOType() != llvm::MachO::MH_DYLIB6
) {
491
2
      diagnostics
492
2
          << "error: -compatibility_version can only be used with -dylib\n";
493
2
      return false;
494
2
    }
495
4
    uint32_t parsedVers;
496
4
    if (
MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)4
) {
497
0
      diagnostics << "error: -compatibility_version value is malformed\n";
498
0
      return false;
499
0
    }
500
4
    ctx.setCompatibilityVersion(parsedVers);
501
4
  }
502
238
503
236
  
if (llvm::opt::Arg *236
vers236
= parsedArgs.getLastArg(OPT_current_version)) {
504
6
    if (
ctx.outputMachOType() != llvm::MachO::MH_DYLIB6
) {
505
2
      diagnostics << "-current_version can only be used with -dylib\n";
506
2
      return false;
507
2
    }
508
4
    uint32_t parsedVers;
509
4
    if (
MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)4
) {
510
0
      diagnostics << "error: -current_version value is malformed\n";
511
0
      return false;
512
0
    }
513
4
    ctx.setCurrentVersion(parsedVers);
514
4
  }
515
236
516
236
  // Handle -bundle_loader
517
234
  
if (llvm::opt::Arg *234
loader234
= parsedArgs.getLastArg(OPT_bundle_loader))
518
2
    ctx.setBundleLoader(loader->getValue());
519
234
520
234
  // Handle -sectalign segname sectname align
521
3
  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') && 3
(alignStr[1] == 'x')3
)
526
3
      alignStr += 2;
527
3
    unsigned long long alignValue;
528
3
    if (
llvm::getAsUnsignedInteger(alignStr, 16, alignValue)3
) {
529
0
      diagnostics << "error: -sectalign alignment value '"
530
0
                  << alignStr << "' not a valid number\n";
531
0
      return false;
532
0
    }
533
3
    uint16_t align = 1 << llvm::countTrailingZeros(alignValue);
534
3
    if (
!llvm::isPowerOf2_64(alignValue)3
) {
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
3
    ctx.addSectionAlignment(segName, sectName, align);
542
3
  }
543
234
544
234
  // Handle -mllvm
545
234
  
for (auto &llvmArg : parsedArgs.filtered(OPT_mllvm)) 234
{
546
0
    ctx.appendLLVMOption(llvmArg->getValue());
547
0
  }
548
234
549
234
  // Handle -print_atoms
550
234
  if (parsedArgs.getLastArg(OPT_print_atoms))
551
61
    ctx.setPrintAtoms();
552
234
553
234
  // Handle -t (trace) option.
554
234
  if (parsedArgs.getLastArg(OPT_t))
555
1
    ctx.setLogInputFiles(true);
556
234
557
234
  // Handle -demangle option.
558
234
  if (parsedArgs.getLastArg(OPT_demangle))
559
1
    ctx.setDemangleSymbols(true);
560
234
561
234
  // Handle -keep_private_externs
562
234
  if (
parsedArgs.getLastArg(OPT_keep_private_externs)234
) {
563
2
    ctx.setKeepPrivateExterns(true);
564
2
    if (ctx.outputMachOType() != llvm::MachO::MH_OBJECT)
565
0
      diagnostics << "warning: -keep_private_externs only used in -r mode\n";
566
2
  }
567
234
568
234
  // Handle -dependency_info <path> used by Xcode.
569
234
  if (llvm::opt::Arg *
depInfo234
= parsedArgs.getLastArg(OPT_dependency_info)) {
570
1
    if (std::error_code 
ec1
= 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
234
578
234
  // In -test_file_usage mode, we'll be given an explicit list of paths that
579
234
  // exist. We'll also be expected to print out information about how we located
580
234
  // libraries and so on that the user specified, but not to actually do any
581
234
  // linking.
582
234
  if (
parsedArgs.getLastArg(OPT_test_file_usage)234
) {
583
11
    ctx.setTestingFileUsage();
584
11
585
11
    // With paths existing by fiat, linking is not going to end well.
586
11
    ctx.setDoNothing(true);
587
11
588
11
    // Only bother looking for an existence override if we're going to use it.
589
65
    for (auto existingPath : parsedArgs.filtered(OPT_path_exists)) {
590
65
      ctx.addExistingPathForDebug(existingPath->getValue());
591
65
    }
592
11
  }
593
234
594
234
  // Register possible input file parsers.
595
234
  if (
!ctx.doNothing()234
) {
596
223
    ctx.registry().addSupportMachOObjects(ctx);
597
223
    ctx.registry().addSupportArchives(ctx.logInputFiles());
598
223
    ctx.registry().addSupportYamlFiles();
599
223
  }
600
234
601
234
  // Now construct the set of library search directories, following ld64's
602
234
  // baroque set of accumulated hacks. Mostly, the algorithm constructs
603
234
  //     { syslibroots } x { libpaths }
604
234
  //
605
234
  // Unfortunately, there are numerous exceptions:
606
234
  //   1. Only absolute paths get modified by syslibroot options.
607
234
  //   2. If there is just 1 -syslibroot, system paths not found in it are
608
234
  //      skipped.
609
234
  //   3. If the last -syslibroot is "/", all of them are ignored entirely.
610
234
  //   4. If { syslibroots } x path ==  {}, the original path is kept.
611
234
  std::vector<StringRef> sysLibRoots;
612
8
  for (auto syslibRoot : parsedArgs.filtered(OPT_syslibroot)) {
613
8
    sysLibRoots.push_back(syslibRoot->getValue());
614
8
  }
615
234
  if (
!sysLibRoots.empty()234
) {
616
6
    // Ignore all if last -syslibroot is "/".
617
6
    if (sysLibRoots.back() != "/")
618
5
      ctx.setSysLibRoots(sysLibRoots);
619
6
  }
620
234
621
234
  // Paths specified with -L come first, and are not considered system paths for
622
234
  // the case where there is precisely 1 -syslibroot.
623
8
  for (auto libPath : parsedArgs.filtered(OPT_L)) {
624
8
    ctx.addModifiedSearchDir(libPath->getValue());
625
8
  }
626
234
627
234
  // Process -F directories (where to look for frameworks).
628
5
  for (auto fwPath : parsedArgs.filtered(OPT_F)) {
629
5
    ctx.addFrameworkSearchDir(fwPath->getValue());
630
5
  }
631
234
632
234
  // -Z suppresses the standard search paths.
633
234
  if (
!parsedArgs.hasArg(OPT_Z)234
) {
634
233
    ctx.addModifiedSearchDir("/usr/lib", true);
635
233
    ctx.addModifiedSearchDir("/usr/local/lib", true);
636
233
    ctx.addFrameworkSearchDir("/Library/Frameworks", true);
637
233
    ctx.addFrameworkSearchDir("/System/Library/Frameworks", true);
638
233
  }
639
234
640
234
  // Now that we've constructed the final set of search paths, print out those
641
234
  // search paths in verbose mode.
642
234
  if (
parsedArgs.getLastArg(OPT_v)234
) {
643
8
    diagnostics << "Library search paths:\n";
644
15
    for (auto path : ctx.searchDirs()) {
645
15
      diagnostics << "    " << path << '\n';
646
15
    }
647
8
    diagnostics << "Framework search paths:\n";
648
5
    for (auto path : ctx.frameworkDirs()) {
649
5
      diagnostics << "    " << path << '\n';
650
5
    }
651
8
  }
652
234
653
234
  // Handle -exported_symbols_list <file>
654
2
  for (auto expFile : parsedArgs.filtered(OPT_exported_symbols_list)) {
655
2
    if (
ctx.exportMode() == MachOLinkingContext::ExportMode::blackList2
) {
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
2
    ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
661
2
    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
234
  }
670
234
671
234
  // Handle -exported_symbol <symbol>
672
234
  
for (auto symbol : parsedArgs.filtered(OPT_exported_symbol)) 234
{
673
7
    if (
ctx.exportMode() == MachOLinkingContext::ExportMode::blackList7
) {
674
0
      diagnostics << "error: -exported_symbol cannot be combined "
675
0
                  << "with -unexported_symbol[s_list]\n";
676
0
       return false;
677
0
    }
678
7
    ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
679
7
    ctx.addExportSymbol(symbol->getValue());
680
7
  }
681
234
682
234
  // Handle -unexported_symbols_list <file>
683
234
  
for (auto expFile : parsedArgs.filtered(OPT_unexported_symbols_list)) 234
{
684
0
    if (
ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList0
) {
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
234
  }
699
234
700
234
  // Handle -unexported_symbol <symbol>
701
234
  
for (auto symbol : parsedArgs.filtered(OPT_unexported_symbol)) 234
{
702
2
    if (
ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList2
) {
703
0
      diagnostics << "error: -unexported_symbol cannot be combined "
704
0
                  << "with -exported_symbol[s_list]\n";
705
0
       return false;
706
0
    }
707
2
    ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
708
2
    ctx.addExportSymbol(symbol->getValue());
709
2
  }
710
234
711
234
  // Handle obosolete -multi_module and -single_module
712
234
  
if (llvm::opt::Arg *234
mod234
=
713
1
          parsedArgs.getLastArg(OPT_multi_module, OPT_single_module)) {
714
1
    if (
mod->getOption().getID() == OPT_multi_module1
) {
715
0
      diagnostics << "warning: -multi_module is obsolete and being ignored\n";
716
0
    }
717
1
    else {
718
1
      if (
ctx.outputMachOType() != llvm::MachO::MH_DYLIB1
) {
719
0
        diagnostics << "warning: -single_module being ignored. "
720
0
                       "It is only for use when producing a dylib\n";
721
0
      }
722
1
    }
723
1
  }
724
234
725
234
  // Handle obsolete ObjC options: -objc_gc_compaction, -objc_gc, -objc_gc_only
726
234
  if (
parsedArgs.getLastArg(OPT_objc_gc_compaction)234
) {
727
1
    diagnostics << "error: -objc_gc_compaction is not supported\n";
728
1
    return false;
729
1
  }
730
233
731
233
  
if (233
parsedArgs.getLastArg(OPT_objc_gc)233
) {
732
1
    diagnostics << "error: -objc_gc is not supported\n";
733
1
    return false;
734
1
  }
735
232
736
232
  
if (232
parsedArgs.getLastArg(OPT_objc_gc_only)232
) {
737
1
    diagnostics << "error: -objc_gc_only is not supported\n";
738
1
    return false;
739
1
  }
740
231
741
231
  // Handle -pie or -no_pie
742
231
  
if (llvm::opt::Arg *231
pie231
= 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
0
      case MachOLinkingContext::OS::iOS:
755
0
        if ((minOSVersion < 0x00040200) &&
756
0
            
(pie->getOption().getID() == OPT_pie)0
) {
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_pie0
) {
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
0
    case llvm::MachO::MH_PRELOAD:
774
0
      break;
775
0
    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
231
    }
785
231
  }
786
231
787
231
  // Handle -version_load_command or -no_version_load_command
788
231
  {
789
231
    bool flagOn = false;
790
231
    bool flagOff = false;
791
231
    if (auto *arg = parsedArgs.getLastArg(OPT_version_load_command,
792
3
                                          OPT_no_version_load_command)) {
793
3
      flagOn = arg->getOption().getID() == OPT_version_load_command;
794
3
      flagOff = arg->getOption().getID() == OPT_no_version_load_command;
795
3
    }
796
231
797
231
    // default to adding version load command for dynamic code,
798
231
    // static code must opt-in
799
231
    switch (ctx.outputMachOType()) {
800
89
      case llvm::MachO::MH_OBJECT:
801
89
        ctx.setGenerateVersionLoadCommand(false);
802
89
        break;
803
86
      case llvm::MachO::MH_EXECUTE:
804
86
        // dynamic executables default to generating a version load command,
805
86
        // while static exectuables only generate it if required.
806
86
        if (
isStaticExecutable86
) {
807
10
          if (flagOn)
808
1
            ctx.setGenerateVersionLoadCommand(true);
809
86
        } else {
810
76
          if (!flagOff)
811
76
            ctx.setGenerateVersionLoadCommand(true);
812
76
        }
813
86
        break;
814
1
      case llvm::MachO::MH_PRELOAD:
815
1
      case llvm::MachO::MH_KEXT_BUNDLE:
816
1
        if (flagOn)
817
0
          ctx.setGenerateVersionLoadCommand(true);
818
1
        break;
819
55
      case llvm::MachO::MH_DYLINKER:
820
55
      case llvm::MachO::MH_DYLIB:
821
55
      case llvm::MachO::MH_BUNDLE:
822
55
        if (!flagOff)
823
54
          ctx.setGenerateVersionLoadCommand(true);
824
55
        break;
825
0
      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
231
    }
833
231
  }
834
231
835
231
  // Handle -function_starts or -no_function_starts
836
231
  {
837
231
    bool flagOn = false;
838
231
    bool flagOff = false;
839
231
    if (auto *arg = parsedArgs.getLastArg(OPT_function_starts,
840
3
                                          OPT_no_function_starts)) {
841
3
      flagOn = arg->getOption().getID() == OPT_function_starts;
842
3
      flagOff = arg->getOption().getID() == OPT_no_function_starts;
843
3
    }
844
231
845
231
    // default to adding functions start for dynamic code, static code must
846
231
    // opt-in
847
231
    switch (ctx.outputMachOType()) {
848
89
      case llvm::MachO::MH_OBJECT:
849
89
        ctx.setGenerateFunctionStartsLoadCommand(false);
850
89
        break;
851
86
      case llvm::MachO::MH_EXECUTE:
852
86
        // dynamic executables default to generating a version load command,
853
86
        // while static exectuables only generate it if required.
854
86
        if (
isStaticExecutable86
) {
855
10
          if (flagOn)
856
1
            ctx.setGenerateFunctionStartsLoadCommand(true);
857
86
        } else {
858
76
          if (!flagOff)
859
76
            ctx.setGenerateFunctionStartsLoadCommand(true);
860
76
        }
861
86
        break;
862
1
      case llvm::MachO::MH_PRELOAD:
863
1
      case llvm::MachO::MH_KEXT_BUNDLE:
864
1
        if (flagOn)
865
0
          ctx.setGenerateFunctionStartsLoadCommand(true);
866
1
        break;
867
55
      case llvm::MachO::MH_DYLINKER:
868
55
      case llvm::MachO::MH_DYLIB:
869
55
      case llvm::MachO::MH_BUNDLE:
870
55
        if (!flagOff)
871
54
          ctx.setGenerateFunctionStartsLoadCommand(true);
872
55
        break;
873
0
      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
231
    }
881
231
  }
882
231
883
231
  // Handle -data_in_code_info or -no_data_in_code_info
884
231
  {
885
231
    bool flagOn = false;
886
231
    bool flagOff = false;
887
231
    if (auto *arg = parsedArgs.getLastArg(OPT_data_in_code_info,
888
5
                                          OPT_no_data_in_code_info)) {
889
5
      flagOn = arg->getOption().getID() == OPT_data_in_code_info;
890
5
      flagOff = arg->getOption().getID() == OPT_no_data_in_code_info;
891
5
    }
892
231
893
231
    // default to adding data in code for dynamic code, static code must
894
231
    // opt-in
895
231
    switch (ctx.outputMachOType()) {
896
89
      case llvm::MachO::MH_OBJECT:
897
89
        if (!flagOff)
898
88
          ctx.setGenerateDataInCodeLoadCommand(true);
899
89
        break;
900
86
      case llvm::MachO::MH_EXECUTE:
901
86
        // dynamic executables default to generating a version load command,
902
86
        // while static exectuables only generate it if required.
903
86
        if (
isStaticExecutable86
) {
904
10
          if (flagOn)
905
1
            ctx.setGenerateDataInCodeLoadCommand(true);
906
86
        } else {
907
76
          if (!flagOff)
908
76
            ctx.setGenerateDataInCodeLoadCommand(true);
909
76
        }
910
86
        break;
911
1
      case llvm::MachO::MH_PRELOAD:
912
1
      case llvm::MachO::MH_KEXT_BUNDLE:
913
1
        if (flagOn)
914
0
          ctx.setGenerateDataInCodeLoadCommand(true);
915
1
        break;
916
55
      case llvm::MachO::MH_DYLINKER:
917
55
      case llvm::MachO::MH_DYLIB:
918
55
      case llvm::MachO::MH_BUNDLE:
919
55
        if (!flagOff)
920
54
          ctx.setGenerateDataInCodeLoadCommand(true);
921
55
        break;
922
0
      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
231
    }
930
231
  }
931
231
932
231
  // Handle sdk_version
933
231
  
if (llvm::opt::Arg *231
arg231
= parsedArgs.getLastArg(OPT_sdk_version)) {
934
2
    uint32_t sdkVersion = 0;
935
2
    if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
936
2
                                                sdkVersion)) {
937
1
      diagnostics << "error: malformed sdkVersion value\n";
938
1
      return false;
939
1
    }
940
1
    ctx.setSdkVersion(sdkVersion);
941
231
  } else 
if (229
ctx.generateVersionLoadCommand()229
) {
942
129
    // If we don't have an sdk version, but were going to emit a load command
943
129
    // with min_version, then we need to give an warning as we have no sdk
944
129
    // version to put in that command.
945
129
    // FIXME: We need to decide whether to make this an error.
946
129
    diagnostics << "warning: -sdk_version is required when emitting "
947
129
                   "min version load command.  "
948
129
                   "Setting sdk version to match provided min version\n";
949
129
    ctx.setSdkVersion(ctx.osMinVersion());
950
129
  }
951
231
952
231
  // Handle source_version
953
230
  
if (llvm::opt::Arg *230
arg230
= parsedArgs.getLastArg(OPT_source_version)) {
954
2
    uint64_t version = 0;
955
2
    if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
956
2
                                                version)) {
957
1
      diagnostics << "error: malformed source_version value\n";
958
1
      return false;
959
1
    }
960
1
    ctx.setSourceVersion(version);
961
1
  }
962
230
963
230
  // Handle stack_size
964
229
  
if (llvm::opt::Arg *229
stackSize229
= parsedArgs.getLastArg(OPT_stack_size)) {
965
3
    uint64_t stackSizeVal;
966
3
    if (
parseNumberBase16(stackSize->getValue(), stackSizeVal)3
) {
967
1
      diagnostics << "error: stack_size expects a hex number\n";
968
1
      return false;
969
1
    }
970
2
    
if (2
(stackSizeVal % ctx.pageSize()) != 02
) {
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
229
979
229
  // Handle debug info handling options: -S
980
227
  
if (227
parsedArgs.hasArg(OPT_S)227
)
981
0
    ctx.setDebugInfoMode(MachOLinkingContext::DebugInfoMode::noDebugMap);
982
227
983
227
  // Handle -order_file <file>
984
1
  for (auto orderFile : parsedArgs.filtered(OPT_order_file)) {
985
1
    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
227
  }
994
227
995
227
  // Handle -flat_namespace.
996
227
  
if (llvm::opt::Arg *227
ns227
=
997
5
          parsedArgs.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace)) {
998
5
    if (ns->getOption().getID() == OPT_flat_namespace)
999
2
      ctx.setUseFlatNamespace(true);
1000
5
  }
1001
227
1002
227
  // Handle -undefined
1003
227
  if (llvm::opt::Arg *
undef227
= parsedArgs.getLastArg(OPT_undefined)) {
1004
5
    MachOLinkingContext::UndefinedMode UndefMode;
1005
5
    if (StringRef(undef->getValue()).equals("error"))
1006
1
      UndefMode = MachOLinkingContext::UndefinedMode::error;
1007
4
    else 
if (4
StringRef(undef->getValue()).equals("warning")4
)
1008
1
      UndefMode = MachOLinkingContext::UndefinedMode::warning;
1009
3
    else 
if (3
StringRef(undef->getValue()).equals("suppress")3
)
1010
2
      UndefMode = MachOLinkingContext::UndefinedMode::suppress;
1011
1
    else 
if (1
StringRef(undef->getValue()).equals("dynamic_lookup")1
)
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
5
1019
5
    
if (5
ctx.useFlatNamespace()5
) {
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
5
    } else {
1025
3
      // If we're using -twolevel_namespace then 'warning' and 'suppress' are
1026
3
      // illegal. Emit a diagnostic if they've been (mis)used.
1027
3
      if (UndefMode == MachOLinkingContext::UndefinedMode::warning ||
1028
3
          
UndefMode == MachOLinkingContext::UndefinedMode::suppress2
) {
1029
2
        diagnostics << "error: can't use -undefined warning or suppress with "
1030
2
                       "-twolevel_namespace\n";
1031
2
        return false;
1032
2
      }
1033
3
    }
1034
3
1035
3
    ctx.setUndefinedMode(UndefMode);
1036
3
  }
1037
227
1038
227
  // Handle -no_objc_category_merging.
1039
225
  
if (225
parsedArgs.getLastArg(OPT_no_objc_category_merging)225
)
1040
0
    ctx.setMergeObjCCategories(false);
1041
225
1042
225
  // Handle -rpath <path>
1043
225
  if (
parsedArgs.hasArg(OPT_rpath)225
) {
1044
1
    switch (ctx.outputMachOType()) {
1045
1
      case llvm::MachO::MH_EXECUTE:
1046
1
      case llvm::MachO::MH_DYLIB:
1047
1
      case llvm::MachO::MH_BUNDLE:
1048
1
        if (
!ctx.minOS("10.5", "2.0")1
) {
1049
0
          if (
ctx.os() == MachOLinkingContext::OS::macOSX0
) {
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
1
        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
1
    }
1064
1
1065
1
    
for (auto rPath : parsedArgs.filtered(OPT_rpath)) 1
{
1066
1
      ctx.addRpath(rPath->getValue());
1067
1
    }
1068
1
  }
1069
225
1070
225
  // Parse the LLVM options before we process files in case the file handling
1071
225
  // makes use of things like DEBUG().
1072
225
  parseLLVMOptions(ctx);
1073
225
1074
225
  // Handle input files and sectcreate.
1075
1.25k
  for (auto &arg : parsedArgs) {
1076
1.25k
    bool upward;
1077
1.25k
    llvm::Optional<StringRef> resolvedPath;
1078
1.25k
    switch (arg->getOption().getID()) {
1079
881
    default:
1080
881
      continue;
1081
341
    case OPT_INPUT:
1082
341
      addFile(arg->getValue(), ctx, globalWholeArchive, false, diagnostics);
1083
341
      break;
1084
2
    case OPT_upward_library:
1085
2
      addFile(arg->getValue(), ctx, false, true, diagnostics);
1086
2
      break;
1087
2
    case OPT_force_load:
1088
2
      addFile(arg->getValue(), ctx, true, false, diagnostics);
1089
2
      break;
1090
16
    case OPT_l:
1091
16
    case OPT_upward_l:
1092
16
      upward = (arg->getOption().getID() == OPT_upward_l);
1093
16
      resolvedPath = ctx.searchLibrary(arg->getValue());
1094
16
      if (
!resolvedPath16
) {
1095
1
        diagnostics << "Unable to find library for " << arg->getSpelling()
1096
1
                    << arg->getValue() << "\n";
1097
1
        return false;
1098
15
      } else 
if (15
ctx.testingFileUsage()15
) {
1099
11
        diagnostics << "Found " << (upward ? 
"upward "1
:
" "10
) << "library "
1100
15
                   << canonicalizePath(resolvedPath.getValue()) << '\n';
1101
15
      }
1102
15
      addFile(resolvedPath.getValue(), ctx, globalWholeArchive,
1103
15
              upward, diagnostics);
1104
15
      break;
1105
7
    case OPT_framework:
1106
7
    case OPT_upward_framework:
1107
7
      upward = (arg->getOption().getID() == OPT_upward_framework);
1108
7
      resolvedPath = ctx.findPathForFramework(arg->getValue());
1109
7
      if (
!resolvedPath7
) {
1110
0
        diagnostics << "Unable to find framework for "
1111
0
                    << arg->getSpelling() << " " << arg->getValue() << "\n";
1112
0
        return false;
1113
7
      } else 
if (7
ctx.testingFileUsage()7
) {
1114
7
        diagnostics << "Found " << (upward ? 
"upward "1
:
" "6
) << "framework "
1115
7
                    << canonicalizePath(resolvedPath.getValue()) << '\n';
1116
7
      }
1117
7
      addFile(resolvedPath.getValue(), ctx, globalWholeArchive,
1118
7
              upward, diagnostics);
1119
7
      break;
1120
2
    case OPT_filelist:
1121
2
      if (auto ec = loadFileList(arg->getValue(),
1122
2
                                 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
2
      break;
1132
1
    case OPT_sectcreate: {
1133
1
        const char* seg  = arg->getValue(0);
1134
1
        const char* sect = arg->getValue(1);
1135
1
        const char* fileName = arg->getValue(2);
1136
1
1137
1
        ErrorOr<std::unique_ptr<MemoryBuffer>> contentOrErr =
1138
1
          MemoryBuffer::getFile(fileName);
1139
1
1140
1
        if (
!contentOrErr1
) {
1141
0
          diagnostics << "error: can't open -sectcreate file " << fileName << "\n";
1142
0
          return false;
1143
0
        }
1144
1
1145
1
        ctx.addSectCreateSection(seg, sect, std::move(*contentOrErr));
1146
1
      }
1147
1
      break;
1148
1.25k
    }
1149
1.25k
  }
1150
224
1151
224
  
if (224
ctx.getNodes().empty()224
) {
1152
0
    diagnostics << "No input files\n";
1153
0
    return false;
1154
0
  }
1155
224
1156
224
  // Validate the combination of options used.
1157
224
  return ctx.validate(diagnostics);
1158
224
}
1159
1160
364
static void createFiles(MachOLinkingContext &ctx, bool Implicit) {
1161
364
  std::vector<std::unique_ptr<File>> Files;
1162
364
  if (Implicit)
1163
182
    ctx.createImplicitFiles(Files);
1164
364
  else
1165
182
    ctx.createInternalFiles(Files);
1166
684
  for (auto i = Files.rbegin(), e = Files.rend(); 
i != e684
;
++i320
) {
1167
320
    auto &members = ctx.getNodes();
1168
320
    members.insert(members.begin(), llvm::make_unique<FileNode>(std::move(*i)));
1169
320
  }
1170
364
}
1171
1172
/// This is where the link is actually performed.
1173
206
bool link(llvm::ArrayRef<const char *> args, raw_ostream &diagnostics) {
1174
206
  MachOLinkingContext ctx;
1175
206
  if (!parse(args, ctx, diagnostics))
1176
14
    return false;
1177
192
  
if (192
ctx.doNothing()192
)
1178
10
    return true;
1179
182
  
if (182
ctx.getNodes().empty()182
)
1180
0
    return false;
1181
182
1182
182
  for (std::unique_ptr<Node> &ie : ctx.getNodes())
1183
316
    
if (FileNode *316
node316
= dyn_cast<FileNode>(ie.get()))
1184
316
      node->getFile()->parse();
1185
182
1186
182
  createFiles(ctx, false /* Implicit */);
1187
182
1188
182
  // Give target a chance to add files
1189
182
  createFiles(ctx, true /* Implicit */);
1190
182
1191
182
  // Give target a chance to postprocess input files.
1192
182
  // Mach-O uses this chance to move all object files before library files.
1193
182
  ctx.finalizeInputFiles();
1194
182
1195
182
  // Do core linking.
1196
182
  ScopedTask resolveTask(getDefaultDomain(), "Resolve");
1197
182
  Resolver resolver(ctx);
1198
182
  if (!resolver.resolve())
1199
14
    return false;
1200
168
  SimpleFile *merged = nullptr;
1201
168
  {
1202
168
    std::unique_ptr<SimpleFile> mergedFile = resolver.resultFile();
1203
168
    merged = mergedFile.get();
1204
168
    auto &members = ctx.getNodes();
1205
168
    members.insert(members.begin(),
1206
168
                   llvm::make_unique<FileNode>(std::move(mergedFile)));
1207
168
  }
1208
168
  resolveTask.end();
1209
168
1210
168
  // Run passes on linked atoms.
1211
168
  ScopedTask passTask(getDefaultDomain(), "Passes");
1212
168
  PassManager pm;
1213
168
  ctx.addPasses(pm);
1214
168
  if (auto 
ec168
= 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
167
1223
167
  passTask.end();
1224
167
1225
167
  // Give linked atoms to Writer to generate output file.
1226
167
  ScopedTask writeTask(getDefaultDomain(), "Write");
1227
167
  if (auto 
ec167
= ctx.writeFile(*merged)) {
1228
1
    // FIXME: This should be passed to logAllUnhandledErrors but it needs
1229
1
    // to be passed a Twine instead of a string.
1230
1
    diagnostics << "Failed to write file '" << ctx.outputPath() << "': ";
1231
1
    logAllUnhandledErrors(std::move(ec), diagnostics, std::string());
1232
1
    return false;
1233
1
  }
1234
166
1235
166
  return true;
1236
166
}
1237
1238
} // end namespace mach_o
1239
} // end namespace lld