Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-850 Improve Demangler error checking and reporting.

ghizard4990a9dc4ef5
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/AbstractDemanglerAnalyzer.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/AbstractDemanglerAnalyzer.java
index 966e4fa931..631a9b5b40 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/AbstractDemanglerAnalyzer.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/AbstractDemanglerAnalyzer.java
@@ -15,6 +15,9 @@
*/
package ghidra.app.plugin.core.analysis;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.exception.ExceptionUtils;
+
import ghidra.app.services.*;
import ghidra.app.util.demangler.*;
import ghidra.app.util.importer.MessageLog;
@@ -25,18 +28,18 @@ import ghidra.util.exception.CancelledException;
import ghidra.util.task.TaskMonitor;
/**
- * The base demangler analyzer. Implementations of this analyzer will attempt to demangle
+ * The base demangler analyzer. Implementations of this analyzer will attempt to demangle
* symbols in the binary being analyzed.
- *
+ *
* <P>Default implementations of this class exist for Microsoft and GNU. These two analyzers will
* only be enabled when the program being analyzed has an architecture that fits each respective
- * analyzer. Users can subclass this analyzer to easily control the demangling behavior from
+ * analyzer. Users can subclass this analyzer to easily control the demangling behavior from
* the analyzer UI.
- *
- * <P>This analyzer will call each implementation's
- * {@link #doDemangle(String, DemanglerOptions, MessageLog)} method for each symbol.
+ *
+ * <P>This analyzer will call each implementation's
+ * {@link #doDemangle(String, DemanglerOptions, MessageLog)} method for each symbol.
* See the various protected methods of this class for points at which behavior can be overridden.
- *
+ *
*/
public abstract class AbstractDemanglerAnalyzer extends AbstractAnalyzer {
@@ -51,7 +54,7 @@ public abstract class AbstractDemanglerAnalyzer extends AbstractAnalyzer {
@Override
public boolean canAnalyze(Program program) {
- // override this to control program-specific enablement
+ // override this to control program-specific enablement
return true;
}
@@ -71,15 +74,14 @@ public abstract class AbstractDemanglerAnalyzer extends AbstractAnalyzer {
}
private boolean doAdded(Program program, AddressSetView set, TaskMonitor monitor,
- MessageLog log)
- throws CancelledException {
+ MessageLog log) throws CancelledException {
DemanglerOptions options = getOptions();
if (!validateOptions(options, log)) {
log.appendMsg(getName(), "Invalid demangler options--cannot demangle");
return false;
}
-
+
// Demangle external symbols after memory symbols.
// This is done to compensate for cases where the mangled name on externals may be lost
// after demangling when an alternate Ordinal symbol exists. The external mangled
@@ -134,9 +136,9 @@ public abstract class AbstractDemanglerAnalyzer extends AbstractAnalyzer {
/**
* The implementation-specific demangling callback
- *
+ *
* @param mangled the mangled string
- * @param options the demangler options
+ * @param options the demangler options
* @param log the error log
* @return the demangled object; null if demangling was unsuccessful
* @throws DemangledException if there is a problem demangling or building the result
@@ -147,7 +149,7 @@ public abstract class AbstractDemanglerAnalyzer extends AbstractAnalyzer {
/**
* Called before each analysis request to ensure that the current options (which may have
* user-defined input) will work with the current demangler
- *
+ *
* @param options the current options in use
* @param log the error log into which error message can be written
* @return true if valid
@@ -159,7 +161,7 @@ public abstract class AbstractDemanglerAnalyzer extends AbstractAnalyzer {
/**
* True if this analyzer should <b>not</b> attempt to demangle the given symbol
- *
+ *
* @param symbol the symbol
* @return true to skip the symbol
*/
@@ -180,7 +182,7 @@ public abstract class AbstractDemanglerAnalyzer extends AbstractAnalyzer {
}
// Someone has already added arguments or return to the function signature.
- // Treatment of thunks must be handled later since thunk relationship may
+ // Treatment of thunks must be handled later since thunk relationship may
// need to be broken
if (symbol.getSymbolType() == SymbolType.FUNCTION) {
Function function = (Function) symbol.getObject();
@@ -194,15 +196,15 @@ public abstract class AbstractDemanglerAnalyzer extends AbstractAnalyzer {
}
/**
- * Creates the options for the demangler used by implementations of this analyzer. This will
+ * Creates the options for the demangler used by implementations of this analyzer. This will
* be called before each {@link #added(Program, AddressSetView, TaskMonitor, MessageLog)}
* call processes symbols.
- *
- * @return the options
+ *
+ * @return the options
*/
protected DemanglerOptions getOptions() {
// note: these can be stored in the analyzer subclass and updated when the
- // analysis options change
+ // analysis options change
DemanglerOptions options = new DemanglerOptions();
options.setApplySignature(true);
options.setDoDisassembly(true);
@@ -213,7 +215,7 @@ public abstract class AbstractDemanglerAnalyzer extends AbstractAnalyzer {
/**
* This calss's default demangle method. This may be overridden to change how errors are
* handled.
- *
+ *
* @param mangled the mangled string
* @param address the symbol address
* @param options the demangler options
@@ -236,9 +238,8 @@ public abstract class AbstractDemanglerAnalyzer extends AbstractAnalyzer {
}
}
- log.appendMsg(getName(),
- "Unable to demangle symbol: " + mangled + " at " + address + ". Message: " +
- e.getMessage());
+ log.appendMsg(getName(), "Unable to demangle symbol: " + mangled + " at " + address +
+ ". Message: " + e.getMessage());
return null;
}
@@ -247,9 +248,9 @@ public abstract class AbstractDemanglerAnalyzer extends AbstractAnalyzer {
/**
* Applies the given demangled object to the program
- *
+ *
* @param program the program
- * @param address the apply address
+ * @param address the apply address
* @param demangled the demangled object
* @param options the options used during the apply
* @param log the error log
@@ -258,27 +259,37 @@ public abstract class AbstractDemanglerAnalyzer extends AbstractAnalyzer {
protected void apply(Program program, Address address, DemangledObject demangled,
DemanglerOptions options, MessageLog log, TaskMonitor monitor) {
- String errorMessage = null;
try {
if (demangled.applyTo(program, address, options, monitor)) {
return;
}
+ logApplyErrorMessage(log, demangled, address, null);
}
catch (Exception e) {
- String message = e.getMessage();
- if (message == null) {
- message = "";
- }
- errorMessage = "\n" + e.getClass().getSimpleName() + ' ' + message;
+ logApplyErrorMessage(log, demangled, address, e);
}
- String failMessage = " (" + getName() + "/" + demangled.getClass().getName() + ")";
- if (errorMessage != null) {
- failMessage += errorMessage;
+ }
+
+ private void logApplyErrorMessage(MessageLog log, DemangledObject demangled, Address address,
+ Exception exception) {
+
+ String message;
+ String name;
+ if (exception == null) {
+ // Eventually, if we switch all errors over to being passed by an exception, then
+ // we can eliminate this block of code (and not pass null into this method).
+ message = "Unknown error at address " + address;
+ name = "\n\t" + demangled.getName();
+ }
+ else {
+ message = ExceptionUtils.getMessage(exception);
+ name = StringUtils.EMPTY;
}
- log.appendMsg(getName(), "Failed to apply mangled symbol at " + address + "; name: " +
- demangled.getMangledString() + failMessage);
+ String className = demangled.getClass().getSimpleName();
+ log.appendMsg(getName(), "Apply failure (" + className + ": " + message + ")\n\t" +
+ demangled.getMangledString() + name);
}
protected String cleanSymbol(Address address, String name) {
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/demangler/DemangledFunction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/demangler/DemangledFunction.java
index 60a759ac82..1788468741 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/demangler/DemangledFunction.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/demangler/DemangledFunction.java
@@ -128,9 +128,9 @@ public class DemangledFunction extends DemangledObject {
return callingConvention;
}
- /**
- * Special constructor where it has a templated type before the parameter list
- * @param type the type
+ /**
+ * Special constructor where it has a templated type before the parameter list
+ * @param type the type
*/
public void setTemplatedConstructorType(String type) {
this.templatedConstructorType = type;
@@ -335,19 +335,53 @@ public class DemangledFunction extends DemangledObject {
return super.isAlreadyDemangled(program, address);
}
+ /**
+ * This method assumes preconditions test has been run.
+ */
+ private boolean shouldDisassemble(Program program, Address address, DemanglerOptions options) {
+ CodeUnit codeUnit = program.getListing().getCodeUnitAt(address);
+ return (codeUnit instanceof Data); // preconditions check guarantees data is undefined data.
+ }
+
+ private boolean passesPreconditions(Program program, Address address) throws Exception {
+
+ if (!demangledNameSuccessfully()) {
+ throw new DemangledException("Symbol did not demangle at address: " + address);
+ }
+
+ if (isAlreadyDemangled(program, address)) {
+ return false; // not an error, but signifies that we should not continue to process
+ }
+
+ if (address.isMemoryAddress()) {
+ CodeUnit codeUnit = program.getListing().getCodeUnitAt(address);
+ if (codeUnit == null) {
+ throw new IllegalArgumentException(
+ "Address not in memory or is off-cut data/instruction: " + address);
+ }
+ if (codeUnit instanceof Data) {
+ if (((Data) codeUnit).isDefined()) {
+ throw new IllegalArgumentException("Defined data at address: " + address);
+ }
+ }
+ }
+ return true;
+ }
+
@Override
public boolean applyTo(Program program, Address address, DemanglerOptions options,
TaskMonitor monitor) throws Exception {
- if (isAlreadyDemangled(program, address)) {
- return true;
+ if (!passesPreconditions(program, address)) {
+ return true; // eventually will not return anything
}
if (!super.applyTo(program, address, options, monitor)) {
return false;
}
- Function function = createFunction(program, address, options.doDisassembly(), monitor);
+ boolean disassemble = shouldDisassemble(program, address, options);
+ Function function = createFunction(program, address, disassemble, monitor);
if (function == null) {
// No function whose signature we need to update
return false;
@@ -408,10 +442,10 @@ public class DemangledFunction extends DemangledObject {
}
/**
- * Determine if existing thunk relationship should be preserved and mangled symbol
+ * Determine if existing thunk relationship should be preserved and mangled symbol
* discarded. This is the case when the thunk function mangled name matches
* the thunked function since we want to avoid duplicate symbol names.
- * @param thunkFunction thunk function with a mangled symbol which is currently
+ * @param thunkFunction thunk function with a mangled symbol which is currently
* being demangled.
* @return true if thunk should be preserved and mangled symbol discarded, otherwise
* false if thunk relationship should be eliminated and demangled function information
@@ -453,7 +487,7 @@ public class DemangledFunction extends DemangledObject {
return true;
}
- // TODO: carefully compare signature in absense of matching mangled name
+ // TODO: carefully compare signature in absence of matching mangled name
return false;
}
@@ -575,7 +609,7 @@ public class DemangledFunction extends DemangledObject {
if (program.getCompilerSpec().getCallingConvention(callingConvention) == null) {
// warn that calling convention not found. Datatypes are still good,
// the real calling convention can be figured out later
- // For example X64 can have __cdecl, __fastcall, __stdcall, that
+ // For example X64 can have __cdecl, __fastcall, __stdcall, that
// are accepted but ignored
BookmarkManager bm = program.getBookmarkManager();
Address entry = function.getEntryPoint();
@@ -674,7 +708,7 @@ public class DemangledFunction extends DemangledObject {
/**
* check if the return/param data types were defined by better than analysis (user, import)
- *
+ *
* @param func the function to check
* @return true if the parameters are not undefined, or are of a higher source type.
*/
@@ -692,7 +726,7 @@ public class DemangledFunction extends DemangledObject {
if (dt == null || Undefined.isUndefined(dt)) {
continue;
}
- // if the parameters source is higher than
+ // if the parameters source is higher than
if (parameter.getSource().isHigherPriorityThan(SourceType.ANALYSIS)) {
return true;
}
@@ -841,7 +875,7 @@ public class DemangledFunction extends DemangledObject {
}
protected Function createFunction(Program prog, Address addr, boolean doDisassembly,
- TaskMonitor monitor) {
+ TaskMonitor monitor) throws DemangledException {
Listing listing = prog.getListing();
Function func = listing.getFunctionAt(addr);
if (func != null) {
@@ -851,7 +885,9 @@ public class DemangledFunction extends DemangledObject {
if (addr.isExternalAddress()) {
Symbol extSymbol = prog.getSymbolTable().getPrimarySymbol(addr);
CreateExternalFunctionCmd cmd = new CreateExternalFunctionCmd(extSymbol);
- cmd.applyTo(prog);
+ if (!cmd.applyTo(prog)) {
+ throw new DemangledException("Unable to create function: " + cmd.getStatusMsg());
+ }
}
else {
if (doDisassembly) {
@@ -863,7 +899,9 @@ public class DemangledFunction extends DemangledObject {
}
}
CreateFunctionCmd cmd = new CreateFunctionCmd(addr);
- cmd.applyTo(prog, monitor);
+ if (!cmd.applyTo(prog, monitor)) {
+ throw new DemangledException("Unable to create function: " + cmd.getStatusMsg());
+ }
}
return listing.getFunctionAt(addr);
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/demangler/DemangledObject.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/demangler/DemangledObject.java
index 03b7d601bb..d83f066b64 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/demangler/DemangledObject.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/demangler/DemangledObject.java
@@ -47,7 +47,7 @@ public abstract class DemangledObject implements Demangled {
protected Demangled namespace;
protected String visibility;//public, protected, etc.
- //TODO: storageClass refers to things such as "static" but const and volatile are
+ //TODO: storageClass refers to things such as "static" but const and volatile are
// typeQualifiers. Should change this everywhere(?).
protected String storageClass; //const, volatile, etc
@@ -70,6 +70,9 @@ public abstract class DemangledObject implements Demangled {
private String signature;
+ // Status of mangled String converted successfully to demangled String
+ private boolean demangledNameSucceeded = false;
+
DemangledObject(String mangled, String originalDemangled) {
this.mangled = mangled;
this.originalDemangled = originalDemangled;
@@ -179,6 +182,15 @@ public abstract class DemangledObject implements Demangled {
this.name =
DemanglerUtil.stripSuperfluousSignatureSpaces(name).trim().replace(' ', '_');
}
+ demangledNameSucceeded = !mangled.equals(name);
+ }
+
+ /**
+ * Returns the success state of converting a mangled String into a demangled String
+ * @return true succeeded creating demangled String
+ */
+ public boolean demangledNameSuccessfully() {
+ return demangledNameSucceeded;
}
@Override
@@ -310,14 +322,19 @@ public abstract class DemangledObject implements Demangled {
}
/**
- * @param program The program for which to apply the comment
+ * @param program The program for which to apply the comment
* @param address The address for the comment
* @return {@code true} if a comment was applied
+ * @throws Exception if the symbol could not be demangled or if the address is invalid
*/
- public boolean applyPlateCommentOnly(Program program, Address address) {
- if (mangled.equals(name)) {
- return false;
+ public boolean applyPlateCommentOnly(Program program, Address address) throws Exception {
+ if (!demangledNameSuccessfully()) {
+ throw new DemangledException("Symbol did not demangle at address: " + address);
}
+ if (!address.isMemoryAddress() || !program.getMemory().contains(address)) {
+ throw new IllegalArgumentException("Invalid program memory address: " + address);
+ }
+
String comment = program.getListing().getComment(CodeUnit.PLATE_COMMENT, address);
String newComment = generatePlateComment();
if (comment == null || comment.indexOf(newComment) < 0) {
@@ -423,10 +440,10 @@ public abstract class DemangledObject implements Demangled {
}
/**
- * Get or create the specified typeNamespace. The returned namespace may only be a partial
+ * Get or create the specified typeNamespace. The returned namespace may only be a partial
* namespace if errors occurred. The caller should check the returned namespace and adjust
- * any symbol creation accordingly.
- *
+ * any symbol creation accordingly.
+ *
* @param program the program
* @param typeNamespace demangled namespace
* @param parentNamespace root namespace to be used (e.g., library, global, etc.)
@@ -456,13 +473,11 @@ public abstract class DemangledObject implements Demangled {
catch (DuplicateNameException e) {
Msg.error(DemangledObject.class,
"Failed to create namespace due to name conflict: " +
- NamespaceUtils.getNamespaceQualifiedName(namespace, namespaceName,
- false));
+ NamespaceUtils.getNamespaceQualifiedName(namespace, namespaceName, false));
break;
}
catch (InvalidInputException e) {
- Msg.error(DemangledObject.class,
- "Failed to create namespace: " + e.getMessage());
+ Msg.error(DemangledObject.class, "Failed to create namespace: " + e.getMessage());
break;
}
@@ -492,10 +507,10 @@ public abstract class DemangledObject implements Demangled {
return functionPermitted && symbolType == SymbolType.FUNCTION;
}
- /**
+ /**
* Ensure name does not pass the limit defined by Ghidra
- *
- * @param name the name whose length to restrict
+ *
+ * @param name the name whose length to restrict
* @return the name, updated as needed
*/
protected static String ensureNameLength(String name) {
diff --git a/Ghidra/Features/MicrosoftDmang/src/test/java/mdemangler/MDMangBaseTest.java b/Ghidra/Features/MicrosoftDmang/src/test/java/mdemangler/MDMangBaseTest.java
index 679189772c..14dcde4753 100644
--- a/Ghidra/Features/MicrosoftDmang/src/test/java/mdemangler/MDMangBaseTest.java
+++ b/Ghidra/Features/MicrosoftDmang/src/test/java/mdemangler/MDMangBaseTest.java
@@ -14563,6 +14563,24 @@ public class MDMangBaseTest extends AbstractGenericTest {
demangleAndTest();
}
+ // Contrived example.
+ @Test
+ public void testCastOperatorToFunctionPointer() throws Exception {
+ mangled = "??BClassName@@YAP6KXP6KXH@Z@ZXZ";
+ msTruth = "__cdecl ClassName::operator void (*)(void (*)(int))(void)";
+ mdTruth = msTruth;
+ demangleAndTest();
+ }
+
+ // Contrived example.
+ @Test
+ public void testReferenceToConstMemberPointerOfTypeFloatAsFunctionParameter() throws Exception {
+ mangled = "?FnName@FnSpace@@YKXABPUClassName@@M@Z";
+ msTruth = "void FnSpace::FnName(float ClassName::* const &)";
+ mdTruth = msTruth;
+ demangleAndTest();
+ }
+
//TODO: ignore for now.
@Ignore
public void testFuzzyFit() throws Exception {