Ghidra is a software reverse engineering (SRE) framework
GP-3753: 'Add To Program' workflow for dyld_shared_cache components
Ryan Kurtzd81a42df6d3c
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedFixups.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedFixups.javaindex 12ce63c7bf..b85fba455d 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedFixups.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedFixups.java@@ -273,7 +273,7 @@ public class DyldChainedFixups {symName = chainedImport.getName();// lookup the symbol, and then add addendList<Symbol> globalSymbols = program.getSymbolTable().getGlobalSymbols(symName);- if (globalSymbols.size() == 1) {+ if (globalSymbols.size() > 0) {Symbol symbol = globalSymbols.get(0);newChainValue = symbol.getAddress().getOffset();fixupExternalLibrary(chainedImport.getLibOrdinal(), symbol);@@ -293,7 +293,7 @@ public class DyldChainedFixups {// lookup the symbol, and then add addendList<Symbol> globalSymbols = program.getSymbolTable().getGlobalSymbols(symName);- if (globalSymbols.size() == 1) {+ if (globalSymbols.size() > 0) {Symbol symbol = globalSymbols.get(0);newChainValue = symbol.getAddress().getOffset();fixupExternalLibrary(chainedImport.getLibOrdinal(), symbol);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoLoader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoLoader.javaindex 57d7e86d26..bb6b95dec7 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoLoader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoLoader.java@@ -60,7 +60,7 @@ public class MachoLoader extends AbstractLibrarySupportLoader {MachHeader machHeader = new MachHeader(provider);String magic =CpuTypes.getMagicString(machHeader.getCpuType(), machHeader.getCpuSubType());- List<QueryResult> results = QueryOpinionService.query(getName(), magic, null);+ List<QueryResult> results = QueryOpinionService.query(MACH_O_NAME, magic, null);for (QueryResult result : results) {loadSpecs.add(new LoadSpec(this, machHeader.getImageBase(), result));}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoProgramBuilder.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoProgramBuilder.javaindex 94a6278820..ccebcf8d93 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoProgramBuilder.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoProgramBuilder.java@@ -118,7 +118,6 @@ public class MachoProgramBuilder {// Setup memorysetImageBase();processMemoryBlocks(machoHeader, provider.getName(), true, true);- fixupProgramTree();// Process load commandsprocessEntryPoint();@@ -139,7 +138,7 @@ public class MachoProgramBuilder {// Markup structuresmarkupHeaders(machoHeader, setupHeaderAddr(machoHeader.getAllSegments()));markupSections();- markupLoadCommandData(machoHeader, null);+ markupLoadCommandData(machoHeader, provider.getName());markupChainedFixups(machoHeader, chainedFixups);markupProgramVars();@@ -149,6 +148,7 @@ public class MachoProgramBuilder {// Perform additional actionsrenameObjMsgSendRtpSymbol();+ fixupProgramTree(null); // should be done last to account for new memory blocks}/**@@ -337,9 +337,14 @@ public class MachoProgramBuilder {/*** Fixes up the Program Tree to better visualize the memory blocks that were split into sections*+ * @param suffix An optional suffix that will get appended to tree segment and segment nodes* @throws Exception if there was a problem fixing up the Program Tree*/- protected void fixupProgramTree() throws Exception {+ protected void fixupProgramTree(String suffix)+ throws Exception {+ if (suffix == null) {+ suffix = "";+ }ProgramModule rootModule = listing.getDefaultRootModule();ListIterator<SegmentCommand> it = machoHeader.getAllSegments().listIterator();while (it.hasNext()) {@@ -364,7 +369,7 @@ public class MachoProgramBuilder {if (segmentName.isBlank()) {segmentName = "SEGMENT." + i;}- String noSectionsName = segmentName + " <no section>";+ String noSectionsName = segmentName + " <no section>" + suffix;ProgramFragment segmentFragment = null;for (Group group : rootModule.getChildren()) {if (group instanceof ProgramFragment fragment &&@@ -378,7 +383,7 @@ public class MachoProgramBuilder {log.appendMsg("Could not find/fixup segment in Program Tree: " + segmentName);continue;}- ProgramModule segmentModule = rootModule.createModule(segmentName);+ ProgramModule segmentModule = rootModule.createModule(segmentName + suffix);try {segmentModule.reparent(noSectionsName, rootModule);}@@ -397,8 +402,9 @@ public class MachoProgramBuilder {if (!memory.contains(sectionEnd)) {sectionEnd = memory.getBlock(sectionStart).getEnd();}- ProgramFragment sectionFragment = segmentModule.createFragment(- String.format("%s %s", section.getSegmentName(), section.getSectionName()));+ ProgramFragment sectionFragment =+ segmentModule.createFragment(String.format("%s %s", section.getSegmentName(),+ section.getSectionName() + suffix));sectionFragment.move(sectionStart, sectionEnd);}@@ -407,6 +413,15 @@ public class MachoProgramBuilder {segmentModule.removeChild(segmentFragment.getName());}}++ // Update EXTERNAL block if it exists+ for (Group group : rootModule.getChildren()) {+ if (group instanceof ProgramFragment fragment &&+ fragment.getName().equals(MemoryBlock.EXTERNAL_BLOCK_NAME)) {+ fragment.setName(MemoryBlock.EXTERNAL_BLOCK_NAME + suffix);+ break;+ }+ }}/**@@ -483,9 +498,7 @@ public class MachoProgramBuilder {for (ExportEntry export : exports) {String name = SymbolUtilities.replaceInvalidChars(export.name(), true);try {- Address exportAddr = baseAddr.add(export.address());- program.getSymbolTable().addExternalEntryPoint(exportAddr);- program.getSymbolTable().createLabel(exportAddr, name, SourceType.IMPORTED);+ processNewExport(baseAddr, export, name);}catch (AddressOutOfBoundsException e) {log.appendMsg("Failed to process export '" + export + "': " + e.getMessage());@@ -498,6 +511,13 @@ public class MachoProgramBuilder {return !exports.isEmpty();}+ protected void processNewExport(Address baseAddr, ExportEntry export, String name)+ throws AddressOutOfBoundsException, Exception {+ Address exportAddr = baseAddr.add(export.address());+ program.getSymbolTable().addExternalEntryPoint(exportAddr);+ program.getSymbolTable().createLabel(exportAddr, name, SourceType.IMPORTED);+ }+protected void processSymbolTables(MachHeader header, boolean processExports) throws Exception {monitor.setMessage("Processing symbol tables...");SymbolTable symbolTable = program.getSymbolTable();@@ -683,6 +703,8 @@ public class MachoProgramBuilder {String name = SymbolUtilities.replaceInvalidChars(symbol.getString(), true);if (name != null && name.length() > 0) {program.getSymbolTable().createLabel(start, name, SourceType.IMPORTED);+ program.getExternalManager()+ .addExtLocation(Library.UNKNOWN, name, start, SourceType.IMPORTED);}}catch (Exception e) {@@ -1343,7 +1365,15 @@ public class MachoProgramBuilder {}private Address getAddress() {- Address maxAddress = program.getMaxAddress();+ Address maxAddress = null;+ for (MemoryBlock block : program.getMemory().getBlocks()) {+ if (block.isOverlay()) {+ continue;+ }+ if (maxAddress == null || block.getEnd().compareTo(maxAddress) > 0) {+ maxAddress = block.getEnd();+ }+ }if (maxAddress == null) {return space.getAddress(0x1000);}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/app/util/opinion/DyldCacheExtractLoader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/app/util/opinion/DyldCacheExtractLoader.javanew file mode 100644index 0000000000..38bc9aba26--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/app/util/opinion/DyldCacheExtractLoader.java@@ -0,0 +1,115 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.app.util.opinion;++import java.io.IOException;+import java.util.*;++import ghidra.app.util.MemoryBlockUtils;+import ghidra.app.util.Option;+import ghidra.app.util.bin.ByteProvider;+import ghidra.app.util.importer.MessageLog;+import ghidra.file.formats.ios.dyldcache.DyldCacheExtractor;+import ghidra.framework.model.DomainObject;+import ghidra.framework.model.Project;+import ghidra.program.database.mem.FileBytes;+import ghidra.program.model.listing.Program;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * A {@link Loader} for components extracted by Ghidra from a DYLD Cache+ */+public class DyldCacheExtractLoader extends MachoLoader {++ public final static String DYLD_CACHE_EXTRACT_NAME = "Extracted DYLD Component";++ @Override+ public Collection<LoadSpec> findSupportedLoadSpecs(ByteProvider provider) throws IOException {+ if (provider.length() >= DyldCacheExtractor.FOOTER_V1.length) {+ if (Arrays.equals(DyldCacheExtractor.FOOTER_V1,+ provider.readBytes(provider.length() - DyldCacheExtractor.FOOTER_V1.length,+ DyldCacheExtractor.FOOTER_V1.length))) {+ return super.findSupportedLoadSpecs(provider);+ }+ }+ return List.of();+ }++ @Override+ public void load(ByteProvider provider, LoadSpec loadSpec, List<Option> options,+ Program program, TaskMonitor monitor, MessageLog log) throws IOException {++ try {+ FileBytes fileBytes = MemoryBlockUtils.createFileBytes(program, provider, monitor);+ DyldCacheExtractProgramBuilder.buildProgram(program, provider, fileBytes, log, monitor);+ }+ catch (CancelledException e) {+ return;+ }+ catch (IOException e) {+ throw e;+ }+ catch (Exception e) {+ throw new IOException(e);+ }+ }++ @Override+ protected void loadProgramInto(ByteProvider provider, LoadSpec loadSpec,+ List<Option> options, MessageLog messageLog, Program program, TaskMonitor monitor)+ throws IOException, LoadException, CancelledException {+ load(provider, loadSpec, options, program, monitor, messageLog);+ }++ @Override+ public boolean supportsLoadIntoProgram(Program program) {+ return DYLD_CACHE_EXTRACT_NAME.equals(program.getExecutableFormat());+ }++ @Override+ public String getName() {+ return DYLD_CACHE_EXTRACT_NAME;+ }++ @Override+ public int getTierPriority() {+ return 49; // Higher priority than MachoLoader+ }++ @Override+ public List<Option> getDefaultOptions(ByteProvider provider, LoadSpec loadSpec,+ DomainObject domainObject, boolean loadIntoProgram) {+ return List.of();+ }++ @Override+ protected boolean isLoadLocalLibraries(List<Option> options) {+ return false;+ }++ @Override+ protected boolean isLoadSystemLibraries(List<Option> options) {+ return false;+ }++ @Override+ protected void postLoadProgramFixups(List<Loaded<Program>> loadedPrograms, Project project,+ List<Option> options, MessageLog messageLog, TaskMonitor monitor)+ throws CancelledException, IOException {+ // Do nothing+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/app/util/opinion/DyldCacheExtractProgramBuilder.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/app/util/opinion/DyldCacheExtractProgramBuilder.javanew file mode 100644index 0000000000..aa0d09534d--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/app/util/opinion/DyldCacheExtractProgramBuilder.java@@ -0,0 +1,125 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.app.util.opinion;++import ghidra.app.util.bin.ByteProvider;+import ghidra.app.util.bin.format.macho.commands.ExportTrie.ExportEntry;+import ghidra.app.util.importer.MessageLog;+import ghidra.program.database.mem.FileBytes;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressOutOfBoundsException;+import ghidra.program.model.listing.*;+import ghidra.program.model.symbol.*;+import ghidra.util.task.TaskMonitor;++/**+ * Builds up a {@link Program} of components extracted from a DYLD Cache by parsing the Mach-O+ * headers+ */+public class DyldCacheExtractProgramBuilder extends MachoProgramBuilder {++ /**+ * Creates a new {@link DyldCacheExtractProgramBuilder} based on the given information.+ *+ * @param program The {@link Program} to build up.+ * @param provider The {@link ByteProvider} that contains the Mach-O's bytes.+ * @param fileBytes Where the Mach-O's bytes came from.+ * @param log The log.+ * @param monitor A cancelable task monitor.+ * @throws Exception if a problem occurs.+ */+ protected DyldCacheExtractProgramBuilder(Program program, ByteProvider provider,+ FileBytes fileBytes, MessageLog log, TaskMonitor monitor) throws Exception {+ super(program, provider, fileBytes, log, monitor);+ }++ /**+ * Builds up a {@link Program} of components extracted from a DYLD Cache+ *+ * @param program The {@link Program} to build up.+ * @param provider The {@link ByteProvider} that contains the Mach-O's bytes.+ * @param fileBytes Where the Mach-O's bytes came from.+ * @param log The log.+ * @param monitor A cancelable task monitor.+ * @throws Exception if a problem occurs.+ */+ public static void buildProgram(Program program, ByteProvider provider, FileBytes fileBytes,+ MessageLog log, TaskMonitor monitor) throws Exception {+ DyldCacheExtractProgramBuilder programBuilder = new DyldCacheExtractProgramBuilder(program,+ provider, fileBytes, log, monitor);+ programBuilder.build();+ }++ @Override+ protected void setImageBase() throws Exception {+ program.setImageBase(space.getAddress(0), true);+ }++ @Override+ protected void fixupProgramTree(String suffix) throws Exception {+ super.fixupProgramTree(" - " + provider.getAbsolutePath());++ // Our program tree must account for Add To Program's happening, so we want to put each+ // added program into its own subfolder. We tag these subfolders with ".extract" so we+ // can keep all of these program subfolders at the top-level of the tree.+ ProgramModule rootModule = listing.getDefaultRootModule();+ String tag = ".extract";+ String newName = provider.getAbsolutePath() + tag;+ ProgramModule newRootModule = rootModule.createModule(newName);+ for (Group group : rootModule.getChildren()) {+ if (!group.getName().endsWith(tag)) {+ newRootModule.reparent(group.getName(), rootModule);+ }+ }+ }++ @Override+ protected void processNewExport(Address baseAddr, ExportEntry export, String name)+ throws AddressOutOfBoundsException, Exception {+ SymbolTable symbolTable = program.getSymbolTable();+ FunctionManager funcManager = program.getFunctionManager();+ ExternalManager extManager = program.getExternalManager();++ // Add the new exported symbol like normal+ super.processNewExport(baseAddr, export, name);++ Address exportAddr = baseAddr.add(export.address());++ for (Symbol sym : symbolTable.getGlobalSymbols(name)) {++ // If it's a thunk function (stub), redirect its thunked function from the external+ // location to the newly exported function+ Function func = funcManager.getFunctionAt(sym.getAddress());+ if (func != null && func.getThunkedFunction(false) != null) {+ func.setThunkedFunction(createOneByteFunction(name, exportAddr));++ // Remove the external location associated with the thunk function.+ // After the first delete, the external location becomes an external label, which+ // must also get deleted.+ ExternalLocation loc = extManager.getUniqueExternalLocation(Library.UNKNOWN, name);+ if (loc != null) {+ if (loc.getSymbol().delete()) {+ loc = extManager.getUniqueExternalLocation(Library.UNKNOWN, name);+ if (loc != null) {+ loc.getSymbol().delete();+ }+ }+ }+ }++ }+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ios/dyldcache/DyldCacheFileSystem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ios/dyldcache/DyldCacheFileSystem.javaindex 1073668fac..0b38fcee9c 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ios/dyldcache/DyldCacheFileSystem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ios/dyldcache/DyldCacheFileSystem.java@@ -42,9 +42,11 @@ import ghidra.util.task.TaskMonitor;/*** A {@link GFileSystem} implementation for the components of a DYLD Cache*/-@FileSystemInfo(type = "dyldcachev1", description = "iOS DYLD Cache Version 1", factory = GFileSystemBaseFactory.class)+@FileSystemInfo(type = DyldCacheFileSystem.DYLD_CACHE_FSTYPE, description = "iOS DYLD Cache Version 1", factory = GFileSystemBaseFactory.class)public class DyldCacheFileSystem extends GFileSystemBase {+ public static final String DYLD_CACHE_FSTYPE = "dyldcachev1";+private SplitDyldCache splitDyldCache;private boolean parsedLocalSymbols = false;private Map<DyldCacheSlideInfoCommon, List<DyldCacheSlideFixup>> slideFixupMap;diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/macosx/plugins/DyldCacheBuilderPlugin.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/macosx/plugins/DyldCacheBuilderPlugin.javanew file mode 100644index 0000000000..6a00528af9--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/macosx/plugins/DyldCacheBuilderPlugin.java@@ -0,0 +1,242 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.macosx.plugins;++import java.io.IOException;+import java.util.List;++import docking.action.builder.ActionBuilder;+import ghidra.app.CorePluginPackage;+import ghidra.app.context.ProgramLocationActionContext;+import ghidra.app.plugin.PluginCategoryNames;+import ghidra.app.util.bin.ByteProvider;+import ghidra.app.util.bin.format.macho.MachException;+import ghidra.app.util.bin.format.macho.MachHeader;+import ghidra.app.util.bin.format.macho.commands.SegmentCommand;+import ghidra.app.util.bin.format.macho.dyld.*;+import ghidra.app.util.opinion.DyldCacheExtractLoader;+import ghidra.app.util.opinion.DyldCacheUtils.SplitDyldCache;+import ghidra.file.formats.ios.dyldcache.DyldCacheFileSystem;+import ghidra.formats.gfilesystem.*;+import ghidra.framework.options.Options;+import ghidra.framework.plugintool.*;+import ghidra.framework.plugintool.util.PluginStatus;+import ghidra.plugin.importer.ImporterUtilities;+import ghidra.plugin.importer.ProgramMappingService;+import ghidra.program.model.address.Address;+import ghidra.program.model.listing.Program;+import ghidra.program.util.ProgramLocation;+import ghidra.util.HelpLocation;+import ghidra.util.Msg;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskLauncher;+import ghidra.util.task.TaskMonitor;++/**+ * A {@link Plugin} that adds an action to build up a DYLD Cache from extracted components+ */+//@formatter:off+@PluginInfo(+ status = PluginStatus.RELEASED,+ packageName = CorePluginPackage.NAME,+ category = PluginCategoryNames.COMMON,+ shortDescription = "DYLD Cache Builder",+ description = "This plugin provides actions for adding DYLD Cache components to the program"+)+//@formatter:on+public class DyldCacheBuilderPlugin extends Plugin {++ /**+ * Creates a new {@link DyldCacheBuilderPlugin}+ *+ * @param tool The {@link PluginTool} that will host/contain this {@link Plugin}+ */+ public DyldCacheBuilderPlugin(PluginTool tool) {+ super(tool);+ }++ @Override+ protected void init() {+ super.init();++ String actionName = "Add To Program";+ new ActionBuilder(actionName, getName())+ .withContext(ProgramLocationActionContext.class)+ .enabledWhen(p -> p.getProgram()+ .getExecutableFormat()+ .equals(DyldCacheExtractLoader.DYLD_CACHE_EXTRACT_NAME))+ .onAction(plac -> TaskLauncher.launchModal(actionName,+ monitor -> addMissingDyldCacheComponent(plac.getLocation(), monitor)))+ .popupMenuPath("References", actionName)+ .popupMenuGroup("Add")+ .helpLocation(new HelpLocation("ImporterPlugin", "Add_To_Program"))+ .buildAndInstall(tool);+ }++ /**+ * Attempts to add the DYLD Cache component that resides at the given {@link ProgramLocation}'s+ * "referred to" address+ *+ * @param location The {@link ProgramLocation} where the action took place+ * @param monitor A {@link TaskMonitor}+ */+ private void addMissingDyldCacheComponent(ProgramLocation location, TaskMonitor monitor) {+ Program program = location.getProgram();+ Address refAddress = location.getRefAddress();+ if (refAddress == null) {+ Msg.showInfo(this, null, name, "No referenced address selected");+ return;+ }+ if (refAddress.getAddressSpace().isExternalSpace()) {+ Msg.showInfo(this, null, name, "External locations are not currently supported");+ return;+ }+ if (program.getMemory().contains(refAddress)) {+ Msg.showInfo(this, null, name, "Referenced address already exists in memory");+ return;+ }++ try (FileSystemRef fsRef = openDyldCache(program, monitor)) {+ DyldCacheFileSystem fs = (DyldCacheFileSystem) fsRef.getFilesystem();+ SplitDyldCache splitDyldCache = fs.getSplitDyldCache();+ long refAddr = refAddress.getOffset();+ String fsPath = findInDylibSegment(refAddr, splitDyldCache);+ if (fsPath == null) {+ fsPath = findInStubs(refAddr, splitDyldCache);+ }+ if (fsPath == null) {+ fsPath = findInDyldData(refAddr, splitDyldCache);+ }+ if (fsPath != null) {+ ImporterUtilities.showAddToProgramDialog(fs.getFSRL().appendPath(fsPath), program,+ tool, monitor);+ }+ else {+ Msg.showInfo(this, null, name,+ "Address %s not found in %s".formatted(refAddress, fs.toString()));+ }+ }+ catch (CancelledException e) {+ // Do nothing+ }+ catch (MachException | IOException e) {+ Msg.showError(this, null, name, e.getMessage(), e);+ }+ }++ /**+ * Attempts to open the given {@link Program}'s originating {@link DyldCacheFileSystem}+ *+ * @param program The {@link Program}+ * @param monitor A {@link TaskMonitor}+ * @return A {@link FileSystemRef file system reference} to the open {@link DyldCacheFileSystem}+ * @throws IOException if an FSRL or IO-related error occurred+ * @throws CancelledException if the user cancelled the operation+ */+ private FileSystemRef openDyldCache(Program program, TaskMonitor monitor)+ throws IOException, CancelledException {+ FileSystemService fsService = FileSystemService.getInstance();+ Options props = program.getOptions(Program.PROGRAM_INFO);+ String fsrlProp = props.getString(ProgramMappingService.PROGRAM_SOURCE_FSRL, null);+ if (fsrlProp == null) {+ throw new IOException("The program does not have an FSRL property");+ }+ FSRL fsrl = FSRL.fromString(fsrlProp);+ String requiredProtocol = DyldCacheFileSystem.DYLD_CACHE_FSTYPE;+ if (!fsrl.getFS().getProtocol().equals(requiredProtocol)) {+ throw new IOException("The program's FSRL protocol is '%s' but '%s' is required"+ .formatted(fsrl.getFS().getProtocol(), requiredProtocol));+ }+ FSRLRoot fsrlRoot = fsrl.getFS();+ return fsService.getFilesystem(fsrlRoot, monitor);+ }++ /**+ * Attempts to find the given address in the DYLD Cache's DYLIB segments+ *+ * @param addr The address to find+ * @param splitDyldCache The {@link SplitDyldCache}+ * @return The path of the DYLIB within the {@link DyldCacheFileSystem} that contains the given+ * address, or null if the address was not found+ * @throws MachException if there was an error parsing a DYLIB header+ * @throws IOException if an IO-related error occurred+ */+ private String findInDylibSegment(long addr, SplitDyldCache splitDyldCache)+ throws MachException, IOException {+ for (int i = 0; i < splitDyldCache.size(); i++) {+ DyldCacheHeader dyldCacheHeader = splitDyldCache.getDyldCacheHeader(i);+ ByteProvider provider = splitDyldCache.getProvider(i);+ for (DyldCacheImage mappedImage : dyldCacheHeader.getMappedImages()) {+ MachHeader machHeader = new MachHeader(provider,+ mappedImage.getAddress() - dyldCacheHeader.getBaseAddress());+ for (SegmentCommand segment : machHeader.parseSegments()) {+ if (segment.contains(addr)) {+ return mappedImage.getPath();+ }+ }+ }+ }+ return null;+ }++ /**+ * Attempts to find the given address in the DYLD Cache's text stubs+ *+ * @param addr The address to find+ * @param splitDyldCache The {@link SplitDyldCache}+ * @return The path of the text stub within the {@link DyldCacheFileSystem} that contains the+ * given address, or null if the address was not found+ */+ private String findInStubs(long addr, SplitDyldCache splitDyldCache) {+ for (int i = 0; i < splitDyldCache.size(); i++) {+ String dyldCacheName = splitDyldCache.getName(i);+ DyldCacheHeader dyldCacheHeader = splitDyldCache.getDyldCacheHeader(i);+ for (DyldCacheMappingAndSlideInfo mappingInfo : dyldCacheHeader+ .getCacheMappingAndSlideInfos()) {+ if (mappingInfo.contains(addr) && mappingInfo.isTextStubs()) {+ return DyldCacheFileSystem.getStubPath(dyldCacheName);+ }+ }+ }+ return null;+ }++ /**+ * Attempts to find the given address in the DYLD data+ *+ * @param addr The address to find+ * @param splitDyldCache The {@link SplitDyldCache}+ * @return The path of the Dyld data within the {@link DyldCacheFileSystem} that contains the+ * given address, or null if the address was not found+ */+ private String findInDyldData(long addr, SplitDyldCache splitDyldCache) {+ for (int i = 0; i < splitDyldCache.size(); i++) {+ String dyldCacheName = splitDyldCache.getName(i);+ if (dyldCacheName.endsWith(".dylddata")) {+ DyldCacheHeader dyldCacheHeader = splitDyldCache.getDyldCacheHeader(i);+ List<DyldCacheMappingAndSlideInfo> mappingInfos =+ dyldCacheHeader.getCacheMappingAndSlideInfos();+ for (int j = 0; j < mappingInfos.size(); j++) {+ DyldCacheMappingAndSlideInfo mappingInfo = mappingInfos.get(j);+ if (mappingInfo.contains(addr)) {+ return DyldCacheFileSystem.getDyldDataPath(dyldCacheName, j);+ }+ }+ }+ }+ return null;+ }+}