Ghidra is a software reverse engineering (SRE) framework
GP-7337 - Function signature parsing of calling convention
dragonmacher5ab9a046b547
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.javaindex 00aae64f51..df7c92064a 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@@ -1041,13 +1041,19 @@ public class FunctionEditorModel {parser.parseWithNamespace(getFunctionSignature(), signatureFieldText);FunctionDefinitionDataType f = result.functionDefinition();- // Preserve calling convention and noreturn flag from current model+ // Preserve no return flag from current modelf.setNoReturn(functionData.hasNoReturn());- try {- f.setCallingConvention(getCallingConventionName());- }- catch (InvalidInputException e) {- // ignore++ // if the parsing did not apply a calling convention, then use the value from the combo box+ String newName = f.getCallingConventionName();+ if (newName == null) {+ try {+ String ccName = getCallingConventionName();+ f.setCallingConvention(ccName);+ }+ catch (InvalidInputException e) {+ // ignore+ }}// We allow the user to omit the namespace when parsing the signature. If the value isdiff --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.javaindex 3d45dfc54e..81470c7900 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@@ -25,6 +25,7 @@ import ghidra.app.util.SymbolPath;import ghidra.app.util.cparser.C.ParseException;import ghidra.program.database.data.DataTypeUtilities;import ghidra.program.model.data.*;+import ghidra.program.model.lang.CompilerSpec;import ghidra.program.model.listing.FunctionSignature;import ghidra.util.data.DataTypeParser;import ghidra.util.data.DataTypeParser.AllowedDataTypes;@@ -67,18 +68,15 @@ public class FunctionSignatureParser {* Constructs a SignatureParser for a program. The destDataTypeManager and/or* service must be specified.*- * @param destDataTypeManager the destination datatype maanger.+ * @param destDataTypeManager the destination datatype manager; cannot be null* @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(DataTypeManager destDataTypeManager,DataTypeQueryService service) {- this.destDataTypeManager = destDataTypeManager;- if (destDataTypeManager == null && service == null) {- throw new IllegalArgumentException(- "Destination DataTypeManager or DataTypeManagerService provider required");- }++ this.destDataTypeManager = Objects.requireNonNull(destDataTypeManager);if (service != null) {dtmService = new ParserDataTypeManagerService(service);}@@ -126,22 +124,36 @@ public class FunctionSignatureParser {FunctionDefinitionDataType function =new FunctionDefinitionDataType(name, destDataTypeManager);+ boolean hasCallingConvention = false;String callingConvention = extractCallingConvention(signatureText);if (callingConvention != null) {- try {- function.setCallingConvention(callingConvention);- }- catch (InvalidInputException e) {- throw new ParseException("Invalid calling convention: " + callingConvention);- }+ doSetCallingConvention(function, callingConvention);+ hasCallingConvention = true;}- function.setReturnType(extractReturnType(signatureText));- function.setArguments(extractArguments(signatureText));- function.setVarArgs(hasVarArgs(signatureText));++ DataType returnType = extractReturnType(signatureText, hasCallingConvention);+ function.setReturnType(returnType);++ ParameterDefinition[] args = extractArguments(signatureText);+ function.setArguments(args);++ boolean hasVarArgs = hasVarArgs(signatureText);+ function.setVarArgs(hasVarArgs);return new FsParseResult(nsPath, function);}+ private void doSetCallingConvention(FunctionDefinitionDataType f, String callingConvention)+ throws ParseException {+ try {+ f.setCallingConvention(callingConvention);+ }+ catch (InvalidInputException e) {+ // should not happen since we validate the calling convention when we extract it+ throw new ParseException("Invalid calling convention: " + callingConvention);+ }+ }+private void initDataTypeMap(FunctionSignature signature) {cacheDataType(signature.getReturnType());for (ParameterDefinition p : signature.getArguments()) {@@ -275,24 +287,26 @@ public class FunctionSignatureParser {return substitute(text, name, replacementName);}- DataType extractReturnType(String signatureText) throws ParseException, CancelledException {+ DataType extractReturnType(String signatureText, boolean hasCallingConvention)+ throws ParseException, CancelledException {+int parenIndex = signatureText.indexOf('(');if (parenIndex < 0) {throw new ParseException("Can't find return type");}- String[] split = StringUtils.split(signatureText.substring(0, parenIndex));- if (split.length < 2) {- throw new ParseException("Can't find return type");- }- int endIndex = split.length - 1;- if (extractCallingConvention(signatureText) != null) {- --endIndex;- }- if (endIndex == 0) {++ String beforeParens = signatureText.substring(0, parenIndex);+ String[] parts = StringUtils.split(beforeParens);+ if (parts.length < 2) {throw new ParseException("Can't find return type");}- String returnTypeName = StringUtils.join(split, " ", 0, endIndex);+ // The function name is the last item. If there is a calling convention, it will just+ // before the function name.+ int len = parts.length;+ int end = hasCallingConvention ? len - 2 : len - 1; // exclusive++ String returnTypeName = StringUtils.join(parts, " ", 0, end);DataType dt = resolveDataType(returnTypeName);if (dt == null) {throw new ParseException("Can't resolve return type: " + returnTypeName);@@ -305,19 +319,21 @@ public class FunctionSignatureParser {if (parenIndex < 0) {throw new ParseException("Can't find calling convention");}- String[] split = StringUtils.split(signatureText.substring(0, parenIndex));- if (split.length < 3) {++ String beforeParens = signatureText.substring(0, parenIndex);+ String[] parts = StringUtils.split(beforeParens);+ if (parts.length < 3) {return null;}- String candidate = split[split.length - 2];- GenericCallingConvention genericConvention =- GenericCallingConvention.getGenericCallingConvention(candidate);- if (genericConvention != GenericCallingConvention.unknown) {- return genericConvention.getDeclarationName();- }- if (destDataTypeManager != null &&- destDataTypeManager.getKnownCallingConventionNames().contains(candidate)) {+ // The function name is the last item. If there is a calling convention, it will be just+ // before the function name.+ String candidate = parts[parts.length - 2];+ Collection<String> dtmCcNames = destDataTypeManager.getKnownCallingConventionNames();+ Set<String> allNames = new HashSet<>(dtmCcNames);+ allNames.add(CompilerSpec.CALLING_CONVENTION_unknown);+ allNames.add(CompilerSpec.CALLING_CONVENTION_default);+ if (allNames.contains(candidate)) {return candidate;}return null;diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/parser/FunctionSignatureParserCallingConventionTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/parser/FunctionSignatureParserCallingConventionTest.javadeleted file mode 100644index 5ef4247763..0000000000--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/parser/FunctionSignatureParserCallingConventionTest.java+++ /dev/null@@ -1,78 +0,0 @@-/* ###- * IP: GHIDRA- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package ghidra.app.util.parser;--import static org.junit.Assert.*;--import java.util.List;--import org.junit.Before;-import org.junit.Test;--import ghidra.program.database.ProgramBuilder;-import ghidra.program.database.ProgramDB;-import ghidra.program.model.data.FunctionDefinitionDataType;-import ghidra.program.model.data.GenericCallingConvention;-import ghidra.test.AbstractGhidraHeadedIntegrationTest;-import ghidra.test.ToyProgramBuilder;--public class FunctionSignatureParserCallingConventionTest- extends AbstractGhidraHeadedIntegrationTest {-- private ProgramDB program;- private FunctionSignatureParser parser;-- @Before- public void setUp() throws Exception {- ProgramBuilder builder = new ToyProgramBuilder("test", false);- program = builder.getProgram();- parser = new FunctionSignatureParser(program.getDataTypeManager(), null);- }-- @Test- public void testParseCdeclPointerSignature() throws Exception {- FunctionDefinitionDataType function =- parser.parse(null, "void * __cdecl test(void * arg0)");-- assertEquals("test", function.getName());- assertEquals("__cdecl", function.getCallingConventionName());- assertEquals("void * __cdecl test(void * arg0)", function.getPrototypeString(true));- }-- @Test- public void testParseGenericCallingConventions() throws Exception {- List<GenericCallingConvention> conventions = List.of(GenericCallingConvention.cdecl,- GenericCallingConvention.stdcall, GenericCallingConvention.fastcall,- GenericCallingConvention.thiscall, GenericCallingConvention.vectorcall);-- for (GenericCallingConvention convention : conventions) {- String declarationName = convention.getDeclarationName();- FunctionDefinitionDataType function =- parser.parse(null, "int " + declarationName + " test(int arg0)");-- assertEquals(declarationName, function.getCallingConventionName());- assertEquals("int " + declarationName + " test(int arg0)",- function.getPrototypeString(true));- }- }-- @Test- public void testParseWithoutCallingConvention() throws Exception {- FunctionDefinitionDataType function = parser.parse(null, "int test(int arg0)");-- assertEquals("int test(int arg0)", function.getPrototypeString());- }-}diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/parser/FunctionSignatureParserTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/parser/FunctionSignatureParserTest.javaindex 2cc7388504..2447158e4a 100644--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/parser/FunctionSignatureParserTest.java+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/parser/FunctionSignatureParserTest.java@@ -27,6 +27,7 @@ import ghidra.app.services.DataTypeManagerService;import ghidra.app.util.cparser.C.ParseException;import ghidra.program.database.ProgramBuilder;import ghidra.program.database.ProgramDB;+import ghidra.program.database.data.ProgramDataTypeManager;import ghidra.program.model.data.*;import ghidra.program.model.listing.FunctionSignature;import ghidra.test.AbstractGhidraHeadedIntegrationTest;@@ -138,8 +139,8 @@ public class FunctionSignatureParserTest extends AbstractGhidraHeadedIntegration@Testpublic void testExtractReturnTypeName() throws Exception {DataType voidDt = BuiltInDataTypeManager.getDataTypeManager().getDataType("/void");- assertEquals(voidDt, parser.extractReturnType("void bob(int a)"));- assertEquals(voidDt, parser.extractReturnType("void bob (int a)"));+ assertEquals(voidDt, parser.extractReturnType("void bob(int a)", false));+ assertEquals(voidDt, parser.extractReturnType("void bob (int a)", false));}@Test@@ -479,6 +480,59 @@ public class FunctionSignatureParserTest extends AbstractGhidraHeadedIntegrationassertEquals("int Bob(char[2] * bob, float )", dt.getRepresentation(null, null, 0));}+ @Test+ public void testParseCdeclPointerSignature() throws Exception {+ FunctionDefinitionDataType function =+ parser.parse(null, "void * __thiscall test(void * arg0)");++ assertEquals("test", function.getName());+ assertEquals("__thiscall", function.getCallingConventionName());+ assertEquals("void * __thiscall test(void * arg0)", function.getPrototypeString(true));+ }++ @Test+ public void testParseGenericCallingConventions() throws Exception {++ ProgramDataTypeManager dtm = program.getDataTypeManager();+ Collection<String> ccNames = dtm.getDefinedCallingConventionNames();+ for (String convension : ccNames) {++ FunctionDefinitionDataType function =+ parser.parse(null, "int " + convension + " test(int arg0)");++ assertEquals(convension, function.getCallingConventionName());+ assertEquals("int " + convension + " test(int arg0)",+ function.getPrototypeString(true));+ }+ }++ @Test+ public void testParseWithoutCallingConvention() throws Exception {+ FunctionDefinitionDataType function = parser.parse(null, "int test(int arg0)");+ assertEquals("int test(int arg0)", function.getPrototypeString());+ }++ @Test+ public void testParseCallingConvention_Default() throws Exception {+ FunctionDefinitionDataType function = parser.parse(null, "int default test(int arg0)");+ assertEquals("int test(int arg0)", function.getPrototypeString());+ }++ @Test+ public void testParseCallingConvention_Unknown() throws Exception {+ FunctionDefinitionDataType function = parser.parse(null, "int unknown test(int arg0)");+ assertEquals("int test(int arg0)", function.getPrototypeString());+ }++ @Test(expected = ParseException.class)+ public void testParseWithInvalidCallingConvention() throws Exception {+ parser.parse(null, "int __bob test(int arg0)");+ }++//=================================================================================================+// Private Methods+//=================================================================================================+private DataType createDataType(String name) {if (name.equals("int")) {return new IntegerDataType();