Ghidra is a software reverse engineering (SRE) framework
GP-1265: Specified DataType.encodeValue/Representation, implemented some primitives and strings.
Dan527c4fcd5823
diff --git a/Ghidra/Features/Base/src/test/java/ghidra/app/plugin/core/datamgr/util/DataTypeUtilsTest.java b/Ghidra/Features/Base/src/test/java/ghidra/app/plugin/core/datamgr/util/DataTypeUtilsTest.javaindex d0dd5a1340..277f2e6e61 100644--- a/Ghidra/Features/Base/src/test/java/ghidra/app/plugin/core/datamgr/util/DataTypeUtilsTest.java+++ b/Ghidra/Features/Base/src/test/java/ghidra/app/plugin/core/datamgr/util/DataTypeUtilsTest.java@@ -23,7 +23,7 @@ import org.junit.Test;import generic.test.AbstractGTest;import ghidra.program.model.data.DataType;import ghidra.program.model.data.DataTypeComparator;-import ghidra.program.model.data.TestDoubleDataType;+import ghidra.program.model.data.StubDataType;import ghidra.util.UniversalIdGenerator;public class DataTypeUtilsTest {@@ -114,7 +114,7 @@ public class DataTypeUtilsTest {AbstractGTest.assertListEqualUnordered(null, expectedMatches, actualMatches);}- private class FakeDataType extends TestDoubleDataType {+ private class FakeDataType extends StubDataType {FakeDataType(String name) {super(name);diff --git a/Ghidra/Features/Base/src/test/java/ghidra/app/util/datatype/DataTypeUrlTest.java b/Ghidra/Features/Base/src/test/java/ghidra/app/util/datatype/DataTypeUrlTest.javaindex 37d9683dfd..41c2eac31a 100644--- a/Ghidra/Features/Base/src/test/java/ghidra/app/util/datatype/DataTypeUrlTest.java+++ b/Ghidra/Features/Base/src/test/java/ghidra/app/util/datatype/DataTypeUrlTest.java@@ -199,7 +199,7 @@ public class DataTypeUrlTest {// Inner Classes//==================================================================================================- private class FakeDataType extends TestDoubleDataType {+ private class FakeDataType extends StubDataType {private DataTypeManager manager = new FakeDataTypeManager();diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/data/DataTypeDB.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/data/DataTypeDB.javaindex 8d2bca488c..d286ca933d 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/data/DataTypeDB.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/data/DataTypeDB.java@@ -17,6 +17,7 @@ package ghidra.program.database.data;import java.io.IOException;import java.net.URL;+import java.nio.ByteBuffer;import java.util.List;import db.DBRecord;@@ -61,29 +62,27 @@ abstract class DataTypeDB extends DatabaseObject implements DataType {}/**- * Subclasses implement this to either read the name from the database record or- * compute if it is a derived name such as a pointer or array. Implementers can- * assume that the database lock will be acquired when this method is called.+ * Subclasses implement this to either read the name from the database record or compute if it+ * is a derived name such as a pointer or array. Implementers can assume that the database lock+ * will be acquired when this method is called.*/protected abstract String doGetName();/**- * Subclasses implement this to read the category path from the database- * record.Implementers can assume that the database lock will be acquired when- * this method is called.+ * Subclasses implement this to read the category path from the database record.Implementers can+ * assume that the database lock will be acquired when this method is called.*/protected abstract long doGetCategoryID();/**- * Subclasses implement this to update the category path ID to the database.- * Implementers can assume that the database lock will be acquired when this- * method is called.+ * Subclasses implement this to update the category path ID to the database. Implementers can+ * assume that the database lock will be acquired when this method is called.*/protected abstract void doSetCategoryPathRecord(long categoryID) throws IOException;/**- * Subclasses implement this to update the to the database. Implementers can- * assume that the database lock will be acquired when this method is called.+ * Subclasses implement this to update the to the database. Implementers can assume that the+ * database lock will be acquired when this method is called.** @param newName new data type name*/@@ -91,16 +90,14 @@ abstract class DataTypeDB extends DatabaseObject implements DataType {throws IOException, InvalidNameException;/**- * Subclasses implement this to read the source archive id from the record.- * Implementers can assume that the database lock will be acquired when this- * method is called.+ * Subclasses implement this to read the source archive id from the record. Implementers can+ * assume that the database lock will be acquired when this method is called.*/protected abstract UniversalID getSourceArchiveID();/**- * Subclasses implement this to update the source archive id from the record.- * Implementers can assume that the database lock will be acquired when this- * method is called.+ * Subclasses implement this to update the source archive id from the record. Implementers can+ * assume that the database lock will be acquired when this method is called.*/protected abstract void setSourceArchiveID(UniversalID id);@@ -149,8 +146,8 @@ abstract class DataTypeDB extends DatabaseObject implements DataType {}/**- * Get the current name without refresh. This is intended to be used for event- * generation when an old-name is needed.+ * Get the current name without refresh. This is intended to be used for event generation when+ * an old-name is needed.** @return old name*/@@ -186,10 +183,10 @@ abstract class DataTypeDB extends DatabaseObject implements DataType {/*** Set the data in the form of the appropriate Object for this DataType.*- * @param buf the data buffer.+ * @param buf the data buffer.* @param settings the display settings for the current value.- * @param length the number of bytes to set the value from.- * @param value the new value to set object+ * @param length the number of bytes to set the value from.+ * @param value the new value to set object*/public void setValue(MemBuffer buf, Settings settings, int length, Object value) {@@ -417,9 +414,9 @@ abstract class DataTypeDB extends DatabaseObject implements DataType {}/**- * Notify all parents that the size of this datatype has changed or- * other significant change that may affect a parent containing this- * datatype.+ * Notify all parents that the size of this datatype has changed or other significant change+ * that may affect a parent containing this datatype.+ ** @param isAutoChange true if changes are in response to another datatype's change.*/protected void notifySizeChanged(boolean isAutoChange) {@@ -431,6 +428,7 @@ abstract class DataTypeDB extends DatabaseObject implements DataType {/*** Notification that this composite data type's alignment has changed.+ ** @param isAutoChange true if changes are in response to another datatype's change.*/protected void notifyAlignmentChanged(boolean isAutoChange) {@@ -515,8 +513,8 @@ abstract class DataTypeDB extends DatabaseObject implements DataType {/*** Sets a String briefly describing this DataType. <br>- * If a data type that extends this class wants to allow the description to be- * changed, then it must override this method.+ * If a data type that extends this class wants to allow the description to be changed, then it+ * must override this method.** @param description a one-liner describing this DataType.*/@@ -526,15 +524,13 @@ abstract class DataTypeDB extends DatabaseObject implements DataType {}/**- * setUniversalID is a package level method that allows you to change a data- * type's universal ID. This is only intended to be used when transforming a- * newly parsed data type archive so that it can be used as a replacement of the- * archive from a previous software release.+ * setUniversalID is a package level method that allows you to change a data type's universal+ * ID. This is only intended to be used when transforming a newly parsed data type archive so+ * that it can be used as a replacement of the archive from a previous software release.*- * @param oldUniversalID the old universal ID value that the user is already- * referencing with their data types. This is the- * universal ID that we want the new data type to be known- * by.+ * @param oldUniversalID the old universal ID value that the user is already referencing with+ * their data types. This is the universal ID that we want the new data type to be+ * known by.*/abstract void setUniversalID(UniversalID oldUniversalID);@@ -557,4 +553,20 @@ abstract class DataTypeDB extends DatabaseObject implements DataType {getName().equals(otherDt.getName()) && isEquivalent(otherDt);}+ @Override+ public boolean isEncodable() {+ return false;+ }++ @Override+ public byte[] encodeValue(Object value, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ throw new DataTypeEncodeException("Encoding not supported", value, this);+ }++ @Override+ public byte[] encodeRepresentation(String repr, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ throw new DataTypeEncodeException("Encoding not supported", repr, this);+ }}diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractDataType.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractDataType.javaindex d7aec5563c..4ec56dfd0f 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractDataType.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractDataType.java@@ -264,4 +264,21 @@ public abstract class AbstractDataType implements DataType {// By default we will do nothing different for offcut valuesreturn getDefaultLabelPrefix(buf, settings, len, options);}++ @Override+ public boolean isEncodable() {+ return false;+ }++ @Override+ public byte[] encodeValue(Object value, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ throw new DataTypeEncodeException("Encoding not supported", value, this);+ }++ @Override+ public byte[] encodeRepresentation(String repr, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ throw new DataTypeEncodeException("Encoding not supported", repr, this);+ }}diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractFloatDataType.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractFloatDataType.javaindex b4197a8fe5..5342dc492b 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractFloatDataType.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractFloatDataType.java@@ -58,7 +58,8 @@ public abstract class AbstractFloatDataType extends BuiltIn {/***- * @see ghidra.program.model.data.DataType#getValue(ghidra.program.model.mem.MemBuffer, ghidra.docking.settings.Settings, int)+ * @see ghidra.program.model.data.DataType#getValue(ghidra.program.model.mem.MemBuffer,+ * ghidra.docking.settings.Settings, int)*/@Overridepublic Object getValue(MemBuffer buf, Settings settings, int length) {@@ -74,6 +75,7 @@ public abstract class AbstractFloatDataType extends BuiltIn {double doubleValue = floatFormat.getHostFloat(value);switch (len) {case 2:+ // TODO: GP-1379return (short) doubleValue;case 4:return (float) doubleValue;@@ -89,6 +91,47 @@ public abstract class AbstractFloatDataType extends BuiltIn {}}+ @Override+ public boolean isEncodable() {+ int length = getLength();+ return length == 4 || length == 8;+ }++ @Override+ public byte[] encodeValue(Object value, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ try {+ int len = getLength();+ if (length != -1 && length != len) {+ throw new DataTypeEncodeException("Length mismatch", value, this);+ }+ FloatFormat floatFormat = FloatFormatFactory.getFloatFormat(len);+ if (len == 8 || len == 4) {+ if (!(value instanceof Number)) {+ throw new DataTypeEncodeException(+ "length-" + len + " float requires Number type", value, this);+ }+ double doubleValue = ((Number) value).doubleValue();+ long encoding = floatFormat.getEncoding(doubleValue);+ return Utils.longToBytes(encoding, len, buf.isBigEndian());+ }+ if (!(value instanceof BigFloat)) {+ // TODO: BigFloat really ought to have a valueOf(double) method, or --+ // TODO: -- or BigFloat really ought to have a valueOf(BigDecimal) method+ throw new DataTypeEncodeException(+ "non-standard float length requires BigFloat type", value, this);+ }+ BigInteger encoding = floatFormat.getEncoding((BigFloat) value);+ return Utils.bigIntegerToBytes(encoding, len, buf.isBigEndian());+ }+ catch (DataTypeEncodeException e) {+ throw e;+ }+ catch (Exception e) {+ throw new DataTypeEncodeException(value, this, e);+ }+ }+/**** @see ghidra.program.model.data.DataType#getRepresentation(MemBuffer, Settings, int)@@ -102,6 +145,30 @@ public abstract class AbstractFloatDataType extends BuiltIn {return obj.toString();}+ @Override+ public byte[] encodeRepresentation(String repr, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ try {+ int len = getLength();+ if (length != -1 && length != len) {+ throw new DataTypeEncodeException("Length mismatch", repr, this);+ }+ if (length == 8 || length == 4) {+ double doubleValue = Double.parseDouble(repr);+ return encodeValue(doubleValue, buf, settings, length);+ }+ // TODO: BigFloat ought to have a parse(String) method, or valueOf(BigDecimal)+ throw new DataTypeEncodeException(+ "Cannot yet parse values of non-standard float length", repr, this);+ }+ catch (DataTypeEncodeException e) {+ throw e;+ }+ catch (Exception e) {+ throw new DataTypeEncodeException(repr, this, e);+ }+ }+/*** @see ghidra.program.model.data.BuiltIn#getBuiltInSettingsDefinitions()*/@@ -140,9 +207,10 @@ public abstract class AbstractFloatDataType extends BuiltIn {/*** Get a Float data-type instance of the requested size+ ** @param size data type size, unsupported sizes will cause an undefined type to be returned.- * @param dtm optional program data-type manager, if specified- * a generic data-type will be returned if possible (i.e., float, double, long double).+ * @param dtm optional program data-type manager, if specified a generic data-type will be+ * returned if possible (i.e., float, double, long double).* @return float data type of specified size*/public static DataType getFloatDataType(int size, DataTypeManager dtm) {@@ -172,8 +240,9 @@ public abstract class AbstractFloatDataType extends BuiltIn {/*** Returns all built-in float data-types- * @param dtm optional program data-type manager, if specified- * generic data-types will be returned in place of fixed-sized data-types.+ *+ * @param dtm optional program data-type manager, if specified generic data-types will be+ * returned in place of fixed-sized data-types.*/public static AbstractFloatDataType[] getFloatDataTypes(DataTypeManager dtm) {TreeMap<Integer, AbstractFloatDataType> floatMap = getFloatTypes();diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractImageBaseOffsetDataType.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractImageBaseOffsetDataType.javaindex ad5994dd34..22d0306068 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractImageBaseOffsetDataType.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractImageBaseOffsetDataType.java@@ -83,6 +83,41 @@ abstract class AbstractImageBaseOffsetDataType extends BuiltIn {return null;}+ @Override+ public boolean isEncodable() {+ return getScalarDataType().isEncodable();+ }++ @Override+ public byte[] encodeValue(Object value, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ if (!(value instanceof Address)) {+ throw new DataTypeEncodeException("Requires Address", value, this);+ }+ Address addressValue = (Address) value;+ Address imageBase = buf.getMemory().getProgram().getImageBase();+ long offset;+ try {+ offset = addressValue.subtract(imageBase);+ }+ catch (IllegalArgumentException e) {+ throw new DataTypeEncodeException(value, this, e);+ }+ Scalar scalarOffset = new Scalar(imageBase.getSize(), offset, false);+ DataType dt = getScalarDataType();+ return dt.encodeValue(scalarOffset, buf, settings, length);+ }++ @Override+ public byte[] encodeRepresentation(String repr, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ Address address = buf.getMemory().getProgram().getAddressFactory().getAddress(repr);+ if (address == null) {+ throw new DataTypeEncodeException("Cannot parse address", repr, this);+ }+ return encodeValue(address, buf, settings, length);+ }+@Overridepublic Class<?> getValueClass(Settings settings) {return Address.class;diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractIntegerDataType.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractIntegerDataType.javaindex 26b514dc40..a1fcbe3cfc 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractIntegerDataType.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractIntegerDataType.java@@ -16,20 +16,24 @@package ghidra.program.model.data;import java.math.BigInteger;+import java.nio.charset.MalformedInputException;+import java.nio.charset.UnmappableCharacterException;import ghidra.docking.settings.*;+import ghidra.pcode.utils.Utils;+import ghidra.program.model.data.StringRenderParser.StringParseException;import ghidra.program.model.mem.MemBuffer;import ghidra.program.model.scalar.Scalar;import ghidra.util.StringFormat;import utilities.util.ArrayUtilities;/**- * Base type for integer data types such as {@link CharDataType chars}, {@link IntegerDataType ints},- * and {@link LongDataType longs}.+ * Base type for integer data types such as {@link CharDataType chars}, {@link IntegerDataType+ * ints}, and {@link LongDataType longs}.* <p>* If {@link FormatSettingsDefinition#getFormat(Settings)} indicates that this is a- * {@link FormatSettingsDefinition#CHAR CHAR} type, the {@link ArrayStringable} methods will- * treat an array of this data type as a string.+ * {@link FormatSettingsDefinition#CHAR CHAR} type, the {@link ArrayStringable} methods will treat+ * an array of this data type as a string.*/public abstract class AbstractIntegerDataType extends BuiltIn implements ArrayStringable {@@ -56,6 +60,7 @@ public abstract class AbstractIntegerDataType extends BuiltIn implements ArraySt/*** Constructor+ ** @param name a unique signed/unsigned data-type name (also used as the mnemonic)* @param signed true if signed, false if unsigned* @param dtm data-type manager whose data organization should be used@@ -66,11 +71,10 @@ public abstract class AbstractIntegerDataType extends BuiltIn implements ArraySt}/**- * Return the Format settings definition included in the settings- * definition array+ * Return the Format settings definition included in the settings definition array+ ** @see #getSettingsDefinitions()- * @return Format settings definition included in the settings- * definition array+ * @return Format settings definition included in the settings definition array*/protected FormatSettingsDefinition getFormatSettingsDefinition() {return FormatSettingsDefinition.DEF_HEX;@@ -106,17 +110,15 @@ public abstract class AbstractIntegerDataType extends BuiltIn implements ArraySt}/**- * @return the Assembly style data-type declaration- * for this data-type.+ * @return the Assembly style data-type declaration for this data-type.*/public String getAssemblyMnemonic() {return name;}/**- * @return the C style data-type mnemonic- * for this data-type.- * NOTE: currently the same as getCDeclaration().+ * @return the C style data-type mnemonic for this data-type. NOTE: currently the same as+ * getCDeclaration().*/public String getCMnemonic() {String str = getCDeclaration();@@ -124,9 +126,8 @@ public abstract class AbstractIntegerDataType extends BuiltIn implements ArraySt}/**- * @return the C style data-type declaration- * for this data-type. Null is returned if- * no appropriate declaration exists.+ * @return the C style data-type declaration for this data-type. Null is returned if no+ * appropriate declaration exists.*/public String getCDeclaration() {int size = getLength();@@ -187,6 +188,42 @@ public abstract class AbstractIntegerDataType extends BuiltIn implements ArrayStreturn new Scalar(size * 8, val, isSigned());}+ protected BigInteger castValueToEncode(Object value) throws DataTypeEncodeException {+ if (value instanceof BigInteger) {+ return (BigInteger) value;+ }+ if (value instanceof Scalar) {+ return ((Scalar) value).getBigInteger();+ }+ if (value instanceof Byte || value instanceof Short || value instanceof Character ||+ value instanceof Integer || value instanceof Long) {+ return BigInteger.valueOf(((Number) value).longValue());+ }+ throw new DataTypeEncodeException("Unsupported value type", value, this);+ }++ @Override+ public boolean isEncodable() {+ return true;+ }++ @Override+ public byte[] encodeValue(Object value, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ if (length == -1) {+ length = getLength();+ }+ if (length != getLength()) {+ throw new DataTypeEncodeException("Length mismatch", value, this);+ }+ BigInteger bigValue = castValueToEncode(value);+ byte[] encoding = Utils.bigIntegerToBytes(bigValue, length, isSigned());+ if (!ENDIAN.isBigEndian(settings, buf)) {+ ArrayUtilities.reverse(encoding);+ }+ return encoding;+ }+@Overridepublic Class<?> getValueClass(Settings settings) {if (getLength() > 8) {@@ -227,7 +264,8 @@ public abstract class AbstractIntegerDataType extends BuiltIn implements ArraySt/*** Get integer representation of the big-endian value.* <p>- * Does not handle CHAR format, use {@link StringDataInstance#getCharRepresentation(DataType, byte[], Settings)}+ * Does not handle CHAR format, use+ * {@link StringDataInstance#getCharRepresentation(DataType, byte[], Settings)}** @param bigInt BigInteger value with the appropriate sign* @param settings integer format settings (PADDING, FORMAT, etc.)@@ -274,6 +312,53 @@ public abstract class AbstractIntegerDataType extends BuiltIn implements ArrayStreturn valStr;}+ @Override+ public byte[] encodeRepresentation(String repr, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ int format = getFormatSettingsDefinition().getFormat(settings);+ BigInteger value;+ int radix;+ String suffix;+ switch (format) {+ case FormatSettingsDefinition.CHAR:+ StringDataInstance sdi =+ StringDataInstance.getStringDataInstance(this, buf, settings, getLength());+ try {+ return sdi.encodeReplacementFromCharRepresentation(repr);+ }+ catch (MalformedInputException | UnmappableCharacterException+ | StringParseException e) {+ throw new DataTypeEncodeException(repr, this, e);+ }+ case FormatSettingsDefinition.HEX:+ radix = 16;+ suffix = "h";+ break;+ case FormatSettingsDefinition.DECIMAL:+ radix = 10;+ suffix = "";+ case FormatSettingsDefinition.BINARY:+ radix = 2;+ suffix = "b";+ case FormatSettingsDefinition.OCTAL:+ radix = 8;+ suffix = "o";+ default:+ throw new AssertionError();+ }++ if (!repr.endsWith(suffix)) {+ throw new DataTypeEncodeException("value must have " + suffix + " suffix", repr, this);+ }+ try {+ value = new BigInteger(repr.substring(0, repr.length() - suffix.length()), radix);+ }+ catch (Exception e) {+ throw new DataTypeEncodeException(repr, this, e);+ }+ return encodeValue(value, buf, settings, length);+ }+@Overridepublic boolean hasStringValue(Settings settings) {int format = getFormatSettingsDefinition().getFormat(settings);@@ -305,9 +390,8 @@ public abstract class AbstractIntegerDataType extends BuiltIn implements ArraySt}/**- * @return the data-type with the opposite signedness from- * this data-type. For example, this method on IntegerDataType will- * return an instance of UnsignedIntegerDataType.+ * @return the data-type with the opposite signedness from this data-type. For example, this+ * method on IntegerDataType will return an instance of UnsignedIntegerDataType.*/public abstract AbstractIntegerDataType getOppositeSignednessDataType();@@ -320,9 +404,9 @@ public abstract class AbstractIntegerDataType extends BuiltIn implements ArrayStprivate static AbstractIntegerDataType[] unsignedTypes;/**- * An "map" of the first 8 (by size) signed integer data types, where- * the element at index <code>i</code> points to the datatype of size <code>i+1</code>,- * with additional types with no size restriction appended after the first 8.+ * An "map" of the first 8 (by size) signed integer data types, where the element at index+ * <code>i</code> points to the datatype of size <code>i+1</code>, with additional types with no+ * size restriction appended after the first 8.** @return array of all signed integer types (char and bool types excluded)*/@@ -338,9 +422,9 @@ public abstract class AbstractIntegerDataType extends BuiltIn implements ArraySt}/**- * An "map" of the first 8 (by size) unsigned integer data types, where- * the element at index <code>i</code> points to the datatype of size <code>i+1</code>,- * with additional types with no size restriction appended after the first 8.+ * An "map" of the first 8 (by size) unsigned integer data types, where the element at index+ * <code>i</code> points to the datatype of size <code>i+1</code>, with additional types with no+ * size restriction appended after the first 8.** @return array of all unsigned integer types (char and bool types excluded)*/@@ -357,10 +441,11 @@ public abstract class AbstractIntegerDataType extends BuiltIn implements ArraySt/*** Get a Signed Integer data-type instance of the requested size- * @param size data type size, sizes greater than 8 (and other than 16)- * will cause an SignedByteDataType[size] (i.e., Array) to be returned.- * @param dtm optional program data-type manager, if specified- * a generic data-type will be returned if possible.+ *+ * @param size data type size, sizes greater than 8 (and other than 16) will cause an+ * SignedByteDataType[size] (i.e., Array) to be returned.+ * @param dtm optional program data-type manager, if specified a generic data-type will be+ * returned if possible.* @return signed integer data type*/public static DataType getSignedDataType(int size, DataTypeManager dtm) {@@ -395,8 +480,9 @@ public abstract class AbstractIntegerDataType extends BuiltIn implements ArraySt/*** Returns all built-in signed integer data-types.- * @param dtm optional program data-type manager, if specified- * generic data-types will be returned in place of fixed-sized data-types.+ *+ * @param dtm optional program data-type manager, if specified generic data-types will be+ * returned in place of fixed-sized data-types.* @return array of all signed integer types (char and bool types excluded)*/public static AbstractIntegerDataType[] getSignedDataTypes(DataTypeManager dtm) {@@ -427,10 +513,11 @@ public abstract class AbstractIntegerDataType extends BuiltIn implements ArraySt/*** Get a Unsigned Integer data-type instance of the requested size- * @param size data type size, sizes greater than 8 (and other than 16)- * will cause an undefined type to be returned.- * @param dtm optional program data-type manager, if specified- * a generic data-type will be returned if possible.+ *+ * @param size data type size, sizes greater than 8 (and other than 16) will cause an undefined+ * type to be returned.+ * @param dtm optional program data-type manager, if specified a generic data-type will be+ * returned if possible.* @return unsigned integer data type*/public static DataType getUnsignedDataType(int size, DataTypeManager dtm) {@@ -465,8 +552,9 @@ public abstract class AbstractIntegerDataType extends BuiltIn implements ArraySt/*** Returns all built-in unsigned integer data-types- * @param dtm optional program data-type manager, if specified- * generic data-types will be returned in place of fixed-sized data-types.+ *+ * @param dtm optional program data-type manager, if specified generic data-types will be+ * returned in place of fixed-sized data-types.* @return array of all unsigned integer types (char and bool types excluded)*/public static AbstractIntegerDataType[] getUnsignedDataTypes(DataTypeManager dtm) {diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractStringDataType.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractStringDataType.javaindex b18ea48e80..b342476e73 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractStringDataType.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/AbstractStringDataType.java@@ -15,9 +15,11 @@*/package ghidra.program.model.data;-import static ghidra.program.model.data.CharsetSettingsDefinition.*;-import static ghidra.program.model.data.RenderUnicodeSettingsDefinition.*;-import static ghidra.program.model.data.TranslationSettingsDefinition.*;+import static ghidra.program.model.data.CharsetSettingsDefinition.CHARSET;+import static ghidra.program.model.data.RenderUnicodeSettingsDefinition.RENDER;+import static ghidra.program.model.data.TranslationSettingsDefinition.TRANSLATION;++import java.nio.charset.CoderResult;import ghidra.docking.settings.*;import ghidra.program.model.mem.MemBuffer;@@ -28,8 +30,9 @@ import ghidra.program.model.mem.MemBuffer;* See {@link StringDataType} for information about string variations and configuration details.* <p>* Sub-classes generally only need to implement a constructor that calls the mega-constructor- * {@link #AbstractStringDataType(String, String, String, String, String, String, String, DataType, StringLayoutEnum, DataTypeManager) AbstractStringDataType.AbstractStringDataType(lots,of,params)}- * and the {@link DataType#clone(DataTypeManager) } method.+ * {@link #AbstractStringDataType(String, String, String, String, String, String, String, DataType, StringLayoutEnum, DataTypeManager)+ * AbstractStringDataType.AbstractStringDataType(lots,of,params)} and the+ * {@link DataType#clone(DataTypeManager) } method.* <p>**/@@ -56,8 +59,8 @@ abstract public class AbstractStringDataType extends BuiltIn/*** The name of the character set used to convert bytes into java native Strings.* <p>- * If null, the {@link CharsetSettingsDefinition settings} attached to the data- * instance will be queried for a charset, which will default to ASCII if not present.+ * If null, the {@link CharsetSettingsDefinition settings} attached to the data instance will be+ * queried for a charset, which will default to ASCII if not present.*/private final String charsetName;/**@@ -83,8 +86,8 @@ abstract public class AbstractStringDataType extends BuiltInprivate final StringLayoutEnum stringLayout;/**- * String used as a prefix to the data instance location when creating a label when- * there is a problem accessing the string data.+ * String used as a prefix to the data instance location when creating a label when there is a+ * problem accessing the string data.* <p>* Example: "STRING" produces something like: "STRING_00410ea0"* <p>@@ -111,17 +114,20 @@ abstract public class AbstractStringDataType extends BuiltIn/*** Protected constructor used by derived types to provide all their datatype details.* <p>+ ** @param name Name of this datatype* @param mnemonic Mnemonic of this datatype- * @param defaultLabel Label string for this datatype. See {@link #defaultLabel}.- * @param defaultLabelPrefix Label prefix string for this datatype. See {@link #defaultLabelPrefix}.- * @param defaultAbbrevLabelPrefix Abbreviated label prefix for this datatype. See {@link #defaultAbbrevLabelPrefix}.+ * @param defaultLabel Label string for this datatype. See {@link #defaultLabel}.+ * @param defaultLabelPrefix Label prefix string for this datatype. See+ * {@link #defaultLabelPrefix}.+ * @param defaultAbbrevLabelPrefix Abbreviated label prefix for this datatype. See+ * {@link #defaultAbbrevLabelPrefix}.* @param description Description of this datatype.- * @param charsetName Charset name for this string datatype. If null the- * settings of the data instance will be queried for a {@link CharsetSettingsDefinition charset}.+ * @param charsetName Charset name for this string datatype. If null the settings of the data+ * instance will be queried for a {@link CharsetSettingsDefinition charset}.* @param replacementDataType Replacement {@link DataType}.- * @param stringLayout {@link StringLayoutEnum stringLayout} controls how the string is laid- * out in memory.+ * @param stringLayout {@link StringLayoutEnum stringLayout} controls how the string is laid out+ * in memory.* @param dtm {@link DataTypeManager} for this datatype, null ok.*/protected AbstractStringDataType(String name, String mnemonic, String defaultLabel,@@ -170,6 +176,7 @@ abstract public class AbstractStringDataType extends BuiltIn* Creates a new {@link StringDataInstance} using the bytes in the supplied MemBuffer and* options provided by this DataType.* <p>+ ** @param buf the data.* @param settings the settings to use for the representation.* @param length the number of bytes to represent.@@ -217,16 +224,48 @@ abstract public class AbstractStringDataType extends BuiltInreturn String.class;}+ @Override+ public boolean isEncodable() {+ return true;+ }+@Overridepublic Object getValue(MemBuffer buf, Settings settings, int length) {return getStringDataInstance(buf, settings, length).getStringValue();}+ @Override+ public byte[] encodeValue(Object value, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ if (!(value instanceof CharSequence)) {+ throw new DataTypeEncodeException("Requires CharSequence", value, this);+ }+ try {+ StringDataInstance sdi = getStringDataInstance(buf, settings, length);+ return sdi.encodeReplacementFromStringValue((CharSequence) value);+ }+ catch (Exception e) {+ throw new DataTypeEncodeException(value, this, e);+ }+ }+@Overridepublic String getRepresentation(MemBuffer buf, Settings settings, int length) {return getStringDataInstance(buf, settings, length).getStringRepresentation();}+ @Override+ public byte[] encodeRepresentation(String repr, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ try {+ StringDataInstance sdi = getStringDataInstance(buf, settings, length);+ return sdi.encodeReplacementFromStringRepresentation(repr);+ }+ catch (Throwable e) {+ throw new DataTypeEncodeException(repr, this, e);+ }+ }+@Overridepublic String getDefaultLabelPrefix(MemBuffer buf, Settings settings, int len,DataTypeDisplayOptions options) {diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/CharDataType.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/CharDataType.javaindex 721ba03f75..d6c754320d 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/CharDataType.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/CharDataType.java@@ -22,9 +22,8 @@ import ghidra.util.StringFormat;import ghidra.util.classfinder.ClassTranslator;/**- * Provides a definition of an primitive char in a program.- * The size and signed-ness of this type is determined by the data- * organization of the associated data type manager.+ * Provides a definition of an primitive char in a program. The size and signed-ness of this type is+ * determined by the data organization of the associated data type manager.*/public class CharDataType extends AbstractIntegerDataType implements DataTypeWithCharset {private final static long serialVersionUID = 1;@@ -84,9 +83,8 @@ public class CharDataType extends AbstractIntegerDataType implements DataTypeWit}/**- * Returns the C style data-type declaration- * for this data-type. Null is returned if- * no appropriate declaration exists.+ * Returns the C style data-type declaration for this data-type. Null is returned if no+ * appropriate declaration exists.*/@Overridepublic String getCDeclaration() {@@ -132,6 +130,23 @@ public class CharDataType extends AbstractIntegerDataType implements DataTypeWit}}+ @Override+ public boolean isEncodable() {+ return true;+ }++ @Override+ public byte[] encodeValue(Object value, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ return encodeCharacterValue(value, buf, settings);+ }++ @Override+ public byte[] encodeRepresentation(String repr, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ return encodeCharacterRepresentation(repr, buf, settings);+ }+@Overridepublic Class<?> getValueClass(Settings settings) {return Character.class;diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataType.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataType.javaindex d8f49d8102..e80f3ff2ca 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataType.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataType.java@@ -25,14 +25,14 @@ import ghidra.util.UniversalID;import ghidra.util.exception.DuplicateNameException;/**- * The interface that all data types must implement.+ * The interface that all datatypes must implement.*/public interface DataType {/**- * WARNING: do not add <code>default</code> method implementations to this interface.- * Doing so intereferes with correct initialization of the static instance variables- * {@link #DEFAULT} and {@link #VOID} below.+ * WARNING: do not add <code>default</code> method implementations to this interface. Doing so+ * intereferes with correct initialization of the static instance variables {@link #DEFAULT} and+ * {@link #VOID} below.*//**@@ -42,8 +42,10 @@ public interface DataType {/*** Instance of void datatype (never use <code>==</code>)+ ** @deprecated should use {@link VoidDataType#dataType} instead*/+ @Deprecatedpublic static final DataType VOID = VoidDataType.dataType;public final static String CONFLICT_SUFFIX = ".conflict";@@ -52,145 +54,172 @@ public interface DataType {static final long NO_LAST_CHANGE_TIME = 0L;/**- * Indicates if the length of this data-type is determined based- * upon the {@link DataOrganization} obtained from the associated {@link DataTypeManager}.+ * Indicates if the length of this data-type is determined based upon the+ * {@link DataOrganization} obtained from the associated {@link DataTypeManager}.+ ** @return true length is language/compiler-specification dependent, else false*/public boolean hasLanguageDependantLength();/**- * Gets a list of all the settingsDefinitions used by this data type.- * @return a list of the settingsDefinitions used by this data type.+ * Gets a list of all the settingsDefinitions used by this datatype.+ *+ * @return a list of the settingsDefinitions used by this datatype.*/public SettingsDefinition[] getSettingsDefinitions();/**- * Gets the default settings for this data type.- * @return the default settings for this dataType.+ * Gets the default settings for this datatype.+ *+ * @return the default settings for this datatype.*/public Settings getDefaultSettings();/**- * Returns an instance of this DataType with its universalID and SourceArchive identity retained.- * The current instanceof will be returned if this datatype's DataTypeManager matches- * the specified dtm. The recursion depth of a clone will stop on any datatype whose- * DataTypeManager matches the specified dtm and simply use the existing datatype instance.+ * Returns an instance of this DataType with its universalID and SourceArchive identity+ * retained.+ * <p>+ * The current instanceof will be returned if this datatype's DataTypeManager matches the+ * specified dtm. The recursion depth of a clone will stop on any datatype whose DataTypeManager+ * matches the specified dtm and simply use the existing datatype instance.+ ** @param dtm the data-type manager instance whose data-organization should apply.* @return cloned instance which may be the same as this instance*/public DataType clone(DataTypeManager dtm);/**- * Returns a new instance (shallow copy) of this DataType with a new identity.+ * Returns a new instance (shallow copy) of this DataType with a new identity.+ * <p>* Any reference to other datatypes will use {@link #clone(DataTypeManager)}.+ ** @param dtm the data-type manager instance whose data-organization should apply.* @return new instanceof of this datatype*/public DataType copy(DataTypeManager dtm);/**- * Gets the categoryPath associated with this data type+ * Gets the categoryPath associated with this datatype+ ** @return the datatype's category path*/public CategoryPath getCategoryPath();- /**- * Returns the dataTypePath for this dataType;- * @return the dataTypePath for this dataType;+ /**+ * Returns the dataTypePath for this datatype;+ *+ * @return the dataTypePath for this datatype;*/public DataTypePath getDataTypePath();/**- * @param path set the categoryPath associated with this data type- * @throws DuplicateNameException if an attempt to place this datatype into the- * specified category resulted in a name collision. This should not occur for non-DB- * DataType instances.+ * Set the categoryPath associated with this datatype+ *+ * @param path the new path+ * @throws DuplicateNameException if an attempt to place this datatype into the specified+ * category resulted in a name collision. This should not occur for non-DB DataType+ * instances.*/public void setCategoryPath(CategoryPath path) throws DuplicateNameException;/**- * @return the DataTypeManager that is associated with this dataType.- * This association should not be used to indicate whether this DataType has been- * resolved, but is intended to indicate whether the appropriate DataOrganization- * is being used.+ * Get the DataTypeManager containing this datatype.+ * <p>+ * This association should not be used to indicate whether this DataType has been resolved, but+ * is intended to indicate whether the appropriate DataOrganization is being used.+ *+ * @return the DataTypeManager that is associated with this datatype.*/public DataTypeManager getDataTypeManager();/**- * Gets the name for referring to this data type.+ * Gets the name for referring to this datatype.+ ** @return generic name for this Data Type (i.e.: Word)*/public String getDisplayName();/**- * @return the name of this data type+ * Get the name of this datatype.+ *+ * @return the name*/public String getName();/**- * @return the full category path name that includes this dataType's name. If- * the category is null, then this just the dataType's name is returned.+ * Get the full category path name that includes this datatype's name.+ * <p>+ * If the category is null, then this just the datatype's name is returned.+ *+ * @return the path, or just this type's name*/public String getPathName();/**- * Sets the name of the dataType- * @param name the new name for this dataType.+ * Sets the name of the datatype+ *+ * @param name the new name for this datatype.* @throws InvalidNameException if the given name does not form a valid name.- * @throws DuplicateNameException if name change on stored {@link DataType}- * is a duplicate of another datatype within the same category (only applies to- * DB stored {@link DataType}).+ * @throws DuplicateNameException if name change on stored {@link DataType} is a duplicate of+ * another datatype within the same category (only applies to DB stored+ * {@link DataType}).*/public void setName(String name) throws InvalidNameException, DuplicateNameException;/**- * Sets the name and category of a dataType at the same time.+ * Sets the name and category of a datatype at the same time.+ ** @param path the new category path.* @param name the new name* @throws InvalidNameException if the name is invalid- * @throws DuplicateNameException if name change on stored {@link DataType}- * is a duplicate of another datatype within the same category (only applies to- * DB stored {@link DataType}).+ * @throws DuplicateNameException if name change on stored {@link DataType} is a duplicate of+ * another datatype within the same category (only applies to DB stored+ * {@link DataType}).*/public void setNameAndCategory(CategoryPath path, String name)throws InvalidNameException, DuplicateNameException;/*** Get the mnemonic for this DataType.+ ** @param settings settings which may influence the result or null* @return the mnemonic for this DataType.*/public String getMnemonic(Settings settings);/**- * Get the length (number of 8-bit bytes) of this DataType.- * <p>P- * NOTE: No datatype should ever return 0, even if {@link #isZeroLength()}, and only- * {@link Dynamic} datatypes should return -1. If {@link #isZeroLength()} is true a length of 1- * should be returned. Where a zero-length datatype can be handled (e.g., {@link Composite})- * the {@link #isZeroLength()} method should be used.+ * Get the length (number of 8-bit bytes) of this DataType.+ * <p>+ * NOTE: No datatype should ever return 0, even if {@link #isZeroLength()}, and only+ * {@link Dynamic} datatypes should return -1. If {@link #isZeroLength()} is true a length of 1+ * should be returned. Where a zero-length datatype can be handled (e.g., {@link Composite}) the+ * {@link #isZeroLength()} method should be used.+ ** @return the length of this DataType*/public int getLength();/*** Indicates this datatype is defined with a zero length.- * This method should not be confused with {@link #isNotYetDefined()}- * which indicates that nothing but the name and basic type is known.- * NOTE: a zero-length datatype must return a length of 1- * via {@link #getLength()}. Zero-length datatypes used as a- * component within a {@link Composite} may, or may not, be assigned- * a component length of 0. The method {@link DataTypeComponent#usesZeroLengthComponent(DataType)}+ * <p>+ * This method should not be confused with {@link #isNotYetDefined()} which indicates that+ * nothing but the name and basic type is known.+ * <p>+ * NOTE: a zero-length datatype must return a length of 1 via {@link #getLength()}. Zero-length+ * datatypes used as a component within a {@link Composite} may, or may not, be assigned a+ * component length of 0. The method {@link DataTypeComponent#usesZeroLengthComponent(DataType)}* is used to make this determination.+ ** @return true if type definition has a length of 0, else false*/public boolean isZeroLength();/*** Indicates if this datatype has not yet been fully defined.- * Such datatypes should always return a {@link #getLength()} of 1 and- * true for {@link #isZeroLength()}.- * (example: empty structure)+ * <p>+ * Such datatypes should always return a {@link #getLength()} of 1 and true for+ * {@link #isZeroLength()}. (example: empty structure)+ ** @return true if this type is not yet defined.*/public boolean isNotYetDefined();@@ -204,29 +233,29 @@ public interface DataType {/*** Sets a String briefly describing this DataType.+ ** @param description a one-liner describing this DataType.- * @throws UnsupportedOperationException if the description is not allowed to be set for this data type.+ * @throws UnsupportedOperationException if the description is not allowed to be set for this+ * datatype.*/public void setDescription(String description) throws UnsupportedOperationException;/**- * The getDocs method should provide a URL pointing to extended- * documentation for this DataType if it exists. A typical- * use would be to return a URL pointing to the programmers- * reference for this instruction or a page describing this- * data structure.+ * The getDocs method should provide a URL pointing to extended documentation for this DataType+ * if it exists.+ * <p>+ * A typical use would be to return a URL pointing to the programmers reference for this+ * instruction or a page describing this data structure.** @return null - there is no URL documentation for this prototype.*/public URL getDocs();/**- * Get the data in the form of the appropriate Object for- * this DataType.- *- * For instance if the data type is an AddressDT, return an Address object.- * a Byte, return a Scalar* (maybe this should be a Byte)- * a Float, return a Float+ * Get the data in the form of the appropriate Object for this DataType.+ * <p>+ * For instance if the datatype is an AddressDT, return an Address object. a Byte, return a+ * Scalar* (maybe this should be a Byte) a Float, return a Float** @param buf the data buffer.* @param settings the settings to use.@@ -236,32 +265,70 @@ public interface DataType {public Object getValue(MemBuffer buf, Settings settings, int length);/**- * Get the Class of the value to be returned by this data type.+ * Check if this type supports encoding (patching)+ * <p>+ * If unsupported, {@link #encodeValue(Object, MemBuffer, Settings, int)} and+ * {@link #encodeRepresentation(String, MemBuffer, Settings, int)} will always throw an+ * exception. Actions which rely on either {@code encode} method should not be displayed if the+ * applicable datatype is not encodable.+ *+ * @return true if encoding is supported+ */+ public boolean isEncodable();++ /**+ * Encode bytes from an Object appropriate for this DataType.+ * <p>+ * Converts the given object to the byte encoding and returns it. When appropriate, this should+ * seek the nearest encoding to the specified value, since the object may come from a user+ * script. For example, a floating-point value may be rounded. Invalid values should be rejected+ * with a {@link DataTypeEncodeException}.+ *+ * @param value the desired value.+ * @param buf a buffer representing the eventual destination of the bytes.+ * @param settings the settings to use.+ * @param length the expected length of the result, usually the length of the data unit, or -1+ * to let the type choose the length. It may be ignored, e.g., for fixed-length+ * types.+ * @return the encoded value.+ * @throws DataTypeEncodeException if the value cannot be encoded for any reason, e.g.,+ * incorrect type, not enough space, buffer overflow, unsupported (see+ * {@link #isEncodable()}).+ */+ public byte[] encodeValue(Object value, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException;++ /**+ * Get the Class of the value to be returned by this datatype.+ ** @param settings the relevant settings to use or null for default.- * @return Class of the value to be returned by this data type or null if it can vary- * or is unspecified. Types which correspond to a string or char array will- * return the String class.+ * @return Class of the value to be returned by this datatype or null if it can vary or is+ * unspecified. Types which correspond to a string or char array will return the String+ * class.*/public Class<?> getValueClass(Settings settings);/*** Returns the appropriate string to use as the default label prefix in the absence of any data.+ ** @return the default label prefix or null if none specified.*/public String getDefaultLabelPrefix();/**- * Returns the prefix to use for this datatype when an abbreviated prefix is desired. For- * example, some data types will built a large default label, at which is is more desirable to- * have a shortened prefix.+ * Returns the prefix to use for this datatype when an abbreviated prefix is desired.+ * <p>+ * For example, some datatypes will built a large default label, at which is is more desirable+ * to have a shortened prefix.*- * @return the prefix to use for this datatype when an abbreviated prefix is desired. May- * return null.+ * @return the prefix to use for this datatype when an abbreviated prefix is desired. May return+ * null.*/public String getDefaultAbbreviatedLabelPrefix();/*** Returns the appropriate string to use as the default label prefix.+ ** @param buf memory buffer containing the bytes.* @param settings the Settings object* @param len the length of the data.@@ -272,9 +339,10 @@ public interface DataType {DataTypeDisplayOptions options);/**- * Returns the appropriate string to use as the default label prefix, taking into account- * the fact that there exists a reference to the data that references- * <code>offcutLength</code> bytes into this type+ * Returns the appropriate string to use as the default label prefix.+ * <p>+ * This takes into account the fact that there exists a reference to the data that references+ * <code>offcutLength</code> bytes into this type** @param buf memory buffer containing the bytes.* @param settings the Settings object@@ -296,183 +364,229 @@ public interface DataType {*/public String getRepresentation(MemBuffer buf, Settings settings, int length);- /**- * Returns true if this data type has been deleted and is no longer valid- * @return true if this data type has been deleted and is no longer valid.+ /**+ * Encode bytes according to the display format for this type.+ * <p>+ * Converts the given representation to the byte encoding and returns it. When appropriate, this+ * should seek the nearest encoding to the specified value, since the representation is likely+ * coming from user input. For example, a floating-point value may be rounded. Invalid+ * representations should be rejected with a {@link DataTypeEncodeException}.+ *+ * @param repr the representation of the desired value, as in+ * {@link #getRepresentation(MemBuffer, Settings, int)}. The supported formats depend+ * on the specific datatype and its settings.+ * @param buf a buffer representing the eventual destination of the bytes.+ * @param settings the settings to use for the representation.+ * @param length the expected length of the result, usually the length of the data unit, or -1+ * to let the type choose the length. It may be ignored, e.g., for fixed-length+ * types.+ * @return the encoded value.+ * @throws DataTypeEncodeException if the value cannot be encoded for any reason, e.g.,+ * incorrect format, not enough space, buffer overflow, unsupported (see+ * {@link #isEncodable()}).+ */+ public byte[] encodeRepresentation(String repr, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException;++ /**+ * Returns true if this datatype has been deleted and is no longer valid+ *+ * @return true if this datatype has been deleted and is no longer valid.*/public boolean isDeleted();/**- * Returns true if the given dataType is equivalent to this dataType. The- * precise meaning of "equivalent" is dataType dependent.- * <br>- * NOTE: if invoked by a DB object or manager it should be invoked on the- * DataTypeDB object passing the other datatype as the argument.- * @param dt the dataType being tested for equivalence.- * @return true if the if the given dataType is equivalent to this dataType.+ * Check if the given datatype is equivalent to this datatype.+ * <p>+ * The precise meaning of "equivalent" is datatype dependent. <br>+ * NOTE: if invoked by a DB object or manager it should be invoked on the DataTypeDB object+ * passing the other datatype as the argument.+ *+ * @param dt the datatype being tested for equivalence.+ * @return true if the if the given datatype is equivalent to this datatype.*/public boolean isEquivalent(DataType dt);/**- * Notification that the given dataType's size has changed. DataTypes may- * need to make internal changes in response.- * <br>- * TODO: This method is reserved for internal DB use.- * <br>- * @param dt the dataType that has changed.+ * Notification that the given datatype's size has changed.+ * <p>+ * DataTypes may need to make internal changes in response. <br>+ * TODO: This method is reserved for internal DB use. <br>+ *+ * @param dt the datatype that has changed.*/public void dataTypeSizeChanged(DataType dt);/**- * Notification that the given dataType's alignment has changed. DataTypes may- * need to make internal changes in response.- * <br>- * TODO: This method is reserved for internal DB use.- * <br>- * @param dt the dataType that has changed.+ * Notification that the given datatype's alignment has changed.+ * <p>+ * DataTypes may need to make internal changes in response. <br>+ * TODO: This method is reserved for internal DB use. <br>+ *+ * @param dt the datatype that has changed.*/public void dataTypeAlignmentChanged(DataType dt);/**- * Informs this dataType that the given dataType has been deleted.- * <br>- * TODO: This method is reserved for internal DB use.- * <br>- * @param dt the dataType that has been deleted.+ * Informs this datatype that the given datatype has been deleted.+ * <p>+ * TODO: This method is reserved for internal DB use. <br>+ *+ * @param dt the datatype that has been deleted.*/public void dataTypeDeleted(DataType dt);/**- * Informs this data type that the given oldDT has been replaced with newDT- * <br>- * TODO: This method is reserved for internal DB use.- * <br>- * @param oldDt old data type- * @param newDt new data type+ * Informs this datatype that the given oldDT has been replaced with newDT+ * <p>+ * TODO: This method is reserved for internal DB use. <br>+ *+ * @param oldDt old datatype+ * @param newDt new datatype*/public void dataTypeReplaced(DataType oldDt, DataType newDt);/**- * Set the default settings for this data type.- * <br>- * TODO: This method is reserved for internal DB use.- * <br>- * @param settings the settings to be used as this dataTypes default settings.+ * Set the default settings for this datatype.+ * <p>+ * TODO: This method is reserved for internal DB use. <br>+ *+ * @param settings the settings to be used as this dataTypes default settings.*/public void setDefaultSettings(Settings settings);/**- * Inform this data type that it has the given parent- * <br>- * TODO: This method is reserved for internal DB use.- * <br>- * @param dt parent data type+ * Inform this datatype that it has the given parent+ * <p>+ * TODO: This method is reserved for internal DB use. <br>+ *+ * @param dt parent datatype*/public void addParent(DataType dt);/**- * Remove a parent data type- * <br>- * TODO: This method is reserved for internal DB use.- * <br>- * @param dt parent data type+ * Remove a parent datatype+ * <p>+ * TODO: This method is reserved for internal DB use. <br>+ *+ * @param dt parent datatype*/public void removeParent(DataType dt);/**- * Informs this data type that its name has changed from the indicated old name.- * <br>- * TODO: This method is reserved for internal DB use.- * <br>- * @param dt the data type whose name changed- * @param oldName the data type's old name+ * Informs this datatype that its name has changed from the indicated old name.+ * <p>+ * TODO: This method is reserved for internal DB use. <br>+ *+ * @param dt the datatype whose name changed+ * @param oldName the datatype's old name*/public void dataTypeNameChanged(DataType dt, String oldName);/**- * @return an array of parents of this data type+ * Get the parents of this datatype+ *+ * @return an array of parents of this datatype*/public DataType[] getParents();/**- * Gets the alignment to be used when aligning this data type within another data type.- * @return this data type's alignment.+ * Gets the alignment to be used when aligning this datatype within another datatype.+ *+ * @return this datatype's alignment.*/public int getAlignment();/**- * Returns true if this dataType depends on the existence of the given dataType.- * For example byte[] depends on byte. If byte were deleted, then byte[] would- * also be deleted.- * @param dt the dataType to test that this dataType depends on.- * @return true if the existence of this datatype relies on the existence- * of the specified datatype dt.+ * Check if this datatype depends on the existence of the given datatype.+ * <p>+ * For example byte[] depends on byte. If byte were deleted, then byte[] would also be deleted.+ *+ * @param dt the datatype to test that this datatype depends on.+ * @return true if the existence of this datatype relies on the existence of the specified+ * datatype dt.*/public boolean dependsOn(DataType dt);/*** Get the source archive where this type originated+ ** @return source archive object*/public SourceArchive getSourceArchive();/*** Set the source archive where this type originated+ ** @param archive source archive object*/public void setSourceArchive(SourceArchive archive);/**- * Get the timestamp corresponding to the last time this type was changed- * within its data type manager- * @return timestamp of last change within data type manager+ * Get the timestamp corresponding to the last time this type was changed within its datatype+ * manager+ *+ * @return timestamp of last change within datatype manager*/public long getLastChangeTime();/**- * Get the timestamp corresponding to the last time this type was sync'd- * within its source archive+ * Get the timestamp corresponding to the last time this type was sync'd within its source+ * archive+ ** @return timestamp of last sync with source archive*/public long getLastChangeTimeInSourceArchive();/**- * Get the universal ID for this data type. This value is intended to be a- * unique identifier across all programs and archives. The same ID indicates- * that two data types were originally the same one. Keep in mind names, categories,+ * Get the universal ID for this datatype.+ * <p>+ * This value is intended to be a unique identifier across all programs and archives. The same+ * ID indicates that two datatypes were originally the same one. Keep in mind names, categories,* and component makeup may differ and have changed since there origin.- * @return data type UniversalID+ *+ * @return datatype UniversalID*/public UniversalID getUniversalID();/**- * For dataTypes that support change, this method replaces the internals of this dataType with- * the internals of the given dataType. The dataTypes must be of the same "type" (i.e. structure- * can only be replacedWith another structure.- * @param dataType the dataType that contains the internals to upgrade to.- * @throws UnsupportedOperationException if the dataType does not support change.- * @throws IllegalArgumentException if the given dataType is not the same type as this dataType.+ * For datatypes that support change, this method replaces the internals of this datatype with+ * the internals of the given datatype.+ * <p>+ * The datatypes must be of the same "type" (i.e. structure can only be replacedWith another+ * structure.+ *+ * @param datatype the datatype that contains the internals to upgrade to.+ * @throws UnsupportedOperationException if the datatype does not support change.+ * @throws IllegalArgumentException if the given datatype is not the same type as this datatype.*/public void replaceWith(DataType dataType);/**- * Sets the lastChangeTime for this dataType. Normally, this is updated automatically when- * a dataType is changed, but when committing or updating while synchronizing an archive, the- * lastChangeTime may need to be updated externally.- * @param lastChangeTime the time to use as the lastChangeTime for this dataType+ * Sets the lastChangeTime for this datatype.+ * <p>+ * Normally, this is updated automatically when a datatype is changed, but when committing or+ * updating while synchronizing an archive, the lastChangeTime may need to be updated+ * externally.+ *+ * @param lastChangeTime the time to use as the lastChangeTime for this datatype*/public void setLastChangeTime(long lastChangeTime);/**- * Sets the lastChangeTimeInSourceArchive for this dataType. This is used by when a dataType- * change is committed back to its source archive.- * @param lastChangeTimeInSourceArchive the time to use as the lastChangeTimeInSourceArchive for this dataType+ * Sets the lastChangeTimeInSourceArchive for this datatype.+ * <p>+ * This is used by when a datatype change is committed back to its source archive.+ *+ * @param lastChangeTimeInSourceArchive the time to use as the lastChangeTimeInSourceArchive for+ * this datatype*/public void setLastChangeTimeInSourceArchive(long lastChangeTimeInSourceArchive);/*** Returns the DataOrganization associated with this data-type- * @return associated data organization+ *+ * @return associated data organization*/public DataOrganization getDataOrganization();diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataTypeEncodeException.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataTypeEncodeException.javanew file mode 100644index 0000000000..97c363825c--- /dev/null+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataTypeEncodeException.java@@ -0,0 +1,82 @@+/* ###+ * 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.program.model.data;++import ghidra.util.exception.UsrException;++/**+ * Exception thrown when a value cannot be encoded for a data type+ */+public class DataTypeEncodeException extends UsrException {++ private final Object value;+ private final DataType dt;++ /**+ * Constructor+ *+ * @param message the exception message+ * @param value the requested value or representation+ * @param dt the data type+ */+ public DataTypeEncodeException(String message, Object value, DataType dt) {+ this(message, value, dt, null);+ }++ /**+ * Constructor+ *+ * @param message the exception message+ * @param value the requested value or representation+ * @param dt the data type+ * @param cause the exception cause+ */+ public DataTypeEncodeException(String message, Object value, DataType dt, Throwable cause) {+ super("Cannot encode '" + value + "' for " + dt.getDisplayName() ++ (message == null ? "" : ": " + message), cause);+ this.value = value;+ this.dt = dt;+ }++ /**+ * Constructor+ *+ * @param value the requested value or representation+ * @param dt the data type+ * @param cause the exception cause+ */+ public DataTypeEncodeException(Object value, DataType dt, Throwable cause) {+ this(null, value, dt, cause);+ }++ /**+ * Get the requested value or representation+ *+ * @return the requested value representation+ */+ public Object getValue() {+ return value;+ }++ /**+ * Get the data type+ *+ * @return the data type+ */+ public DataType getDataType() {+ return dt;+ }+}diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataTypeWithCharset.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataTypeWithCharset.javaindex cba67384a4..03c24cc38c 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataTypeWithCharset.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataTypeWithCharset.java@@ -16,16 +16,72 @@package ghidra.program.model.data;import ghidra.docking.settings.Settings;+import ghidra.program.model.mem.MemBuffer;public interface DataTypeWithCharset extends DataType {+ /**+ * Utility for character data types to encode a value.+ *+ * @param value the character value to encode.+ * @param buf a buffer representing the eventual destination of the bytes.+ * @param settings the settings to use.+ * @return the encoded value+ * @throws DataTypeEncodeException if the value cannot be encoded+ */+ public default byte[] encodeCharacterValue(Object value, MemBuffer buf, Settings settings)+ throws DataTypeEncodeException {+ char[] normalizedValue;+ if (value instanceof Character) {+ normalizedValue = new char[] { (Character) value };+ }+ else if (value instanceof char[]) {+ normalizedValue = (char[]) value;+ if (normalizedValue.length > 2) {+ throw new DataTypeEncodeException("char[] must represent a single code point",+ value, this);+ }+ }+ else {+ throw new DataTypeEncodeException(+ "Requires Character or char[] with a single code point", value, this);+ }+ StringDataInstance sdi = new StringDataInstance(this, settings, buf, getLength());+ try {+ return sdi.encodeReplacementFromCharValue(normalizedValue);+ }+ catch (Throwable e) {+ throw new DataTypeEncodeException(value, this, e);+ }+ }++ /**+ * Utility for character data types to encode a representation.+ *+ * @param repr the single-character string to encode.+ * @param buf a buffer representing the eventual destination of the bytes.+ * @param settings the settings to use.+ * @return the encoded value+ * @throws DataTypeEncodeException if the value cannot be encoded+ */+ public default byte[] encodeCharacterRepresentation(String repr, MemBuffer buf,+ Settings settings) throws DataTypeEncodeException {+ StringDataInstance sdi = new StringDataInstance(this, settings, buf, getLength());+ try {+ return sdi.encodeReplacementFromCharRepresentation(repr);+ }+ catch (Throwable e) {+ throw new DataTypeEncodeException(repr, this, e);+ }+ }+/*** Get the character set for a specific data type and settings+ ** @param settings data instance settings* @return Charset for this datatype and settings*/public default String getCharsetName(Settings settings) {return StringDataInstance.DEFAULT_CHARSET_NAME;}-}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 f36e147f63..e011502832 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@@ -15,20 +15,21 @@*/package ghidra.program.model.data;-import static ghidra.program.model.data.EndianSettingsDefinition.*;-import static ghidra.program.model.data.RenderUnicodeSettingsDefinition.*;+import static ghidra.program.model.data.EndianSettingsDefinition.ENDIAN;+import static ghidra.program.model.data.RenderUnicodeSettingsDefinition.RENDER;import static ghidra.program.model.data.StringLayoutEnum.*;-import static ghidra.program.model.data.TranslationSettingsDefinition.*;+import static ghidra.program.model.data.TranslationSettingsDefinition.TRANSLATION;-import java.nio.charset.Charset;-import java.util.HashMap;-import java.util.Map;+import java.nio.*;+import java.nio.charset.*;+import java.util.*;import generic.stl.Pair;import ghidra.docking.settings.*;import ghidra.program.model.address.Address;import ghidra.program.model.address.AddressOutOfBoundsException;import ghidra.program.model.data.RenderUnicodeSettingsDefinition.RENDER_ENUM;+import ghidra.program.model.data.StringRenderParser.StringParseException;import ghidra.program.model.lang.Endian;import ghidra.program.model.listing.Data;import ghidra.program.model.mem.*;@@ -37,10 +38,10 @@ import ghidra.util.*;/*** Represents an instance of a string in a {@link MemBuffer}.* <p>- * This class handles all the details of detecting a terminated string's length,- * converting the bytes in the membuffer into a java native String, and converting- * the raw String into a formatted human-readable version, according to the- * various {@link SettingsDefinition}s attached to the string data location.+ * This class handles all the details of detecting a terminated string's length, converting the+ * bytes in the membuffer into a java native String, and converting the raw String into a formatted+ * human-readable version, according to the various {@link SettingsDefinition}s attached to the+ * string data location.* <p>*/public class StringDataInstance {@@ -69,13 +70,12 @@ public class StringDataInstance {}/**- * Returns true if the specified {@link DataType} is (or could be) a- * string.+ * Returns true if the specified {@link DataType} is (or could be) a string.* <p>- * Arrays of char-like elements (see {@link ArrayStringable}) are treated- * as string data types. The actual data instance needs to be inspected- * to determine if the array is an actual string.+ * Arrays of char-like elements (see {@link ArrayStringable}) are treated as string data types.+ * The actual data instance needs to be inspected to determine if the array is an actual string.* <p>+ ** @param dt DataType to test* @return boolean true if data type is or could be a string*/@@ -91,7 +91,7 @@ public class StringDataInstance {* Returns true if the {@link Data} instance is one of the many 'char' data types.** @param data {@link Data} instance to test, null ok- * @return boolean true if char data+ * @return boolean true if char data*/public static boolean isChar(Data data) {if (data == null) {@@ -103,14 +103,17 @@ public class StringDataInstance {}/**- * Returns a string representation of the character(s) contained in the byte array, suitable- * for display as a single character, or as a sequence of characters.+ * Returns a string representation of the character(s) contained in the byte array, suitable for+ * display as a single character, or as a sequence of characters.* <p>*- * @param dataType the {@link DataType} of the element containing the bytes (most likely a ByteDataType)+ * @param dataType the {@link DataType} of the element containing the bytes (most likely a+ * ByteDataType)* @param bytes the big-endian ordered bytes to convert to a char representation- * @param settings the {@link Settings} object for the location where the bytes came from, or null- * @return formatted string (typically with quotes around the contents): single character: 'a', multiple characters: "a\x12bc"+ * @param settings the {@link Settings} object for the location where the bytes came from, or+ * null+ * @return formatted string (typically with quotes around the contents): single character: 'a',+ * multiple characters: "a\x12bc"*/public static String getCharRepresentation(DataType dataType, byte[] bytes, Settings settings) {if (bytes == null || bytes.length == 0) {@@ -127,11 +130,11 @@ public class StringDataInstance {}/**- * Determine if bytes contain only a single ASCII value within- * least-significant-byte of big-endian byte array+ * Determine if bytes contain only a single ASCII value within least-significant-byte of+ * big-endian byte array+ ** @param bytes value byte array in big-endian order- * @return true if bytes contain a single ASCII value within- * least-significant-byte+ * @return true if bytes contain a single ASCII value within least-significant-byte*/private static boolean isSingleAsciiValue(byte[] bytes) {@@ -150,8 +153,9 @@ public class StringDataInstance {/*** Returns a new {@link StringDataInstance} using the bytes in the data codeunit.* <p>+ ** @param data {@link Data} item- * @return new {@link StringDataInstance}, never NULL. See {@link #NULL_INSTANCE}.+ * @return new {@link StringDataInstance}, never NULL. See {@link #NULL_INSTANCE}.*/public static StringDataInstance getStringDataInstance(Data data) {if (data == null) {@@ -176,11 +180,12 @@ public class StringDataInstance {/*** Returns a new {@link StringDataInstance} using the bytes in the MemBuffer.* <p>+ ** @param dataType {@link DataType} of the bytes in the buffer.* @param buf memory buffer containing the bytes.* @param settings the Settings object* @param length the length of the data.- * @return new {@link StringDataInstance}, never NULL. See {@link #NULL_INSTANCE}.+ * @return new {@link StringDataInstance}, never NULL. See {@link #NULL_INSTANCE}.*/public static StringDataInstance getStringDataInstance(DataType dataType, MemBuffer buf,Settings settings, int length) {@@ -220,8 +225,8 @@ public class StringDataInstance {*/private static final String BOM_RESULT_STR = "\ufeff";- private static final int SIZEOF_PASCAL255_STR_LEN_FIELD = 1;- private static final int SIZEOF_PASCAL64k_STR_LEN_FIELD = 2;+ static final int SIZEOF_PASCAL255_STR_LEN_FIELD = 1;+ static final int SIZEOF_PASCAL64k_STR_LEN_FIELD = 2;private final String charsetName;private final int charSize;@@ -251,35 +256,35 @@ public class StringDataInstance {}/**- * Creates a string instance using the data in the {@link MemBuffer} and the settings- * pulled from the {@link AbstractStringDataType string data type}.+ * Creates a string instance using the data in the {@link MemBuffer} and the settings pulled+ * from the {@link AbstractStringDataType string data type}.*- * @param dataType {@link DataType} of the string, either a {@link AbstractStringDataType} derived type- * or an {@link ArrayStringable} element-of-char-array type.+ * @param dataType {@link DataType} of the string, either a {@link AbstractStringDataType}+ * derived type or an {@link ArrayStringable} element-of-char-array type.* @param settings {@link Settings} attached to the data location.* @param buf {@link MemBuffer} containing the data.- * @param length Length passed from the caller to the datatype. -1 indicates a 'probe'- * trying to detect the length of an unknown string, otherwise it will be the length- * of the containing field of the data instance.+ * @param length Length passed from the caller to the datatype. -1 indicates a 'probe' trying to+ * detect the length of an unknown string, otherwise it will be the length of the+ * containing field of the data instance.*/public StringDataInstance(DataType dataType, Settings settings, MemBuffer buf, int length) {this(dataType, settings, buf, length, false);}/**- * Creates a string instance using the data in the {@link MemBuffer} and the settings- * pulled from the {@link AbstractStringDataType string data type}.+ * Creates a string instance using the data in the {@link MemBuffer} and the settings pulled+ * from the {@link AbstractStringDataType string data type}.*- * @param dataType {@link DataType} of the string, either a {@link AbstractStringDataType} derived type- * or an {@link ArrayStringable} element-of-char-array type.+ * @param dataType {@link DataType} of the string, either a {@link AbstractStringDataType}+ * derived type or an {@link ArrayStringable} element-of-char-array type.* @param settings {@link Settings} attached to the data location.* @param buf {@link MemBuffer} containing the data.- * @param length Length passed from the caller to the datatype. -1 indicates a 'probe'- * trying to detect the length of an unknown string, otherwise it will be the length- * of the containing field of the data instance.- * @param isArrayElement boolean flag, true indicates that the specified dataType is an- * element in an array (ie. char[] vs. just a plain char), causing the string layout- * to be forced to {@link StringLayoutEnum#NULL_TERMINATED_BOUNDED}+ * @param length Length passed from the caller to the datatype. -1 indicates a 'probe' trying to+ * detect the length of an unknown string, otherwise it will be the length of the+ * containing field of the data instance.+ * @param isArrayElement boolean flag, true indicates that the specified dataType is an element+ * in an array (ie. char[] vs. just a plain char), causing the string layout to be+ * forced to {@link StringLayoutEnum#NULL_TERMINATED_BOUNDED}*/public StringDataInstance(DataType dataType, Settings settings, MemBuffer buf, int length,boolean isArrayElement) {@@ -337,7 +342,7 @@ public class StringDataInstance {return StringLayoutEnum.NULL_TERMINATED_BOUNDED;}- private static String getCharsetNameFromDataTypeOrSettings(DataType dataType,+ static String getCharsetNameFromDataTypeOrSettings(DataType dataType,Settings settings) {if (dataType instanceof BitFieldDataType) {dataType = ((BitFieldDataType) dataType).getBaseDataType();@@ -388,32 +393,31 @@ public class StringDataInstance {}/**- * Returns the length, in bytes, of the string data object contained in the- * {@link MemBuffer}, or -1 if the length could not be determined.+ * Returns the length, in bytes, of the string data object contained in the {@link MemBuffer},+ * or -1 if the length could not be determined.* <p>* This is not the same as the number of characters in the string, or the number of bytes- * occupied by the characters. For instance, pascal strings have a 1 or 2 byte length- * field that increases the size of the string data object beyond the characters in the- * string, and null terminated strings have don't include the null character, but its- * presence is included in the size of the string object.+ * occupied by the characters. For instance, pascal strings have a 1 or 2 byte length field that+ * increases the size of the string data object beyond the characters in the string, and null+ * terminated strings have don't include the null character, but its presence is included in the+ * size of the string object.* <p>- * For length-specified string data types that do not use null-terminators and with a- * known data instance length (ie. not a probe), this method just returns the- * value specified in the constructor {@code length} parameter, otherwise a null-terminator- * is searched for.+ * For length-specified string data types that do not use null-terminators and with a known data+ * instance length (ie. not a probe), this method just returns the value specified in the+ * constructor {@code length} parameter, otherwise a null-terminator is searched for.* <p>- * When searching for a null-terminator, the constructor {@code length} parameter will- * be respected or ignored depending on the {@link StringLayoutEnum}.+ * When searching for a null-terminator, the constructor {@code length} parameter will be+ * respected or ignored depending on the {@link StringLayoutEnum}.* <p>- * When the length parameter is ignored (ie. "unbounded" searching), the search is- * limited to {@link #MAX_STRING_LENGTH} bytes.+ * When the length parameter is ignored (ie. "unbounded" searching), the search is limited to+ * {@link #MAX_STRING_LENGTH} bytes.* <p>- * The MemBuffer's endian'ness is used to determine which end of the padded character- * field contains our n-bit character which will be tested for null-ness. (not the- * endian'ness of the character set name - ie. "UTF-16BE")+ * The MemBuffer's endian'ness is used to determine which end of the padded character field+ * 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 no terminator found.+ * @return length of the string (NOT including null term if null term probe), in bytes, or -1 if+ * no terminator found.*/public int getStringLength() {if (stringLayout.isPascal()) {@@ -457,8 +461,8 @@ public class StringDataInstance {/*** Returns true if the string should have a trailing NULL character and doesn't.*- * @return boolean true if the trailing NULL character is missing, false if string type- * doesn't need a trailing NULL character or if it is present.+ * @return boolean true if the trailing NULL character is missing, false if string type doesn't+ * need a trailing NULL character or if it is present.*/public boolean isMissingNullTerminator() {@@ -502,20 +506,20 @@ public class StringDataInstance {}/**- * Returns the string contained in the specified {@link MemBuffer}, or null if- * all the bytes of the string could not be read.+ * Returns the string contained in the specified {@link MemBuffer}, or null if all the bytes of+ * the string could not be read.* <p>* This method deals in characters of size {@link #charSize}, that might be- * {@link #paddedCharSize padded} to a larger size. The raw n-byte characters- * are converted into a Java String using a Java {@link Charset} or by- * using a custom Ghidra conversion. (see convertBytesToStringCustomCharset)+ * {@link #paddedCharSize padded} to a larger size. The raw n-byte characters are converted into+ * a Java String using a Java {@link Charset} or by using a custom Ghidra conversion. (see+ * convertBytesToStringCustomCharset)* <p>- * The MemBuffer's endian'ness is used to determine which end of the- * {@link #paddedCharSize padded } field contains our {@link #charSize}- * character bytes which will be used to create the java String.+ * The MemBuffer's endian'ness is used to determine which end of the {@link #paddedCharSize+ * padded } field contains our {@link #charSize} character bytes which will be used to create+ * the java String.*- * @return String containing the characters in buf or null if unable to read all- * {@code length} bytes from the membuffer.+ * @return String containing the characters in buf or null if unable to read all {@code length}+ * bytes from the membuffer.*/public String getStringValue() {String str = getStringValueNoTrim();@@ -633,6 +637,21 @@ public class StringDataInstance {return unpaddedBytes;}+ private byte[] convertUnpaddedToPadded(byte[] unpaddedBytes) {+ if (paddedCharSize == charSize || unpaddedBytes == null) {+ return unpaddedBytes;+ }++ byte[] paddedBytes = new byte[(unpaddedBytes.length / charSize) * paddedCharSize];+ for (int srcOffset = 0, destOffset = buf.isBigEndian() ? paddedCharSize - charSize+ : 0; srcOffset < unpaddedBytes.length; srcOffset += charSize, destOffset +=+ paddedCharSize) {+ System.arraycopy(unpaddedBytes, srcOffset, paddedBytes, destOffset, charSize);+ }++ return paddedBytes;+ }+private Endian getMemoryEndianness() {return buf.isBigEndian() ? Endian.BIG : Endian.LITTLE;}@@ -644,6 +663,17 @@ public class StringDataInstance {: convertBytesToStringCustomCharset(bytes, aci);}+ private AdjustedCharsetInfo getAdjustedCharsetInfo() {+ if (length == -1 && getStringLength() == -1) {+ return getAdjustedCharsetInfo(new byte[] {});+ }+ byte[] stringBytes = convertPaddedToUnpadded(getStringBytes());+ if (stringBytes == null) {+ return getAdjustedCharsetInfo(new byte[] {});+ }+ return getAdjustedCharsetInfo(stringBytes);+ }+private AdjustedCharsetInfo getAdjustedCharsetInfo(byte[] bytes) {AdjustedCharsetInfo result = new AdjustedCharsetInfo(charsetName);if (CharsetInfo.isBOMCharset(charsetName)) {@@ -712,9 +742,9 @@ public class StringDataInstance {/*** Returns a formatted version of the string returned by {@link #getStringValue()}.* <p>- * The resulting string will be formatted with quotes around the parts that contain- * plain ASCII alpha characters (and simple escape sequences), and out-of-range- * byte-ish values listed as comma separated hex-encoded values:+ * The resulting string will be formatted with quotes around the parts that contain plain ASCII+ * alpha characters (and simple escape sequences), and out-of-range byte-ish values listed as+ * comma separated hex-encoded values:* <p>* Example (quotes are part of result): {@code "Test\tstring",01,02,"Second\npart",00}*@@ -875,6 +905,7 @@ public class StringDataInstance {* {@link TranslationSettingsDefinition#getTranslatedValue(Settings) translated settings}* string.* <p>+ ** @return previously translated string.*/public String getTranslatedValue() {@@ -882,8 +913,8 @@ public class StringDataInstance {}/**- * Returns true if the user should be shown the translated value of the string instead- * of the real value.+ * Returns true if the user should be shown the translated value of the string instead of the+ * real value.** @return boolean true if should show previously translated value.*/@@ -892,8 +923,8 @@ public class StringDataInstance {}/**- * Convert a char value (or sequence of char values) in memory into its canonical unicode representation, using- * attached charset and encoding information.+ * Convert a char value (or sequence of char values) in memory into its canonical unicode+ * representation, using attached charset and encoding information.* <p>** @return String containing the representation of the char.@@ -978,12 +1009,13 @@ public class StringDataInstance {}/**- * Returns a new {@link StringDataInstance} that points to the string characters- * that start at {@code byteOffset} from the start of this instance.+ * Returns a new {@link StringDataInstance} that points to the string characters that start at+ * {@code byteOffset} from the start of this instance.* <p>* If the requested offset is not valid, the base string instance (itself) will be returned* instead of a new instance.* <p>+ ** @param byteOffset number of bytes from start of data instance to start new instance.* @return new StringDataInstance, or <code>this</code> if offset not valid.*/@@ -999,21 +1031,22 @@ public class StringDataInstance {}/**- * Create a new {@link StringDataInstance} that points to a portion of this- * instance, starting at a character offset (whereever that may be) into the data.+ * Create a new {@link StringDataInstance} that points to a portion of this instance, starting+ * at a character offset (whereever that may be) into the data.* <p>- * @param offsetChars number of characters from the beginning of the string to start- * the new StringDataInstance.+ *+ * @param offsetChars number of characters from the beginning of the string to start the new+ * StringDataInstance.* @return new {@link StringDataInstance} pointing to a subset of characters, or the- * <code>this</code> instance if there was an error.+ * <code>this</code> instance if there was an error.*/public StringDataInstance getCharOffcut(int offsetChars) {return getByteOffcut(getCharOffset(offsetChars));}/**- * Maps a {@link StringDataInstance}'s layout and charset info into the best String- * DataType that can handle this type of data instance.+ * Maps a {@link StringDataInstance}'s layout and charset info into the best String DataType+ * that can handle this type of data instance.* <p>* An entry with a null charset name is equivalent to any charset.*@@ -1041,11 +1074,12 @@ public class StringDataInstance {}/**- * Maps a {@link StringDataInstance} (this type) to the String DataType that best- * can handle this type of data.+ * Maps a {@link StringDataInstance} (this type) to the String DataType that best can handle+ * this type of data.* <p>* I dare myself to type Type one more time.* <p>+ ** @return {@link DataType}, defaulting to {@link StringDataType} if no direct match found.*/public DataType getStringDataTypeGuess() {@@ -1064,6 +1098,129 @@ public class StringDataInstance {return getStringValue();}+ private static ByteBuffer allocBuf(MemBuffer buf, int length) {+ return ByteBuffer.allocate(length)+ .order(buf.isBigEndian() ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);+ }++ private static boolean fitsIn(ByteBuffer buf, int lenLen) {+ return buf.limit() < (1 << (8 * lenLen));+ }++ /**+ * Encode a string to replace the current value+ *+ * @param value the value to encode+ * @return the encoded value+ * @throws CharacterCodingException if a character could not be encoded+ */+ public byte[] encodeReplacementFromStringValue(CharSequence value)+ throws CharacterCodingException {+ CharsetEncoder ce = Charset.forName(charsetName).newEncoder();+ ByteBuffer bb = ce.encode(CharBuffer.wrap(value));+ return convertUnpaddedToPadded(checkAndEncodeLayout(bb));+ }++ /**+ * Parse and encode a string from its representation to replace the current value+ *+ * @param repr the representation of the string+ * @return the encoded value+ * @throws StringParseException if the representation could not be parsed+ * @throws UnmappableCharacterException if a character could not be encoded+ * @throws MalformedInputException if the input contains invalid character sequences+ */+ public byte[] encodeReplacementFromStringRepresentation(CharSequence repr)+ throws MalformedInputException, UnmappableCharacterException, StringParseException {+ AdjustedCharsetInfo aci = getAdjustedCharsetInfo();+ StringRenderParser parser = new StringRenderParser(StringRenderBuilder.DOUBLE_QUOTE,+ aci.endian, aci.charsetName, aci.byteStartOffset != 0);+ ByteBuffer bb = parser.parse(CharBuffer.wrap(repr));+ return convertUnpaddedToPadded(checkAndEncodeLayout(bb));+ }++ /**+ * Encode a single character to replace the current value+ *+ * @param value a single code point to encode+ * @return the encoded value+ * @throws CharacterCodingException if the character could not be encoded+ */+ public byte[] encodeReplacementFromCharValue(char[] value) throws CharacterCodingException {+ CharsetEncoder ce = Charset.forName(charsetName).newEncoder();+ ByteBuffer bb = ce.encode(CharBuffer.wrap(value));+ return Arrays.copyOf(bb.array(), bb.limit());+ }++ /**+ * Parse and encode a single character from its representation to replace the current value+ *+ * @param repr the representation of a single character+ * @return the encoded value+ * @throws StringParseException if the representation could not be parsed+ * @throws UnmappableCharacterException if a character could not be encoded+ * @throws MalformedInputException if the input contains invalid character sequences+ */+ public byte[] encodeReplacementFromCharRepresentation(CharSequence repr)+ throws MalformedInputException, UnmappableCharacterException, StringParseException {+ // TODO: Given all the representation forms, how to check for a single character?+ AdjustedCharsetInfo aci = getAdjustedCharsetInfo();+ StringRenderParser parser = new StringRenderParser(StringRenderBuilder.SINGLE_QUOTE,+ aci.endian, aci.charsetName, aci.byteStartOffset != 0);+ ByteBuffer bb = parser.parse(CharBuffer.wrap(repr));+ return Arrays.copyOf(bb.array(), bb.limit());+ }++ private byte[] checkAndEncodeLayout(ByteBuffer encoded) {+ switch (stringLayout) {+ case CHAR_SEQ:+ case FIXED_LEN: {+ if (length != -1 && encoded.limit() > length) {+ throw new IllegalArgumentException("Encoded string does not fit");+ }+ byte[] result = new byte[length != -1 ? length : encoded.limit()];+ encoded.get(result, 0, encoded.limit());+ return result;+ }+ case NULL_TERMINATED_BOUNDED: {+ if (length != -1 && encoded.limit() + charSize > length) {+ throw new IllegalArgumentException("Encoded string does not fit");+ }+ byte[] result = new byte[encoded.limit() + charSize];+ encoded.get(result, 0, encoded.limit());+ return result;+ }+ case NULL_TERMINATED_UNBOUNDED: {+ byte[] result = new byte[encoded.limit() + charSize];+ encoded.get(result, 0, encoded.limit());+ return result;+ }+ case PASCAL_255: {+ if (!fitsIn(encoded, StringDataInstance.SIZEOF_PASCAL255_STR_LEN_FIELD)) {+ throw new IllegalArgumentException("Encoded string does not fit");+ }+ ByteBuffer result = allocBuf(buf,+ encoded.limit() + StringDataInstance.SIZEOF_PASCAL255_STR_LEN_FIELD);+ result.put((byte) encoded.limit());+ result.put(encoded);+ return result.array();+ }+ case PASCAL_64k: {+ if (!fitsIn(encoded, StringDataInstance.SIZEOF_PASCAL64k_STR_LEN_FIELD)) {+ throw new IllegalArgumentException("Encoded string does not fit");+ }+ ByteBuffer result = allocBuf(buf,+ encoded.limit() + StringDataInstance.SIZEOF_PASCAL64k_STR_LEN_FIELD);+ result.putShort((short) encoded.limit());+ result.put(encoded);+ return result.array();+ }+ default: {+ throw new IllegalArgumentException("Unknown string layout");+ }+ }+ }+//==================================================================================================// Inner Classes//==================================================================================================diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/StringRenderParser.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/StringRenderParser.javanew file mode 100644index 0000000000..533ecd30c1--- /dev/null+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/StringRenderParser.java@@ -0,0 +1,424 @@+/* ###+ * 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.program.model.data;++import java.nio.*;+import java.nio.charset.*;+import java.util.*;+import java.util.stream.Collectors;++import ghidra.program.model.lang.Endian;+import ghidra.util.StringUtilities;+import ghidra.util.exception.UsrException;++/**+ * A parser to invert {@link StringDataInstance#getStringRepresentation()},+ * {@link StringDataInstance#getCharRepresentation()}, and related.+ */+public class StringRenderParser {++ private static String hexDigits = "0123456789ABCDEFabcdef";++ /**+ * An exception for when a string representation cannot be parsed.+ */+ public static class StringParseException extends UsrException {+ public StringParseException(int pos, Set<Character> expected, char got) {+ super("Error parsing string representation at position " + pos + ". Expected one of " ++ Objects.requireNonNull(expected) + " but got " + got);+ }++ public StringParseException(int pos) {+ super("Unexpected end of string representation at position " + pos + ".");+ }+ }++ private enum State {+ INIT(true, "uU'\"" + hexDigits),+ PREFIX(false, "8'\"" + hexDigits),+ UNIT(true, "'\"" + hexDigits),+ STR(false),+ BYTE(false, hexDigits),+ BYTE_SUFFIX(false, "h"),+ COMMA(true, ","),+ ESCAPE(false, "0abtnvfr\\\"'xuU"),+ CODE_POINT(false, hexDigits);++ private final boolean isFinal;+ private final Set<Character> accepts;++ private State(boolean isFinal) { // Implies this accepts any+ this.isFinal = isFinal;+ this.accepts = null;+ }++ private State(boolean isFinal, String accepts) {+ this(isFinal, accepts.chars()+ .mapToObj(i -> (char) i)+ .collect(Collectors.toCollection(HashSet::new)));+ }++ private State(boolean isFinal, Set<Character> accepts) {+ this.isFinal = isFinal;+ this.accepts = Collections.unmodifiableSet(accepts);+ }++ private void checkAccepts(int pos, char c) throws StringParseException {+ if (accepts == null) {+ return;+ }+ if (accepts.contains(c)) {+ return;+ }+ throw new StringParseException(pos, accepts, c);+ }++ private void checkFinal(int pos) throws StringParseException {+ if (isFinal) {+ return;+ }+ throw new StringParseException(pos);+ }+ }++ private final char quoteChar;+ private final Endian endian;+ private final String charsetName;+ private final boolean includeBOM;+ private final CharBuffer oneCodePointBuffer = CharBuffer.allocate(2);++ private int pos; // total characters consumed, not just of current buffer+ private State state;+ private Charset charset;+ private CharsetEncoder encoder;+ private int val;+ private int codeDigits;++ /**+ * Construct a parser+ *+ * @param quoteChar the character expected to enclose the representation. Use double quote (")+ * for strings. Use single quote (') for characters.+ * @param endian the endian for unicode strings+ * @param charsetName the character set name, as in {@link Charset#forName(String)}+ * @param includeBOM true to prepend a byte order marker, if applicable+ */+ public StringRenderParser(char quoteChar, Endian endian, String charsetName,+ boolean includeBOM) {+ this.quoteChar = Objects.requireNonNull(quoteChar);+ this.endian = Objects.requireNonNull(endian);+ this.charsetName = charsetName;+ this.includeBOM = includeBOM;++ reset();+ }++ /**+ * Reset the parser+ */+ public void reset() {+ pos = 0;+ state = State.INIT;+ val = 0;++ charset = null;+ encoder = null;+ }++ protected void initCharset(ByteBuffer out, String reprCharsetName) {+ String charsetName = this.charsetName != null ? this.charsetName : reprCharsetName;+ int charSize = CharsetInfo.getInstance().getCharsetCharSize(charsetName);+ if (CharsetInfo.isBOMCharset(charsetName)) {+ // Take care of the BOM ourselves, because it must be first, before any initial bytes+ charsetName += endian.isBigEndian() ? "BE" : "LE";+ }+ charset = Charset.forName(charsetName);+ if (includeBOM) {+ if (charSize == 2) {+ out.putShort((short) StringUtilities.UNICODE_BE_BYTE_ORDER_MARK);+ }+ else if (charSize == 4) {+ out.putInt(StringUtilities.UNICODE_BE_BYTE_ORDER_MARK);+ }+ }+ encoder = charset.newEncoder();+ }++ protected int valHexDigit(char c) {+ if ('0' <= c && c <= '9') {+ return c - '0' + 0;+ }+ if ('A' <= c && c <= 'F') {+ return c - 'A' + 0xA;+ }+ if ('a' <= c && c <= 'f') {+ return c - 'a' + 0xa;+ }+ throw new AssertionError();+ }++ protected State parseCharInit(ByteBuffer out, char c) {+ if (c == 'u') {+ return State.PREFIX;+ }+ if (c == 'U') {+ initCharset(out, CharsetInfo.UTF32);+ return State.UNIT;+ }+ initCharset(out, CharsetInfo.USASCII);+ return parseCharUnit(out, c);+ }++ protected State parseCharPrefix(ByteBuffer out, char c) {+ if (c == '8') {+ initCharset(out, CharsetInfo.UTF8);+ return State.UNIT;+ }+ initCharset(out, CharsetInfo.UTF16);+ return parseCharUnit(out, c);+ }++ protected State parseCharUnit(ByteBuffer out, char c) {+ if (('0' <= c && c <= '9') || ('A' <= c && c <= 'F') || ('a' <= c && c <= 'f')) {+ val = valHexDigit(c);+ return State.BYTE;+ }+ if (c == quoteChar) {+ return State.STR;+ }+ throw new AssertionError();+ }++ protected void encodeCodePoint(ByteBuffer out, int cp)+ throws MalformedInputException, UnmappableCharacterException {+ if (!Character.isSupplementaryCodePoint(cp)) {+ encodeChar(out, (char) cp);+ return;+ }+ oneCodePointBuffer.clear();+ oneCodePointBuffer.put(0, Character.highSurrogate(cp));+ oneCodePointBuffer.put(1, Character.lowSurrogate(cp));+ encodeBufferedCodePoint(out);+ }++ protected void encodeChar(ByteBuffer out, char c)+ throws MalformedInputException, UnmappableCharacterException {+ oneCodePointBuffer.clear();+ oneCodePointBuffer.put(0, c);+ oneCodePointBuffer.limit(1);+ encodeBufferedCodePoint(out);+ }++ protected void encodeBufferedCodePoint(ByteBuffer out)+ throws MalformedInputException, UnmappableCharacterException {+ CoderResult cr = encoder.encode(oneCodePointBuffer, out, false);+ if (cr.isOverflow()) {+ throw new BufferOverflowException();+ }+ if (cr.isMalformed()) {+ throw new MalformedInputException(1);+ }+ if (cr.isUnmappable()) {+ throw new UnmappableCharacterException(1);+ }+ }++ protected State parseCharStr(ByteBuffer out, char c)+ throws MalformedInputException, UnmappableCharacterException {+ if (c == quoteChar) {+ return State.COMMA;+ }+ if (c == '\\') {+ return State.ESCAPE;+ }+ encodeChar(out, c);+ return State.STR;+ }++ protected State parseCharByte(ByteBuffer out, char c) {+ val = (val << 4) + valHexDigit(c);+ return State.BYTE_SUFFIX;+ }++ protected State parseCharByteSuffix(ByteBuffer out, char c) {+ if (c == 'h') {+ out.put((byte) val);+ val = 0;+ return State.COMMA;+ }+ throw new AssertionError();+ }++ protected State parseCharComma(ByteBuffer out, char c) {+ if (c == ',') {+ return State.UNIT;+ }+ throw new AssertionError();+ }++ protected State parseCharEscape(ByteBuffer out, char c)+ throws MalformedInputException, UnmappableCharacterException {+ switch (c) {+ case '0':+ encodeChar(out, '\0');+ return State.STR;+ case 'a':+ encodeChar(out, (char) 7);+ return State.STR;+ case 'b':+ encodeChar(out, '\b');+ return State.STR;+ case 't':+ encodeChar(out, '\t');+ return State.STR;+ case 'n':+ encodeChar(out, '\n');+ return State.STR;+ case 'v':+ encodeChar(out, (char) 11);+ return State.STR;+ case 'f':+ encodeChar(out, '\f');+ return State.STR;+ case 'r':+ encodeChar(out, '\r');+ return State.STR;+ case '\\':+ encodeChar(out, '\\');+ return State.STR;+ case '\"':+ encodeChar(out, '"');+ return State.STR;+ case '\'':+ encodeChar(out, '\'');+ return State.STR;+ case 'x':+ codeDigits = 2;+ return State.CODE_POINT;+ case 'u':+ codeDigits = 4;+ return State.CODE_POINT;+ case 'U':+ codeDigits = 8;+ return State.CODE_POINT;+ default:+ throw new AssertionError();+ }+ }++ protected State parseCharCodePoint(ByteBuffer out, char c)+ throws MalformedInputException, UnmappableCharacterException {+ assert codeDigits > 0;+ val = (val << 4) + valHexDigit(c);+ if (0 == (--codeDigits)) {+ encodeCodePoint(out, val);+ return State.STR;+ }+ return State.CODE_POINT;+ }++ protected State parseChar(ByteBuffer out, char c)+ throws MalformedInputException, UnmappableCharacterException {+ switch (state) {+ case INIT:+ return parseCharInit(out, c);+ case PREFIX:+ return parseCharPrefix(out, c);+ case UNIT:+ return parseCharUnit(out, c);+ case STR:+ return parseCharStr(out, c);+ case BYTE:+ return parseCharByte(out, c);+ case BYTE_SUFFIX:+ return parseCharByteSuffix(out, c);+ case COMMA:+ return parseCharComma(out, c);+ case ESCAPE:+ return parseCharEscape(out, c);+ case CODE_POINT:+ return parseCharCodePoint(out, c);+ default:+ throw new AssertionError();+ }+ }++ /**+ * Parse and encode a complete string or character representation+ *+ * @param in the buffer containing the representation+ * @return a buffer containing the encoded string or character+ * @throws StringParseException if the representation could not be parsed+ * @throws MalformedInputException if a character sequence in the representation is not valid+ * @throws UnmappableCharacterException if a character cannot be encoded+ */+ public ByteBuffer parse(CharBuffer in)+ throws StringParseException, MalformedInputException, UnmappableCharacterException {+ int bufSize = in.remaining() * 2; // We don't know the charset, yet.+ while (true) {+ ByteBuffer out = ByteBuffer.allocate(bufSize)+ .order(endian == Endian.BIG ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);+ int pos = in.position();+ try {+ parse(out, in);+ finish(out);+ out.flip();+ return out;+ }+ catch (BufferOverflowException e) {+ bufSize <<= 1;+ in.position(pos);+ reset();+ }+ }+ }++ /**+ * Parse and encode a portion of a string or character representation+ *+ * @param out the destination buffer for the encoded string or character, having matching byte+ * order to the charset.+ * @param in the source buffer for the representation+ * @throws StringParseException if the representation could not be parsed+ * @throws MalformedInputException if a character sequence in the representation is not valid+ * @throws UnmappableCharacterException if a character cannot be encoded+ */+ public void parse(ByteBuffer out, CharBuffer in)+ throws StringParseException, MalformedInputException, UnmappableCharacterException {+ try {+ while (in.hasRemaining()) {+ char c = in.get();+ state.checkAccepts(pos, c);+ state = parseChar(out, c);+ pos++;+ }+ }+ catch (Throwable e) {+ in.position(in.position() - 1);+ throw e;+ }+ }++ /**+ * Finish parsing and encoded a string or character representation+ *+ * @param out the destination buffer for the encoded string or character+ * @throws StringParseException if the representation is not complete+ */+ public void finish(ByteBuffer out) throws StringParseException {+ state.checkFinal(pos);+ }+}diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/WideChar16DataType.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/WideChar16DataType.javaindex 07b62ea1dc..6ae4622afc 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/WideChar16DataType.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/WideChar16DataType.java@@ -15,6 +15,9 @@*/package ghidra.program.model.data;+import java.nio.CharBuffer;+import java.nio.charset.Charset;+import ghidra.docking.settings.Settings;import ghidra.docking.settings.SettingsDefinition;import ghidra.program.model.mem.MemBuffer;@@ -23,7 +26,7 @@ import ghidra.util.StringUtilities;public class WideChar16DataType extends BuiltIn implements ArrayStringable, DataTypeWithCharset {- /** A statically defined WideCharDataType instance.*/+ /** A statically defined WideCharDataType instance. */public final static WideChar16DataType dataType = new WideChar16DataType();public WideChar16DataType() {@@ -78,6 +81,23 @@ public class WideChar16DataType extends BuiltIn implements ArrayStringable, Datareturn null;}+ @Override+ public boolean isEncodable() {+ return true;+ }++ @Override+ public byte[] encodeValue(Object value, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ return encodeCharacterValue(value, buf, settings);+ }++ @Override+ public byte[] encodeRepresentation(String repr, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ return encodeCharacterRepresentation(repr, buf, settings);+ }+@Overridepublic Class<?> getValueClass(Settings settings) {return Character.class;diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/WideChar32DataType.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/WideChar32DataType.javaindex 3a7cd1127a..1ffe2eda4a 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/WideChar32DataType.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/WideChar32DataType.java@@ -24,7 +24,7 @@ import ghidra.util.StringUtilities;public class WideChar32DataType extends BuiltIn implements ArrayStringable, DataTypeWithCharset {- /** A statically defined WideCharDataType instance.*/+ /** A statically defined WideCharDataType instance. */public final static WideChar32DataType dataType = new WideChar32DataType();public WideChar32DataType() {@@ -80,6 +80,23 @@ public class WideChar32DataType extends BuiltIn implements ArrayStringable, Datareturn null;}+ @Override+ public boolean isEncodable() {+ return true;+ }++ @Override+ public byte[] encodeValue(Object value, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ return encodeCharacterValue(value, buf, settings);+ }++ @Override+ public byte[] encodeRepresentation(String repr, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ return encodeCharacterRepresentation(repr, buf, settings);+ }+@Overridepublic Class<?> getValueClass(Settings settings) {return Scalar.class;diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/WideCharDataType.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/WideCharDataType.javaindex 15cccb7c77..bf52522e2a 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/WideCharDataType.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/WideCharDataType.java@@ -26,7 +26,7 @@ public class WideCharDataType extends BuiltIn implements ArrayStringable, DataTyfinal static SettingsDefinition[] DEFAULT_WIDE_CHAR_SETTINGS = new SettingsDefinition[] {EndianSettingsDefinition.DEF, RenderUnicodeSettingsDefinition.RENDER };- /** A statically defined WideCharDataType instance.*/+ /** A statically defined WideCharDataType instance. */public final static WideCharDataType dataType = new WideCharDataType();public WideCharDataType() {@@ -92,6 +92,23 @@ public class WideCharDataType extends BuiltIn implements ArrayStringable, DataTyreturn null;}+ @Override+ public boolean isEncodable() {+ return true;+ }++ @Override+ public byte[] encodeValue(Object value, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ return encodeCharacterValue(value, buf, settings);+ }++ @Override+ public byte[] encodeRepresentation(String repr, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ return encodeCharacterRepresentation(repr, buf, settings);+ }+@Overridepublic Class<?> getValueClass(Settings settings) {switch (getLength()) {diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/mem/MutableMemBuffer.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/mem/MutableMemBuffer.javaindex 574caa3b33..2cc56e6d13 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/mem/MutableMemBuffer.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/mem/MutableMemBuffer.java@@ -18,14 +18,12 @@ package ghidra.program.model.mem;import ghidra.program.model.address.Address;import ghidra.program.model.address.AddressOverflowException;-/**- * The MutableMemBuffer interface facilitates- * repositioning of a MemBuffer object.+ * The MutableMemBuffer interface facilitates repositioning of a MemBuffer object.*/public interface MutableMemBuffer extends MemBuffer {- /**+ /*** Advance the Address pointer.** @param displacement the amount to adjust the pointer by.@@ -33,15 +31,16 @@ public interface MutableMemBuffer extends MemBuffer {*/public void advance(int displacement) throws AddressOverflowException;- /**- * Sets the Address to which offset of 0 points to.- *- * @param addr the new base Address.- */- public void setPosition(Address addr);+ /**+ * Sets the Address to which offset of 0 points to.+ *+ * @param addr the new base Address.+ */+ public void setPosition(Address addr);/*** Create a cloned copy of this MutableMemBuffer+ ** @return new cloned instance of this buffer object*/public MutableMemBuffer clone();diff --git a/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/program/model/data/CharDataTypesRenderTest.java b/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/program/model/data/CharDataTypesRenderTest.javaindex 619913cacc..5d47963989 100644--- a/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/program/model/data/CharDataTypesRenderTest.java+++ b/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/program/model/data/CharDataTypesRenderTest.java@@ -72,6 +72,33 @@ public class CharDataTypesRenderTest extends AbstractGTest {//@formatter:on}+ @Test+ public void testEncodeSimpleASCIIChar() throws DataTypeEncodeException {+ assertArrayEquals(bytes('a'),+ charDT.encodeRepresentation("'a'", mb(false), newset(), -1));+ assertArrayEquals(bytes('a'),+ ucharDT.encodeRepresentation("'a'", mb(false), newset(), -1));+ // TODO: UTF-8?+ assertArrayEquals(bytes('a', 0),+ wcharDT.encodeRepresentation("u'a'", mb(false), newset(), -1));+ assertArrayEquals(bytes('a', 0),+ wchar16DT.encodeRepresentation("u'a'", mb(false), newset(), -1));+ assertArrayEquals(bytes('a', 0, 0, 0),+ wchar32DT.encodeRepresentation("U'a'", mb(false), newset(), -1));++ assertArrayEquals(bytes('a'),+ charDT.encodeRepresentation("'a'", mb(true), newset(), -1));+ assertArrayEquals(bytes('a'),+ ucharDT.encodeRepresentation("'a'", mb(true), newset(), -1));+ // TODO: UTF-8?+ assertArrayEquals(bytes(0, 'a'),+ wcharDT.encodeRepresentation("u'a'", mb(true), newset(), -1));+ assertArrayEquals(bytes(0, 'a'),+ wchar16DT.encodeRepresentation("u'a'", mb(true), newset(), -1));+ assertArrayEquals(bytes(0, 0, 0, 'a'),+ wchar32DT.encodeRepresentation("U'a'", mb(true), newset(), -1));+ }+@Testpublic void testWideCharsNonAscii() {// Test rendering a non-ascii, but valid ideographic character.@@ -97,6 +124,30 @@ public class CharDataTypesRenderTest extends AbstractGTest {//@formatter:on}+ @Test+ public void testEncodeWideCharsNonAscii() throws DataTypeEncodeException {+ // Contrast to the _EscSeq variant by the same name below.+ // The single \ucc01 is interpreted by the Java compiler.+ // Double \\ucc01 is interpreted by the parser under test.+ assertArrayEquals(bytes(66),+ charDT.encodeRepresentation("'\u0e01'", mb(false), newset().set(thaiCS), -1));++ assertArrayEquals(bytes(0xcc, 0x01),+ wcharDT.encodeRepresentation("u'\ucc01'", mb(true), newset(), -1));+ assertArrayEquals(bytes(0x01, 0xcc),+ wcharDT.encodeRepresentation("u'\ucc01'", mb(false), newset(), -1));++ assertArrayEquals(bytes(0xcc, 0x01),+ wchar16DT.encodeRepresentation("u'\ucc01'", mb(true), newset(), -1));+ assertArrayEquals(bytes(0x01, 0xcc),+ wchar16DT.encodeRepresentation("u'\ucc01'", mb(false), newset(), -1));++ assertArrayEquals(bytes(0, 0, 0xcc, 0x01),+ wchar32DT.encodeRepresentation("U'\ucc01'", mb(true), newset(), -1));+ assertArrayEquals(bytes(0x01, 0xcc, 0, 0),+ wchar32DT.encodeRepresentation("U'\ucc01'", mb(false), newset(), -1));+ }+@Testpublic void testWideCharsNonAscii_EscSeq() {ByteMemBufferImpl buf_thai = mb(false, 66);@@ -118,6 +169,30 @@ public class CharDataTypesRenderTest extends AbstractGTest {//@formatter:on}+ @Test+ public void testEncodeWideCharsNonAscii_EscSeq() throws DataTypeEncodeException {+ // Contrast to the non_EscSeq variant by the same name above.+ // The single \ucc01 is interpreted by the Java compiler.+ // Double \\ucc01 is interpreted by the parser under test.+ assertArrayEquals(bytes(66),+ charDT.encodeRepresentation("'\\u0e01'", mb(false), newset().set(thaiCS), -1));++ assertArrayEquals(bytes(0xcc, 0x01),+ wcharDT.encodeRepresentation("u'\\ucc01'", mb(true), newset(), -1));+ assertArrayEquals(bytes(0x01, 0xcc),+ wcharDT.encodeRepresentation("u'\\ucc01'", mb(false), newset(), -1));++ assertArrayEquals(bytes(0xcc, 0x01),+ wchar16DT.encodeRepresentation("u'\\ucc01'", mb(true), newset(), -1));+ assertArrayEquals(bytes(0x01, 0xcc),+ wchar16DT.encodeRepresentation("u'\\ucc01'", mb(false), newset(), -1));++ assertArrayEquals(bytes(0, 0, 0xcc, 0x01),+ wchar32DT.encodeRepresentation("U'\\ucc01'", mb(true), newset(), -1));+ assertArrayEquals(bytes(0x01, 0xcc, 0, 0),+ wchar32DT.encodeRepresentation("U'\\ucc01'", mb(false), newset(), -1));+ }+@Testpublic void testNonAsciiCharset() {// in thai charset, byte 73 ('I') maps to the normal ascii char '['@@ -127,6 +202,12 @@ public class CharDataTypesRenderTest extends AbstractGTest {assertEquals("'['", result);}+ @Test+ public void testEncodeNonAsciiCharset() throws DataTypeEncodeException {+ assertArrayEquals(bytes(73),+ charDT.encodeRepresentation("'['", mb(false), newset().set(thaiCS), -1));+ }+@Testpublic void testEscapeSequenceRender_singlebyte_to_multibyte() {// in thai charset, byte 66 ('B') maps to a 'n' looking thing with a line@@ -198,4 +279,10 @@ public class CharDataTypesRenderTest extends AbstractGTest {newset().set(RENDER_ENUM.BYTE_SEQ), wchar16DT.getLength());assertEquals("FDh,FFh", result);}++ @Test+ public void testEncodeByteSequence() throws DataTypeEncodeException {+ assertArrayEquals(bytes(0xaa, 0xff, 0xfd),+ charDT.encodeRepresentation("AAh,FFh,FDh", mb(true), newset(), -1));+ }}diff --git a/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/program/model/data/StringDataTypeTest.java b/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/program/model/data/StringDataTypeTest.javaindex ffedbe1231..21532b0d37 100644--- a/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/program/model/data/StringDataTypeTest.java+++ b/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/program/model/data/StringDataTypeTest.java@@ -366,6 +366,14 @@ public class StringDataTypeTest extends AbstractGTest {fixedlenString.getRepresentation(buf, newset(), buf.getLength()));}+ @Test+ public void testProbeEncodeStringRep_LeadingBinaryBytes() throws DataTypeEncodeException {+ byte[] bytes = bytes(1, 2, 'x');+ assertArrayEquals(bytes,+ fixedlenString.encodeRepresentation("01h,02h,\"x\"", mb(false), newset(),+ bytes.length));+ }+@Testpublic void testGetStringRep_FixedLen() {ByteMemBufferImpl buf = mb(false, 'h', 'e', 'l', 'l', 'o', 0, 'a', '\n', 'b', 255, 0);@@ -375,6 +383,14 @@ public class StringDataTypeTest extends AbstractGTest {fixedlenString.getRepresentation(buf, newset(), buf.getLength()));}+ @Test+ public void testEncodeStringRep_FixedLen() throws DataTypeEncodeException {+ byte[] bytes = bytes('h', 'e', 'l', 'l', 'o', 0, 'a', '\n', 'b', 255, 0);+ assertArrayEquals(bytes,+ fixedlenString.encodeRepresentation("\"hello\\0a\\nb\",FFh", mb(false), newset(),+ bytes.length));+ }+@Testpublic void testGetStringRepEmpty_Term() {ByteMemBufferImpl buf = mb(false, 0, 0);@@ -382,6 +398,12 @@ public class StringDataTypeTest extends AbstractGTest {assertEquals("\"\"", termString.getRepresentation(buf, newset(), buf.getLength()));}+ @Test+ public void testEncodeStringRepEmpty_Term() throws DataTypeEncodeException {+ assertArrayEquals(bytes(0), // NOTE: Differs from inverse test above.+ termString.encodeRepresentation("\"\"", mb(false), newset(), -1));+ }+@Testpublic void testGetStringRepEmpty_TermUTF16() {ByteMemBufferImpl buf = mb(false, 0, 0);@@ -389,6 +411,12 @@ public class StringDataTypeTest extends AbstractGTest {assertEquals("u\"\"", termUtf16String.getRepresentation(buf, newset(), buf.getLength()));}+ @Test+ public void testEncodeStringRepEmpty_TermUTF16() throws DataTypeEncodeException {+ assertArrayEquals(bytes(0, 0),+ termUtf16String.encodeRepresentation("u\"\"", mb(false), newset(), -1));+ }+@Testpublic void testGetStringRepEmpty_FixedLen() {ByteMemBufferImpl buf = mb(false, 0, 0, 0, 0, 0);@@ -396,6 +424,14 @@ public class StringDataTypeTest extends AbstractGTest {assertEquals("\"\"", fixedlenString.getRepresentation(buf, newset(), buf.getLength()));}+ @Test+ public void testEncodeStringRepEmpty_FixedLen() throws DataTypeEncodeException {+ // TODO: Should the caller or the encoder handle padding the remaining bytes+ byte[] bytes = bytes(0, 0, 0, 0, 0);+ assertArrayEquals(bytes,+ fixedlenString.encodeRepresentation("\"\"", mb(false), newset(), bytes.length));+ }+@Testpublic void testGetStringRepEmpty_P() {ByteMemBufferImpl buf = mb(false, 0, 0);@@ -403,6 +439,12 @@ public class StringDataTypeTest extends AbstractGTest {assertEquals("\"\"", pascalString.getRepresentation(buf, newset(), buf.getLength()));}+ @Test+ public void testEncodeStringRepEmpty_P() throws DataTypeEncodeException {+ assertArrayEquals(bytes(0, 0),+ pascalString.encodeRepresentation("\"\"", mb(false), newset(), -1));+ }+@Testpublic void testGetStringRepAllChars() {int[] allAsciiChars = new int[256];@@ -435,6 +477,32 @@ public class StringDataTypeTest extends AbstractGTest {}+ @Test+ public void testEncodeStringRepAllChars() throws DataTypeEncodeException {+ byte[] allAsciiChars = new byte[256];+ for (int i = 0; i < allAsciiChars.length; i++) {+ allAsciiChars[i] = (byte) i;+ }+ String repr = "" ++ "\"\\0\"," ++ "01h,02h,03h,04h,05h,06h," ++ "\"\\a\\b\\t\\n\\v\\f\\r\",0Eh,0Fh,10h,11h,12h,13h,14h,15h,16h,17h,18h,19h,1Ah,1Bh,1Ch,1Dh,1Eh,1Fh,\"" ++ " !\\\"#$%&'()*+,-./0123456789:;<=>?@" ++ "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`" ++ "abcdefghijklmnopqrstuvwxyz{|}~\",7Fh," ++ "80h,81h,82h,83h,84h,85h,86h,87h,88h,89h,8Ah,8Bh,8Ch,8Dh,8Eh,8Fh," ++ "90h,91h,92h,93h,94h,95h,96h,97h,98h,99h,9Ah,9Bh,9Ch,9Dh,9Eh,9Fh," ++ "A0h,A1h,A2h,A3h,A4h,A5h,A6h,A7h,A8h,A9h,AAh,ABh,ACh,ADh,AEh,AFh," ++ "B0h,B1h,B2h,B3h,B4h,B5h,B6h,B7h,B8h,B9h,BAh,BBh,BCh,BDh,BEh,BFh," ++ "C0h,C1h,C2h,C3h,C4h,C5h,C6h,C7h,C8h,C9h,CAh,CBh,CCh,CDh,CEh,CFh," ++ "D0h,D1h,D2h,D3h,D4h,D5h,D6h,D7h,D8h,D9h,DAh,DBh,DCh,DDh,DEh,DFh," ++ "E0h,E1h,E2h,E3h,E4h,E5h,E6h,E7h,E8h,E9h,EAh,EBh,ECh,EDh,EEh,EFh," ++ "F0h,F1h,F2h,F3h,F4h,F5h,F6h,F7h,F8h,F9h,FAh,FBh,FCh,FDh,FEh,FFh";++ assertArrayEquals(allAsciiChars, fixedlenString.encodeRepresentation(repr, mb(false),+ newset().set(StandardCharsets.US_ASCII), -1));+ }+@Testpublic void testGetStringRep_utf16_le() {ByteMemBufferImpl buf = mb(false, //@@ -451,6 +519,20 @@ public class StringDataTypeTest extends AbstractGTest {fixedUtf16String.getRepresentation(buf, newset(), buf.getLength()));}+ @Test+ public void testEncodeStringRep_utf16_le() throws DataTypeEncodeException {+ assertArrayEquals(bytes(+ 'h', 0, //+ 'e', 0, //+ 'l', 0, //+ 'l', 0, //+ 'o', 0, //+ 0, 0, //+ 'x', 0, //+ 'y', 0),+ fixedUtf16String.encodeRepresentation("U\"hello\\0xy\"", mb(false), newset(), -1));+ }+@Testpublic void testGetStringRep_utf16_ideographic() {// "ab" and 2 random ideographic characters cc01 & 1202 (big & little endian)@@ -475,6 +557,31 @@ public class StringDataTypeTest extends AbstractGTest {newset().set(RENDER_ENUM.ESC_SEQ), buf_le.getLength()));}+ @Test+ public void testEncodeStringRep_utf16_ideographic() throws DataTypeEncodeException {+ byte[] bytes_be = bytes(0, 'a', 0, 'b', 0xcc, 0x01, 0x12, 0x02);+ byte[] bytes_le = bytes('a', 0, 'b', 0, 0x01, 0xcc, 0x02, 0x12);++ String e1 = "u\"ab\ucc01\u1202\"";+ assertArrayEquals(bytes_be,+ fixedUtf16String.encodeRepresentation(e1, mb(true), newset(), -1));+ assertArrayEquals(bytes_le,+ fixedUtf16String.encodeRepresentation(e1, mb(false), newset(), -1));++ String e2_be = "u\"ab\",CCh,01h,12h,02h";+ String e2_le = "u\"ab\",01h,CCh,02h,12h";+ assertArrayEquals(bytes_be,+ fixedUtf16String.encodeRepresentation(e2_be, mb(true), newset(), -1));+ assertArrayEquals(bytes_le,+ fixedUtf16String.encodeRepresentation(e2_le, mb(false), newset(), -1));++ String e3 = "u\"ab\\uCC01\\u1202\"";+ assertArrayEquals(bytes_be,+ fixedUtf16String.encodeRepresentation(e3, mb(true), newset(), -1));+ assertArrayEquals(bytes_le,+ fixedUtf16String.encodeRepresentation(e3, mb(false), newset(), -1));+ }+@Testpublic void testGetStringRep_utf16_escapeseq_U() {// 2 utf-16 chars that create a single code point.@@ -485,6 +592,12 @@ public class StringDataTypeTest extends AbstractGTest {newset().set(RENDER_ENUM.ESC_SEQ), buf_be.getLength()));}+ @Test+ public void testEncodeStringRep_utf16_escapeseq_U() throws DataTypeEncodeException {+ assertArrayEquals(bytes(0, 'a', 0, 'b', 0xd8, 0x00, 0xdd, 0x12, 0, 'c'),+ fixedUtf16String.encodeRepresentation("u\"ab\\U00010112c\"", mb(true), newset(), -1));+ }+@Testpublic void testGetStringRep_utf32() {ByteMemBufferImpl buf = mb(false, //@@ -501,6 +614,20 @@ public class StringDataTypeTest extends AbstractGTest {fixedUtf32String.getRepresentation(buf, newset(), buf.getLength()));}+ @Test+ public void testEncodeStringRep_utf32() throws DataTypeEncodeException {+ assertArrayEquals(bytes(+ 'h', 0, 0, 0, //+ 'e', 0, 0, 0, //+ 'l', 0, 0, 0, //+ 'l', 0, 0, 0, //+ 'o', 0, 0, 0, //+ 0, 0, 0, 0, //+ 'x', 0, 0, 0, //+ 'y', 0, 0, 0),+ fixedUtf32String.encodeRepresentation("U\"hello\\0xy\"", mb(false), newset(), -1));+ }+@Testpublic void testGetStringRep_Pascal_EOF() {assertEquals("Pascal string with length past end of mem should return error... string",diff --git a/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/program/model/data/TestDoubleDataType.java b/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/program/model/data/StubDataType.javasimilarity index 90%rename from Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/program/model/data/TestDoubleDataType.javarename to Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/program/model/data/StubDataType.javaindex c16c1765a3..778b462a45 100644--- a/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/program/model/data/TestDoubleDataType.java+++ b/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/program/model/data/StubDataType.java@@ -16,6 +16,7 @@package ghidra.program.model.data;import java.net.URL;+import java.nio.ByteBuffer;import ghidra.docking.settings.Settings;import ghidra.docking.settings.SettingsDefinition;@@ -24,15 +25,15 @@ import ghidra.util.*;import ghidra.util.exception.DuplicateNameException;/**- * A stub of the {@link DataType} interface. This can be used to supply a test values- * or to spy on system internals by overriding methods as needed.+ * A stub of the {@link DataType} interface. This can be used to supply a test values or to spy on+ * system internals by overriding methods as needed.*/-public class TestDoubleDataType implements DataType {+public class StubDataType implements DataType {private UniversalID id;private String name;- public TestDoubleDataType(String name) {+ public StubDataType(String name) {this.name = name;this.id = UniversalIdGenerator.nextID();}@@ -153,6 +154,17 @@ public class TestDoubleDataType implements DataType {throw new UnsupportedOperationException();}+ @Override+ public boolean isEncodable() {+ return false;+ }++ @Override+ public byte[] encodeValue(Object value, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ throw new UnsupportedOperationException();+ }+@Overridepublic Class<?> getValueClass(Settings settings) {throw new UnsupportedOperationException();@@ -185,6 +197,12 @@ public class TestDoubleDataType implements DataType {throw new UnsupportedOperationException();}+ @Override+ public byte[] encodeRepresentation(String repr, MemBuffer buf, Settings settings, int length)+ throws DataTypeEncodeException {+ throw new UnsupportedOperationException();+ }+@Overridepublic boolean isDeleted() {throw new UnsupportedOperationException();