Ghidra is a software reverse engineering (SRE) framework
GP-2070 fixes and tests for the format string analyzer
James86db20d6b3a7
diff --git a/Ghidra/Features/DecompilerDependent/src/main/java/ghidra/app/plugin/core/string/variadic/PcodeFunctionParser.java b/Ghidra/Features/DecompilerDependent/src/main/java/ghidra/app/plugin/core/string/variadic/PcodeFunctionParser.javaindex 14692acecb..9627c60ced 100644--- a/Ghidra/Features/DecompilerDependent/src/main/java/ghidra/app/plugin/core/string/variadic/PcodeFunctionParser.java+++ b/Ghidra/Features/DecompilerDependent/src/main/java/ghidra/app/plugin/core/string/variadic/PcodeFunctionParser.java@@ -17,7 +17,6 @@ package ghidra.app.plugin.core.string.variadic;import java.util.*;-import ghidra.docking.settings.SettingsImpl;import ghidra.program.model.address.Address;import ghidra.program.model.data.*;import ghidra.program.model.listing.*;@@ -33,13 +32,11 @@ import ghidra.program.model.symbol.SourceType;*/public class PcodeFunctionParser {- // All values within the range [32, 126] are ascii readable- private static final int READABLE_ASCII_LOWER_BOUND = 32;- private static final int READABLE_ASCII_UPPER_BOUND = 126;// How many bytes to read from a memory address when initial format- // String cannot be found. This normally only happens for short format- // Strings with lengths less than 5- private static final int BUFFER_LENGTH = 20;+ // String cannot be found. This can happen when the format string+ // is too short or contains escape characters that thwart the+ // ASCII string analyzer+ private static final int NULL_TERMINATOR_PROBE = -1;private static final String CALL_INSTRUCTION = "CALL";private Program program;@@ -150,7 +147,7 @@ public class PcodeFunctionParser {if ((type == null) || !(type instanceof Pointer)) {continue;}- String formatStringCandidate = findFormatString(v.getAddress(), (Pointer) type);+ String formatStringCandidate = findNullTerminatedString(v.getAddress(), (Pointer) type);if (formatStringCandidate == null) {continue;}@@ -175,7 +172,7 @@ public class PcodeFunctionParser {* @param pointer Pointer "type" of string* @return format String*/- private String findFormatString(Address address, Pointer pointer) {+ String findNullTerminatedString(Address address, Pointer pointer) {if (!address.getAddressSpace().isConstantSpace()) {return null;@@ -191,24 +188,14 @@ public class PcodeFunctionParser {//StringDataInstace.getStringDataInstance checks that charType is appropriate//and returns StringDataInstace.NULL_INSTANCE if notStringDataInstance stringDataInstance = StringDataInstance.getStringDataInstance(charType,- memoryBuffer, SettingsImpl.NO_SETTINGS, BUFFER_LENGTH);- String stringValue = stringDataInstance.getStringValue();- if (stringValue == null) {+ memoryBuffer, charType.getDefaultSettings(), NULL_TERMINATOR_PROBE);+ int detectedLength = stringDataInstance.getStringLength();+ if (detectedLength == -1) {return null;}-- String formatStringCandidate = "";- for (int i = 0; i < stringValue.length(); i++) {- if (!isAsciiReadable(stringValue.charAt(i))) {- break;- }- formatStringCandidate += stringValue.charAt(i);- }- return formatStringCandidate;+ stringDataInstance = new StringDataInstance(charType, charType.getDefaultSettings(),+ memoryBuffer, detectedLength, true);+ return stringDataInstance.getStringValue();}- private boolean isAsciiReadable(char c) {-- return c >= READABLE_ASCII_LOWER_BOUND && c <= READABLE_ASCII_UPPER_BOUND;- }}diff --git a/Ghidra/Features/DecompilerDependent/src/test.slow/java/ghidra/app/plugin/core/string/variadic/FormatStringFinderTest.java b/Ghidra/Features/DecompilerDependent/src/test.slow/java/ghidra/app/plugin/core/string/variadic/FormatStringFinderTest.javanew file mode 100644index 0000000000..b3c2b4bf87--- /dev/null+++ b/Ghidra/Features/DecompilerDependent/src/test.slow/java/ghidra/app/plugin/core/string/variadic/FormatStringFinderTest.java@@ -0,0 +1,110 @@+/* ###+ * 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.plugin.core.string.variadic;++import static org.junit.Assert.*;++import org.junit.Test;++import ghidra.program.database.ProgramBuilder;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressFactory;+import ghidra.program.model.data.*;+import ghidra.program.model.listing.Program;+import ghidra.test.AbstractProgramBasedTest;++public class FormatStringFinderTest extends AbstractProgramBasedTest {++ private static final int BASE_ADDRESS = 0x10000;+ private static final int LENGTH = 0x1000;++ private static final byte[] SIMPLE_FORMAT =+ new byte[] { 'l', 'e', 'n', 'g', 't', 'h', ':', ' ', '%', 'd' };++ private static final int SIMPLE_NON_FORMAT_START = 0x10010;+ private static final byte[] SIMPLE_NON_FORMAT = new byte[] { 'h', 'e', 'l', 'l', 'o' };++ private static final int WIDE_CHAR_STRING_START = 0x10020;+ private static final byte[] WIDE_CHAR_STRING = new byte[] { '%', 0, 0, 0, 's', 0, 0, 0 };++ private static final int SHORT_FORMAT_STRING_START = 0x10030;+ private static final int SHORT_NEAR_END_START = BASE_ADDRESS + LENGTH - 4;+ private static final byte[] SHORT_FORMAT_STRING = new byte[] { '%', 'd' };++ private static final int ANSI_COLOR_CODE_STRING_START = 0x10040;+ private static final byte[] ANSI_COLOR_CODE_STRING =+ new byte[] { 'r', 'e', 'p', 'r', 'o', 'd', 'u', 'c', 'e', 's', ' ', 'e', 'r', 'r', 'o', 'r',+ ' ', ':', ' ', '%', 's', '!', '\n', 0x1b, '[', '0', 'm' };++ @Test+ public void testNullTerminatedStringFinder() throws Exception {+ initialize();+ PcodeFunctionParser parser = new PcodeFunctionParser(program);+ AddressFactory addrFactory = program.getAddressFactory();++ Pointer charPointer = program.getDataTypeManager().getPointer(new CharDataType());+ Pointer widePointer = program.getDataTypeManager()+ .getPointer(new WideCharDataType(program.getDataTypeManager()));++ Address base = addrFactory.getConstantAddress(BASE_ADDRESS);+ String simpleFormat = parser.findNullTerminatedString(base, charPointer);+ assertEquals(new String(SIMPLE_FORMAT), simpleFormat);++ Address simpleNonFormatAddr = addrFactory.getConstantAddress(SIMPLE_NON_FORMAT_START);+ String simpleNonFormat = parser.findNullTerminatedString(simpleNonFormatAddr, charPointer);+ assertEquals(new String(SIMPLE_NON_FORMAT), simpleNonFormat);++ Address wideCharStringAddr = addrFactory.getConstantAddress(WIDE_CHAR_STRING_START);+ String wide = parser.findNullTerminatedString(wideCharStringAddr, widePointer);+ assertEquals("%s", wide);++ Address shortAddr = addrFactory.getConstantAddress(SHORT_FORMAT_STRING_START);+ String shortString = parser.findNullTerminatedString(shortAddr, charPointer);+ assertEquals(new String(SHORT_FORMAT_STRING), shortString);++ Address shortNearEndAddr = addrFactory.getConstantAddress(SHORT_NEAR_END_START);+ shortString = parser.findNullTerminatedString(shortNearEndAddr, charPointer);+ assertEquals(new String(SHORT_FORMAT_STRING), shortString);++ Address ansiColorAddr = addrFactory.getConstantAddress(ANSI_COLOR_CODE_STRING_START);+ String ansiColorString = parser.findNullTerminatedString(ansiColorAddr, charPointer);+ assertEquals(new String(ANSI_COLOR_CODE_STRING), ansiColorString);++ }++ @Override+ protected Program getProgram() {+ ProgramBuilder builder = null;+ try {+ builder = new ProgramBuilder("test", ProgramBuilder._X64, "gcc", null);+ builder.createMemory("test", Integer.toHexString(BASE_ADDRESS), LENGTH, "test",+ (byte) 0x0);+ builder.setBytes(Integer.toHexString(BASE_ADDRESS), SIMPLE_FORMAT);+ builder.setBytes(Integer.toHexString(SIMPLE_NON_FORMAT_START), SIMPLE_NON_FORMAT);+ builder.setBytes(Integer.toHexString(WIDE_CHAR_STRING_START), WIDE_CHAR_STRING);+ builder.setBytes(Integer.toHexString(SHORT_FORMAT_STRING_START), SHORT_FORMAT_STRING);+ builder.setBytes(Integer.toHexString(SHORT_NEAR_END_START), SHORT_FORMAT_STRING);+ builder.setBytes(Integer.toHexString(ANSI_COLOR_CODE_STRING_START),+ ANSI_COLOR_CODE_STRING);+ }+ catch (Exception e) {+ fail("Exception creating testing program: " + e.getMessage());+ }++ return builder.getProgram();+ }++}diff --git a/Ghidra/Features/DecompilerDependent/src/test/java/ghidra/app/plugin/core/string/variadic/FormatStringParserTest.java b/Ghidra/Features/DecompilerDependent/src/test/java/ghidra/app/plugin/core/string/variadic/FormatStringParserTest.javaindex a6aceccd47..a2ce29af66 100644--- a/Ghidra/Features/DecompilerDependent/src/test/java/ghidra/app/plugin/core/string/variadic/FormatStringParserTest.java+++ b/Ghidra/Features/DecompilerDependent/src/test/java/ghidra/app/plugin/core/string/variadic/FormatStringParserTest.java@@ -107,9 +107,8 @@ public class FormatStringParserTest extends AbstractGenericTest {{ program.getDataTypeManager().getPointer(new CharDataType()), new LongDataType() };runFormatTest("#thisisatest%+-4.12s%#.1lin\nd2", expectedTypes2, true);- DataType[] expectedTypes3 =- { new PointerDataType(DataType.VOID), new LongDoubleDataType(),- new UnsignedCharDataType() };+ DataType[] expectedTypes3 = { new PointerDataType(DataType.VOID), new LongDoubleDataType(),+ new UnsignedCharDataType() };runFormatTest("%01.3pp%%%#1.2Lg%%%%%hhXxn2", expectedTypes3, true);DataType[] expectedTypes4 = { new IntegerDataType(), new IntegerDataType(),@@ -124,10 +123,10 @@ public class FormatStringParserTest extends AbstractGenericTest {}- // Tests format strings that use astericks to add another int+ // Tests format strings that use asterisks to add another int// argument to determine field width or precision@Test- public void testAsterickFormatString() {+ public void testAsteriskFormatString() {DataType[] expectedTypes1 = { new IntegerDataType(), new IntegerDataType() };runFormatTest("%*d", expectedTypes1, true);@@ -158,9 +157,8 @@ public class FormatStringParserTest extends AbstractGenericTest {DataType[] expectedTypes3 = { new UnsignedShortDataType(), new UnsignedCharDataType() };runFormatTest("%hx %hhu", expectedTypes3, true);- DataType[] expectedTypes4 =- { new UnsignedLongDataType(), new LongLongDataType(), new UnsignedLongLongDataType(),- new PointerDataType(LongLongDataType.dataType) };+ DataType[] expectedTypes4 = { new UnsignedLongDataType(), new LongLongDataType(),+ new UnsignedLongLongDataType(), new PointerDataType(LongLongDataType.dataType) };runFormatTest("%lX %lld %llx %lln", expectedTypes4, true);DataType[] expectedTypes5 =diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/StringDataInstance.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/StringDataInstance.javaindex 7ca9dce920..81a5c43cca 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/StringDataInstance.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/StringDataInstance.java@@ -426,7 +426,7 @@ public class StringDataInstance {* contains our n-bit character which will be tested for null-ness. (not the endian'ness of the* character set name - ie. "UTF-16BE")*- * @return length of the string (NOT including null term if null term probe), in bytes, or -1 if+ * @return length of the string (INCLUDING null term if null term probe), in bytes, or -1 if* no terminator found.*/public int getStringLength() {