Ghidra is a software reverse engineering (SRE) framework
GP-3565: Mach-O markup improvements
Ryan Kurtz0069658d4884
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/MachoBinaryAnalysisCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/MachoBinaryAnalysisCommand.javaindex e325c3d947..1aa61ebae4 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/MachoBinaryAnalysisCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/MachoBinaryAnalysisCommand.java@@ -109,7 +109,8 @@ public class MachoBinaryAnalysisCommand extends FlatProgramAPIList<LoadCommand> commands = header.getLoadCommands();for (LoadCommand command : commands) {- command.markup(header, this, getAddress(program), true, module, monitor, messages);+ command.markupRawBinary(header, this, getAddress(program), module, monitor,+ messages);commandAddress = commandAddress.add(command.getCommandSize());if (command instanceof UnsupportedLoadCommand) {bookmarkManager.setBookmark(machAddress.add(command.getStartIndex()),diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/MachoFunctionStartsAnalyzer.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/MachoFunctionStartsAnalyzer.javaindex 187a01b478..0315b3a540 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/MachoFunctionStartsAnalyzer.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/MachoFunctionStartsAnalyzer.java@@ -172,7 +172,7 @@ public class MachoFunctionStartsAnalyzer extends AbstractAnalyzer {header.parse();monitor.setIndeterminate(true);monitor.setMessage("Analyzing function starts...");- analyzeFunctionStarts(program, header, provider, set, monitor);+ analyzeFunctionStarts(program, header, set, monitor);}/**@@ -225,8 +225,7 @@ public class MachoFunctionStartsAnalyzer extends AbstractAnalyzer {for (DyldCacheHeader header : providerMap.keySet()) {for (DyldCacheMappingInfo mappingInfo : header.getMappingInfos()) {if (mappingInfo.contains(linkEdit.getVMaddress())) {- analyzeFunctionStarts(program, machoHeader, providerMap.get(header),- set, monitor);+ analyzeFunctionStarts(program, machoHeader, set, monitor);foundLinkEdit = true;break;}@@ -249,13 +248,12 @@ public class MachoFunctionStartsAnalyzer extends AbstractAnalyzer {** @param program The {@link Program}* @param header The {@link MachHeader} that contains the LC_FUNCTION_STARTS load command- * @param provider The {@link ByteProvider} that contains the LC_FUNCTION_STARTS data* @param set The set of addresses to find new functions at* @param monitor A cancellable monitor* @throws CancelledException If the user cancelled*/- private void analyzeFunctionStarts(Program program, MachHeader header, ByteProvider provider,- AddressSetView set, TaskMonitor monitor) throws IOException, CancelledException {+ private void analyzeFunctionStarts(Program program, MachHeader header, AddressSetView set,+ TaskMonitor monitor) throws IOException, CancelledException {FunctionManager functionMgr = program.getFunctionManager();Listing listing = program.getListing();PseudoDisassembler pdis = new PseudoDisassembler(program);@@ -273,7 +271,7 @@ public class MachoFunctionStartsAnalyzer extends AbstractAnalyzer {Address textSegmentAddr = space.getAddress(textSegment.getVMaddress());List<FunctionStartsCommand> commands = header.getLoadCommands(FunctionStartsCommand.class);for (FunctionStartsCommand cmd : commands) {- for (Address addr : cmd.findFunctionStartAddrs(provider, textSegmentAddr)) {+ for (Address addr : cmd.findFunctionStartAddrs(textSegmentAddr)) {monitor.checkCancelled();if (!set.contains(textSegmentAddr)) {continue;diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/MachHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/MachHeader.javaindex b9dc1d2530..300122335a 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/MachHeader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/MachHeader.java@@ -28,7 +28,7 @@ import ghidra.util.exception.DuplicateNameException;/*** Represents a mach_header structure.*- * @see <a href="https://opensource.apple.com/source/xnu/xnu-7195.81.3/EXTERNAL_HEADERS/mach-o/loader.h.auto.html">mach-o/loader.h</a>+ * @see <a href="https://github.com/apple-oss-distributions/xnu/blob/main/EXTERNAL_HEADERS/mach-o/loader.h">EXTERNAL_HEADERS/mach-o/loader.h</a>*/public class MachHeader implements StructConverter {private int magic;diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/MachHeaderFlags.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/MachHeaderFlags.javaindex 048c1fa5d6..2ab8e7b13f 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/MachHeaderFlags.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/MachHeaderFlags.java@@ -22,7 +22,7 @@ import java.util.List;/*** Constants for the flags field of the mach_header*- * @see <a href="https://opensource.apple.com/source/xnu/xnu-7195.81.3/EXTERNAL_HEADERS/mach-o/loader.h.auto.html">mach-o/loader.h</a>+ * @see <a href="https://github.com/apple-oss-distributions/xnu/blob/main/EXTERNAL_HEADERS/mach-o/loader.h">EXTERNAL_HEADERS/mach-o/loader.h</a>*/public final class MachHeaderFlags {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/RelocationInfo.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/RelocationInfo.javaindex 9f1c890708..6df665bac3 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/RelocationInfo.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/RelocationInfo.java@@ -25,7 +25,7 @@ import ghidra.util.exception.DuplicateNameException;/*** Represents a relocation_info and scattered_relocation_info structure.*- * @see <a href="https://opensource.apple.com/source/xnu/xnu-7195.81.3/EXTERNAL_HEADERS/mach-o/reloc.h.auto.html">mach-o/reloc.h</a>+ * @see <a href="https://github.com/apple-oss-distributions/xnu/blob/main/EXTERNAL_HEADERS/mach-o/reloc.h">EXTERNAL_HEADERS/mach-o/reloc.h</a>*/public class RelocationInfo implements StructConverter {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/Section.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/Section.javaindex 52a30f5677..02d9e6a41d 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/Section.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/Section.java@@ -29,7 +29,7 @@ import ghidra.util.exception.DuplicateNameException;/*** Represents a section and section_64 structure.*- * @see <a href="https://opensource.apple.com/source/xnu/xnu-4570.71.2/EXTERNAL_HEADERS/mach-o/loader.h.auto.html">mach-o/loader.h</a>+ * @see <a href="https://github.com/apple-oss-distributions/xnu/blob/main/EXTERNAL_HEADERS/mach-o/loader.h">EXTERNAL_HEADERS/mach-o/loader.h</a>*/public class Section implements StructConverter {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/BuildVersionCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/BuildVersionCommand.javaindex 5383e4f445..d66e6d7fbd 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/BuildVersionCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/BuildVersionCommand.java@@ -20,14 +20,8 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;import ghidra.app.util.bin.format.macho.MachConstants;-import ghidra.app.util.bin.format.macho.MachHeader;-import ghidra.app.util.importer.MessageLog;-import ghidra.program.flatapi.FlatProgramAPI;-import ghidra.program.model.address.Address;import ghidra.program.model.data.*;-import ghidra.program.model.listing.ProgramModule;import ghidra.util.exception.DuplicateNameException;-import ghidra.util.task.TaskMonitor;/*** Represents a build_version_command structure@@ -76,23 +70,6 @@ public class BuildVersionCommand extends LoadCommand {return "build_version_command";}- @Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,- ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {-- updateMonitor(monitor);- try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address address = baseAddress.getNewAddress(getStartIndex());- api.createData(address, toDataType());- }- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName());- }- }-public int getPlatform() {return platform;}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DataInCodeCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DataInCodeCommand.javanew file mode 100644index 0000000000..d3f2cba273--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DataInCodeCommand.java@@ -0,0 +1,86 @@+/* ###+ * 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.bin.format.macho.commands;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.format.macho.MachHeader;+import ghidra.app.util.importer.MessageLog;+import ghidra.program.model.address.Address;+import ghidra.program.model.data.DataUtilities;+import ghidra.program.model.listing.Program;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * Represents a LC_DATA_IN_CODE command.+ */+public class DataInCodeCommand extends LinkEditDataCommand {++ private List<DataInCodeEntry> entries = new ArrayList<>();++ /**+ * Creates and parses a new {@link DataInCodeCommand}+ *+ * @param loadCommandReader A {@link BinaryReader reader} that points to the start of the load+ * command+ * @param dataReader A {@link BinaryReader reader} that can read the data that the load command+ * references. Note that this might be in a different underlying provider.+ * @throws IOException if an IO-related error occurs while parsing+ */+ DataInCodeCommand(BinaryReader loadCommandReader, BinaryReader dataReader)+ throws IOException {+ super(loadCommandReader, dataReader);++ for (int i = 0; i + DataInCodeEntry.SIZE <= datasize; i += DataInCodeEntry.SIZE) {+ entries.add(new DataInCodeEntry(dataReader));+ }+ }++ /**+ * Gets the {@link List} of {@link DataInCodeEntry}s+ *+ * @return The {@link List} of {@link DataInCodeEntry}s+ */+ public List<DataInCodeEntry> getEntries() {+ return entries;+ }++ @Override+ public void markup(Program program, MachHeader header, Address addr, TaskMonitor monitor,+ MessageLog log) throws CancelledException {+ if (addr == null || datasize == 0) {+ return;+ }++ super.markup(program, header, addr, monitor, log);++ try {+ for (DataInCodeEntry entry : entries) {+ DataUtilities.createData(program, addr, entry.toDataType(), -1,+ DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ addr = addr.add(DataInCodeEntry.SIZE);+ }+ }+ catch (Exception e) {+ log.appendMsg(DyldChainedFixupsCommand.class.getSimpleName(), "Failed to markup %s."+ .formatted(LoadCommandTypes.getLoadCommandName(getCommandType())));+ }+ }+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DataInCodeEntry.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DataInCodeEntry.javanew file mode 100644index 0000000000..f4688ab3a1--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DataInCodeEntry.java@@ -0,0 +1,91 @@+/* ###+ * 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.bin.format.macho.commands;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;+import ghidra.app.util.bin.format.macho.MachConstants;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * Represents a data_in_code_entry structure+ *+ * @see <a href="https://github.com/apple-oss-distributions/xnu/blob/main/EXTERNAL_HEADERS/mach-o/loader.h">EXTERNAL_HEADERS/mach-o/loader.h</a>+ */+public class DataInCodeEntry implements StructConverter {++ /**+ * The size (in bytes) of a {@link DataInCodeEntry} structure+ */+ public static final int SIZE = 8;++ private long offset;+ private int length;+ private short kind;++ /**+ * Creates a new {@link DataInCodeEntry}+ *+ * @param reader A {@link BinaryReader} positioned at the start of the structure+ * @throws IOException if there was an IO-related problem creating the structure+ */+ public DataInCodeEntry(BinaryReader reader) throws IOException {+ offset = reader.readNextUnsignedInt();+ length = reader.readNextUnsignedShort();+ kind = reader.readNextShort();+ }++ /**+ * Gets the offset+ *+ * @return The offset+ */+ public long getOffset() {+ return offset;+ }++ /**+ * Gets the length+ *+ * @return The length+ */+ public int getLength() {+ return length;+ }++ /**+ * Gets the kind+ *+ * @return The kind+ */+ public short getKind() {+ return kind;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ StructureDataType struct = new StructureDataType("data_in_code_entry", 0);+ struct.add(DWORD, "offset", "from mach_header to start of data range");+ struct.add(WORD, "length", "number of bytes in data range");+ struct.add(WORD, "kind",+ "DICE_KIND_DATA=1, DICE_KIND_JUMP_TABLE8=2, DICE_KIND_JUMP_TABLE16=3, DICE_KIND_JUMP_TABLE32=4, DICE_KIND_ABS_JUMP_TABLE32=5");+ struct.setCategoryPath(new CategoryPath(MachConstants.DATA_TYPE_CATEGORY));+ return struct;+ }+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedFixupHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedFixupHeader.javadeleted file mode 100644index 049c86e440..0000000000--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedFixupHeader.java+++ /dev/null@@ -1,119 +0,0 @@-/* ###- * 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.bin.format.macho.commands;--import java.io.IOException;--import ghidra.app.util.bin.BinaryReader;-import ghidra.app.util.bin.StructConverter;-import ghidra.app.util.bin.format.macho.MachConstants;-import ghidra.program.model.data.*;-import ghidra.util.exception.DuplicateNameException;--/**- * Represents a dyld_chained_fixups_header structure.- *- * @see <a href="https://opensource.apple.com/source/dyld/dyld-852.2/include/mach-o/fixup-chains.h.auto.html">mach-o/fixup-chains.h</a>- */-public class DyldChainedFixupHeader implements StructConverter {-- private int fixups_version; // 0- private int starts_offset; // offset of dyld_chained_starts_in_image in chain_data- private int imports_offset; // offset of imports table in chain_data- private int symbols_offset; // offset of symbol strings in chain_data- private int imports_count; // number of imported symbol names- private int imports_format; // DYLD_CHAINED_IMPORT*- private int symbols_format; // 0 => uncompressed, 1 => zlib compressed-- DyldChainedStartsInImage chainedStartsInImage;- DyldChainedImports chainedImports;-- DyldChainedFixupHeader(BinaryReader reader) throws IOException {- long ptrIndex = reader.getPointerIndex();-- fixups_version = reader.readNextInt();- starts_offset = reader.readNextInt();- imports_offset = reader.readNextInt();- symbols_offset = reader.readNextInt();- imports_count = reader.readNextInt();- imports_format = reader.readNextInt();- symbols_format = reader.readNextInt();-- reader.setPointerIndex(ptrIndex + starts_offset);- chainedStartsInImage = new DyldChainedStartsInImage(reader);-- reader.setPointerIndex(ptrIndex + imports_offset);- chainedImports = new DyldChainedImports(reader, this);-- reader.setPointerIndex(ptrIndex + symbols_offset);- chainedImports.initSymbols(reader, this);- }-- @Override- public DataType toDataType() throws DuplicateNameException, IOException {- StructureDataType struct = new StructureDataType("dyld_chained_fixups_header", 0);- struct.add(DWORD, "fixups_version", null);- struct.add(DWORD, "starts_offset", null);- struct.add(DWORD, "imports_offset", null);- struct.add(DWORD, "symbols_offset", null);- struct.add(DWORD, "imports_count", null);- struct.add(DWORD, "imports_format", null);- struct.add(DWORD, "symbols_format", null);-- struct.setCategoryPath(new CategoryPath(MachConstants.DATA_TYPE_CATEGORY));- return struct;- }-- public int getFixups_version() {- return fixups_version;- }-- public int getStarts_offset() {- return starts_offset;- }-- public int getImports_offset() {- return imports_offset;- }-- public int getSymbols_offset() {- return symbols_offset;- }-- public int getImports_count() {- return imports_count;- }-- public int getImports_format() {- return imports_format;- }-- public int getSymbols_format() {- return symbols_format;- }-- public boolean isCompress() {- return symbols_format != 0;- }-- public DyldChainedStartsInImage getChainedStartsInImage() {- return chainedStartsInImage;- }-- public DyldChainedImports getChainedImports() {- return chainedImports;- }-}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedFixupsCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedFixupsCommand.javaindex e93472395b..de0d106200 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedFixupsCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedFixupsCommand.java@@ -20,19 +20,23 @@ import java.util.List;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.macho.MachHeader;+import ghidra.app.util.bin.format.macho.commands.chained.*;import ghidra.app.util.importer.MessageLog;import ghidra.program.flatapi.FlatProgramAPI;import ghidra.program.model.address.Address;import ghidra.program.model.data.DataType;+import ghidra.program.model.data.DataUtilities;+import ghidra.program.model.listing.Program;import ghidra.program.model.listing.ProgramModule;import ghidra.program.model.util.CodeUnitInsertionException;+import ghidra.util.exception.CancelledException;import ghidra.util.exception.DuplicateNameException;import ghidra.util.task.TaskMonitor;/**- * Represents a dyld_chained_fixups_command structure+ * Represents a <code>dyld_chained_fixups_command</code> structure*- * @see <a href="https://opensource.apple.com/source/xnu/xnu-7195.81.3/EXTERNAL_HEADERS/mach-o/loader.h.auto.html">mach-o/loader.h</a>+ * @see <a href="https://github.com/apple-oss-distributions/dyld/blob/main/include/mach-o/fixup-chains.h">mach-o/fixup-chains.h</a>*/public class DyldChainedFixupsCommand extends LinkEditDataCommand {@@ -60,23 +64,62 @@ public class DyldChainedFixupsCommand extends LinkEditDataCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,- ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);+ public void markup(Program program, MachHeader header, Address addr, TaskMonitor monitor,+ MessageLog log) throws CancelledException {++ if (addr == null || datasize == 0) {+ return;+ }++ super.markup(program, header, addr, monitor, log);+try {- if (isBinary) {- super.markup(header, api, baseAddress, isBinary, parentModule, monitor, log);-- List<Address> addrs =- api.getCurrentProgram().getMemory().locateAddressesForFileOffset(- getDataOffset());- if (addrs.size() <= 0) {- throw new Exception("Chain Header does not exist in program");+ DataUtilities.createData(program, addr, chainHeader.toDataType(), -1,+ DataUtilities.ClearDataMode.CHECK_FOR_SPACE);++ Address segsAddr = addr.add(chainHeader.getStartsOffset());+ DyldChainedStartsInImage chainedStartsInImage = chainHeader.getChainedStartsInImage();+ DataUtilities.createData(program, segsAddr, chainedStartsInImage.toDataType(), -1,+ DataUtilities.ClearDataMode.CHECK_FOR_SPACE);++ int[] segInfoOffset = chainedStartsInImage.getSegInfoOffset();+ List<DyldChainedStartsInSegment> chainedStarts =+ chainedStartsInImage.getChainedStarts();+ int skipCount = 0;+ for (int i = 0; i < segInfoOffset.length; i++) {+ if (segInfoOffset[i] == 0) {+ // The chainStarts list doesn't have entries for 0 offsets, so we must keep+ // track of the index differences between the 2 entities+ skipCount++;+ continue;+ }+ DyldChainedStartsInSegment startsInSeg = chainedStarts.get(i - skipCount);+ if (startsInSeg != null) {+ DataUtilities.createData(program, segsAddr.add(segInfoOffset[i]),+ startsInSeg.toDataType(), -1, DataUtilities.ClearDataMode.CHECK_FOR_SPACE);}- Address dyldChainedHeader = addrs.get(0);+ }+ }+ catch (Exception e) {+ log.appendMsg(DyldChainedFixupsCommand.class.getSimpleName(), "Failed to markup %s."+ .formatted(LoadCommandTypes.getLoadCommandName(getCommandType())));+ }+ }++ @Override+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,+ ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {+ try {+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);- markupChainedFixupHeader(header, api, dyldChainedHeader, parentModule, monitor);+ List<Address> addrs =+ api.getCurrentProgram().getMemory().locateAddressesForFileOffset(getDataOffset());+ if (addrs.size() <= 0) {+ throw new Exception("Chain Header does not exist in program");}+ Address dyldChainedHeader = addrs.get(0);++ markupChainedFixupHeader(header, api, dyldChainedHeader, parentModule, monitor);}catch (Exception e) {log.appendMsg("Unable to create " + getCommandName());@@ -90,17 +133,17 @@ public class DyldChainedFixupsCommand extends LinkEditDataCommand {DataType cHeader = chainHeader.toDataType();api.createData(baseAddress, cHeader);- Address segsAddr = baseAddress.add(chainHeader.getStarts_offset());+ Address segsAddr = baseAddress.add(chainHeader.getStartsOffset());DyldChainedStartsInImage chainedStartsInImage = chainHeader.getChainedStartsInImage();- int[] seg_info_offset = chainedStartsInImage.getSeg_info_offset();+ int[] segInfoOffset = chainedStartsInImage.getSegInfoOffset();- DyldChainedStartsInSegment[] chainedStarts = chainedStartsInImage.getChainedStarts();- for (int i = 0; i < chainedStarts.length; i++) {- DyldChainedStartsInSegment startsInSeg = chainedStarts[i];+ List<DyldChainedStartsInSegment> chainedStarts = chainedStartsInImage.getChainedStarts();+ for (int i = 0; i < chainedStarts.size(); i++) {+ DyldChainedStartsInSegment startsInSeg = chainedStarts.get(i);DataType dataType = startsInSeg.toDataType();- api.createData(segsAddr.add(seg_info_offset[i]), dataType);+ api.createData(segsAddr.add(segInfoOffset[i]), dataType);}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedStartsInSegment.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedStartsInSegment.javadeleted file mode 100644index f907b4371a..0000000000--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedStartsInSegment.java+++ /dev/null@@ -1,99 +0,0 @@-/* ###- * 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.bin.format.macho.commands;--import java.io.IOException;--import ghidra.app.util.bin.BinaryReader;-import ghidra.app.util.bin.StructConverter;-import ghidra.app.util.bin.format.macho.MachConstants;-import ghidra.program.model.data.*;-import ghidra.util.exception.DuplicateNameException;--/**- * Represents a dyld_chained_starts_in_segment structure.- *- * @see <a href="https://opensource.apple.com/source/dyld/dyld-852.2/include/mach-o/fixup-chains.h.auto.html">mach-o/fixup-chains.h</a>- */-public class DyldChainedStartsInSegment implements StructConverter {-- private int size; // size of this (amount kernel needs to copy)- private short page_size; // 0x1000 or 0x4000- private short pointer_format; // DYLD_CHAINED_PTR_*- private long segment_offset; // offset in memory to start of segment- private int max_valid_pointer; // for 32-bit OS, any value beyond this is not a pointer- private short page_count; // how many pages are in array- private short page_starts[]; // each entry is offset in each page of first element in chain- private short chain_starts[]; // TODO: used for some 32-bit formats with multiple starts per page-- DyldChainedStartsInSegment(BinaryReader reader) throws IOException {- size = reader.readNextInt();- page_size = reader.readNextShort();- pointer_format = reader.readNextShort();- segment_offset = reader.readNextLong();- max_valid_pointer = reader.readNextInt();- page_count = reader.readNextShort();-- page_starts = reader.readNextShortArray(page_count);- }-- @Override- public DataType toDataType() throws DuplicateNameException, IOException {- StructureDataType struct = new StructureDataType("dyld_chained_starts_in_segment", 0);- struct.add(DWORD, "size", null);- struct.add(WORD, "page_size", null);- struct.add(WORD, "pointer_format", null);- struct.add(QWORD, "segment_offset", null);- struct.add(DWORD, "max_valid_pointer", null);- struct.add(WORD, "page_count", null);- struct.add(new ArrayDataType(WORD, page_count, 1), "page_starts", "");-- struct.setCategoryPath(new CategoryPath(MachConstants.DATA_TYPE_CATEGORY));- return struct;- }-- public int getSize() {- return size;- }-- public short getPageSize() {- return page_size;- }-- public short getPointerFormat() {- return pointer_format;- }-- public long getSegmentOffset() {- return segment_offset;- }-- public int getMaxValidPointer() {- return max_valid_pointer;- }-- public short getPageCount() {- return page_count;- }-- public short[] getPage_starts() {- return page_starts;- }-- public short[] getChain_starts() {- return chain_starts;- }-}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldExportsTrieCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldExportsTrieCommand.javaindex b50866bfff..2ac95cdb13 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldExportsTrieCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldExportsTrieCommand.java@@ -20,9 +20,7 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;/**- * Represents a LC_DYLD_EXPORTS_TRIE command- *- * @see <a href="https://opensource.apple.com/source/xnu/xnu-7195.81.3/EXTERNAL_HEADERS/mach-o/loader.h.auto.html">mach-o/loader.h</a>+ * Represents a LC_DYLD_EXPORTS_TRIE command*/public class DyldExportsTrieCommand extends LinkEditDataCommand {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldInfoCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldInfoCommand.javaindex ade7dcc582..319623fff0 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldInfoCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldInfoCommand.java@@ -85,39 +85,34 @@ public class DyldInfoCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address address = baseAddress.getNewAddress(getStartIndex());- api.createData(address, toDataType());-- if (rebase_size > 0) {- Address start = baseAddress.getNewAddress(rebase_off);- api.createFragment(parentModule, getCommandName() + "_REBASE", start,- rebase_size);- }- if (bind_size > 0) {- Address start = baseAddress.getNewAddress(bind_off);- api.createFragment(parentModule, getCommandName() + "_BIND", start, bind_size);- }- if (weak_bind_size > 0) {- Address start = baseAddress.getNewAddress(weak_bind_off);- api.createFragment(parentModule, getCommandName() + "_WEAK_BIND", start,- weak_bind_size);- }- if (lazy_bind_size > 0) {- Address start = baseAddress.getNewAddress(lazy_bind_off);- api.createFragment(parentModule, getCommandName() + "_LAZY_BIND", start,- lazy_bind_size);- }- if (export_size > 0) {- Address start = baseAddress.getNewAddress(export_off);- api.createFragment(parentModule, getCommandName() + "_EXPORT", start,- export_size);- }+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);++ if (rebase_size > 0) {+ Address start = baseAddress.getNewAddress(rebase_off);+ api.createFragment(parentModule, getCommandName() + "_REBASE", start,+ rebase_size);+ }+ if (bind_size > 0) {+ Address start = baseAddress.getNewAddress(bind_off);+ api.createFragment(parentModule, getCommandName() + "_BIND", start, bind_size);+ }+ if (weak_bind_size > 0) {+ Address start = baseAddress.getNewAddress(weak_bind_off);+ api.createFragment(parentModule, getCommandName() + "_WEAK_BIND", start,+ weak_bind_size);+ }+ if (lazy_bind_size > 0) {+ Address start = baseAddress.getNewAddress(lazy_bind_off);+ api.createFragment(parentModule, getCommandName() + "_LAZY_BIND", start,+ lazy_bind_size);+ }+ if (export_size > 0) {+ Address start = baseAddress.getNewAddress(export_off);+ api.createFragment(parentModule, getCommandName() + "_EXPORT", start,+ export_size);}}catch (Exception e) {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DynamicLibraryCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DynamicLibraryCommand.javaindex d084dc58d5..dc5bb7cd02 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DynamicLibraryCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DynamicLibraryCommand.java@@ -63,19 +63,16 @@ public class DynamicLibraryCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address address = baseAddress.getNewAddress(getStartIndex());- api.createData(address, toDataType());- LoadCommandString name = dylib.getName();- int length = getCommandSize() - name.getOffset();- Address strAddr = address.add(name.getOffset());- api.createAsciiString(strAddr, length);- }+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);++ Address address = baseAddress.getNewAddress(getStartIndex());+ LoadCommandString name = dylib.getName();+ int length = getCommandSize() - name.getOffset();+ Address strAddr = address.add(name.getOffset());+ api.createAsciiString(strAddr, length);}catch (Exception e) {log.appendMsg("Unable to create " + getCommandName());diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DynamicLinkerCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DynamicLinkerCommand.javaindex 31caddc390..25631f5593 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DynamicLinkerCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DynamicLinkerCommand.java@@ -59,17 +59,14 @@ public class DynamicLinkerCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address address = baseAddress.getNewAddress(getStartIndex());- api.createData(address, toDataType());- int length = getCommandSize() - name.getOffset();- api.createAsciiString(address.add(name.getOffset()), length);- }+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);++ Address address = baseAddress.getNewAddress(getStartIndex());+ int length = getCommandSize() - name.getOffset();+ api.createAsciiString(address.add(name.getOffset()), length);}catch (Exception e) {log.appendMsg("Unable to create " + getCommandName());diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DynamicSymbolTableCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DynamicSymbolTableCommand.javaindex ba95f0f0fc..a77f1dfeec 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DynamicSymbolTableCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DynamicSymbolTableCommand.java@@ -336,22 +336,17 @@ public class DynamicSymbolTableCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address address = baseAddress.getNewAddress(getStartIndex());- api.createData(address, toDataType());-- markupTOC(header, api, baseAddress, parentModule, monitor);- markupModules(header, api, baseAddress, parentModule, monitor);- markupReferencedSymbolTable(header, api, baseAddress, parentModule, monitor);- makupIndirectSymbolTable(header, api, baseAddress, parentModule, monitor);- markupExternalRelocations(api, baseAddress, parentModule, monitor);- markupLocalRelocations(api, baseAddress, parentModule, monitor);- }+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);++ markupTOC(header, api, baseAddress, parentModule, monitor);+ markupModules(header, api, baseAddress, parentModule, monitor);+ markupReferencedSymbolTable(header, api, baseAddress, parentModule, monitor);+ makupIndirectSymbolTable(header, api, baseAddress, parentModule, monitor);+ markupExternalRelocations(api, baseAddress, parentModule, monitor);+ markupLocalRelocations(api, baseAddress, parentModule, monitor);}catch (Exception e) {log.appendMsg("Unable to create " + getCommandName());diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/EncryptedInformationCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/EncryptedInformationCommand.javaindex ed0c72481f..c0cc6b11a0 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/EncryptedInformationCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/EncryptedInformationCommand.java@@ -19,14 +19,8 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.macho.MachConstants;-import ghidra.app.util.bin.format.macho.MachHeader;-import ghidra.app.util.importer.MessageLog;-import ghidra.program.flatapi.FlatProgramAPI;-import ghidra.program.model.address.Address;import ghidra.program.model.data.*;-import ghidra.program.model.listing.ProgramModule;import ghidra.util.exception.DuplicateNameException;-import ghidra.util.task.TaskMonitor;/*** Represents an encryption_info_command structure@@ -64,22 +58,6 @@ public class EncryptedInformationCommand extends LoadCommand {return "encryption_info_command";}- @Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,- ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);- try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address address = baseAddress.getNewAddress(getStartIndex());- api.createData(address, toDataType());- }- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName());- }- }-@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {StructureDataType struct = new StructureDataType(getCommandName(), 0);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/EntryPointCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/EntryPointCommand.javaindex 6e1f81f3e8..ecb9bb382a 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/EntryPointCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/EntryPointCommand.java@@ -19,14 +19,8 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.macho.MachConstants;-import ghidra.app.util.bin.format.macho.MachHeader;-import ghidra.app.util.importer.MessageLog;-import ghidra.program.flatapi.FlatProgramAPI;-import ghidra.program.model.address.Address;import ghidra.program.model.data.*;-import ghidra.program.model.listing.ProgramModule;import ghidra.util.exception.DuplicateNameException;-import ghidra.util.task.TaskMonitor;/*** Represents an entry_point_command structure@@ -73,22 +67,4 @@ public class EntryPointCommand extends LoadCommand {return "entry_point_command";}- @Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,- ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {-- updateMonitor(monitor);- try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address address = baseAddress.getNewAddress(getStartIndex());- api.createData(address, toDataType());- }- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName());- }-- }-}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/ExportTrie.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/ExportTrie.javaindex 6d299836a4..98689570f3 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/ExportTrie.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/ExportTrie.java@@ -15,15 +15,13 @@*/package ghidra.app.util.bin.format.macho.commands;-import static ghidra.app.util.bin.format.macho.commands.DyldInfoCommandConstants.EXPORT_SYMBOL_FLAGS_REEXPORT;-import static ghidra.app.util.bin.format.macho.commands.DyldInfoCommandConstants.EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER;+import static ghidra.app.util.bin.format.macho.commands.DyldInfoCommandConstants.*;+import java.io.IOException;import java.util.*;import java.util.function.Predicate;import java.util.stream.Collectors;-import java.io.IOException;-import ghidra.app.util.bin.BinaryReader;import ghidra.program.model.data.LEB128;@@ -138,78 +136,17 @@ public class ExportTrie {}/**- * A export trie entry+ * Creates a new {@link ExportEntry}+ *+ * @param name The export name+ * @param address The export address+ * @param flags The export flags+ * @param other The export "other" info+ * @param importName The export import name (could be null if not a re-export)*/- public static class ExportEntry {-- private String name;- private long address;- private long flags;- private long other;- private String importName;-- /**- * Creates a new {@link ExportEntry}- *- * @param name The export name- * @param address The export address- * @param flags The export flags- * @param other The export "other" info- * @param importName The export import name (could be null if not a re-export)- */- public ExportEntry(String name, long address, long flags, long other, String importName) {- this.name = name;- this.address = address;- this.flags = flags;- this.other = other;- this.importName = importName;- }-- /**- * Gets the export name- *- * @return The export name- */- public String getName() {- return name;- }-- /**- * Gets the export address, which is is an image base offset (from the Mach-O header)- *- * @return The export address- */- public long getAddress() {- return address;- }-- /**- * Gets the export flags- *- * @return The export flags- */- public long getFlags() {- return flags;- }-- /**- * Gets the export "other" info- *- * @return The export "other" info- */- public long getOther() {- return other;- }-- /**- * Gets the export import name- *- * @return The export import name (could be null if not a re-export)- */- public String getImportName() {- return importName;- }-+ public record ExportEntry(String name, long address, long flags, long other,+ String importName) {+/*** Check to see if the export is a "re-export"*@@ -229,15 +166,8 @@ public class ExportTrie {/*** A trie node*/- private static class Node {- String name;- int offset;-- Node(String name, int offset) {- this.name = name;- this.offset = offset;- }-+ private record Node(String name, int offset) {+@Overridepublic String toString() {return String.format("%s, 0x%x", name, offset);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/FileSetEntryCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/FileSetEntryCommand.javaindex 91b6ad79cd..06cebac6ac 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/FileSetEntryCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/FileSetEntryCommand.java@@ -19,14 +19,8 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.macho.MachConstants;-import ghidra.app.util.bin.format.macho.MachHeader;-import ghidra.app.util.importer.MessageLog;-import ghidra.program.flatapi.FlatProgramAPI;-import ghidra.program.model.address.Address;import ghidra.program.model.data.*;-import ghidra.program.model.listing.ProgramModule;import ghidra.util.exception.DuplicateNameException;-import ghidra.util.task.TaskMonitor;/*** Represents a fileset_entry_command@@ -106,24 +100,6 @@ public class FileSetEntryCommand extends LoadCommand {return "fileset_entry_command";}- @Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,- ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);- try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address addr = baseAddress.getNewAddress(getStartIndex());- DataType fileSetEntryDT = toDataType();- api.createData(addr, fileSetEntryDT);- api.setPlateComment(addr, entryId.getString());- }- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());- }- }-@Overridepublic String toString() {return entryId.getString();diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/FixedVirtualMemoryFileCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/FixedVirtualMemoryFileCommand.javaindex 00a2bb6885..873fe13233 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/FixedVirtualMemoryFileCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/FixedVirtualMemoryFileCommand.java@@ -72,32 +72,19 @@ public class FixedVirtualMemoryFileCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);- if (isBinary) {- try {- createFragment(api, baseAddress, parentModule);- }- catch (Exception e) {- log.appendException(e);- }+ try {+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);+Address addr = baseAddress.getNewAddress(getStartIndex());- try {- api.createData(addr, toDataType());- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());- }- try {- int strLen = getCommandSize() - name.getOffset();- Address strAddr = addr.add(name.getOffset());- api.createAsciiString(strAddr, strLen);- }- catch (Exception e) {- log.appendMsg("Unable to create load command string for " + getCommandName() +- " - " + e.getMessage());- }+ int strLen = getCommandSize() - name.getOffset();+ Address strAddr = addr.add(name.getOffset());+ api.createAsciiString(strAddr, strLen);+ }+ catch (Exception e) {+ log.appendMsg("Unable to create " + getCommandName());+}}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/FunctionStartsCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/FunctionStartsCommand.javaindex 299cc9d8fd..2c7b63f47e 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/FunctionStartsCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/FunctionStartsCommand.java@@ -15,25 +15,31 @@*/package ghidra.app.util.bin.format.macho.commands;+import java.io.IOException;import java.util.ArrayList;import java.util.List;-import java.io.IOException;-import ghidra.app.util.bin.BinaryReader;-import ghidra.app.util.bin.ByteProvider;+import ghidra.app.util.bin.LEB128Info;+import ghidra.app.util.bin.format.macho.MachHeader;+import ghidra.app.util.importer.MessageLog;import ghidra.program.model.address.Address;-import ghidra.program.model.data.LEB128;+import ghidra.program.model.data.DataUtilities;+import ghidra.program.model.listing.Data;+import ghidra.program.model.listing.Program;+import ghidra.program.model.symbol.*;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;/**- * Represents a LC_FUNCTION_STARTS command.- *- * @see <a href="https://opensource.apple.com/source/xnu/xnu-7195.81.3/EXTERNAL_HEADERS/mach-o/loader.h.auto.html">mach-o/loader.h</a>+ * Represents a LC_FUNCTION_STARTS command.*/public class FunctionStartsCommand extends LinkEditDataCommand {+ private List<LEB128Info> lebs = new ArrayList<>();+/**- * Creates and parses a new {@link LinkEditDataCommand}+ * Creates and parses a new {@link FunctionStartsCommand}** @param loadCommandReader A {@link BinaryReader reader} that points to the start of the load* command@@ -44,50 +50,70 @@ public class FunctionStartsCommand extends LinkEditDataCommand {FunctionStartsCommand(BinaryReader loadCommandReader, BinaryReader dataReader)throws IOException {super(loadCommandReader, dataReader);++ int i = 0;+ while (true) {+ LEB128Info info = dataReader.readNext(LEB128Info::unsigned);+ if (i + info.getLength() > datasize || info.asLong() == 0) {+ break;+ }+ i += info.getLength();+ lebs.add(info);+ }}/*** Finds the {@link List} of function start addresses*- * @param provider The provider that contains the function start addresses. This could be a- * different provider than the one that contains the load command.* @param textSegmentAddr The {@link Address} of the function starts' __TEXT segment* @return The {@link List} of function start addresses* @throws IOException if there was an issue reading bytes*/- public List<Address> findFunctionStartAddrs(ByteProvider provider, Address textSegmentAddr)- throws IOException {+ public List<Address> findFunctionStartAddrs(Address textSegmentAddr) throws IOException {List<Address> addrs = new ArrayList<>();- Address current = textSegmentAddr;- for (long offset : findFunctionStartOffsets(provider)) {- current = current.add(offset);- addrs.add(current);+ long currentFuncOffset = 0;+ for (LEB128Info leb : lebs) {+ currentFuncOffset += leb.asLong();+ addrs.add(textSegmentAddr.add(currentFuncOffset));}-return addrs;}- /**- * Finds the {@link List} of function start offsets- *- * @param provider The provider that contains the function start offsets. This could be a- * different provider than the one that contains the load command.- * @return The {@link List} of function start offsets- * @throws IOException if there was an issue reading bytes- */- private List<Long> findFunctionStartOffsets(ByteProvider provider) throws IOException {- BinaryReader reader = new BinaryReader(provider, true);- reader.setPointerIndex(getDataOffset());+ @Override+ public void markup(Program program, MachHeader header, Address addr, TaskMonitor monitor,+ MessageLog log) throws CancelledException {+ if (addr == null || datasize == 0) {+ return;+ }- List<Long> offsets = new ArrayList<>();- while (true) {- long offset = reader.readNext(LEB128::unsigned);- if (offset == 0) {- break;- }- offsets.add(offset);+ super.markup(program, header, addr, monitor, log);++ SegmentCommand textSegment = header.getSegment(SegmentNames.SEG_TEXT);+ if (textSegment == null) {+ return;}- return offsets;+ try {+ ReferenceManager referenceManager = program.getReferenceManager();+ Address textSegmentAddr = program.getAddressFactory()+ .getDefaultAddressSpace()+ .getAddress(textSegment.getVMaddress());+ long currentFuncOffset = 0;+ for (LEB128Info leb : lebs) {+ Data d = DataUtilities.createData(program, addr, ULEB128, -1,+ DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ addr = addr.add(leb.getLength());+ currentFuncOffset += leb.asLong();+ Reference ref = referenceManager.addMemoryReference(d.getMinAddress(),+ textSegmentAddr.add(currentFuncOffset),+ RefType.DATA, SourceType.IMPORTED, 0);+ referenceManager.setPrimary(ref, true);+ }++ }+ catch (Exception e) {+ log.appendMsg(DyldChainedFixupsCommand.class.getSimpleName(), "Failed to markup %s."+ .formatted(LoadCommandTypes.getLoadCommandName(getCommandType())));+ }}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LinkEditDataCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LinkEditDataCommand.javaindex be37359ced..d2f54de63b 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LinkEditDataCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LinkEditDataCommand.java@@ -23,8 +23,10 @@ import ghidra.app.util.bin.format.macho.MachHeader;import ghidra.app.util.importer.MessageLog;import ghidra.program.flatapi.FlatProgramAPI;import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSpace;import ghidra.program.model.data.*;-import ghidra.program.model.listing.ProgramModule;+import ghidra.program.model.listing.*;+import ghidra.util.exception.CancelledException;import ghidra.util.exception.DuplicateNameException;import ghidra.util.task.TaskMonitor;@@ -69,23 +71,37 @@ public class LinkEditDataCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,+ public Address getDataAddress(MachHeader header, AddressSpace space) {+ if (dataoff != 0 && datasize != 0) {+ SegmentCommand segment = getContainingSegment(header, dataoff);+ if (segment != null) {+ return space+ .getAddress(segment.getVMaddress() + (dataoff - segment.getFileOffset()));+ }+ }+ return null;+ }++ @Override+ public void markup(Program program, MachHeader header, Address addr, TaskMonitor monitor,+ MessageLog log) throws CancelledException {+ if (addr == null || datasize == 0) {+ return;+ }+ String lcName = LoadCommandTypes.getLoadCommandName(getCommandType());+ program.getListing().setComment(addr, CodeUnit.PLATE_COMMENT, lcName);+ }++ @Override+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address address = baseAddress.getNewAddress(getStartIndex());- api.createData(address, toDataType());- api.setPlateComment(address,- LoadCommandTypes.getLoadCommandName(getCommandType()));--//TODO markup actual data+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);- if (datasize > 0) {- Address start = baseAddress.getNewAddress(dataoff);- api.createFragment(parentModule, getCommandName() + "_DATA", start, datasize);- }+ if (datasize > 0) {+ Address start = baseAddress.getNewAddress(dataoff);+ api.createFragment(parentModule,+ LoadCommandTypes.getLoadCommandName(getCommandType()), start, datasize);}}catch (Exception e) {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LinkerOptionCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LinkerOptionCommand.javaindex e8468ab2d2..4fce941555 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LinkerOptionCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LinkerOptionCommand.java@@ -15,21 +15,14 @@*/package ghidra.app.util.bin.format.macho.commands;+import java.io.IOException;import java.util.ArrayList;import java.util.List;-import java.io.IOException;-import ghidra.app.util.bin.BinaryReader;-import ghidra.app.util.bin.format.macho.MachHeader;-import ghidra.app.util.importer.MessageLog;-import ghidra.program.flatapi.FlatProgramAPI;-import ghidra.program.model.address.Address;import ghidra.program.model.data.DataType;import ghidra.program.model.data.StructureDataType;-import ghidra.program.model.listing.ProgramModule;import ghidra.util.exception.DuplicateNameException;-import ghidra.util.task.TaskMonitor;/*** Represents a linker_option_command structure@@ -73,21 +66,4 @@ public class LinkerOptionCommand extends LoadCommand {return struct;}- @Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,- ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);-- try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address address = baseAddress.getNewAddress(getStartIndex());- api.createData(address, toDataType());- }- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName());- }- }-}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommand.javaindex 4ad8722f56..c49372215a 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommand.java@@ -17,20 +17,22 @@ package ghidra.app.util.bin.format.macho.commands;import java.io.IOException;+import ghidra.app.cmd.formats.MachoBinaryAnalysisCommand;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;import ghidra.app.util.bin.format.macho.MachHeader;import ghidra.app.util.importer.MessageLog;import ghidra.program.flatapi.FlatProgramAPI;import ghidra.program.model.address.Address;-import ghidra.program.model.listing.ProgramFragment;-import ghidra.program.model.listing.ProgramModule;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.listing.*;+import ghidra.util.exception.CancelledException;import ghidra.util.task.TaskMonitor;/*** Represents a load_command structure*- * @see <a href="https://opensource.apple.com/source/xnu/xnu-7195.81.3/EXTERNAL_HEADERS/mach-o/loader.h.auto.html">mach-o/loader.h</a>+ * @see <a href="https://github.com/apple-oss-distributions/xnu/blob/main/EXTERNAL_HEADERS/mach-o/loader.h">EXTERNAL_HEADERS/mach-o/loader.h</a>*/public abstract class LoadCommand implements StructConverter {private long startIndex;@@ -84,25 +86,87 @@ public abstract class LoadCommand implements StructConverter {public abstract String getCommandName();/**- * Marks-up the program with the data structures for this load command+ * Gets the {@link Address} of this load command's "data"*- * @param header the mach header- * @param api the flat program api- * @param baseAddress the base address to apply the mark-up- * @param isBinary true if mach-o was loaded as binary- * @param parentModule parent module to create fragments- * @param monitor the task monitor- * @param log the message logS+ * @param header The Mach-O header+ * @param space The {@link AddressSpace}+ * @return The {@link Address} of this load command's "data", or null if it has no data*/- public abstract void markup(MachHeader header, FlatProgramAPI api, Address baseAddress,- boolean isBinary, ProgramModule parentModule, TaskMonitor monitor, MessageLog log);+ public Address getDataAddress(MachHeader header, AddressSpace space) {+ return null;+ }- ///////////////////////////////////////////////////////////////////////+ /**+ * Marks up this {@link LoadCommand} data with data structures and comments. Assumes the+ * program was imported as a Mach-O.+ *+ * @param program The {@link Program} to mark up+ * @param header The Mach-O header+ * @param addr The {@link Address} of the start of load command data (could be null if no data)+ * @param monitor A cancellable task monitor+ * @param log The log+ * @throws CancelledException if the user cancelled the operation+ */+ public void markup(Program program, MachHeader header, Address addr, TaskMonitor monitor,+ MessageLog log) throws CancelledException {+ // Default is no markup+ return;+ }++ /**+ * Gets the {@link SegmentCommand segment} that contains the give file offset+ *+ * @param header The Mach-O header+ * @param fileOffset The file offset+ * @return The {@link SegmentCommand segment} that contains the give file offset, or null if+ * one was not found+ */+ protected SegmentCommand getContainingSegment(MachHeader header, long fileOffset) {+ for (SegmentCommand segment : header.getAllSegments()) {+ if (fileOffset >= segment.getFileOffset() &&+ fileOffset < segment.getFileOffset() + segment.getFileSize()) {+ return segment;+ }+ }+ return null;+ }++ //-------------------Legacy code to support Raw Binary markup----------------------------------+ /**+ * Marks-up this {@link LoadCommand} with data structures and comments. Assumes the program+ * was imported as a Raw Binary.+ *+ * @param header The Mach-O header+ * @param api A {@link FlatProgramAPI}+ * @param baseAddress The base address of the program+ * @param parentModule The parent {@link ProgramModule module} to create fragments+ * @param monitor A cancellable task monitor+ * @param log The log+ * @see MachoBinaryAnalysisCommand+ */+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,+ ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {+ updateMonitor(monitor);+ try {+ createFragment(api, baseAddress, parentModule);+ Address addr = baseAddress.getNewAddress(getStartIndex());+ api.createData(addr, toDataType());+ createPlateComment(api, addr);+ }+ catch (Exception e) {+ log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());+ }+ }protected final ProgramFragment createFragment(FlatProgramAPI api, Address baseAddress,ProgramModule module) throws Exception {Address start = baseAddress.getNewAddress(getStartIndex());- return api.createFragment(module, getCommandName(), start, getCommandSize());+ return api.createFragment(module, LoadCommandTypes.getLoadCommandName(getCommandType()),+ start, getCommandSize());+ }++ protected final void createPlateComment(FlatProgramAPI api, Address addr) {+ api.setPlateComment(addr, LoadCommandTypes.getLoadCommandName(getCommandType()));}protected final void updateMonitor(TaskMonitor monitor) {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommandFactory.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommandFactory.javaindex ee3ebe7b71..409390d17b 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommandFactory.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommandFactory.java@@ -110,7 +110,6 @@ public class LoadCommandFactory {return new RunPathCommand(reader);case LC_CODE_SIGNATURE:case LC_SEGMENT_SPLIT_INFO:- case LC_DATA_IN_CODE:case LC_OPTIMIZATION_HINT:case LC_DYLIB_CODE_SIGN_DRS:return new LinkEditDataCommand(reader,@@ -134,6 +133,9 @@ public class LoadCommandFactory {getLinkerLoadCommandReader(reader, header, splitDyldCache));case LC_MAIN:return new EntryPointCommand(reader);+ case LC_DATA_IN_CODE:+ return new DataInCodeCommand(reader,+ getLinkerLoadCommandReader(reader, header, splitDyldCache));case LC_SOURCE_VERSION:return new SourceVersionCommand(reader);case LC_LAZY_LOAD_DYLIB:diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/NList.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/NList.javaindex a75fe0dbae..9945443a3d 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/NList.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/NList.java@@ -27,7 +27,7 @@ import ghidra.util.exception.DuplicateNameException;/*** Represents an nlist and nlist_64 structure.*- * @see <a href="https://opensource.apple.com/source/xnu/xnu-4570.71.2/EXTERNAL_HEADERS/mach-o/nlist.h.auto.html">mach-o/nlist.h</a>+ * @see <a href="https://github.com/apple-oss-distributions/xnu/blob/main/EXTERNAL_HEADERS/mach-o/nlist.h">EXTERNAL_HEADERS/mach-o/nlist.h</a>*/public class NList implements StructConverter {private int n_strx;diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/ObsoleteCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/ObsoleteCommand.javaindex 208987502d..1c7c32b517 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/ObsoleteCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/ObsoleteCommand.java@@ -19,13 +19,8 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.macho.*;-import ghidra.app.util.importer.MessageLog;-import ghidra.program.flatapi.FlatProgramAPI;-import ghidra.program.model.address.Address;import ghidra.program.model.data.*;-import ghidra.program.model.listing.ProgramModule;import ghidra.util.exception.DuplicateNameException;-import ghidra.util.task.TaskMonitor;public abstract class ObsoleteCommand extends LoadCommand {@@ -35,30 +30,16 @@ public abstract class ObsoleteCommand extends LoadCommand {}public DataType toDataType() throws DuplicateNameException, IOException {- StructureDataType struct = new StructureDataType(getCommandName(), 0);- struct.add(DWORD, "cmd", null);- struct.add(DWORD, "cmdsize", null);- struct.add(getByteArray(), "obsolete", null);- struct.setCategoryPath(new CategoryPath(MachConstants.DATA_TYPE_CATEGORY));- return struct;+ StructureDataType struct = new StructureDataType(getCommandName(), 0);+ struct.add(DWORD, "cmd", null);+ struct.add(DWORD, "cmdsize", null);+ struct.add(getByteArray(), "obsolete", null);+ struct.setCategoryPath(new CategoryPath(MachConstants.DATA_TYPE_CATEGORY));+ return struct;}private DataType getByteArray() {- return new ArrayDataType(BYTE, getCommandSize()-8, BYTE.getLength());+ return new ArrayDataType(BYTE, getCommandSize() - 8, BYTE.getLength());}- @Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary, ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);- try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address addr = baseAddress.getNewAddress(getStartIndex());- api.createData(addr, toDataType());- }- }- catch (Exception e) {- log.appendMsg("Unable to create "+getCommandName()+" - "+e.getMessage());- }- }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/PrebindChecksumCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/PrebindChecksumCommand.javaindex 06824b88f2..09cbf08166 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/PrebindChecksumCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/PrebindChecksumCommand.java@@ -19,14 +19,8 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.macho.MachConstants;-import ghidra.app.util.bin.format.macho.MachHeader;-import ghidra.app.util.importer.MessageLog;-import ghidra.program.flatapi.FlatProgramAPI;-import ghidra.program.model.address.Address;import ghidra.program.model.data.*;-import ghidra.program.model.listing.ProgramModule;import ghidra.util.exception.DuplicateNameException;-import ghidra.util.task.TaskMonitor;/*** Represents a prebind_cksum_command structure@@ -61,20 +55,4 @@ public class PrebindChecksumCommand extends LoadCommand {public String getCommandName() {return "prebind_cksum_command";}-- @Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,- ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);- try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address addr = baseAddress.getNewAddress(getStartIndex());- api.createData(addr, toDataType());- }- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());- }- }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/PreboundDynamicLibraryCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/PreboundDynamicLibraryCommand.javaindex 6809f99a75..5798398245 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/PreboundDynamicLibraryCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/PreboundDynamicLibraryCommand.java@@ -85,19 +85,15 @@ public class PreboundDynamicLibraryCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address addr = baseAddress.getNewAddress(getStartIndex());- api.createData(addr, toDataType());+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);- int nameLen = getCommandSize() - name.getOffset();- Address nameAddr = addr.add(name.getOffset());- api.createAsciiString(nameAddr, nameLen);- }+ Address addr = baseAddress.getNewAddress(getStartIndex());+ int nameLen = getCommandSize() - name.getOffset();+ Address nameAddr = addr.add(name.getOffset());+ api.createAsciiString(nameAddr, nameLen);}catch (Exception e) {log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/RoutinesCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/RoutinesCommand.javaindex 8ea66e8e81..35021e8c01 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/RoutinesCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/RoutinesCommand.java@@ -19,14 +19,8 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.macho.MachConstants;-import ghidra.app.util.bin.format.macho.MachHeader;-import ghidra.app.util.importer.MessageLog;-import ghidra.program.flatapi.FlatProgramAPI;-import ghidra.program.model.address.Address;import ghidra.program.model.data.*;-import ghidra.program.model.listing.ProgramModule;import ghidra.util.exception.DuplicateNameException;-import ghidra.util.task.TaskMonitor;/*** Represents a routines_command and routines_command_64 structure@@ -134,19 +128,4 @@ public class RoutinesCommand extends LoadCommand {public String getCommandName() {return "routines_command";}-- @Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary, ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);- try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address addr = baseAddress.getNewAddress(getStartIndex());- api.createData(addr, toDataType());- }- }- catch (Exception e) {- log.appendMsg("Unable to create "+getCommandName()+" - "+e.getMessage());- }- }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/RunPathCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/RunPathCommand.javaindex 97abb38dac..cd9a02ffce 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/RunPathCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/RunPathCommand.java@@ -49,17 +49,13 @@ public class RunPathCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address address = baseAddress.getNewAddress(getStartIndex());- api.createData(address, toDataType());- int length = getCommandSize() - path.getOffset();- api.createAsciiString(address.add(path.getOffset()), length);- }+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);+ Address address = baseAddress.getNewAddress(getStartIndex());+ int length = getCommandSize() - path.getOffset();+ api.createAsciiString(address.add(path.getOffset()), length);}catch (Exception e) {log.appendMsg("Unable to create " + getCommandName());diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SegmentCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SegmentCommand.javaindex a5e5e98896..c2e97d397e 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SegmentCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SegmentCommand.java@@ -220,59 +220,53 @@ public class SegmentCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address addr = baseAddress.getNewAddress(getStartIndex());- DataType segmentDT = toDataType();- api.createData(addr, segmentDT);- api.setPlateComment(addr, getSegmentName());-- Address sectionAddress = addr.add(segmentDT.getLength());- for (Section section : sections) {- if (monitor.isCancelled()) {- return;- }- DataType sectionDT = section.toDataType();- api.createData(sectionAddress, sectionDT);- api.setPlateComment(sectionAddress, section.toString());- sectionAddress = sectionAddress.add(sectionDT.getLength());+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);+ Address addr = baseAddress.getNewAddress(getStartIndex());- if (section.getType() == SectionTypes.S_ZEROFILL) {- continue;- }- if (header.getFileType() == MachHeaderFileTypes.MH_DYLIB_STUB) {- continue;- }+ Address sectionAddress = addr.add(toDataType().getLength());+ for (Section section : sections) {+ if (monitor.isCancelled()) {+ return;+ }+ DataType sectionDT = section.toDataType();+ api.createData(sectionAddress, sectionDT);+ api.setPlateComment(sectionAddress, section.toString());+ sectionAddress = sectionAddress.add(sectionDT.getLength());- Address sectionByteAddr = baseAddress.add(section.getOffset());- if (section.getSize() > 0) {- api.createLabel(sectionByteAddr, section.getSectionName(), true,- SourceType.IMPORTED);- api.createFragment(parentModule, "SECTION_BYTES", sectionByteAddr,- section.getSize());- }+ if (section.getType() == SectionTypes.S_ZEROFILL) {+ continue;+ }+ if (header.getFileType() == MachHeaderFileTypes.MH_DYLIB_STUB) {+ continue;+ }++ Address sectionByteAddr = baseAddress.add(section.getOffset());+ if (section.getSize() > 0) {+ api.createLabel(sectionByteAddr, section.getSectionName(), true,+ SourceType.IMPORTED);+ api.createFragment(parentModule, "SECTION_BYTES", sectionByteAddr,+ section.getSize());+ }- if (section.getRelocationOffset() > 0) {- Address relocStartAddr = baseAddress.add(section.getRelocationOffset());- long offset = 0;- List<RelocationInfo> relocations = section.getRelocations();- for (RelocationInfo reloc : relocations) {- if (monitor.isCancelled()) {- return;- }- DataType relocDT = reloc.toDataType();- Address relocAddr = relocStartAddr.add(offset);- api.createData(relocAddr, relocDT);- api.setPlateComment(relocAddr, reloc.toString());- offset += relocDT.getLength();+ if (section.getRelocationOffset() > 0) {+ Address relocStartAddr = baseAddress.add(section.getRelocationOffset());+ long offset = 0;+ List<RelocationInfo> relocations = section.getRelocations();+ for (RelocationInfo reloc : relocations) {+ if (monitor.isCancelled()) {+ return;}- api.createFragment(parentModule, section.getSectionName() + "_Relocations",- relocStartAddr, offset);+ DataType relocDT = reloc.toDataType();+ Address relocAddr = relocStartAddr.add(offset);+ api.createData(relocAddr, relocDT);+ api.setPlateComment(relocAddr, reloc.toString());+ offset += relocDT.getLength();}+ api.createFragment(parentModule, section.getSectionName() + "_Relocations",+ relocStartAddr, offset);}}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SourceVersionCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SourceVersionCommand.javaindex be1584a6c4..782d3b3df5 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SourceVersionCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SourceVersionCommand.java@@ -19,14 +19,8 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.macho.MachConstants;-import ghidra.app.util.bin.format.macho.MachHeader;-import ghidra.app.util.importer.MessageLog;-import ghidra.program.flatapi.FlatProgramAPI;-import ghidra.program.model.address.Address;import ghidra.program.model.data.*;-import ghidra.program.model.listing.ProgramModule;import ghidra.util.exception.DuplicateNameException;-import ghidra.util.task.TaskMonitor;/*** Represents a source_version_command structure@@ -62,22 +56,4 @@ public class SourceVersionCommand extends LoadCommand {return "source_version_command";}- @Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,- ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {-- updateMonitor(monitor);- try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address address = baseAddress.getNewAddress(getStartIndex());- api.createData(address, toDataType());- }- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName());- }-- }-}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubClientCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubClientCommand.javaindex c7ed9fc987..756dbbebc5 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubClientCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubClientCommand.java@@ -63,32 +63,18 @@ public class SubClientCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);- if (isBinary) {- try {- createFragment(api, baseAddress, parentModule);- }- catch (Exception e) {- log.appendException(e);- }+ try {+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);+Address addr = baseAddress.getNewAddress(getStartIndex());- try {- api.createData(addr, toDataType());- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());- }- try {- int strLen = getCommandSize() - client.getOffset();- Address strAddr = addr.add(client.getOffset());- api.createAsciiString(strAddr, strLen);- }- catch (Exception e) {- log.appendMsg("Unable to create load command string for " + getCommandName() +- " - " + e.getMessage());- }+ int strLen = getCommandSize() - client.getOffset();+ Address strAddr = addr.add(client.getOffset());+ api.createAsciiString(strAddr, strLen);+ }+ catch (Exception e) {+ log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());}}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubFrameworkCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubFrameworkCommand.javaindex ba803f852f..7c5b170b0e 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubFrameworkCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubFrameworkCommand.java@@ -59,32 +59,18 @@ public class SubFrameworkCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);- if (isBinary) {- try {- createFragment(api, baseAddress, parentModule);- }- catch (Exception e) {- log.appendException(e);- }+ try {+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);+Address addr = baseAddress.getNewAddress(getStartIndex());- try {- api.createData(addr, toDataType());- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());- }- try {- int strLen = getCommandSize() - umbrella.getOffset();- Address strAddr = addr.add(umbrella.getOffset());- api.createAsciiString(strAddr, strLen);- }- catch (Exception e) {- log.appendMsg("Unable to create load command string for " + getCommandName() +- " - " + e.getMessage());- }+ int strLen = getCommandSize() - umbrella.getOffset();+ Address strAddr = addr.add(umbrella.getOffset());+ api.createAsciiString(strAddr, strLen);+ }+ catch (Exception e) {+ log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());}}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubLibraryCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubLibraryCommand.javaindex 08b552a56b..f4fd3129ae 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubLibraryCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubLibraryCommand.java@@ -59,32 +59,18 @@ public class SubLibraryCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);- if (isBinary) {- try {- createFragment(api, baseAddress, parentModule);- }- catch (Exception e) {- log.appendException(e);- }+ try {+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);+Address addr = baseAddress.getNewAddress(getStartIndex());- try {- api.createData(addr, toDataType());- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());- }- try {- int strLen = getCommandSize() - sub_library.getOffset();- Address strAddr = addr.add(sub_library.getOffset());- api.createAsciiString(strAddr, strLen);- }- catch (Exception e) {- log.appendMsg("Unable to create load command string for " + getCommandName() +- " - " + e.getMessage());- }+ int strLen = getCommandSize() - sub_library.getOffset();+ Address strAddr = addr.add(sub_library.getOffset());+ api.createAsciiString(strAddr, strLen);+ }+ catch (Exception e) {+ log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());}}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubUmbrellaCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubUmbrellaCommand.javaindex f54a03834f..7fd595b338 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubUmbrellaCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SubUmbrellaCommand.java@@ -59,32 +59,18 @@ public class SubUmbrellaCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);- if (isBinary) {- try {- createFragment(api, baseAddress, parentModule);- }- catch (Exception e) {- log.appendException(e);- }+ try {+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);+Address addr = baseAddress.getNewAddress(getStartIndex());- try {- api.createData(addr, toDataType());- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());- }- try {- int strLen = getCommandSize() - sub_umbrella.getOffset();- Address strAddr = addr.add(sub_umbrella.getOffset());- api.createAsciiString(strAddr, strLen);- }- catch (Exception e) {- log.appendMsg("Unable to create load command string " + getCommandName() + " - " +- e.getMessage());- }+ int strLen = getCommandSize() - sub_umbrella.getOffset();+ Address strAddr = addr.add(sub_umbrella.getOffset());+ api.createAsciiString(strAddr, strLen);+ }+ catch (Exception e) {+ log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());}}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SymbolTableCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SymbolTableCommand.javaindex d69681aa41..67aa2f2f7c 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SymbolTableCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/SymbolTableCommand.java@@ -26,11 +26,11 @@ import ghidra.app.util.bin.format.macho.MachHeader;import ghidra.app.util.importer.MessageLog;import ghidra.program.flatapi.FlatProgramAPI;import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSpace;import ghidra.program.model.data.*;-import ghidra.program.model.listing.Data;-import ghidra.program.model.listing.ProgramModule;-import ghidra.program.model.symbol.RefType;-import ghidra.program.model.symbol.Reference;+import ghidra.program.model.listing.*;+import ghidra.program.model.symbol.*;+import ghidra.util.exception.CancelledException;import ghidra.util.exception.DuplicateNameException;import ghidra.util.task.TaskMonitor;@@ -154,61 +154,104 @@ public class SymbolTableCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,- ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);- if (isBinary) {- try {- createFragment(api, baseAddress, parentModule);- Address address = baseAddress.getNewAddress(getStartIndex());- api.createData(address, toDataType());-- if (getStringTableSize() > 0) {- Address stringTableStart = baseAddress.getNewAddress(getStringTableOffset());- api.createFragment(parentModule, "string_table", stringTableStart,- getStringTableSize());- }+ public Address getDataAddress(MachHeader header, AddressSpace space) {+ if (symoff != 0 && nsyms != 0) {+ SegmentCommand segment = getContainingSegment(header, symoff);+ if (segment != null) {+ return space+ .getAddress(segment.getVMaddress() + (symoff - segment.getFileOffset()));+ }+ }+ return null;+ }- int symbolIndex = 0;- Address symbolStartAddr = baseAddress.getNewAddress(getSymbolOffset());- long offset = 0;- for (NList symbol : symbols) {- if (monitor.isCancelled()) {- return;- }-- DataType symbolDT = symbol.toDataType();- Address symbolAddr = symbolStartAddr.add(offset);- Data symbolData = api.createData(symbolAddr, symbolDT);-- Address stringAddress = baseAddress.getNewAddress(- getStringTableOffset() + symbol.getStringTableIndex());- Data stringData = api.createAsciiString(stringAddress);- String string = (String) stringData.getValue();-- Reference ref =- api.createMemoryReference(symbolData, stringAddress, RefType.DATA);- api.setReferencePrimary(ref, false);-- api.setPlateComment(symbolAddr,- string + "\n" + "Index: 0x" + Integer.toHexString(symbolIndex) +- "\n" + "Value: 0x" + Long.toHexString(symbol.getValue()) +- "\n" + "Description: 0x" +- Long.toHexString(symbol.getDescription() & 0xffff) + "\n" +- "Library Ordinal: 0x" +- Long.toHexString(symbol.getLibraryOrdinal() & 0xff));-- offset += symbolDT.getLength();- ++symbolIndex;+ @Override+ public void markup(Program program, MachHeader header, Address symbolTableAddr,+ TaskMonitor monitor, MessageLog log) throws CancelledException {+ if (symbolTableAddr == null) {+ return;+ }+ Address stringTableAddr = stroff != 0 ? symbolTableAddr.add(stroff - symoff) : null;++ Listing listing = program.getListing();+ ReferenceManager referenceManager = program.getReferenceManager();+ String lcName = LoadCommandTypes.getLoadCommandName(getCommandType());+ try {+ listing.setComment(symbolTableAddr, CodeUnit.PLATE_COMMENT, lcName);+ for (int i = 0; i < nsyms; i++) {+ NList nlist = symbols.get(i);+ DataType dt = nlist.toDataType();+ Address nlistAddr = symbolTableAddr.add(i * dt.getLength());+ Data d = DataUtilities.createData(program, nlistAddr, dt, -1,+ DataUtilities.ClearDataMode.CHECK_FOR_SPACE);++ if (stringTableAddr != null) {+ Address strAddr = stringTableAddr.add(nlist.getStringTableIndex());+ DataUtilities.createData(program, strAddr, STRING, -1,+ DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ Reference ref = referenceManager.addMemoryReference(d.getMinAddress(), strAddr,+ RefType.DATA, SourceType.IMPORTED, 0);+ referenceManager.setPrimary(ref, true);}+ }+ }+ catch (Exception e) {+ log.appendMsg(SymbolTableCommand.class.getSimpleName(),+ "Failed to markup %s.".formatted(lcName));+ }+ }- if (getNumberOfSymbols() > 0) {- api.createFragment(parentModule, "symbols", symbolStartAddr, offset);+ @Override+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,+ ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {+ try {+ super.markupRawBinary(header, api, baseAddress, parentModule, monitor, log);++ if (getStringTableSize() > 0) {+ Address stringTableStart = baseAddress.getNewAddress(getStringTableOffset());+ api.createFragment(parentModule, "string_table", stringTableStart,+ getStringTableSize());+ }++ int symbolIndex = 0;+ Address symbolStartAddr = baseAddress.getNewAddress(getSymbolOffset());+ long offset = 0;+ for (NList symbol : symbols) {+ if (monitor.isCancelled()) {+ return;}++ DataType symbolDT = symbol.toDataType();+ Address symbolAddr = symbolStartAddr.add(offset);+ Data symbolData = api.createData(symbolAddr, symbolDT);++ Address stringAddress = baseAddress.getNewAddress(+ getStringTableOffset() + symbol.getStringTableIndex());+ Data stringData = api.createAsciiString(stringAddress);+ String string = (String) stringData.getValue();++ Reference ref =+ api.createMemoryReference(symbolData, stringAddress, RefType.DATA);+ api.setReferencePrimary(ref, false);++ api.setPlateComment(symbolAddr,+ string + "\n" + "Index: 0x" + Integer.toHexString(symbolIndex) ++ "\n" + "Value: 0x" + Long.toHexString(symbol.getValue()) ++ "\n" + "Description: 0x" ++ Long.toHexString(symbol.getDescription() & 0xffff) + "\n" ++ "Library Ordinal: 0x" ++ Long.toHexString(symbol.getLibraryOrdinal() & 0xff));++ offset += symbolDT.getLength();+ ++symbolIndex;}- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());++ if (getNumberOfSymbols() > 0) {+ api.createFragment(parentModule, "symbols", symbolStartAddr, offset);}}+ catch (Exception e) {+ log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());+ }}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/TwoLevelHint.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/TwoLevelHint.javaindex 67376b19c7..47e9fe4436 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/TwoLevelHint.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/TwoLevelHint.java@@ -26,7 +26,7 @@ import ghidra.util.exception.DuplicateNameException;/*** Represents a twolevel_hint structure.*- * @see <a href="https://opensource.apple.com/source/xnu/xnu-4570.71.2/EXTERNAL_HEADERS/mach-o/loader.h.auto.html">mach-o/loader.h</a>+ * @see <a href="https://github.com/apple-oss-distributions/xnu/blob/main/EXTERNAL_HEADERS/mach-o/loader.h">EXTERNAL_HEADERS/mach-o/loader.h</a>*/public class TwoLevelHint implements StructConverter {public final static int SIZEOF = 4;diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/TwoLevelHintsCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/TwoLevelHintsCommand.javaindex 23d67f2a4f..97edb8d962 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/TwoLevelHintsCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/TwoLevelHintsCommand.java@@ -89,31 +89,29 @@ public class TwoLevelHintsCommand extends LoadCommand {}@Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,+ public void markupRawBinary(MachHeader header, FlatProgramAPI api, Address baseAddress,ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {updateMonitor(monitor);try {- if (isBinary) {- ProgramFragment fragment = createFragment(api, baseAddress, parentModule);- Address addr = baseAddress.getNewAddress(getStartIndex());- api.createData(addr, toDataType());+ ProgramFragment fragment = createFragment(api, baseAddress, parentModule);+ Address addr = baseAddress.getNewAddress(getStartIndex());+ api.createData(addr, toDataType());- Address hintStartAddress = baseAddress.add(getOffset());- Address hintAddress = hintStartAddress;- for (TwoLevelHint hint : hints) {- if (monitor.isCancelled()) {- return;- }- DataType hintDT = hint.toDataType();- api.createData(hintAddress, hintDT);- api.setPlateComment(hintAddress,- "Sub-image Index: 0x" + Integer.toHexString(hint.getSubImageIndex()) +- '\n' + " TOC Index: 0x" +- Integer.toHexString(hint.getTableOfContentsIndex()));- hintAddress = hintAddress.add(hintDT.getLength());+ Address hintStartAddress = baseAddress.add(getOffset());+ Address hintAddress = hintStartAddress;+ for (TwoLevelHint hint : hints) {+ if (monitor.isCancelled()) {+ return;}- fragment.move(hintStartAddress, hintAddress.subtract(1));+ DataType hintDT = hint.toDataType();+ api.createData(hintAddress, hintDT);+ api.setPlateComment(hintAddress,+ "Sub-image Index: 0x" + Integer.toHexString(hint.getSubImageIndex()) ++ '\n' + " TOC Index: 0x" ++ Integer.toHexString(hint.getTableOfContentsIndex()));+ hintAddress = hintAddress.add(hintDT.getLength());}+ fragment.move(hintStartAddress, hintAddress.subtract(1));}catch (Exception e) {log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/UnsupportedLoadCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/UnsupportedLoadCommand.javaindex e53e23f786..02fbf48ce1 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/UnsupportedLoadCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/UnsupportedLoadCommand.java@@ -19,14 +19,8 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.macho.MachConstants;-import ghidra.app.util.bin.format.macho.MachHeader;-import ghidra.app.util.importer.MessageLog;-import ghidra.program.flatapi.FlatProgramAPI;-import ghidra.program.model.address.Address;import ghidra.program.model.data.*;-import ghidra.program.model.listing.ProgramModule;import ghidra.util.exception.DuplicateNameException;-import ghidra.util.task.TaskMonitor;public class UnsupportedLoadCommand extends LoadCommand {private int type;@@ -41,22 +35,6 @@ public class UnsupportedLoadCommand extends LoadCommand {return "Unsupported Load Command Type = 0x" + Integer.toHexString(type);}- @Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,- ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);- if (isBinary) {- try {- createFragment(api, baseAddress, parentModule);- Address address = baseAddress.getNewAddress(getStartIndex());- api.createData(address, toDataType());- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());- }- }- }-@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {StructureDataType struct = new StructureDataType(getCommandName(), 0);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/UuidCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/UuidCommand.javaindex bcd46deaee..3e11ae8c2d 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/UuidCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/UuidCommand.java@@ -19,14 +19,8 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.macho.MachConstants;-import ghidra.app.util.bin.format.macho.MachHeader;-import ghidra.app.util.importer.MessageLog;-import ghidra.program.flatapi.FlatProgramAPI;-import ghidra.program.model.address.Address;import ghidra.program.model.data.*;-import ghidra.program.model.listing.ProgramModule;import ghidra.util.exception.DuplicateNameException;-import ghidra.util.task.TaskMonitor;/*** Represents a uuid_command structure@@ -52,21 +46,6 @@ public class UuidCommand extends LoadCommand {return "uuid_command";}- @Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,- ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address address = baseAddress.getNewAddress(getStartIndex());- api.createData(address, toDataType());- }- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName());- }- }-@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {StructureDataType struct = new StructureDataType(getCommandName(), 0);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/VersionMinCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/VersionMinCommand.javaindex 1f09e7d5d0..61cfae4eb9 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/VersionMinCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/VersionMinCommand.java@@ -19,14 +19,8 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.macho.MachConstants;-import ghidra.app.util.bin.format.macho.MachHeader;-import ghidra.app.util.importer.MessageLog;-import ghidra.program.flatapi.FlatProgramAPI;-import ghidra.program.model.address.Address;import ghidra.program.model.data.*;-import ghidra.program.model.listing.ProgramModule;import ghidra.util.exception.DuplicateNameException;-import ghidra.util.task.TaskMonitor;/*** Represents a version_min_command structure@@ -48,25 +42,6 @@ public class VersionMinCommand extends LoadCommand {return "version_min_command";}- @Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,- ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {-- updateMonitor(monitor);- try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address addr = baseAddress.getNewAddress(getStartIndex());- api.createData(addr, toDataType());- api.setPlateComment(addr,- LoadCommandTypes.getLoadCommandName(getCommandType()));- }- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());- }- }-@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {StructureDataType struct = new StructureDataType(getCommandName(), 0);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedFixupHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedFixupHeader.javanew file mode 100644index 0000000000..be0df54c78--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedFixupHeader.java@@ -0,0 +1,124 @@+/* ###+ * 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.bin.format.macho.commands.chained;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;+import ghidra.app.util.bin.format.macho.MachConstants;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * Represents a dyld_chained_fixups_header structure.+ *+ * @see <a href="https://github.com/apple-oss-distributions/dyld/blob/main/include/mach-o/fixup-chains.h">mach-o/fixup-chains.h</a>+ */+public class DyldChainedFixupHeader implements StructConverter {++ private int fixupsVersion;+ private int startsOffset;+ private int importsOffset;+ private int symbolsOffset;+ private int importsCount;+ private int importsFormat;+ private int symbolsFormat;++ private DyldChainedStartsInImage chainedStartsInImage;+ private DyldChainedImports chainedImports;++ /**+ * Creates a new {@link DyldChainedFixupHeader}+ *+ * @param reader A {@link BinaryReader} positioned at the start of the structure+ * @throws IOException if there was an IO-related problem creating the structure+ */+ public DyldChainedFixupHeader(BinaryReader reader) throws IOException {+ long ptrIndex = reader.getPointerIndex();++ fixupsVersion = reader.readNextInt();+ startsOffset = reader.readNextInt();+ importsOffset = reader.readNextInt();+ symbolsOffset = reader.readNextInt();+ importsCount = reader.readNextInt();+ importsFormat = reader.readNextInt();+ symbolsFormat = reader.readNextInt();++ reader.setPointerIndex(ptrIndex + startsOffset);+ chainedStartsInImage = new DyldChainedStartsInImage(reader);++ reader.setPointerIndex(ptrIndex + importsOffset);+ chainedImports = new DyldChainedImports(reader, this);++ reader.setPointerIndex(ptrIndex + symbolsOffset);+ chainedImports.initSymbols(reader, this);+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ StructureDataType struct = new StructureDataType("dyld_chained_fixups_header", 0);+ struct.add(DWORD, "fixups_version", "0");+ struct.add(DWORD, "starts_offset", "offset of dyld_chained_starts_in_image in chain_data");+ struct.add(DWORD, "imports_offset", "offset of imports table in chain_data");+ struct.add(DWORD, "symbols_offset", "offset of symbol strings in chain_data");+ struct.add(DWORD, "imports_count", "number of imported symbol names");+ struct.add(DWORD, "imports_format", "DYLD_CHAINED_IMPORT*");+ struct.add(DWORD, "symbols_format", "0 => uncompressed, 1 => zlib compressed");+ struct.setCategoryPath(new CategoryPath(MachConstants.DATA_TYPE_CATEGORY));+ return struct;+ }++ public int getFixupsVersion() {+ return fixupsVersion;+ }++ public int getStartsOffset() {+ return startsOffset;+ }++ public int getImportsOffset() {+ return importsOffset;+ }++ public int getSymbolsOffset() {+ return symbolsOffset;+ }++ public int getImportsCount() {+ return importsCount;+ }++ public int getImportsFormat() {+ return importsFormat;+ }++ public int getSymbolsFormat() {+ return symbolsFormat;+ }++ public boolean isCompress() {+ return symbolsFormat != 0;+ }++ public DyldChainedStartsInImage getChainedStartsInImage() {+ return chainedStartsInImage;+ }++ public DyldChainedImports getChainedImports() {+ return chainedImports;+ }+}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.javanew file mode 100644index 0000000000..c7a8ba824d--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedFixups.java@@ -0,0 +1,408 @@+/* ###+ * 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.bin.format.macho.commands.chained;++import static ghidra.app.util.bin.format.macho.dyld.DyldChainedPtr.*;++import java.util.*;++import ghidra.app.util.bin.format.macho.MachHeader;+import ghidra.app.util.bin.format.macho.Section;+import ghidra.app.util.bin.format.macho.commands.*;+import ghidra.app.util.bin.format.macho.dyld.DyldChainedPtr;+import ghidra.app.util.bin.format.macho.dyld.DyldChainedPtr.DyldChainType;+import ghidra.app.util.importer.MessageLog;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.listing.Program;+import ghidra.program.model.mem.Memory;+import ghidra.program.model.mem.MemoryAccessException;+import ghidra.program.model.reloc.Relocation.Status;+import ghidra.program.model.reloc.RelocationResult;+import ghidra.program.model.symbol.Symbol;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++public class DyldChainedFixups {++ private MachHeader machoHeader;+ private Program program;+ private boolean shouldAddChainedFixupsRelocations;+ private MessageLog log;+ private TaskMonitor monitor;+ private Memory memory;+ private AddressSpace space;++ /**+ * Creates a new {@link DyldChainedFixups}+ *+ * @param program The {@link Program}+ * @param header The Mach-O header+ * @param shouldAddChainedFixupsRelocations True if relocations should be added for chained+ * fixups; otherwise, false+ * @param log The log+ * @param monitor A cancelable task monitor.+ */+ public DyldChainedFixups(Program program, MachHeader header,+ boolean shouldAddChainedFixupsRelocations, MessageLog log, TaskMonitor monitor) {+ this.program = program;+ this.machoHeader = header;+ this.shouldAddChainedFixupsRelocations = shouldAddChainedFixupsRelocations;+ this.log = log;+ this.monitor = monitor;+ this.memory = program.getMemory();+ this.space = program.getAddressFactory().getDefaultAddressSpace();+ }++ /**+ * Fixes up any chained fixups. Relies on the __thread_starts section being present.+ *+ * @return A list of addresses where chained fixups were performed.+ * @throws Exception if there was a problem reading/writing memory.+ */+ public List<Address> processChainedFixups() throws Exception {++ List<Address> fixedAddresses = new ArrayList<>();++ // if has Chained Fixups load command, use it+ List<DyldChainedFixupsCommand> loadCommands =+ machoHeader.getLoadCommands(DyldChainedFixupsCommand.class);+ for (LoadCommand loadCommand : loadCommands) {+ DyldChainedFixupsCommand linkCmd = (DyldChainedFixupsCommand) loadCommand;++ DyldChainedFixupHeader chainHeader = linkCmd.getChainHeader();++ DyldChainedStartsInImage chainedStartsInImage = chainHeader.getChainedStartsInImage();++ List<DyldChainedStartsInSegment> chainedStarts =+ chainedStartsInImage.getChainedStarts();+ for (DyldChainedStartsInSegment chainStart : chainedStarts) {+ fixedAddresses.addAll(processSegmentPointerChain(chainHeader, chainStart));+ }+ log.appendMsg("Fixed up " + fixedAddresses.size() + " chained pointers.");+ }++ // if pointer chains fixed by DyldChainedFixupsCommands, then all finished+ if (loadCommands.size() > 0) {+ return fixedAddresses;+ }++ // if has thread_starts use to fixup chained pointers+ Section threadStarts = machoHeader.getSection(SegmentNames.SEG_TEXT, "__thread_starts");+ if (threadStarts == null) {+ return Collections.emptyList();+ }++ Address threadSectionStart = null;+ Address threadSectionEnd = null;+ threadSectionStart = space.getAddress(threadStarts.getAddress());+ threadSectionEnd = threadSectionStart.add(threadStarts.getSize() - 1);++ monitor.setMessage("Fixing up chained pointers...");++ long nextOffSize = (memory.getInt(threadSectionStart) & 1) * 4 + 4;+ Address chainHead = threadSectionStart.add(4);++ while (chainHead.compareTo(threadSectionEnd) < 0 && !monitor.isCancelled()) {+ int headStartOffset = memory.getInt(chainHead);+ if (headStartOffset == 0xFFFFFFFF || headStartOffset == 0) {+ break;+ }++ Address chainStart = program.getImageBase().add(headStartOffset & 0xffffffffL);+ fixedAddresses.addAll(processPointerChain(chainStart, nextOffSize));+ chainHead = chainHead.add(4);+ }++ log.appendMsg("Fixed up " + fixedAddresses.size() + " chained pointers.");+ return fixedAddresses;+ }++ private List<Address> processSegmentPointerChain(DyldChainedFixupHeader chainHeader,+ DyldChainedStartsInSegment chainStart)+ throws MemoryAccessException, CancelledException {++ List<Address> fixedAddresses = new ArrayList<Address>();+ long fixedAddressCount = 0;++ if (chainStart.getPointerFormat() == 0) {+ return fixedAddresses;+ }++ long dataPageStart = chainStart.getSegmentOffset();+ dataPageStart = dataPageStart + program.getImageBase().getOffset();+ long pageSize = chainStart.getPageSize();+ long pageStartsCount = chainStart.getPageCount();++ long authValueAdd = 0;++ short[] pageStarts = chainStart.getPageStarts();++ short ptrFormatValue = chainStart.getPointerFormat();+ DyldChainType ptrFormat = DyldChainType.lookupChainPtr(ptrFormatValue);++ monitor.setMessage("Fixing " + ptrFormat.getName() + " chained pointers...");++ monitor.setMaximum(pageStartsCount);+ for (int index = 0; index < pageStartsCount; index++) {+ monitor.checkCancelled();++ long page = dataPageStart + (pageSize * index);++ monitor.setProgress(index);++ int pageEntry = pageStarts[index] & 0xffff;+ if (pageEntry == DYLD_CHAINED_PTR_START_NONE) {+ continue;+ }++ List<Address> unchainedLocList = new ArrayList<>(1024);++ long pageOffset = pageEntry; // first entry is byte based++ switch (ptrFormat) {+ case DYLD_CHAINED_PTR_ARM64E:+ case DYLD_CHAINED_PTR_ARM64E_KERNEL:+ case DYLD_CHAINED_PTR_ARM64E_USERLAND:+ case DYLD_CHAINED_PTR_ARM64E_USERLAND24:+ processPointerChain(chainHeader, unchainedLocList, ptrFormat, page, pageOffset,+ authValueAdd);+ break;++ // These might work, but have not been fully tested!+ case DYLD_CHAINED_PTR_64:+ case DYLD_CHAINED_PTR_64_OFFSET:+ case DYLD_CHAINED_PTR_64_KERNEL_CACHE:+ case DYLD_CHAINED_PTR_32:+ case DYLD_CHAINED_PTR_32_CACHE:+ case DYLD_CHAINED_PTR_32_FIRMWARE:+ case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE:+ processPointerChain(chainHeader, unchainedLocList, ptrFormat, page, pageOffset,+ authValueAdd);+ break;++ case DYLD_CHAINED_PTR_ARM64E_FIRMWARE:+ default:+ log.appendMsg(+ "WARNING: Pointer Chain format " + ptrFormat + " not processed yet!");+ break;+ }++ fixedAddressCount += unchainedLocList.size();++ fixedAddresses.addAll(unchainedLocList);+ }++ log.appendMsg(+ "Fixed " + fixedAddressCount + " " + ptrFormat.getName() + " chained pointers.");++ return fixedAddresses;+ }++ /**+ * Fixes up any chained pointers, starting at the given address.+ *+ * @param chainHeader fixup header chains+ * @param unchainedLocList list of locations that were unchained+ * @param pointerFormat format of pointers within this chain+ * @param page within data pages that has pointers to be unchained+ * @param nextOff offset within the page that is the chain start+ * @param auth_value_add value to be added to each chain pointer+ *+ * @throws MemoryAccessException IO problem reading file+ * @throws CancelledException user cancels+ */+ private void processPointerChain(DyldChainedFixupHeader chainHeader,+ List<Address> unchainedLocList, DyldChainType pointerFormat, long page, long nextOff,+ long auth_value_add) throws MemoryAccessException, CancelledException {++ long imageBaseOffset = program.getImageBase().getOffset();+ Address chainStart = memory.getProgram().getLanguage().getDefaultSpace().getAddress(page);++ long next = -1;+ boolean start = true;+ while (next != 0) {+ monitor.checkCancelled();++ Address chainLoc = chainStart.add(nextOff);+ final long chainValue = DyldChainedPtr.getChainValue(memory, chainLoc, pointerFormat);+ long newChainValue = chainValue;++ boolean isAuthenticated = DyldChainedPtr.isAuthenticated(pointerFormat, chainValue);+ boolean isBound = DyldChainedPtr.isBound(pointerFormat, chainValue);++ String symName = null;++ if (isAuthenticated && !isBound) {+ long offsetFromSharedCacheBase =+ DyldChainedPtr.getTarget(pointerFormat, chainValue);+ //long diversityData = DyldChainedPtr.getDiversity(pointerFormat, chainValue);+ //boolean hasAddressDiversity =+ // DyldChainedPtr.hasAddrDiversity(pointerFormat, chainValue);+ //long key = DyldChainedPtr.getKey(pointerFormat, chainValue);+ newChainValue = imageBaseOffset + offsetFromSharedCacheBase + auth_value_add;+ }+ else if (!isAuthenticated && isBound) {+ int chainOrdinal = (int) DyldChainedPtr.getOrdinal(pointerFormat, chainValue);+ long addend = DyldChainedPtr.getAddend(pointerFormat, chainValue);+ DyldChainedImports chainedImports = chainHeader.getChainedImports();+ DyldChainedImport chainedImport = chainedImports.getChainedImport(chainOrdinal);+ //int libOrdinal = chainedImport.getLibOrdinal();+ symName = chainedImport.getName();+ // lookup the symbol, and then add addend+ List<Symbol> globalSymbols = program.getSymbolTable().getGlobalSymbols(symName);+ if (globalSymbols.size() == 1) {+ newChainValue = globalSymbols.get(0).getAddress().getOffset();+ }+ newChainValue += addend;+ }+ else if (isAuthenticated && isBound) {+ int chainOrdinal = (int) DyldChainedPtr.getOrdinal(pointerFormat, chainValue);+ //long addend = DyldChainedPtr.getAddend(pointerFormat, chainValue);+ //long diversityData = DyldChainedPtr.getDiversity(pointerFormat, chainValue);+ //boolean hasAddressDiversity =+ // DyldChainedPtr.hasAddrDiversity(pointerFormat, chainValue);+ //long key = DyldChainedPtr.getKey(pointerFormat, chainValue);++ DyldChainedImports chainedImports = chainHeader.getChainedImports();+ DyldChainedImport chainedImport = chainedImports.getChainedImport(chainOrdinal);+ symName = chainedImport.getName();++ // lookup the symbol, and then add addend+ List<Symbol> globalSymbols = program.getSymbolTable().getGlobalSymbols(symName);+ if (globalSymbols.size() == 1) {+ newChainValue = globalSymbols.get(0).getAddress().getOffset();+ }+ newChainValue = newChainValue + auth_value_add;+ }+ else {+ newChainValue = DyldChainedPtr.getTarget(pointerFormat, chainValue);+ if (DyldChainedPtr.isRelative(pointerFormat)) {+ newChainValue += imageBaseOffset;+ }+ }++ if (!start || !program.getRelocationTable().hasRelocation(chainLoc)) {+ int byteLength = 0;+ Status status = Status.FAILURE;+ try {+ RelocationResult result =+ DyldChainedPtr.setChainValue(memory, chainLoc, pointerFormat,+ newChainValue);+ status = result.status();+ byteLength = result.byteLength();+ }+ finally {+ if (shouldAddChainedFixupsRelocations) {+ program.getRelocationTable()+ .add(chainLoc, status,+ (start ? 0x8000 : 0x4000) | (isAuthenticated ? 4 : 0) |+ (isBound ? 2 : 0) | 1,+ new long[] { newChainValue }, byteLength, symName);+ }+ }+ }+ // delay creating data until after memory has been changed+ unchainedLocList.add(chainLoc);++ start = false;+ next = DyldChainedPtr.getNext(pointerFormat, chainValue);+ nextOff += next * DyldChainedPtr.getStride(pointerFormat);+ }+ }++ /**+ * Fixes up any chained pointers, starting at the given address.+ *+ * @param chainStart The starting of address of the pointer chain to fix.+ * @param nextOffSize The size of the next offset.+ * @return A list of addresses where pointer fixes were performed.+ * @throws MemoryAccessException if there was a problem reading/writing memory.+ */+ private List<Address> processPointerChain(Address chainStart, long nextOffSize)+ throws MemoryAccessException {+ List<Address> fixedAddresses = new ArrayList<>();++ while (!monitor.isCancelled()) {+ long chainValue = memory.getLong(chainStart);++ fixupPointer(chainStart, chainValue);+ fixedAddresses.add(chainStart);++ long nextValueOff = ((chainValue >> 51L) & 0x7ffL) * nextOffSize;+ if (nextValueOff == 0) {+ break;+ }+ chainStart = chainStart.add(nextValueOff);+ }++ return fixedAddresses;+ }++ /**+ * Fixes up the pointer at the given address.+ *+ * @param pointerAddr The address of the pointer to fix.+ * @param pointerValue The value at the address of the pointer to fix.+ * @throws MemoryAccessException if there was a problem reading/writing memory.+ */+ private void fixupPointer(Address pointerAddr, long pointerValue) throws MemoryAccessException {++ final long BIT63 = (0x1L << 63);+ final long BIT62 = (0x1L << 62);++ // Bad chain value+ if ((pointerValue & BIT62) != 0) {+ // this is a pointer, but is good now+ }++ long fixedPointerValue = 0;+ long fixedPointerType = 0;++ // Pointer checked value+ if ((pointerValue & BIT63) != 0) {+ //long tagType = (pointerValue >> 49L) & 0x3L;+ long pacMod = ((pointerValue >> 32) & 0xffff);+ fixedPointerType = pacMod;+ fixedPointerValue = program.getImageBase().getOffset() + (pointerValue & 0xffffffffL);+ }+ else {+ fixedPointerValue =+ ((pointerValue << 13) & 0xff00000000000000L) | (pointerValue & 0x7ffffffffffL);+ if ((pointerValue & 0x40000000000L) != 0) {+ fixedPointerValue |= 0xfffc0000000000L;+ }+ }++ // Add entry to relocation table for the pointer fixup+ byte origBytes[] = new byte[8];+ memory.getBytes(pointerAddr, origBytes);++ boolean success = false;+ try {+ // Fixup the pointer+ memory.setLong(pointerAddr, fixedPointerValue);+ success = true;+ }+ finally {+ Status status = success ? Status.APPLIED : Status.FAILURE;+ program.getRelocationTable()+ .add(pointerAddr, status, (int) fixedPointerType,+ new long[] { fixedPointerValue },+ origBytes, null);+ }+ }+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedImport.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedImport.javasimilarity index 95%rename from Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedImport.javarename to Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedImport.javaindex 3200e2ed24..2fbee724de 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedImport.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedImport.java@@ -13,7 +13,7 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package ghidra.app.util.bin.format.macho.commands;+package ghidra.app.util.bin.format.macho.commands.chained;import java.io.IOException;@@ -26,7 +26,7 @@ import ghidra.util.exception.DuplicateNameException;/*** Represents a dyld_chained_import structure.*- * @see <a href="https://opensource.apple.com/source/dyld/dyld-852.2/include/mach-o/fixup-chains.h.auto.html">mach-o/fixup-chains.h</a>+ * @see <a href="https://github.com/apple-oss-distributions/dyld/blob/main/include/mach-o/fixup-chains.h">mach-o/fixup-chains.h</a>*/public class DyldChainedImport implements StructConverter {private static final int DYLD_CHAINED_IMPORT = 1;diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedImports.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedImports.javasimilarity index 75%rename from Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedImports.javarename to Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedImports.javaindex 5f609bcfd1..e6170aad12 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedImports.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedImports.java@@ -13,7 +13,7 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package ghidra.app.util.bin.format.macho.commands;+package ghidra.app.util.bin.format.macho.commands.chained;import java.io.IOException;import java.util.ArrayList;@@ -27,25 +27,25 @@ import ghidra.util.exception.DuplicateNameException;/*** Represents a dyld_chained_import array.*- * @see <a href="https://opensource.apple.com/source/dyld/dyld-852.2/include/mach-o/fixup-chains.h.auto.html">mach-o/fixup-chains.h</a>+ * @see <a href="https://github.com/apple-oss-distributions/dyld/blob/main/include/mach-o/fixup-chains.h">mach-o/fixup-chains.h</a>*/public class DyldChainedImports implements StructConverter {- private int imports_count;- private int imports_format;- private long imports_offset;+ private int importsCount;+ private int importsFormat;+ private long importsOffset;private DyldChainedImport chainedImports[];DyldChainedImports(BinaryReader reader, DyldChainedFixupHeader cfh) throws IOException {long ptrIndex = reader.getPointerIndex();- imports_offset = ptrIndex;+ importsOffset = ptrIndex;- this.imports_count = cfh.getImports_count();- this.imports_format = cfh.getImports_format();+ this.importsCount = cfh.getImportsCount();+ this.importsFormat = cfh.getImportsFormat();ArrayList<DyldChainedImport> starts = new ArrayList<>();- for (int i = 0; i < imports_count; i++) {- starts.add(new DyldChainedImport(reader, cfh, imports_format));+ for (int i = 0; i < importsCount; i++) {+ starts.add(new DyldChainedImport(reader, cfh, importsFormat));}chainedImports = starts.toArray(DyldChainedImport[]::new);}@@ -54,17 +54,17 @@ public class DyldChainedImports implements StructConverter {public DataType toDataType() throws DuplicateNameException, IOException {DataType chainedImportDt = chainedImports[0].toDataType();DataType dt =- new ArrayDataType(chainedImportDt, imports_count, chainedImportDt.getLength());+ new ArrayDataType(chainedImportDt, importsCount, chainedImportDt.getLength());return dt;}public int getImportsCount() {- return imports_count;+ return importsCount;}public long getImportsOffset() {- return imports_offset;+ return importsOffset;}public DyldChainedImport[] getChainedImports() {@@ -72,7 +72,7 @@ public class DyldChainedImports implements StructConverter {}public DyldChainedImport getChainedImport(int ordinal) {- if (ordinal < 0 || ordinal >= imports_count) {+ if (ordinal < 0 || ordinal >= importsCount) {return null;}return chainedImports[ordinal];diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedStartsInImage.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedStartsInImage.javasimilarity index 52%rename from Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedStartsInImage.javarename to Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedStartsInImage.javaindex cd0d104e9b..8177c7152e 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedStartsInImage.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedStartsInImage.java@@ -13,10 +13,11 @@* See the License for the specific language governing permissions and* limitations under the License.*/-package ghidra.app.util.bin.format.macho.commands;+package ghidra.app.util.bin.format.macho.commands.chained;import java.io.IOException;import java.util.ArrayList;+import java.util.List;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;@@ -27,56 +28,56 @@ import ghidra.util.exception.DuplicateNameException;/*** Represents a dyld_chained_starts_in_image structure.*- * @see <a href="https://opensource.apple.com/source/dyld/dyld-852.2/include/mach-o/fixup-chains.h.auto.html">mach-o/fixup-chains.h</a>+ * @see <a href="https://github.com/apple-oss-distributions/dyld/blob/main/include/mach-o/fixup-chains.h">mach-o/fixup-chains.h</a>*/public class DyldChainedStartsInImage implements StructConverter {- private int seg_count; // count of segment chain starts- private int seg_info_offset[];+ private int segCount;+ private int[] segInfoOffset;- private DyldChainedStartsInSegment chainedStarts[];+ private List<DyldChainedStartsInSegment> chainedStarts;- DyldChainedStartsInImage(BinaryReader reader) throws IOException {+ /**+ * Creates a new {@link DyldChainedStartsInImage}+ *+ * @param reader A {@link BinaryReader} positioned at the start of the structure+ * @throws IOException if there was an IO-related problem creating the structure+ */+ public DyldChainedStartsInImage(BinaryReader reader) throws IOException {long ptrIndex = reader.getPointerIndex();- seg_count = reader.readNextInt();- seg_info_offset = reader.readNextIntArray(seg_count);+ segCount = reader.readNextInt();+ segInfoOffset = reader.readNextIntArray(segCount);- ArrayList<DyldChainedStartsInSegment> starts = new ArrayList<>();- for (int off : seg_info_offset) {-- // off == 0 means there is no associated starts_in_segment entry- if (off == 0) {- continue;+ chainedStarts = new ArrayList<>();+ for (int offset : segInfoOffset) {+ if (offset != 0) {+ reader.setPointerIndex(ptrIndex + offset);+ chainedStarts.add(new DyldChainedStartsInSegment(reader));}-- reader.setPointerIndex(ptrIndex + off);- starts.add(new DyldChainedStartsInSegment(reader));}- chainedStarts = starts.toArray(DyldChainedStartsInSegment[]::new);}@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {StructureDataType struct = new StructureDataType("dyld_chained_starts_in_image", 0);-struct.add(DWORD, "seg_count", null);- struct.add(new ArrayDataType(DWORD, seg_count, 1), "seg_info_offset", "");-+ struct.add(new ArrayDataType(DWORD, segCount, 1), "seg_info_offset",+ "each entry is offset into this struct for that segment followed by pool of dyld_chain_starts_in_segment data");struct.setCategoryPath(new CategoryPath(MachConstants.DATA_TYPE_CATEGORY));return struct;}- public int getSeg_count() {- return seg_count;+ public int getSegCount() {+ return segCount;}- public int[] getSeg_info_offset() {- return seg_info_offset;+ public int[] getSegInfoOffset() {+ return segInfoOffset;}- public DyldChainedStartsInSegment[] getChainedStarts() {+ public List<DyldChainedStartsInSegment> getChainedStarts() {return chainedStarts;}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedStartsInSegment.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedStartsInSegment.javanew file mode 100644index 0000000000..7034f60a61--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedStartsInSegment.java@@ -0,0 +1,102 @@+/* ###+ * 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.bin.format.macho.commands.chained;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;+import ghidra.app.util.bin.format.macho.MachConstants;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * Represents a dyld_chained_starts_in_segment structure.+ *+ * @see <a href="https://github.com/apple-oss-distributions/dyld/blob/main/include/mach-o/fixup-chains.h">mach-o/fixup-chains.h</a>+ */+public class DyldChainedStartsInSegment implements StructConverter {++ private int size;+ private short pageSize;+ private short pointerFormat;+ private long segmentOffset;+ private int maxValidPointer;+ private short pageCount;++ private short[] pageStarts;++ /**+ * Creates a new {@link DyldChainedStartsInSegment}+ *+ * @param reader A {@link BinaryReader} positioned at the start of the structure+ * @throws IOException if there was an IO-related problem creating the structure+ */+ public DyldChainedStartsInSegment(BinaryReader reader) throws IOException {+ size = reader.readNextInt();+ pageSize = reader.readNextShort();+ pointerFormat = reader.readNextShort();+ segmentOffset = reader.readNextLong();+ maxValidPointer = reader.readNextInt();+ pageCount = reader.readNextShort();++ pageStarts = reader.readNextShortArray(pageCount);+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ StructureDataType struct = new StructureDataType("dyld_chained_starts_in_segment", 0);+ struct.add(DWORD, "size", "size of this (amount kernel needs to copy)");+ struct.add(WORD, "page_size", "0x1000 or 0x4000");+ struct.add(WORD, "pointer_format", "DYLD_CHAINED_PTR_*");+ struct.add(IBO64, "segment_offset", "offset in memory to start of segment");+ struct.add(DWORD, "max_valid_pointer",+ "for 32-bit OS, any value beyond this is not a pointer");+ struct.add(WORD, "page_count", "how many pages are in array");+ struct.add(new ArrayDataType(WORD, pageCount, 1), "page_starts",+ "each entry is offset in each page of first element in chain or DYLD_CHAINED_PTR_START_NONE if no fixups on page");+ struct.setCategoryPath(new CategoryPath(MachConstants.DATA_TYPE_CATEGORY));+ return struct;+ }++ public int getSize() {+ return size;+ }++ public short getPageSize() {+ return pageSize;+ }++ public short getPointerFormat() {+ return pointerFormat;+ }++ public long getSegmentOffset() {+ return segmentOffset;+ }++ public int getMaxValidPointer() {+ return maxValidPointer;+ }++ public short getPageCount() {+ return pageCount;+ }++ public short[] getPageStarts() {+ return pageStarts;+ }+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/dyld/DyldCacheLocalSymbolsInfo.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/dyld/DyldCacheLocalSymbolsInfo.javaindex bb53fc231a..8bdf237227 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/dyld/DyldCacheLocalSymbolsInfo.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/dyld/DyldCacheLocalSymbolsInfo.java@@ -108,7 +108,7 @@ public class DyldCacheLocalSymbolsInfo implements StructConverter {MessageLog log) throws CancelledException {markupLocalSymbols(program, localSymbolsInfoAddr, monitor, log);- // Not worth marking up the huge NList in production code. Keep it commented for debugging.+ // TODO: This is slow and not too useful. Add an option for it.//markupNList(program, localSymbolsInfoAddr, monitor, log);}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/threadcommand/ThreadCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/threadcommand/ThreadCommand.javaindex 162fa5cea6..e8ce1c9300 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/threadcommand/ThreadCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/threadcommand/ThreadCommand.java@@ -20,14 +20,9 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.macho.*;import ghidra.app.util.bin.format.macho.commands.LoadCommand;-import ghidra.app.util.importer.MessageLog;-import ghidra.program.flatapi.FlatProgramAPI;-import ghidra.program.model.address.Address;import ghidra.program.model.data.*;-import ghidra.program.model.listing.ProgramModule;import ghidra.util.Msg;import ghidra.util.exception.DuplicateNameException;-import ghidra.util.task.TaskMonitor;/*** Represents a thread_command structure@@ -110,20 +105,4 @@ public class ThreadCommand extends LoadCommand {public String getCommandName() {return "thread_command";}-- @Override- public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,- ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {- updateMonitor(monitor);- try {- if (isBinary) {- createFragment(api, baseAddress, parentModule);- Address addr = baseAddress.getNewAddress(getStartIndex());- api.createData(addr, toDataType());- }- }- catch (Exception e) {- log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());- }- }}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/DyldCacheProgramBuilder.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/DyldCacheProgramBuilder.javaindex 28194636fb..f7de0cdda9 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/DyldCacheProgramBuilder.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/DyldCacheProgramBuilder.java@@ -441,6 +441,9 @@ public class DyldCacheProgramBuilder extends MachoProgramBuilder {if (!name.isEmpty()) {listing.setComment(headerAddr, CodeUnit.PLATE_COMMENT, path);}++ // TODO: This can be slow. Add an option for it.+ //DyldCacheProgramBuilder.this.markupLoadCommandData(header);}/**diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoPrelinkProgramBuilder.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoPrelinkProgramBuilder.javaindex 9379236ae7..1636090147 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoPrelinkProgramBuilder.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoPrelinkProgramBuilder.java@@ -110,7 +110,7 @@ public class MachoPrelinkProgramBuilder extends MachoProgramBuilder {}// Do things that needed to wait until after the inner Mach-O's are processed- super.markupChainedFixups(chainedFixups);+ super.markupChainedFixups(machoHeader, chainedFixups);}/**@@ -185,7 +185,8 @@ public class MachoPrelinkProgramBuilder extends MachoProgramBuilder {}@Override- protected void markupChainedFixups(List<Address> fixups) throws CancelledException {+ protected void markupChainedFixups(MachHeader header, List<Address> fixups)+ throws CancelledException {// Just save the list.// We need to delay doing the markup until after we process all the inner Mach-O's.this.chainedFixups = fixups;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 0d161a9589..e83397a2a5 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@@ -15,8 +15,6 @@*/package ghidra.app.util.opinion;-import static ghidra.app.util.bin.format.macho.dyld.DyldChainedPtr.*;-import java.math.BigInteger;import java.util.*;@@ -27,9 +25,8 @@ import ghidra.app.util.bin.format.RelocationException;import ghidra.app.util.bin.format.macho.*;import ghidra.app.util.bin.format.macho.commands.*;import ghidra.app.util.bin.format.macho.commands.ExportTrie.ExportEntry;+import ghidra.app.util.bin.format.macho.commands.chained.DyldChainedFixups;import ghidra.app.util.bin.format.macho.commands.dyld.*;-import ghidra.app.util.bin.format.macho.dyld.DyldChainedPtr;-import ghidra.app.util.bin.format.macho.dyld.DyldChainedPtr.DyldChainType;import ghidra.app.util.bin.format.macho.relocation.*;import ghidra.app.util.bin.format.macho.threadcommand.ThreadCommand;import ghidra.app.util.bin.format.objectiveC.ObjectiveC1_Constants;@@ -125,32 +122,42 @@ public class MachoProgramBuilder {machoHeader.parse();monitor.setCancelEnabled(true);+ // Setup memorysetImageBase();- processEncryption();- processEntryPoint();processMemoryBlocks(machoHeader, provider.getName(), true, true);fixupProgramTree();- processUnsupportedLoadCommands();++ // Process load commands+ processEntryPoint();boolean exportsFound = processExports(machoHeader);processSymbolTables(machoHeader, !exportsFound);processIndirectSymbols();- setRelocatableProperty();- processLibraries();- processProgramDescription();- renameObjMsgSendRtpSymbol();processUndefinedSymbols();processAbsoluteSymbols();- List<Address> chainedFixups = processChainedFixups();+ List<Address> chainedFixups = processChainedFixups(machoHeader);processBindings(false);- markupHeaders(machoHeader, setupHeaderAddr(machoHeader.getAllSegments()));- markupSections();- processProgramVars();processSectionRelocations();processExternalRelocations();processLocalRelocations();- markupChainedFixups(chainedFixups);- }+ processLibraries();+ processEncryption();+ processUnsupportedLoadCommands();++ // Markup structures+ markupHeaders(machoHeader, setupHeaderAddr(machoHeader.getAllSegments()));+ markupSections();+ markupLoadCommandData(machoHeader);+ markupChainedFixups(machoHeader, chainedFixups);+ markupProgramVars();++ // Set program info+ setRelocatableProperty();+ setProgramDescription();+ // Perform additional actions+ renameObjMsgSendRtpSymbol();+ }+/*** Sets the image base*@@ -176,63 +183,6 @@ public class MachoProgramBuilder {program.setImageBase(space.getAddress(0), true);}}-- /**- * Logs encrypted block ranges- *- * @throws Exception if there was a problem detecting the encrypted block ranges- */- protected void processEncryption() throws Exception {- monitor.setMessage("Processing encryption...");- for (EncryptedInformationCommand cmd : machoHeader- .getLoadCommands(EncryptedInformationCommand.class)) {- if (cmd.getCryptID() != 0) {- log.appendMsg(String.format("ENCRYPTION DETECTED: (file offset 0x%x, size 0x%x)",- cmd.getCryptOffset(), cmd.getCryptSize()));- }- }- }-- /**- * Attempts to discover and set the entry point.- *- * @throws Exception If there was a problem discovering or setting the entry point.- */- protected void processEntryPoint() throws Exception {- monitor.setMessage("Processing entry point...");- Address entryPointAddr = null;-- EntryPointCommand entryPointCommand =- machoHeader.getFirstLoadCommand(EntryPointCommand.class);- if (entryPointCommand != null) {- long offset = entryPointCommand.getEntryOffset();- if (offset > 0) {- SegmentCommand segment = machoHeader.getSegment("__TEXT");- if (segment != null) {- entryPointAddr = space.getAddress(segment.getVMaddress()).add(offset);- }- }- }-- if (entryPointAddr == null) {- ThreadCommand threadCommand = machoHeader.getFirstLoadCommand(ThreadCommand.class);- if (threadCommand != null) {- long pointer = threadCommand.getInitialInstructionPointer();- if (pointer != -1) {- entryPointAddr = space.getAddress(pointer);- }- }- }-- if (entryPointAddr != null) {- program.getSymbolTable().createLabel(entryPointAddr, "entry", SourceType.IMPORTED);- program.getSymbolTable().addExternalEntryPoint(entryPointAddr);- createOneByteFunction("entry", entryPointAddr);- }- else {- log.appendMsg("Unable to determine entry point.");- }- }/*** Creates memory blocks for the given header.@@ -467,18 +417,45 @@ public class MachoProgramBuilder {}/**- * Processes {@link LoadCommand}s that we haven't implemented yet.- *- * @throws CancelledException if the operation was cancelled.- */- protected void processUnsupportedLoadCommands() throws CancelledException {- monitor.setMessage("Processing unsupported load commands...");+ * Attempts to discover and set the entry point.+ *+ * @throws Exception If there was a problem discovering or setting the entry point.+ */+ protected void processEntryPoint() throws Exception {+ monitor.setMessage("Processing entry point...");+ Address entryPointAddr = null;- for (LoadCommand loadCommand : machoHeader.getLoadCommands(UnsupportedLoadCommand.class)) {- monitor.checkCancelled();- log.appendMsg(loadCommand.getCommandName());- }- }+ EntryPointCommand entryPointCommand =+ machoHeader.getFirstLoadCommand(EntryPointCommand.class);+ if (entryPointCommand != null) {+ long offset = entryPointCommand.getEntryOffset();+ if (offset > 0) {+ SegmentCommand segment = machoHeader.getSegment("__TEXT");+ if (segment != null) {+ entryPointAddr = space.getAddress(segment.getVMaddress()).add(offset);+ }+ }+ }++ if (entryPointAddr == null) {+ ThreadCommand threadCommand = machoHeader.getFirstLoadCommand(ThreadCommand.class);+ if (threadCommand != null) {+ long pointer = threadCommand.getInitialInstructionPointer();+ if (pointer != -1) {+ entryPointAddr = space.getAddress(pointer);+ }+ }+ }++ if (entryPointAddr != null) {+ program.getSymbolTable().createLabel(entryPointAddr, "entry", SourceType.IMPORTED);+ program.getSymbolTable().addExternalEntryPoint(entryPointAddr);+ createOneByteFunction("entry", entryPointAddr);+ }+ else {+ log.appendMsg("Unable to determine entry point.");+ }+ }protected boolean processExports(MachHeader header) throws Exception {monitor.setMessage("Processing exports...");@@ -511,9 +488,9 @@ public class MachoProgramBuilder {Address baseAddr = space.getAddress(textSegment.getVMaddress());for (ExportEntry export : exports) {- String name = SymbolUtilities.replaceInvalidChars(export.getName(), true);+ String name = SymbolUtilities.replaceInvalidChars(export.name(), true);try {- Address exportAddr = baseAddr.add(export.getAddress());+ Address exportAddr = baseAddr.add(export.address());program.getSymbolTable().addExternalEntryPoint(exportAddr);program.getSymbolTable().createLabel(exportAddr, name, SourceType.IMPORTED);}@@ -672,99 +649,6 @@ public class MachoProgramBuilder {}}- protected void setRelocatableProperty() {- Options props = program.getOptions(Program.PROGRAM_INFO);- switch (machoHeader.getFileType()) {- case MachHeaderFileTypes.MH_EXECUTE:- props.setBoolean(RelocationTable.RELOCATABLE_PROP_NAME, false);- break;- default:- props.setBoolean(RelocationTable.RELOCATABLE_PROP_NAME, true);- break;- }- }-- protected void processLibraries() throws Exception {- monitor.setMessage("Processing libraries...");-- Options props = program.getOptions(Program.PROGRAM_INFO);- int libraryIndex = 0;-- for (LoadCommand command : machoHeader.getLoadCommands()) {- if (monitor.isCancelled()) {- return;- }-- String libraryPath = null;-- if (command instanceof DynamicLibraryCommand dylibCommand) {- DynamicLibrary dylib = dylibCommand.getDynamicLibrary();- libraryPath = dylib.getName().getString();- }- else if (command instanceof SubLibraryCommand sublibCommand) {- libraryPath = sublibCommand.getSubLibraryName().getString();- }- else if (command instanceof PreboundDynamicLibraryCommand pbdlCommand) {- libraryPath = pbdlCommand.getLibraryName();- }-- if (libraryPath != null) {- // For now, strip off the full path and just the use the filename. We will utilize- // the full path one day when we started looking in dyld_shared_cache files for- // libraries.- int index = libraryPath.lastIndexOf("/");- String libraryName = index != -1 ? libraryPath.substring(index + 1) : libraryPath;- if (!libraryName.equals(program.getName())) {- addLibrary(libraryName);- props.setString(- ExternalSymbolResolver.getRequiredLibraryProperty(libraryIndex++),- libraryName);- }- }- }-- program.getSymbolTable().createExternalLibrary(Library.UNKNOWN, SourceType.IMPORTED);- }-- protected void processProgramDescription() {- Options props = program.getOptions(Program.PROGRAM_INFO);- props.setString("Mach-O File Type",- MachHeaderFileTypes.getFileTypeName(machoHeader.getFileType()));- props.setString("Mach-O File Type Description",- MachHeaderFileTypes.getFileTypeDescription(machoHeader.getFileType()));- List<String> flags = MachHeaderFlags.getFlags(machoHeader.getFlags());- for (int i = 0; i < flags.size(); ++i) {- props.setString("Mach-O Flag " + i, flags.get(i));- }-- List<SubUmbrellaCommand> umbrellas = machoHeader.getLoadCommands(SubUmbrellaCommand.class);- for (int i = 0; i < umbrellas.size(); ++i) {- props.setString("Mach-O Sub-umbrella " + i,- umbrellas.get(i).getSubUmbrellaFrameworkName().getString());- }-- List<SubFrameworkCommand> frameworks =- machoHeader.getLoadCommands(SubFrameworkCommand.class);- for (int i = 0; i < frameworks.size(); ++i) {- props.setString("Mach-O Sub-framework " + i,- frameworks.get(i).getUmbrellaFrameworkName().getString());- }- }-- protected void renameObjMsgSendRtpSymbol()- throws DuplicateNameException, InvalidInputException {- Address address = space.getAddress(ObjectiveC1_Constants.OBJ_MSGSEND_RTP);- Symbol symbol = program.getSymbolTable().getPrimarySymbol(address);- if (symbol != null && symbol.isDynamic()) {- symbol.setName(ObjectiveC1_Constants.OBJC_MSG_SEND_RTP_NAME, SourceType.IMPORTED);- }- else {- program.getSymbolTable()- .createLabel(address, ObjectiveC1_Constants.OBJC_MSG_SEND_RTP_NAME,- SourceType.IMPORTED);- }- }-protected void processUndefinedSymbols() throws Exception {monitor.setMessage("Processing undefined symbols...");@@ -878,6 +762,12 @@ public class MachoProgramBuilder {}}+ public List<Address> processChainedFixups(MachHeader header) throws Exception {+ DyldChainedFixups dyldChainedFixups =+ new DyldChainedFixups(program, header, shouldAddChainedFixupsRelocations, log, monitor);+ return dyldChainedFixups.processChainedFixups();+ }+protected void processBindings(boolean doClassic) {List<DyldInfoCommand> commands = machoHeader.getLoadCommands(DyldInfoCommand.class);for (DyldInfoCommand command : commands) {@@ -944,6 +834,8 @@ public class MachoProgramBuilder {DataType loadCommandDataType = loadCommand.toDataType();DataUtilities.createData(program, loadCommandAddr, loadCommandDataType, -1,DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ listing.setComment(loadCommandAddr, CodeUnit.PRE_COMMENT,+ LoadCommandTypes.getLoadCommandName(loadCommand.getCommandType()));if (loadCommand instanceof SegmentCommand) {SegmentCommand segmentCommand = (SegmentCommand) loadCommand;@@ -1147,120 +1039,43 @@ public class MachoProgramBuilder {}/**- * See crt.c from opensource.apple.com- */- protected void processProgramVars() {- if (program.getLanguage().getProcessor() == Processor- .findOrPossiblyCreateProcessor("PowerPC")) {- return;+ * Processes the section relocations from all {@link Section}s.+ *+ * @throws CancelledException if the operation was cancelled.+ */+ protected void processSectionRelocations() throws CancelledException {+ monitor.setMessage("Processing section relocations...");++ LinkedHashMap<RelocationInfo, Address> relocationMap = new LinkedHashMap<>();+ for (Section section : machoHeader.getAllSections()) {+ monitor.checkCancelled();++ MemoryBlock sectionMemoryBlock = getMemoryBlock(section);+ if (sectionMemoryBlock == null) {+ if (section.getNumberOfRelocations() > 0) {+ log.appendMsg("Unable to process relocations for " + section.getSectionName() ++ ". No memory block was created.");+ }+ continue;+ }++ for (RelocationInfo relocationInfo : section.getRelocations()) {+ monitor.checkCancelled();+ Address address = sectionMemoryBlock.getStart().add(relocationInfo.getAddress());+ relocationMap.put(relocationInfo, address);+ }}+ performRelocations(relocationMap);+ }- SymbolTable symbolTable = program.getSymbolTable();+ /**+ * Processes the external relocations from all {@link DynamicSymbolTableCommand}s.+ *+ * @throws CancelledException if the operation was cancelled.+ */+ protected void processExternalRelocations() throws CancelledException {- int defaultPointerSize = program.getDefaultPointerSize();-- DataType intDataType =- (defaultPointerSize == 8) ? new QWordDataType() : new DWordDataType();- DataType intPointerDataType = PointerDataType.getPointer(intDataType, defaultPointerSize);//int *- DataType voidPointerDatatype =- PointerDataType.getPointer(new VoidDataType(), defaultPointerSize);//void *- DataType charPointerX1DataType =- PointerDataType.getPointer(new CharDataType(), defaultPointerSize);//char *- DataType charPointerX2DataType =- PointerDataType.getPointer(charPointerX1DataType, defaultPointerSize);//char **- DataType charPointerX3DataType =- PointerDataType.getPointer(charPointerX2DataType, defaultPointerSize);//char ***-- Structure structure = new StructureDataType(SectionNames.PROGRAM_VARS, 0);- structure.add(voidPointerDatatype, "mh", "pointer to __mh_execute_header");- structure.add(intPointerDataType, "NXArgcPtr", "pointer to argc");- structure.add(charPointerX3DataType, "NXArgvPtr", "pointer to argv");- structure.add(charPointerX3DataType, "environPtr", "pointer to environment");- structure.add(charPointerX2DataType, "__prognamePtr", "pointer to program name");-- Namespace namespace = createNamespace(SectionNames.PROGRAM_VARS);-- List<Section> sections = machoHeader.getAllSections();- for (Section section : sections) {- if (section.getSectionName().equals(SectionNames.PROGRAM_VARS)) {- MemoryBlock memoryBlock = getMemoryBlock(section);- try {- listing.createData(memoryBlock.getStart(), structure);- Data data = listing.getDataAt(memoryBlock.getStart());-- Data mhData = data.getComponent(0);- if (symbolTable.getSymbol("__mh_execute_header", mhData.getAddress(0),- namespace) == null) {- symbolTable.createLabel(mhData.getAddress(0), "__mh_execute_header",- namespace, SourceType.IMPORTED);- }-- Data argcData = data.getComponent(1);- symbolTable.createLabel(argcData.getAddress(0), "NXArgc", namespace,- SourceType.IMPORTED);- listing.createData(argcData.getAddress(0), intDataType);-- Data argvData = data.getComponent(2);- symbolTable.createLabel(argvData.getAddress(0), "NXArgv", namespace,- SourceType.IMPORTED);- listing.createData(argvData.getAddress(0), charPointerX2DataType);-- Data environData = data.getComponent(3);- symbolTable.createLabel(environData.getAddress(0), "environ", namespace,- SourceType.IMPORTED);- listing.createData(environData.getAddress(0), charPointerX2DataType);-- Data prognameData = data.getComponent(4);- symbolTable.createLabel(prognameData.getAddress(0), "__progname", namespace,- SourceType.IMPORTED);- listing.createData(prognameData.getAddress(0), charPointerX1DataType);- }- catch (Exception e) {- log.appendException(e);- return;- }- }- }- }-- /**- * Processes the section relocations from all {@link Section}s.- *- * @throws CancelledException if the operation was cancelled.- */- protected void processSectionRelocations() throws CancelledException {- monitor.setMessage("Processing section relocations...");-- LinkedHashMap<RelocationInfo, Address> relocationMap = new LinkedHashMap<>();- for (Section section : machoHeader.getAllSections()) {- monitor.checkCancelled();-- MemoryBlock sectionMemoryBlock = getMemoryBlock(section);- if (sectionMemoryBlock == null) {- if (section.getNumberOfRelocations() > 0) {- log.appendMsg("Unable to process relocations for " + section.getSectionName() +- ". No memory block was created.");- }- continue;- }-- for (RelocationInfo relocationInfo : section.getRelocations()) {- monitor.checkCancelled();- Address address = sectionMemoryBlock.getStart().add(relocationInfo.getAddress());- relocationMap.put(relocationInfo, address);- }- }- performRelocations(relocationMap);- }-- /**- * Processes the external relocations from all {@link DynamicSymbolTableCommand}s.- *- * @throws CancelledException if the operation was cancelled.- */- protected void processExternalRelocations() throws CancelledException {-- monitor.setMessage("Processing external relocations...");+ monitor.setMessage("Processing external relocations...");LinkedHashMap<RelocationInfo, Address> relocationMap = new LinkedHashMap<>();for (DynamicSymbolTableCommand cmd : machoHeader@@ -1295,12 +1110,84 @@ public class MachoProgramBuilder {performRelocations(relocationMap);}+ protected void processLibraries() throws Exception {+ monitor.setMessage("Processing libraries...");++ Options props = program.getOptions(Program.PROGRAM_INFO);+ int libraryIndex = 0;++ for (LoadCommand command : machoHeader.getLoadCommands()) {+ if (monitor.isCancelled()) {+ return;+ }++ String libraryPath = null;++ if (command instanceof DynamicLibraryCommand dylibCommand) {+ DynamicLibrary dylib = dylibCommand.getDynamicLibrary();+ libraryPath = dylib.getName().getString();+ }+ else if (command instanceof SubLibraryCommand sublibCommand) {+ libraryPath = sublibCommand.getSubLibraryName().getString();+ }+ else if (command instanceof PreboundDynamicLibraryCommand pbdlCommand) {+ libraryPath = pbdlCommand.getLibraryName();+ }++ if (libraryPath != null) {+ // For now, strip off the full path and just the use the filename. We will utilize+ // the full path one day when we started looking in dyld_shared_cache files for+ // libraries.+ int index = libraryPath.lastIndexOf("/");+ String libraryName = index != -1 ? libraryPath.substring(index + 1) : libraryPath;+ if (!libraryName.equals(program.getName())) {+ addLibrary(libraryName);+ props.setString(+ ExternalSymbolResolver.getRequiredLibraryProperty(libraryIndex++),+ libraryName);+ }+ }+ }++ program.getSymbolTable().createExternalLibrary(Library.UNKNOWN, SourceType.IMPORTED);+ }++ /**+ * Logs encrypted block ranges+ *+ * @throws Exception if there was a problem detecting the encrypted block ranges+ */+ protected void processEncryption() throws Exception {+ monitor.setMessage("Processing encryption...");+ for (EncryptedInformationCommand cmd : machoHeader+ .getLoadCommands(EncryptedInformationCommand.class)) {+ if (cmd.getCryptID() != 0) {+ log.appendMsg(String.format("ENCRYPTION DETECTED: (file offset 0x%x, size 0x%x)",+ cmd.getCryptOffset(), cmd.getCryptSize()));+ }+ }+ }++ /**+ * Processes {@link LoadCommand}s that we haven't implemented yet.+ *+ * @throws CancelledException if the operation was cancelled.+ */+ protected void processUnsupportedLoadCommands() throws CancelledException {+ monitor.setMessage("Processing unsupported load commands...");++ for (LoadCommand loadCommand : machoHeader.getLoadCommands(UnsupportedLoadCommand.class)) {+ monitor.checkCancelled();+ log.appendMsg(loadCommand.getCommandName());+ }+ }+/*** Performs the given relocations.** @param relocationMap The relocations to perform, mapped to the addresses they should get- * performed at. The relocations must be performed in their supplied order.- * @throws CancelledException if the operation was cancelled.+ * performed at. The relocations must be performed in their supplied order.+ * @throws CancelledException if the operation was cancelled.*/private void performRelocations(LinkedHashMap<RelocationInfo, Address> relocationMap)throws CancelledException {@@ -1360,11 +1247,26 @@ public class MachoProgramBuilder {}/**- * Handles a relocation error by placing a bookmark and writing to the log- *- * @param address The address of the relocation error- * @param message The error message- */+ * Marks up {@link LoadCommand} dadta+ *+ * @param header The Mach-O header+ * @throws Exception If there was a problem performing the markup+ */+ protected void markupLoadCommandData(MachHeader header) throws Exception {+ for (LoadCommand cmd : header.getLoadCommands()) {+ Address dataAddr = cmd.getDataAddress(header, space);+ if (dataAddr != null) {+ cmd.markup(program, header, dataAddr, monitor, log);+ }+ }+ }++ /**+ * Handles a relocation error by placing a bookmark and writing to the log+ *+ * @param address The address of the relocation error+ * @param message The error message+ */private void handleRelocationError(Address address, String message) {program.getBookmarkManager().setBookmark(address, BookmarkType.ERROR, "Relocations", message);@@ -1575,359 +1477,151 @@ public class MachoProgramBuilder {}/**- * Fixes up any chained fixups. Relies on the __thread_starts section being present.+ * Markup the given {@link List} of chained fixups by creating pointers at their locations,+ * if possible*- * @return A list of addresses where chained fixups were performed.- * @throws Exception if there was a problem reading/writing memory.+ * @param header The Mach-O header+ * @param chainedFixups The {@link List} of chained fixups to markup+ * @throws CancelledException if the operation was cancelled*/- protected List<Address> processChainedFixups() throws Exception {-- List<Address> fixedAddresses = new ArrayList<>();-- // if has Chained Fixups load command, use it- List<DyldChainedFixupsCommand> loadCommands =- machoHeader.getLoadCommands(DyldChainedFixupsCommand.class);- for (LoadCommand loadCommand : loadCommands) {- DyldChainedFixupsCommand linkCmd = (DyldChainedFixupsCommand) loadCommand;-- DyldChainedFixupHeader chainHeader = linkCmd.getChainHeader();-- DyldChainedStartsInImage chainedStartsInImage = chainHeader.getChainedStartsInImage();-- DyldChainedStartsInSegment[] chainedStarts = chainedStartsInImage.getChainedStarts();- for (DyldChainedStartsInSegment chainStart : chainedStarts) {- fixedAddresses.addAll(processSegmentPointerChain(chainHeader, chainStart));+ protected void markupChainedFixups(MachHeader header, List<Address> chainedFixups)+ throws CancelledException {+ for (Address addr : chainedFixups) {+ monitor.checkCancelled();+ try {+ listing.createData(addr, Pointer64DataType.dataType);}- log.appendMsg("Fixed up " + fixedAddresses.size() + " chained pointers.");- }-- // if pointer chains fixed by DyldChainedFixupsCommands, then all finished- if (loadCommands.size() > 0) {- return fixedAddresses;- }-- // if has thread_starts use to fixup chained pointers- Section threadStarts = machoHeader.getSection(SegmentNames.SEG_TEXT, "__thread_starts");- if (threadStarts == null) {- return Collections.emptyList();- }-- Address threadSectionStart = null;- Address threadSectionEnd = null;- threadSectionStart = space.getAddress(threadStarts.getAddress());- threadSectionEnd = threadSectionStart.add(threadStarts.getSize() - 1);-- monitor.setMessage("Fixing up chained pointers...");-- long nextOffSize = (memory.getInt(threadSectionStart) & 1) * 4 + 4;- Address chainHead = threadSectionStart.add(4);-- while (chainHead.compareTo(threadSectionEnd) < 0 && !monitor.isCancelled()) {- int headStartOffset = memory.getInt(chainHead);- if (headStartOffset == 0xFFFFFFFF || headStartOffset == 0) {- break;+ catch (CodeUnitInsertionException e) {+ // No worries, something presumably more important was there already}-- Address chainStart = program.getImageBase().add(headStartOffset & 0xffffffffL);- fixedAddresses.addAll(processPointerChain(chainStart, nextOffSize));- chainHead = chainHead.add(4);}-- log.appendMsg("Fixed up " + fixedAddresses.size() + " chained pointers.");- return fixedAddresses;}- private List<Address> processSegmentPointerChain(DyldChainedFixupHeader chainHeader,- DyldChainedStartsInSegment chainStart)- throws MemoryAccessException, CancelledException {-- List<Address> fixedAddresses = new ArrayList<Address>();- long fixedAddressCount = 0;-- if (chainStart.getPointerFormat() == 0) {- return fixedAddresses;+ /**+ * See crt.c from opensource.apple.com+ */+ protected void markupProgramVars() {+ if (program.getLanguage().getProcessor() == Processor+ .findOrPossiblyCreateProcessor("PowerPC")) {+ return;}- long dataPageStart = chainStart.getSegmentOffset();- dataPageStart = dataPageStart + program.getImageBase().getOffset();- long pageSize = chainStart.getPageSize();- long pageStartsCount = chainStart.getPageCount();-- long authValueAdd = 0;-- short[] pageStarts = chainStart.getPage_starts();-- short ptrFormatValue = chainStart.getPointerFormat();- DyldChainType ptrFormat = DyldChainType.lookupChainPtr(ptrFormatValue);-- monitor.setMessage("Fixing " + ptrFormat.getName() + " chained pointers...");-- monitor.setMaximum(pageStartsCount);- for (int index = 0; index < pageStartsCount; index++) {- monitor.checkCancelled();-- long page = dataPageStart + (pageSize * index);-- monitor.setProgress(index);-- int pageEntry = pageStarts[index] & 0xffff;- if (pageEntry == DYLD_CHAINED_PTR_START_NONE) {- continue;- }-- List<Address> unchainedLocList = new ArrayList<>(1024);-- long pageOffset = pageEntry; // first entry is byte based-- switch (ptrFormat) {- case DYLD_CHAINED_PTR_ARM64E:- case DYLD_CHAINED_PTR_ARM64E_KERNEL:- case DYLD_CHAINED_PTR_ARM64E_USERLAND:- case DYLD_CHAINED_PTR_ARM64E_USERLAND24:- processPointerChain(chainHeader, unchainedLocList, ptrFormat, page, pageOffset,- authValueAdd);- break;+ SymbolTable symbolTable = program.getSymbolTable();- // These might work, but have not been fully tested!- case DYLD_CHAINED_PTR_64:- case DYLD_CHAINED_PTR_64_OFFSET:- case DYLD_CHAINED_PTR_64_KERNEL_CACHE:- case DYLD_CHAINED_PTR_32:- case DYLD_CHAINED_PTR_32_CACHE:- case DYLD_CHAINED_PTR_32_FIRMWARE:- case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE:- processPointerChain(chainHeader, unchainedLocList, ptrFormat, page, pageOffset,- authValueAdd);- break;+ int defaultPointerSize = program.getDefaultPointerSize();- case DYLD_CHAINED_PTR_ARM64E_FIRMWARE:- default:- log.appendMsg(- "WARNING: Pointer Chain format " + ptrFormat + " not processed yet!");- break;- }+ DataType intDataType =+ (defaultPointerSize == 8) ? new QWordDataType() : new DWordDataType();+ DataType intPointerDataType = PointerDataType.getPointer(intDataType, defaultPointerSize);//int *+ DataType voidPointerDatatype =+ PointerDataType.getPointer(new VoidDataType(), defaultPointerSize);//void *+ DataType charPointerX1DataType =+ PointerDataType.getPointer(new CharDataType(), defaultPointerSize);//char *+ DataType charPointerX2DataType =+ PointerDataType.getPointer(charPointerX1DataType, defaultPointerSize);//char **+ DataType charPointerX3DataType =+ PointerDataType.getPointer(charPointerX2DataType, defaultPointerSize);//char ***- fixedAddressCount += unchainedLocList.size();+ Structure structure = new StructureDataType(SectionNames.PROGRAM_VARS, 0);+ structure.add(voidPointerDatatype, "mh", "pointer to __mh_execute_header");+ structure.add(intPointerDataType, "NXArgcPtr", "pointer to argc");+ structure.add(charPointerX3DataType, "NXArgvPtr", "pointer to argv");+ structure.add(charPointerX3DataType, "environPtr", "pointer to environment");+ structure.add(charPointerX2DataType, "__prognamePtr", "pointer to program name");- fixedAddresses.addAll(unchainedLocList);- }+ Namespace namespace = createNamespace(SectionNames.PROGRAM_VARS);- log.appendMsg(- "Fixed " + fixedAddressCount + " " + ptrFormat.getName() + " chained pointers.");+ List<Section> sections = machoHeader.getAllSections();+ for (Section section : sections) {+ if (section.getSectionName().equals(SectionNames.PROGRAM_VARS)) {+ MemoryBlock memoryBlock = getMemoryBlock(section);+ try {+ listing.createData(memoryBlock.getStart(), structure);+ Data data = listing.getDataAt(memoryBlock.getStart());- return fixedAddresses;- }+ Data mhData = data.getComponent(0);+ if (symbolTable.getSymbol("__mh_execute_header", mhData.getAddress(0),+ namespace) == null) {+ symbolTable.createLabel(mhData.getAddress(0), "__mh_execute_header",+ namespace, SourceType.IMPORTED);+ }- /**- * Fixes up any chained pointers, starting at the given address.- *- * @param chainHeader fixup header chains- * @param unchainedLocList list of locations that were unchained- * @param pointerFormat format of pointers within this chain- * @param page within data pages that has pointers to be unchained- * @param nextOff offset within the page that is the chain start- * @param auth_value_add value to be added to each chain pointer- *- * @throws MemoryAccessException IO problem reading file- * @throws CancelledException user cancels- */- private void processPointerChain(DyldChainedFixupHeader chainHeader,- List<Address> unchainedLocList, DyldChainType pointerFormat, long page, long nextOff,- long auth_value_add) throws MemoryAccessException, CancelledException {+ Data argcData = data.getComponent(1);+ symbolTable.createLabel(argcData.getAddress(0), "NXArgc", namespace,+ SourceType.IMPORTED);+ listing.createData(argcData.getAddress(0), intDataType);- long imageBaseOffset = program.getImageBase().getOffset();- Address chainStart = memory.getProgram().getLanguage().getDefaultSpace().getAddress(page);+ Data argvData = data.getComponent(2);+ symbolTable.createLabel(argvData.getAddress(0), "NXArgv", namespace,+ SourceType.IMPORTED);+ listing.createData(argvData.getAddress(0), charPointerX2DataType);- long next = -1;- boolean start = true;- while (next != 0) {- monitor.checkCancelled();+ Data environData = data.getComponent(3);+ symbolTable.createLabel(environData.getAddress(0), "environ", namespace,+ SourceType.IMPORTED);+ listing.createData(environData.getAddress(0), charPointerX2DataType);- Address chainLoc = chainStart.add(nextOff);- final long chainValue = DyldChainedPtr.getChainValue(memory, chainLoc, pointerFormat);- long newChainValue = chainValue;-- boolean isAuthenticated = DyldChainedPtr.isAuthenticated(pointerFormat, chainValue);- boolean isBound = DyldChainedPtr.isBound(pointerFormat, chainValue);-- String symName = null;-- if (isAuthenticated && !isBound) {- long offsetFromSharedCacheBase =- DyldChainedPtr.getTarget(pointerFormat, chainValue);- //long diversityData = DyldChainedPtr.getDiversity(pointerFormat, chainValue);- //boolean hasAddressDiversity =- // DyldChainedPtr.hasAddrDiversity(pointerFormat, chainValue);- //long key = DyldChainedPtr.getKey(pointerFormat, chainValue);- newChainValue = imageBaseOffset + offsetFromSharedCacheBase + auth_value_add;- }- else if (!isAuthenticated && isBound) {- int chainOrdinal = (int) DyldChainedPtr.getOrdinal(pointerFormat, chainValue);- long addend = DyldChainedPtr.getAddend(pointerFormat, chainValue);- DyldChainedImports chainedImports = chainHeader.getChainedImports();- DyldChainedImport chainedImport = chainedImports.getChainedImport(chainOrdinal);- //int libOrdinal = chainedImport.getLibOrdinal();- symName = chainedImport.getName();- // lookup the symbol, and then add addend- List<Symbol> globalSymbols = program.getSymbolTable().getGlobalSymbols(symName);- if (globalSymbols.size() == 1) {- newChainValue = globalSymbols.get(0).getAddress().getOffset();- }- newChainValue += addend;- }- else if (isAuthenticated && isBound) {- int chainOrdinal = (int) DyldChainedPtr.getOrdinal(pointerFormat, chainValue);- //long addend = DyldChainedPtr.getAddend(pointerFormat, chainValue);- //long diversityData = DyldChainedPtr.getDiversity(pointerFormat, chainValue);- //boolean hasAddressDiversity =- // DyldChainedPtr.hasAddrDiversity(pointerFormat, chainValue);- //long key = DyldChainedPtr.getKey(pointerFormat, chainValue);-- DyldChainedImports chainedImports = chainHeader.getChainedImports();- DyldChainedImport chainedImport = chainedImports.getChainedImport(chainOrdinal);- symName = chainedImport.getName();-- // lookup the symbol, and then add addend- List<Symbol> globalSymbols = program.getSymbolTable().getGlobalSymbols(symName);- if (globalSymbols.size() == 1) {- newChainValue = globalSymbols.get(0).getAddress().getOffset();- }- newChainValue = newChainValue + auth_value_add;- }- else {- newChainValue = DyldChainedPtr.getTarget(pointerFormat, chainValue);- if (DyldChainedPtr.isRelative(pointerFormat)) {- newChainValue += imageBaseOffset;- }- }-- if (!start || !program.getRelocationTable().hasRelocation(chainLoc)) {- int byteLength = 0;- Status status = Status.FAILURE;- try {- RelocationResult result =- DyldChainedPtr.setChainValue(memory, chainLoc, pointerFormat,- newChainValue);- status = result.status();- byteLength = result.byteLength();- }- finally {- if (shouldAddChainedFixupsRelocations) {- program.getRelocationTable()- .add(chainLoc, status,- (start ? 0x8000 : 0x4000) | (isAuthenticated ? 4 : 0) |- (isBound ? 2 : 0) | 1,- new long[] { newChainValue }, byteLength, symName);- }+ Data prognameData = data.getComponent(4);+ symbolTable.createLabel(prognameData.getAddress(0), "__progname", namespace,+ SourceType.IMPORTED);+ listing.createData(prognameData.getAddress(0), charPointerX1DataType);+ }+ catch (Exception e) {+ log.appendException(e);+ return;}}- // delay creating data until after memory has been changed- unchainedLocList.add(chainLoc);-- start = false;- next = DyldChainedPtr.getNext(pointerFormat, chainValue);- nextOff += next * DyldChainedPtr.getStride(pointerFormat);}}- /**- * Fixes up any chained pointers, starting at the given address.- *- * @param chainStart The starting of address of the pointer chain to fix.- * @param nextOffSize The size of the next offset.- * @return A list of addresses where pointer fixes were performed.- * @throws MemoryAccessException if there was a problem reading/writing memory.- */- private List<Address> processPointerChain(Address chainStart, long nextOffSize)- throws MemoryAccessException {- List<Address> fixedAddresses = new ArrayList<>();-- while (!monitor.isCancelled()) {- long chainValue = memory.getLong(chainStart);-- fixupPointer(chainStart, chainValue);- fixedAddresses.add(chainStart);-- long nextValueOff = ((chainValue >> 51L) & 0x7ffL) * nextOffSize;- if (nextValueOff == 0) {+ protected void setRelocatableProperty() {+ Options props = program.getOptions(Program.PROGRAM_INFO);+ switch (machoHeader.getFileType()) {+ case MachHeaderFileTypes.MH_EXECUTE:+ props.setBoolean(RelocationTable.RELOCATABLE_PROP_NAME, false);+ break;+ default:+ props.setBoolean(RelocationTable.RELOCATABLE_PROP_NAME, true);break;- }- chainStart = chainStart.add(nextValueOff);}-- return fixedAddresses;}- /**- * Fixes up the pointer at the given address.- *- * @param pointerAddr The address of the pointer to fix.- * @param pointerValue The value at the address of the pointer to fix.- * @throws MemoryAccessException if there was a problem reading/writing memory.- */- private void fixupPointer(Address pointerAddr, long pointerValue) throws MemoryAccessException {-- final long BIT63 = (0x1L << 63);- final long BIT62 = (0x1L << 62);-- // Bad chain value- if ((pointerValue & BIT62) != 0) {- // this is a pointer, but is good now+ protected void setProgramDescription() {+ Options props = program.getOptions(Program.PROGRAM_INFO);+ props.setString("Mach-O File Type",+ MachHeaderFileTypes.getFileTypeName(machoHeader.getFileType()));+ props.setString("Mach-O File Type Description",+ MachHeaderFileTypes.getFileTypeDescription(machoHeader.getFileType()));+ List<String> flags = MachHeaderFlags.getFlags(machoHeader.getFlags());+ for (int i = 0; i < flags.size(); ++i) {+ props.setString("Mach-O Flag " + i, flags.get(i));}- long fixedPointerValue = 0;- long fixedPointerType = 0;-- // Pointer checked value- if ((pointerValue & BIT63) != 0) {- //long tagType = (pointerValue >> 49L) & 0x3L;- long pacMod = ((pointerValue >> 32) & 0xffff);- fixedPointerType = pacMod;- fixedPointerValue = program.getImageBase().getOffset() + (pointerValue & 0xffffffffL);- }- else {- fixedPointerValue =- ((pointerValue << 13) & 0xff00000000000000L) | (pointerValue & 0x7ffffffffffL);- if ((pointerValue & 0x40000000000L) != 0) {- fixedPointerValue |= 0xfffc0000000000L;- }+ List<SubUmbrellaCommand> umbrellas = machoHeader.getLoadCommands(SubUmbrellaCommand.class);+ for (int i = 0; i < umbrellas.size(); ++i) {+ props.setString("Mach-O Sub-umbrella " + i,+ umbrellas.get(i).getSubUmbrellaFrameworkName().getString());}- // Add entry to relocation table for the pointer fixup- byte origBytes[] = new byte[8];- memory.getBytes(pointerAddr, origBytes);-- boolean success = false;- try {- // Fixup the pointer- memory.setLong(pointerAddr, fixedPointerValue);- success = true;- }- finally {- Status status = success ? Status.APPLIED : Status.FAILURE;- program.getRelocationTable()- .add(pointerAddr, status, (int) fixedPointerType,- new long[] { fixedPointerValue },- origBytes, null);+ List<SubFrameworkCommand> frameworks =+ machoHeader.getLoadCommands(SubFrameworkCommand.class);+ for (int i = 0; i < frameworks.size(); ++i) {+ props.setString("Mach-O Sub-framework " + i,+ frameworks.get(i).getUmbrellaFrameworkName().getString());}}- /**- * Markup the given {@link List} of chained fixups by creating pointers at their locations,- * if possible- *- * @param chainedFixups The {@link List} of chained fixups to markup- * @throws CancelledException if the operation was cancelled- */- protected void markupChainedFixups(List<Address> chainedFixups) throws CancelledException {- for (Address addr : chainedFixups) {- monitor.checkCancelled();- try {- listing.createData(addr, Pointer64DataType.dataType);- }- catch (CodeUnitInsertionException e) {- // No worries, something presumably more important was there already- }+ protected void renameObjMsgSendRtpSymbol()+ throws DuplicateNameException, InvalidInputException {+ Address address = space.getAddress(ObjectiveC1_Constants.OBJ_MSGSEND_RTP);+ Symbol symbol = program.getSymbolTable().getPrimarySymbol(address);+ if (symbol != null && symbol.isDynamic()) {+ symbol.setName(ObjectiveC1_Constants.OBJC_MSG_SEND_RTP_NAME, SourceType.IMPORTED);+ }+ else {+ program.getSymbolTable()+ .createLabel(address, ObjectiveC1_Constants.OBJC_MSG_SEND_RTP_NAME,+ SourceType.IMPORTED);}}}