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