48 "unsupported load command encountered");
56 SectionPred RemovePred = [](
const std::unique_ptr<Section> &) {
61 RemovePred = [&Config, RemovePred](
const std::unique_ptr<Section> &Sec) {
68 RemovePred = [RemovePred](
const std::unique_ptr<Section> &Sec) {
69 if (Sec->Segname ==
"__DWARF")
72 return RemovePred(Sec);
78 RemovePred = [&Config](
const std::unique_ptr<Section> &Sec) {
83 return Obj.removeSections(RemovePred);
90 (*ISE.
Symbol)->Referenced =
true;
97 for (
const std::unique_ptr<Section> &Sec : LC.
Sections)
99 if (R.Symbol && *R.Symbol)
100 (*R.Symbol)->Referenced =
true;
136 Sym.
Name = std::string(
I->getValue());
140 &Obj](
const std::unique_ptr<SymbolEntry> &
N) {
157 *Obj.SwiftVersion &&
N->isSwiftSymbol())
162 Obj.SymTable.removeSymbols(RemovePred);
165template <
typename LCType>
168 "unsupported load command encountered");
173 LC.
Payload.assign(NewCmdsize -
sizeof(LCType), 0);
180 RPathLC.
cmd = MachO::LC_RPATH;
197 if (LC.MachOLoadCommand.load_command_data.cmd == MachO::LC_RPATH) {
204 if (RPathsToRemove.
count(RPath)) {
205 RPathsToRemove.
erase(RPath);
212 if (
Error E = Obj.removeLoadCommands(RemovePred))
218 if (RPathsToRemove.
count(RPath))
220 "no LC_RPATH load command with path: %s",
221 RPath.str().c_str());
238 "no LC_RPATH load command with path: " + Old);
242 "' would create a duplicate load command");
248 case MachO::LC_ID_DYLIB:
254 case MachO::LC_RPATH: {
257 if (!NewRPath.
empty())
264 case MachO::LC_LOAD_DYLIB:
265 case MachO::LC_LOAD_WEAK_DYLIB:
269 if (!NewInstallName.
empty())
281 "' would create a duplicate load command");
290 "' would create a duplicate load command");
293 Obj.LoadCommands.insert(Obj.LoadCommands.begin(),
300 Obj.updateLoadCommandIndexes();
312 if (
Error E = Obj.removeLoadCommands(RemovePred))
322 for (
const std::unique_ptr<Section> &Sec : LC.
Sections) {
323 if (Sec->CanonicalName == SecName) {
328 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
329 llvm::copy(Sec->Content, Buf->getBufferStart());
331 if (
Error E = Buf->commit())
338 "section '%s' not found", SecName.
str().c_str());
344 Section Sec(TargetSegName, Pair.second);
346 Obj.NewSectionsContents.save(NewSection.
SectionData->getBuffer());
352 if (SegName && SegName == TargetSegName) {
354 for (
const std::unique_ptr<Section> &S : LC.
Sections)
355 Addr = std::max(Addr, S->Addr + S->Size);
356 LC.
Sections.push_back(std::make_unique<Section>(Sec));
366 NewSegment.
Sections.push_back(std::make_unique<Section>(Sec));
373 std::tie(SegName, SecName) = SecName.
split(
",");
383 for (
const auto& LC : O.LoadCommands)
384 for (
const auto& Sec : LC.Sections)
385 if (Sec->Segname == SegName && Sec->Sectname == SecName)
388 StringRef ErrMsg =
"could not find section with name '%s' in '%s' segment";
390 SecName.
str().c_str(), SegName.
str().c_str());
394 return LC.getSegmentName() == SegName;
396 if (FoundSeg == O.LoadCommands.end())
398 "could not find segment with name '%s'",
399 SegName.
str().c_str());
401 [SecName](
const std::unique_ptr<Section> &Sec) {
402 return Sec->Sectname == SecName;
404 if (FoundSec == FoundSeg->Sections.end())
406 "could not find section with name '%s'",
407 SecName.
str().c_str());
409 assert(FoundSec->get()->CanonicalName == (SegName +
"," + SecName).str());
416 if (!SecToUpdateOrErr)
418 Section &Sec = *SecToUpdateOrErr;
423 "new section cannot be larger than previous section");
433 if (Name.count(
',') != 1)
435 "invalid section name '%s' (should be formatted "
436 "as '<segment name>,<section name>')",
439 std::pair<StringRef, StringRef> Pair = Name.split(
',');
440 if (Pair.first.size() > 16)
442 "too long segment name: '%s'",
443 Pair.first.str().c_str());
444 if (Pair.second.size() > 16)
446 "too long section name: '%s'",
447 Pair.second.str().c_str());
473 for (std::unique_ptr<Section> &Sec : LC.
Sections)
474 Sec->Relocations.clear();
507 "%s: MH_PRELOAD files are not supported",
516 switch (In.getArch()) {
526 MachOWriter Writer(**O, In.is64Bit(), In.isLittleEndian(),
530 return Writer.
write();
538 for (
const auto &O : In.objects()) {
543 if (!NewArchiveMembersOrErr)
544 return NewArchiveMembersOrErr.
takeError();
545 auto Kind = (*ArOrErr)->kind();
550 *NewArchiveMembersOrErr,
554 (*ArOrErr)->isThin());
555 if (!OutputBufferOrErr)
562 std::move(*OutputBufferOrErr));
564 O.getCPUType(), O.getCPUSubType(),
565 O.getArchFlagName(), O.getAlign());
578 std::errc::invalid_argument,
579 "slice for '%s' of the universal Mach-O binary "
580 "'%s' is not a Mach-O object or an archive",
581 O.getArchFlagName().c_str(),
584 std::string ArchFlagName = O.getArchFlagName();
591 return MachO.takeError();
594 **ObjOrErr, MemStream))
597 auto MB = std::make_unique<SmallVectorMemoryBuffer>(
598 std::move(Buffer), ArchFlagName,
false);
602 Binaries.
emplace_back(std::move(*BinaryOrErr), std::move(MB));
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseSet and SmallDenseSet classes.
std::function< bool(const SectionBase &Sec)> SectionPred
static cl::opt< int > PageSize("imp-null-check-page-size", cl::desc("The page size of the target in bytes"), cl::init(4096), cl::Hidden)
static Error processLoadCommands(const MachOConfig &MachOConfig, Object &Obj)
static Expected< Section & > findSection(StringRef SecName, Object &O)
static Error isValidMachOCannonicalName(StringRef Name)
static void updateLoadCommandPayloadString(LoadCommand &LC, StringRef S)
static LoadCommand buildRPathLoadCommand(StringRef Path)
static bool isLoadCommandWithPayloadString(const LoadCommand &LC)
static void markSymbols(const CommonConfig &Config, Object &Obj)
static Error handleArgs(const CommonConfig &Config, const MachOConfig &MachOConfig, Object &Obj)
static Error removeSections(const CommonConfig &Config, Object &Obj)
std::function< bool(const LoadCommand &LC)> LoadCommandPred
static Error dumpSectionToFile(StringRef SecName, StringRef Filename, StringRef InputFilename, Object &Obj)
static Error addSection(const NewSectionInfo &NewSection, Object &Obj)
static StringRef getPayloadString(const LoadCommand &LC)
static void updateAndRemoveSymbols(const CommonConfig &Config, const MachOConfig &MachOConfig, Object &Obj)
static Error updateSection(const NewSectionInfo &NewSection, Object &O)
static cl::opt< std::string > InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"))
static constexpr StringLiteral Filename
Implements a dense probed hash-table based set.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
static LLVM_ABI Expected< std::unique_ptr< FileOutputBuffer > > create(StringRef FilePath, size_t Size, unsigned Flags=0)
Factory method to create an OutputBuffer object which manages a read/write buffer of the specified si...
reference emplace_back(ArgTypes &&... Args)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
std::string str() const
Get the contents as an std::string.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
StringRef rtrim(char Char) const
Return string with consecutive Char characters starting from the right removed.
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
bool erase(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
bool matches(StringRef S) const
virtual Expected< std::unique_ptr< Object > > create() const =0
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an SmallVector or SmallString.
LLVM_ABI Error executeObjcopyOnBinary(const CommonConfig &Config, const MachOConfig &MachOConfig, object::MachOObjectFile &In, raw_ostream &Out)
Apply the transformations described by Config and MachOConfig to In and writes the result into Out.
LLVM_ABI Error executeObjcopyOnMachOUniversalBinary(const MultiFormatConfig &Config, const object::MachOUniversalBinary &In, raw_ostream &Out)
Apply the transformations described by Config and MachOConfig to In and writes the result into Out.
Expected< std::vector< NewArchiveMember > > createNewArchiveMembers(const MultiFormatConfig &Config, const object::Archive &Ar)
Applies the transformations described by Config to each member in archive Ar.
LLVM_ABI Error writeUniversalBinaryToStream(ArrayRef< Slice > Slices, raw_ostream &Out, FatHeaderType FatHeader=FatHeaderType::FatHeader)
LLVM_ABI Expected< std::unique_ptr< Binary > > createBinary(MemoryBufferRef Source, LLVMContext *Context=nullptr, bool InitContent=true)
Create a Binary from Source, autodetecting the file type.
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Expected< std::unique_ptr< MemoryBuffer > > writeArchiveToBuffer(ArrayRef< NewArchiveMember > NewMembers, SymtabWritingMode WriteSymtab, object::Archive::Kind Kind, bool Deterministic, bool Thin, function_ref< void(Error)> Warn=warnToStderr)
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
constexpr T alignToPowerOf2(U Value, V Align)
Will overflow only if result is not representable in T.
OutputIt copy(R &&Range, OutputIt Out)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
void consumeError(Error Err)
Consume a Error without doing anything.
SmallVector< NewSectionInfo, 0 > UpdateSection
NameMatcher SymbolsToGlobalize
SmallVector< StringRef, 0 > DumpSection
NameMatcher SymbolsToWeaken
NameMatcher SymbolsToKeepGlobal
bool DeterministicArchives
NameMatcher SymbolsToSkip
SmallVector< NewSectionInfo, 0 > AddSection
StringMap< StringRef > SymbolsToRename
NameMatcher SymbolsToLocalize
std::vector< StringRef > RPathToPrepend
DenseMap< StringRef, StringRef > InstallNamesToUpdate
std::optional< StringRef > SharedLibId
DenseSet< StringRef > EmptySegmentsToRemove
DenseSet< StringRef > RPathsToRemove
DenseMap< StringRef, StringRef > RPathsToUpdate
std::vector< StringRef > RPathToAdd
std::shared_ptr< MemoryBuffer > SectionData
std::optional< SymbolEntry * > Symbol
The Symbol referenced by this entry.
MachO::macho_load_command MachOLoadCommand
std::optional< StringRef > getSegmentName() const
std::vector< std::unique_ptr< Section > > Sections
std::optional< uint64_t > getSegmentVMAddr() const
std::vector< uint8_t > Payload
bool isExternalSymbol() const
bool isUndefinedSymbol() const