Skip to content

Ghidra is a software reverse engineering (SRE) framework

GT-3059 corrected Function Signature Parser issues related to use of datatype service ensure that returned types are properly cloned to target program.

ghidra1120d4241e5e2
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/editor/DataTypeEditorManager.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/editor/DataTypeEditorManager.java
index 03e5651960..b669c5486c 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/editor/DataTypeEditorManager.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/editor/DataTypeEditorManager.java
@@ -35,8 +35,7 @@ import ghidra.program.model.data.*;
import ghidra.program.model.data.Enum;
import ghidra.program.model.listing.*;
import ghidra.util.*;
-import ghidra.util.exception.DuplicateNameException;
-import ghidra.util.exception.InvalidInputException;
+import ghidra.util.exception.*;
/**
* Manages program and archive data type editors.
@@ -615,7 +614,13 @@ public class DataTypeEditorManager
protected boolean applyChanges() {
// can't use a command here as we have to create a transaction on the datatypeManager
// (it might be an archive and the transaction on the program wouldn't work)
- FunctionDefinitionDataType newDefinition = parseSignature();
+ FunctionDefinitionDataType newDefinition = null;
+ try {
+ newDefinition = parseSignature();
+ }
+ catch (CancelledException e1) {
+ // ignore
+ }
if (newDefinition == null) {
return false;
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataTypeUtils.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataTypeUtils.java
index 083ebd7613..373e556d95 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataTypeUtils.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataTypeUtils.java
@@ -22,6 +22,7 @@ import java.util.List;
import javax.swing.Icon;
import javax.swing.ImageIcon;
+import ghidra.app.services.DataTypeQueryService;
import ghidra.app.services.DataTypeManagerService;
import ghidra.program.model.data.*;
import ghidra.program.model.data.Enum;
@@ -328,7 +329,7 @@ public class DataTypeUtils {
* string.
*/
public static List<DataType> getStartsWithMatchingDataTypes(String searchString,
- DataTypeManagerService dataService) {
+ DataTypeQueryService dataService) {
return getMatchingSubList(searchString, searchString + END_CHAR,
dataService.getSortedDataTypeList());
}
@@ -343,7 +344,7 @@ public class DataTypeUtils {
* string.
*/
public static List<DataType> getExactMatchingDataTypes(String searchString,
- DataTypeManagerService dataService) {
+ DataTypeQueryService dataService) {
return getMatchingSubList(searchString, searchString + BEGIN_CHAR,
dataService.getSortedDataTypeList());
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/function/EditFunctionSignatureDialog.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/function/EditFunctionSignatureDialog.java
index 3a61db9340..dcd4bfdcba 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/function/EditFunctionSignatureDialog.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/function/EditFunctionSignatureDialog.java
@@ -40,6 +40,7 @@ import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Program;
import ghidra.program.model.symbol.SourceType;
import ghidra.util.Msg;
+import ghidra.util.exception.CancelledException;
import ghidra.util.exception.InvalidInputException;
/**
@@ -294,8 +295,13 @@ public class EditFunctionSignatureDialog extends DialogComponentProvider {
@Override
protected void okCallback() {
// only close the dialog if the user made valid changes
- if (applyChanges()) {
- close();
+ try {
+ if (applyChanges()) {
+ close();
+ }
+ }
+ catch (CancelledException e) {
+ // ignore - do not close
}
}
@@ -310,8 +316,9 @@ public class EditFunctionSignatureDialog extends DialogComponentProvider {
* command and executed.
*
* @return true if the command was successfully created.
+ * @throws CancelledException if operation cancelled by user
*/
- protected boolean applyChanges() {
+ protected boolean applyChanges() throws CancelledException {
// create the command
Command command = createCommand();
@@ -329,9 +336,9 @@ public class EditFunctionSignatureDialog extends DialogComponentProvider {
return true;
}
- protected FunctionDefinitionDataType parseSignature() {
- FunctionSignatureParser parser = new FunctionSignatureParser(getProgram(),
- tool.getService(DataTypeManagerService.class));
+ protected FunctionDefinitionDataType parseSignature() throws CancelledException {
+ FunctionSignatureParser parser = new FunctionSignatureParser(
+ getProgram().getDataTypeManager(), tool.getService(DataTypeManagerService.class));
try {
return parser.parse(getFunction().getSignature(), getSignature());
}
@@ -341,7 +348,7 @@ public class EditFunctionSignatureDialog extends DialogComponentProvider {
return null;
}
- private Command createCommand() {
+ private Command createCommand() throws CancelledException {
Command cmd = null;
if (!getSignature().equals(this.oldFunctionSignature) || !isSameCallingConvention() ||
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/function/editor/FunctionEditorModel.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/function/editor/FunctionEditorModel.java
index e3056ff3ce..a90bd312e9 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/function/editor/FunctionEditorModel.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/function/editor/FunctionEditorModel.java
@@ -1173,9 +1173,9 @@ public class FunctionEditorModel {
setSignatureFieldText(getFunctionSignatureTextFromModel());
}
- public void parseSignatureFieldText() throws ParseException {
+ public void parseSignatureFieldText() throws ParseException, CancelledException {
FunctionSignatureParser parser =
- new FunctionSignatureParser(getProgram(), dataTypeManagerService);
+ new FunctionSignatureParser(program.getDataTypeManager(), dataTypeManagerService);
FunctionDefinitionDataType f = parser.parse(function.getSignature(), signatureFieldText);
setFunctionData(f);
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/services/DataTypeManagerService.java b/Ghidra/Features/Base/src/main/java/ghidra/app/services/DataTypeManagerService.java
index e7f311a17f..720cc5c678 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/services/DataTypeManagerService.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/services/DataTypeManagerService.java
@@ -26,7 +26,6 @@ import ghidra.app.plugin.core.datamgr.DataTypeManagerPlugin;
import ghidra.app.plugin.core.datamgr.archive.Archive;
import ghidra.app.plugin.core.datamgr.archive.DuplicateIdException;
import ghidra.framework.plugintool.ServiceInfo;
-import ghidra.framework.store.LockException;
import ghidra.program.model.data.*;
import ghidra.program.model.listing.DataTypeArchive;
import ghidra.util.HelpLocation;
@@ -37,11 +36,18 @@ import ghidra.util.HelpLocation;
* data and defining function return types and parameters.
*/
@ServiceInfo(defaultProvider = DataTypeManagerPlugin.class, description = "Service to provide list of cycle groups and data types identified as 'Favorites.'")
-public interface DataTypeManagerService {
+public interface DataTypeManagerService extends DataTypeQueryService {
+
+ /**
+ * Get the data type manager that has all of the built in types.
+ * @return data type manager for built in data types
+ */
+ public DataTypeManager getBuiltInDataTypesManager();
/**
* Get the data types marked as favorites that will show up on
* a popup menu.
+ * @return list of favorite datatypess
*/
public List<DataType> getFavorites();
@@ -95,19 +101,6 @@ public interface DataTypeManagerService {
*/
public void edit(DataType dt);
- /**
- * Get the data type manager that has all of the built in types.
- * @return data type manager for built in data types
- */
- public DataTypeManager getBuiltInDataTypesManager();
-
- /**
- * Gets the open data type managers.
- *
- * @return the open data type managers.
- */
- public DataTypeManager[] getDataTypeManagers();
-
/**
* Closes the archive for the given {@link DataTypeManager}. This will ignore request to
* close the open Program's manager and the built-in manager.
@@ -143,22 +136,13 @@ public interface DataTypeManagerService {
*
* @param file data type archive file
* @param acquireWriteLock true if write lock should be acquired (i.e., open for update)
- * @return an Archive based upon the given archive file
- * @throws LockException
+ * @return an Archive based upon the given archive files
* @throws IOException if an i/o error occurs opening the data type archive
* @throws DuplicateIdException if another archive with the same ID is already open
*/
public Archive openArchive(File file, boolean acquireWriteLock)
throws IOException, DuplicateIdException;
- /**
- * Gets the sorted list of all datatypes known by this service via it's owned DataTypeManagers.
- * This method can be called frequently, as the underlying data is indexed and only updated
- * as changes are made.
- * @return the sorted list of known data types.
- */
- public List<DataType> getSortedDataTypeList();
-
/**
* Selects the given data type in the display of data types. A null <tt>dataType</tt>
* value will clear the current selection.
@@ -167,16 +151,6 @@ public interface DataTypeManagerService {
*/
public void setDataTypeSelected(DataType dataType);
- /**
- * Shows the user a dialog that allows them to choose a data type from a tree of all available
- * data types.
- *
- * @param filterText If not null, this text filters the visible data types to only show those
- * that start with the given text
- * @return A data type chosen by the user
- */
- public DataType getDataType(String filterText);
-
/**
* Shows the user a dialog that allows them to choose a data type from a tree of all available
* data types.
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/services/DataTypeQueryService.java b/Ghidra/Features/Base/src/main/java/ghidra/app/services/DataTypeQueryService.java
new file mode 100644
index 0000000000..cb44234c23
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/services/DataTypeQueryService.java
@@ -0,0 +1,57 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.services;
+
+import java.util.List;
+
+import ghidra.program.model.data.DataType;
+import ghidra.program.model.data.DataTypeManager;
+
+/**
+ * Simplified datatype service interface to provide query capabilities
+ * to a set of open datatype managers
+ */
+public interface DataTypeQueryService {
+
+ /**
+ * Gets the open data type managers.
+ *
+ * @return the open data type managers.
+ */
+ public DataTypeManager[] getDataTypeManagers();
+
+ /**
+ * Gets the sorted list of all datatypes known by this service via it's owned DataTypeManagers.
+ * This method can be called frequently, as the underlying data is indexed and only updated
+ * as changes are made.
+ * @return the sorted list of known data types.
+ */
+ public List<DataType> getSortedDataTypeList();
+
+ /**
+ * Obtain the preferred datatype which corresponds to the specified
+ * datatype specified by filterText. A tool-based service provider
+ * may prompt the user to select a datatype if more than one possibility
+ * exists.
+ *
+ * @param filterText If not null, this text filters the visible data types to only show those
+ * that start with the given text
+ * @return the preferred data type (e.g., chosen by the user) or null if no match found
+ * or selection was cancelled by user.
+ */
+ public DataType getDataType(String filterText);
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/datatype/DataTypeSelectionEditor.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/datatype/DataTypeSelectionEditor.java
index 3bdf812625..36bfd231f8 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/datatype/DataTypeSelectionEditor.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/datatype/DataTypeSelectionEditor.java
@@ -29,6 +29,7 @@ import ghidra.app.services.DataTypeManagerService;
import ghidra.framework.plugintool.ServiceProvider;
import ghidra.program.model.data.*;
import ghidra.util.data.DataTypeParser;
+import ghidra.util.exception.CancelledException;
/**
* An editor that is used to show the {@link DropDownSelectionTextField} for the entering of
@@ -355,7 +356,12 @@ public class DataTypeSelectionEditor extends AbstractCellEditor {
DataType newDataType = null;
DataTypeParser parser = new DataTypeParser(dataTypeManager, dataTypeManager,
dataTypeManagerService, allowedDataTypes);
- newDataType = parser.parse(selectionField.getText(), getDataTypeRootForCurrentText());
+ try {
+ newDataType = parser.parse(selectionField.getText(), getDataTypeRootForCurrentText());
+ }
+ catch (CancelledException e) {
+ return false;
+ }
if (newDataType != null) {
if (maxSize >= 0 && newDataType.getLength() > newDataType.getLength()) {
throw new InvalidDataTypeException("data-type larger than " + maxSize + " bytes");
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/parser/FunctionSignatureParser.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/parser/FunctionSignatureParser.java
index 9d4a3b4af0..feedec161b 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/parser/FunctionSignatureParser.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/parser/FunctionSignatureParser.java
@@ -16,77 +16,94 @@
package ghidra.app.util.parser;
import java.util.*;
+import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import javax.help.UnsupportedOperationException;
+
import org.apache.commons.lang3.StringUtils;
-import ghidra.app.services.DataTypeManagerService;
+import ghidra.app.services.DataTypeQueryService;
import ghidra.app.util.cparser.C.ParseException;
-import ghidra.framework.plugintool.ServiceProvider;
+import ghidra.program.database.data.DataTypeUtilities;
import ghidra.program.model.data.*;
import ghidra.program.model.listing.FunctionSignature;
-import ghidra.program.model.listing.Program;
import ghidra.util.data.DataTypeParser;
import ghidra.util.data.DataTypeParser.AllowedDataTypes;
+import ghidra.util.exception.CancelledException;
/**
- * Class for parsing function signatures. This class attempts to be much more flexible than
- * a full parser that requires correct C or C++ syntax. To achieve this, it scans the original
- * function signature (if present) for names that would cause parse problems (parens, commas, and
- * spaces). If it finds any problem names, it looks for those strings in the text to be parsed and
- * if it finds them, it replaces them with substitutes that parse easily. Then, after parsing, those
- * replacement strings are then restored to their original values.
+ * Class for parsing function signatures. This class attempts to be much more
+ * flexible than a full parser that requires correct C or C++ syntax. To achieve
+ * this, it scans the original function signature (if present) for names that
+ * would cause parse problems (parens, brackets, asterisk, commas, and spaces).
+ * If it finds any problem names, it looks for those strings in the text to be
+ * parsed and if it finds them, it replaces them with substitutes that parse
+ * easily. Then, after parsing, those replacement strings are then restored to
+ * their original values.
* <P>
* Some examples of valid c++ that would fail due to the current limitations:
* <P>
* void foo(myclass<int, float> x) - fails due to comma in x's data type name
- * int operator()(int x) - fails due to parens in function name
- * unsigned int bar(float y) - fails due to space in return type name
+ * int operator()(int x) - fails due to parens in function name unsigned int
+ * bar(float y) - fails due to space in return type name
* <P>
- * Note: you can edit signatures that already have these features as long as your modifications
- * don't affect the pieces containing parens, commas or spaces in their name.
+ * Note: you can edit signatures that already have these features as long as
+ * your modifications don't affect the pieces containing parens, commas or
+ * spaces in their name.
*/
public class FunctionSignatureParser {
private static final String REPLACEMENT_DT_NAME = "__REPLACE_DT_NAME__";
private static final String REPLACE_NAME = "__REPLACE_NAME__";
private DataTypeParser dataTypeParser;
private Map<String, DataType> dtMap = new HashMap<>();
+
private Map<String, String> nameMap = new HashMap<>();
+ private DataTypeManager destDataTypeManager;
+ private ParserDataTypeManagerService dtmService;
/**
- * Constructs a SignatureParser for a program.
- *
- * @param program the program whose datatype manager is used to resolve datatype names.
- * @param service the DataTypeManagerService to use for resolving datatypes that can't be
- * found in the given program. Can be null to utilize program based types only.
+ * Constructs a SignatureParser for a program. The destDataTypeManager and/or
+ * service must be specified.
+ *
+ * @param destDataTypeManager the destination datatype maanger.
+ * @param service the DataTypeManagerService to use for resolving datatypes that
+ * can't be found in the given program. Can be null to utilize
+ * program based types only.
*/
- public FunctionSignatureParser(Program program, DataTypeManagerService service) {
- if (service == null) {
- if (program == null) {
- throw new IllegalArgumentException("program or service provider required");
- }
- DataTypeManager dataTypeManager = program.getDataTypeManager();
- dataTypeParser = new DataTypeParser(dataTypeManager, dataTypeManager, null,
- AllowedDataTypes.FIXED_LENGTH);
- }
- else {
- dataTypeParser = new DataTypeParser(service, AllowedDataTypes.FIXED_LENGTH);
- }
+ public FunctionSignatureParser(DataTypeManager destDataTypeManager,
+ DataTypeQueryService service) {
+ this.destDataTypeManager = destDataTypeManager;
+ if (destDataTypeManager != null && service == null) {
+ throw new IllegalArgumentException(
+ "Destination DataTypeManager or DataTypeManagerService provider required");
+ }
+ if (service != null) {
+ dtmService = new ParserDataTypeManagerService(service);
+ }
+ dataTypeParser = new DataTypeParser(destDataTypeManager, destDataTypeManager, dtmService,
+ AllowedDataTypes.FIXED_LENGTH);
}
/**
* Parse the given function signature text into a FunctionDefinitionDataType.
*
- * @param originalSignature the function signature before editing. This may be null
- * if the user is entering a new signature instead of editing an existing one.
- * @param signatureText the text to be parsed into a function signature.
+ * @param originalSignature the function signature before editing. This may be
+ * null if the user is entering a new signature instead
+ * of editing an existing one.
+ * @param signatureText the text to be parsed into a function signature.
* @return the FunctionDefinitionDataType resulting from parsing.
* @throws ParseException if the text could not be parsed.
+ * @throws CancelledException if parse cancelled by user
*/
public FunctionDefinitionDataType parse(FunctionSignature originalSignature,
- String signatureText) throws ParseException {
+ String signatureText) throws ParseException, CancelledException {
+
dtMap.clear();
nameMap.clear();
+ if (dtmService != null) {
+ dtmService.clearCache(); // clear datatype selection cache
+ }
if (originalSignature != null) {
initDataTypeMap(originalSignature);
@@ -94,7 +111,8 @@ public class FunctionSignatureParser {
}
String functionName = extractFunctionName(signatureText);
- FunctionDefinitionDataType function = new FunctionDefinitionDataType(functionName);
+ FunctionDefinitionDataType function =
+ new FunctionDefinitionDataType(functionName, destDataTypeManager);
function.setReturnType(extractReturnType(signatureText));
function.setArguments(extractArguments(signatureText));
@@ -129,13 +147,6 @@ public class FunctionSignatureParser {
cacheDataType(baseType);
}
- private static DataTypeManagerService getDataTypeManagerService(ServiceProvider provider) {
- if (provider != null) {
- return provider.getService(DataTypeManagerService.class);
- }
- return null;
- }
-
private boolean hasVarArgs(String newSignatureText) {
int startIndex = newSignatureText.lastIndexOf(',');
int endIndex = newSignatureText.indexOf(')');
@@ -146,7 +157,8 @@ public class FunctionSignatureParser {
return "...".equals(lastArg);
}
- private ParameterDefinition[] extractArguments(String newSignatureText) throws ParseException {
+ private ParameterDefinition[] extractArguments(String newSignatureText)
+ throws ParseException, CancelledException {
int startIndex = newSignatureText.indexOf('(');
int endIndex = newSignatureText.indexOf(')');
if (startIndex < 0 || endIndex < 0 || startIndex >= endIndex) {
@@ -176,7 +188,7 @@ public class FunctionSignatureParser {
}
private void addParameter(List<ParameterDefinition> parameterList, String arg)
- throws ParseException {
+ throws ParseException, CancelledException {
if ("...".equals(arg)) {
return;
}
@@ -242,7 +254,7 @@ public class FunctionSignatureParser {
return substitute(text, name, replacementName);
}
- DataType extractReturnType(String signatureText) throws ParseException {
+ DataType extractReturnType(String signatureText) throws ParseException, CancelledException {
int parenIndex = signatureText.indexOf('(');
if (parenIndex < 0) {
throw new ParseException("Can't find return type");
@@ -260,17 +272,42 @@ public class FunctionSignatureParser {
return dt;
}
- private DataType resolveDataType(String dataTypeName) {
+ // The following regex pattern attempts to isolate the parameter name from
+ // the begining of a parameter specification. Since the name is optional,
+ // additional steps must be taken in code to ensure that the trailing word of
+ // a multi-word type-specified is not treated as a name (e.g., unsigned long).
+ //
+ // The regex pattern attempts to isolate the following fields:
+ //
+ // <type-specifier> [<array-specifier>|<pointer-specifier>]* [param-name]
+ // group-1 group-3 group-4
+ //
+ // Note: group-2 is an inner group to group-3 is not useful
+ //
+ private static final Pattern parameterNameCapturePattern =
+ Pattern.compile("(.+?)((\\[\\d*\\]|\\*\\d*)\\s*)*([^\\s\\[\\*]+)");
+
+ private DataType resolveDataType(String dataTypeName) throws CancelledException {
if (dtMap.containsKey(dataTypeName)) {
return dtMap.get(dataTypeName);
}
+ Matcher m = parameterNameCapturePattern.matcher(dataTypeName);
+ if (m.matches()) {
+ boolean hasPointerOrArraySpec = m.group(3) != null;
+ boolean hasName = (m.group(4) != null) && (m.group(4).length() != 0);
+ if (hasPointerOrArraySpec && hasName) {
+ // name after array/pointer spec - dataTypeName is not a valid datatype
+ return null;
+ }
+ }
+
DataType dataType = null;
try {
dataType = dataTypeParser.parse(dataTypeName);
}
catch (InvalidDataTypeException e) {
- // ignore
+ // ignore - return null
}
return dataType;
}
@@ -304,7 +341,57 @@ public class FunctionSignatureParser {
}
private boolean canParse(String text) {
- return !StringUtils.containsAny(text, "(), ");
+ return !StringUtils.containsAny(text, "()*[], ");
}
+ /**
+ * <code></code> provides a simple caching datatype manager service
+ * wrapper. Implementation intended for use with {@link FunctionSignatureParser}
+ * and underlying {@link DataTypeParser} and {@link DataTypeUtilities} classes.
+ */
+ private static class ParserDataTypeManagerService implements DataTypeQueryService {
+
+ private Map<String, DataType> dtCache = new HashMap<>();
+
+ private final DataTypeQueryService service;
+
+ /**
+ * Construct caching datatype manager service.
+ * @param service actual datatype manager service which may prompt
+ * user to make a datatype selection. It is this impementation's
+ * purpose to cache such a choice for {@link #getDataType(String)} to
+ * avoid repeated selections of the same choice if type is reused
+ * within a function signature.
+ */
+ ParserDataTypeManagerService(DataTypeQueryService service) {
+ this.service = service;
+ }
+
+ void clearCache() {
+ dtCache.clear();
+ }
+
+ @Override
+ public DataTypeManager[] getDataTypeManagers() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public List<DataType> getSortedDataTypeList() {
+ return service.getSortedDataTypeList();
+ }
+
+ @Override
+ public DataType getDataType(String filterText) {
+ DataType dt = dtCache.get(filterText);
+ if (dt == null) {
+ dt = service.getDataType(filterText);
+ if (dt != null) {
+ dtCache.put(filterText, dt);
+ }
+ }
+ return dt;
+ }
+
+ }
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/xml/DtParser.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/xml/DtParser.java
index a617a8ddff..50cf504e0a 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/xml/DtParser.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/xml/DtParser.java
@@ -1,6 +1,5 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,6 +18,7 @@ package ghidra.app.util.xml;
import ghidra.program.model.data.*;
import ghidra.util.data.DataTypeParser;
import ghidra.util.data.DataTypeParser.AllowedDataTypes;
+import ghidra.util.exception.CancelledException;
/**
* DtParser
@@ -27,12 +27,12 @@ class DtParser {
private DataTypeManager dtManager;
private DataTypeParser parser;
-
+
DtParser(DataTypeManager dtManager) {
this.dtManager = dtManager;
this.parser = new DataTypeParser(dtManager, dtManager, null, AllowedDataTypes.DYNAMIC);
}
-
+
/**
* Parse the specified dtName within the specified category.
* @param dtName
@@ -44,7 +44,8 @@ class DtParser {
DataType dt;
try {
dt = parser.parse(dtName, category);
- } catch (InvalidDataTypeException e) {
+ }
+ catch (InvalidDataTypeException | CancelledException e) {
return null;
}
if (size > 0 && size != dt.getLength()) {
@@ -62,13 +63,13 @@ class DtParser {
*/
private DataType adjustPointerDataTypes(int size, DataType dt) {
if (dt instanceof Pointer) {
- Pointer p = (Pointer)dt;
+ Pointer p = (Pointer) dt;
dt = new PointerDataType(p.getDataType(), size, dtManager);
}
- else if (dt instanceof Array && ((Array)dt).getDataType() instanceof Pointer) {
+ else if (dt instanceof Array && ((Array) dt).getDataType() instanceof Pointer) {
// TODO: does not handle multi-dimensional pointer arrays
- Array array = (Array)dt;
- DataType pointerDt = ((Pointer)array.getDataType()).getDataType();
+ Array array = (Array) dt;
+ DataType pointerDt = ((Pointer) array.getDataType()).getDataType();
int pointerSize = size / array.getNumElements();
DataType pointer = new PointerDataType(pointerDt, pointerSize, dtManager);
dt = new ArrayDataType(pointer, array.getNumElements(), pointerSize, dtManager);
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/util/data/DataTypeParser.java b/Ghidra/Features/Base/src/main/java/ghidra/util/data/DataTypeParser.java
index 1397e89052..682d45e558 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/util/data/DataTypeParser.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/util/data/DataTypeParser.java
@@ -19,11 +19,13 @@ import java.util.ArrayList;
import java.util.List;
import ghidra.app.plugin.core.datamgr.util.DataTypeUtils;
+import ghidra.app.services.DataTypeQueryService;
import ghidra.app.services.DataTypeManagerService;
import ghidra.program.database.data.DataTypeUtilities;
import ghidra.program.database.data.ProgramDataTypeManager;
import ghidra.program.model.data.*;
import ghidra.util.exception.AssertException;
+import ghidra.util.exception.CancelledException;
public class DataTypeParser {
@@ -86,7 +88,7 @@ public class DataTypeParser {
private DataTypeManager sourceDataTypeManager; // may be null
private DataTypeManager destinationDataTypeManager; // may be null
- private DataTypeManagerService dataTypeManagerService; // may be null
+ private DataTypeQueryService dataTypeManagerService; // may be null
private AllowedDataTypes allowedTypes;
/**
@@ -97,7 +99,7 @@ public class DataTypeParser {
* @param dataTypeManagerService
* @param allowedTypes
*/
- public DataTypeParser(DataTypeManagerService dataTypeManagerService,
+ public DataTypeParser(DataTypeQueryService dataTypeManagerService,
AllowedDataTypes allowedTypes) {
this.dataTypeManagerService = dataTypeManagerService;
this.allowedTypes = allowedTypes;
@@ -114,7 +116,7 @@ public class DataTypeParser {
*/
public DataTypeParser(DataTypeManager sourceDataTypeManager,
DataTypeManager destinationDataTypeManager,
- DataTypeManagerService dataTypeManagerService, AllowedDataTypes allowedTypes) {
+ DataTypeQueryService dataTypeManagerService, AllowedDataTypes allowedTypes) {
this.sourceDataTypeManager = sourceDataTypeManager;
this.destinationDataTypeManager = destinationDataTypeManager;
this.dataTypeManagerService = dataTypeManagerService;
@@ -126,8 +128,10 @@ public class DataTypeParser {
* @param dataTypeString a known data-type name followed by zero or more pointer/array decorations.
* @return parsed data-type or null if not found
* @throws InvalidDataTypeException if data-type string is invalid or length exceeds specified maxSize
+ * @throws CancelledException parse cancelled through user interaction
*/
- public DataType parse(String dataTypeString) throws InvalidDataTypeException {
+ public DataType parse(String dataTypeString)
+ throws InvalidDataTypeException, CancelledException {
return parse(dataTypeString, (CategoryPath) null);
}
@@ -138,9 +142,10 @@ public class DataTypeParser {
* @param category known path of data-type or null if unknown
* @return parsed data-type or null if not found
* @throws InvalidDataTypeException if data-type string is invalid or length exceeds specified maxSize
+ * @throws CancelledException parse cancelled through user interaction (only if parser contructed with service)
*/
public DataType parse(String dataTypeString, CategoryPath category)
- throws InvalidDataTypeException {
+ throws InvalidDataTypeException, CancelledException {
dataTypeString = dataTypeString.replaceAll("\\s+", " ").trim();
String dataTypeName = getBaseString(dataTypeString);
DataType namedDt = getNamedDataType(dataTypeName, category);
@@ -158,9 +163,10 @@ public class DataTypeParser {
* The string may start with the baseDataType's name.
* @return parsed data-type or null if not found
* @throws InvalidDataTypeException if data-type string is invalid or length exceeds specified maxSize
+ * @throws CancelledException parse cancelled through user interaction (only if parser contructed with service)
*/
public DataType parse(String dataTypeString, DataType suggestedBaseDataType)
- throws InvalidDataTypeException {
+ throws InvalidDataTypeException, CancelledException {
dataTypeString = dataTypeString.replaceAll("\\s+", " ").trim();
String dataTypeName = getBaseString(dataTypeString);
if (dataTypeName == null || dataTypeName.length() == 0) {
@@ -244,6 +250,7 @@ public class DataTypeParser {
List<DtPiece> modifiers = new ArrayList<>();
boolean terminalModifier = false;
for (String piece : splitDataTypeModifiers(dataTypeModifiers)) {
+ piece = piece.trim();
if (terminalModifier) {
throw new InvalidDataTypeException("Invalid data type modifier");
}
@@ -312,7 +319,7 @@ public class DataTypeParser {
}
private DataType getNamedDataType(String baseName, CategoryPath category)
- throws InvalidDataTypeException {
+ throws InvalidDataTypeException, CancelledException {
List<DataType> results = new ArrayList<>();
DataType dt = findDataType(sourceDataTypeManager, baseName, category, results);
@@ -338,7 +345,8 @@ public class DataTypeParser {
return dt.clone(destinationDataTypeManager);
}
- private DataType findDataTypeInAllDataTypeManagers(String baseName, List<DataType> results) {
+ private DataType findDataTypeInAllDataTypeManagers(String baseName, List<DataType> results)
+ throws CancelledException {
if (results.isEmpty() && dataTypeManagerService != null) {
results.addAll(
DataTypeUtils.getExactMatchingDataTypes(baseName, dataTypeManagerService));
@@ -351,6 +359,9 @@ public class DataTypeParser {
if (dt == null && dataTypeManagerService != null) {
// give up and ask the user
dt = dataTypeManagerService.getDataType(baseName);
+ if (dt == null) {
+ throw new CancelledException();
+ }
}
}
return dt;
@@ -361,7 +372,7 @@ public class DataTypeParser {
DataTypeManager builtInDTM = BuiltInDataTypeManager.getDataTypeManager();
if (dtm == null) {
- // not DTM specified--try the built-ins
+ // no DTM specified--try the built-ins
return findDataType(builtInDTM, baseName, category, list);
}
diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/function/EditFunctionSignatureDialogTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/function/EditFunctionSignatureDialogTest.java
index 2bea49eb24..526b1edd86 100644
--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/function/EditFunctionSignatureDialogTest.java
+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/function/EditFunctionSignatureDialogTest.java
@@ -22,8 +22,8 @@ import org.junit.*;
import ghidra.app.plugin.core.datamgr.DataTypeManagerPlugin;
import ghidra.framework.plugintool.PluginTool;
import ghidra.program.database.ProgramDB;
-import ghidra.program.model.TestDoubleFunctionSignature;
import ghidra.program.model.FunctionTestDouble;
+import ghidra.program.model.TestDoubleFunctionSignature;
import ghidra.program.model.data.*;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Program;
@@ -51,7 +51,7 @@ public class EditFunctionSignatureDialogTest extends AbstractGhidraHeadedIntegra
}
@Test
- public void testParseSignature_Good() {
+ public void testParseSignature_Good() throws Exception {
String signature = "void bob(int a)";
Function f = function("bob", signature);
@@ -62,7 +62,7 @@ public class EditFunctionSignatureDialogTest extends AbstractGhidraHeadedIntegra
}
@Test
- public void testParseSignature_Bad_AtSignInName() {
+ public void testParseSignature_Bad_AtSignInName() throws Exception {
String signature = "void bob@12(int a)";
Function f = function("bob@12", signature);
@@ -73,7 +73,7 @@ public class EditFunctionSignatureDialogTest extends AbstractGhidraHeadedIntegra
}
@Test
- public void testParseSignature_Bad_ExtraParensAtEnd() {
+ public void testParseSignature_Bad_ExtraParensAtEnd() throws Exception {
String signature = "void bob(int a)()";
Function f = function("bob", signature);
@@ -86,7 +86,7 @@ public class EditFunctionSignatureDialogTest extends AbstractGhidraHeadedIntegra
}
@Test
- public void testParseSignature_Bad_MissingParen() {
+ public void testParseSignature_Bad_MissingParen() throws Exception {
String signature = "void bob(int a";
Function f = function("bob", signature);
@@ -96,7 +96,7 @@ public class EditFunctionSignatureDialogTest extends AbstractGhidraHeadedIntegra
}
@Test
- public void testParseSignature_Bad_MissingReturnType() {
+ public void testParseSignature_Bad_MissingReturnType() throws Exception {
String signature = "bob(int a)";
Function f = function("bob", signature);
diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/util/data/DataTypeParserTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/util/data/DataTypeParserTest.java
index 38438197af..66d187c540 100644
--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/util/data/DataTypeParserTest.java
+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/util/data/DataTypeParserTest.java
@@ -15,7 +15,7 @@
*/
package ghidra.util.data;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.*;
import org.junit.*;
@@ -175,7 +175,7 @@ public class DataTypeParserTest extends AbstractEditorTest {
DataType dt = parser.parse(dtString);
assertNotNull(dt);
}
- catch (InvalidDataTypeException e) {
+ catch (Exception e) {
Assert.fail(e.getMessage());
}
}
@@ -187,7 +187,7 @@ public class DataTypeParserTest extends AbstractEditorTest {
DataType dt = parser.parse(dtString);
assertNotNull(dt);
}
- catch (InvalidDataTypeException e) {
+ catch (Exception e) {
Assert.fail(e.getMessage());
}
}
@@ -202,6 +202,9 @@ public class DataTypeParserTest extends AbstractEditorTest {
catch (InvalidDataTypeException e) {
// good
}
+ catch (Exception e) {
+ Assert.fail(e.getMessage());
+ }
}
private void checkInvalidDt(String dtString, AllowedDataTypes allowableTypes) {
@@ -214,6 +217,9 @@ public class DataTypeParserTest extends AbstractEditorTest {
catch (InvalidDataTypeException e) {
// good
}
+ catch (Exception e) {
+ Assert.fail(e.getMessage());
+ }
}
}
diff --git a/Ghidra/Features/Base/src/test/java/ghidra/app/plugin/core/function/editor/FunctionEditorModelTest.java b/Ghidra/Features/Base/src/test/java/ghidra/app/plugin/core/function/editor/FunctionEditorModelTest.java
index 2f4f23fb10..7698b02a8c 100644
--- a/Ghidra/Features/Base/src/test/java/ghidra/app/plugin/core/function/editor/FunctionEditorModelTest.java
+++ b/Ghidra/Features/Base/src/test/java/ghidra/app/plugin/core/function/editor/FunctionEditorModelTest.java
@@ -917,7 +917,7 @@ public class FunctionEditorModelTest extends AbstractGenericTest {
}
@Test
- public void testSettingParamTypeToVariableLengthDT() throws ParseException {
+ public void testSettingParamTypeToVariableLengthDT() throws Exception {
model.setCallingConventionName(null);
model.setSignatureFieldText("int joe(char a)");
model.parseSignatureFieldText();
@@ -932,7 +932,7 @@ public class FunctionEditorModelTest extends AbstractGenericTest {
}
@Test
- public void testSettingParamTypeToVoid() throws ParseException {
+ public void testSettingParamTypeToVoid() throws Exception {
model.setCallingConventionName(null);
model.setSignatureFieldText("int joe(char a)");
model.parseSignatureFieldText();
@@ -1670,7 +1670,7 @@ public class FunctionEditorModelTest extends AbstractGenericTest {
}
@Test
- public void testAutoAddingRemovingThisParameterFixesSelection() throws ParseException {
+ public void testAutoAddingRemovingThisParameterFixesSelection() throws Exception {
model.setSignatureFieldText("int joe(int a, int b, int c)");
model.parseSignatureFieldText();
assertEquals(3, model.getParameters().size());
@@ -1705,8 +1705,7 @@ public class FunctionEditorModelTest extends AbstractGenericTest {
}
@Test
- public void testParsingWorksEvenWithBadFunctionNameIfFunctionNameNotChanged()
- throws ParseException {
+ public void testParsingWorksEvenWithBadFunctionNameIfFunctionNameNotChanged() throws Exception {
model.setSignatureFieldText("int joe(int a, int b, int c)");
model.parseSignatureFieldText();
String strangeName = "as(s)+[]";
@@ -1719,7 +1718,7 @@ public class FunctionEditorModelTest extends AbstractGenericTest {
}
@Test
- public void testParsingWorksWithNamePatternDuplication() throws ParseException {
+ public void testParsingWorksWithNamePatternDuplication() throws Exception {
int txId = program.startTransaction("Add TypeDef jjjjjj");
try {
DataType dt = new TypedefDataType("jjjjjj", ByteDataType.dataType);
@@ -1745,7 +1744,7 @@ public class FunctionEditorModelTest extends AbstractGenericTest {
}
@Test
- public void testCopyStorageByNameWhenParsing() throws ParseException {
+ public void testCopyStorageByNameWhenParsing() throws Exception {
model.setSignatureFieldText("int joe(int a, int b, int c)");
model.parseSignatureFieldText();
@@ -1766,7 +1765,7 @@ public class FunctionEditorModelTest extends AbstractGenericTest {
}
@Test
- public void testCopyStorageByOrdinal() throws ParseException {
+ public void testCopyStorageByOrdinal() throws Exception {
model.setSignatureFieldText("int joe(int a, int b, int c)");
model.parseSignatureFieldText();
@@ -1787,7 +1786,7 @@ public class FunctionEditorModelTest extends AbstractGenericTest {
}
@Test
- public void testCopyStorageByNameAndOrdinal() throws ParseException {
+ public void testCopyStorageByNameAndOrdinal() throws Exception {
model.setSignatureFieldText("int joe(int a, int b, int c, int d)");
model.parseSignatureFieldText();
@@ -1809,7 +1808,7 @@ public class FunctionEditorModelTest extends AbstractGenericTest {
}
@Test
- public void testCopyStorageByNameAndOrdinal2() throws ParseException {
+ public void testCopyStorageByNameAndOrdinal2() throws Exception {
model.setSignatureFieldText("int joe(int a, int b, int c, int d)");
model.parseSignatureFieldText();
@@ -1832,7 +1831,7 @@ public class FunctionEditorModelTest extends AbstractGenericTest {
}
@Test
- public void testCopyStorageQuitsWhenSizesDontMatch() throws ParseException {
+ public void testCopyStorageQuitsWhenSizesDontMatch() throws Exception {
model.setSignatureFieldText("int joe(int a, int b, int c)");
model.parseSignatureFieldText();
@@ -1851,7 +1850,7 @@ public class FunctionEditorModelTest extends AbstractGenericTest {
}
@Test
- public void testApplyUseCustomStorage() throws ParseException {
+ public void testApplyUseCustomStorage() throws Exception {
model.setSignatureFieldText("int joe(int a, int b, int c)");
model.parseSignatureFieldText();
model.apply();
@@ -1899,7 +1898,7 @@ public class FunctionEditorModelTest extends AbstractGenericTest {
// this test was to reproduce a bug where if you setAllowCustomStoarge=true, then edited the
// return type, you got a stack trace when validating the model.
@Test
- public void testPar() throws ParseException {
+ public void testPar() throws Exception {
model.setUseCustomizeStorage(true);
model.setSignatureFieldText("int bob(int a)");
model.parseSignatureFieldText();
diff --git a/Ghidra/Features/Base/src/test/java/ghidra/app/util/parser/FunctionSignatureParserTest.java b/Ghidra/Features/Base/src/test/java/ghidra/app/util/parser/FunctionSignatureParserTest.java
index bbbea59fd1..159f2c3801 100644
--- a/Ghidra/Features/Base/src/test/java/ghidra/app/util/parser/FunctionSignatureParserTest.java
+++ b/Ghidra/Features/Base/src/test/java/ghidra/app/util/parser/FunctionSignatureParserTest.java
@@ -17,9 +17,13 @@ package ghidra.app.util.parser;
import static org.junit.Assert.*;
+import java.util.*;
+
import org.junit.Before;
import org.junit.Test;
+import ghidra.app.plugin.core.analysis.DefaultDataTypeManagerService;
+import ghidra.app.services.DataTypeManagerService;
import ghidra.app.util.cparser.C.ParseException;
import ghidra.program.database.ProgramBuilder;
import ghidra.program.database.ProgramDB;
@@ -27,17 +31,67 @@ import ghidra.program.model.data.*;
import ghidra.program.model.listing.FunctionSignature;
import ghidra.test.AbstractGhidraHeadedIntegrationTest;
import ghidra.test.ToyProgramBuilder;
+import ghidra.util.exception.CancelledException;
public class FunctionSignatureParserTest extends AbstractGhidraHeadedIntegrationTest {
private ProgramDB program;
private FunctionSignatureParser parser;
+ private int dtChoiceCount;
@Before
public void setUp() throws Exception {
ProgramBuilder builder = new ToyProgramBuilder("test", false);
+ StructureDataType s = new StructureDataType("StructA", 0);
+ s.setInternallyAligned(true);
+ s.add(IntegerDataType.dataType);
+ builder.addDataType(s);
program = builder.getProgram();
- parser = new FunctionSignatureParser(program, null);
+
+ DataTypeManagerService service = new DefaultDataTypeManagerService() {
+ ArrayList<DataType> dtList; // assume types list will not change after requested during parse
+
+ @Override
+ public List<DataType> getSortedDataTypeList() {
+ if (dtList != null) {
+ return dtList;
+ }
+ // Default implementation only provides builtIn types which is not consistent
+ // with Tool-based service.
+ dtList = new ArrayList<>(super.getSortedDataTypeList());
+ program.getDataTypeManager().getAllDataTypes(dtList);
+ Collections.sort(dtList, new NameComparator());
+ return dtList;
+ }
+
+ @Override
+ public DataType getDataType(String filterText) {
+ // method only called if no results or multiple results were found.
+ // Tool based implementation will prompt user, test will pick last one
+ ArrayList<DataType> list = new ArrayList<>();
+ program.getDataTypeManager().findDataTypes(filterText, list);
+ if (list.isEmpty()) {
+ return null;
+ }
+ int count = list.size();
+ assertTrue("Expected when required to choose from multiple types", count > 1);
+ ++dtChoiceCount;
+ return list.get(count - 1);
+ }
+ };
+
+ parser = new FunctionSignatureParser(program.getDataTypeManager(), service);
+ }
+
+ private class NameComparator implements Comparator<DataType> {
+ @Override
+ public int compare(DataType d1, DataType d2) {
+ int c = d1.getName().compareTo(d2.getName());
+ if (c == 0) {
+ return d1.getCategoryPath().compareTo(d2.getCategoryPath());
+ }
+ return c;
+ }
}
@Test
@@ -94,13 +148,13 @@ public class FunctionSignatureParserTest extends AbstractGhidraHeadedIntegration
}
@Test
- public void testParseSimple() throws ParseException {
+ public void testParseSimple() throws Exception {
FunctionDefinitionDataType dt = parser.parse(null, "int Bob(int a, float b)");
assertEquals("int Bob(int a, float b)", dt.getRepresentation(null, null, 0));
}
@Test
- public void testParseWithFunkyFunctionName() throws ParseException {
+ public void testParseWithFunkyFunctionName() throws Exception {
FunctionSignature f = fun("int", "Bo<{}?>b", "int", "a", "float", "b");
FunctionDefinitionDataType dt = parser.parse(f, "int Bo<{}?>b(int a, int b)");
@@ -108,7 +162,7 @@ public class FunctionSignatureParserTest extends AbstractGhidraHeadedIntegration
}
@Test
- public void testParseWithFunkyParamDataType() throws ParseException {
+ public void testParseWithFunkyParamDataType() throws Exception {
FunctionSignature f = fun("int", "Bob", "int", "a", "Bo<{()", "b");
FunctionDefinitionDataType dt = parser.parse(f, "int Bob(float a, Bo<{() b)");
@@ -116,7 +170,7 @@ public class FunctionSignatureParserTest extends AbstractGhidraHeadedIntegration
}
@Test
- public void testParseWithFunkyParamName() throws ParseException {
+ public void testParseWithFunkyParamName() throws Exception {
FunctionSignature f = fun("int", "Bob", "int", "a()<>@", "int", "b");
FunctionDefinitionDataType dt = parser.parse(f, "int Bob(float a()<>@, int b)");
@@ -124,7 +178,7 @@ public class FunctionSignatureParserTest extends AbstractGhidraHeadedIntegration
}
@Test
- public void testParseWithFunkyReturnType() throws ParseException {
+ public void testParseWithFunkyReturnType() throws Exception {
FunctionSignature f = fun("abc(d", "Bob", "int", "a");
FunctionDefinitionDataType dt = parser.parse(f, "abc(d Bob(int a, float b)");
@@ -132,7 +186,7 @@ public class FunctionSignatureParserTest extends AbstractGhidraHeadedIntegration
}
@Test
- public void testParseWithMultiWordCtypes() throws ParseException {
+ public void testParseWithMultiWordCtypes() throws Exception {
FunctionSignature f = fun("int", "Bob");
FunctionDefinitionDataType dt =
@@ -144,18 +198,20 @@ public class FunctionSignatureParserTest extends AbstractGhidraHeadedIntegration
public void testSpacesNotAllowedInTypedFunctionName() {
FunctionSignature f = fun("int", "Bob", "int", "a");
- FunctionDefinitionDataType dt;
try {
- dt = parser.parse(f, "int bo b(int a, float b)");
+ parser.parse(f, "int bo b(int a, float b)");
fail("parsed name with space");
}
catch (ParseException e) {
assertTrue(e.getMessage().contains("Can't resolve"));
}
+ catch (CancelledException e) {
+ fail("Unexpected cancellation");
+ }
}
@Test
- public void testVarArgs() throws ParseException {
+ public void testVarArgs() throws Exception {
FunctionSignature f = fun("int", "Bob", "int", "a");
FunctionDefinitionDataType dt = parser.parse(f, "int Bob(int a, float b, ...)");
@@ -164,7 +220,7 @@ public class FunctionSignatureParserTest extends AbstractGhidraHeadedIntegration
}
@Test
- public void testNoArgs() throws ParseException {
+ public void testNoArgs() throws Exception {
FunctionSignature f = fun("int", "Bob", "int", "a");
FunctionDefinitionDataType dt = parser.parse(f, "int Bob()");
@@ -172,7 +228,7 @@ public class FunctionSignatureParserTest extends AbstractGhidraHeadedIntegration
}
@Test
- public void testVoidArgs() throws ParseException {
+ public void testVoidArgs() throws Exception {
FunctionSignature f = fun("int", "Bob", "int", "a");
FunctionDefinitionDataType dt = parser.parse(f, "int Bob(void)");
@@ -180,23 +236,139 @@ public class FunctionSignatureParserTest extends AbstractGhidraHeadedIntegration
}
@Test
- public void testNoParamNames() throws ParseException {
+ public void testMultiChoice() throws Exception {
+
+ int txId = program.startTransaction("Add Struct");
+ try {
+ StructureDataType s = new StructureDataType(new CategoryPath("/Test"), "StructA", 0);
+ s.setInternallyAligned(true);
+ s.add(ByteDataType.dataType);
+ program.getDataTypeManager().addDataType(s, null);
+ }
+ finally {
+ program.endTransaction(txId, true);
+ }
+
+ FunctionSignature f = fun("int", "Bob");
+ FunctionDefinitionDataType dt = parser.parse(f, "int Foo(int, float, StructA *)");
+ assertTrue(dt.getReturnType() instanceof IntegerDataType);
+ assertEquals("Foo", dt.getName());
+ ParameterDefinition[] args = dt.getArguments();
+ assertEquals(3, args.length);
+ assertTrue(args[0].getDataType() instanceof IntegerDataType);
+ assertEquals("", args[0].getName());
+ assertTrue(args[1].getDataType() instanceof FloatDataType);
+ assertEquals("", args[1].getName());
+ assertTrue(args[2].getDataType() instanceof Pointer);
+ assertEquals("", args[2].getName());
+ assertTrue("Expected structure choice to be made", dtChoiceCount == 1);
+ }
+
+ @Test
+ public void testTypeCaching() throws Exception {
+ FunctionSignature f = fun("int", "Bob");
+ FunctionDefinitionDataType dt = parser.parse(f, "int Foo(int, StructA, StructA)");
+ assertTrue(dt.getReturnType() instanceof IntegerDataType);
+ assertEquals("Foo", dt.getName());
+ ParameterDefinition[] args = dt.getArguments();
+ assertEquals(3, args.length);
+ assertTrue(args[0].getDataType() instanceof IntegerDataType);
+ assertEquals("", args[0].getName());
+ assertTrue(args[1].getDataType() instanceof Structure);
+ assertEquals("", args[1].getName());
+ assertTrue(args[2].getDataType() instanceof Structure);
+ assertEquals("", args[2].getName());
+ // Only a single call to the DTM service should occur for StructA choice
+ assertFalse("Unexpected datatype choice", dtChoiceCount == 1);
+ assertEquals(args[1].getDataType(), args[1].getDataType());
+ }
+
+ @Test
+ public void testNoParamNames() throws Exception {
+ FunctionSignature f = fun("int", "Bob");
+ FunctionDefinitionDataType dt = parser.parse(f, "int Foo(int, float, StructA)");
+ assertTrue(dt.getReturnType() instanceof IntegerDataType);
+ assertEquals("Foo", dt.getName());
+ ParameterDefinition[] args = dt.getArguments();
+ assertEquals(3, args.length);
+ assertTrue(args[0].getDataType() instanceof IntegerDataType);
+ assertEquals("", args[0].getName());
+ assertTrue(args[1].getDataType() instanceof FloatDataType);
+ assertEquals("", args[1].getName());
+ assertTrue(args[2].getDataType() instanceof Structure);
+ assertEquals("", args[2].getName());
+ assertFalse("Unexpected datatype choice", dtChoiceCount == 1);
+ }
+
+ @Test
+ public void testMultiWordDataTypesWithNoParamNames() throws Exception {
FunctionSignature f = fun("int", "Bob");
- FunctionDefinitionDataType dt = parser.parse(f, "int Bob(int, float)");
+ FunctionDefinitionDataType dt =
+ parser.parse(f, "unsigned long Foo(unsigned long long, signed int, StructA)");
+ assertTrue(dt.getReturnType() instanceof UnsignedLongDataType);
+ assertEquals("Foo", dt.getName());
ParameterDefinition[] args = dt.getArguments();
- assertEquals(2, args.length);
+ assertEquals(3, args.length);
+ assertTrue(args[0].getDataType() instanceof UnsignedLongLongDataType);
assertEquals("", args[0].getName());
+ assertTrue(args[1].getDataType() instanceof IntegerDataType);
assertEquals("", args[1].getName());
+ assertTrue(args[2].getDataType() instanceof Structure);
+ assertEquals("", args[2].getName());
}
@Test
- public void testMultiWordDataTypesWithNoParamNames() throws ParseException {
+ public void testMultiWordModifiedDataTypesWithNoParamNames() throws Exception {
FunctionSignature f = fun("int", "Bob");
- FunctionDefinitionDataType dt = parser.parse(f, "int Bob(unsigned int, float)");
+ FunctionDefinitionDataType dt =
+ parser.parse(f, "unsigned long[3] Foo(unsigned long long *, signed int[3], StructA*)");
+ assertTrue((new ArrayDataType(UnsignedLongDataType.dataType, 3, -1)).isEquivalent(
+ dt.getReturnType()));
+ assertEquals("Foo", dt.getName());
ParameterDefinition[] args = dt.getArguments();
- assertEquals(2, args.length);
+ assertEquals(3, args.length);
+ assertTrue((new PointerDataType(UnsignedLongLongDataType.dataType)).isEquivalent(
+ args[0].getDataType()));
assertEquals("", args[0].getName());
+ assertTrue((new ArrayDataType(IntegerDataType.dataType, 3, -1)).isEquivalent(
+ args[1].getDataType()));
assertEquals("", args[1].getName());
+ assertTrue(args[2].getDataType() instanceof Pointer);
+ assertEquals("", args[2].getName());
+ }
+
+ @Test
+ public void testMultiWordDataTypesWithParamNames() throws Exception {
+ FunctionSignature f = fun("int", "Bob");
+ FunctionDefinitionDataType dt =
+ parser.parse(f, "unsigned long Foo(unsigned long long foo, signed int bar, StructA s)");
+ assertTrue(dt.getReturnType() instanceof UnsignedLongDataType);
+ assertEquals("Foo", dt.getName());
+ ParameterDefinition[] args = dt.getArguments();
+ assertEquals(3, args.length);
+ assertTrue(args[0].getDataType() instanceof UnsignedLongLongDataType);
+ assertEquals("foo", args[0].getName());
+ assertTrue(args[1].getDataType() instanceof IntegerDataType);
+ assertEquals("bar", args[1].getName());
+ assertTrue(args[2].getDataType() instanceof Structure);
+ assertEquals("s", args[2].getName());
+ }
+
+ @Test
+ public void testMultiWordModifiedDataTypesWithParamNames() throws Exception {
+ FunctionSignature f = fun("int", "Bob");
+ FunctionDefinitionDataType dt = parser.parse(f,
+ "unsigned long[3] Bob(unsigned long long *foo, signed int[3] bar, StructA *s)");
+ ParameterDefinition[] args = dt.getArguments();
+ assertEquals(3, args.length);
+ assertTrue((new PointerDataType(UnsignedLongLongDataType.dataType)).isEquivalent(
+ args[0].getDataType()));
+ assertEquals("foo", args[0].getName());
+ assertTrue((new ArrayDataType(IntegerDataType.dataType, 3, -1)).isEquivalent(
+ args[1].getDataType()));
+ assertEquals("bar", args[1].getName());
+ assertTrue(args[2].getDataType() instanceof Pointer);
+ assertEquals("s", args[2].getName());
}
@Test
@@ -209,10 +381,13 @@ public class FunctionSignatureParserTest extends AbstractGhidraHeadedIntegration
catch (ParseException e) {
//expected
}
+ catch (CancelledException e) {
+ fail("Unexpected cancellation");
+ }
}
@Test
- public void testUnsignedLong() throws ParseException {
+ public void testUnsignedLong() throws Exception {
FunctionSignature f = fun("int", "Bob");
FunctionDefinitionDataType dt = parser.parse(f, "int Bob(unsigned long bob, float)");
assertEquals("int Bob(ulong bob, float )", dt.getRepresentation(null, null, 0));
@@ -220,12 +395,26 @@ public class FunctionSignatureParserTest extends AbstractGhidraHeadedIntegration
}
@Test
- public void testPointerNoSpaceBeforeName() throws ParseException {
+ public void testPointerNoSpaceBeforeName() throws Exception {
FunctionSignature f = fun("int", "Bob");
FunctionDefinitionDataType dt = parser.parse(f, "int Bob(char *bob, float)");
assertEquals("int Bob(char * bob, float )", dt.getRepresentation(null, null, 0));
}
+ @Test
+ public void testDoublePointerNoSpaceBeforeName() throws Exception {
+ FunctionSignature f = fun("int", "Bob");
+ FunctionDefinitionDataType dt = parser.parse(f, "int Bob(char **bob, float)");
+ assertEquals("int Bob(char * * bob, float )", dt.getRepresentation(null, null, 0));
+ }
+
+ @Test
+ public void testArrayPointerNoSpaceBeforeName() throws Exception {
+ FunctionSignature f = fun("int", "Bob");
+ FunctionDefinitionDataType dt = parser.parse(f, "int Bob(char[2] *bob, float)");
+ assertEquals("int Bob(char[2] * bob, float )", dt.getRepresentation(null, null, 0));
+ }
+
private DataType createDataType(String name) {
if (name.equals("int")) {
return new IntegerDataType();
diff --git a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/plugin/core/decompile/actions/OverridePrototypeAction.java b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/plugin/core/decompile/actions/OverridePrototypeAction.java
index fd8c12f395..a6644f1859 100644
--- a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/plugin/core/decompile/actions/OverridePrototypeAction.java
+++ b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/plugin/core/decompile/actions/OverridePrototypeAction.java
@@ -15,6 +15,12 @@
*/
package ghidra.app.plugin.core.decompile.actions;
+import java.util.Iterator;
+
+import docking.ActionContext;
+import docking.action.DockingAction;
+import docking.action.MenuData;
+import docking.widgets.OptionDialog;
import ghidra.app.decompiler.*;
import ghidra.app.decompiler.component.DecompilerController;
import ghidra.app.decompiler.component.DecompilerPanel;
@@ -27,13 +33,7 @@ import ghidra.program.model.listing.*;
import ghidra.program.model.pcode.*;
import ghidra.util.Msg;
import ghidra.util.UndefinedFunction;
-
-import java.util.Iterator;
-
-import docking.ActionContext;
-import docking.action.DockingAction;
-import docking.action.MenuData;
-import docking.widgets.OptionDialog;
+import ghidra.util.exception.CancelledException;
public class OverridePrototypeAction extends DockingAction {
private final DecompilerController controller;
@@ -50,7 +50,6 @@ public class OverridePrototypeAction extends DockingAction {
super(tool, "Override Signature", func);
setSignature(signature);
setCallingConvention(conv);
- functionDefinition = null;
}
/**
@@ -60,13 +59,20 @@ public class OverridePrototypeAction extends DockingAction {
@Override
protected void okCallback() {
// only close the dialog if the user made valid changes
- if (testResult())
+ if (parseFunctionDefinition())
close();
}
- protected boolean testResult() {
+ private boolean parseFunctionDefinition() {
- functionDefinition = parseSignature();
+ functionDefinition = null;
+
+ try {
+ functionDefinition = parseSignature();
+ }
+ catch (CancelledException e) {
+ // ignore
+ }
if (functionDefinition == null) {
return false;
@@ -129,12 +135,12 @@ public class OverridePrototypeAction extends DockingAction {
if (calledfunc != null)
varargs = calledfunc.hasVarArgs();
if ((op.getOpcode() == PcodeOp.CALL) && !varargs) {
- if (OptionDialog.showOptionDialog(
- controller.getDecompilerPanel(),
+ if (OptionDialog.showOptionDialog(controller.getDecompilerPanel(),
"Warning : Localized Override",
- "Incorrect information entered here may hide other good information.\n"
- + "For direct calls, it is usually better to alter the prototype on the function\n"
- + "itself, rather than overriding the local call. Proceed anyway?", "Proceed") != 1)
+ "Incorrect information entered here may hide other good information.\n" +
+ "For direct calls, it is usually better to alter the prototype on the function\n" +
+ "itself, rather than overriding the local call. Proceed anyway?",
+ "Proceed") != 1)
return;
}
Address addr = op.getSeqnum().getTarget();