1//===- llvm-ifs.cpp -------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===-----------------------------------------------------------------------===/
8
9#include "ErrorCollector.h"
10#include "llvm/ADT/StringRef.h"
11#include "llvm/ADT/StringSwitch.h"
12#include "llvm/BinaryFormat/ELF.h"
13#include "llvm/InterfaceStub/ELFObjHandler.h"
14#include "llvm/InterfaceStub/IFSHandler.h"
15#include "llvm/InterfaceStub/IFSStub.h"
16#include "llvm/ObjectYAML/yaml2obj.h"
17#include "llvm/Option/Arg.h"
18#include "llvm/Option/ArgList.h"
19#include "llvm/Option/Option.h"
20#include "llvm/Support/CommandLine.h"
21#include "llvm/Support/Debug.h"
22#include "llvm/Support/Driver.h"
23#include "llvm/Support/Errc.h"
24#include "llvm/Support/Error.h"
25#include "llvm/Support/MemoryBuffer.h"
26#include "llvm/Support/VersionTuple.h"
27#include "llvm/Support/WithColor.h"
28#include "llvm/Support/YAMLTraits.h"
29#include "llvm/Support/raw_ostream.h"
30#include "llvm/TargetParser/Triple.h"
31#include "llvm/TextAPI/InterfaceFile.h"
32#include "llvm/TextAPI/TextAPIReader.h"
33#include "llvm/TextAPI/TextAPIWriter.h"
34#include <optional>
35#include <string>
36#include <vector>
37
38using namespace llvm;
39using namespace llvm::yaml;
40using namespace llvm::MachO;
41using namespace llvm::ifs;
42
43#define DEBUG_TYPE "llvm-ifs"
44
45namespace {
46const VersionTuple IfsVersionCurrent(3, 0);
47
48enum class FileFormat { IFS, ELF, TBD };
49} // end anonymous namespace
50
51using namespace llvm::opt;
52enum ID {
53 OPT_INVALID = 0, // This is not an option ID.
54#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
55#include "Opts.inc"
56#undef OPTION
57};
58
59#define OPTTABLE_CODE
60#include "Opts.inc"
61
62class IFSOptTable : public opt::OptTable {
63public:
64 IFSOptTable() : opt::OptTable(optionTables()) {
65 setGroupedShortOptions(true);
66 }
67};
68
69struct DriverConfig {
70 std::vector<std::string> InputFilePaths;
71
72 std::optional<FileFormat> InputFormat;
73 std::optional<FileFormat> OutputFormat;
74
75 std::optional<std::string> HintIfsTarget;
76 std::optional<std::string> OptTargetTriple;
77 std::optional<IFSArch> OverrideArch;
78 std::optional<IFSBitWidthType> OverrideBitWidth;
79 std::optional<IFSEndiannessType> OverrideEndianness;
80
81 bool StripIfsArch = false;
82 bool StripIfsBitwidth = false;
83 bool StripIfsEndianness = false;
84 bool StripIfsTarget = false;
85 bool StripNeeded = false;
86 bool StripSize = false;
87 bool StripUndefined = false;
88
89 std::vector<std::string> Exclude;
90
91 std::optional<std::string> SoName;
92
93 std::optional<std::string> Output;
94 std::optional<std::string> OutputElf;
95 std::optional<std::string> OutputIfs;
96 std::optional<std::string> OutputTbd;
97
98 bool WriteIfChanged = false;
99};
100
101static std::string getTypeName(IFSSymbolType Type) {
102 switch (Type) {
103 case IFSSymbolType::NoType:
104 return "NoType";
105 case IFSSymbolType::Func:
106 return "Func";
107 case IFSSymbolType::Object:
108 return "Object";
109 case IFSSymbolType::TLS:
110 return "TLS";
111 case IFSSymbolType::Unknown:
112 return "Unknown";
113 }
114 llvm_unreachable("Unexpected ifs symbol type.");
115}
116
117static Expected<std::unique_ptr<IFSStub>>
118readInputFile(std::optional<FileFormat> &InputFormat, StringRef FilePath) {
119 // Read in file.
120 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrError =
121 MemoryBuffer::getFileOrSTDIN(Filename: FilePath, /*IsText=*/true);
122 if (!BufOrError)
123 return createStringError(EC: BufOrError.getError(), Fmt: "Could not open `%s`",
124 Vals: FilePath.data());
125
126 std::unique_ptr<MemoryBuffer> FileReadBuffer = std::move(*BufOrError);
127 ErrorCollector EC(/*UseFatalErrors=*/false);
128
129 // First try to read as a binary (fails fast if not binary).
130 if (!InputFormat || *InputFormat == FileFormat::ELF) {
131 Expected<std::unique_ptr<IFSStub>> StubFromELF =
132 readELFFile(Buf: FileReadBuffer->getMemBufferRef());
133 if (StubFromELF) {
134 InputFormat = FileFormat::ELF;
135 (*StubFromELF)->IfsVersion = IfsVersionCurrent;
136 return std::move(*StubFromELF);
137 }
138 EC.addError(E: StubFromELF.takeError(), Tag: "BinaryRead");
139 }
140
141 // Fall back to reading as a ifs.
142 if (!InputFormat || *InputFormat == FileFormat::IFS) {
143 Expected<std::unique_ptr<IFSStub>> StubFromIFS =
144 readIFSFromBuffer(Buf: FileReadBuffer->getBuffer());
145 if (StubFromIFS) {
146 InputFormat = FileFormat::IFS;
147 if ((*StubFromIFS)->IfsVersion > IfsVersionCurrent)
148 EC.addError(
149 E: createStringError(EC: errc::not_supported,
150 S: "IFS version " +
151 (*StubFromIFS)->IfsVersion.getAsString() +
152 " is unsupported."),
153 Tag: "ReadInputFile");
154 else
155 return std::move(*StubFromIFS);
156 } else {
157 EC.addError(E: StubFromIFS.takeError(), Tag: "YamlParse");
158 }
159 }
160
161 // If both readers fail, build a new error that includes all information.
162 EC.addError(E: createStringError(EC: errc::not_supported,
163 Fmt: "No file readers succeeded reading `%s` "
164 "(unsupported/malformed file?)",
165 Vals: FilePath.data()),
166 Tag: "ReadInputFile");
167 EC.escalateToFatal();
168 return EC.makeError();
169}
170
171static int writeTbdStub(const Triple &T, const std::vector<IFSSymbol> &Symbols,
172 const StringRef Format, raw_ostream &Out) {
173
174 auto PlatformTypeOrError =
175 [](const llvm::Triple &T) -> llvm::Expected<llvm::MachO::PlatformType> {
176 if (T.isMacOSX())
177 return llvm::MachO::PLATFORM_MACOS;
178 if (T.isTvOS())
179 return llvm::MachO::PLATFORM_TVOS;
180 if (T.isWatchOS())
181 return llvm::MachO::PLATFORM_WATCHOS;
182 // Note: put isiOS last because tvOS and watchOS are also iOS according
183 // to the Triple.
184 if (T.isiOS())
185 return llvm::MachO::PLATFORM_IOS;
186
187 return createStringError(EC: errc::not_supported, S: "Invalid Platform.\n");
188 }(T);
189
190 if (!PlatformTypeOrError)
191 return -1;
192
193 PlatformType Plat = PlatformTypeOrError.get();
194 TargetList Targets({Target(llvm::MachO::mapToArchitecture(Target: T), Plat)});
195
196 InterfaceFile File;
197 File.setFileType(FileType::TBD_V3); // Only supporting v3 for now.
198 File.addTargets(Targets);
199
200 for (const auto &Symbol : Symbols) {
201 auto Name = Symbol.Name;
202 auto Kind = EncodeKind::GlobalSymbol;
203 switch (Symbol.Type) {
204 default:
205 case IFSSymbolType::NoType:
206 Kind = EncodeKind::GlobalSymbol;
207 break;
208 case IFSSymbolType::Object:
209 Kind = EncodeKind::GlobalSymbol;
210 break;
211 case IFSSymbolType::Func:
212 Kind = EncodeKind::GlobalSymbol;
213 break;
214 }
215 if (Symbol.Weak)
216 File.addSymbol(Kind, Name, Targets, Flags: SymbolFlags::WeakDefined);
217 else
218 File.addSymbol(Kind, Name, Targets);
219 }
220
221 SmallString<4096> Buffer;
222 raw_svector_ostream OS(Buffer);
223 if (Error Result = TextAPIWriter::writeToStream(OS, File))
224 return -1;
225 Out << OS.str();
226 return 0;
227}
228
229static void fatalError(Error Err) {
230 WithColor::defaultErrorHandler(Err: std::move(Err));
231 exit(status: 1);
232}
233
234static void fatalError(Twine T) {
235 WithColor::error() << T.str() << '\n';
236 exit(status: 1);
237}
238
239/// writeIFS() writes a Text-Based ELF stub to a file using the latest version
240/// of the YAML parser.
241static Error writeIFS(StringRef FilePath, IFSStub &Stub, bool WriteIfChanged) {
242 // Write IFS to memory first.
243 std::string IFSStr;
244 raw_string_ostream OutStr(IFSStr);
245 Error YAMLErr = writeIFSToOutputStream(OS&: OutStr, Stub);
246 if (YAMLErr)
247 return YAMLErr;
248
249 if (WriteIfChanged) {
250 if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrError =
251 MemoryBuffer::getFile(Filename: FilePath)) {
252 // Compare IFS output with the existing IFS file. If unchanged, avoid
253 // changing the file.
254 if ((*BufOrError)->getBuffer() == IFSStr)
255 return Error::success();
256 }
257 }
258 // Open IFS file for writing.
259 std::error_code SysErr;
260 raw_fd_ostream Out(FilePath, SysErr);
261 if (SysErr)
262 return createStringError(EC: SysErr, Fmt: "Couldn't open `%s` for writing",
263 Vals: FilePath.data());
264 Out << IFSStr;
265 return Error::success();
266}
267
268static DriverConfig parseArgs(int argc, char *const *argv) {
269 BumpPtrAllocator A;
270 StringSaver Saver(A);
271 IFSOptTable Tbl;
272 StringRef ToolName = argv[0];
273 llvm::opt::InputArgList Args = Tbl.parseArgs(
274 Argc: argc, Argv: argv, Unknown: OPT_UNKNOWN, Saver, ErrorFn: [&](StringRef Msg) { fatalError(T: Msg); });
275 if (Args.hasArg(Ids: OPT_help)) {
276 Tbl.printHelp(OS&: llvm::outs(),
277 Usage: (Twine(ToolName) + " <input_file> <output_file> [options]")
278 .str()
279 .c_str(),
280 Title: "shared object stubbing tool");
281 std::exit(status: 0);
282 }
283 if (Args.hasArg(Ids: OPT_version)) {
284 llvm::outs() << ToolName << '\n';
285 cl::PrintVersionMessage();
286 std::exit(status: 0);
287 }
288
289 DriverConfig Config;
290 for (const opt::Arg *A : Args.filtered(Ids: OPT_INPUT))
291 Config.InputFilePaths.push_back(x: A->getValue());
292 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_input_format_EQ)) {
293 Config.InputFormat = StringSwitch<std::optional<FileFormat>>(A->getValue())
294 .Case(S: "IFS", Value: FileFormat::IFS)
295 .Case(S: "ELF", Value: FileFormat::ELF)
296 .Default(Value: std::nullopt);
297 if (!Config.InputFormat)
298 fatalError(T: Twine("invalid argument '") + A->getValue());
299 }
300
301 auto OptionNotFound = [ToolName](StringRef FlagName, StringRef OptionName) {
302 fatalError(T: Twine(ToolName) + ": for the " + FlagName +
303 " option: Cannot find option named '" + OptionName + "'!");
304 };
305 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_output_format_EQ)) {
306 Config.OutputFormat = StringSwitch<std::optional<FileFormat>>(A->getValue())
307 .Case(S: "IFS", Value: FileFormat::IFS)
308 .Case(S: "ELF", Value: FileFormat::ELF)
309 .Case(S: "TBD", Value: FileFormat::TBD)
310 .Default(Value: std::nullopt);
311 if (!Config.OutputFormat)
312 OptionNotFound("--output-format", A->getValue());
313 }
314 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_arch_EQ)) {
315 uint16_t eMachine = ELF::convertArchNameToEMachine(Arch: A->getValue());
316 if (eMachine == ELF::EM_NONE) {
317 fatalError(T: Twine("unknown arch '") + A->getValue() + "'");
318 }
319 Config.OverrideArch = eMachine;
320 }
321 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_bitwidth_EQ)) {
322 size_t Width;
323 llvm::StringRef S(A->getValue());
324 if (!S.getAsInteger<size_t>(Radix: 10, Result&: Width) || Width == 64 || Width == 32)
325 Config.OverrideBitWidth =
326 Width == 64 ? IFSBitWidthType::IFS64 : IFSBitWidthType::IFS32;
327 else
328 OptionNotFound("--bitwidth", A->getValue());
329 }
330 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_endianness_EQ)) {
331 Config.OverrideEndianness =
332 StringSwitch<std::optional<IFSEndiannessType>>(A->getValue())
333 .Case(S: "little", Value: IFSEndiannessType::Little)
334 .Case(S: "big", Value: IFSEndiannessType::Big)
335 .Default(Value: std::nullopt);
336 if (!Config.OverrideEndianness)
337 OptionNotFound("--endianness", A->getValue());
338 }
339 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_target_EQ))
340 Config.OptTargetTriple = A->getValue();
341 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_hint_ifs_target_EQ))
342 Config.HintIfsTarget = A->getValue();
343
344 Config.StripIfsArch = Args.hasArg(Ids: OPT_strip_ifs_arch);
345 Config.StripIfsBitwidth = Args.hasArg(Ids: OPT_strip_ifs_bitwidth);
346 Config.StripIfsEndianness = Args.hasArg(Ids: OPT_strip_ifs_endianness);
347 Config.StripIfsTarget = Args.hasArg(Ids: OPT_strip_ifs_target);
348 Config.StripUndefined = Args.hasArg(Ids: OPT_strip_undefined);
349 Config.StripNeeded = Args.hasArg(Ids: OPT_strip_needed);
350 Config.StripSize = Args.hasArg(Ids: OPT_strip_size);
351
352 for (const opt::Arg *A : Args.filtered(Ids: OPT_exclude_EQ))
353 Config.Exclude.push_back(x: A->getValue());
354 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_soname_EQ))
355 Config.SoName = A->getValue();
356 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_output_EQ))
357 Config.Output = A->getValue();
358 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_output_elf_EQ))
359 Config.OutputElf = A->getValue();
360 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_output_ifs_EQ))
361 Config.OutputIfs = A->getValue();
362 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_output_tbd_EQ))
363 Config.OutputTbd = A->getValue();
364 Config.WriteIfChanged = Args.hasArg(Ids: OPT_write_if_changed);
365 return Config;
366}
367
368int llvm_ifs_main(int argc, char **argv, const llvm::ToolContext &) {
369 DriverConfig Config = parseArgs(argc, argv);
370
371 if (Config.InputFilePaths.empty())
372 Config.InputFilePaths.push_back(x: "-");
373
374 // If input files are more than one, they can only be IFS files.
375 if (Config.InputFilePaths.size() > 1)
376 Config.InputFormat = FileFormat::IFS;
377
378 // Attempt to merge input.
379 IFSStub Stub;
380 std::map<std::string, IFSSymbol> SymbolMap;
381 std::string PreviousInputFilePath;
382 for (const std::string &InputFilePath : Config.InputFilePaths) {
383 Expected<std::unique_ptr<IFSStub>> StubOrErr =
384 readInputFile(InputFormat&: Config.InputFormat, FilePath: InputFilePath);
385 if (!StubOrErr)
386 fatalError(Err: StubOrErr.takeError());
387
388 std::unique_ptr<IFSStub> TargetStub = std::move(StubOrErr.get());
389 if (PreviousInputFilePath.empty()) {
390 Stub.IfsVersion = TargetStub->IfsVersion;
391 Stub.Target = TargetStub->Target;
392 Stub.SoName = TargetStub->SoName;
393 Stub.NeededLibs = TargetStub->NeededLibs;
394 } else {
395 if (Stub.IfsVersion != TargetStub->IfsVersion) {
396 if (Stub.IfsVersion.getMajor() != IfsVersionCurrent.getMajor()) {
397 WithColor::error()
398 << "Interface Stub: IfsVersion Mismatch."
399 << "\nFilenames: " << PreviousInputFilePath << " "
400 << InputFilePath << "\nIfsVersion Values: " << Stub.IfsVersion
401 << " " << TargetStub->IfsVersion << "\n";
402 return -1;
403 }
404 if (TargetStub->IfsVersion > Stub.IfsVersion)
405 Stub.IfsVersion = TargetStub->IfsVersion;
406 }
407 if (Stub.Target != TargetStub->Target && !TargetStub->Target.empty()) {
408 WithColor::error() << "Interface Stub: Target Mismatch."
409 << "\nFilenames: " << PreviousInputFilePath << " "
410 << InputFilePath;
411 return -1;
412 }
413 if (Stub.SoName != TargetStub->SoName) {
414 WithColor::error() << "Interface Stub: SoName Mismatch."
415 << "\nFilenames: " << PreviousInputFilePath << " "
416 << InputFilePath
417 << "\nSoName Values: " << Stub.SoName << " "
418 << TargetStub->SoName << "\n";
419 return -1;
420 }
421 if (Stub.NeededLibs != TargetStub->NeededLibs) {
422 WithColor::error() << "Interface Stub: NeededLibs Mismatch."
423 << "\nFilenames: " << PreviousInputFilePath << " "
424 << InputFilePath << "\n";
425 return -1;
426 }
427 }
428
429 for (auto Symbol : TargetStub->Symbols) {
430 auto [SI, Inserted] = SymbolMap.try_emplace(k: Symbol.Name, args&: Symbol);
431 if (Inserted)
432 continue;
433
434 assert(Symbol.Name == SI->second.Name && "Symbol Names Must Match.");
435
436 // Check conflicts:
437 if (Symbol.Type != SI->second.Type) {
438 WithColor::error() << "Interface Stub: Type Mismatch for "
439 << Symbol.Name << ".\nFilename: " << InputFilePath
440 << "\nType Values: " << getTypeName(Type: SI->second.Type)
441 << " " << getTypeName(Type: Symbol.Type) << "\n";
442
443 return -1;
444 }
445 if (Symbol.Size != SI->second.Size) {
446 WithColor::error() << "Interface Stub: Size Mismatch for "
447 << Symbol.Name << ".\nFilename: " << InputFilePath
448 << "\nSize Values: " << SI->second.Size << " "
449 << Symbol.Size << "\n";
450
451 return -1;
452 }
453 if (Symbol.Weak != SI->second.Weak) {
454 Symbol.Weak = false;
455 continue;
456 }
457 // TODO: Not checking Warning. Will be dropped.
458 }
459
460 PreviousInputFilePath = InputFilePath;
461 }
462
463 if (Stub.IfsVersion != IfsVersionCurrent)
464 if (Stub.IfsVersion.getMajor() != IfsVersionCurrent.getMajor()) {
465 WithColor::error() << "Interface Stub: Bad IfsVersion: "
466 << Stub.IfsVersion << ", llvm-ifs supported version: "
467 << IfsVersionCurrent << ".\n";
468 return -1;
469 }
470
471 for (auto &Entry : SymbolMap)
472 Stub.Symbols.push_back(x: Entry.second);
473
474 // Change SoName before emitting stubs.
475 if (Config.SoName)
476 Stub.SoName = *Config.SoName;
477
478 Error OverrideError =
479 overrideIFSTarget(Stub, OverrideArch: Config.OverrideArch, OverrideEndianness: Config.OverrideEndianness,
480 OverrideBitWidth: Config.OverrideBitWidth, OverrideTriple: Config.OptTargetTriple);
481 if (OverrideError)
482 fatalError(Err: std::move(OverrideError));
483
484 if (Config.StripNeeded)
485 Stub.NeededLibs.clear();
486
487 if (Error E = filterIFSSyms(Stub, StripUndefined: Config.StripUndefined, Exclude: Config.Exclude))
488 fatalError(Err: std::move(E));
489
490 if (Config.StripSize)
491 for (IFSSymbol &Sym : Stub.Symbols)
492 Sym.Size.reset();
493
494 if (!Config.OutputElf && !Config.OutputIfs && !Config.OutputTbd) {
495 if (!Config.OutputFormat) {
496 WithColor::error() << "at least one output should be specified.";
497 return -1;
498 }
499 } else if (Config.OutputFormat) {
500 WithColor::error() << "'--output-format' cannot be used with "
501 "'--output-{FILE_FORMAT}' options at the same time";
502 return -1;
503 }
504 if (Config.OutputFormat) {
505 // TODO: Remove OutputFormat flag in the next revision.
506 WithColor::warning() << "--output-format option is deprecated, please use "
507 "--output-{FILE_FORMAT} options instead\n";
508 switch (*Config.OutputFormat) {
509 case FileFormat::TBD: {
510 std::error_code SysErr;
511 raw_fd_ostream Out(*Config.Output, SysErr);
512 if (SysErr) {
513 WithColor::error() << "Couldn't open " << *Config.Output
514 << " for writing.\n";
515 return -1;
516 }
517 if (!Stub.Target.Triple) {
518 WithColor::error()
519 << "Triple should be defined when output format is TBD";
520 return -1;
521 }
522 return writeTbdStub(T: llvm::Triple(*Stub.Target.Triple), Symbols: Stub.Symbols,
523 Format: "TBD", Out);
524 }
525 case FileFormat::IFS: {
526 Stub.IfsVersion = IfsVersionCurrent;
527 if (*Config.InputFormat == FileFormat::ELF && Config.HintIfsTarget) {
528 std::error_code HintEC(1, std::generic_category());
529 IFSTarget HintTarget = parseTriple(TripleStr: *Config.HintIfsTarget);
530 if (*Stub.Target.Arch != *HintTarget.Arch)
531 fatalError(Err: make_error<StringError>(
532 Args: "Triple hint does not match the actual architecture", Args&: HintEC));
533 if (*Stub.Target.Endianness != *HintTarget.Endianness)
534 fatalError(Err: make_error<StringError>(
535 Args: "Triple hint does not match the actual endianness", Args&: HintEC));
536 if (*Stub.Target.BitWidth != *HintTarget.BitWidth)
537 fatalError(Err: make_error<StringError>(
538 Args: "Triple hint does not match the actual bit width", Args&: HintEC));
539
540 stripIFSTarget(Stub, StripTriple: true, StripArch: false, StripEndianness: false, StripBitWidth: false);
541 Stub.Target.Triple = *Config.HintIfsTarget;
542 } else {
543 stripIFSTarget(Stub, StripTriple: Config.StripIfsTarget, StripArch: Config.StripIfsArch,
544 StripEndianness: Config.StripIfsEndianness, StripBitWidth: Config.StripIfsBitwidth);
545 }
546 Error IFSWriteError =
547 writeIFS(FilePath: *Config.Output, Stub, WriteIfChanged: Config.WriteIfChanged);
548 if (IFSWriteError)
549 fatalError(Err: std::move(IFSWriteError));
550 break;
551 }
552 case FileFormat::ELF: {
553 Error TargetError = validateIFSTarget(Stub, ParseTriple: true);
554 if (TargetError)
555 fatalError(Err: std::move(TargetError));
556 Error BinaryWriteError =
557 writeBinaryStub(FilePath: *Config.Output, Stub, WriteIfChanged: Config.WriteIfChanged);
558 if (BinaryWriteError)
559 fatalError(Err: std::move(BinaryWriteError));
560 break;
561 }
562 }
563 } else {
564 // Check if output path for individual format.
565 if (Config.OutputElf) {
566 Error TargetError = validateIFSTarget(Stub, ParseTriple: true);
567 if (TargetError)
568 fatalError(Err: std::move(TargetError));
569 Error BinaryWriteError =
570 writeBinaryStub(FilePath: *Config.OutputElf, Stub, WriteIfChanged: Config.WriteIfChanged);
571 if (BinaryWriteError)
572 fatalError(Err: std::move(BinaryWriteError));
573 }
574 if (Config.OutputIfs) {
575 Stub.IfsVersion = IfsVersionCurrent;
576 if (*Config.InputFormat == FileFormat::ELF && Config.HintIfsTarget) {
577 std::error_code HintEC(1, std::generic_category());
578 IFSTarget HintTarget = parseTriple(TripleStr: *Config.HintIfsTarget);
579 if (*Stub.Target.Arch != *HintTarget.Arch)
580 fatalError(Err: make_error<StringError>(
581 Args: "Triple hint does not match the actual architecture", Args&: HintEC));
582 if (*Stub.Target.Endianness != *HintTarget.Endianness)
583 fatalError(Err: make_error<StringError>(
584 Args: "Triple hint does not match the actual endianness", Args&: HintEC));
585 if (*Stub.Target.BitWidth != *HintTarget.BitWidth)
586 fatalError(Err: make_error<StringError>(
587 Args: "Triple hint does not match the actual bit width", Args&: HintEC));
588
589 stripIFSTarget(Stub, StripTriple: true, StripArch: false, StripEndianness: false, StripBitWidth: false);
590 Stub.Target.Triple = *Config.HintIfsTarget;
591 } else {
592 stripIFSTarget(Stub, StripTriple: Config.StripIfsTarget, StripArch: Config.StripIfsArch,
593 StripEndianness: Config.StripIfsEndianness, StripBitWidth: Config.StripIfsBitwidth);
594 }
595 Error IFSWriteError =
596 writeIFS(FilePath: *Config.OutputIfs, Stub, WriteIfChanged: Config.WriteIfChanged);
597 if (IFSWriteError)
598 fatalError(Err: std::move(IFSWriteError));
599 }
600 if (Config.OutputTbd) {
601 std::error_code SysErr;
602 raw_fd_ostream Out(*Config.OutputTbd, SysErr);
603 if (SysErr) {
604 WithColor::error() << "Couldn't open " << *Config.OutputTbd
605 << " for writing.\n";
606 return -1;
607 }
608 if (!Stub.Target.Triple) {
609 WithColor::error()
610 << "Triple should be defined when output format is TBD";
611 return -1;
612 }
613 return writeTbdStub(T: llvm::Triple(*Stub.Target.Triple), Symbols: Stub.Symbols,
614 Format: "TBD", Out);
615 }
616 }
617 return 0;
618}
619