48 "unsupported load command encountered");
56 SectionPred RemovePred = [](
const std::unique_ptr<Section> &) {
60 if (!
Config.ToRemove.empty()) {
61 RemovePred = [&
Config, RemovePred](
const std::unique_ptr<Section> &Sec) {
62 return Config.ToRemove.matches(Sec->CanonicalName);
68 RemovePred = [RemovePred](
const std::unique_ptr<Section> &Sec) {
69 if (Sec->Segname ==
"__DWARF")
72 return RemovePred(Sec);
76 if (!
Config.OnlySection.empty()) {
78 RemovePred = [&
Config](
const std::unique_ptr<Section> &Sec) {
79 return !
Config.OnlySection.matches(Sec->CanonicalName);
90 (*ISE.
Symbol)->Referenced =
true;
98 bool IsExportedAndDefined =
101 if (IsExportedAndDefined &&
105 auto I =
Config.SymbolsToRename.find(
Sym.Name);
106 if (
I !=
Config.SymbolsToRename.end())
107 Sym.Name = std::string(
I->getValue());
111 &Obj](
const std::unique_ptr<SymbolEntry> &
N) {
136template <
typename LCType>
139 "unsupported load command encountered");
144 LC.
Payload.assign(NewCmdsize -
sizeof(LCType), 0);
151 RPathLC.
cmd = MachO::LC_RPATH;
156 std::copy(Path.begin(), Path.end(), LC.
Payload.begin());
167 if (LC.MachOLoadCommand.load_command_data.cmd == MachO::LC_RPATH) {
174 if (RPathsToRemove.
count(RPath)) {
175 RPathsToRemove.
erase(RPath);
188 if (RPathsToRemove.
count(RPath))
190 "no LC_RPATH load command with path: %s",
191 RPath.
str().c_str());
208 "no LC_RPATH load command with path: " + Old);
212 "' would create a duplicate load command");
218 case MachO::LC_ID_DYLIB:
220 updateLoadCommandPayloadString<MachO::dylib_command>(
224 case MachO::LC_RPATH: {
227 if (!NewRPath.
empty())
228 updateLoadCommandPayloadString<MachO::rpath_command>(LC, NewRPath);
234 case MachO::LC_LOAD_DYLIB:
235 case MachO::LC_LOAD_WEAK_DYLIB:
239 if (!NewInstallName.
empty())
240 updateLoadCommandPayloadString<MachO::dylib_command>(LC,
251 "' would create a duplicate load command");
260 "' would create a duplicate load command");
292 for (
const std::unique_ptr<Section> &Sec : LC.
Sections) {
293 if (Sec->CanonicalName == SecName) {
298 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
299 llvm::copy(Sec->Content, Buf->getBufferStart());
301 if (
Error E = Buf->commit())
308 SecName.
str().c_str());
314 Section Sec(TargetSegName, Pair.second);
322 if (SegName && SegName == TargetSegName) {
324 for (
const std::unique_ptr<Section> &S : LC.
Sections)
325 Addr = std::max(
Addr, S->Addr + S->Size);
326 LC.
Sections.push_back(std::make_unique<Section>(Sec));
336 NewSegment.
Sections.push_back(std::make_unique<Section>(Sec));
343 std::tie(SegName, SecName) = SecName.
split(
",");
346 return LC.getSegmentName() == SegName;
348 if (FoundSeg == O.LoadCommands.end())
350 "could not find segment with name '%s'",
351 SegName.
str().c_str());
353 [SecName](
const std::unique_ptr<Section> &Sec) {
354 return Sec->Sectname == SecName;
356 if (FoundSec == FoundSeg->Sections.end())
358 "could not find section with name '%s'",
359 SecName.
str().c_str());
361 assert(FoundSec->get()->CanonicalName == (SegName +
"," + SecName).str());
368 if (!SecToUpdateOrErr)
370 Section &Sec = *SecToUpdateOrErr;
374 errc::invalid_argument,
375 "new section cannot be larger than previous section");
385 if (
Name.count(
',') != 1)
387 "invalid section name '%s' (should be formatted "
388 "as '<segment name>,<section name>')",
391 std::pair<StringRef, StringRef> Pair =
Name.split(
',');
392 if (Pair.first.size() > 16)
394 "too long segment name: '%s'",
395 Pair.first.str().c_str());
396 if (Pair.second.size() > 16)
398 "too long section name: '%s'",
399 Pair.second.str().c_str());
425 for (std::unique_ptr<Section> &Sec : LC.
Sections)
426 Sec->Relocations.clear();
457 if (O->get()->Header.FileType == MachO::HeaderFileType::MH_PRELOAD)
459 "%s: MH_PRELOAD files are not supported",
460 Config.InputFilename.str().c_str());
468 switch (In.getArch()) {
469 case Triple::ArchType::arm:
470 case Triple::ArchType::aarch64:
471 case Triple::ArchType::aarch64_32:
478 MachOWriter Writer(**O, In.is64Bit(), In.isLittleEndian(),
482 return Writer.
write();
490 for (
const auto &O : In.objects()) {
495 if (!NewArchiveMembersOrErr)
496 return NewArchiveMembersOrErr.
takeError();
497 auto Kind = (*ArOrErr)->kind();
502 *NewArchiveMembersOrErr,
503 (*ArOrErr)->hasSymbolTable() ? SymtabWritingMode::NormalSymtab
504 : SymtabWritingMode::NoSymtab,
505 Kind,
Config.getCommonConfig().DeterministicArchives,
506 (*ArOrErr)->isThin());
507 if (!OutputBufferOrErr)
514 std::move(*OutputBufferOrErr));
516 O.getCPUType(), O.getCPUSubType(),
517 O.getArchFlagName(), O.getAlign());
530 std::errc::invalid_argument,
531 "slice for '%s' of the universal Mach-O binary "
532 "'%s' is not a Mach-O object or an archive",
533 O.getArchFlagName().c_str(),
534 Config.getCommonConfig().InputFilename.str().c_str());
536 std::string ArchFlagName = O.getArchFlagName();
546 **ObjOrErr, MemStream))
549 auto MB = std::make_unique<SmallVectorMemoryBuffer>(
550 std::move(Buffer), ArchFlagName,
false);
554 Binaries.
emplace_back(std::move(*BinaryOrErr), std::move(MB));
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 &, 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 addSection(const NewSectionInfo &NewSection, Object &Obj)
static Error dumpSectionToFile(StringRef SecName, StringRef Filename, 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)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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 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.
StringRef - 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
str - Get the contents as an std::string.
constexpr bool empty() const
empty - Check if the string is empty.
constexpr size_t size() const
size - Get the string size.
StringRef rtrim(char Char) const
Return string with consecutive Char characters starting from the right removed.
StringRef save(const char *S)
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.
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.
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.
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 Archive &Ar)
Applies the transformations described by Config to each member in archive Ar.
Error writeUniversalBinaryToStream(ArrayRef< Slice > Slices, raw_ostream &Out, FatHeaderType FatHeader=FatHeaderType::FatHeader)
Expected< std::unique_ptr< Binary > > createBinary(MemoryBufferRef Source, LLVMContext *Context=nullptr, bool InitContent=true)
Create a Binary from Source, autodetecting the file type.
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
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.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
OutputIt copy(R &&Range, OutputIt Out)
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.
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.
std::vector< IndirectSymbolEntry > Symbols
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
void updateLoadCommandIndexes()
StringSaver NewSectionsContents
Error removeLoadCommands(function_ref< bool(const LoadCommand &)> ToRemove)
Error removeSections(function_ref< bool(const std::unique_ptr< Section > &)> ToRemove)
std::vector< LoadCommand > LoadCommands
std::optional< uint32_t > SwiftVersion
IndirectSymbolTable IndirectSymTable
LoadCommand & addSegment(StringRef SegName, uint64_t SegVMSize)
Creates a new segment load command in the object and returns a reference to the newly created load co...
void removeSymbols(function_ref< bool(const std::unique_ptr< SymbolEntry > &)> ToRemove)