Ghidra is a software reverse engineering (SRE) framework
GP-6438 - Version Tracking - Added support for applying empty composite types
dragonmacher8edb21f1bd04
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/program/util/DataTypeCleaner.java b/Ghidra/Features/Base/src/main/java/ghidra/program/util/DataTypeCleaner.javaindex f9c0dcce3d..161f837e71 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/program/util/DataTypeCleaner.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/program/util/DataTypeCleaner.java@@ -4,9 +4,9 @@* 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.@@ -30,7 +30,8 @@ import ghidra.util.task.TaskMonitor;* {@link DataTypeManager}. The cleaning process entails clearing all details associated with* all composites other than their description which may be present. There is also an option* to retain those composites which are already defined within the target.- * <br>+ *+ * <P>* All datatypes and their referenced datatypes will be accumulated and possibly re-used across* multiple invocations of the {@link #clean(DataType)} method. It is important that this instance* be {@link #close() closed} when instance and any resulting {@link DataType} is no longer in use.@@ -44,7 +45,7 @@ public class DataTypeCleaner implements Closeable {private int txId;/**- * Consruct a {@link DataTypeCleaner} instance. The caller must ensure that this instance+ * Construct a {@link DataTypeCleaner} instance. The caller must ensure that this instance* is {@link #close() closed} when instance and any resulting {@link DataType} is no longer in* use.* @param targetDtm target datatype manager@@ -95,11 +96,11 @@ public class DataTypeCleaner implements Closeable {continue;}Composite replacement = null;- if (c instanceof Structure s) {+ if (c instanceof Structure) {replacement =new StructureDataType(c.getCategoryPath(), c.getName(), 0, cleanerDtm);}- else if (c instanceof Union u) {+ else if (c instanceof Union) {replacement = new UnionDataType(c.getCategoryPath(), c.getName(), cleanerDtm);}if (replacement != null) {diff --git a/Ghidra/Features/VersionTracking/src/main/help/help/topics/VersionTrackingPlugin/images/VTOptions_ApplyMarkupDialog.png b/Ghidra/Features/VersionTracking/src/main/help/help/topics/VersionTrackingPlugin/images/VTOptions_ApplyMarkupDialog.pngindex 3c7649af45..72d418cb18 100644Binary files a/Ghidra/Features/VersionTracking/src/main/help/help/topics/VersionTrackingPlugin/images/VTOptions_ApplyMarkupDialog.png and b/Ghidra/Features/VersionTracking/src/main/help/help/topics/VersionTrackingPlugin/images/VTOptions_ApplyMarkupDialog.png differdiff --git a/Ghidra/Features/VersionTracking/src/main/help/help/topics/VersionTrackingPlugin/providers/VT_Apply_Options.html b/Ghidra/Features/VersionTracking/src/main/help/help/topics/VersionTrackingPlugin/providers/VT_Apply_Options.htmlindex dd7625325f..ba85f6167b 100644--- a/Ghidra/Features/VersionTracking/src/main/help/help/topics/VersionTrackingPlugin/providers/VT_Apply_Options.html+++ b/Ghidra/Features/VersionTracking/src/main/help/help/topics/VersionTrackingPlugin/providers/VT_Apply_Options.html@@ -463,6 +463,17 @@</TR>+ <TR>+ <TD><b>Use Empty Composite Types</b> : <br>+ Specifies whether to create empty composite types when the destination+ does not already contain the type being applied to the destination+ signature.+ </TD>++ <TD nowrap><tt>False</tt>+ </TD>+ </TR>+<TR><TD><b>Inline</b> : <br>diff --git a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/FunctionSignatureMarkupType.java b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/FunctionSignatureMarkupType.javaindex a691c70a45..02469f5f47 100644--- a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/FunctionSignatureMarkupType.java+++ b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/FunctionSignatureMarkupType.java@@ -33,7 +33,6 @@ import ghidra.framework.options.ToolOptions;import ghidra.program.model.address.Address;import ghidra.program.model.listing.*;import ghidra.program.util.*;-import ghidra.util.SystemUtilities;public class FunctionSignatureMarkupType extends FunctionEntryPointBasedAbstractMarkupType {@@ -83,11 +82,11 @@ public class FunctionSignatureMarkupType extends FunctionEntryPointBasedAbstract@Overridepublic Stringable getSourceValue(VTAssociation association, Address sourceAddress) {- Function function = getSourceFunction(association);- if (function == null) {+ Function srcFunction = getSourceFunction(association);+ if (srcFunction == null) {return null;}- return new FunctionSignatureStringable(function);+ return new FunctionSignatureStringable(srcFunction);}@Override@@ -97,22 +96,22 @@ public class FunctionSignatureMarkupType extends FunctionEntryPointBasedAbstract"Attempted to unapply a non-applied markup item");}- Address destinationAddress = markupItem.getDestinationAddress();- FunctionSignatureStringable destinationSignatureStringable =+ Address destAddress = markupItem.getDestinationAddress();+ FunctionSignatureStringable destStringable =(FunctionSignatureStringable) markupItem.getOriginalDestinationValue();Program destinationProgram = getDestinationProgram(markupItem.getAssociation());- FunctionManager functionManager = destinationProgram.getFunctionManager();- Function destinationFunction = functionManager.getFunctionAt(destinationAddress);- if (destinationFunction == null) {+ FunctionManager fm = destinationProgram.getFunctionManager();+ Function destFunction = fm.getFunctionAt(destAddress);+ if (destFunction == null) {return;}- if (destinationSignatureStringable.sameFunctionSignature(destinationFunction)) {+ if (destStringable.isSameFunctionSignature(destFunction)) {return;}ToolOptions options = getUnapplyOptions();- destinationSignatureStringable.applyFunctionSignature(destinationFunction, options, true);+ destStringable.applyFunctionSignature(destFunction, options, true);}private ToolOptions getUnapplyOptions() {@@ -162,7 +161,6 @@ public class FunctionSignatureMarkupType extends FunctionEntryPointBasedAbstract}Address destinationAddress = markupItem.getDestinationAddress();-if (destinationAddress == null) {throw new VersionTrackingApplyException("The destination address cannot be null!");}@@ -254,11 +252,11 @@ public class FunctionSignatureMarkupType extends FunctionEntryPointBasedAbstractAddress destinationAddress) {Address expectedDestinationAddress = association.getDestinationAddress();if (expectedDestinationAddress.equals(destinationAddress)) {- Function function = getDestinationFunction(association);- if (function == null) {+ Function destFunction = getDestinationFunction(association);+ if (destFunction == null) {return null;}- return new FunctionSignatureStringable(function);+ return new FunctionSignatureStringable(destFunction);}return null;}@@ -289,6 +287,7 @@ public class FunctionSignatureMarkupType extends FunctionEntryPointBasedAbstract@Overridepublic Options convertOptionsToForceApplyOfMarkupItem(VTMarkupItemApplyActionType applyAction,ToolOptions applyOptions) {+ToolOptions options = applyOptions.copy();switch (applyAction) {case ADD:@@ -316,21 +315,19 @@ public class FunctionSignatureMarkupType extends FunctionEntryPointBasedAbstractpublic boolean hasSameSourceAndDestinationValues(VTMarkupItem markupItem) {VTAssociation association = markupItem.getAssociation();- Function sourceFunction = getSourceFunction(association);- Function destinationFunction = getDestinationFunction(association);- if (sourceFunction == null || destinationFunction == null) {+ Function srcFunction = getSourceFunction(association);+ Function destFunction = getDestinationFunction(association);+ if (srcFunction == null || destFunction == null) {return false;}- FunctionSignatureStringable sourceStringable =- new FunctionSignatureStringable(sourceFunction);- FunctionSignatureStringable destinationStringable =- new FunctionSignatureStringable(destinationFunction);- return SystemUtilities.isEqual(sourceStringable, destinationStringable);++ FunctionSignatureStringable srcStringable = new FunctionSignatureStringable(srcFunction);+ FunctionSignatureStringable destStringable = new FunctionSignatureStringable(destFunction);+ return Objects.equals(srcStringable, destStringable);}@Override- public boolean conflictsWithOtherMarkup(MarkupItemImpl markupItem,- Collection<VTMarkupItem> markupItems) {+ public boolean conflictsWithOtherMarkup(MarkupItemImpl item, Collection<VTMarkupItem> others) {return false;}}diff --git a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/stringable/FunctionSignatureStringable.java b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/stringable/FunctionSignatureStringable.javaindex fb3d34edec..34daa5ddab 100644--- a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/stringable/FunctionSignatureStringable.java+++ b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/stringable/FunctionSignatureStringable.java@@ -15,10 +15,13 @@*/package ghidra.feature.vt.api.stringable;+import static ghidra.feature.vt.gui.util.VTMatchApplyChoices.ParameterDataTypeChoices.*;import static ghidra.feature.vt.gui.util.VTOptionDefines.*;import java.util.*;+import org.apache.commons.lang3.StringUtils;+import ghidra.feature.vt.api.util.Stringable;import ghidra.feature.vt.api.util.VersionTrackingApplyException;import ghidra.feature.vt.gui.util.VTMatchApplyChoices;@@ -31,6 +34,7 @@ import ghidra.program.model.lang.*;import ghidra.program.model.listing.*;import ghidra.program.model.listing.Function.FunctionUpdateType;import ghidra.program.model.symbol.*;+import ghidra.program.util.DataTypeCleaner;import ghidra.program.util.FunctionUtility;import ghidra.util.*;import ghidra.util.exception.DuplicateNameException;@@ -77,10 +81,13 @@ public class FunctionSignatureStringable extends Stringable {this.callingConventionName = function.getCallingConventionName();this.callFixup = function.getCallFixup();- // The Function Signature cares about the signature source, custom storage,- // return type/storage, calling convention, parameter data type/storage,- // parameter names and source types, parameter comments, varArgs,- // inline flag, no return flag, and call fixup.+ /*+ The Function Signature cares about:+ signature source, custom storage, return type/storage, calling convention,+ parameter:+ data type/storage, names, source types, comments,+ varArgs, inline flag, no return flag, and call fixup.+ */this.signatureSource = function.getSignatureSource();this.hasCustomStorage = function.hasCustomVariableStorage();@@ -100,8 +107,9 @@ public class FunctionSignatureStringable extends Stringable {String name = parameter.getName(); // default names can be significant!String comment = parameter.getComment();DataType dt = parameter.getDataType();- String paramStorage = parameter.getVariableStorage().getSerializationString();- return new ParameterInfo(dt, name, paramStorage, source, comment);+ VariableStorage storage = parameter.getVariableStorage();+ String storageString = storage.getSerializationString();+ return new ParameterInfo(dt, name, storageString, source, comment);}public boolean hasCustomStorage() {@@ -116,9 +124,10 @@ public class FunctionSignatureStringable extends Stringable {if (signatureString != null) {return signatureString;}- StringBuffer buf = new StringBuffer();++ StringBuilder buf = new StringBuilder();buf.append(returnInfo.dataType.getDisplayName());- buf.append(" ");+ buf.append(' ');if (isInline) {buf.append("inline ");@@ -133,31 +142,31 @@ public class FunctionSignatureStringable extends Stringable {!callingConventionName.equals(Function.DEFAULT_CALLING_CONVENTION_STRING) &&!callingConventionName.equals(Function.UNKNOWN_CALLING_CONVENTION_STRING)) {buf.append(callingConventionName);- buf.append(" ");+ buf.append(' ');}buf.append(originalName);- buf.append("(");+ buf.append('(');- int paramCnt = parameterInfos.size();- boolean emptyList = true;- for (int i = 0; i < paramCnt; i++) {+ int n = parameterInfos.size();+ boolean isVoid = n == 0;+ for (int i = 0; i < n; i++) {ParameterInfo paramInfo = parameterInfos.get(i);buf.append(paramInfo.dataType.getDisplayName());- buf.append(" ");+ buf.append(' ');buf.append(paramInfo.name);- emptyList = false;- if ((i < (paramCnt - 1)) || hasVarargs) {+ if (i < n - 1 || hasVarargs) {buf.append(", ");}}+if (hasVarargs) {buf.append(FunctionSignature.VAR_ARGS_DISPLAY_STRING);}- else if (emptyList && signatureSource != SourceType.DEFAULT) {+ else if (isVoid && signatureSource != SourceType.DEFAULT) {buf.append(FunctionSignature.VOID_PARAM_DISPLAY_STRING);}- buf.append(")");+ buf.append(')');signatureString = buf.toString();return signatureString;@@ -168,40 +177,50 @@ public class FunctionSignatureStringable extends Stringable {if (returnInfo == null) {return "undefined " + SHORT_NAME + "()";}- StringBuffer buf = new StringBuffer();++ StringBuilder buf = new StringBuilder();buf.append(getSignatureDisplayString());- if (hasCustomStorage && (program != null)) {- try {- buf.append(" CustomStorage: ");- VariableStorage returnVariableStorage =- VariableStorage.deserialize(program, returnInfo.storage);- buf.append(returnVariableStorage.toString() + " ");- buf.append("(");- int numParams = parameterInfos.size();- for (int i = 0; i < numParams; i++) {- String parameterStorageString = parameterInfos.get(i).storage;- VariableStorage variableStorage =- VariableStorage.deserialize(program, parameterStorageString);- buf.append(variableStorage.toString());- if ((i < (numParams - 1)) || hasVarargs) {- buf.append(", ");- }- }- if (hasVarargs) {- buf.append(FunctionSignature.VAR_ARGS_DISPLAY_STRING);++ addCustomStorageText(buf);++ if (callFixup != null) {+ buf.append(' ').append(callFixup);+ }++ return buf.toString();+ }++ private void addCustomStorageText(StringBuilder buf) {+ if (!hasCustomStorage || program == null) {+ return;+ }++ buf.append(" CustomStorage: ");+ try {+ VariableStorage returnStorage =+ VariableStorage.deserialize(program, returnInfo.storage);+ buf.append(returnStorage).append(' ');+ buf.append('(');+ int n = parameterInfos.size();+ for (int i = 0; i < n; i++) {+ String storageString = parameterInfos.get(i).storage;+ VariableStorage variableStorage =+ VariableStorage.deserialize(program, storageString);+ buf.append(variableStorage);+ if (i < n - 1 || hasVarargs) {+ buf.append(", ");}- buf.append(")");}- catch (InvalidInputException e) {- buf.append("Error getting variable storage.");- e.printStackTrace();++ if (hasVarargs) {+ buf.append(FunctionSignature.VAR_ARGS_DISPLAY_STRING);}+ buf.append(')');}- if (callFixup != null) {- buf.append(" " + callFixup);+ catch (InvalidInputException e) {+ buf.append("Error getting variable storage.");+ Msg.error(this, "Error getting variable storage.", e);}-- return buf.toString();}@Override@@ -212,21 +231,21 @@ public class FunctionSignatureStringable extends Stringable {}DataTypeManager dataTypeManager = desiredProgram.getDataTypeManager();- StringBuilder buildy = new StringBuilder();- buildy.append(getSavableFunctionSignatureSource()).append(DELIMITER);- buildy.append(getSavableIsInline()).append(DELIMITER);- buildy.append(getSavableHasNoReturn()).append(DELIMITER);- buildy.append(getSavableCallingConvention()).append(DELIMITER);- buildy.append(getSavableCallFixup()).append(DELIMITER);- buildy.append(originalName).append(DELIMITER);- buildy.append(getSavableHasCustomStorage()).append(DELIMITER);- buildy.append(getSavableReturnType(dataTypeManager)).append(DELIMITER);- buildy.append(getSavableReturnStorage()).append(DELIMITER);- buildy.append(getSavableParameterStorage()).append(DELIMITER);- buildy.append(getSavableVarArgs()).append(DELIMITER);- buildy.append(Boolean.toString(isThisCall)).append(DELIMITER);- buildy.append(saveParameterInfos());- return buildy.toString();+ StringBuilder buf = new StringBuilder();+ buf.append(getSavableFunctionSignatureSource()).append(DELIMITER);+ buf.append(getSavableIsInline()).append(DELIMITER);+ buf.append(getSavableHasNoReturn()).append(DELIMITER);+ buf.append(getSavableCallingConvention()).append(DELIMITER);+ buf.append(getSavableCallFixup()).append(DELIMITER);+ buf.append(originalName).append(DELIMITER);+ buf.append(getSavableHasCustomStorage()).append(DELIMITER);+ buf.append(getSavableReturnType(dataTypeManager)).append(DELIMITER);+ buf.append(getSavableReturnStorage()).append(DELIMITER);+ buf.append(getSavableParameterStorage()).append(DELIMITER);+ buf.append(getSavableVarArgs()).append(DELIMITER);+ buf.append(Boolean.toString(isThisCall)).append(DELIMITER);+ buf.append(saveParameterInfos());+ return buf.toString();}private String getSavableReturnType(DataTypeManager dataTypeManager) {@@ -237,11 +256,12 @@ public class FunctionSignatureStringable extends Stringable {makePointer = true;dt = ((Pointer) dt).getDataType();}- String str = Long.toString(dataTypeManager.getResolvedID(dt));++ String id = Long.toString(dataTypeManager.getResolvedID(dt));if (makePointer) {- str = MAKE_POINTER_PREFIX + str;+ id = MAKE_POINTER_PREFIX + id;}- return str;+ return id;}private String getSavableFunctionSignatureSource() {@@ -276,12 +296,12 @@ public class FunctionSignatureStringable extends Stringable {}private String getSavableParameterStorage() {- StringBuilder storageBuilder = new StringBuilder();- storageBuilder.append(parameterInfos.size()).append(PARAMETER_STORAGE_DELIMITER);- for (ParameterInfo paramInfo : parameterInfos) {- storageBuilder.append(paramInfo.storage).append(PARAMETER_STORAGE_DELIMITER);+ StringBuilder buf = new StringBuilder();+ buf.append(parameterInfos.size()).append(PARAMETER_STORAGE_DELIMITER);+ for (ParameterInfo info : parameterInfos) {+ buf.append(info.storage).append(PARAMETER_STORAGE_DELIMITER);}- return storageBuilder.toString();+ return buf.toString();}private String getSavableVarArgs() {@@ -292,7 +312,7 @@ public class FunctionSignatureStringable extends Stringable {protected void doRestoreFromString(String string, Program desiredProgram) {signatureString = null;StringTokenizer tokenizer = new StringTokenizer(string, DELIMITER);- List<String> strings = new LinkedList<>();+ Queue<String> strings = new LinkedList<>(); // use a queue since we remove from the frontwhile (tokenizer.hasMoreTokens()) {strings.add(tokenizer.nextToken());}@@ -300,79 +320,69 @@ public class FunctionSignatureStringable extends Stringable {program = desiredProgram;DataTypeManager dataTypeManager = desiredProgram.getDataTypeManager();- signatureSource = SourceType.valueOf(strings.remove(0)); // Signature Source- isInline = Boolean.parseBoolean(strings.remove(0)); // Inline Flag- hasNoReturn = Boolean.parseBoolean(strings.remove(0)); // NoReturn Flag- callingConventionName = strings.remove(0); // Calling Convention Name- callFixup = strings.remove(0); // Call Fixup+ signatureSource = SourceType.valueOf(strings.remove()); // Signature Source+ isInline = Boolean.parseBoolean(strings.remove()); // Inline Flag+ hasNoReturn = Boolean.parseBoolean(strings.remove()); // NoReturn Flag+ callingConventionName = strings.remove(); // Calling Convention Name+ callFixup = strings.remove(); // Call Fixupif (callFixup.equals("none")) {callFixup = null;}- originalName = strings.remove(0); // Original Function Name- hasCustomStorage = Boolean.parseBoolean(strings.remove(0)); // Custom Storage Flag- String returnTypeID = strings.remove(0); // Return DataType ID with optional MAKE_POINTER_PREFIX- String returnStorage = strings.remove(0); // Return Storage++ originalName = strings.remove(); // Original Function Name+ hasCustomStorage = Boolean.parseBoolean(strings.remove()); // Custom Storage Flag+ String returnTypeID = strings.remove(); // Return DataType ID with optional MAKE_POINTER_PREFIX+ String returnStorage = strings.remove(); // Return StoragereturnInfo = new ParameterInfo(returnTypeID, dataTypeManager, Parameter.RETURN_NAME,returnStorage, SourceType.DEFAULT, null);- String parameterStorageString = strings.remove(0); // Parameter Storage- // Now pull apart the parameter storage and put it in the list.- StringTokenizer parameterTokenizer =- new StringTokenizer(parameterStorageString, PARAMETER_STORAGE_DELIMITER);- // parameterStorageCount currently guarantees there is something in the parameter storage token.-// String parameterStorageCount = parameterTokenizer.nextToken();- List<String> parameterStorage = new LinkedList<>();- // TODO: do we need to check parameterStorageCount- while (parameterTokenizer.hasMoreTokens()) {- parameterStorage.add(parameterTokenizer.nextToken());+ String storageString = strings.remove(); // Parameter Storage+ StringTokenizer storageTokenizer =+ new StringTokenizer(storageString, PARAMETER_STORAGE_DELIMITER);+ storageTokenizer.nextToken(); // ignore param count; not used+ List<String> parameterStorage = new ArrayList<>();+ while (storageTokenizer.hasMoreTokens()) {+ parameterStorage.add(storageTokenizer.nextToken());}- hasVarargs = Boolean.parseBoolean(strings.remove(0)); // VarArgs Flag- isThisCall = Boolean.parseBoolean(strings.remove(0)); // "This" Calling Convention Flag+ hasVarargs = Boolean.parseBoolean(strings.remove()); // VarArgs Flag+ isThisCall = Boolean.parseBoolean(strings.remove()); // "This" Calling Convention Flag- // Now get the parameter infowhile (!strings.isEmpty()) {- String parameterInfoString = strings.remove(0);- // Now pull apart the parameter info.- StringTokenizer parameterInfoTokenizer =- new StringTokenizer(parameterInfoString, PARAMETER_INFO_DELIMITER);- String dtIDString = parameterInfoTokenizer.nextToken();- String name = parameterInfoTokenizer.nextToken();- if (name != null && name.isEmpty()) {+ String paramInfoString = strings.remove();+ StringTokenizer paramTokenizer =+ new StringTokenizer(paramInfoString, PARAMETER_INFO_DELIMITER);+ String dtId = paramTokenizer.nextToken();+ String name = paramTokenizer.nextToken();+ if (StringUtils.isBlank(name)) {name = null;}- String sourceAsName = parameterInfoTokenizer.nextToken();++ String sourceAsName = paramTokenizer.nextToken();SourceType source = SourceType.valueOf(sourceAsName);String comment = null;try {- comment = parameterInfoTokenizer.nextToken();+ comment = paramTokenizer.nextToken();}catch (NoSuchElementException e) {// Do nothing. There isn't a comment.}- if (comment == null || comment.isEmpty()) {++ if (StringUtils.isBlank(comment)) {comment = null;}String decodedComment = decodeString(comment);-String storage = null;int index = parameterInfos.size();if (parameterStorage.size() > index) {storage = parameterStorage.get(index);}- parameterInfos.add(new ParameterInfo(dtIDString, dataTypeManager, name, storage, source,+ parameterInfos.add(new ParameterInfo(dtId, dataTypeManager, name, storage, source,decodedComment));}}- private boolean isDefaultParameterName(String name) {- if (name == null) {- return true;- }- return SymbolUtilities.isDefaultParameterName(name);- }-private String saveParameterInfos() {StringBuilder storageBuilder = new StringBuilder();int nameCount = parameterInfos.size();@@ -484,50 +494,90 @@ public class FunctionSignatureStringable extends Stringable {return true;}- public boolean sameFunctionSignature(Function function) {+ public boolean isSameFunctionSignature(Function function) {return equals(new FunctionSignatureStringable(function));}/**- *- * @param toFunction the function whose signature we are setting.+ * Returns true if the signature is applied+ *+ * @param destFunction the function whose signature we are setting.* @param markupOptions the options indicate what parts of the function signature to apply.* @param forceApply true indicates that the function signature should be applied even if the* function signature, return type, parameter data type or parameter name options are set* to "do not apply".+ * @return true if the signature is applied* @throws VersionTrackingApplyException if all desired parts of the function signature couldn't be applied.*/- public boolean applyFunctionSignature(Function toFunction, ToolOptions markupOptions,- boolean forceApply) throws VersionTrackingApplyException {-- VTMatchApplyChoices.FunctionSignatureChoices functionSignatureChoice = markupOptions- .getEnum(VTOptionDefines.FUNCTION_SIGNATURE, DEFAULT_OPTION_FOR_FUNCTION_SIGNATURE);+ public boolean applyFunctionSignature(Function destFunction,+ ToolOptions markupOptions, boolean forceApply) throws VersionTrackingApplyException {- int toParamCount = toFunction.getParameterCount();-- if ((functionSignatureChoice == FunctionSignatureChoices.WHEN_SAME_PARAMETER_COUNT) &&- (toParamCount != parameterInfos.size())) {- // Don't replace since number of parameters differs.+ if (doesParamCountMismatchPreventApply(destFunction, markupOptions)) {Msg.debug(this, "Number of parameters differs so function signature not applied at " +- toFunction.getEntryPoint() + ".");+ destFunction.getEntryPoint() + ".");return false;}++ applyInline(destFunction, isInline, markupOptions);+ applyNoReturn(destFunction, hasNoReturn, markupOptions);++ applyParameterTypes(destFunction, markupOptions, forceApply);++ boolean hasSrcVarArgs = hasVarargs;+ boolean hasDestVarArgs = destFunction.hasVarArgs();+ if (hasSrcVarArgs != hasDestVarArgs) {+ applyVarArgs(destFunction, hasSrcVarArgs, markupOptions);+ }++ applyCallFixup(destFunction, callFixup, markupOptions);++ if (forceApply) {+ forceParameterNames(destFunction);+ }+ else {+ int paramCount = destFunction.getParameterCount();+ applyParameterNames(destFunction, markupOptions, true, paramCount);+ }+CommentChoices commentChoice =markupOptions.getEnum(PARAMETER_COMMENTS, DEFAULT_OPTION_FOR_PARAMETER_COMMENTS);+ replaceParameterComments(destFunction, commentChoice);- // Set the parameters and their storage.- try {+ return true;+ }- applyInline(toFunction, isInline, markupOptions);- applyNoReturn(toFunction, hasNoReturn, markupOptions);+ private boolean doesParamCountMismatchPreventApply(Function destFunction,+ ToolOptions markupOptions) {- String conventionName = getCallingConvention(toFunction, markupOptions);+ VTMatchApplyChoices.FunctionSignatureChoices functionSignatureChoice = markupOptions+ .getEnum(VTOptionDefines.FUNCTION_SIGNATURE, DEFAULT_OPTION_FOR_FUNCTION_SIGNATURE);- // Adjust whether or not the resulting function will use custom storage.- boolean useCustomStorage = false;+ int paramCount = destFunction.getParameterCount();+ if (functionSignatureChoice == FunctionSignatureChoices.WHEN_SAME_PARAMETER_COUNT &&+ paramCount != parameterInfos.size()) {+ return true;+ }++ return false;+ }++ private void applyParameterTypes(Function destFunction, ToolOptions markupOptions,+ boolean forceApply) throws VersionTrackingApplyException {+ DataTypeCleaner dtCleaner = null;+ if (markupOptions.getBoolean(USE_EMPTY_COMPOSITES,+ // The user would like to create empty structures when creating data types+ DEFAULT_OPTION_FOR_USE_EMPTY_STRUCTURES)) {+ ProgramBasedDataTypeManager destDtm = destFunction.getProgram().getDataTypeManager();+ dtCleaner = new DataTypeCleaner(destDtm, false);+ }++ try {++ String conventionName = getCallingConvention(destFunction, markupOptions);+ boolean useCustomStorage = false;boolean sameLanguage =- FunctionUtility.isSameLanguageAndCompilerSpec(toFunction.getProgram(), program);+ FunctionUtility.isSameLanguageAndCompilerSpec(destFunction.getProgram(), program);// if source program has custom storage and both programs have same language then// set the useCustomStorage flag to enable using custom storage in destination program@@ -536,214 +586,200 @@ public class FunctionSignatureStringable extends Stringable {}Parameter returnParam =- getReturnParameter(toFunction, markupOptions, forceApply, useCustomStorage);+ getReturnParameter(destFunction, markupOptions, forceApply, useCustomStorage,+ dtCleaner);List<Parameter> newParams =- getParameters(toFunction, markupOptions, forceApply, useCustomStorage);+ getParameters(destFunction, markupOptions, forceApply, useCustomStorage,+ dtCleaner);- toFunction- .updateFunction(conventionName, returnParam, newParams,- useCustomStorage ? FunctionUpdateType.CUSTOM_STORAGE- : FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS,- true, signatureSource);+ FunctionUpdateType updateType = useCustomStorage ? FunctionUpdateType.CUSTOM_STORAGE+ : FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS;+ destFunction.updateFunction(conventionName, returnParam, newParams, updateType,+ true, signatureSource);- // Test to see if destination function is now in the same namespace as the source- // if so copy the class structure from source to destination if the update didn't- copyClassStructure(newParams, toFunction, markupOptions);+ maybeCopyClassStructure(newParams, destFunction, markupOptions, dtCleaner);if (forceApply) {// must force signatureSource if precedence has been lowered- // TODO: Should any manual change in function signature force source to be USER_DEFINED instead ??- toFunction.setSignatureSource(signatureSource);+ destFunction.setSignatureSource(signatureSource);}}- catch (DuplicateNameException e) {- throw new VersionTrackingApplyException(e.getMessage(), e);- }- catch (InvalidInputException e) {+ catch (DuplicateNameException | InvalidInputException e) {throw new VersionTrackingApplyException(e.getMessage(), e);}-- boolean hasFromVarArgs = hasVarargs;- boolean hasToVarArgs = toFunction.hasVarArgs();- if (hasFromVarArgs != hasToVarArgs) {- applyVarArgs(toFunction, hasFromVarArgs, markupOptions);- }- applyCallFixup(toFunction, callFixup, markupOptions);-- if (forceApply) {- forceParameterNames(toFunction);- }- else {- applyParameterNames(toFunction, markupOptions, true, toParamCount);+ finally {+ if (dtCleaner != null) {+ dtCleaner.close();+ }}-- replaceParameterComments(toFunction, commentChoice);-- return true;}- /**+ /** Method to determine if a copy is needed of the source class struct to the destination program* and if so, does the copy- * @param newParams the params to apply to the destination program as determined by the apply- * options- * @param toFunction the destination function*/- private void copyClassStructure(List<Parameter> newParams, Function toFunction,- ToolOptions markupOptions) {+ private void maybeCopyClassStructure(List<Parameter> newParams, Function destFunction,+ ToolOptions markupOptions, DataTypeCleaner dtCleaner) {- // this is only meant to handle the case where there are auto this params- // existing other mechanisms handle custom storage case already- if (toFunction.hasCustomVariableStorage()) {+ if (newParams.isEmpty()) {return;}- VTMatchApplyChoices.ParameterDataTypeChoices parameterDataTypesChoice =+ VTMatchApplyChoices.ParameterDataTypeChoices applyChoice =markupOptions.getEnum(VTOptionDefines.PARAMETER_DATA_TYPES,DEFAULT_OPTION_FOR_PARAMETER_DATA_TYPES);-- if (parameterDataTypesChoice == ParameterDataTypeChoices.EXCLUDE) {+ if (applyChoice == EXCLUDE) {return;}- boolean onlyReplaceUndefineds =- (parameterDataTypesChoice == ParameterDataTypeChoices.REPLACE_UNDEFINED_DATA_TYPES_ONLY);-- boolean replaceAlways = (parameterDataTypesChoice == ParameterDataTypeChoices.REPLACE);+ // This method is only meant to handle the case where there are auto this params. Other+ // mechanisms handle custom storage case already.+ if (destFunction.hasCustomVariableStorage()) {+ return;+ }- // check to see if the resulting newParams after checking the markupOptions includes- // a this param and if so resolve the class data type in the destination program- // to make sure the class structure gets copied to the destination program+ //+ // Check to see if the newParams includes a this param and if so resolve the class data type+ // in the destination program to make sure the class structure gets copied to the+ // destination program.+ //- // if source function is not a thiscall then no class structure to copy+ // if source function is not a 'thiscall' then no class structure to copyif (!callingConventionName.equals(CompilerSpec.CALLING_CONVENTION_thiscall)) {return;}- // if there are no new params to apply as determined by the options then nothing to copy- if (newParams.isEmpty()) {++ // if newParams does not have a this param then no copy needed+ Parameter destParam1 = newParams.get(0);+ String destParam1Name = destParam1.getName();+ if (!destParam1Name.equals("this")) {return;}- // if newParams does not have a this param to copy as determined by the apply options then- // no copy needed- if (!newParams.get(0).getName().equals("this")) {+ // Verify the source this param is a pointer to a structure+ ParameterInfo sourceParam1 = parameterInfos.get(0);+ DataType srcClassDt = getPointedToDataType(sourceParam1.dataType);+ if (!isStructure(srcClassDt)) {return;}- // get the this param for source and verify it is a pointer to a structure- ParameterInfo sourceParam1 = parameterInfos.get(0);- DataType sourceClassDataType = getPointedToDataType(sourceParam1.dataType);- if (sourceClassDataType == null) {+ // Verify the destination this param is a pointer to a structure+ DataType paramDt = destParam1.getDataType();+ DataType destClassDt = getPointedToDataType(paramDt);+ if (!isStructure(destClassDt)) {return;}- if (!isStructure(sourceClassDataType)) {+ // If we get this far, then assume both the new destination and source this+ // data types are pointers to class structures.+ //+ // NOTE: we need check to see if the current function namespace is already+ // the same as the assumed new destination this structure name which would indicate that+ // the function already was in the same class and so we still need to do the resolve to make+ // sure that the structure contents get resolved according to the parameter replace options+ VTMatchApplyChoices.FunctionNameChoices functionNameChoice =+ markupOptions.getEnum(VTOptionDefines.FUNCTION_NAME, DEFAULT_OPTION_FOR_FUNCTION_NAME);+ Symbol functionSymbol = destFunction.getSymbol();+ String currentDestNamespace = functionSymbol.getParentNamespace().getName();+ String newDestnClassName = destClassDt.getName();+ if (functionNameChoice == FunctionNameChoices.EXCLUDE &&+ !currentDestNamespace.equals(newDestnClassName)) {++ // This check is odd. I suppose we are trying to handle the case where the name was not+ // changed, but the namespace was updated. In that case, we only need to copy the class+ // if the function was moved into a class namespace. If the namespace names do not+ // match, then that copy didn't happen.return;}- // get the pointed to data type for the new destination this param- // if it isn't a pointer to a data type then return- Parameter newDestinationParam1 = newParams.get(0);- DataType newDestinationClassDataType =- getPointedToDataType(newDestinationParam1.getDataType());- if (newDestinationClassDataType == null) {+ // Use the source path get the same named structure in the destination data type manager+ ProgramBasedDataTypeManager destDtm = destFunction.getProgram().getDataTypeManager();+ String srcClassPath = srcClassDt.getPathName();+ DataType existingDestDt = destDtm.getDataType(srcClassPath);+ if (!shouldCopyClassStructure(applyChoice, existingDestDt)) {return;}- // if the new this param (ie what the calling method has determined what the new this- // param is supposed to be) is not a pointer to a structure then return because it- // doesn't think it should also be a class structure- if (!isStructure(newDestinationClassDataType)) {+ // Use the original data type to get the struct *+ DataType dt = sourceParam1.dataType;+ if (dtCleaner != null) {+ // resolve an empty composite+ dt = dtCleaner.clean(dt);+ }++ // resolve the full data type+ destDtm.resolve(dt,+ DataTypeConflictHandler.REPLACE_EMPTY_STRUCTS_OR_RENAME_AND_ADD_HANDLER);++ warnAboutClassConflicts(destFunction, destClassDt, srcClassPath);+ }++ private void warnAboutClassConflicts(Function toFunction, DataType newDestClassDt,+ String srcClassPath) {++ // Check to see if the resolve probably updated the function's auto this param datatype.+ // It might not have if there was a .conflict created during the resolve or if the+ // source and destination data types were in different folders or if one program+ // has the preferred root data type manager folder set and the other doesn't.+ // Not sure there is a way to tell this info since I don't know which the decompiler will+ // pick at this point because nothing has been applied yet.+ ProgramBasedDataTypeManager destDtm = toFunction.getProgram().getDataTypeManager();+ DataType destDtConflict = destDtm.getDataType(srcClassPath + ".conflict");+ if (destDtConflict != null) {+ Msg.debug(this, "Copied" + newDestClassDt.getPathName() ++ " to the destination program but a .conflict was created due to an existing " ++ "non-empty structure with that same path and name.");+ }++ // get the original toFunction this param if there was one and get it's path+ // if the new path is different then spit out warming too+ if (toFunction.getParameterCount() == 0) {return;}- // if it gets this far then can probably assume both the new destination and source this- // data types are pointers to class structures- // NOTE: at this time there is a use case where the calling method incorrectly assumes the- // newParam is the same class structure as the source one. However, that method did not- // check the FunctionName option to see if that option was to not replace the function- // name. So we need to have a check to see if the current function namespace is already- // the same as the assumed new destination this structure name which would indicate that- // the function already was in the same class and so we still need to do the resolve to make- // sure that the structure contents get resolved according to the parameter replace options- VTMatchApplyChoices.FunctionNameChoices functionNameChoice =- markupOptions.getEnum(VTOptionDefines.FUNCTION_NAME, DEFAULT_OPTION_FOR_FUNCTION_NAME);- String currentDestinationFunctionNamespaceName =- toFunction.getSymbol().getParentNamespace().getName();- String newDestinationClassName = newDestinationClassDataType.getName();- if (functionNameChoice == FunctionNameChoices.EXCLUDE &&- !currentDestinationFunctionNamespaceName.equals(newDestinationClassName)) {+ Parameter existingDestParam1 = toFunction.getParameter(0);+ if (!existingDestParam1.getName().equals("this")) {return;}- // now use the path to the source data type to try and get the same named structure- // in the destination data type manager- ProgramBasedDataTypeManager destinationDataTypeManager =- toFunction.getProgram().getDataTypeManager();-- String pathName = sourceClassDataType.getPathName();- DataType destinationDataTypeInDTM = destinationDataTypeManager.getDataType(pathName);-- // only do the copy if the option is to replace always or if it is replace undefines and the- // destination structure is empty (ie undefined)- if (replaceAlways ||- destinationDataTypeInDTM == null ||- (destinationDataTypeInDTM.isNotYetDefined() && onlyReplaceUndefineds)) {-- // since nothing above prevents the copy go ahead and copy the source class data type-- //needs to be the original dt to get the struct * not just the struct- destinationDataTypeManager.resolve(sourceParam1.dataType,- DataTypeConflictHandler.REPLACE_EMPTY_STRUCTS_OR_RENAME_AND_ADD_HANDLER);-- // check to see if the resolve probably updated the function's auto this param datatype- // it might not have if there was a .conflict created during the resolve or if the- // source and destination data types were in different folders or if one program- // has the preferred root data type manager folder set and the other doesn't- // not sure there is a way to tell this info since I don't know which the decompiler will- // pick at this point because nothing has been applied yet- DataType destinationDataTypeConflict =- destinationDataTypeManager.getDataType(pathName + ".conflict");-- if (destinationDataTypeConflict != null) {- Msg.debug(this, "The applied class structure " +- newDestinationClassDataType.getPathName() +- " was copied to the destination program but a .conflict was created due to there " +- "already being a non-empty structure with that same path and name.");- }+ DataType pointedToDt = getPointedToDataType(existingDestParam1.getDataType());+ if (pointedToDt == null) {+ return;+ }- // get the original toFunction this param if there was one and get it's path- // if the new path is different then spit out warming too- if (toFunction.getParameterCount() == 0) {- return;- }+ if (!pointedToDt.getName().equals(newDestClassDt.getName())) {+ return;+ }- if (!toFunction.getParameter(0).getName().equals("this")) {- return;- }+ String existingClassPath = pointedToDt.getPathName();+ if (existingClassPath.equals(srcClassPath)) {+ return; // message already printed with conflict check above+ }- DataType pointedToDataType =- getPointedToDataType(toFunction.getParameter(0).getDataType());- if (pointedToDataType == null) {- return;- }+ //@formatter:off+ String message = """+ Class structure copied to '%s' which is different than the existing class structure \+ path '%s'. The decompiler will first check for one in the Preferred Class Root Folder \+ (if one has been set) otherwise it will use the first one it finds.+ """.formatted(srcClassPath, existingClassPath);+ //@formatter:on+ Msg.debug(this, message);+ }- if (!pointedToDataType.getName().equals(newDestinationClassName)) {- return;- }+ private boolean shouldCopyClassStructure(ParameterDataTypeChoices applyChoice,+ DataType existingDestDt) {- if (pointedToDataType.getPathName().equals(pathName)) {- return; // already handled with conflict check above- }+ if (applyChoice == REPLACE) {+ return true; // always replace+ }- Msg.debug(this,- "The applied class structure was copied to the same data type manager " +- "path as in the source program whichi is different than the path to the existing " +- "class structure. The decompiler will first check for one in the Preferred Class" +- "Root Folder (if one has been set) otherwise it will use the first one it finds.");+ if (existingDestDt == null) {+ return true; // no class; need to copy}+ boolean onlyReplaceUndefineds = applyChoice == REPLACE_UNDEFINED_DATA_TYPES_ONLY;+ return existingDestDt.isNotYetDefined() && onlyReplaceUndefineds;}private boolean isStructure(DataType dataType) {@@ -761,15 +797,10 @@ public class FunctionSignatureStringable extends Stringable {}private DataType getPointedToDataType(DataType dataType) {-- if (!(dataType instanceof PointerDataType)) {- return null;+ if (dataType instanceof PointerDataType pointer) {+ return pointer.getDataType();}-- PointerDataType pointerDataType = (PointerDataType) dataType;-- return pointerDataType.getDataType();-+ return null;}private void applyInline(Function toFunction, boolean fromFunctionIsInline,@@ -787,28 +818,31 @@ public class FunctionSignatureStringable extends Stringable {}}- private Parameter getReturnParameter(Function toFunction, ToolOptions markupOptions,- boolean forceApply, boolean useCustomStorage) throws InvalidInputException {- Parameter returnParam = toFunction.getReturn();+ private Parameter getReturnParameter(Function destFunction, ToolOptions markupOptions,+ boolean forceApply, boolean useCustomStorage, DataTypeCleaner dtCleaner)+ throws InvalidInputException {++ Parameter returnParam = destFunction.getReturn();ParameterDataTypeChoices returnTypeChoice =markupOptions.getEnum(FUNCTION_RETURN_TYPE, DEFAULT_OPTION_FOR_FUNCTION_RETURN_TYPE);- boolean onlyReplaceUndefineds =- returnTypeChoice == ParameterDataTypeChoices.REPLACE_UNDEFINED_DATA_TYPES_ONLY;if (returnTypeChoice == ParameterDataTypeChoices.EXCLUDE) {return returnParam; // Not replacing return type.}- DataType toReturnType = toFunction.getReturnType();+ DataType toReturnType = destFunction.getReturnType();DataType fromReturnType = returnInfo.dataType;boolean isFromDefault = fromReturnType == DataType.DEFAULT;boolean isToDefault = toReturnType == DataType.DEFAULT;boolean isToUndefined = Undefined.isUndefined(getBaseDataType(toReturnType));+ boolean onlyReplaceUndefineds =+ returnTypeChoice == ParameterDataTypeChoices.REPLACE_UNDEFINED_DATA_TYPES_ONLY;if (!forceApply && onlyReplaceUndefineds) {if (!isToDefault && !isToUndefined) {return returnParam; // can't do it because we should only replace undefined data types.}}+if (!forceApply && isFromDefault) {return returnParam; // do nothing since default data type is lowest priority.}@@ -816,21 +850,29 @@ public class FunctionSignatureStringable extends Stringable {DataType returnType = (forceApply) ? fromReturnType: getHighestPriorityDataType(fromReturnType, toReturnType, onlyReplaceUndefineds);- VariableStorage returnVariableStorage = VariableStorage.UNASSIGNED_STORAGE;+ Program destProgram = destFunction.getProgram();+ VariableStorage storage = VariableStorage.UNASSIGNED_STORAGE;if (useCustomStorage && returnInfo.storage != null) {- returnVariableStorage =- VariableStorage.deserialize(toFunction.getProgram(), returnInfo.storage);+ storage = VariableStorage.deserialize(destProgram, returnInfo.storage);+ }++ // Update the type if the user prefers empty composites+ if (dtCleaner != null) {+ returnType = dtCleaner.clean(returnType);}- return new ReturnParameterImpl(returnType, returnVariableStorage, toFunction.getProgram());++ return new ReturnParameterImpl(returnType, storage, destProgram);}private void applyNoReturn(Function toFunction, boolean fromFunctionHasNoReturn,ToolOptions markupOptions) {+ReplaceChoices noReturnChoice =markupOptions.getEnum(NO_RETURN, DEFAULT_OPTION_FOR_NO_RETURN);if (noReturnChoice == ReplaceChoices.EXCLUDE) {return; // Not replacing no return flag.}+boolean toFunctionHasNoReturn = toFunction.hasNoReturn();if (fromFunctionHasNoReturn == toFunctionHasNoReturn) {return;@@ -842,14 +884,17 @@ public class FunctionSignatureStringable extends Stringable {private void applyVarArgs(Function toFunction, boolean fromFunctionHasVarArgs,ToolOptions markupOptions) {+ReplaceChoices varArgsChoice = markupOptions.getEnum(VAR_ARGS, DEFAULT_OPTION_FOR_VAR_ARGS);if (varArgsChoice == ReplaceChoices.EXCLUDE) {return; // Not replacing var args.}+boolean toFunctionHasVarArgs = toFunction.hasVarArgs();if (fromFunctionHasVarArgs == toFunctionHasVarArgs) {return;}+if (varArgsChoice == ReplaceChoices.REPLACE) {toFunction.setVarArgs(fromFunctionHasVarArgs);}@@ -857,15 +902,18 @@ public class FunctionSignatureStringable extends Stringable {private void applyCallFixup(Function toFunction, String fromFunctionCallFixup,ToolOptions markupOptions) {+ReplaceChoices callFixupChoice =markupOptions.getEnum(CALL_FIXUP, DEFAULT_OPTION_FOR_CALL_FIXUP);if (callFixupChoice == ReplaceChoices.EXCLUDE) {return; // Not replacing call fixup.}+String toFunctionCallFixup = toFunction.getCallFixup();if (SystemUtilities.isEqual(fromFunctionCallFixup, toFunctionCallFixup)) {return;}+if (callFixupChoice == ReplaceChoices.REPLACE) {// Check that you have the same cspec before trying to apply call fixup.if (FunctionUtility.isSameLanguageAndCompilerSpec(toFunction.getProgram(), program)) {@@ -875,16 +923,17 @@ public class FunctionSignatureStringable extends Stringable {}private String getCallingConvention(Function toFunction, ToolOptions markupOptions) {+boolean isFromUnknownCallingConvention =CompilerSpec.isUnknownCallingConvention(callingConventionName);CallingConventionChoices callingConventionChoice =markupOptions.getEnum(CALLING_CONVENTION, DEFAULT_OPTION_FOR_CALLING_CONVENTION);String toCallingConventionName = toFunction.getCallingConventionName();- if (SystemUtilities.isEqual(callingConventionName, toCallingConventionName)) {+ if (Objects.equals(callingConventionName, toCallingConventionName)) {return callingConventionName;}- Program toProgram = toFunction.getProgram();+ Program toProgram = toFunction.getProgram();switch (callingConventionChoice) {case SAME_LANGUAGE:if (FunctionUtility.isSameLanguageAndCompilerSpec(program, toProgram)) {@@ -909,11 +958,12 @@ public class FunctionSignatureStringable extends Stringable {CompilerSpec defaultCompilerSpec = language.getDefaultCompilerSpec();PrototypeModel callingConvention =defaultCompilerSpec.getCallingConvention(myCallingConventionName);- return (callingConvention != null);+ return callingConvention != null;}private List<Parameter> getParameters(Function toFunction, ToolOptions markupOptions,- boolean forceApply, boolean useCustomStorage) throws InvalidInputException {+ boolean forceApply, boolean useCustomStorage, DataTypeCleaner dtCleaner)+ throws InvalidInputException {// See what options the user has specified when applying parameter names.VTMatchApplyChoices.ParameterDataTypeChoices parameterDataTypesChoice =@@ -921,7 +971,7 @@ public class FunctionSignatureStringable extends Stringable {DEFAULT_OPTION_FOR_PARAMETER_DATA_TYPES);boolean onlyReplaceUndefineds =- (parameterDataTypesChoice == ParameterDataTypeChoices.REPLACE_UNDEFINED_DATA_TYPES_ONLY);+ parameterDataTypesChoice == ParameterDataTypeChoices.REPLACE_UNDEFINED_DATA_TYPES_ONLY;Program toProgram = toFunction.getProgram();Parameter[] toParameters = toFunction.getParameters();@@ -951,6 +1001,12 @@ public class FunctionSignatureStringable extends Stringable {dataType =getHighestPriorityDataType(fromDataType, toDataType, onlyReplaceUndefineds);}++ // Update the type if the user prefers empty composites+ if (dtCleaner != null) {+ dataType = dtCleaner.clean(dataType);+ }+VariableStorage storage = VariableStorage.UNASSIGNED_STORAGE;if (useCustomStorage) {if ((i < toCount) && (dataType == toDataType)) {@@ -1008,22 +1064,23 @@ public class FunctionSignatureStringable extends Stringable {}/**- *- * @param toFunction the function whose parameter names we are setting.- * @param markupOptions+ * Applies the given parameter names+ *+ * @param destFunction the function whose parameter names we are setting.+ * @param markupOptions the options* @param doNotReplaceWithDefaultNames flag indicating whether or not a parameter name can be* replaced with a default name.- * @param originalToParamCount original number of parameters in toFunction- * @throws VersionTrackingApplyException+ * @param originalDestParamCount original number of parameters in toFunction+ * @throws VersionTrackingApplyException if there is any exception applying a name*/- public boolean applyParameterNames(Function toFunction, ToolOptions markupOptions,- boolean doNotReplaceWithDefaultNames, int originalToParamCount)+ public void applyParameterNames(Function destFunction, ToolOptions markupOptions,+ boolean doNotReplaceWithDefaultNames, int originalDestParamCount)throws VersionTrackingApplyException {// See what options the user has specified when applying parameter names.VTMatchApplyChoices.SourcePriorityChoices parameterNamesChoice = markupOptions.getEnum(VTOptionDefines.PARAMETER_NAMES, DEFAULT_OPTION_FOR_PARAMETER_NAMES);- VTMatchApplyChoices.HighestSourcePriorityChoices highestPriorityChoice =+ VTMatchApplyChoices.HighestSourcePriorityChoices priorityChoice =markupOptions.getEnum(VTOptionDefines.HIGHEST_NAME_PRIORITY,DEFAULT_OPTION_FOR_HIGHEST_NAME_PRIORITY);boolean replaceSamePriorityNames =@@ -1031,18 +1088,18 @@ public class FunctionSignatureStringable extends Stringable {DEFAULT_OPTION_FOR_PARAMETER_NAMES_REPLACE_IF_SAME_PRIORITY);int fromParameterCount = parameterInfos.size();- int minParameterCount = Math.min(fromParameterCount, originalToParamCount);+ int minParameterCount = Math.min(fromParameterCount, originalDestParamCount);boolean duplicateNameOccurred =- tryToSetNames(toFunction, doNotReplaceWithDefaultNames, parameterNamesChoice,- highestPriorityChoice, replaceSamePriorityNames, minParameterCount);+ tryToSetNames(destFunction, doNotReplaceWithDefaultNames, parameterNamesChoice,+ priorityChoice, replaceSamePriorityNames, minParameterCount);+// If a duplicate name was created, then try applying again to see if it can now be set// to the desired name. A duplicate may have occurred due to changing order of parameters.if (duplicateNameOccurred) {- tryToSetNames(toFunction, doNotReplaceWithDefaultNames, parameterNamesChoice,- highestPriorityChoice, replaceSamePriorityNames, minParameterCount);+ tryToSetNames(destFunction, doNotReplaceWithDefaultNames, parameterNamesChoice,+ priorityChoice, replaceSamePriorityNames, minParameterCount);}- return true;}private boolean tryToSetNames(Function toFunction, boolean doNotReplaceWithDefaultNames,@@ -1051,9 +1108,9 @@ public class FunctionSignatureStringable extends Stringable {boolean replaceSamePriorityNames, int minParameterCount)throws VersionTrackingApplyException {- boolean duplicateNameOccurred = false;- int paramCnt = parameterInfos.size();- for (int i = 0; i < paramCnt; i++) {+ boolean duplicateName = false;+ int n = parameterInfos.size();+ for (int i = 0; i < n; i++) {// Check the name against the options to see when we should set the name.ParameterInfo parameterInfo = parameterInfos.get(i);String fromName = parameterInfo.name;@@ -1066,22 +1123,23 @@ public class FunctionSignatureStringable extends Stringable {if (fromIsDefaultName && (doNotReplaceWithDefaultNames || toIsDefaultName)) {continue;}- if (SystemUtilities.isEqual(fromName, toName)) {+ if (Objects.equals(fromName, toName)) {continue;}+if (i < minParameterCount) {switch (parameterNamesChoice) {case PRIORITY_REPLACE:if (highestPriorityChoice == HighestSourcePriorityChoices.IMPORT_PRIORITY_HIGHEST) {// Import, User, Analysis, Default.- if (!isFirstHigherPriorityWhenImportedPriority(fromSource, toSource,+ if (!isFirstHigherPriorityForImports(fromSource, toSource,replaceSamePriorityNames)) {continue;}}else {// User, Import, Analysis, Default.- if (!isFirstHigherPriorityWhenUserPriority(fromSource, toSource,+ if (!isFirstHigherPriorityWhenForUser(fromSource, toSource,replaceSamePriorityNames)) {continue;}@@ -1101,29 +1159,34 @@ public class FunctionSignatureStringable extends Stringable {}}+ duplicateName = setName(toFunction, toParameter, fromName, fromSource);+ }+ return duplicateName;+ }++ private boolean setName(Function function, Parameter parameter, String name,+ SourceType source) throws VersionTrackingApplyException {++ try {+ parameter.setName(name, source);+ return false;+ }+ catch (DuplicateNameException e) {+ Program p = function.getProgram();+ SymbolTable st = p.getSymbolTable();+ String uniqueName = getUniqueParameterName(st, function, name);try {- toParameter.setName(fromName, fromSource);+ parameter.setName(uniqueName, source);+ return true;}- catch (DuplicateNameException e) {- SymbolTable symbolTable = toFunction.getProgram().getSymbolTable();- String uniqueParameterName =- getUniqueParameterName(symbolTable, toFunction, fromName);- try {- toParameter.setName(uniqueParameterName, fromSource);- duplicateNameOccurred = true;- }- catch (DuplicateNameException e1) {- throw new VersionTrackingApplyException(e1.getMessage(), e1);- }- catch (InvalidInputException e1) {- throw new VersionTrackingApplyException(e1.getMessage(), e1);- }- }- catch (InvalidInputException e) {- throw new VersionTrackingApplyException(e.getMessage(), e);+ catch (DuplicateNameException | InvalidInputException e1) {+ // shouldn't happen+ throw new VersionTrackingApplyException(e1.getMessage(), e1);}}- return duplicateNameOccurred;+ catch (InvalidInputException e) {+ throw new VersionTrackingApplyException(e.getMessage(), e);+ }}/**@@ -1132,10 +1195,9 @@ public class FunctionSignatureStringable extends Stringable {* name in the function.* @param toFunction the function whose parameter names are to be changed using the names* from this stringable.- * @return true if the names are replaced.- * @throws VersionTrackingApplyException+ * @throws VersionTrackingApplyException if there is any exception applying the names*/- private boolean forceParameterNames(Function toFunction) throws VersionTrackingApplyException {+ private void forceParameterNames(Function toFunction) throws VersionTrackingApplyException {boolean duplicateNameOccurred = tryToForceNames(toFunction);if (duplicateNameOccurred) {@@ -1143,14 +1205,11 @@ public class FunctionSignatureStringable extends Stringable {// to the desired name. A duplicate may have occurred due to changing order of parameters.tryToForceNames(toFunction);}-- return true;}private boolean tryToForceNames(Function toFunction) throws VersionTrackingApplyException {- boolean duplicateNameOccurred = false;- int paramCnt = parameterInfos.size();- for (int i = 0; i < paramCnt; i++) {+ boolean duplicateName = false;+ for (int i = 0; i < parameterInfos.size(); i++) {ParameterInfo parameterInfo = parameterInfos.get(i);String fromName = parameterInfo.name;SourceType fromSource = parameterInfo.source;@@ -1158,37 +1217,19 @@ public class FunctionSignatureStringable extends Stringable {if (toParameter.isAutoParameter()) {continue;}+SourceType toSource = toParameter.getSource();String toName = (toSource != SourceType.DEFAULT) ? toParameter.getName() : null;- if (SystemUtilities.isEqual(fromName, toName)) {+ if (Objects.equals(fromName, toName)) {continue;}- try {- toParameter.setName(fromName, fromSource);- }- catch (DuplicateNameException e) {- SymbolTable symbolTable = toFunction.getProgram().getSymbolTable();- String uniqueParameterName =- getUniqueParameterName(symbolTable, toFunction, fromName);- try {- toParameter.setName(uniqueParameterName, fromSource);- duplicateNameOccurred = true;- }- catch (DuplicateNameException e1) {- throw new VersionTrackingApplyException(e1.getMessage(), e1);- }- catch (InvalidInputException e1) {- throw new VersionTrackingApplyException(e1.getMessage(), e1);- }- }- catch (InvalidInputException e) {- throw new VersionTrackingApplyException(e.getMessage(), e);- }++ duplicateName = setName(toFunction, toParameter, fromName, fromSource);}- return duplicateNameOccurred;+ return duplicateName;}- private boolean isFirstHigherPriorityWhenUserPriority(SourceType first, SourceType second,+ private boolean isFirstHigherPriorityWhenForUser(SourceType first, SourceType second,boolean replaceSamePriorityNames) {if (first == SourceType.DEFAULT) {return false;@@ -1199,7 +1240,7 @@ public class FunctionSignatureStringable extends Stringable {return first.isHigherPriorityThan(second);}- private boolean isFirstHigherPriorityWhenImportedPriority(SourceType first, SourceType second,+ private boolean isFirstHigherPriorityForImports(SourceType first, SourceType second,boolean replaceSamePriorityNames) {if (first == SourceType.DEFAULT) {return false;@@ -1232,20 +1273,23 @@ public class FunctionSignatureStringable extends Stringable {String fromComment = parameterInfo.comment;Parameter toParameter = toFunction.getParameter(i);String toComment = toParameter.getComment();- if (SystemUtilities.isEqual(fromComment, toComment)) {+ if (Objects.equals(fromComment, toComment)) {continue;}+if (commentChoice == CommentChoices.APPEND_TO_EXISTING) {String mergedComment = StringUtilities.mergeStrings(toComment, fromComment);- if (mergedComment != null && mergedComment.length() == 0) {+ if (StringUtils.isBlank(mergedComment)) {mergedComment = null;}- if (!SystemUtilities.isEqual(mergedComment, toComment)) {++ if (!Objects.equals(mergedComment, toComment)) {toParameter.setComment(mergedComment);}}+if (commentChoice == CommentChoices.OVERWRITE_EXISTING) {- if (fromComment != null && fromComment.length() == 0) {+ if (StringUtils.isBlank(fromComment)) {fromComment = null;}toParameter.setComment(fromComment);@@ -1261,51 +1305,41 @@ public class FunctionSignatureStringable extends Stringable {private final String comment;private final String storage;- /**- * Create parameter info object- * @param dataTypeID- * @param makePointer if true the specified data-type identified by dataTypeID is wrapped in a pointer- * @param name- * @param source- * @param comment- */private ParameterInfo(DataType dataType, String name, String storage, SourceType source,String comment) {this.dataType = dataType;this.name = name;this.storage = storage;this.source = source;- this.comment = comment;- if (comment != null && comment.trim().length() == 0) {- comment = null;- }+ this.comment = StringUtils.isBlank(comment) ? null : comment;}- private ParameterInfo(String serializedDataTypeID, DataTypeManager dtMgr, String name,+ private ParameterInfo(String serializedDtId, DataTypeManager dtm, String name,String storage, SourceType source, String comment) {- long dataTypeID = -1;+ this.dataType = getDt(dtm, serializedDtId);+ this.name = name;+ this.storage = storage;+ this.source = source;+ this.comment = StringUtils.isBlank(comment) ? null : comment;+ }++ private DataType getDt(DataTypeManager dtm, String dtIdString) {+ long dtId = -1;boolean makePtr = false;- if (serializedDataTypeID != null && !serializedDataTypeID.isEmpty()) {- if (serializedDataTypeID.startsWith(MAKE_POINTER_PREFIX)) {+ if (!StringUtils.isBlank(dtIdString)) {+ if (dtIdString.startsWith(MAKE_POINTER_PREFIX)) {makePtr = true;- serializedDataTypeID =- serializedDataTypeID.substring(MAKE_POINTER_PREFIX.length());+ dtIdString = dtIdString.substring(MAKE_POINTER_PREFIX.length());}- dataTypeID = Long.parseLong(serializedDataTypeID);+ dtId = Long.parseLong(dtIdString);}- DataType dt = dtMgr.getDataType(dataTypeID);++ DataType dt = dtm.getDataType(dtId);if (makePtr) {- dt = new PointerDataType(dt, dtMgr);- }- this.dataType = dt;- this.name = name;- this.storage = storage;- this.source = source;- this.comment = comment;- if (comment != null && comment.trim().length() == 0) {- comment = null;+ dt = new PointerDataType(dt, dtm);}+ return dt;}boolean isEquivalent(ParameterInfo other) {@@ -1344,9 +1378,9 @@ public class FunctionSignatureStringable extends Stringable {String name = baseName;if (name != null) {// establish unique name- int cnt = 0;+ int count = 0;while (symbolTable.getVariableSymbol(name, function) != null) {- name = baseName + (++cnt);+ name = baseName + (++count);}}return name;diff --git a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/provider/matchtable/ApplyMarkupPropertyEditor.java b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/provider/matchtable/ApplyMarkupPropertyEditor.javaindex 688c95243a..b4063be3a9 100644--- a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/provider/matchtable/ApplyMarkupPropertyEditor.java+++ b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/provider/matchtable/ApplyMarkupPropertyEditor.java@@ -119,6 +119,7 @@ public class ApplyMarkupPropertyEditor implements OptionsEditor {private JLabel functionNameLabel;private JLabel functionSignatureLabel;private JLabel useFunctionNamespaceLabel;+ private JLabel useEmptyCompositesLabel;private JLabel returnTypeLabel;private JLabel inlineLabel;private JLabel noReturnLabel;@@ -139,6 +140,7 @@ public class ApplyMarkupPropertyEditor implements OptionsEditor {private JComboBox<Enum<?>> functionNameComboBox;private JComboBox<Enum<?>> functionSignatureComboBox;private JCheckBox useFunctionNamespaceCheckBox;+ private JCheckBox useEmptyCompositesCheckBox;private JComboBox<Enum<?>> returnTypeComboBox;private JComboBox<Enum<?>> callingConventionComboBox;private JComboBox<Enum<?>> inlineComboBox;@@ -426,6 +428,9 @@ public class ApplyMarkupPropertyEditor implements OptionsEditor {panel.add(useFunctionNamespaceLabel);panel.add(useFunctionNamespaceCheckBox);+ panel.add(useEmptyCompositesLabel);+ panel.add(useEmptyCompositesCheckBox);+outerPanel.add(panel);return outerPanel;}@@ -445,6 +450,9 @@ public class ApplyMarkupPropertyEditor implements OptionsEditor {useFunctionNamespaceLabel = new GDLabel("Replace Namespace", SwingConstants.RIGHT);useFunctionNamespaceLabel.setToolTipText(USE_NAMESPACE_TOOLTIP);++ useEmptyCompositesLabel = new GDLabel("Use Emtpy Composite Types", SwingConstants.RIGHT);+ useEmptyCompositesLabel.setToolTipText(USE_EMPTY_COMPOSITES_TOOLTIP);}private void createNonCommentMarkupChoices() {@@ -464,6 +472,7 @@ public class ApplyMarkupPropertyEditor implements OptionsEditor {functionSignatureComboBox.setToolTipText(FUNCTION_SIGNATURE_TOOLTIP);useFunctionNamespaceCheckBox = createCheckBox("");+ useEmptyCompositesCheckBox = createCheckBox("");}private JPanel createCommentsSubPanel() {@@ -560,6 +569,9 @@ public class ApplyMarkupPropertyEditor implements OptionsEditor {boolean useNamespaces = useFunctionNamespaceCheckBox.isSelected();options.setBoolean(USE_NAMESPACE_FUNCTIONS, useNamespaces);++ boolean useEmptyComposites = useEmptyCompositesCheckBox.isSelected();+ options.setBoolean(USE_EMPTY_COMPOSITES, useEmptyComposites);}private void updateCommentOptions(ToolOptions options) {@@ -676,6 +688,12 @@ public class ApplyMarkupPropertyEditor implements OptionsEditor {if (useFunctionNamespaceCheckBox.isSelected() != useNamespace) {useFunctionNamespaceCheckBox.setSelected(useNamespace);}++ boolean useEmtpyStructures =+ options.getBoolean(USE_EMPTY_COMPOSITES, DEFAULT_OPTION_FOR_USE_EMPTY_STRUCTURES);+ if (useEmptyCompositesCheckBox.isSelected() != useEmtpyStructures) {+ useEmptyCompositesCheckBox.setSelected(useEmtpyStructures);+ }}private void setEditorCommentValues(ToolOptions options) {diff --git a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/provider/matchtable/VTMatchTableProvider.java b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/provider/matchtable/VTMatchTableProvider.javaindex abba8cf0bc..a2e2a95ab7 100644--- a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/provider/matchtable/VTMatchTableProvider.java+++ b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/provider/matchtable/VTMatchTableProvider.java@@ -768,6 +768,8 @@ public class VTMatchTableProvider extends ComponentProviderAdaptervtOptions.registerOption(USE_NAMESPACE_FUNCTIONS, DEFAULT_OPTION_FOR_NAMESPACE_FUNCTIONS,null, USE_NAMESPACE_TOOLTIP);+ vtOptions.registerOption(USE_EMPTY_COMPOSITES, DEFAULT_OPTION_FOR_USE_EMPTY_STRUCTURES,+ null, USE_EMPTY_COMPOSITES_TOOLTIP);vtOptions.getOptions(APPLY_MARKUP_OPTIONS_NAME).registerOptionsEditor(() -> new ApplyMarkupPropertyEditor(controller));diff --git a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/util/VTOptionDefines.java b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/util/VTOptionDefines.javaindex 2ad0385fa9..7cf9c9238a 100644--- a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/util/VTOptionDefines.java+++ b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/util/VTOptionDefines.java@@ -69,6 +69,7 @@ public class VTOptionDefines {CommentChoices.APPEND_TO_EXISTING;public static boolean DEFAULT_OPTION_FOR_NAMESPACE_FUNCTIONS = false;+ public static boolean DEFAULT_OPTION_FOR_USE_EMPTY_STRUCTURES = false;public static final String FUNCTION_NAME = APPLY_MARKUP_OPTIONS_NAME + ".Function Name";public static final String FUNCTION_RETURN_TYPE = APPLY_MARKUP_OPTIONS_NAME +@@ -114,7 +115,12 @@ public class VTOptionDefines {APPLY_MARKUP_OPTIONS_NAME + ".Replace Namespace";public static final String USE_NAMESPACE_TOOLTIP =- "Apply the non-Global source namespace to the destination function.";+ "Apply the non-Global source namespace to the destination function";++ public static final String USE_EMPTY_COMPOSITES =+ APPLY_MARKUP_OPTIONS_NAME + ".Use Emtpy Composite Types";+ public static final String USE_EMPTY_COMPOSITES_TOOLTIP =+ "Create empty composite data types in destination function signatures";// Auto VT Optionspublic static final String AUTO_VT_OPTIONS_NAME = "Auto Version Tracking Options";diff --git a/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/VTMatchApplyFunctionSignatureTest.java b/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/VTMatchApplyFunctionSignatureTest.javaindex f25a744353..0bb26f3be6 100644--- a/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/VTMatchApplyFunctionSignatureTest.java+++ b/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/VTMatchApplyFunctionSignatureTest.java@@ -126,7 +126,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedInteg}//Create Gadget structure - slightly different than usual in last field to simplify test- private Structure createGadgetStruct() {+ private Structure createNonEmptyGadgetStruct() {Structure gadgetStruct = new StructureDataType("Gadget", 0);PointerDataType charPtr = new PointerDataType(new CharDataType());@@ -184,6 +184,9 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegbuilder.createEmptyFunction("use", "Gadget", CompilerSpec.CALLING_CONVENTION_thiscall,false, "0x401040", 10, DataType.DEFAULT, new ParameterImpl("person", ptr1, p));+ builder.createEmptyFunction("createGadget", null,+ CompilerSpec.CALLING_CONVENTION_stdcall, false, "0x401060", 10, DataType.DEFAULT);+p.addConsumer(this);return p;}@@ -217,6 +220,9 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegCompilerSpec.CALLING_CONVENTION_thiscall, "0x401040", 10, DataType.DEFAULT,Undefined4DataType.dataType);+ builder.createEmptyFunction((String) null, (String) null,+ CompilerSpec.CALLING_CONVENTION_stdcall, "0x401060", 10, DataType.DEFAULT);+p.withTransaction("Set SourceType", () -> {f1.setSignatureSource(SourceType.DEFAULT);f2.setSignatureSource(SourceType.ANALYSIS);@@ -234,11 +240,8 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegProgramBuilder builder = new ProgramBuilder("helloProgram", ProgramBuilder._TOY, this);try {Program p = builder.getProgram();-builder.createMemory(".text", "0x10938", 0x10);-builder.createEmptyFunction(null, "0x10938", 0x10, DataType.DEFAULT);-return p;}finally {@@ -297,12 +300,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegapplyOptions.setEnum(NO_RETURN, ReplaceChoices.EXCLUDE);applyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- VtTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("int * addPerson(Person * * list, char * personName)",@@ -310,15 +308,9 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegassertEquals(VTAssociationStatus.ACCEPTED, testMatch.getAssociation().getStatus());checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.REPLACED);- // Test unapply- task = new ClearMatchTask(controller, matches);- runTask(session, task);-// Verify unapply.- checkSignatures("int * addPerson(Person * * list, char * personName)",+ unapplyTestMatch("int * addPerson(Person * * list, char * personName)","undefined FUN_004011a0(void * * param_1, char * param_2)");- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);}@Test@@ -341,17 +333,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegapplyOptions.setEnum(NO_RETURN, ReplaceChoices.EXCLUDE);applyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- checkClassDataType(false, false);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined use(Gadget * this, Person * person)",@@ -363,16 +345,9 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedInteg// the destination so no Gadget class data type should existcheckClassDataType(false, false);- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-// Verify unapply.- checkSignatures("undefined use(Gadget * this, Person * person)",+ unapplyTestMatch("undefined use(Gadget * this, Person * person)","undefined FUN_00401040(void * this, undefined4 param_1)");- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-}// use case: test replace undefined for return and params when they are undefined ptrs@@ -383,45 +358,34 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedInteguseMatch("0x00401040", "0x00401040");// update the source function to have a Gadget * type+ tx(sourceProgram, () -> {+ FunctionManager fm = sourceProgram.getFunctionManager();+ Function function = fm.getFunctionAt(addr("0x00401040", sourceProgram));- Function srcFunction = sourceProgram.getFunctionManager()- .getFunctionAt(addr("0x00401040", sourceProgram));-- DataType existingEmptyGadgetStruct =- sourceProgram.getDataTypeManager().getDataType(CategoryPath.ROOT, "Gadget");- assertNotNull(existingEmptyGadgetStruct);-- Pointer ptr1 =- PointerDataType.getPointer(existingEmptyGadgetStruct,- sourceProgram.getDataTypeManager());-- assertNotNull(ptr1);-- int id = sourceProgram.startTransaction("Test");-- srcFunction.setReturnType(ptr1, SourceType.USER_DEFINED);+ ProgramBasedDataTypeManager dtm = sourceProgram.getDataTypeManager();+ DataType existingEmptyGadget = dtm.getDataType(CategoryPath.ROOT, "Gadget");+ assertNotNull(existingEmptyGadget);- sourceProgram.endTransaction(id, true);+ Pointer ptr1 = PointerDataType.getPointer(existingEmptyGadget, dtm);+ function.setReturnType(ptr1, SourceType.USER_DEFINED);+ });// update the destination function to have undefined4 * return type and to have param_1// also be a undefined4 *+ tx(destinationProgram, () -> {- id = destinationProgram.startTransaction("Test");-- Function destFunction = destinationProgram.getFunctionManager()- .getFunctionAt(addr("0x00401040", destinationProgram));- ptr1 =- PointerDataType.getPointer(Undefined4DataType.dataType,- destinationProgram.getDataTypeManager());- destFunction.setReturnType(ptr1, SourceType.DEFAULT);-- Parameter[] parameters = destFunction.getParameters();- parameters[1].setDataType(ptr1, parameters[1].getSource());+ FunctionManager fm = destinationProgram.getFunctionManager();+ Function function = fm.getFunctionAt(addr("0x00401040", destinationProgram));+ ProgramBasedDataTypeManager dtm = destinationProgram.getDataTypeManager();+ Pointer ptr = PointerDataType.getPointer(Undefined4DataType.dataType, dtm);+ function.setReturnType(ptr, SourceType.DEFAULT);- destFunction.replaceParameters(FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true,- SourceType.USER_DEFINED, parameters);+ Parameter[] parameters = function.getParameters();+ parameters[1].setDataType(ptr, parameters[1].getSource());- destinationProgram.endTransaction(id, true);+ function.replaceParameters(FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true,+ SourceType.USER_DEFINED, parameters);+ });// Check initial valuescheckSignatures("Gadget * use(Gadget * this, Person * person)",@@ -443,17 +407,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegParameterDataTypeChoices.REPLACE_UNDEFINED_DATA_TYPES_ONLY);applyOptions.setBoolean(VTOptionDefines.USE_NAMESPACE_FUNCTIONS, true); //replace namespace- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- checkClassDataType(false, false);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("Gadget * use(Gadget * this, Person * person)",@@ -461,22 +415,194 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegassertEquals(VTAssociationStatus.ACCEPTED, testMatch.getAssociation().getStatus());checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.REPLACED);- // since no option to apply function name there will be no class namespace applied to- // the destination so no Gadget class data type should exist+ // option to apply function name is on, there will be a class namespace applied to+ // the destination so Gadget class data type should existcheckClassDataType(true, false);- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-// Verify unapply.- checkSignatures("Gadget * use(Gadget * this, Person * person)",+ unapplyTestMatch("Gadget * use(Gadget * this, Person * person)","undefined4 * FUN_00401040(void * this, undefined4 * param_1)");- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);}+ // Use case: Source has non-empty Gadget, dest has no Gadget; apply empty structs+ @Test+ public void testApplyMatch_ReplaceSignature_EmptyStructureOption_SourceThisParam_DestParamUndefined()+ throws Exception {++ useMatch("0x00401040", "0x00401040");++ applySourceNonEmtpyGadget();++ // Check initial values+ checkSignatures("undefined use(Gadget * this, Person * person)",+ "undefined FUN_00401040(void * this, undefined4 param_1)");++ ToolOptions applyOptions = controller.getOptions();+ applyOptions.setEnum(VTOptionDefines.FUNCTION_NAME,+ FunctionNameChoices.REPLACE_DEFAULT_ONLY);+ applyOptions.setEnum(FUNCTION_SIGNATURE,+ FunctionSignatureChoices.WHEN_SAME_PARAMETER_COUNT);+ applyOptions.setEnum(CALLING_CONVENTION, CallingConventionChoices.SAME_LANGUAGE);+ applyOptions.setEnum(PARAMETER_DATA_TYPES, ParameterDataTypeChoices.REPLACE);+ applyOptions.setEnum(PARAMETER_NAMES, SourcePriorityChoices.REPLACE);+ applyOptions.setEnum(PARAMETER_COMMENTS, CommentChoices.APPEND_TO_EXISTING);+ applyOptions.setEnum(NO_RETURN, ReplaceChoices.EXCLUDE);+ applyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);+ applyOptions.setBoolean(VTOptionDefines.USE_NAMESPACE_FUNCTIONS, true); // replace namespace+ applyOptions.setBoolean(VTOptionDefines.USE_EMPTY_COMPOSITES, true);++ applyTestMatch();++ // Verify apply.+ checkSignatures("undefined use(Gadget * this, Person * person)",+ "undefined use(Gadget * this, Person * person)");+ assertEquals(VTAssociationStatus.ACCEPTED, testMatch.getAssociation().getStatus());+ checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.REPLACED);++ // since there is option to apply function name there should be a class namespace applied to+ // the destination so the Gadget class data type should exist+ // In this test Gadget is not an empty structure in the source, but the option to use empty+ // composites is enabled, so dest should be empty.+ checkClassDataType(true, false);++ unapplyTestMatch("undefined use(Gadget * this, Person * person)",+ "undefined FUN_00401040(void * this, undefined4 param_1)");+ }++ // Use case: Source has populated Gadget struct, dest has empty Gadget struct; apply empty structs+ @Test+ public void testApplyMatch_ReplaceSignature_EmptyStructureOption_SourceThisParam_DestEmptyGadget()+ throws Exception {++ useMatch("0x00401040", "0x00401040");++ applySourceNonEmtpyGadget_DestEmtpyGadgetInDtm();++ // Check initial values+ checkSignatures("undefined use(Gadget * this, Person * person)",+ "undefined FUN_00401040(void * this, undefined4 param_1)");++ // Set the function signature options for this test+ ToolOptions applyOptions = controller.getOptions();+ applyOptions.setEnum(VTOptionDefines.FUNCTION_NAME,+ FunctionNameChoices.REPLACE_DEFAULT_ONLY);+ applyOptions.setEnum(FUNCTION_SIGNATURE,+ FunctionSignatureChoices.WHEN_SAME_PARAMETER_COUNT);+ applyOptions.setEnum(CALLING_CONVENTION, CallingConventionChoices.SAME_LANGUAGE);+ applyOptions.setEnum(PARAMETER_DATA_TYPES, ParameterDataTypeChoices.REPLACE);+ applyOptions.setEnum(PARAMETER_NAMES, SourcePriorityChoices.REPLACE);+ applyOptions.setEnum(PARAMETER_COMMENTS, CommentChoices.APPEND_TO_EXISTING);+ applyOptions.setEnum(NO_RETURN, ReplaceChoices.EXCLUDE);+ applyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);+ applyOptions.setBoolean(VTOptionDefines.USE_NAMESPACE_FUNCTIONS, true); //replace namespace+ applyOptions.setBoolean(VTOptionDefines.USE_EMPTY_COMPOSITES, true);++ applyTestMatch();++ // Verify apply.+ checkSignatures("undefined use(Gadget * this, Person * person)",+ "undefined use(Gadget * this, Person * person)");+ assertEquals(VTAssociationStatus.ACCEPTED, testMatch.getAssociation().getStatus());+ checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.REPLACED);++ // since there is option to apply function name there should be a class namespace applied to+ // the destination so the Gadget class data type should exist+ // In this test Gadget is a populated structure in the source replacing an empty+ // one in the dest. However, the option to use empty structures is on, so the destination+ // Gadget should be empty.+ checkClassDataType(true, false);++ unapplyTestMatch("undefined use(Gadget * this, Person * person)",+ "undefined FUN_00401040(void * this, undefined4 param_1)");+ }++ @Test+ public void testApplyMatch_ReplaceSignature_EmptyStructureOption_SourceReturnGadger_DestReturnUndefined()+ throws Exception {++ useMatch("0x00401060", "0x00401060");++ Structure gadget = makeSrcGadgetNonEmpty();+ PointerDataType ptr = new PointerDataType(gadget);+ setReturnType(sourceFunction, ptr, SourceType.USER_DEFINED);++ // Check initial values+ checkSignatures("Gadget * createGadget(void)",+ "undefined FUN_00401060(void)");++ // Set the function signature options for this test+ ToolOptions applyOptions = controller.getOptions();+ applyOptions.setEnum(VTOptionDefines.FUNCTION_NAME,+ FunctionNameChoices.REPLACE_DEFAULT_ONLY);+ applyOptions.setEnum(FUNCTION_SIGNATURE,+ FunctionSignatureChoices.WHEN_SAME_PARAMETER_COUNT);+ applyOptions.setEnum(CALLING_CONVENTION, CallingConventionChoices.SAME_LANGUAGE);+ applyOptions.setEnum(PARAMETER_DATA_TYPES, ParameterDataTypeChoices.REPLACE);+ applyOptions.setEnum(PARAMETER_NAMES, SourcePriorityChoices.REPLACE);+ applyOptions.setEnum(PARAMETER_COMMENTS, CommentChoices.APPEND_TO_EXISTING);+ applyOptions.setEnum(NO_RETURN, ReplaceChoices.EXCLUDE);+ applyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);+ applyOptions.setBoolean(VTOptionDefines.USE_NAMESPACE_FUNCTIONS, true); //replace namespace+ applyOptions.setBoolean(VTOptionDefines.USE_EMPTY_COMPOSITES, true);++ applyTestMatch();++ // Verify apply.+ checkSignatures("Gadget * createGadget(void)",+ "Gadget * createGadget(void)");+ assertEquals(VTAssociationStatus.ACCEPTED, testMatch.getAssociation().getStatus());+ checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.REPLACED);++ checkGadgetReturnType(false);++ unapplyTestMatch("Gadget * createGadget(void)",+ "undefined FUN_00401060(void)");+ }++ @Test+ public void testApplyMatch_ReplaceSignature_EmptyStructureOptionOff_SourceReturnGadger_DestReturnUndefined()+ throws Exception {++ useMatch("0x00401060", "0x00401060");++ Structure gadget = makeSrcGadgetNonEmpty();+ PointerDataType ptr = new PointerDataType(gadget);+ setReturnType(sourceFunction, ptr, SourceType.USER_DEFINED);++ // Check initial values+ checkSignatures("Gadget * createGadget(void)",+ "undefined FUN_00401060(void)");++ // Set the function signature options for this test+ ToolOptions applyOptions = controller.getOptions();+ applyOptions.setEnum(VTOptionDefines.FUNCTION_NAME,+ FunctionNameChoices.REPLACE_DEFAULT_ONLY);+ applyOptions.setEnum(FUNCTION_SIGNATURE,+ FunctionSignatureChoices.WHEN_SAME_PARAMETER_COUNT);+ applyOptions.setEnum(CALLING_CONVENTION, CallingConventionChoices.SAME_LANGUAGE);+ applyOptions.setEnum(PARAMETER_DATA_TYPES, ParameterDataTypeChoices.REPLACE);+ applyOptions.setEnum(PARAMETER_NAMES, SourcePriorityChoices.REPLACE);+ applyOptions.setEnum(PARAMETER_COMMENTS, CommentChoices.APPEND_TO_EXISTING);+ applyOptions.setEnum(NO_RETURN, ReplaceChoices.EXCLUDE);+ applyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);+ applyOptions.setBoolean(VTOptionDefines.USE_NAMESPACE_FUNCTIONS, true); //replace namespace+ applyOptions.setBoolean(VTOptionDefines.USE_EMPTY_COMPOSITES, false);++ applyTestMatch();++ // Verify apply.+ checkSignatures("Gadget * createGadget(void)",+ "Gadget * createGadget(void)");+ assertEquals(VTAssociationStatus.ACCEPTED, testMatch.getAssociation().getStatus());+ checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.REPLACED);++ checkGadgetReturnType(true);++ unapplyTestMatch("Gadget * createGadget(void)",+ "undefined FUN_00401060(void)");+ }+// Use case: Source has empty Gadget struct, dest has no Gadget struct@Testpublic void testApplyMatch_ReplaceSignature_AndName_SameNumParams_ThisToThis_NoDestGadgetStruct()@@ -508,17 +634,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegapplyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);applyOptions.setBoolean(VTOptionDefines.USE_NAMESPACE_FUNCTIONS, true); //replace namespace- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- checkClassDataType(false, false);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined use(Gadget * this, Person * person)",@@ -531,16 +647,8 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedInteg// In this test Gadget is an empty structure in the source so should be empty in destcheckClassDataType(true, false);- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined use(Gadget * this, Person * person)",+ unapplyTestMatch("undefined use(Gadget * this, Person * person)","undefined FUN_00401040(void * this, undefined4 param_1)");- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-}// Use case: Source has populated Gadget struct, dest has empty Gadget struct@@ -550,33 +658,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedInteguseMatch("0x00401040", "0x00401040");- ProgramBasedDataTypeManager sourceDtm = sourceProgram.getDataTypeManager();- ProgramBasedDataTypeManager destDtm = destinationProgram.getDataTypeManager();-- DataType existingEmptyGadgetStruct = sourceDtm.getDataType(CategoryPath.ROOT, "Gadget");- assertNotNull(existingEmptyGadgetStruct);-- // replace the source empty gadget with a populated one- Structure gadgetStruct = createGadgetStruct();-- int id = sourceDtm.startTransaction("Test");- sourceDtm.addDataType(gadgetStruct, DataTypeConflictHandler.REPLACE_HANDLER);- sourceDtm.endTransaction(id, true);-- // verify it took- DataType updatedSourceGadget = sourceDtm.getDataType(CategoryPath.ROOT, "Gadget");- assertTrue(updatedSourceGadget.isEquivalent(gadgetStruct));-- // add empty gadget to the destination program- Structure emptyGadgetStruct = createEmptyGadgetStruct();-- id = destDtm.startTransaction("Test");- destDtm.addDataType(emptyGadgetStruct, DataTypeConflictHandler.REPLACE_HANDLER);- destDtm.endTransaction(id, true);-- // verify it took- DataType destGadget = destDtm.getDataType(CategoryPath.ROOT, "Gadget");- assertTrue(destGadget.isNotYetDefined());+ Structure srcGadget = applySourceNonEmtpyGadget_DestEmtpyGadgetInDtm();// Check initial valuescheckSignatures("undefined use(Gadget * this, Person * person)",@@ -602,15 +684,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegapplyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);applyOptions.setBoolean(VTOptionDefines.USE_NAMESPACE_FUNCTIONS, true); //replace namespace- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined use(Gadget * this, Person * person)",@@ -622,19 +696,12 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedInteg// the destination so the Gadget class data type should exist// In this test Gadget is a populated structure in the source replacing an empty// one in the dest so the resulting one in dest should be same populated on from source- destGadget = destDtm.getDataType(CategoryPath.ROOT, "Gadget");- assertTrue(destGadget.isEquivalent(gadgetStruct));-- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);+ ProgramBasedDataTypeManager destDtm = destinationProgram.getDataTypeManager();+ DataType destGadget = destDtm.getDataType(CategoryPath.ROOT, "Gadget");+ assertTrue(destGadget.isEquivalent(srcGadget));- // Verify unapply.- checkSignatures("undefined use(Gadget * this, Person * person)",+ unapplyTestMatch("undefined use(Gadget * this, Person * person)","undefined FUN_00401040(void * this, undefined4 param_1)");- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-}// Use case: Source has populated Gadget struct, dest has same Gadget struct@@ -652,21 +719,19 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegassertNotNull(existingEmptyGadgetStruct);// replace the source empty gadget with a populated one- Structure gadgetStruct = createGadgetStruct();-- int id = sourceDtm.startTransaction("Test");- sourceDtm.addDataType(gadgetStruct, DataTypeConflictHandler.REPLACE_HANDLER);- sourceDtm.endTransaction(id, true);+ Structure gadgetStruct = createNonEmptyGadgetStruct();+ tx(sourceDtm, () -> {+ sourceDtm.addDataType(gadgetStruct, DataTypeConflictHandler.REPLACE_HANDLER);+ });// verify it tookDataType updatedSourceGadget = sourceDtm.getDataType(CategoryPath.ROOT, "Gadget");assertTrue(updatedSourceGadget.isEquivalent(gadgetStruct));// add same Gadget to the destination program-- id = destDtm.startTransaction("Test");- destDtm.addDataType(gadgetStruct, DataTypeConflictHandler.REPLACE_HANDLER);- destDtm.endTransaction(id, true);+ tx(destDtm, () -> {+ destDtm.addDataType(gadgetStruct, DataTypeConflictHandler.REPLACE_HANDLER);+ });// verify it tookDataType destGadget = destDtm.getDataType(CategoryPath.ROOT, "Gadget");@@ -696,15 +761,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegapplyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);applyOptions.setBoolean(VTOptionDefines.USE_NAMESPACE_FUNCTIONS, true); //replace namespace- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined use(Gadget * this, Person * person)",@@ -722,16 +779,8 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegDataType gadgetConflict = destDtm.getDataType(CategoryPath.ROOT, "Gadget.conflict");assertNull(gadgetConflict);- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined use(Gadget * this, Person * person)",+ unapplyTestMatch("undefined use(Gadget * this, Person * person)","undefined FUN_00401040(void * this, undefined4 param_1)");- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-}// Use case: Source has populated Gadget struct, dest has different non-empty Gadget struct@@ -749,11 +798,10 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegassertNotNull(existingEmptyGadgetStruct);// replace the source empty gadget with a populated one- Structure gadgetStruct = createGadgetStruct();-- int id = sourceDtm.startTransaction("Test");- sourceDtm.addDataType(gadgetStruct, DataTypeConflictHandler.REPLACE_HANDLER);- sourceDtm.endTransaction(id, true);+ Structure gadgetStruct = createNonEmptyGadgetStruct();+ tx(sourceDtm, () -> {+ sourceDtm.addDataType(gadgetStruct, DataTypeConflictHandler.REPLACE_HANDLER);+ });// verify it tookDataType updatedSourceGadget = sourceDtm.getDataType(CategoryPath.ROOT, "Gadget");@@ -761,9 +809,9 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedInteg// add different Gadget to the destination programStructure differentGadgetStruct = createDifferentGadgetStruct();- id = destDtm.startTransaction("Test");- destDtm.addDataType(differentGadgetStruct, DataTypeConflictHandler.REPLACE_HANDLER);- destDtm.endTransaction(id, true);+ tx(destDtm, () -> {+ destDtm.addDataType(differentGadgetStruct, DataTypeConflictHandler.REPLACE_HANDLER);+ });// verify it tookDataType destGadget = destDtm.getDataType(CategoryPath.ROOT, "Gadget");@@ -793,15 +841,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegapplyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);applyOptions.setBoolean(VTOptionDefines.USE_NAMESPACE_FUNCTIONS, true); //replace namespace- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined use(Gadget * this, Person * person)",@@ -820,16 +860,8 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegDataType gadgetConflict = destDtm.getDataType(CategoryPath.ROOT, "Gadget.conflict");assertTrue(gadgetConflict.isEquivalent(gadgetStruct));- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined use(Gadget * this, Person * person)",+ unapplyTestMatch("undefined use(Gadget * this, Person * person)","undefined FUN_00401040(void * this, undefined4 param_1)");- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-}@Test@@ -841,20 +873,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckSignatures("undefined use(Gadget * this, Person * person)","undefined FUN_00401040(void * this, undefined4 param_1)");- tx(sourceProgram, () -> {- sourceFunction.setCustomVariableStorage(true);-- sourceFunction.getParameter(0)- .setDataType(sourceFunction.getParameter(1).getDataType(),- SourceType.USER_DEFINED);- });-- DataType personType = sourceProgram.getDataTypeManager().getDataType("/Person");- assertNotNull(personType);-- tx(destinationProgram, () -> {- destinationFunction.setReturnType(personType, SourceType.USER_DEFINED);- });+ setSourceFunctionThisPointerToPersonStructure();// Check modified valuescheckSignatures("undefined use(Person * this, Person * person)",@@ -870,17 +889,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegapplyOptions.setEnum(NO_RETURN, ReplaceChoices.EXCLUDE);applyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- checkClassDataType(false, false);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply. (return type not replaced with undefined due to lower priority)checkSignatures("undefined use(Person * this, Person * person)",@@ -894,17 +903,8 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegassertTrue(destinationFunction.hasCustomVariableStorage());- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined use(Person * this, Person * person)",+ unapplyTestMatch("undefined use(Person * this, Person * person)","Person * FUN_00401040(void * this, Person * __return_storage_ptr__, undefined4 param_1)");-- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-assertFalse(destinationFunction.hasCustomVariableStorage());}@@ -917,20 +917,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckSignatures("undefined use(Gadget * this, Person * person)","undefined FUN_00401040(void * this, undefined4 param_1)");- tx(sourceProgram, () -> {- sourceFunction.setCustomVariableStorage(true);-- sourceFunction.getParameter(0)- .setDataType(sourceFunction.getParameter(1).getDataType(),- SourceType.USER_DEFINED);- });-- DataType personType = sourceProgram.getDataTypeManager().getDataType("/Person");- assertNotNull(personType);-- tx(destinationProgram, () -> {- destinationFunction.setReturnType(personType, SourceType.USER_DEFINED);- });+ setSourceFunctionThisPointerToPersonStructure();// Check modified valuescheckSignatures("undefined use(Person * this, Person * person)",@@ -948,16 +935,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegapplyOptions.setEnum(NO_RETURN, ReplaceChoices.EXCLUDE);applyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);- checkClassDataType(false, false);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply. (return type not replaced with undefined due to lower priority)checkSignatures("undefined use(Person * this, Person * person)",@@ -968,20 +946,11 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegassertTrue(destinationFunction.hasCustomVariableStorage());// since there is option to apply function name there should be a class namespace applied to- // the destination so the Gadget class data type should exist+ // the destination so the Person class data type should existcheckClassDataType(true, true);- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined use(Person * this, Person * person)",+ unapplyTestMatch("undefined use(Person * this, Person * person)","Person * FUN_00401040(void * this, Person * __return_storage_ptr__, undefined4 param_1)");-- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-assertFalse(destinationFunction.hasCustomVariableStorage());}@@ -994,20 +963,10 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckSignatures("undefined use(Gadget * this, Person * person)","undefined FUN_00401040(void * this, undefined4 param_1)");- tx(sourceProgram, () -> {- sourceFunction.setCustomVariableStorage(true);-- sourceFunction.getParameter(0)- .setDataType(sourceFunction.getParameter(1).getDataType(),- SourceType.USER_DEFINED);- });-- DataType personType = sourceProgram.getDataTypeManager().getDataType("/Person");- assertNotNull(personType);+ setSourceFunctionThisPointerToPersonStructureWithCustomStorage();- tx(destinationProgram, () -> {- destinationFunction.setCustomVariableStorage(true);- });+ checkSignatures("undefined use(Person * this, Person * person)",+ "undefined FUN_00401040(void * this, undefined4 param_2)");// Set the function signature options for this testToolOptions applyOptions = controller.getOptions();@@ -1019,21 +978,15 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegapplyOptions.setEnum(NO_RETURN, ReplaceChoices.EXCLUDE);applyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();assertEquals(VTAssociationStatus.ACCEPTED, testMatch.getAssociation().getStatus());checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.REPLACED);assertTrue(destinationFunction.hasCustomVariableStorage());+ unapplyTestMatch("undefined use(Person * this, Person * person)",+ "undefined FUN_00401040(void * this, undefined4 param_2)");}@Test@@ -1049,6 +1002,9 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegdestinationFunction.setCustomVariableStorage(true);});+ checkSignatures("undefined use(Gadget * this, Person * person)",+ "undefined FUN_00401040(void * this, undefined4 param_2)");+// Set the function signature options for this testToolOptions applyOptions = controller.getOptions();applyOptions.setEnum(FUNCTION_SIGNATURE, FunctionSignatureChoices.REPLACE);@@ -1059,21 +1015,14 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegapplyOptions.setEnum(NO_RETURN, ReplaceChoices.EXCLUDE);applyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();assertEquals(VTAssociationStatus.ACCEPTED, testMatch.getAssociation().getStatus());checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.REPLACED);-assertFalse(destinationFunction.hasCustomVariableStorage());+ unapplyTestMatch("undefined use(Gadget * this, Person * person)",+ "undefined FUN_00401040(void * this, undefined4 param_2)");}@Test@@ -1081,9 +1030,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedInteguseMatch("0x00401040", "0x00401040");setCallingConvention(sourceFunction, "__cdecl");-// removeParameter(sourceFunction, 0);setCallingConvention(destinationFunction, "__stdcall");-// removeParameter(destinationFunction, 0);// Check initial valuescheckSignatures("undefined use(Person * person)",@@ -1101,15 +1048,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegapplyOptions.setEnum(NO_RETURN, ReplaceChoices.EXCLUDE);applyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkCallingConvention("__cdecl", "__cdecl");@@ -1119,17 +1058,9 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckInline(false, false);checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.REPLACED);- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined use(Person * person)",+ unapplyTestMatch("undefined use(Person * person)","undefined FUN_00401040(undefined4 param_1)");- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkInline(false, false);checkCallingConvention("__cdecl", "__stdcall");- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);}@Test@@ -1139,9 +1070,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegsetLanguage(sourceFunction, "Toy:LE:32:default", "default");setCallingConvention(sourceFunction, "__stdcall");-// removeParameter(sourceFunction, 0);setCallingConvention(destinationFunction, "__cdecl");-// removeParameter(destinationFunction, 0);// Check initial valuescheckSignatures("undefined use(Person * person)",@@ -1160,15 +1089,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegapplyOptions.setEnum(NO_RETURN, ReplaceChoices.EXCLUDE);applyOptions.setEnum(FUNCTION_RETURN_TYPE, ParameterDataTypeChoices.REPLACE);- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkCallingConvention("__stdcall", "__cdecl");@@ -1178,17 +1099,9 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckInline(false, false);checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.REPLACED);- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined use(Person * person)",+ unapplyTestMatch("undefined use(Person * person)","undefined FUN_00401040(undefined4 param_1)");- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkInline(false, false);checkCallingConvention("__stdcall", "__cdecl");- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);}@Test@@ -1198,9 +1111,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegsetLanguage(sourceFunction, "Toy:LE:32:default", "default");setCallingConvention(sourceFunction, "__stdcall");-// removeParameter(sourceFunction, 0);setCallingConvention(destinationFunction, "__cdecl");-// removeParameter(destinationFunction, 0);// Check initial valuescheckSignatures("undefined use(Person * person)",@@ -1221,15 +1132,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegapplyOptions.setEnum(PARAMETER_COMMENTS, CommentChoices.APPEND_TO_EXISTING);applyOptions.setEnum(NO_RETURN, ReplaceChoices.EXCLUDE);- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkCallingConvention("__stdcall", "__stdcall");@@ -1237,19 +1140,11 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedInteg"undefined FUN_00401040(Person * person)");assertEquals(VTAssociationStatus.ACCEPTED, testMatch.getAssociation().getStatus());checkInline(false, false);- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.REPLACED);-- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined use(Person * person)",- "undefined FUN_00401040(undefined4 param_1)");- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkInline(false, false);+ checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.REPLACED);++ unapplyTestMatch("undefined use(Person * person)",+ "undefined FUN_00401040(undefined4 param_1)");checkCallingConvention("__stdcall", "__cdecl");- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);}@Test@@ -1267,7 +1162,6 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedInteguseMatch("0x00401040", "0x00010938");setCallingConvention(sourceFunction, "__cdecl");-// removeParameter(sourceFunction, 0);setCallingConvention(destinationFunction, "__stdcall");// Check initial values@@ -1288,15 +1182,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegapplyOptions.setEnum(PARAMETER_COMMENTS, CommentChoices.APPEND_TO_EXISTING);applyOptions.setEnum(NO_RETURN, ReplaceChoices.EXCLUDE);- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);-- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkCallingConvention("__cdecl", "__stdcall");@@ -1306,16 +1192,8 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckInline(false, false);checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.REPLACED);- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined use(Person * person)", "undefined FUN_00010938(void)");- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkInline(false, false);+ unapplyTestMatch("undefined use(Person * person)", "undefined FUN_00010938(void)");checkCallingConvention("__cdecl", "__stdcall");- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);}@Test@@ -1347,12 +1225,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckInline(true, false);checkNoReturn(true, false);- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("float addPerson(Person * * list, char * personName)",@@ -1362,15 +1235,8 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckInline(true, true);checkNoReturn(true, true);- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("float addPerson(Person * * list, char * personName)",+ unapplyTestMatch("float addPerson(Person * * list, char * personName)","undefined FUN_004011a0(void * * param_1, char * param_2)");- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);checkInline(true, false);checkNoReturn(true, false);}@@ -1414,12 +1280,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckInline(false, true);checkNoReturn(false, true);- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined addPerson(Person * * param_1, char * personName)",@@ -1433,15 +1294,8 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(destinationFunction, 0, "The entire list");checkParameterComments(destinationFunction, 1, "Last Name\nName of the person");- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined addPerson(Person * * param_1, char * personName)",+ unapplyTestMatch("undefined addPerson(Person * * param_1, char * personName)","float FUN_004011a0(void * * list, char * name)");- assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());- checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);checkInline(false, true);checkNoReturn(false, true);checkParameterComments(sourceFunction, 0, null);@@ -1489,12 +1343,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(destinationFunction, 0, "The entire list");checkParameterComments(destinationFunction, 1, "Last Name");- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined addPerson(Person * * param_1, char * personName)",@@ -1508,12 +1357,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(destinationFunction, 0, null);checkParameterComments(destinationFunction, 1, "Name of the person");- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined addPerson(Person * * param_1, char * personName)",+ unapplyTestMatch("undefined addPerson(Person * * param_1, char * personName)","float FUN_004011a0(void * * list, char * name)");assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);@@ -1564,12 +1408,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(destinationFunction, 0, "The entire list");checkParameterComments(destinationFunction, 1, "Last Name");- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined addPerson(Person * * param_1, char * personName)",@@ -1583,12 +1422,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(destinationFunction, 0, "The entire list");checkParameterComments(destinationFunction, 1, "Last Name");- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined addPerson(Person * * param_1, char * personName)",+ unapplyTestMatch("undefined addPerson(Person * * param_1, char * personName)","float FUN_004011a0(void * * list, char * name)");assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);@@ -1639,12 +1473,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(destinationFunction, 0, "The entire list");checkParameterComments(destinationFunction, 1, "Last Name");- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined addPerson(Person * * param_1, char * personName)",@@ -1658,12 +1487,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(destinationFunction, 0, "The entire list");checkParameterComments(destinationFunction, 1, "Last Name");- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined addPerson(Person * * param_1, char * personName)",+ unapplyTestMatch("undefined addPerson(Person * * param_1, char * personName)","float FUN_004011a0(void * * list, char * name)");assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);@@ -1717,12 +1541,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(sourceFunction, 1, "The person's name");checkParameterComments(destinationFunction, 0, "The entire list");- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined addPerson(Person * * list, char * personName)",@@ -1736,12 +1555,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(destinationFunction, 0, "The entire list\na list");checkParameterComments(destinationFunction, 1, "The person's name");- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined addPerson(Person * * list, char * personName)",+ unapplyTestMatch("undefined addPerson(Person * * list, char * personName)","word FUN_004011a0(void * * list)");assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);@@ -1794,12 +1608,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(sourceFunction, 1, "The person's name");checkParameterComments(destinationFunction, 0, "The entire list");- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined addPerson(Person * * list, char * personName)",@@ -1812,12 +1621,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(sourceFunction, 1, "The person's name");checkParameterComments(destinationFunction, 0, "a list");- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined addPerson(Person * * list, char * personName)",+ unapplyTestMatch("undefined addPerson(Person * * list, char * personName)","word FUN_004011a0(void * * list)");assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);@@ -1868,12 +1672,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(destinationFunction, 0, "The entire list");checkParameterComments(destinationFunction, 1, "The person's name");- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined addPerson(Person * * list)", "word FUN_004011a0(void * * list)");@@ -1884,12 +1683,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(sourceFunction, 0, "a list");checkParameterComments(destinationFunction, 0, "The entire list\na list");- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined addPerson(Person * * list)",+ unapplyTestMatch("undefined addPerson(Person * * list)","word FUN_004011a0(void * * param_1, char * param_2)");assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);@@ -1940,12 +1734,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(destinationFunction, 0, "The entire list");checkParameterComments(destinationFunction, 1, "The person's name");- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined addPerson(Person * * list)",@@ -1957,12 +1746,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(sourceFunction, 0, "a list");checkParameterComments(destinationFunction, 0, "The entire list\na list");- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined addPerson(Person * * list)",+ unapplyTestMatch("undefined addPerson(Person * * list)","word FUN_004011a0(void * * param_1, char * param_2)");assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);@@ -2008,12 +1792,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(sourceFunction, 0, null);checkParameterComments(sourceFunction, 1, null);- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("int * addPerson(Person * * list, char * personName, ...)",@@ -2025,12 +1804,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(sourceFunction, 0, null);checkParameterComments(sourceFunction, 1, null);- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("int * addPerson(Person * * list, char * personName, ...)",+ unapplyTestMatch("int * addPerson(Person * * list, char * personName, ...)","undefined FUN_004011a0()");assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);@@ -2073,12 +1847,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckParameterComments(destinationFunction, 0, null);checkParameterComments(destinationFunction, 1, null);- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined addPerson(void)", "undefined FUN_004011a0(void)");@@ -2087,12 +1856,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckInline(false, false);checkNoReturn(false, false);- // Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);- runTask(session, unapplyTask);-- // Verify unapply.- checkSignatures("undefined addPerson(void)",+ unapplyTestMatch("undefined addPerson(void)","undefined FUN_004011a0(void * * param_1, char * param_2, ...)");assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);@@ -2134,12 +1898,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckNoReturn(false, false);checkSignatureSource(SourceType.USER_DEFINED, SourceType.DEFAULT);- List<VTMatch> matches = new ArrayList<>();- matches.add(testMatch);-- // Test Apply- ApplyMatchTask task = new ApplyMatchTask(controller, matches);- runTask(session, task);+ applyTestMatch();// Verify apply.checkSignatures("undefined addPerson(void)", "undefined FUN_004011a0(void)");@@ -2149,22 +1908,142 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegcheckNoReturn(false, false);checkSignatureSource(SourceType.USER_DEFINED, SourceType.USER_DEFINED);+ unapplyTestMatch("undefined addPerson(void)", "undefined FUN_004011a0()");+ assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());+ checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);+ checkInline(false, false);+ checkNoReturn(false, false);+ checkSignatureSource(SourceType.USER_DEFINED, SourceType.DEFAULT);+ }++//==================================================================================================+// Helper Methods+//==================================================================================================++ private Structure makeSrcGadgetNonEmpty() {++ ProgramBasedDataTypeManager sourceDtm = sourceProgram.getDataTypeManager();+ DataType existingEmptyGadgetStruct = sourceDtm.getDataType(CategoryPath.ROOT, "Gadget");+ assertNotNull(existingEmptyGadgetStruct);++ // replace the source empty gadget with a populated one+ Structure gadgetStruct = createNonEmptyGadgetStruct();+ tx(sourceDtm, () -> {+ sourceDtm.addDataType(gadgetStruct, DataTypeConflictHandler.REPLACE_HANDLER);+ });++ return (Structure) sourceDtm.getDataType(CategoryPath.ROOT, "Gadget");+ }++ private void applyTestMatch() {+ assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());+ checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);++ List<VTMatch> matches = new ArrayList<>();+ matches.add(testMatch);++ ApplyMatchTask task = new ApplyMatchTask(controller, matches);+ runTask(session, task);+ }++ private void unapplyTestMatch(String expectedSrc, String expectedDest) {+// Test unapply- ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);+ ClearMatchTask unapplyTask = new ClearMatchTask(controller, List.of(testMatch));runTask(session, unapplyTask);// Verify unapply.- checkSignatures("undefined addPerson(void)", "undefined FUN_004011a0()");+ checkSignatures(expectedSrc, expectedDest);assertEquals(VTAssociationStatus.AVAILABLE, testMatch.getAssociation().getStatus());checkFunctionSignatureStatus(testMatch, VTMarkupItemStatus.UNAPPLIED);- checkInline(false, false);- checkNoReturn(false, false);- checkSignatureSource(SourceType.USER_DEFINED, SourceType.DEFAULT);}- //==================================================================================================- // Helper Methods- //==================================================================================================+ private Structure applySourceNonEmtpyGadget() {++ ProgramBasedDataTypeManager sourceDtm = sourceProgram.getDataTypeManager();+ DataType existingEmptyGadgetStruct = sourceDtm.getDataType(CategoryPath.ROOT, "Gadget");+ assertNotNull(existingEmptyGadgetStruct);++ // replace the source empty gadget with a populated one+ Structure gadgetStruct = createNonEmptyGadgetStruct();+ tx(sourceDtm, () -> {+ sourceDtm.addDataType(gadgetStruct, DataTypeConflictHandler.REPLACE_HANDLER);+ });++ // verify it took+ DataType updatedSourceGadget = sourceDtm.getDataType(CategoryPath.ROOT, "Gadget");+ assertTrue(updatedSourceGadget.isEquivalent(gadgetStruct));++ return gadgetStruct;+ }++ private Structure applySourceNonEmtpyGadget_DestEmtpyGadgetInDtm() {++ ProgramBasedDataTypeManager sourceDtm = sourceProgram.getDataTypeManager();+ ProgramBasedDataTypeManager destDtm = destinationProgram.getDataTypeManager();++ DataType existingEmptyGadgetStruct = sourceDtm.getDataType(CategoryPath.ROOT, "Gadget");+ assertNotNull(existingEmptyGadgetStruct);++ // replace the source empty gadget with a populated one+ Structure gadgetStruct = createNonEmptyGadgetStruct();++ tx(sourceDtm, () -> {+ sourceDtm.addDataType(gadgetStruct, DataTypeConflictHandler.REPLACE_HANDLER);+ });++ // verify it took+ DataType updatedSourceGadget = sourceDtm.getDataType(CategoryPath.ROOT, "Gadget");+ assertTrue(updatedSourceGadget.isEquivalent(gadgetStruct));++ // add empty gadget to the destination program+ Structure emptyGadgetStruct = createEmptyGadgetStruct();+ tx(destDtm, () -> {+ destDtm.addDataType(emptyGadgetStruct, DataTypeConflictHandler.REPLACE_HANDLER);+ });++ // verify it took+ DataType destGadget = destDtm.getDataType(CategoryPath.ROOT, "Gadget");+ assertTrue(destGadget.isNotYetDefined());++ return gadgetStruct;+ }++ private void setSourceFunctionThisPointerToPersonStructure() {+ tx(sourceProgram, () -> {+ sourceFunction.setCustomVariableStorage(true);++ Parameter param0 = sourceFunction.getParameter(0);+ Parameter param1 = sourceFunction.getParameter(1);+ param0.setDataType(param1.getDataType(), SourceType.USER_DEFINED);+ });++ DataType personType = sourceProgram.getDataTypeManager().getDataType("/Person");+ assertNotNull(personType);++ // non-custom storage+ tx(destinationProgram, () -> {+ destinationFunction.setReturnType(personType, SourceType.USER_DEFINED);+ });+ }++ private void setSourceFunctionThisPointerToPersonStructureWithCustomStorage() {+ tx(sourceProgram, () -> {+ sourceFunction.setCustomVariableStorage(true);++ Parameter param0 = sourceFunction.getParameter(0);+ Parameter param1 = sourceFunction.getParameter(1);+ param0.setDataType(param1.getDataType(), SourceType.USER_DEFINED);+ });++ DataType personType = sourceProgram.getDataTypeManager().getDataType("/Person");+ assertNotNull(personType);++ // custom storage+ tx(destinationProgram, () -> {+ destinationFunction.setCustomVariableStorage(true);+ });+ }@SuppressWarnings("unused")private String dumpStatus(List<VTMarkupItem> individualItems) {@@ -2194,8 +2073,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegassertNotNull(destinationFunction);}- private void checkSignatures(String expectedSourceSignature,- String expectedDestinationSignature) {+ private void checkSignatures(String expectedSrc, String expectedDest) {final String[] sourceStringBox = new String[1];final String[] destinationStringBox = new String[1];@@ -2205,8 +2083,8 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegdestinationStringBox[0] = destinationFunction.getPrototypeString(false, false);});- assertEquals(expectedSourceSignature, sourceStringBox[0]);- assertEquals(expectedDestinationSignature, destinationStringBox[0]);+ assertEquals("Source signature is not correct", expectedSrc, sourceStringBox[0]);+ assertEquals("Destination signature is not correct", expectedDest, destinationStringBox[0]);}private void checkSignatureSource(SourceType expectedSourceSigSourceType,@@ -2287,28 +2165,53 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegDataType dstDataType = dstDtman.getDataType(dataTypePath);if (shouldExist) {- assertTrue(dstDataType instanceof Pointer);+ assertTrue("Class type is not a pointer: " + dstDataType,+ dstDataType instanceof Pointer);Pointer dstDataTypePtr = (Pointer) dstDataType;-DataType pointedToDataType = dstDataTypePtr.getDataType();-assertTrue(pointedToDataType instanceof Structure);Structure struct = (Structure) pointedToDataType;-assertNotNull(struct);+if (shouldBeNonEmpty) {- assertFalse(struct.isNotYetDefined());+ assertFalse("The structure should not be empty", struct.isNotYetDefined());}else {- assertTrue(struct.isNotYetDefined());+ assertTrue("The structure is not empty as expected", struct.isNotYetDefined());}}else {assertNull(dstDataType);}+ }++ private void checkGadgetReturnType(boolean shouldBeNonEmpty) {++ DataType dt = sourceFunction.getReturnType();+ DataTypePath dataTypePath = dt.getDataTypePath();++ ProgramBasedDataTypeManager dstDtman = destinationProgram.getDataTypeManager();+ DataType dstDataType = dstDtman.getDataType(dataTypePath);+ assertTrue("Class type is not a pointer: " + dstDataType,+ dstDataType instanceof Pointer);++ Pointer dstDataTypePtr = (Pointer) dstDataType;+ DataType pointedToDataType = dstDataTypePtr.getDataType();+ assertTrue(pointedToDataType instanceof Structure);++ Structure struct = (Structure) pointedToDataType;+ assertNotNull(struct);++ if (shouldBeNonEmpty) {+ assertFalse("The return type structure should not be empty", struct.isNotYetDefined());+ }+ else {+ assertTrue("The return type structure is not empty as expected",+ struct.isNotYetDefined());+ }}private VTMarkupItem getFunctionSignatureMarkup(VTMatch match) {@@ -2323,6 +2226,7 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedIntegreturn null;}+ @SuppressWarnings("deprecation") // don't show warning for test codeprivate void removeParameter(Function function, int ordinal) {Program program = function.getProgram();int transaction = -1;@@ -2454,13 +2358,18 @@ public class VTMatchApplyFunctionSignatureTest extends AbstractGhidraHeadedInteg}}- private void runTask(VTSession session, VtTask task) {- int id = session.startTransaction("test");+ private void runTask(VTSession vtSession, VtTask task) {+ int id = vtSession.startTransaction("test");try {task.run(TaskMonitor.DUMMY);}finally {- session.endTransaction(id, true);+ vtSession.endTransaction(id, true);++ if (task.hasErrors()) {+ String errorDetails = task.getErrorDetails();+ fail("Error applying task: " + errorDetails);+ }}}}