Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-5552: Integrated the UniversalMachoLoader into MachoLoader to address a library loading issue

Ryan Kurtz6c6eb609c22d
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoLoader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoLoader.java
index 75a7e99987..8c51c0ecc9 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoLoader.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/MachoLoader.java
@@ -65,50 +65,57 @@ public class MachoLoader extends AbstractLibrarySupportLoader {
return loadSpecs;
}
- // Efficient check to fail fast
- byte[] magicBytes = provider.readBytes(0, 4);
- if (!MachConstants.isMagic(LittleEndianDataConverter.INSTANCE.getInt(magicBytes))) {
- return loadSpecs;
+ // This loader can handle both Mach-O files as well as Universal Binary files. If it's a
+ // Universal Binary, each Mach-O it contains will be presented as a single "preferred"
+ // load spec, forcing the user to have to select the desired processor from the import
+ // dialog.
+ List<ByteProvider> allProviders = new ArrayList<>();
+ boolean onlyPreferred;
+ if (isUniveralBinary(provider)) {
+ allProviders.addAll(getUniveralBinaryProviders(provider));
+ onlyPreferred = true;
+ }
+ else {
+ allProviders.add(provider);
+ onlyPreferred = false;
}
- try {
- MachHeader machHeader = new MachHeader(provider);
- String magic =
- CpuTypes.getMagicString(machHeader.getCpuType(), machHeader.getCpuSubType());
- String compiler = detectCompilerName(machHeader);
- List<QueryResult> results = QueryOpinionService.query(MACH_O_NAME, magic, compiler);
- for (QueryResult result : results) {
- loadSpecs.add(new LoadSpec(this, machHeader.getImageBase(), result));
+ for (ByteProvider machoProvider : allProviders) {
+ byte[] magicBytes = machoProvider.readBytes(0, 4);
+ if (!MachConstants.isMagic(LittleEndianDataConverter.INSTANCE.getInt(magicBytes))) {
+ continue;
}
- if (loadSpecs.isEmpty()) {
- loadSpecs.add(new LoadSpec(this, machHeader.getImageBase(), true));
+ try {
+ MachHeader machHeader = new MachHeader(machoProvider);
+ String magic =
+ CpuTypes.getMagicString(machHeader.getCpuType(), machHeader.getCpuSubType());
+ String compiler = detectCompilerName(machHeader);
+ List<QueryResult> results = QueryOpinionService.query(MACH_O_NAME, magic, compiler);
+ for (QueryResult result : results) {
+ if (!onlyPreferred || result.preferred) {
+ loadSpecs.add(new LoadSpec(this, machHeader.getImageBase(), result));
+ }
+ }
+ if (loadSpecs.isEmpty() && !onlyPreferred) {
+ loadSpecs.add(new LoadSpec(this, machHeader.getImageBase(), true));
+ }
+ }
+ catch (MachException e) {
+ // not a problem, just don't add it
}
}
- catch (MachException e) {
- // not a problem, just don't add it
- }
- return loadSpecs;
- }
- private String detectCompilerName(MachHeader machHeader) throws IOException {
- List<String> sectionNames = machHeader.parseSegments()
- .stream()
- .flatMap(seg -> seg.getSections().stream())
- .map(section -> section.getSectionName())
- .toList();
- if (SwiftUtils.isSwift(sectionNames)) {
- return SwiftUtils.SWIFT_COMPILER;
- }
- if (GoRttiMapper.hasGolangSections(sectionNames)) {
- return GoConstants.GOLANG_CSPEC_NAME;
- }
- return null;
+ return loadSpecs;
}
@Override
public void load(ByteProvider provider, LoadSpec loadSpec, List<Option> options,
Program program, TaskMonitor monitor, MessageLog log) throws IOException {
+ if (isUniveralBinary(provider)) {
+ provider = matchUniversalBinaryProvider(provider, loadSpec, monitor);
+ }
+
try {
FileBytes fileBytes = MemoryBlockUtils.createFileBytes(program, provider, monitor);
@@ -292,16 +299,6 @@ public class MachoLoader extends AbstractLibrarySupportLoader {
return null;
}
- /**
- * Checks to see if reexports should be performed
- *
- * @param options a {@link List} of {@link Option}s
- * @return True if reexports should be performed; otherwise, false
- */
- private boolean shouldPerformReexports(List<Option> options) {
- return OptionUtils.getOption(REEXPORT_OPTION_NAME, options, REEXPORT_OPTION_DEFAULT);
- }
-
/**
* {@inheritDoc}
* <p>
@@ -361,33 +358,6 @@ public class MachoLoader extends AbstractLibrarySupportLoader {
}
}
- /**
- * Gets a {@link List} of reexport library paths from the given {@link Program}
- *
- * @param program The {@link Program}
- * @param log The log
- * @return A {@link List} of reexport library paths from the given {@link Program}
- * @throws MachException if there was a problem parsing the Mach-O {@link Program}
- * @throws IOException if there was an IO-related error
- */
- private List<String> getReexportPaths(Program program, MessageLog log)
- throws MachException, IOException {
- Symbol header =
- program.getSymbolTable().getSymbols(MachoProgramBuilder.HEADER_SYMBOL).next();
- if (header == null) {
- log.appendMsg("Failed to lookup reexport paths...couldn't find '%s' symbol"
- .formatted(MachoProgramBuilder.HEADER_SYMBOL));
- return List.of();
- }
- ByteProvider p = new MemoryByteProvider(program.getMemory(), header.getAddress());
- return new MachHeader(p).parseReexports()
- .stream()
- .map(DynamicLibraryCommand::getDynamicLibrary)
- .map(DynamicLibrary::getName)
- .map(LoadCommandString::getString)
- .toList();
- }
-
/**
* {@inheritDoc}
* <p>
@@ -429,6 +399,141 @@ public class MachoLoader extends AbstractLibrarySupportLoader {
monitor);
}
+ /**
+ * Checks to see if the given {@link ByteProvider} is a Universal Binary
+ *
+ * @param provider The {@link ByteProvider} to check
+ * @return True if the given {@link ByteProvider} is a Universal Binary; otherwise, false
+ * @throws IOException if there was an IO-related error
+ */
+ private boolean isUniveralBinary(ByteProvider provider) throws IOException {
+ BinaryReader reader = new BinaryReader(provider, false);
+ int magic = reader.readInt(0);
+ return magic == FatHeader.FAT_MAGIC || magic == FatHeader.FAT_CIGAM;
+ }
+
+ /**
+ * Gets a {@link List} of {@link ByteProviderWrapper}s, one for each entry in the Universal
+ * Binary
+ *
+ * @param provider The Universal Binary's provider
+ * @return A {@link List} of {@link ByteProviderWrapper}s, one for each entry in the Universal
+ * Binary
+ * @throws IOException if an IO-related error occurred
+ */
+ private List<ByteProviderWrapper> getUniveralBinaryProviders(ByteProvider provider)
+ throws IOException {
+ List<ByteProviderWrapper> wrappers = new ArrayList<>();
+ try {
+ FatHeader fatHeader = new FatHeader(provider);
+ List<Long> machStarts = fatHeader.getMachStarts();
+ List<Long> machSizes = fatHeader.getMachSizes();
+ for (int i = 0; i < machStarts.size(); i++) {
+ wrappers.add(new ByteProviderWrapper(provider, machStarts.get(i), machSizes.get(i),
+ provider.getFSRL()));
+ }
+ }
+ catch (MachException | UbiException e) {
+ // not a problem, just don't add it
+ }
+ return wrappers;
+ }
+
+ /**
+ * Attempts to match a Mach-O entry in the given Universal Binary {@link ByteProvider} to the
+ * given {@link LoadSpec}
+ *
+ * @param provider A Universal Binary {@link ByteProvider}
+ * @param loadSpec The {@link LoadSpec} to match
+ * @param monitor A {@link TaskMonitor monitor}
+ * @return The matched Mach-O {@link ByteProvider}, or {@code null} if a match was not found
+ * @throws IOException if an IO-related error occurred
+ */
+ private ByteProvider matchUniversalBinaryProvider(ByteProvider provider, LoadSpec loadSpec,
+ TaskMonitor monitor) throws IOException {
+ ByteProvider ret = null;
+ boolean stop = false;
+ for (ByteProvider machoProvider : getUniveralBinaryProviders(provider)) {
+ for (LoadSpec ls : findSupportedLoadSpecs(machoProvider)) {
+ if (monitor.isCancelled()) {
+ stop = true;
+ break;
+ }
+ if (loadSpec.getLanguageCompilerSpec().equals(ls.getLanguageCompilerSpec())) {
+ ret = machoProvider;
+ stop = true;
+ break;
+ }
+ }
+ if (stop) {
+ break;
+ }
+ }
+ if (ret == null) {
+ throw new IOException("Failed to match the load spec to a Universal Binary Mach-O");
+ }
+ return ret;
+ }
+
+ /**
+ * Attempts to detect a more specific compiler from the Mach-O
+ *
+ * @param machHeader The {@link MachHeader}
+ * @return The detected compiler name, or {@code null} if one could be detected
+ * @throws IOException if an IO-related error occurred
+ */
+ private String detectCompilerName(MachHeader machHeader) throws IOException {
+ List<String> sectionNames = machHeader.parseSegments()
+ .stream()
+ .flatMap(seg -> seg.getSections().stream())
+ .map(section -> section.getSectionName())
+ .toList();
+ if (SwiftUtils.isSwift(sectionNames)) {
+ return SwiftUtils.SWIFT_COMPILER;
+ }
+ if (GoRttiMapper.hasGolangSections(sectionNames)) {
+ return GoConstants.GOLANG_CSPEC_NAME;
+ }
+ return null;
+ }
+
+ /**
+ * Checks to see if reexports should be performed
+ *
+ * @param options a {@link List} of {@link Option}s
+ * @return True if reexports should be performed; otherwise, false
+ */
+ private boolean shouldPerformReexports(List<Option> options) {
+ return OptionUtils.getOption(REEXPORT_OPTION_NAME, options, REEXPORT_OPTION_DEFAULT);
+ }
+
+ /**
+ * Gets a {@link List} of reexport library paths from the given {@link Program}
+ *
+ * @param program The {@link Program}
+ * @param log The log
+ * @return A {@link List} of reexport library paths from the given {@link Program}
+ * @throws MachException if there was a problem parsing the Mach-O {@link Program}
+ * @throws IOException if there was an IO-related error
+ */
+ private List<String> getReexportPaths(Program program, MessageLog log)
+ throws MachException, IOException {
+ Symbol header =
+ program.getSymbolTable().getSymbols(MachoProgramBuilder.HEADER_SYMBOL).next();
+ if (header == null) {
+ log.appendMsg("Failed to lookup reexport paths...couldn't find '%s' symbol"
+ .formatted(MachoProgramBuilder.HEADER_SYMBOL));
+ return List.of();
+ }
+ ByteProvider p = new MemoryByteProvider(program.getMemory(), header.getAddress());
+ return new MachHeader(p).parseReexports()
+ .stream()
+ .map(DynamicLibraryCommand::getDynamicLibrary)
+ .map(DynamicLibrary::getName)
+ .map(LoadCommandString::getString)
+ .toList();
+ }
+
/**
* "Reexports" symbols from to a {@link Program}
*
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/UniversalMachoLoader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/UniversalMachoLoader.java
deleted file mode 100644
index 93b591c017..0000000000
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/UniversalMachoLoader.java
+++ /dev/null
@@ -1,113 +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.opinion;
-
-import java.io.IOException;
-import java.util.*;
-
-import ghidra.app.util.Option;
-import ghidra.app.util.bin.*;
-import ghidra.app.util.bin.format.macho.MachException;
-import ghidra.app.util.bin.format.ubi.FatHeader;
-import ghidra.app.util.bin.format.ubi.UbiException;
-import ghidra.app.util.importer.MessageLog;
-import ghidra.program.model.listing.Program;
-import ghidra.util.task.TaskMonitor;
-
-/**
- * A {@link Loader} for Mach-O files contained in a Universal Binary
- */
-public class UniversalMachoLoader extends MachoLoader {
-
- public final static String UNIVERSAL_MACH_O_NAME = "Universal Mach-O";
- private static final long MIN_BYTE_LENGTH = 4;
-
- @Override
- public Collection<LoadSpec> findSupportedLoadSpecs(ByteProvider provider) throws IOException {
- List<LoadSpec> loadSpecs = new ArrayList<>();
-
- // Efficient check to fail fast
- if (provider.length() < MIN_BYTE_LENGTH) {
- return loadSpecs;
- }
-
- // Efficient check to fail fast
- BinaryReader reader = new BinaryReader(provider, false);
- int magic = reader.readInt(0);
- if (magic != FatHeader.FAT_MAGIC && magic != FatHeader.FAT_CIGAM) {
- return loadSpecs;
- }
-
- // Only add the preferred load specs for each Mach-O so only 1 entry for each architecture
- // shows up. Keep them all preferred though so the user is forced to pick one (headless
- // will just use the "first preferred" by default)
- for (ByteProvider wrapper : getWrappers(provider)) {
- super.findSupportedLoadSpecs(wrapper).stream()
- .filter(LoadSpec::isPreferred)
- .forEach(loadSpecs::add);
- }
-
- return loadSpecs;
- }
-
- @Override
- public void load(ByteProvider provider, LoadSpec loadSpec, List<Option> options,
- Program program, TaskMonitor monitor, MessageLog log) throws IOException {
- for (ByteProvider wrapper : getWrappers(provider)) {
- for (LoadSpec ls : super.findSupportedLoadSpecs(wrapper)) {
- if (monitor.isCancelled()) {
- break;
- }
- if (loadSpec.getLanguageCompilerSpec().equals(ls.getLanguageCompilerSpec())) {
- super.load(wrapper, loadSpec, options, program, monitor, log);
- return;
- }
- }
- }
- }
-
- @Override
- public String getName() {
- return UNIVERSAL_MACH_O_NAME;
- }
-
- /**
- * Gets a {@link List} of {@link ByteProviderWrapper}s, one for each entry in the Universal
- * Binary
- *
- * @param provider The Universal Binary's provider
- * @return A {@link List} of {@link ByteProviderWrapper}s, one for each entry in the Universal
- * Binary
- * @throws IOException if an IO-related error occurred
- */
- private List<ByteProviderWrapper> getWrappers(ByteProvider provider) throws IOException {
- List<ByteProviderWrapper> wrappers = new ArrayList<>();
- try {
- FatHeader fatHeader = new FatHeader(provider);
- List<Long> machStarts = fatHeader.getMachStarts();
- List<Long> machSizes = fatHeader.getMachSizes();
- for (int i = 0; i < machStarts.size(); i++) {
- wrappers.add(new ByteProviderWrapper(provider, machStarts.get(i), machSizes.get(i),
- provider.getFSRL()));
- }
- }
- catch (MachException | UbiException e) {
- // not a problem, just don't add it
- }
- return wrappers;
- }
-
-}