Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-2008: Mach-O export trie support, and other symbol improvements

Ryan Kurtz4dd4dd9a559b
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.java
index 428523dc97..6eba0b8360 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
@@ -21,6 +21,7 @@ import java.util.List;
import ghidra.app.util.bin.*;
import ghidra.app.util.bin.format.macho.commands.*;
+import ghidra.app.util.opinion.DyldCacheUtils.SplitDyldCache;
import ghidra.program.model.data.*;
import ghidra.util.exception.DuplicateNameException;
@@ -135,14 +136,34 @@ public class MachHeader implements StructConverter {
_commandIndex = _reader.getPointerIndex();
}
+ /**
+ * Parses this {@link MachHeader}'s {@link LoadCommand load commands}
+ *
+ * @return This {@link MachHeader}, for convenience
+ * @throws IOException If there was an IO-related error
+ * @throws MachException if the load command is invalid
+ */
public MachHeader parse() throws IOException, MachException {
+ return parse(null);
+ }
+
+ /**
+ * Parses this {@link MachHeader}'s {@link LoadCommand load commands}
+ *
+ * @param splitDyldCache The {@link SplitDyldCache} that this header resides in. Could be null
+ * if a split DYLD cache is not being used.
+ * @return This {@link MachHeader}, for convenience
+ * @throws IOException If there was an IO-related error
+ * @throws MachException if the load command is invalid
+ */
+ public MachHeader parse(SplitDyldCache splitDyldCache) throws IOException, MachException {
if (_parsed) {
return this;
}
long currentIndex = _commandIndex;
for (int i = 0; i < nCmds; ++i) {
_reader.setPointerIndex(currentIndex);
- LoadCommand lc = LoadCommandFactory.getLoadCommand(_reader, this);
+ LoadCommand lc = LoadCommandFactory.getLoadCommand(_reader, this, splitDyldCache);
_commands.add(lc);
currentIndex += lc.getCommandSize();
}
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.java
index f4a2fba95c..e93472395b 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
@@ -38,13 +38,20 @@ public class DyldChainedFixupsCommand extends LinkEditDataCommand {
private DyldChainedFixupHeader chainHeader;
- DyldChainedFixupsCommand(BinaryReader reader) throws IOException {
- super(reader);
-
- long ptrIndex = reader.getPointerIndex();
- reader.setPointerIndex(getDataOffset());
- chainHeader = new DyldChainedFixupHeader(reader);
- reader.setPointerIndex(ptrIndex);
+ /**
+ * Creates and parses a new {@link DyldChainedFixupsCommand}
+ *
+ * @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
+ */
+ DyldChainedFixupsCommand(BinaryReader loadCommandReader, BinaryReader dataReader)
+ throws IOException {
+ super(loadCommandReader, dataReader);
+
+ chainHeader = new DyldChainedFixupHeader(dataReader);
}
@Override
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.java
new file mode 100644
index 0000000000..b50866bfff
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldExportsTrieCommand.java
@@ -0,0 +1,54 @@
+/* ###
+ * 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;
+
+/**
+ * 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>
+ */
+public class DyldExportsTrieCommand extends LinkEditDataCommand {
+
+ private ExportTrie exportTrie;
+
+ /**
+ * Creates and parses a new {@link DyldExportsTrieCommand}
+ *
+ * @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
+ */
+ DyldExportsTrieCommand(BinaryReader loadCommandReader, BinaryReader dataReader)
+ throws IOException {
+ super(loadCommandReader, dataReader);
+ exportTrie = dataoff > 0 && datasize > 0 ? new ExportTrie(dataReader) : new ExportTrie();
+ }
+
+ /**
+ * Gets the {@link ExportTrie}
+ *
+ * @return The {@link ExportTrie}
+ */
+ public ExportTrie getExportTrie() {
+ return exportTrie;
+ }
+}
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.java
index d48d3760eb..ade7dcc582 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
@@ -42,20 +42,41 @@ public class DyldInfoCommand extends LoadCommand {
private int lazy_bind_size;
private int export_off;
private int export_size;
+
+ private ExportTrie exportTrie;
- DyldInfoCommand(BinaryReader reader) throws IOException {
- super(reader);
-
- rebase_off = reader.readNextInt();
- rebase_size = reader.readNextInt();
- bind_off = reader.readNextInt();
- bind_size = reader.readNextInt();
- weak_bind_off = reader.readNextInt();
- weak_bind_size = reader.readNextInt();
- lazy_bind_off = reader.readNextInt();
- lazy_bind_size = reader.readNextInt();
- export_off = reader.readNextInt();
- export_size = reader.readNextInt();
+ /**
+ * Creates and parses a new {@link DyldInfoCommand}
+ *
+ * @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.
+ * @param header The {@link MachHeader header} associated with this load command
+ * @throws IOException if an IO-related error occurs while parsing
+ */
+ DyldInfoCommand(BinaryReader loadCommandReader, BinaryReader dataReader, MachHeader header)
+ throws IOException {
+ super(loadCommandReader);
+
+ rebase_off = loadCommandReader.readNextInt();
+ rebase_size = loadCommandReader.readNextInt();
+ bind_off = loadCommandReader.readNextInt();
+ bind_size = loadCommandReader.readNextInt();
+ weak_bind_off = loadCommandReader.readNextInt();
+ weak_bind_size = loadCommandReader.readNextInt();
+ lazy_bind_off = loadCommandReader.readNextInt();
+ lazy_bind_size = loadCommandReader.readNextInt();
+ export_off = loadCommandReader.readNextInt();
+ export_size = loadCommandReader.readNextInt();
+
+ if (export_off > 0 && export_size > 0) {
+ dataReader.setPointerIndex(header.getStartIndex() + export_off);
+ exportTrie = new ExportTrie(dataReader);
+ }
+ else {
+ exportTrie = new ExportTrie();
+ }
}
@Override
@@ -202,4 +223,13 @@ public class DyldInfoCommand extends LoadCommand {
public int getExportSize() {
return export_size;
}
+
+ /**
+ * Gets the {@link ExportTrie}
+ *
+ * @return The {@link ExportTrie}
+ */
+ public ExportTrie getExportTrie() {
+ return exportTrie;
+ }
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldInfoCommandConstants.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldInfoCommandConstants.java
index eb86f07398..2330a2eb25 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldInfoCommandConstants.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldInfoCommandConstants.java
@@ -74,7 +74,8 @@ public final class DyldInfoCommandConstants {
public final static int EXPORT_SYMBOL_FLAGS_KIND_MASK = 0x03;
public final static int EXPORT_SYMBOL_FLAGS_KIND_REGULAR = 0x00;
public final static int EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL = 0x01;
+ public final static int EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE = 0x02;
public final static int EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION = 0x04;
- public final static int EXPORT_SYMBOL_FLAGS_INDIRECT_DEFINITION = 0x08;
- public final static int EXPORT_SYMBOL_FLAGS_HAS_SPECIALIZATIONS = 0x10;
+ public final static int EXPORT_SYMBOL_FLAGS_REEXPORT = 0x08;
+ public final static int EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER = 0x10;
}
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.java
index 47196b4827..ba95f0f0fc 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
@@ -63,69 +63,76 @@ public class DynamicSymbolTableCommand extends LoadCommand {
private List<RelocationInfo> externalRelocations = new ArrayList<RelocationInfo>();
private List<RelocationInfo> localRelocations = new ArrayList<RelocationInfo>();
- DynamicSymbolTableCommand(BinaryReader reader, MachHeader header) throws IOException {
- super(reader);
-
- ilocalsym = reader.readNextInt();
- nlocalsym = reader.readNextInt();
- iextdefsym = reader.readNextInt();
- nextdefsym = reader.readNextInt();
- iundefsym = reader.readNextInt();
- nundefsym = reader.readNextInt();
- tocoff = reader.readNextInt();
- ntoc = reader.readNextInt();
- modtaboff = reader.readNextInt();
- nmodtab = reader.readNextInt();
- extrefsymoff = reader.readNextInt();
- nextrefsyms = reader.readNextInt();
- indirectsymoff = reader.readNextInt();
- nindirectsyms = reader.readNextInt();
- extreloff = reader.readNextInt();
- nextrel = reader.readNextInt();
- locreloff = reader.readNextInt();
- nlocrel = reader.readNextInt();
-
- long index = reader.getPointerIndex();
+ /**
+ * Creates and parses a new {@link DynamicSymbolTableCommand}
+ *
+ * @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.
+ * @param header The {@link MachHeader header} associated with this load command
+ * @throws IOException if an IO-related error occurs while parsing
+ */
+ DynamicSymbolTableCommand(BinaryReader loadCommandReader, BinaryReader dataReader,
+ MachHeader header) throws IOException {
+ super(loadCommandReader);
+
+ ilocalsym = loadCommandReader.readNextInt();
+ nlocalsym = loadCommandReader.readNextInt();
+ iextdefsym = loadCommandReader.readNextInt();
+ nextdefsym = loadCommandReader.readNextInt();
+ iundefsym = loadCommandReader.readNextInt();
+ nundefsym = loadCommandReader.readNextInt();
+ tocoff = loadCommandReader.readNextInt();
+ ntoc = loadCommandReader.readNextInt();
+ modtaboff = loadCommandReader.readNextInt();
+ nmodtab = loadCommandReader.readNextInt();
+ extrefsymoff = loadCommandReader.readNextInt();
+ nextrefsyms = loadCommandReader.readNextInt();
+ indirectsymoff = loadCommandReader.readNextInt();
+ nindirectsyms = loadCommandReader.readNextInt();
+ extreloff = loadCommandReader.readNextInt();
+ nextrel = loadCommandReader.readNextInt();
+ locreloff = loadCommandReader.readNextInt();
+ nlocrel = loadCommandReader.readNextInt();
if (tocoff > 0) {
- reader.setPointerIndex(header.getStartIndex() + tocoff);
+ dataReader.setPointerIndex(header.getStartIndex() + tocoff);
for (int i = 0; i < ntoc; ++i) {
- tocList.add(new TableOfContents(reader));
+ tocList.add(new TableOfContents(dataReader));
}
}
if (modtaboff > 0) {
- reader.setPointerIndex(header.getStartIndex() + modtaboff);
+ dataReader.setPointerIndex(header.getStartIndex() + modtaboff);
for (int i = 0; i < nmodtab; ++i) {
- moduleList.add(new DynamicLibraryModule(reader, header));
+ moduleList.add(new DynamicLibraryModule(dataReader, header));
}
}
if (extrefsymoff > 0) {
- reader.setPointerIndex(header.getStartIndex() + extrefsymoff);
+ dataReader.setPointerIndex(header.getStartIndex() + extrefsymoff);
for (int i = 0; i < nextrefsyms; ++i) {
- referencedList.add(new DynamicLibraryReference(reader));
+ referencedList.add(new DynamicLibraryReference(dataReader));
}
}
if (indirectsymoff > 0) {
- reader.setPointerIndex(header.getStartIndex() + indirectsymoff);
+ dataReader.setPointerIndex(header.getStartIndex() + indirectsymoff);
indirectSymbols = new int[nindirectsyms];
for (int i = 0; i < nindirectsyms; ++i) {
- indirectSymbols[i] = reader.readNextInt();
+ indirectSymbols[i] = dataReader.readNextInt();
}
}
if (extreloff > 0) {
- reader.setPointerIndex(header.getStartIndex() + extreloff);
+ dataReader.setPointerIndex(header.getStartIndex() + extreloff);
for (int i = 0; i < nextrel; ++i) {
- externalRelocations.add(new RelocationInfo(reader));
+ externalRelocations.add(new RelocationInfo(dataReader));
}
}
if (locreloff > 0) {
- reader.setPointerIndex(header.getStartIndex() + locreloff);
+ dataReader.setPointerIndex(header.getStartIndex() + locreloff);
for (int i = 0; i < nlocrel; ++i) {
- localRelocations.add(new RelocationInfo(reader));
+ localRelocations.add(new RelocationInfo(dataReader));
}
}
-
- reader.setPointerIndex(index);
}
/**
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.java
new file mode 100644
index 0000000000..b109fc17e0
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/ExportTrie.java
@@ -0,0 +1,244 @@
+/* ###
+ * 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 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 ghidra.app.util.bin.BinaryReader;
+import ghidra.app.util.bin.format.dwarf4.LEB128;
+
+/**
+ * Mach-O export trie
+ *
+ * @see <a href="https://github.com/qyang-nj/llios/blob/main/exported_symbol/README.md">Exported Symbol</a>
+ * @see <a href="https://github.com/opensource-apple/dyld/blob/master/launch-cache/MachOTrie.hpp">dyld/launch-cache/MachOTrie.hpp</a>
+ */
+public class ExportTrie {
+
+ private BinaryReader reader;
+ private long base;
+ private List<ExportEntry> exports;
+
+ /**
+ * Creates an empty {@link ExportTrie}. This is useful for export trie load commands that are
+ * defined but do not point to any data.
+ */
+ public ExportTrie() {
+ this.exports = new ArrayList<>();
+ }
+
+ /**
+ * Creates and parses a new {@link ExportTrie}
+ *
+ * @param reader A {@link BinaryReader reader} positioned at the start of the export trie
+ * @throws IOException if an IO-related error occurs while parsing
+ */
+ public ExportTrie(BinaryReader reader) throws IOException {
+ this();
+ this.reader = reader;
+ this.base = reader.getPointerIndex();
+
+ parseTrie();
+ }
+
+ /**
+ * Gets the {@link List} of {@link ExportEntry exports}
+ *
+ * @return The {@link List} of {@link ExportEntry exports}
+ */
+ public List<ExportEntry> getExports() {
+ return exports;
+ }
+
+ /**
+ * Gets the {@link List} of {@link ExportEntry exports}
+ *
+ * @param filter A filter on the returned {@link List}
+ * @return The {@link List} of {@link ExportEntry exports}
+ */
+ public List<ExportEntry> getExports(Predicate<ExportEntry> filter) {
+ return exports.stream().filter(filter).collect(Collectors.toList());
+ }
+
+ /**
+ * Parses the export trie
+ *
+ * @throws IOException if there was an IO-related error
+ */
+ private void parseTrie() throws IOException {
+ LinkedList<Node> remainingNodes = parseNode("", 0);
+ while(!remainingNodes.isEmpty()) {
+ Node parent = remainingNodes.removeFirst();
+ LinkedList<Node> children = parseNode(parent.name, parent.offset);
+ for (Node child : children) {
+ remainingNodes.add(new Node(parent.name + child.name, child.offset));
+ }
+ }
+ }
+
+ /**
+ * Parses a node of the export trie
+ *
+ * @param name The node edge (symbol name substring)
+ * @param offset An offset from the data base where the node starts
+ * @return A {@link LinkedList list} of child {@link Node nodes}
+ * @throws IOException if there was an IO-related error
+ */
+ private LinkedList<Node> parseNode(String name, int offset) throws IOException {
+ LinkedList<Node> children = new LinkedList<>();
+ reader.setPointerIndex(base + offset);
+ int terminalSize = LEB128.readAsUInt32(reader);
+ long childrenIndex = reader.getPointerIndex() + terminalSize;
+ if (terminalSize != 0) {
+ long flags = LEB128.readAsLong(reader, false);
+ long address = 0;
+ long other = 0;
+ String importName = null;
+ if ((flags & EXPORT_SYMBOL_FLAGS_REEXPORT) != 0) {
+ other = LEB128.readAsLong(reader, false); // dylib ordinal
+ importName = reader.readNextAsciiString();
+ }
+ else {
+ address = LEB128.readAsLong(reader, false);
+ if ((flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) != 0) {
+ other = LEB128.readAsLong(reader, false);
+ }
+ }
+ ExportEntry export = new ExportEntry(name, address, flags, other, importName);
+ exports.add(export);
+ }
+ reader.setPointerIndex(childrenIndex);
+ int numChildren = LEB128.readAsUInt32(reader);
+ for (int i = 0; i < numChildren; i++) {
+ String childName = reader.readNextAsciiString();
+ int childOffset = LEB128.readAsUInt32(reader);
+ children.add(new Node(childName, childOffset));
+ }
+ return children;
+ }
+
+ /**
+ * A export trie entry
+ */
+ 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;
+ }
+
+ /**
+ * Check to see if the export is a "re-export"
+ *
+ * @return True if re-export; otherwise, false
+ */
+ public boolean isReExport() {
+ return (flags & EXPORT_SYMBOL_FLAGS_REEXPORT) != 0;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("%s addr: 0x%x, flags: 0x%x, other: 0x%x, importName: %s", name,
+ address, flags, other, importName != null ? importName : "<null>");
+ }
+ }
+
+ /**
+ * A trie node
+ */
+ private static class Node {
+ String name;
+ int offset;
+
+ Node(String name, int offset) {
+ this.name = name;
+ this.offset = offset;
+ }
+
+ @Override
+ public 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/FunctionStartsCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/FunctionStartsCommand.java
index 87bf7475a6..55fca86c63 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
@@ -31,8 +31,18 @@ import ghidra.program.model.address.Address;
*/
public class FunctionStartsCommand extends LinkEditDataCommand {
- FunctionStartsCommand(BinaryReader reader) throws IOException {
- super(reader);
+ /**
+ * Creates and parses a new {@link LinkEditDataCommand}
+ *
+ * @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
+ */
+ FunctionStartsCommand(BinaryReader loadCommandReader, BinaryReader dataReader)
+ throws IOException {
+ super(loadCommandReader, dataReader);
}
/**
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.java
index 1febe20200..be37359ced 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
@@ -32,13 +32,27 @@ import ghidra.util.task.TaskMonitor;
* Represents a linkedit_data_command structure
*/
public class LinkEditDataCommand extends LoadCommand {
- private int dataoff;
- private int datasize;
+ protected int dataoff;
+ protected int datasize;
+ protected BinaryReader dataReader;
- LinkEditDataCommand(BinaryReader reader) throws IOException {
- super(reader);
- dataoff = reader.readNextInt();
- datasize = reader.readNextInt();
+ /**
+ * Creates and parses a new {@link LinkEditDataCommand}. Sets <code>dataReader</code> to the
+ * data offset.
+ *
+ * @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
+ */
+ LinkEditDataCommand(BinaryReader loadCommandReader, BinaryReader dataReader)
+ throws IOException {
+ super(loadCommandReader);
+ this.dataoff = loadCommandReader.readNextInt();
+ this.datasize = loadCommandReader.readNextInt();
+ this.dataReader = dataReader;
+ this.dataReader.setPointerIndex(dataoff);
}
public int getDataOffset() {
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.java
index 605b0f9719..ec7ae0403a 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
@@ -22,7 +22,10 @@ import java.io.IOException;
import ghidra.app.util.bin.BinaryReader;
import ghidra.app.util.bin.format.macho.MachException;
import ghidra.app.util.bin.format.macho.MachHeader;
+import ghidra.app.util.bin.format.macho.dyld.DyldCacheHeader;
+import ghidra.app.util.bin.format.macho.dyld.DyldCacheMappingInfo;
import ghidra.app.util.bin.format.macho.threadcommand.ThreadCommand;
+import ghidra.app.util.opinion.DyldCacheUtils.SplitDyldCache;
import ghidra.util.Msg;
/**
@@ -31,22 +34,25 @@ import ghidra.util.Msg;
public class LoadCommandFactory {
/**
- * Creates a {@link LoadCommand}
+ * Create and parses a {@link LoadCommand}
*
- * @param reader A {@link BinaryReader} positioned at the start of the load command to create
- * @param header The {@link MachHeader} that contains the load command to create
- * @return A {@link LoadCommand}
- * @throws IOException if there was an IO-related error
- * @throws MachException if there was a problem parsing the load command
+ * @param reader A {@link BinaryReader reader} that points to the start of the load command
+ * @param header The {@link MachHeader header} associated with this load command
+ * @param splitDyldCache The {@link SplitDyldCache} that this header resides in. Could be null
+ * if a split DYLD cache is not being used.
+ * @return A new {@link LoadCommand}
+ * @throws IOException if an IO-related error occurs while parsing
+ * @throws MachException if the load command is invalid
*/
- public static LoadCommand getLoadCommand(BinaryReader reader, MachHeader header)
- throws IOException, MachException {
+ public static LoadCommand getLoadCommand(BinaryReader reader, MachHeader header,
+ SplitDyldCache splitDyldCache) throws IOException, MachException {
int type = reader.peekNextInt();
switch (type) {
case LC_SEGMENT:
return new SegmentCommand(reader, header.is32bit());
case LC_SYMTAB:
- return new SymbolTableCommand(reader, header);
+ return new SymbolTableCommand(reader,
+ getLinkEditReader(reader, header, splitDyldCache), header);
case LC_SYMSEG:
return new SymbolCommand(reader);
case LC_THREAD:
@@ -62,7 +68,8 @@ public class LoadCommandFactory {
case LC_PREPAGE:
return new UnsupportedLoadCommand(reader, type);
case LC_DYSYMTAB:
- return new DynamicSymbolTableCommand(reader, header);
+ return new DynamicSymbolTableCommand(reader,
+ getLinkEditReader(reader, header, splitDyldCache), header);
case LC_LOAD_DYLIB:
case LC_ID_DYLIB:
case LC_LOAD_UPWARD_DYLIB:
@@ -102,7 +109,8 @@ public class LoadCommandFactory {
case LC_DATA_IN_CODE:
case LC_OPTIMIZATION_HINT:
case LC_DYLIB_CODE_SIGN_DRS:
- return new LinkEditDataCommand(reader);
+ return new LinkEditDataCommand(reader,
+ getLinkEditReader(reader, header, splitDyldCache));
case LC_REEXPORT_DYLIB:
return new DynamicLibraryCommand(reader);
case LC_ENCRYPTION_INFO:
@@ -110,14 +118,16 @@ public class LoadCommandFactory {
return new EncryptedInformationCommand(reader, header.is32bit());
case LC_DYLD_INFO:
case LC_DYLD_INFO_ONLY:
- return new DyldInfoCommand(reader);
+ return new DyldInfoCommand(reader,
+ getLinkEditReader(reader, header, splitDyldCache), header);
case LC_VERSION_MIN_MACOSX:
case LC_VERSION_MIN_IPHONEOS:
case LC_VERSION_MIN_TVOS:
case LC_VERSION_MIN_WATCHOS:
return new VersionMinCommand(reader);
case LC_FUNCTION_STARTS:
- return new FunctionStartsCommand(reader);
+ return new FunctionStartsCommand(reader,
+ getLinkEditReader(reader, header, splitDyldCache));
case LC_MAIN:
return new EntryPointCommand(reader);
case LC_SOURCE_VERSION:
@@ -129,9 +139,11 @@ public class LoadCommandFactory {
case LC_BUILD_VERSION:
return new BuildVersionCommand(reader);
case LC_DYLD_EXPORTS_TRIE:
- return new LinkEditDataCommand(reader);
+ return new DyldExportsTrieCommand(reader,
+ getLinkEditReader(reader, header, splitDyldCache));
case LC_DYLD_CHAINED_FIXUPS:
- return new DyldChainedFixupsCommand(reader);
+ return new DyldChainedFixupsCommand(reader,
+ getLinkEditReader(reader, header, splitDyldCache));
case LC_FILESET_ENTRY:
return new FileSetEntryCommand(reader);
default:
@@ -139,4 +151,39 @@ public class LoadCommandFactory {
return new UnsupportedLoadCommand(reader, type);
}
}
+
+ /**
+ * Gets a {@link BinaryReader} that points to the given {@link MachHeader Mach-O header's}
+ * __LINKEDIT segment. Note that this segment may live in a different provider than
+ * the Mach-O header if a {@link SplitDyldCache} is being used.
+ *
+ * @param reader The {@link BinaryReader} used to read the given Mach-O header
+ * @param header The {@link MachHeader Mach-O header}
+ * @param splitDyldCache The {@link SplitDyldCache}, or null if that is not being used
+ * @return A {@link BinaryReader} that points to the given {@link MachHeader Mach-O header's}
+ * __LINKEDIT segment
+ * @throws MachException If the __LINKEDIT segment was not found
+ */
+ private static BinaryReader getLinkEditReader(BinaryReader reader, MachHeader header,
+ SplitDyldCache splitDyldCache) throws MachException {
+ SegmentCommand linkEdit = header.getSegment(SegmentNames.SEG_LINKEDIT);
+ if (linkEdit == null) {
+ throw new MachException("__LINKEDIT segment not found");
+ }
+ if (splitDyldCache == null) {
+ return reader.clone(linkEdit.getFileOffset());
+ }
+ for (int i = 0; i < splitDyldCache.size(); i++) {
+ DyldCacheHeader dyldCacheHeader = splitDyldCache.getDyldCacheHeader(i);
+ for (DyldCacheMappingInfo mappingInfo : dyldCacheHeader.getMappingInfos()) {
+ if (mappingInfo.contains(linkEdit.getVMaddress())) {
+ BinaryReader linkEditReader =
+ new BinaryReader(splitDyldCache.getProvider(i), true);
+ linkEditReader.setPointerIndex(linkEdit.getFileOffset());
+ return linkEditReader;
+ }
+ }
+ }
+ throw new MachException("__LINKEDIT segment not found in DYLD cache");
+ }
}
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.java
index c007c5706d..5ab7c26e56 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
@@ -36,7 +36,7 @@ import ghidra.util.exception.DuplicateNameException;
import ghidra.util.task.TaskMonitor;
/**
- * Represents a symtab_command structure
+ * Represents a symtab_command structure
*/
public class SymbolTableCommand extends LoadCommand {
private int symoff;
@@ -46,42 +46,44 @@ public class SymbolTableCommand extends LoadCommand {
private List<NList> symbols = new ArrayList<NList>();
- public SymbolTableCommand(BinaryReader reader, MachHeader header) throws IOException {
- super(reader);
-
- symoff = reader.readNextInt();
- nsyms = reader.readNextInt();
- stroff = reader.readNextInt();
- strsize = reader.readNextInt();
-
- long index = reader.getPointerIndex();
+ /**
+ * Creates and parses a new {@link SymbolTableCommand}
+ *
+ * @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.
+ * @param header The {@link MachHeader header} associated with this load command
+ * @throws IOException if an IO-related error occurs while parsing
+ */
+ public SymbolTableCommand(BinaryReader loadCommandReader, BinaryReader dataReader,
+ MachHeader header) throws IOException {
+ super(loadCommandReader);
- reader.setPointerIndex(header.getStartIndex() + symoff);
+ symoff = loadCommandReader.readNextInt();
+ nsyms = loadCommandReader.readNextInt();
+ stroff = loadCommandReader.readNextInt();
+ strsize = loadCommandReader.readNextInt();
List<NList> nlistList = new ArrayList<>(nsyms);
- long startIndex = header.getStartIndex();
- boolean is32bit = header.is32bit();
- reader.setPointerIndex(startIndex + symoff);
-
+ dataReader.setPointerIndex(header.getStartIndex() + symoff);
for (int i = 0; i < nsyms; ++i) {
- nlistList.add(new NList(reader, is32bit));
+ nlistList.add(new NList(dataReader, header.is32bit()));
}
+
// sort the entries by the index in the string table, so don't jump around reading
List<NList> sortedList =
nlistList.stream().sorted((o1, o2) -> Integer.compare(o1.getStringTableIndex(),
o2.getStringTableIndex())).collect(Collectors.toList());
// initialize the sorted NList strings from string table
- long stringTableOffset = stroff;
for (NList nList : sortedList) {
- nList.initString(reader, stringTableOffset);
+ nList.initString(dataReader, stroff);
}
// the symbol table should be in the original order.
// The table is indexed by other tables in the MachO headers
symbols = nlistList;
-
- reader.setPointerIndex(index);
}
/**
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.java
index 391828123f..cbc11aae1b 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
@@ -106,8 +106,10 @@ public class DyldCacheLocalSymbolsInfo implements StructConverter {
*/
public void markup(Program program, Address localSymbolsInfoAddr, TaskMonitor monitor,
MessageLog log) throws CancelledException {
- markupNList(program, localSymbolsInfoAddr, monitor, log);
markupLocalSymbols(program, localSymbolsInfoAddr, monitor, log);
+
+ // Not worth marking up the huge NList in production code. Keep it commented for debugging.
+ //markupNList(program, localSymbolsInfoAddr, monitor, log);
}
/**
@@ -124,7 +126,7 @@ public class DyldCacheLocalSymbolsInfo implements StructConverter {
*
* @return The {@link List} of {@link DyldCacheLocalSymbolsEntry}
*/
- public List<DyldCacheLocalSymbolsEntry> getLocalSymbols() {
+ public List<DyldCacheLocalSymbolsEntry> getLocalSymbolsEntries() {
return localSymbolsEntryList;
}
@@ -146,7 +148,7 @@ public class DyldCacheLocalSymbolsInfo implements StructConverter {
private void parseNList(MessageLog log, TaskMonitor monitor) throws CancelledException {
BinaryReader nListReader =
new BinaryReader(reader.getByteProvider(), reader.isLittleEndian());
- monitor.setMessage("Parsing DYLD nlist symbol table...");
+ monitor.setMessage("Parsing DYLD local symbol nlists...");
monitor.initialize(nlistCount * 2);
nListReader.setPointerIndex(startIndex + nlistOffset);
try {
@@ -194,7 +196,7 @@ public class DyldCacheLocalSymbolsInfo implements StructConverter {
private void markupNList(Program program, Address localSymbolsInfoAddr, TaskMonitor monitor,
MessageLog log) throws CancelledException {
- monitor.setMessage("Marking up DYLD nlist symbol table...");
+ monitor.setMessage("Marking up DYLD local symbol nlists...");
monitor.initialize(nlistCount);
try {
Address addr = localSymbolsInfoAddr.add(nlistOffset);
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.java
index 993362d31a..8b2a58ee4c 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
@@ -111,11 +111,17 @@ public class DyldCacheProgramBuilder extends MachoProgramBuilder {
setDyldCacheImageBase(splitDyldCache.getDyldCacheHeader(0));
// Setup memory
+ // Check if local symbols are present
+ boolean localSymbolsPresent = false;
for (int i = 0; i < splitDyldCache.size(); i++) {
DyldCacheHeader header = splitDyldCache.getDyldCacheHeader(i);
ByteProvider bp = splitDyldCache.getProvider(i);
processDyldCacheMemoryBlocks(header, bp);
+
+ if (header.getLocalSymbolsInfo() != null) {
+ localSymbolsPresent = true;
+ }
}
// Perform additional DYLD processing
@@ -126,8 +132,8 @@ public class DyldCacheProgramBuilder extends MachoProgramBuilder {
fixPageChains(header);
markupHeaders(header);
markupBranchIslands(header, bp);
- createSymbols(header);
- processDylibs(header, bp);
+ createLocalSymbols(header);
+ processDylibs(splitDyldCache, header, bp, localSymbolsPresent);
}
}
}
@@ -223,31 +229,36 @@ public class DyldCacheProgramBuilder extends MachoProgramBuilder {
}
/**
- * Creates the DYLD Cache symbols.
+ * Create the DYLD Cache local symbols.
*
* @param dyldCacheHeader The {@link DyldCacheHeader}
- * @throws Exception if there was a problem creating the symbols
+ * @throws Exception if there was a problem creating the local symbols
*/
- private void createSymbols(DyldCacheHeader dyldCacheHeader) throws Exception {
+ private void createLocalSymbols(DyldCacheHeader dyldCacheHeader) throws Exception {
+ if (!shouldProcessSymbols) {
+ return;
+ }
DyldCacheLocalSymbolsInfo localSymbolsInfo = dyldCacheHeader.getLocalSymbolsInfo();
- if (localSymbolsInfo != null) {
- monitor.setMessage("Processing DYLD symbols...");
- monitor.initialize(localSymbolsInfo.getNList().size());
- for (NList nlist : localSymbolsInfo.getNList()) {
- if (!nlist.getString().trim().isEmpty()) {
- try {
- program.getSymbolTable()
- .createLabel(space.getAddress(nlist.getValue()),
- SymbolUtilities.replaceInvalidChars(nlist.getString(), true),
- program.getGlobalNamespace(), SourceType.IMPORTED);
- }
- catch (Exception e) {
- log.appendMsg(e.getMessage() + " " + nlist.getString());
- }
- }
- monitor.checkCanceled();
- monitor.incrementProgress(1);
+ if (localSymbolsInfo == null) {
+ return;
+ }
+ monitor.setMessage("Creating DYLD local symbols...");
+ monitor.initialize(localSymbolsInfo.getNList().size());
+ for (NList nlist : localSymbolsInfo.getNList()) {
+ if (nlist.getString().isBlank()) {
+ continue;
}
+ try {
+ program.getSymbolTable()
+ .createLabel(space.getAddress(nlist.getValue()),
+ SymbolUtilities.replaceInvalidChars(nlist.getString(), true),
+ program.getGlobalNamespace(), SourceType.IMPORTED);
+ }
+ catch (Exception e) {
+ log.appendMsg(e.getMessage() + " " + nlist.getString());
+ }
+ monitor.checkCanceled();
+ monitor.incrementProgress(1);
}
}
@@ -277,9 +288,11 @@ public class DyldCacheProgramBuilder extends MachoProgramBuilder {
*
* @param dyldCacheHeader The {@link DyldCacheHeader}
* @param bp The corresponding {@link ByteProvider}
+ * @param localSymbolsPresent True if DYLD local symbols are present; otherwise, false
* @throws Exception if there was a problem processing the DYLIB files
*/
- private void processDylibs(DyldCacheHeader dyldCacheHeader, ByteProvider bp) throws Exception {
+ private void processDylibs(SplitDyldCache splitDyldCache, DyldCacheHeader dyldCacheHeader,
+ ByteProvider bp, boolean localSymbolsPresent) throws Exception {
// Create an "info" object for each DyldCache DYLIB, which will make processing them
// easier
monitor.setMessage("Parsing DYLIB's...");
@@ -288,12 +301,34 @@ public class DyldCacheProgramBuilder extends MachoProgramBuilder {
List<DyldCacheImage> mappedImages = dyldCacheHeader.getMappedImages();
monitor.initialize(mappedImages.size());
for (DyldCacheImage mappedImage : mappedImages) {
- infoSet.add(new DyldCacheMachoInfo(bp,
+ infoSet.add(new DyldCacheMachoInfo(splitDyldCache, bp,
mappedImage.getAddress() - dyldCacheHeader.getBaseAddress(),
space.getAddress(mappedImage.getAddress()), mappedImage.getPath()));
monitor.checkCanceled();
monitor.incrementProgress(1);
}
+
+ // Create Exports
+ monitor.setMessage("Creating DYLIB exports...");
+ monitor.initialize(infoSet.size());
+ boolean exportsCreated = false;
+ for (DyldCacheMachoInfo info : infoSet) {
+ info.createExports();
+ monitor.checkCanceled();
+ monitor.incrementProgress(1);
+ }
+
+ // Create DyldCache Mach-O symbols if local symbols are not present
+ if (shouldProcessSymbols && !localSymbolsPresent) {
+ monitor.setMessage("Creating DYLIB symbols...");
+ monitor.initialize(infoSet.size());
+ for (DyldCacheMachoInfo info : infoSet) {
+ info.createSymbols(exportsCreated);
+ monitor.checkCanceled();
+ monitor.incrementProgress(1);
+ }
+ }
+
// Markup DyldCache Mach-O headers
monitor.setMessage("Marking up DYLIB headers...");
@@ -348,17 +383,17 @@ public class DyldCacheProgramBuilder extends MachoProgramBuilder {
/**
* Creates a new {@link DyldCacheMachoInfo} object with the given parameters.
*
+ * @param splitDyldCache The {@link SplitDyldCache}
* @param provider The {@link ByteProvider} that contains the Mach-O's bytes
* @param offset The offset in the provider to the start of the Mach-O
* @param headerAddr The Mach-O's header address
* @param path The path of the Mach-O
* @throws Exception If there was a problem handling the Mach-O info
*/
- public DyldCacheMachoInfo(ByteProvider provider, long offset, Address headerAddr,
- String path) throws Exception {
+ public DyldCacheMachoInfo(SplitDyldCache splitDyldCache, ByteProvider provider, long offset, Address headerAddr, String path) throws Exception {
this.headerAddr = headerAddr;
this.header = new MachHeader(provider, offset, false);
- this.header.parse();
+ this.header.parse(splitDyldCache);
this.path = path;
this.name = new File(path).getName();
}
@@ -373,6 +408,27 @@ public class DyldCacheProgramBuilder extends MachoProgramBuilder {
DyldCacheProgramBuilder.this.processMemoryBlocks(header, name,
shouldCreateDylibSections, false);
}
+
+ /**
+ * Creates exports for this Mach-O.
+ *
+ * @return True if exports were created; otherwise, false
+ * @throws Exception If there was a problem creating exports for this Mach-O
+ */
+ public boolean createExports() throws Exception {
+ return DyldCacheProgramBuilder.this.processExports(header);
+ }
+
+ /**
+ * Creates symbols for this Mach-O (does not include exports).
+ *
+ * @param processExports True if symbol table exports should be processed; otherwise, false
+ * @throws Exception If there was a problem creating symbols for this Mach-O
+ * @see DyldCacheProgramBuilder#processSymbolTables(MachHeader, boolean)
+ */
+ public void createSymbols(boolean processExports) throws Exception {
+ DyldCacheProgramBuilder.this.processSymbolTables(header, processExports);
+ }
/**
* Marks up the Mach-O headers.
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.java
index d8c32cefff..75a901c7d2 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
@@ -25,6 +25,7 @@ import ghidra.app.util.bin.ByteProvider;
import ghidra.app.util.bin.StructConverter;
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.dyld.*;
import ghidra.app.util.bin.format.macho.dyld.DyldChainedPtr;
import ghidra.app.util.bin.format.macho.dyld.DyldChainedPtr.DyldChainType;
@@ -125,7 +126,8 @@ public class MachoProgramBuilder {
processEntryPoint();
processMemoryBlocks(machoHeader, provider.getName(), true, true);
processUnsupportedLoadCommands();
- processSymbolTables();
+ boolean exportsFound = processExports(machoHeader);
+ processSymbolTables(machoHeader, !exportsFound);
processIndirectSymbols();
setRelocatableProperty();
processLibraries();
@@ -411,10 +413,48 @@ public class MachoProgramBuilder {
log.appendMsg(loadCommand.getCommandName());
}
}
+
+ protected boolean processExports(MachHeader header) throws Exception {
+ List<ExportEntry> exports = new ArrayList<>();
+ SegmentCommand textSegment = header.getSegment(SegmentNames.SEG_TEXT);
+ if (textSegment == null) {
+ log.appendMsg("Cannot process exports, __TEXT segment not found!");
+ return false;
+ }
+
+ // Old way - export tree in DyldInfoCommand
+ List<DyldInfoCommand> dyldInfoCommands = header.getLoadCommands(DyldInfoCommand.class);
+ for (DyldInfoCommand dyldInfoCommand : dyldInfoCommands) {
+ exports.addAll(dyldInfoCommand.getExportTrie().getExports(e -> !e.isReExport()));
+
+ }
+
+ // New way - export tree in DyldExportsTrieCommand
+ List<DyldExportsTrieCommand> dyldExportsTrieCommands =
+ header.getLoadCommands(DyldExportsTrieCommand.class);
+ for (DyldExportsTrieCommand dyldExportsTreeCommand : dyldExportsTrieCommands) {
+ exports.addAll(dyldExportsTreeCommand.getExportTrie().getExports(e -> !e.isReExport()));
+ }
+
+ Address baseAddr = space.getAddress(textSegment.getVMaddress());
+ for (ExportEntry export : exports) {
+ String name = SymbolUtilities.replaceInvalidChars(export.getName(), true);
+ Address exportAddr = baseAddr.add(export.getAddress());
+ program.getSymbolTable().addExternalEntryPoint(exportAddr);
+ try {
+ program.getSymbolTable().createLabel(exportAddr, name, SourceType.IMPORTED);
+ }
+ catch (Exception e) {
+ log.appendMsg("Unable to create symbol: " + e.getMessage());
+ }
+ }
- protected void processSymbolTables() throws Exception {
+ return !exports.isEmpty();
+ }
+
+ protected void processSymbolTables(MachHeader header, boolean processExports) throws Exception {
monitor.setMessage("Processing symbol tables...");
- List<SymbolTableCommand> commands = machoHeader.getLoadCommands(SymbolTableCommand.class);
+ List<SymbolTableCommand> commands = header.getLoadCommands(SymbolTableCommand.class);
for (SymbolTableCommand symbolTableCommand : commands) {
List<NList> symbols = symbolTableCommand.getSymbols();
for (NList symbol : symbols) {
@@ -446,7 +486,7 @@ public class MachoProgramBuilder {
continue;
}
- if (symbol.isExternal() || symbol.isPrivateExternal()) {
+ if (processExports && symbol.isExternal()) {
program.getSymbolTable().addExternalEntryPoint(addr);
}
@@ -464,7 +504,12 @@ public class MachoProgramBuilder {
continue;
}
try {
- program.getSymbolTable().createLabel(addr, string, SourceType.IMPORTED);
+ if (!symbol.isExternal() || processExports) {
+ program.getSymbolTable().createLabel(addr, string, SourceType.IMPORTED);
+ if (symbol.isExternal()) {
+ program.getSymbolTable().addExternalEntryPoint(addr);
+ }
+ }
}
catch (Exception e) {
log.appendMsg("Unable to create symbol: " + e.getMessage());