Ghidra is a software reverse engineering (SRE) framework
Clean up and refactor blob and table processing for code standards and consistency, make CLI metadata structures more complete
jmlagorff81c360075f
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/CliMetadataTokenAnalyzer.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/CliMetadataTokenAnalyzer.javaindex bac18fe504..823ca43adc 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/CliMetadataTokenAnalyzer.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/CliMetadataTokenAnalyzer.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -49,8 +49,11 @@ public class CliMetadataTokenAnalyzer extends AbstractAnalyzer {@Overridepublic boolean getDefaultEnablement(Program program) {- return program.getLanguage().getLanguageDescription().getLanguageID().getIdAsString().contains(- "CLI");+ return program.getLanguage()+ .getLanguageDescription()+ .getLanguageID()+ .getIdAsString()+ .contains("CLI");}@Override@@ -63,7 +66,7 @@ public class CliMetadataTokenAnalyzer extends AbstractAnalyzer {throws CancelledException {Symbol metadataRootSymbol = SymbolUtilities.getExpectedLabelOrFunctionSymbol(program,- CliMetadataRoot.NAME, err -> log.error(getName(), err));+ CliMetadataRoot.NAME, err -> log.appendMsg(getName(), err));if (metadataRootSymbol == null) {String message = "CLI Metadata Root Symbol not found.";@@ -75,93 +78,101 @@ public class CliMetadataTokenAnalyzer extends AbstractAnalyzer {ByteProvider bytes = new MemoryByteProvider(program.getMemory(), metadataRootAddr);BinaryReader reader = new BinaryReader(bytes, !program.getLanguage().isBigEndian());+ boolean success = false;try {CliMetadataRoot metadataRoot = new CliMetadataRoot(reader, 0);metadataRoot.parse();CliStreamMetadata metadataStream = metadataRoot.getMetadataStream();- // Determine if each instruction has something we should fix up.- // Note that we use endsWith() instead of equals() because instructions can have prefixes.- InstructionIterator instIter = program.getListing().getInstructions(set, true);- while (instIter.hasNext()) {- try {- Instruction inst = instIter.next();- /* Base Instructions (Partition II.3) */- if (inst.getMnemonicString().endsWith("ldstr")) {- processUserString(metadataStream, inst);- }- else if (inst.getMnemonicString().endsWith("call")) {- processControlFlowInstruction(program, metadataStream, inst,- RefType.UNCONDITIONAL_CALL);- }- else if (inst.getMnemonicString().endsWith("calli")) {- processControlFlowInstruction(program, metadataStream, inst,- RefType.COMPUTED_CALL); // TODO: computed?- }- else if (inst.getMnemonicString().endsWith("jmp")) {- processControlFlowInstruction(program, metadataStream, inst,- RefType.UNCONDITIONAL_JUMP);- }- else if (inst.getMnemonicString().endsWith("ldftn")) {- processGenericMetadataToken(metadataStream, inst);- // TODO: how to say a method pointer is pushed onto the stack...- }- /* Object Model Instructions */- else if (inst.getMnemonicString().endsWith("box") ||- inst.getMnemonicString().endsWith("castclass") ||- inst.getMnemonicString().endsWith("cpobj") ||- inst.getMnemonicString().endsWith("initobj") ||- inst.getMnemonicString().endsWith("isinst") ||- inst.getMnemonicString().endsWith("ldelem") ||- inst.getMnemonicString().endsWith("ldelema") ||- inst.getMnemonicString().endsWith("ldfld") ||- inst.getMnemonicString().endsWith("ldflda") ||- inst.getMnemonicString().endsWith("ldobj") ||- inst.getMnemonicString().endsWith("ldsfld") ||- inst.getMnemonicString().endsWith("ldsflda") ||- inst.getMnemonicString().endsWith("ldtoken") ||- inst.getMnemonicString().endsWith("mkrefany") ||- inst.getMnemonicString().endsWith("newarr") ||- inst.getMnemonicString().endsWith("newobj") ||- inst.getMnemonicString().endsWith("refanyval") ||- inst.getMnemonicString().endsWith("sizeof") ||- inst.getMnemonicString().endsWith("stelem") ||- inst.getMnemonicString().endsWith("stfld") ||- inst.getMnemonicString().endsWith("stobj") ||- inst.getMnemonicString().endsWith("stsfld") ||- inst.getMnemonicString().endsWith("unbox") ||- inst.getMnemonicString().endsWith("unbox.any")) {- processObjectModelInstruction(program, metadataStream, inst);- }- else if (inst.getMnemonicString().endsWith("callvirt")) {- processControlFlowInstruction(program, metadataStream, inst,- RefType.COMPUTED_CALL);- // TODO: Computed call because this is a virtual function on an object- }- else if (inst.getMnemonicString().endsWith("constrained")) {- CliAbstractTableRow tableRow = getRowForMetadataToken(metadataStream, inst);- markMetadataRow(inst, tableRow, "Next instr type req'd to be: ", "",- metadataStream);- }- else if (inst.getMnemonicString().endsWith("ldvirtfn")) {- processObjectModelInstruction(program, metadataStream, inst);- // TODO: ldvirtfn puts virtual method pointer on stack, see above for ldftn- }- }- catch (Exception e) {- e.printStackTrace();- // TODO:- }- }+ success = processManagedInstructions(program, set, monitor, log, metadataRoot);}catch (IOException e) {- // TODO Auto-generated catch block- e.printStackTrace();String message = e.toString();log.appendMsg(getName(), message);log.setStatus(message);- return false;+ success = false;+ }++ return success;+ }++ private boolean processManagedInstructions(Program program, AddressSetView set,+ TaskMonitor monitor, MessageLog log, CliMetadataRoot metadataRoot)+ throws CancelledException {+ // Determine if each instruction has something we should fix up.+ // Note that we use endsWith() instead of equals() because instructions can have prefixes.+ CliStreamMetadata metadataStream = metadataRoot.getMetadataStream();+ InstructionIterator instIter = program.getListing().getInstructions(set, true);+ while (instIter.hasNext()) {+ try {+ Instruction inst = instIter.next();+ /* Base Instructions (Partition II.3) */+ if (inst.getMnemonicString().endsWith("ldstr")) {+ processUserString(metadataStream, inst);+ }+ else if (inst.getMnemonicString().endsWith("call")) {+ processControlFlowInstruction(program, metadataStream, inst,+ RefType.UNCONDITIONAL_CALL);+ }+ else if (inst.getMnemonicString().endsWith("calli")) {+ processControlFlowInstruction(program, metadataStream, inst,+ RefType.COMPUTED_CALL); // TODO: computed?+ }+ else if (inst.getMnemonicString().endsWith("jmp")) {+ processControlFlowInstruction(program, metadataStream, inst,+ RefType.UNCONDITIONAL_JUMP);+ }+ else if (inst.getMnemonicString().endsWith("ldftn")) {+ processGenericMetadataToken(metadataStream, inst);+ // TODO: how to say a method pointer is pushed onto the stack...+ }+ /* Object Model Instructions */+ else if (inst.getMnemonicString().endsWith("box") ||+ inst.getMnemonicString().endsWith("castclass") ||+ inst.getMnemonicString().endsWith("cpobj") ||+ inst.getMnemonicString().endsWith("initobj") ||+ inst.getMnemonicString().endsWith("isinst") ||+ inst.getMnemonicString().endsWith("ldelem") ||+ inst.getMnemonicString().endsWith("ldelema") ||+ inst.getMnemonicString().endsWith("ldfld") ||+ inst.getMnemonicString().endsWith("ldflda") ||+ inst.getMnemonicString().endsWith("ldobj") ||+ inst.getMnemonicString().endsWith("ldsfld") ||+ inst.getMnemonicString().endsWith("ldsflda") ||+ inst.getMnemonicString().endsWith("ldtoken") ||+ inst.getMnemonicString().endsWith("mkrefany") ||+ inst.getMnemonicString().endsWith("newarr") ||+ inst.getMnemonicString().endsWith("newobj") ||+ inst.getMnemonicString().endsWith("refanyval") ||+ inst.getMnemonicString().endsWith("sizeof") ||+ inst.getMnemonicString().endsWith("stelem") ||+ inst.getMnemonicString().endsWith("stfld") ||+ inst.getMnemonicString().endsWith("stobj") ||+ inst.getMnemonicString().endsWith("stsfld") ||+ inst.getMnemonicString().endsWith("unbox") ||+ inst.getMnemonicString().endsWith("unbox.any")) {+ processObjectModelInstruction(program, metadataStream, inst);+ }+ else if (inst.getMnemonicString().endsWith("callvirt")) {+ processControlFlowInstruction(program, metadataStream, inst,+ RefType.COMPUTED_CALL);+ // TODO: Computed call because this is a virtual function on an object+ }+ else if (inst.getMnemonicString().endsWith("constrained")) {+ CliAbstractTableRow tableRow = getRowForMetadataToken(metadataStream, inst);+ markMetadataRow(inst, tableRow, "Next instr type req'd to be: ", "",+ metadataStream);+ }+ else if (inst.getMnemonicString().endsWith("ldvirtfn")) {+ processObjectModelInstruction(program, metadataStream, inst);+ // TODO: ldvirtfn puts virtual method pointer on stack, see above for ldftn+ }+ }+ catch (Exception e) {+ e.printStackTrace();+ // TODO:+ }}return true;@@ -180,7 +191,9 @@ public class CliMetadataTokenAnalyzer extends AbstractAnalyzer {private void processUserString(CliStreamMetadata metaStream, Instruction inst) {Scalar strIndexOp = (Scalar) inst.getOpObjects(0)[0];+int strIndex = (int) strIndexOp.getUnsignedValue();+inst.setComment(CodeUnit.EOL_COMMENT,"\"" + metaStream.getUserStringsStream().getUserString(strIndex) + "\"");}@@ -192,7 +205,7 @@ public class CliMetadataTokenAnalyzer extends AbstractAnalyzer {if (tableRow instanceof CliMethodDefRow) {// TODO: Add a control flow reference ideally// Op 0 => table, Op 1 => call destination?- // inst.addOperandReference(OP_INDEX, DEST_ADDR, RefType.UNCONDITIONAL_CALL, SourceType.ANALYSIS); // TODO: unconditional call?+ // inst.addOperandReference(OP_INDEX, DEST_ADDR, RefType.UNCONDITIONAL_CALL, SourceType.ANALYSIS); // TODO: unconditional call?// program.getReferenceManager().addMemoryReference(INST_ADDR, DEST_ADDR, RefType.UNCONDITIONAL_CALL, SourceType.ANALYSIS, 0);CliMethodDefRow methodDef = (CliMethodDefRow) tableRow;if (methodDef.RVA != 0) {@@ -203,7 +216,8 @@ public class CliMetadataTokenAnalyzer extends AbstractAnalyzer {}}- private CliAbstractTableRow getRowForMetadataToken(CliStreamMetadata metaStream, Instruction inst) {+ private CliAbstractTableRow getRowForMetadataToken(CliStreamMetadata metaStream,+ Instruction inst) {Object ops[] = inst.getOpObjects(0);Scalar tableOp = (Scalar) ops[0];Scalar indexOp = (Scalar) ops[1];@@ -213,13 +227,14 @@ public class CliMetadataTokenAnalyzer extends AbstractAnalyzer {return tableRow;}- private void markMetadataRow(Instruction inst, CliAbstractTableRow tableRow, String prependComment,- String appendComment, CliStreamMetadata stream) {+ private void markMetadataRow(Instruction inst, CliAbstractTableRow tableRow,+ String prependComment, String appendComment, CliStreamMetadata stream) {inst.setComment(CodeUnit.EOL_COMMENT, String.format("%s%s%s", prependComment,tableRow.getShortRepresentation(stream), appendComment));}- private void markMetadataRow(Instruction inst, CliAbstractTableRow tableRow, CliStreamMetadata stream) {+ private void markMetadataRow(Instruction inst, CliAbstractTableRow tableRow,+ CliStreamMetadata stream) {markMetadataRow(inst, tableRow, "", "", stream);}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliAbstractSig.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliAbstractSig.javaindex 2129d34d6b..8c30710aab 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliAbstractSig.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliAbstractSig.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -77,9 +77,11 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentable}return obj.getShortRepresentation();}+if (stream != null) {return obj.getRepresentation(stream);}+return obj.getRepresentation();}@@ -92,7 +94,7 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentablepublic CliTypeCodeDataType() {super(new CategoryPath(PATH), "TypeCode", 1);- // TODO: specify CategoryPath, etc.+for (CliElementType c : CliElementType.values()) {add(c.toString(), c.id());}@@ -100,6 +102,19 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentable}public static DataType convertTypeCodeToDataType(CliElementType typeCode) {+ /*+ TODO:+ ELEMENT_TYPE_VALUETYPE(0x11),+ ELEMENT_TYPE_VAR(0x13), // "Class type variable VAR"+ (0x16),++ ELEMENT_TYPE_MVAR(0x1e), // Method type variable MVAR++ ELEMENT_TYPE_INTERNAL(0x21), // Internal (generated internally, "will not be persisted in any way")+ ELEMENT_TYPE_MAX(0x22),++ */+switch (typeCode) {case ELEMENT_TYPE_VOID:return VoidDataType.dataType;@@ -107,55 +122,58 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentablecase ELEMENT_TYPE_BOOLEAN:return BooleanDataType.dataType;case ELEMENT_TYPE_CHAR:- return ASCII; // TODO: correct?+ return StringUTF8DataType.dataType;case ELEMENT_TYPE_I1:-// return SignedByteDataType.dataType;+ return SignedByteDataType.dataType;case ELEMENT_TYPE_U1:- return BYTE; // TODO: True?+ return ByteDataType.dataType;case ELEMENT_TYPE_I2:-// return ShortDataType.dataType;+ return ShortDataType.dataType;case ELEMENT_TYPE_U2:-// return UnsignedShortDataType.dataType;- return WORD;+ return UnsignedShortDataType.dataType;case ELEMENT_TYPE_I4:-// return IntegerDataType.dataType;+ return IntegerDataType.dataType;case ELEMENT_TYPE_U4:- return DWORD;-// return UnsignedIntegerDataType.dataType;+ return UnsignedIntegerDataType.dataType;case ELEMENT_TYPE_R4:- return FloatDataType.dataType;-- case ELEMENT_TYPE_R8: // TODO: This is really a 64-bit float- return QWORD;+ return Float4DataType.dataType;+ case ELEMENT_TYPE_R8:+ return Float8DataType.dataType;case ELEMENT_TYPE_I8:-// return LongDataType.dataType; // TODO: Long or Long Long?+ return LongLongDataType.dataType;case ELEMENT_TYPE_U8:-// return UnsignedLongDataType.dataType;- return QWORD;+ return UnsignedLongLongDataType.dataType;+ // TODO: Does this change for native architectures other than 32-bit?case ELEMENT_TYPE_I:-// return IntegerDataType.dataType; // TODO: This must change for native architectures other than 32-bit+ return IntegerDataType.dataType;case ELEMENT_TYPE_U:-// return UnsignedIntegerDataType.dataType;- return DWORD;+ return UnsignedIntegerDataType.dataType;case ELEMENT_TYPE_PTR:return PointerDataType.dataType;+ case ELEMENT_TYPE_FNPTR:+ return PointerDataType.dataType;-// case String:-// return StringDataType.dataType;+ case ELEMENT_TYPE_SZARRAY:+ case ELEMENT_TYPE_STRING:+ return new PointerDataType(new CharDataType());+ case ELEMENT_TYPE_ARRAY:+ return new PointerDataType(new ByteDataType());- case ELEMENT_TYPE_FNPTR:- return PointerDataType.dataType; // TODO verify+ case ELEMENT_TYPE_OBJECT: // System.Object+ case ELEMENT_TYPE_CLASS:+ return PointerDataType.dataType;- // TODO: Finish the rest of the options. Don't know why some of these are .dataType and some have that commented out+ case ELEMENT_TYPE_SENTINEL:+ return Undefined1DataType.dataType;default:- return null;+ return VoidDataType.dataType;}}@@ -164,7 +182,7 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentableELEMENT_TYPE_VOID(0x1),ELEMENT_TYPE_BOOLEAN(0x2),ELEMENT_TYPE_CHAR(0x3),- ELEMENT_TYPE_I1(0x4), // CLI names these by number of bytes (e.g. I4, U2, I1), but literally no one else does does, so we're naming by bits,+ ELEMENT_TYPE_I1(0x4), // CLI names these by number of bytes (e.g. I4, U2, I1)ELEMENT_TYPE_U1(0x5),ELEMENT_TYPE_I2(0x6),ELEMENT_TYPE_U2(0x7),@@ -177,14 +195,14 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentableELEMENT_TYPE_STRING(0xe),ELEMENT_TYPE_PTR(0xf),- ELEMENT_TYPE_BYREF(0x10),+ ELEMENT_TYPE_BYREF(0x10), // ByRef flag in paramtersELEMENT_TYPE_VALUETYPE(0x11),ELEMENT_TYPE_CLASS(0x12),ELEMENT_TYPE_VAR(0x13), // "Class type variable VAR"ELEMENT_TYPE_ARRAY(0x14),- ELEMENT_TYPE_GENERICINST(0x15),- ELEMENT_TYPE_TYPEDBYREF(0x16),+ ELEMENT_TYPE_GENERICINST(0x15), // Signifies a variable uses a Generic+ ELEMENT_TYPE_TYPEDBYREF(0x16), // A fully specified ByRef typeELEMENT_TYPE_I(0x18), // native integer sizeELEMENT_TYPE_U(0x19), // native unsigned integer size@@ -199,10 +217,9 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentableELEMENT_TYPE_INTERNAL(0x21), // Internal (generated internally, "will not be persisted in any way")ELEMENT_TYPE_MAX(0x22),- ELEMENT_TYPE_MODIFIER(0x40), // TODO: this value is ORed with the following 4, Could be changed when Enums support ORing.- ELEMENT_TYPE_SENTINAL(0x41),- ELEMENT_TYPE_PINNED(0x45)- ;+ ELEMENT_TYPE_MODIFIER(0x40),+ ELEMENT_TYPE_SENTINEL(0x41), // Sentinel in MethodRefs+ ELEMENT_TYPE_PINNED(0x45); // Constrained variableprivate final int id;@@ -217,8 +234,9 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentablepublic static CliElementType fromInt(int id) {CliElementType[] values = CliElementType.values();for (CliElementType value : values) {- if (value.id == id)+ if (value.id == id) {return value;+ }}return null;}@@ -322,13 +340,17 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentableif (stream != null) {CliAbstractTable table =stream.getTable(CliIndexTypeDefOrRef.getTableName(encodedType));- if (table == null)+ if (table == null) {return "[ErrorRetrievingTable]";- CliAbstractTableRow row = table.getRow(CliIndexTypeDefOrRef.getRowIndex(encodedType));- if (row == null)+ }+ CliAbstractTableRow row =+ table.getRow(CliIndexTypeDefOrRef.getRowIndex(encodedType));+ if (row == null) {return "[ErrorRetrievingRow]";- if (shortRep)+ }+ if (shortRep) {return row.getShortRepresentation();+ }return row.getRepresentation();}return "[ErrorRepresentingClassReference]";@@ -362,7 +384,7 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentableprivate CliAbstractSig sig;private boolean isDefSig; // true => MethodDef, false => MethodRef- public CliTypeFnPtr(BinaryReader reader, CliElementType typeCode) {+ public CliTypeFnPtr(BinaryReader reader, CliElementType typeCode) throws IOException {super(typeCode);// TODO: MethodDef and MethodRef sig need to have static isX(reader) methods so I can tell the difference//sig = new CliSigMethodRef(blob); // MethodRef is just Def plus possible sentinel and minus potential XORed args in the first byte@@ -396,8 +418,7 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentableprivate int countSizeBytes;private List<CliSigType> argTypes = new ArrayList<>();- public CliTypeGenericInst(BinaryReader reader, CliElementType typeCode)- throws IOException {+ public CliTypeGenericInst(BinaryReader reader, CliElementType typeCode) throws IOException {super(typeCode);firstType = CliElementType.fromInt(reader.readNextByte()); // Should be Class or ValueTypelong origIndex = reader.getPointerIndex();@@ -421,20 +442,23 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentableString argTypesRep = "";for (int i = 0; i < genArgCount; i++) {argTypesRep += argTypes.get(i).getRepresentation();- if (i != genArgCount - 1)+ if (i != genArgCount - 1) {argTypesRep += ", ";+ }}String typeRep = Integer.toHexString(encodedType);if (stream != null) {try {CliAbstractTableRow row =- stream.getTable(CliIndexTypeDefOrRef.getTableName(encodedType)).getRow(- CliIndexTypeDefOrRef.getRowIndex(encodedType));- if (shortRep)+ stream.getTable(CliIndexTypeDefOrRef.getTableName(encodedType))+ .getRow(CliIndexTypeDefOrRef.getRowIndex(encodedType));+ if (shortRep) {typeRep = row.getShortRepresentation();- else+ }+ else {typeRep = row.getRepresentation();+ }}catch (InvalidInputException e) {e.printStackTrace();@@ -481,11 +505,12 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentableprivate int number;private int numberBytes;- public CliTypeVarOrMvar(BinaryReader reader, CliElementType typeCode)- throws IOException {+ public CliTypeVarOrMvar(BinaryReader reader, CliElementType typeCode) throws IOException {super(typeCode);+long origIndex = reader.getPointerIndex();number = decodeCompressedUnsignedInt(reader);+long endIndex = reader.getPointerIndex();numberBytes = (int) (endIndex - origIndex);}@@ -511,9 +536,11 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentablepublic CliTypePtr(BinaryReader reader, CliElementType typeCode) throws IOException {super(typeCode);+while (CliCustomMod.isCustomMod(reader)) {customMods.add(new CliCustomMod(reader));}+typeCode = CliElementType.fromInt(reader.readNextByte());}@@ -546,26 +573,31 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentablepublic CliTypeSzArray(BinaryReader reader, CliElementType typeCode)throws IOException, InvalidInputException {super(typeCode);+while (CliCustomMod.isCustomMod(reader)) {customMods.add(new CliCustomMod(reader));}+type = readCliType(reader);}@Overridepublic String getRepresentation(CliStreamMetadata stream) {String typeRep;- if (stream == null)+ if (stream == null) {typeRep = type.getRepresentation();- else+ }+ else {typeRep = type.getRepresentation(stream);+ }String modsRep = "";for (CliCustomMod mod : customMods) {modsRep += mod.toString() + ", ";}- if (customMods.size() > 0)+ if (customMods.size() > 0) {modsRep.substring(0, modsRep.length() - 2); // Remove last comma+space+ }return String.format("SzArray %s %s", modsRep, typeRep);}@@ -590,11 +622,12 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentableprivate int encodedType;private int typeBytes;- public CliTypeValueType(BinaryReader reader, CliElementType typeCode)- throws IOException {+ public CliTypeValueType(BinaryReader reader, CliElementType typeCode) throws IOException {super(typeCode);+long origIndex = reader.getPointerIndex();encodedType = decodeCompressedUnsignedInt(reader);+long endIndex = reader.getPointerIndex();typeBytes = (int) (endIndex - origIndex);}@@ -607,8 +640,9 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentablepublic String getRepresentation(CliStreamMetadata stream, boolean shortRep) {try {CliAbstractTableRow row =- stream.getTable(CliIndexTypeDefOrRef.getTableName(encodedType)).getRow(- CliIndexTypeDefOrRef.getRowIndex(encodedType));+ stream.getTable(CliIndexTypeDefOrRef.getTableName(encodedType))+ .getRow(CliIndexTypeDefOrRef.getRowIndex(encodedType));+return "ValueType " +(shortRep ? row.getShortRepresentation() : row.getRepresentation());}@@ -638,13 +672,13 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentable}}- public CliSigType readCliType(BinaryReader reader)- throws IOException, InvalidInputException {+ public CliSigType readCliType(BinaryReader reader) throws IOException, InvalidInputException {byte typeByte = reader.readNextByte();CliElementType typeCode = CliElementType.fromInt(typeByte);- if (typeCode == null)+ if (typeCode == null) {throw new InvalidInputException("TypeCode not found at reader index " +reader.getPointerIndex() + ". Are you in the right place? (" + typeByte + ")");+ }switch (typeCode) {case ELEMENT_TYPE_ARRAY:return new CliTypeArray(reader, typeCode);@@ -690,8 +724,10 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentablepublic CliCustomMod(BinaryReader reader) throws IOException {cmod = CliElementType.fromInt(reader.readNextByte());+long origIndex = reader.getPointerIndex();typeEncoded = decodeCompressedUnsignedInt(reader);+long endIndex = reader.getPointerIndex();sizeOfCount = (int) (endIndex - origIndex);}@@ -756,8 +792,9 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentable}public String getRepresentation() {- if (constraint == CliElementType.ELEMENT_TYPE_PINNED)+ if (constraint == CliElementType.ELEMENT_TYPE_PINNED) {return constraint.toString();+ }return String.format("Invalid Constraint (%s - %x)", constraint.toString(),constraint.id());}@@ -765,6 +802,7 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentablepublic class CliTypeBase implements CliRepresentable {private List<CliCustomMod> customMods = new ArrayList<>();+ private boolean constraint = false;private boolean byRef = false;private CliSigType type;@@ -773,14 +811,25 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentablepublic CliTypeBase(BinaryReader reader, boolean isRetType)throws IOException, InvalidInputException {this.isVoidAllowed = isRetType;++ // Get any custom modifierswhile (CliCustomMod.isCustomMod(reader)) {customMods.add(new CliCustomMod(reader));}- byte nextByte = reader.peekNextByte();- if (nextByte == CliElementType.ELEMENT_TYPE_BYREF.id()) {++ // Check to see if it's a constrained variable+ if (CliConstraint.isConstraint(reader)) {+ constraint = true;+ reader.readNextByte();+ }++ // Check to see if it's a ByRef+ byte byRefCheck = reader.peekNextByte();+ if (byRefCheck == CliElementType.ELEMENT_TYPE_BYREF.id()) {byRef = true;reader.readNextByte();}+type = readCliType(reader);}@@ -796,16 +845,39 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentablereturn byRef;}+ public boolean isConstrained() {+ return constraint;+ }+private String getRepresentationCommon(CliStreamMetadata stream, boolean shortRep) {String rep = "";+for (CliCustomMod mod : customMods) {rep += mod.getRepresentation() + "; ";}- if (customMods.size() > 0)++ if (customMods.size() > 0) {rep = rep.substring(0, rep.length() - 2) + " ";- if (byRef)+ }++ if (constraint) {+ rep += "constrained ";+ }++ if (byRef) {rep += "byref ";- rep += getRepresentationOf(type, stream, shortRep);+ }++ // The one special case value we have is the SENTINEL, which+ // we represent as "..." to denote that VarArgs might be passed+ // after the declared parameters+ if (type.baseTypeCode == CliElementType.ELEMENT_TYPE_SENTINEL) {+ rep = "...";+ }+ else {+ rep += getRepresentationOf(type, stream, shortRep);+ }+return rep;}@@ -831,11 +903,18 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentablepublic DataType getDefinitionDataType() {StructureDataType struct = new StructureDataType(new CategoryPath(PATH), "Type", 0);+for (CliCustomMod mod : customMods) {struct.add(mod.getDefinitionDataType(), "CustomMod", null);}- if (byRef)++ if (constraint) {+ struct.add(BYTE, "CONSTRAINT", "Constrained");+ }++ if (byRef) {struct.add(BYTE, "BYREF", "By reference");+ }struct.add(type.getDefinitionDataType(), "Type", null);return struct;}@@ -905,13 +984,15 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentablenew StructureDataType(new CategoryPath(PATH), "ArrayShape", 0);struct.add(getDataTypeForBytes(rankBytes), "Rank", "Number of dimensions in array");struct.add(getDataTypeForBytes(numSizesBytes), "NumSizes", "Number of sizes to follow");- for (int i = 0; i < sizeBytes.length; i++)+ for (int i = 0; i < sizeBytes.length; i++) {struct.add(getDataTypeForBytes(sizeBytes[i]), "Size" + i, "Coded integer size");+ }struct.add(getDataTypeForBytes(numLoBoundsBytes), "NumLoBounds","Number of lower bounds in array");- for (int i = 0; i < loBoundBytes.length; i++)+ for (int i = 0; i < loBoundBytes.length; i++) {struct.add(getDataTypeForBytes(loBoundBytes[i]), "LoBound" + i,"Coded integer lower bound");+ }return struct;}@@ -919,21 +1000,4 @@ public abstract class CliAbstractSig extends CliBlob implements CliRepresentablereturn "ArrayShapeNotYetRepresented"; // TODO: Give back a pretty representation of ArrayShape}}-- public class CliCustomAttrib {- // TODO: Implement- }-- public class CliFixedArg {- // TODO: Implement- }-- public class CliElem {- // TODO: Implement- }-- public class CliNamedArg {- // TODO: Implement- }-}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliBlobMarshalSpec.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliBlobMarshalSpec.javaindex 1ad20f2f55..abe7e9e225 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliBlobMarshalSpec.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliBlobMarshalSpec.java@@ -22,6 +22,14 @@ import ghidra.app.util.bin.format.pe.cli.blobs.CliAbstractSig.CliElementType;import ghidra.program.model.data.*;public class CliBlobMarshalSpec extends CliBlob {+ private static final int INIT_VALUE = -1;++ private CliNativeType nativeIntrinsic;+ private CliNativeType arrayElemType;+ private int paramNum = INIT_VALUE;+ private int paramNumBytes;+ private int numElem = INIT_VALUE;+ private int numElemBytes;public enum CliNativeType {NATIVE_TYPE_END(0x00),@@ -74,16 +82,18 @@ public class CliBlobMarshalSpec extends CliBlob {NATIVE_TYPE_IINSPECTABLE(0x2e),NATIVE_TYPE_HSTRING(0x2f),- NATIVE_TYPE_MAX(0x50)- ;-+ NATIVE_TYPE_MAX(0x50);+private final int id;+CliNativeType(int id) {this.id = id;}+public int id() {return id;}+public static CliNativeType fromInt(int id) {CliNativeType[] values = CliNativeType.values();for (CliNativeType value : values) {@@ -94,29 +104,20 @@ public class CliBlobMarshalSpec extends CliBlob {return null;}}-+public static class CliNativeTypeDataType extends EnumDataType {-- public final static CliNativeTypeDataType dataType = new CliNativeTypeDataType();-++ public final static CliNativeTypeDataType dataType = new CliNativeTypeDataType();+public CliNativeTypeDataType() {super(new CategoryPath(PATH), "NativeType", 1);- // TODO: specify CategoryPath, etc.+for (CliElementType c : CliElementType.values()) {add(c.toString(), c.id());}}}-- private static final int INIT_VALUE = -1;-- private CliNativeType nativeIntrinsic;- private CliNativeType arrayElemType;- private int paramNum = INIT_VALUE;- private int paramNumBytes;- private int numElem = INIT_VALUE;- private int numElemBytes;-+public CliBlobMarshalSpec(CliBlob blob) throws IOException {super(blob);@@ -125,6 +126,7 @@ public class CliBlobMarshalSpec extends CliBlob {if (nativeIntrinsic == CliNativeType.NATIVE_TYPE_ARRAY ||nativeIntrinsic == CliNativeType.NATIVE_TYPE_FIXEDARRAY) {arrayElemType = CliNativeType.fromInt(reader.readNextByte());+// There is no sentinel other than blob size that indicates whether 0, 1, or 2 compressed unsigned ints followif (contentsSize > 2) {long origIndex = reader.getPointerIndex();@@ -138,7 +140,7 @@ public class CliBlobMarshalSpec extends CliBlob {}}}-+@Overridepublic DataType getContentsDataType() {StructureDataType struct = new StructureDataType(new CategoryPath(PATH), getName(), 0);@@ -146,27 +148,29 @@ public class CliBlobMarshalSpec extends CliBlob {if (arrayElemType != null) {struct.add(CliNativeTypeDataType.dataType, "ArrayElemTyp", null);if (paramNum != INIT_VALUE) {- struct.add(getDataTypeForBytes(paramNumBytes), "ParamNum", "which parameter provides number of elems for this array");+ struct.add(getDataTypeForBytes(paramNumBytes), "ParamNum",+ "which parameter provides number of elems for this array");if (numElem != INIT_VALUE) {- struct.add(getDataTypeForBytes(numElemBytes), "NumElem", "number of elements or additional elements");+ struct.add(getDataTypeForBytes(numElemBytes), "NumElem",+ "number of elements or additional elements");}}}return struct;}-+@Overridepublic String getContentsName() {return "MarshalSpec";}-+@Overridepublic String getContentsComment() {return "Defines a native type for marshalling between managed/unmanaged code";}-+@Override- public String getRepresentation () {+ public String getRepresentation() {return "Blob (" + getContentsDataType().getDisplayName() + ")";}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigField.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigField.javaindex 1835754607..22a4331886 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigField.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigField.java@@ -20,21 +20,26 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.pe.cli.streams.CliStreamMetadata;import ghidra.program.model.data.*;+import ghidra.util.Msg;import ghidra.util.exception.InvalidInputException;public class CliSigField extends CliAbstractSig {- public static final byte identifier = 0x06;-- public CliParam type;-+ private CliParam type;++ private static final byte CLISIGFIELD_PROLOG = 0x06;+public CliSigField(CliBlob blob) throws IOException {super(blob);- // Now read our special data from the blob!BinaryReader reader = getContentsReader();- byte firstByte = reader.readNextByte();- if (firstByte != identifier)- return; // Do something worse than just return?++ byte prolog = reader.readNextByte();+ if (prolog != CLISIGFIELD_PROLOG) {+ Msg.warn(this,+ "CliSigField had unexpected prolog (0x" + Integer.toHexString(prolog) + ").");+ return;+ }+try {type = new CliParam(reader);}@@ -51,14 +56,17 @@ public class CliSigField extends CliAbstractSig {* @throws IOException*/public static boolean isFieldSig(CliBlob blob) throws IOException {- return blob.getContentsReader().readNextByte() == identifier;+ return blob.getContentsReader().readNextByte() == CLISIGFIELD_PROLOG;+ }++ public CliParam getType() {+ return type;}@Overridepublic DataType getContentsDataType() {- StructureDataType struct =- new StructureDataType(new CategoryPath(PATH), getName(), 0);- struct.add(BYTE, "FIELD", "0x06");+ StructureDataType struct = new StructureDataType(new CategoryPath(PATH), getName(), 0);+ struct.add(BYTE, "FIELD", "Magic (0x06)");struct.add(type.getDefinitionDataType(), "Type", null);return struct;}@@ -77,5 +85,5 @@ public class CliSigField extends CliAbstractSig {public String getRepresentationCommon(CliStreamMetadata stream, boolean isShort) {return getRepresentationOf(type, stream, isShort);}-+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigLocalVar.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigLocalVar.javaindex 308cef42ee..53f62a5d75 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigLocalVar.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigLocalVar.java@@ -20,27 +20,34 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.pe.cli.streams.CliStreamMetadata;import ghidra.program.model.data.*;+import ghidra.util.Msg;import ghidra.util.exception.InvalidInputException;public class CliSigLocalVar extends CliAbstractSig {- public static final int identifier = 0x07;-private int sizeOfCount;private CliParam types[];-++ private static final int CLISIGLOCALVAR_PROLOG = 0x07;+public CliSigLocalVar(CliBlob blob) throws IOException {super(blob);- // Now read our special data from the blob!BinaryReader reader = getContentsReader();- byte id = reader.readNextByte();- if (id != identifier)- return; // Freak out? or just return...++ // Check the prolog byte+ byte prolog = reader.readNextByte();+ if (prolog != CLISIGLOCALVAR_PROLOG) {+ Msg.warn(this,+ "LocalVarSig had unexpected prolog (0x" + Integer.toHexString(prolog) + ")");+ return;+ }+long origIndex = reader.getPointerIndex();int typesCount = decodeCompressedUnsignedInt(reader);sizeOfCount = (int) (reader.getPointerIndex() - origIndex);types = new CliParam[typesCount];- // TODO: Does CliParam parse constraints?++ // CliParam will parse modifiers, constraints, and ByRef notationsfor (byte i = 0; i < typesCount; i++) {try {types[i] = new CliParam(reader);@@ -51,7 +58,7 @@ public class CliSigLocalVar extends CliAbstractSig {}}}-+/*** Checks whether this could *possibly* be a LocalVarSig. Only looks at the identifier byte. Useful for signature index* that could be to different kinds of signatures.@@ -60,38 +67,39 @@ public class CliSigLocalVar extends CliAbstractSig {* @throws IOException*/public static boolean isLocalVarSig(CliBlob blob) throws IOException {- return blob.getContentsReader().readNextByte() == identifier;+ return blob.getContentsReader().readNextByte() == CLISIGLOCALVAR_PROLOG;}-+@Overridepublic String getContentsName() {return "LocalVarSig";}-+@Overridepublic String getContentsComment() {return "Contains signature for function locals";}-+@Overridepublic DataType getContentsDataType() {StructureDataType struct = new StructureDataType(new CategoryPath(PATH), getName(), 0);- struct.add(BYTE, "LOCAL_SIG", "Magic, must be 0x07");+ struct.add(BYTE, "LOCAL_SIG", "Magic (0x07)");struct.add(getDataTypeForBytes(sizeOfCount), "Count", "Number of types to follow");for (CliParam param : types) {struct.add(param.getDefinitionDataType(), "Type", null);}return struct;}-+@Overridepublic String getRepresentationCommon(CliStreamMetadata stream, boolean isShort) {String rep = "";for (CliParam param : types) {rep += getRepresentationOf(param, stream, isShort) + ", ";}- if (types.length > 0)+ if (types.length > 0) {rep = rep.substring(0, rep.length() - 2); // remove comma+space+ }return rep;}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigMethodDef.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigMethodDef.javaindex b2b039c54f..6ffb69f5d9 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigMethodDef.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigMethodDef.java@@ -23,25 +23,34 @@ import ghidra.program.model.data.*;import ghidra.util.exception.InvalidInputException;public class CliSigMethodDef extends CliAbstractSig {-+private CliRetType retType;private CliParam params[];private int sizeOfCount;private int genericParamCount;+ private byte flags;private int sizeOfGenericCount;-++ private final int METHODDEFSIG_FLAGS_DEFAULT = 0x00;+ private final int METHODDEFSIG_FLAGS_VARARG = 0x05;+ private final int METHODDEFSIG_FLAGS_GENERIC = 0x10;+ private final int METHODDEFSIG_FLAGS_HASTHIS = 0x20;+ private final int METHODDEFSIG_FLAGS_EXPLICITTHIS = 0x40;+public CliSigMethodDef(CliBlob blob) throws IOException {super(blob);- // Now read our special stuff.+ // Read and determine meaning of flag byteBinaryReader reader = getContentsReader();- byte firstByte = reader.readNextByte();- // firstByte is HASTHIS | EXPLICITTHIS | DEFAULT | VARARG | GENERIC- if ((firstByte & 0x10) == 0x10) { // GENERIC+ flags = reader.readNextByte();++ if ((flags & METHODDEFSIG_FLAGS_GENERIC) == METHODDEFSIG_FLAGS_GENERIC) {long origIndex = reader.getPointerIndex();genericParamCount = decodeCompressedUnsignedInt(reader);sizeOfGenericCount = (int) (reader.getPointerIndex() - origIndex);}++ // Get parameter count and return typelong origIndex = reader.getPointerIndex();int paramCount = decodeCompressedUnsignedInt(reader);this.sizeOfCount = (int) (reader.getPointerIndex() - origIndex);@@ -51,12 +60,15 @@ public class CliSigMethodDef extends CliAbstractSig {catch (InvalidInputException e) {retType = null;}++ // Get parametersparams = new CliParam[paramCount];for (int i = 0; i < paramCount; i++) {try {params[i] = new CliParam(reader);}- catch (InvalidInputException e) { /* Do not add to params() */ }+ catch (InvalidInputException e) {+ /* Do not add to params[] */ }}}@@ -64,7 +76,7 @@ public class CliSigMethodDef extends CliAbstractSig {public String getContentsName() {return "MethodDefSig";}-+@Overridepublic String getContentsComment() {return "Type info for method return and params";@@ -73,38 +85,59 @@ public class CliSigMethodDef extends CliAbstractSig {@Overridepublic DataType getContentsDataType() {StructureDataType struct = new StructureDataType(new CategoryPath(PATH), getName(), 0);- struct.add(BYTE, "FirstByte", "ORed calling convention and THIS presence"); // TODO: enum+ struct.add(BYTE, "flags", "ORed calling convention and THIS presence"); // TODO: enumif (genericParamCount > 0) {struct.add(getDataTypeForBytes(sizeOfGenericCount), "GenParamCount",- "Number of generic paramameters for the method");+ "Number of generic paramameters for the method");}- struct.add(getDataTypeForBytes(sizeOfCount), "Count", "Number of param types to follow RetType");+ struct.add(getDataTypeForBytes(sizeOfCount), "Count",+ "Number of param types to follow RetType");struct.add(retType.getDefinitionDataType(), "RetType", null);- for (CliParam param : params)+ for (CliParam param : params) {struct.add(param.getDefinitionDataType(), null, null);+ }return struct;}public CliRetType getReturnType() {return retType;}-+public CliParam[] getParamTypes() {return params.clone();}+ public boolean hasThis() {+ return (flags & METHODDEFSIG_FLAGS_HASTHIS) == METHODDEFSIG_FLAGS_HASTHIS;+ }++ public boolean hasExplicitThis() {+ return (flags & METHODDEFSIG_FLAGS_EXPLICITTHIS) == METHODDEFSIG_FLAGS_EXPLICITTHIS;+ }++ public boolean hasVarArgs() {+ return (flags & METHODDEFSIG_FLAGS_VARARG) == METHODDEFSIG_FLAGS_VARARG;+ }++ public Boolean hasGenericArgs() {+ return (flags & METHODDEFSIG_FLAGS_GENERIC) == METHODDEFSIG_FLAGS_GENERIC;+ }++ @Overrideprotected String getRepresentationCommon(CliStreamMetadata stream, boolean isShort) {String rep = getRepresentationOf(retType, stream, isShort);rep += " fn(";for (CliParam param : params) {- if (param == null)+ if (param == null) {rep += "unidentified_param_type, ";+ }else {rep += getRepresentationOf(param, stream, isShort) + ", ";}}- if (params.length > 0)- rep = rep.substring(0, rep.length()-2); // Take off last comma+space+ if (params.length > 0) {+ rep = rep.substring(0, rep.length() - 2); // Take off last comma+space+ }rep += ")";return rep;}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigMethodRef.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigMethodRef.javaindex b5394d8b6c..366e6674fb 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigMethodRef.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigMethodRef.java@@ -23,27 +23,26 @@ import ghidra.program.model.data.*;import ghidra.util.exception.InvalidInputException;public class CliSigMethodRef extends CliAbstractSig {-+private CliRetType retType;private CliParam params[];private int sizeOfCount;- private int genericParamCount;- private int sizeOfGenericCount;+ private byte flags;private int sentinelIndex; // SENTINEL is before the parameter index in this field-++ private final int METHODREFSIG_FLAGS_DEFAULT = 0x00;+ private final int METHODREFSIG_FLAGS_VARARG = 0x05;+ private final int METHODREFSIG_FLAGS_HASTHIS = 0x20;+ private final int METHODREFSIG_FLAGS_EXPLICITTHIS = 0x40;+public CliSigMethodRef(CliBlob blob) throws IOException {super(blob);sentinelIndex = -1;- // Now read our special stuff. Looks like a MethodDef unless vararg is used.+ // Flags is similar to a MethodDef unless vararg is used.BinaryReader reader = getContentsReader();- byte firstByte = reader.readNextByte();- // firstByte is HASTHIS | EXPLICITTHIS | DEFAULT | VARARG | GENERIC- if ((firstByte & 0x10) == 0x10) { // GENERIC- long origIndex = reader.getPointerIndex();- genericParamCount = decodeCompressedUnsignedInt(reader);- sizeOfGenericCount = (int) (reader.getPointerIndex() - origIndex);- }+ flags = reader.readNextByte();+long origIndex = reader.getPointerIndex();int paramCount = decodeCompressedUnsignedInt(reader);this.sizeOfCount = (int) (reader.getPointerIndex() - origIndex);@@ -55,7 +54,7 @@ public class CliSigMethodRef extends CliAbstractSig {}params = new CliParam[paramCount];for (int i = 0; i < paramCount; i++) {- if (reader.peekNextByte() == CliElementType.ELEMENT_TYPE_SENTINAL.id()) {+ if (reader.peekNextByte() == CliElementType.ELEMENT_TYPE_SENTINEL.id()) {reader.readNextByte();sentinelIndex = i;}@@ -72,7 +71,7 @@ public class CliSigMethodRef extends CliAbstractSig {public String getContentsName() {return "MethodRefSig";}-+@Overridepublic String getContentsComment() {return "Type info for imported method return and params";@@ -81,15 +80,12 @@ public class CliSigMethodRef extends CliAbstractSig {@Overridepublic DataType getContentsDataType() {StructureDataType struct = new StructureDataType(new CategoryPath(PATH), getName(), 0);- struct.add(BYTE, "FirstByte", "ORed VARARG and HASTHIS/EXPLICITTHIS");- if (genericParamCount > 0) {- struct.add(getDataTypeForBytes(sizeOfGenericCount), "GenParamCount",- "Number of generic paramameters for the method");- }- struct.add(getDataTypeForBytes(sizeOfCount), "ParamCount", "Number of param types to follow RetType");+ struct.add(BYTE, "flags", "ORed VARARG and HASTHIS/EXPLICITTHIS");+ struct.add(getDataTypeForBytes(sizeOfCount), "ParamCount",+ "Number of param types to follow RetType");struct.add(retType.getDefinitionDataType(), "RetType", null);for (int i = 0; i < params.length; i++) {- struct.add(params[i].getDefinitionDataType(), "Type"+i, null);+ struct.add(params[i].getDefinitionDataType(), "Type" + i, null);}return struct;}@@ -97,26 +93,41 @@ public class CliSigMethodRef extends CliAbstractSig {public CliRetType getReturnType() {return retType;}-+public CliParam[] getParams() {return params.clone();}-++ public boolean hasThis() {+ return (flags & METHODREFSIG_FLAGS_HASTHIS) == METHODREFSIG_FLAGS_HASTHIS;+ }++ public boolean hasExplicitThis() {+ return (flags & METHODREFSIG_FLAGS_EXPLICITTHIS) == METHODREFSIG_FLAGS_EXPLICITTHIS;+ }++ public boolean hasVarArgs() {+ return (flags & METHODREFSIG_FLAGS_VARARG) == METHODREFSIG_FLAGS_VARARG;+ }+@Overrideprotected String getRepresentationCommon(CliStreamMetadata stream, boolean isShort) {String rep = getRepresentationOf(retType, stream, isShort);rep += " fn(";- // TODO: Display SENTINEL as "..."+for (CliParam param : params) {- if (param == null)+ if (param == null) {rep += "unidentified_param_type, ";- else+ }+ else {rep += getRepresentationOf(param, stream, isShort) + ", ";+ }+ }+ if (params.length > 0) {+ rep = rep.substring(0, rep.length() - 2); // Take off last comma+space}- if (params.length > 0)- rep = rep.substring(0, rep.length()-2); // Take off last comma+spacerep += ")";return rep;}-+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigMethodSpec.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigMethodSpec.javaindex 81be1ccef4..2ff3fe1a61 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigMethodSpec.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigMethodSpec.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -20,27 +20,33 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.pe.cli.streams.CliStreamMetadata;import ghidra.program.model.data.*;+import ghidra.util.Msg;import ghidra.util.exception.InvalidInputException;public class CliSigMethodSpec extends CliAbstractSig {-- public static final byte identifier = 0x0a;-- private byte firstByte;private int genArgCount;private int genArgCountBytes;private CliSigType types[];-++ private static final byte CLISIGMETHODSPEC_PROLOG = 0x0A;+public CliSigMethodSpec(CliBlob blob) throws IOException {super(blob);BinaryReader reader = getContentsReader();- firstByte = reader.readNextByte();- if (firstByte != identifier)- return; // TODO: Do something worse?++ // Check that the identifier is correct+ byte prolog = reader.readNextByte();+ if (prolog != CLISIGMETHODSPEC_PROLOG) {+ Msg.warn(this,+ "MethodSpec had unexpected prolog (0x" + Integer.toHexString(prolog) + ").");+ return;+ }+long origIndex = reader.getPointerIndex();genArgCount = decodeCompressedUnsignedInt(reader);genArgCountBytes = (int) (reader.getPointerIndex() - origIndex);+types = new CliSigType[genArgCount];for (int i = 0; i < genArgCount; i++) {try {@@ -56,7 +62,7 @@ public class CliSigMethodSpec extends CliAbstractSig {public String getContentsName() {return "MethodSpecSig";}-+@Overridepublic String getContentsComment() {return "Specifies a generic method with GenArgCount types";@@ -65,10 +71,11 @@ public class CliSigMethodSpec extends CliAbstractSig {@Overridepublic DataType getContentsDataType() {StructureDataType struct = new StructureDataType(new CategoryPath(PATH), getName(), 0);- struct.add(BYTE, "GenericInstByte", "GenericInst");- struct.add(getDataTypeForBytes(genArgCountBytes), "GenArgCount", "Number types to follow");+ struct.add(BYTE, "GENRICINST", "Magic (0x0a)");+ struct.add(getDataTypeForBytes(genArgCountBytes), "GenArgCount",+ "Number of types to follow");for (int i = 0; i < types.length; i++) {- struct.add(types[i].getDefinitionDataType(), "Type"+i, null);+ struct.add(types[i].getDefinitionDataType(), "Type" + i, null);}return struct;}@@ -77,15 +84,18 @@ public class CliSigMethodSpec extends CliAbstractSig {public String getRepresentationCommon(CliStreamMetadata stream, boolean isShort) {String typesRep = "";for (CliSigType type : types) {- if (type == null)+ if (type == null) {typesRep += "unidentified_param_type, ";- else+ }+ else {typesRep += getRepresentationOf(type, stream, isShort) + ", ";+ }+ }+ if (types.length > 0) {+ typesRep = typesRep.substring(0, typesRep.length() - 2); // Take off last comma+space}- if (types.length > 0)- typesRep = typesRep.substring(0, typesRep.length()-2); // Take off last comma+spaceString rep = String.format("GenericInst %d %s", genArgCount, typesRep);return rep;}-+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigProperty.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigProperty.javaindex 9fd82c46bc..26dae7b67c 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigProperty.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigProperty.java@@ -20,30 +20,45 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.format.pe.cli.streams.CliStreamMetadata;import ghidra.program.model.data.*;+import ghidra.util.Msg;import ghidra.util.exception.InvalidInputException;public class CliSigProperty extends CliAbstractSig {private int sizeOfCount;+ private byte flags;private CliRetType returnType;private CliParam params[];-++ private final int CLISIGPROPERTY_PROLOG = 0x08;+ private final int CLISIGPROPERTY_FLAGS_HASTHIS = 0x20;+public CliSigProperty(CliBlob blob) throws IOException {super(blob);- // Now read our special data from the blob!BinaryReader reader = getContentsReader();- byte firstByte = reader.readNextByte();- if ((firstByte & 0x08) != 0x08)- return; // Do something worse than just return?++ // Check for the prolog value and interpret any flags present+ flags = reader.readNextByte();+ if ((flags & CLISIGPROPERTY_PROLOG) != CLISIGPROPERTY_PROLOG) {+ Msg.warn(this,+ "PropertySig had unexpected prolog (0x" + Integer.toHexString(flags) + ")");+ return;+ }++ // Remove the prolog bit, leaving only HASTHIS if present+ flags ^= CLISIGPROPERTY_PROLOG;+long origIndex = reader.getPointerIndex();int paramsCount = decodeCompressedUnsignedInt(reader);this.sizeOfCount = (int) (reader.getPointerIndex() - origIndex);+try {returnType = new CliRetType(reader);}catch (InvalidInputException e) {returnType = null;}+params = new CliParam[paramsCount];for (int i = 0; i < paramsCount; i++) {try {@@ -55,25 +70,30 @@ public class CliSigProperty extends CliAbstractSig {}}}-++ public boolean hasThis() {+ return (flags & CLISIGPROPERTY_FLAGS_HASTHIS) == CLISIGPROPERTY_FLAGS_HASTHIS;+ }+@Overridepublic String getContentsName() {return "PropertySig";}-+@Overridepublic String getContentsComment() {return "Contains signature for properties. Gives params for getters/setters.";}-+@Overridepublic DataType getContentsDataType() {StructureDataType struct = new StructureDataType(new CategoryPath(PATH), getName(), 0);- struct.add(BYTE, "PROPERTY", "must be 0x08 or 0x28. ORed 0x20=HASTHIS and 0x08=PROPERTY");+ struct.add(BYTE, "PROPERTY", "Magic (0x08) optionalled OR'd with HASTHIS (0x20)");struct.add(getDataTypeForBytes(sizeOfCount), "Count", "Number of params to follow RetType");struct.add(returnType.getDefinitionDataType(), "RetType", "Return type");- for (CliParam param : params)+ for (CliParam param : params) {struct.add(param.getDefinitionDataType(), "Param", null);+ }return struct;}@@ -83,9 +103,11 @@ public class CliSigProperty extends CliAbstractSig {for (CliParam param : params) {paramsStr += getRepresentationOf(param, stream, isShort) + ", ";}- if (params.length > 0)+ if (params.length > 0) {paramsStr = paramsStr.substring(0, paramsStr.length() - 2); // remove comma+space- return String.format("%s get(%s)", getRepresentationOf(returnType, stream, isShort), paramsStr);+ }+ return String.format("%s get(%s)", getRepresentationOf(returnType, stream, isShort),+ paramsStr);}-+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigStandAloneMethod.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigStandAloneMethod.javaindex 204685aeee..6af6d66dc2 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigStandAloneMethod.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigStandAloneMethod.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -23,34 +23,51 @@ import ghidra.program.model.data.*;import ghidra.util.exception.InvalidInputException;public class CliSigStandAloneMethod extends CliAbstractSig {-+private CliRetType retType;private CliParam params[];+ private byte flags;private int sizeOfCount;private int sentinelIndex; // SENTINEL is before the parameter index in this field-- // TODO: Note: The only difference between this and the MethodRefSig is the number of args that can be included in the first byte-++ // Note: The only difference between this and the MethodRefSig is the number of+ // values that can be included in the first byte++ private final int STANDALONEMETHODSIG_FLAGS_DEFAULT = 0x0;+ private final int STANDALONEMETHODSIG_FLAGS_HASTHIS = 0x20;+ private final int STANDALONEMETHODSIG_FLAGS_EXPLICITTHIS = 0x40;+ private final int STANDALONEMETHODSIG_FLAGS_VARARG = 0x5;+ private final int STANDALONEMETHODSIG_FLAGS_C = 0x01;+ private final int STANDALONEMETHODSIG_FLAGS_STDCALL = 0x02;+ private final int STANDALONEMETHODSIG_FLAGS_THISCALL = 0x03;+ private final int STANDALONEMETHODSIG_FLAGS_FASTCALL = 0x04;++ public enum CallingConvention {+ MANAGED, C, STDCALL, THISCALL, FASTCALL+ }+public CliSigStandAloneMethod(CliBlob blob) throws IOException {super(blob);sentinelIndex = -1;- // Now read our special stuff.+ // Read the flagsBinaryReader reader = getContentsReader();- byte firstByte = reader.readNextByte();- // firstByte is HASTHIS | EXPLICITTHIS | (VARARG | VARARG | C | STDCALL | THISCALL | FASTCALL)+ flags = reader.readNextByte();+long origIndex = reader.getPointerIndex();int paramCount = decodeCompressedUnsignedInt(reader);this.sizeOfCount = (int) (reader.getPointerIndex() - origIndex);+try {retType = new CliRetType(reader);}catch (InvalidInputException e) {retType = null;}+params = new CliParam[paramCount];for (int i = 0; i < paramCount; i++) {- if (reader.peekNextByte() == CliElementType.ELEMENT_TYPE_SENTINAL.id()) {+ if (reader.peekNextByte() == CliElementType.ELEMENT_TYPE_SENTINEL.id()) {reader.readNextByte();sentinelIndex = i;}@@ -59,7 +76,7 @@ public class CliSigStandAloneMethod extends CliAbstractSig {}catch (InvalidInputException e) {params[i] = null;- }+ }}}@@ -67,7 +84,7 @@ public class CliSigStandAloneMethod extends CliAbstractSig {public String getContentsName() {return "StandAloneMethodSig";}-+@Overridepublic String getContentsComment() {return "Typically for calli instruction; Type info for method return and params";@@ -76,34 +93,77 @@ public class CliSigStandAloneMethod extends CliAbstractSig {@Overridepublic DataType getContentsDataType() {StructureDataType struct = new StructureDataType(new CategoryPath(PATH), getName(), 0);- struct.add(BYTE, "FirstByte", "ORed VARARG/DEFAULT/C/STDCALL/THISCALL/FASTCALL and HASTHIS/EXPLICITTHIS");- struct.add(getDataTypeForBytes(sizeOfCount), "Count", "Number of param types to follow RetType");+ struct.add(BYTE, "flags",+ "ORed VARARG/DEFAULT/C/STDCALL/THISCALL/FASTCALL and HASTHIS/EXPLICITTHIS");+ struct.add(getDataTypeForBytes(sizeOfCount), "Count",+ "Number of param types to follow RetType");struct.add(retType.getDefinitionDataType(), "RetType", null);- for (CliParam param : params)+ for (CliParam param : params) {struct.add(param.getDefinitionDataType(), null, null);+ }return struct;}public CliRetType getReturnType() {return retType;}-+public CliParam[] getParams() {return params.clone();}-++ public boolean hasThis() {+ return (flags & STANDALONEMETHODSIG_FLAGS_HASTHIS) == STANDALONEMETHODSIG_FLAGS_HASTHIS;+ }++ public boolean hasExplicitThis() {+ return (flags &+ STANDALONEMETHODSIG_FLAGS_EXPLICITTHIS) == STANDALONEMETHODSIG_FLAGS_EXPLICITTHIS;+ }++ public boolean hasVarArgs() {+ return (flags & STANDALONEMETHODSIG_FLAGS_VARARG) == STANDALONEMETHODSIG_FLAGS_VARARG;+ }++ public CallingConvention getCallingConvention() {+ if ((flags & STANDALONEMETHODSIG_FLAGS_C) == STANDALONEMETHODSIG_FLAGS_C) {+ // cdecl+ return CallingConvention.C;+ }+ else if ((flags & STANDALONEMETHODSIG_FLAGS_STDCALL) == STANDALONEMETHODSIG_FLAGS_STDCALL) {+ // stdcall+ return CallingConvention.STDCALL;+ }+ else if ((flags &+ STANDALONEMETHODSIG_FLAGS_THISCALL) == STANDALONEMETHODSIG_FLAGS_THISCALL) {+ // ecx/rcx is this pointer+ return CallingConvention.THISCALL;+ }+ else if ((flags &+ STANDALONEMETHODSIG_FLAGS_FASTCALL) == STANDALONEMETHODSIG_FLAGS_FASTCALL) {+ // ecx/rcx and edx/rdx are the first two parameters, standard x64 convention+ return CallingConvention.FASTCALL;+ }++ // Managed code call+ return CallingConvention.MANAGED;+ }+@Overridepublic String getRepresentationCommon(CliStreamMetadata stream, boolean isShort) {String rep = getRepresentationOf(retType, stream, isShort) + " fn(";- // TODO: Display SENTINEL as "..."+for (CliParam param : params) {- if (param == null)+ if (param == null) {rep += "unidentified_param_type, ";- else+ }+ else {rep += getRepresentationOf(param, stream, isShort) + ", ";+ }+ }+ if (params.length > 0) {+ rep = rep.substring(0, rep.length() - 2); // Take off last comma+space}- if (params.length > 0)- rep = rep.substring(0, rep.length()-2); // Take off last comma+spacerep += ")";return rep;}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigTypeSpec.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigTypeSpec.javaindex 170b1bccc0..5477b0c179 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigTypeSpec.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/blobs/CliSigTypeSpec.java@@ -24,9 +24,10 @@ import ghidra.util.exception.InvalidInputException;public class CliSigTypeSpec extends CliAbstractSig {public CliSigType type;-+public CliSigTypeSpec(CliBlob blob) throws IOException {super(blob);+try {type = readCliType(blob.getContentsReader());}@@ -34,17 +35,17 @@ public class CliSigTypeSpec extends CliAbstractSig {type = null;}}-+@Overridepublic String getContentsName() {return "TypeSpec";}-+@Overridepublic String getContentsComment() {return "Describes a type.";}-+@Overridepublic DataType getContentsDataType() {return type.getDefinitionDataType();@@ -52,6 +53,6 @@ public class CliSigTypeSpec extends CliAbstractSig {@Overridepublic String getRepresentationCommon(CliStreamMetadata stream, boolean isShort) {- return "TypeSpec: "+getRepresentationOf(type, stream, isShort);+ return "TypeSpec: " + getRepresentationOf(type, stream, isShort);}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/methods/CliMethodExtraSections.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/methods/CliMethodExtraSections.javaindex a74fce900d..5c95fd1607 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/methods/CliMethodExtraSections.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/methods/CliMethodExtraSections.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -25,116 +25,137 @@ import ghidra.program.model.data.*;import ghidra.util.exception.DuplicateNameException;public class CliMethodExtraSections implements StructConverter {-+public static final String PATH = "/PE/CLI/Methods/ExtraSections";-- private List<ExtraSection> extraSections = new ArrayList<ExtraSection>();-++ private List<ExtraSection> extraSections = new ArrayList<>();+private class ExtraSection {public boolean isEHTable;public boolean isFat;public boolean hasMoreSections;public int dataSize;public boolean isFilterBasedException;-+public static final int CorILMethod_Sect_EHTable = 0x1;public static final int CorILMethod_Sect_OptIL = 0x2;public static final int CorILMethod_Sect_FatFormat = 0x40;public static final int CorILMethod_Sect_MoreSects = 0x80;-+public static final short COR_ILEXCEPTION_CLAUSE_EXCEPTION = 0x0000;- public static final short COR_ILEXCEPTION_CLAUSE_FILTER = 0x0001;+ public static final short COR_ILEXCEPTION_CLAUSE_FILTER = 0x0001;public static final short COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002;public static final short COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004;-+public ExtraSection(BinaryReader reader) throws IOException {- byte one = reader.readNextByte();- if ((one & CorILMethod_Sect_EHTable) == CorILMethod_Sect_EHTable)- isEHTable = true;- if ((one & CorILMethod_Sect_FatFormat) == CorILMethod_Sect_FatFormat)- isFat = true;- if ((one & CorILMethod_Sect_MoreSects) == CorILMethod_Sect_MoreSects)- hasMoreSections = true;-+ byte sectionFlags = reader.readNextByte();+ isEHTable = (sectionFlags & CorILMethod_Sect_EHTable) == CorILMethod_Sect_EHTable;+ isFat = ((sectionFlags & CorILMethod_Sect_FatFormat) == CorILMethod_Sect_FatFormat);+ hasMoreSections =+ ((sectionFlags & CorILMethod_Sect_MoreSects) == CorILMethod_Sect_MoreSects);+// Read sizeif (isFat) {- byte sizeOne = reader.readNextByte();- short sizeTwoThree = reader.readNextShort();- dataSize = (sizeTwoThree << 8) + (sizeOne & 0xff); // this seems counterintuitive but it looks like they're ordering bytes like this+ // This seems counterintuitive but it looks like they're ordering bytes like this+ byte firstSize = reader.readNextByte();+ short secondThirdSize = reader.readNextShort();+ dataSize = (secondThirdSize << 8) + (firstSize & 0xff);}- else+ else {dataSize = reader.readNextByte();-+ }+// Read Flags for exception handlersif (isFat) {- int flags = reader.readNextInt();- isFilterBasedException = ((flags & COR_ILEXCEPTION_CLAUSE_FILTER) == COR_ILEXCEPTION_CLAUSE_FILTER);+ int exceptionHandlingFlags = reader.readNextInt();+ isFilterBasedException = ((exceptionHandlingFlags &+ COR_ILEXCEPTION_CLAUSE_FILTER) == COR_ILEXCEPTION_CLAUSE_FILTER);}else {- short flags = reader.readNextShort();- isFilterBasedException = ((flags & COR_ILEXCEPTION_CLAUSE_FILTER) == COR_ILEXCEPTION_CLAUSE_FILTER);+ short exceptionHandlingFlags = reader.readNextShort();+ isFilterBasedException = ((exceptionHandlingFlags &+ COR_ILEXCEPTION_CLAUSE_FILTER) == COR_ILEXCEPTION_CLAUSE_FILTER);}}-+public StructureDataType getSmallExceptionClauseDataType() {- StructureDataType struct = new StructureDataType(new CategoryPath(PATH), "SmallExceptionHandlerClause", 0);+ StructureDataType struct =+ new StructureDataType(new CategoryPath(PATH), "SmallExceptionHandlerClause", 0);struct.add(WORD, "Flags", "COR_ILEXCEPTION_CLAUSE_*"); // TODO: explain flagsstruct.add(WORD, "TryOffset", "Offset in bytes of try block from start of header");struct.add(BYTE, "TryLength", "Length in bytes of try block");struct.add(WORD, "HandlerOffset", "Location of handler for this try block");struct.add(BYTE, "HandlerLength", "Size of handler code in bytes");- if (isFilterBasedException)- struct.add(DWORD, "FilterOffset", "Offset in method body for filter-based exception handler");- else+ if (isFilterBasedException) {+ struct.add(DWORD, "FilterOffset",+ "Offset in method body for filter-based exception handler");+ }+ else {struct.add(DWORD, "ClassToken", "Metadata token for type-based exception handler");+ }return struct;}public StructureDataType getFatExceptionClauseDataType() {- StructureDataType struct = new StructureDataType(new CategoryPath(PATH), "FatExceptionHandlerClause", 0);+ StructureDataType struct =+ new StructureDataType(new CategoryPath(PATH), "FatExceptionHandlerClause", 0);struct.add(DWORD, "Flags", "COR_ILEXCEPTION_CLAUSE_*"); // TODO: explain flagsstruct.add(DWORD, "TryOffset", "Offset in bytes of try block from start of header");struct.add(DWORD, "TryLength", "Length in bytes of try block");struct.add(DWORD, "HandlerOffset", "Location of handler for this try block");struct.add(DWORD, "HandlerLength", "Size of handler code in bytes");- if (isFilterBasedException)- struct.add(DWORD, "FilterOffset", "Offset in method body for filter-based exception handler");- else+ if (isFilterBasedException) {+ struct.add(DWORD, "FilterOffset",+ "Offset in method body for filter-based exception handler");+ }+ else {struct.add(DWORD, "ClassToken", "Metadata token for type-based exception handler");+ }return struct;}-+public DataType toDataType() {- int clauseSize = (isFat ? 24 : 12);- int numberClauses = (dataSize - 4) / clauseSize;- StructureDataType struct = new StructureDataType(new CategoryPath(PATH), "ExtraSection", 0);+ // Default to skinny clause size+ int clauseSize = 12;+ if (isFat) {+ clauseSize = 24;+ }++ int numberClauses = (dataSize - 4) / clauseSize;+ StructureDataType struct =+ new StructureDataType(new CategoryPath(PATH), "ExtraSection", 0);struct.add(BYTE, "Kind", "flags: EH, OptIL, FatFormat, MoreSects"); // TODO: explain flagsif (isFat) {struct.add(BYTE, "size byte 1", "first byte");struct.add(WORD, "size bytes 2-3", "size continued. n*24+4 clauses follow.");- struct.add(new ArrayDataType(getFatExceptionClauseDataType(), numberClauses, clauseSize), "Clauses", null);+ struct.add(+ new ArrayDataType(getFatExceptionClauseDataType(), numberClauses, clauseSize),+ "Clauses", null);}else {struct.add(BYTE, "DataSize", "section size inc. header; n*12+4 clauses follow");struct.add(WORD, "Padding", "always 0");- struct.add(new ArrayDataType(getSmallExceptionClauseDataType(), numberClauses, clauseSize), "Clauses", null);+ struct.add(+ new ArrayDataType(getSmallExceptionClauseDataType(), numberClauses, clauseSize),+ "Clauses", null);}return struct;}}-+public CliMethodExtraSections(BinaryReader reader) throws IOException {- while (true) {- ExtraSection section = new ExtraSection(reader);+ ExtraSection section;+ do {+ section = new ExtraSection(reader);extraSections.add(section);- if (!section.hasMoreSections)- break;}+ while (section.hasMoreSections);}@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {- StructureDataType struct = new StructureDataType(new CategoryPath(PATH), "ExtraSections", 0);+ StructureDataType struct =+ new StructureDataType(new CategoryPath(PATH), "ExtraSections", 0);for (ExtraSection section : extraSections) {struct.add(section.toDataType(), "ExtraSection", null);}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/streams/CliStreamMetadata.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/streams/CliStreamMetadata.javaindex 93b77a72b3..65d8faf138 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/streams/CliStreamMetadata.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/streams/CliStreamMetadata.java@@ -39,7 +39,7 @@ import ghidra.util.task.TaskMonitor;* @see CliTypeTable*/public class CliStreamMetadata extends CliAbstractStream {-+private byte majorVersion;private byte minorVersion;private byte heapSizes;@@ -47,7 +47,7 @@ public class CliStreamMetadata extends CliAbstractStream {private long sorted;private HashMap<CliTypeTable, Integer> rows;private ArrayList<CliAbstractTable> tables = new ArrayList<>();-+private CliStreamGuid guidStream;private CliStreamUserStrings userStringsStream;private CliStreamStrings stringsStream;@@ -89,7 +89,7 @@ public class CliStreamMetadata extends CliAbstractStream {this.stringsStream = stringsStream;this.blobStream = blobStream;}-+@Overridepublic boolean parse() throws IOException {reader.setPointerIndex(offset);@@ -130,7 +130,7 @@ public class CliStreamMetadata extends CliAbstractStream {return true;}-+/*** Gets the GUID stream.*@@ -179,34 +179,34 @@ public class CliStreamMetadata extends CliAbstractStream {switch (tableType) {case Module:return new CliTableModule(reader, this, tableType);-+case TypeRef:return new CliTableTypeRef(reader, this, tableType);-+case TypeDef:return new CliTableTypeDef(reader, this, tableType);-+case Field:return new CliTableField(reader, this, tableType);-+case MethodDef:return new CliTableMethodDef(reader, this, tableType);-+case Param:return new CliTableParam(reader, this, tableType);-+case InterfaceImpl:return new CliTableInterfaceImpl(reader, this, tableType);-+case MemberRef:return new CliTableMemberRef(reader, this, tableType);-+case Constant:return new CliTableConstant(reader, this, tableType);-+case CustomAttribute:return new CliTableCustomAttribute(reader, this, tableType);-+case FieldMarshal:return new CliTableFieldMarshall(reader, this, tableType);@@ -284,7 +284,7 @@ public class CliStreamMetadata extends CliAbstractStream {case GenericParam:return new CliTableGenericParam(reader, this, tableType);-+case MethodSpec:return new CliTableMethodSpec(reader, this, tableType);@@ -297,7 +297,7 @@ public class CliStreamMetadata extends CliAbstractStream {return null;}}-+/*** Gets the major version.*@@ -357,7 +357,7 @@ public class CliStreamMetadata extends CliAbstractStream {return null;}-+/*** Gets the table with the provided table type id from the metadata stream.*@@ -367,7 +367,7 @@ public class CliStreamMetadata extends CliAbstractStream {public CliAbstractTable getTable(int tableId) {return getTable(CliTypeTable.fromId(tableId));}-+/*** Gets the number of rows in the table with the given table type.*@@ -377,9 +377,9 @@ public class CliStreamMetadata extends CliAbstractStream {*/public int getNumberRowsForTable(CliTypeTable tableType) {Integer ret = rows.get(tableType);- return (ret != null) ? ret : 0;+ return (ret != null) ? ret : 0;}-+/*** Gets the data type of the index into the string stream. Will be either* {@link DWordDataType} or {@link WordDataType}.@@ -389,7 +389,7 @@ public class CliStreamMetadata extends CliAbstractStream {public DataType getStringIndexDataType() {return ((heapSizes & 0x01) != 0) ? DWordDataType.dataType : WordDataType.dataType;}-+/*** Gets the data type of the index into the GUID stream. Will be either* {@link DWordDataType} or {@link WordDataType}.@@ -399,7 +399,7 @@ public class CliStreamMetadata extends CliAbstractStream {public DataType getGuidIndexDataType() {return ((heapSizes & 0x02) != 0) ? DWordDataType.dataType : WordDataType.dataType;}-+/*** Gets the data type of the index into the Blob stream. Will be either* {@link DWordDataType} or {@link WordDataType}.@@ -409,7 +409,7 @@ public class CliStreamMetadata extends CliAbstractStream {public DataType getBlobIndexDataType() {return ((heapSizes & 0x04) != 0) ? DWordDataType.dataType : WordDataType.dataType;}-+/*** Gets the data type of the index into a metadata table. Will be either* {@link DWordDataType} or {@link WordDataType}.@@ -427,11 +427,12 @@ public class CliStreamMetadata extends CliAbstractStream {super.markup(program, isBinary, monitor, log, ntHeader);for (CliAbstractTable table : tables) {try {- table.markup(program, isBinary, monitor, log, ntHeader);Address addr = PeUtils.getMarkupAddress(program, isBinary, ntHeader,rva + getTableOffset(table.getTableType()));- program.getBookmarkManager().setBookmark(addr, BookmarkType.INFO, "CLI Table",- table.toString());+ program.getBookmarkManager()+ .setBookmark(addr, BookmarkType.INFO, "CLI Table", table.toString());++ table.markup(program, isBinary, monitor, log, ntHeader);}catch (Exception e) {Msg.error(this, "Failed to markup " + table);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableField.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableField.javaindex 17bd48c4bb..ec44cf4625 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableField.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableField.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -35,17 +35,17 @@ import ghidra.util.task.TaskMonitor;/*** Describes the Field table. Each row represents a field in a TypeDef class. Fields are stored one after the other, grouped by class.- * References to the Field table encode where the fields for a class start and end.+ * References to the Field table encode where the fields for a class start and end.*/public class CliTableField extends CliAbstractTable {public class CliFieldRow extends CliAbstractTableRow {public short flags;public int nameIndex;public int sigIndex;-+public static final int TYPEDEF_OWNER_INIT_VALUE = -1;public int typeDefOwnerIndex = TYPEDEF_OWNER_INIT_VALUE;-+public CliFieldRow(short flags, int nameIndex, int sigIndex) {super();this.flags = flags;@@ -62,51 +62,57 @@ public class CliTableField extends CliAbstractTable {fieldSig = new CliSigField(sigBlob);sigRep = fieldSig.getShortRepresentation(metadataStream);}- catch (IOException e) {}-+ catch (IOException e) {+ }+String ownerRep;- if (typeDefOwnerIndex == TYPEDEF_OWNER_INIT_VALUE)+ if (typeDefOwnerIndex == TYPEDEF_OWNER_INIT_VALUE) {ownerRep = "";- else+ }+ else {ownerRep = getRowShortRepSafe(CliTypeTable.TypeDef, typeDefOwnerIndex) + "::";-+ }+return String.format("%s %s%s Flags %s", sigRep, ownerRep,metadataStream.getStringsStream().getString(nameIndex),CliEnumFieldAttributes.dataType.getName(flags & 0xffff));}}-- public CliTableField(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {++ public CliTableField(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId)+ throws IOException {super(reader, stream, tableId);CliTableTypeDef typeDefTable =(CliTableTypeDef) metadataStream.getTable(CliTypeTable.TypeDef);for (int i = 0; i < this.numRows; i++) {- CliFieldRow row = new CliFieldRow(reader.readNextShort(), readStringIndex(reader), readBlobIndex(reader));+ CliFieldRow row = new CliFieldRow(reader.readNextShort(), readStringIndex(reader),+ readBlobIndex(reader));rows.add(row);strings.add(row.nameIndex);-+// Figure out owner of this fieldrow.typeDefOwnerIndex = typeDefTable.getOwnerOfFieldIndex(i);}reader.setPointerIndex(this.readerOffset);}-+@Override- public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log, NTHeader ntHeader)+ public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,+ NTHeader ntHeader)throws DuplicateNameException, CodeUnitInsertionException, IOException {for (CliAbstractTableRow row : rows) {CliFieldRow fieldRow = (CliFieldRow) row;- // Handle the signature- Address sigAddr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor, log,- ntHeader, metadataStream.getBlobStream(), fieldRow.sigIndex);- // Create PropertySig object++ // Create FieldSig object and bookmark it+ Address sigAddr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor,+ log, ntHeader, metadataStream.getBlobStream(), fieldRow.sigIndex);+CliSigField fieldSig =new CliSigField(metadataStream.getBlobStream().getBlob(fieldRow.sigIndex));metadataStream.getBlobStream().updateBlob(fieldSig, sigAddr, program);-// program.getBookmarkManager().setBookmark(sigAddr, BookmarkType.INFO, "Signature!", "FieldSig (Offset "+fieldRow.sigIndex+")");}}-+@Overridepublic StructureDataType getRowDataType() {StructureDataType rowDt = new StructureDataType(new CategoryPath(PATH), "Field Row", 0);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableFieldMarshall.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableFieldMarshall.javaindex dd724b76eb..9780abc551 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableFieldMarshall.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableFieldMarshall.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -40,7 +40,7 @@ public class CliTableFieldMarshall extends CliAbstractTable {public class CliFieldMarshallRow extends CliAbstractTableRow {public int parentIndex;public int nativeTypeIndex;-+public CliFieldMarshallRow(int parentIndex, int nativeTypeIndex) {super();this.parentIndex = parentIndex;@@ -51,7 +51,9 @@ public class CliTableFieldMarshall extends CliAbstractTable {public String getRepresentation() {String parentRep;try {- parentRep = getRowRepresentationSafe(CliIndexHasFieldMarshall.getTableName(parentIndex), CliIndexHasFieldMarshall.getRowIndex(parentIndex));+ parentRep =+ getRowRepresentationSafe(CliIndexHasFieldMarshall.getTableName(parentIndex),+ CliIndexHasFieldMarshall.getRowIndex(parentIndex));}catch (InvalidInputException e) {parentRep = Integer.toHexString(parentIndex);@@ -60,36 +62,40 @@ public class CliTableFieldMarshall extends CliAbstractTable {return String.format("Parent %s Native Type %s", parentRep, nativeTypeRep);}}-- public CliTableFieldMarshall(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {++ public CliTableFieldMarshall(BinaryReader reader, CliStreamMetadata stream,+ CliTypeTable tableId) throws IOException {super(reader, stream, tableId);for (int i = 0; i < this.numRows; i++) {- CliFieldMarshallRow row = new CliFieldMarshallRow(CliIndexHasFieldMarshall.readCodedIndex(reader, stream), readBlobIndex(reader));+ CliFieldMarshallRow row = new CliFieldMarshallRow(+ CliIndexHasFieldMarshall.readCodedIndex(reader, stream), readBlobIndex(reader));rows.add(row);}reader.setPointerIndex(this.readerOffset);}-+@Overridepublic StructureDataType getRowDataType() {- StructureDataType rowDt = new StructureDataType(new CategoryPath(PATH), "FieldMarshall Row", 0);+ StructureDataType rowDt =+ new StructureDataType(new CategoryPath(PATH), "FieldMarshall Row", 0);rowDt.add(CliIndexHasFieldMarshall.toDataType(metadataStream), "Parent", null);rowDt.add(metadataStream.getBlobIndexDataType(), "NativeType", null);return rowDt;}-+@Override- public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log, NTHeader ntHeader)+ public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,+ NTHeader ntHeader)throws DuplicateNameException, CodeUnitInsertionException, IOException {for (CliAbstractTableRow row : rows) {Integer nativeTypeIndex = ((CliFieldMarshallRow) row).nativeTypeIndex;Address addr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor, log,ntHeader, metadataStream.getBlobStream(), nativeTypeIndex);- // Create MarshalSpec Blob object and mark it up++ // Create MarshalSpec Blob objectCliBlobMarshalSpec blob =new CliBlobMarshalSpec(metadataStream.getBlobStream().getBlob(nativeTypeIndex));metadataStream.getBlobStream().updateBlob(blob, addr, program);-// program.getBookmarkManager().setBookmark(addr, BookmarkType.INFO, "Signature!", "MarshalSpec/NativeType (Offset "+nativeTypeIndex+")");}}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMemberRef.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMemberRef.javaindex 1ee657dff4..4a0ee2a8dd 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMemberRef.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMemberRef.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -41,18 +41,20 @@ public class CliTableMemberRef extends CliAbstractTable {public int classIndex;public int nameIndex;public int signatureIndex;-+public CliMemberRefRow(int classIndex, int nameIndex, int signatureIndex) {this.classIndex = classIndex;this.nameIndex = nameIndex;this.signatureIndex = signatureIndex;}-+@Overridepublic String getRepresentation() {String classRep;try {- classRep = getRowRepresentationSafe(CliIndexMemberRefParent.getTableName(classIndex), CliIndexMemberRefParent.getRowIndex(classIndex));+ classRep =+ getRowRepresentationSafe(CliIndexMemberRefParent.getTableName(classIndex),+ CliIndexMemberRefParent.getRowIndex(classIndex));}catch (InvalidInputException e) {classRep = Integer.toHexString(classIndex);@@ -69,16 +71,18 @@ public class CliTableMemberRef extends CliAbstractTable {sigRep = methodSig.getRepresentation();}}- catch (IOException e) {}+ catch (IOException e) {+ }return String.format("Class(%s) Member(%s) Signature %s", classRep,metadataStream.getStringsStream().getString(nameIndex), sigRep);}-+@Overridepublic String getRepresentation(CliStreamMetadata stream) {String classRep;try {- classRep = getRowShortRepSafe(CliIndexMemberRefParent.getTableName(classIndex), CliIndexMemberRefParent.getRowIndex(classIndex));+ classRep = getRowShortRepSafe(CliIndexMemberRefParent.getTableName(classIndex),+ CliIndexMemberRefParent.getRowIndex(classIndex));}catch (InvalidInputException e) {classRep = Integer.toHexString(classIndex);@@ -95,50 +99,55 @@ public class CliTableMemberRef extends CliAbstractTable {sigRep = methodSig.getRepresentation();}}- catch (IOException e) {}+ catch (IOException e) {+ }return String.format("%s.%s %s", classRep,stream.getStringsStream().getString(nameIndex), sigRep);}}-- public CliTableMemberRef(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {++ public CliTableMemberRef(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId)+ throws IOException {super(reader, stream, tableId);for (int i = 0; i < this.numRows; i++) {- CliMemberRefRow row = new CliMemberRefRow(CliIndexMemberRefParent.readCodedIndex(reader, stream), readStringIndex(reader), readBlobIndex(reader));+ CliMemberRefRow row =+ new CliMemberRefRow(CliIndexMemberRefParent.readCodedIndex(reader, stream),+ readStringIndex(reader), readBlobIndex(reader));rows.add(row);- strings.add(row.nameIndex);+ strings.add(row.nameIndex);}reader.setPointerIndex(this.readerOffset);}-+@Override- public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log, NTHeader ntHeader)+ public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,+ NTHeader ntHeader)throws DuplicateNameException, CodeUnitInsertionException, IOException {for (CliAbstractTableRow row : rows) {CliMemberRefRow memberRow = (CliMemberRefRow) row;- // Handle the signature- Address sigAddr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor, log,- ntHeader, metadataStream.getBlobStream(), memberRow.signatureIndex);- // Create object for correct kind of sig++ // Get the address and create one of several kinds of *Sig objects+ Address sigAddr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor,+ log, ntHeader, metadataStream.getBlobStream(), memberRow.signatureIndex);+CliBlob sigBlob = metadataStream.getBlobStream().getBlob(memberRow.signatureIndex);if (CliSigField.isFieldSig(sigBlob)) {CliSigField fieldSig = new CliSigField(sigBlob);metadataStream.getBlobStream().updateBlob(fieldSig, sigAddr, program);-// program.getBookmarkManager().setBookmark(sigAddr, BookmarkType.INFO, "Signature!", "FieldSig (Offset "+memberRow.signatureIndex+")");}else {CliSigMethodRef methodSig = new CliSigMethodRef(sigBlob);metadataStream.getBlobStream().updateBlob(methodSig, sigAddr, program);-// program.getBookmarkManager().setBookmark(sigAddr, BookmarkType.INFO, "Signature!", "MethodRefSig (Offset "+memberRow.signatureIndex+")");}}}-+@Overridepublic StructureDataType getRowDataType() {StructureDataType rowDt = new StructureDataType(new CategoryPath(PATH), "MemberRef Row", 0);- rowDt.add(CliIndexMemberRefParent.toDataType(metadataStream), "Class", "index-MemberRefParent coded");+ rowDt.add(CliIndexMemberRefParent.toDataType(metadataStream), "Class",+ "index-MemberRefParent coded");rowDt.add(metadataStream.getStringIndexDataType(), "Name", "index into String heap");rowDt.add(metadataStream.getBlobIndexDataType(), "Signature", "index into Blob heap");return rowDt;diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMethodDef.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMethodDef.javaindex 0194e380cb..763be28323 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMethodDef.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMethodDef.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -23,21 +23,22 @@ import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.MemoryByteProvider;import ghidra.app.util.bin.format.pe.NTHeader;import ghidra.app.util.bin.format.pe.PeUtils;+import ghidra.app.util.bin.format.pe.cli.blobs.CliAbstractSig.CliParam;import ghidra.app.util.bin.format.pe.cli.blobs.CliBlob;import ghidra.app.util.bin.format.pe.cli.blobs.CliSigMethodDef;import ghidra.app.util.bin.format.pe.cli.methods.CliMethodDef;import ghidra.app.util.bin.format.pe.cli.methods.CliMethodExtraSections;import ghidra.app.util.bin.format.pe.cli.streams.CliAbstractStream;import ghidra.app.util.bin.format.pe.cli.streams.CliStreamMetadata;+import ghidra.app.util.bin.format.pe.cli.tables.CliTableParam.CliParamRow;import ghidra.app.util.bin.format.pe.cli.tables.flags.CliFlags.CliEnumMethodAttributes;import ghidra.app.util.bin.format.pe.cli.tables.flags.CliFlags.CliEnumMethodImplAttributes;import ghidra.app.util.importer.MessageLog;import ghidra.program.database.function.OverlappingFunctionException;import ghidra.program.model.address.*;-import ghidra.program.model.data.CategoryPath;-import ghidra.program.model.data.StructureDataType;-import ghidra.program.model.listing.Function;-import ghidra.program.model.listing.Program;+import ghidra.program.model.data.*;+import ghidra.program.model.listing.*;+import ghidra.program.model.listing.Function.FunctionUpdateType;import ghidra.program.model.symbol.SourceType;import ghidra.program.model.util.CodeUnitInsertionException;import ghidra.util.Msg;@@ -57,15 +58,13 @@ public class CliTableMethodDef extends CliAbstractTable {public short Flags; // MethodAttributepublic int nameIndex;public int sigIndex;-// public CliAbstractSig signature;private int paramIndex;-// public List<CliParam> params;- public static final int NEXT_ROW_PARAM_INIT_VALUE = -1;- public int nextRowParamIndex = NEXT_ROW_PARAM_INIT_VALUE; // TODO: May not want to leave this public+ private static final int NEXT_ROW_PARAM_INIT_VALUE = -1;+ private int nextRowParamIndex = NEXT_ROW_PARAM_INIT_VALUE;- public CliMethodDefRow(int rva, short implFlags, short flags, int nameIndex,- int sigIndex, int paramIndex) {+ public CliMethodDefRow(int rva, short implFlags, short flags, int nameIndex, int sigIndex,+ int paramIndex) {this.RVA = rva;this.ImplFlags = implFlags;this.Flags = flags;@@ -104,8 +103,7 @@ public class CliTableMethodDef extends CliAbstractTable {}return String.format("%s %s Params: %s [RVA %x] Impl: %s Attr: %s",- metadataStream.getStringsStream().getString(nameIndex),- methodRep, paramsStr, RVA,+ metadataStream.getStringsStream().getString(nameIndex), methodRep, paramsStr, RVA,CliEnumMethodImplAttributes.dataType.getName(ImplFlags & 0xffff),CliEnumMethodAttributes.dataType.getName(Flags & 0xffff));}@@ -124,7 +122,8 @@ public class CliTableMethodDef extends CliAbstractTable {String paramsStr;if (this.nextRowParamIndex == NEXT_ROW_PARAM_INIT_VALUE) {- this.nextRowParamIndex = metadataStream.getTable(CliTypeTable.Param).getNumRows() + 1;+ this.nextRowParamIndex =+ metadataStream.getTable(CliTypeTable.Param).getNumRows() + 1;}if (this.nextRowParamIndex == this.paramIndex) {paramsStr = "";@@ -138,8 +137,7 @@ public class CliTableMethodDef extends CliAbstractTable {}return String.format("%s %s Params: %s [RVA %x] Impl: %s Attr: %s",- stream.getStringsStream().getString(nameIndex),- methodRep, paramsStr, RVA,+ stream.getStringsStream().getString(nameIndex), methodRep, paramsStr, RVA,CliEnumMethodImplAttributes.dataType.getName(ImplFlags & 0xffff),CliEnumMethodAttributes.dataType.getName(Flags & 0xffff));}@@ -150,10 +148,9 @@ public class CliTableMethodDef extends CliAbstractTable {super(reader, stream, tableId);CliMethodDefRow lastRow = null;for (int i = 0; i < this.numRows; i++) {- CliMethodDefRow row =- new CliMethodDefRow(reader.readNextInt(), reader.readNextShort(),- reader.readNextShort(), readStringIndex(reader), readBlobIndex(reader),- readTableIndex(reader, CliTypeTable.Param));+ CliMethodDefRow row = new CliMethodDefRow(reader.readNextInt(), reader.readNextShort(),+ reader.readNextShort(), readStringIndex(reader), readBlobIndex(reader),+ readTableIndex(reader, CliTypeTable.Param));rows.add(row);strings.add(row.nameIndex);@@ -167,98 +164,105 @@ public class CliTableMethodDef extends CliAbstractTable {@Overridepublic void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,- NTHeader ntHeader) throws DuplicateNameException, CodeUnitInsertionException,- IOException {+ NTHeader ntHeader)+ throws DuplicateNameException, CodeUnitInsertionException, IOException {+int rvaZero = 0;- for (CliAbstractTableRow methodRow : rows) {- CliMethodDefRow method = (CliMethodDefRow) methodRow;- if (method.RVA == 0) {++ for (CliAbstractTableRow method : rows) {+ CliMethodDefRow methodRow = (CliMethodDefRow) method;++ // This indicates the method is abstract, runtime, or PInvokeImpl+ if (methodRow.RVA == 0) {rvaZero++;continue;- } // TODO: this indicates the method is either abstract, runtime, or PInvokeImpl- Address addr = PeUtils.getMarkupAddress(program, isBinary, ntHeader, method.RVA); // TODO: offset, RVA?- // Create MethodDef at RVA+ }++ Address addr = PeUtils.getMarkupAddress(program, isBinary, ntHeader, methodRow.RVA);++ // Create MethodDef at this RVABinaryReader reader =new BinaryReader(new MemoryByteProvider(program.getMemory(), addr),!program.getMemory().isBigEndian());CliMethodDef methodDef = new CliMethodDef(addr, reader);+PeUtils.createData(program, addr, methodDef.toDataType(), log);- // Now mark up a function++ // Get the function's address space, default to zero-length just in caseAddress startAddr = addr.add(methodDef.toDataType().getLength());- Address endAddr = startAddr.add(methodDef.getMethodSize() - 1); // TODO: -1? AddressSetView is inclusive.- AddressSetView funcAddrSet =- new AddressSet(startAddr, endAddr);- String funcName = "func_" + method.RVA;- try {- if (method.nameIndex != 0) {- Address nameAddr = CliAbstractStream.getStreamMarkupAddress(program, isBinary,- monitor, log, ntHeader, metadataStream.getStringsStream(), method.nameIndex);- BinaryReader strReader =- new BinaryReader(new MemoryByteProvider(program.getMemory(), nameAddr),- !program.getMemory().isBigEndian());- funcName = strReader.readNextAsciiString();- funcName += "-" + method.sigIndex + "-" + method.RVA; // TODO: MethodDefs are guaranteed unique on the triple (Owning TypeDef row index, Name, Signature contents)- if (program.getFunctionManager().getFunctionAt(startAddr) == null) {- // TODO: Why can a function exist here already? Different methodRow's can have the same RVA...why?- // In this case, the params table index is the only thing different.- program.getFunctionManager().createFunction(funcName, startAddr,- funcAddrSet, SourceType.ANALYSIS);- }- }- }- catch (InvalidInputException e) {- // TODO Auto-generated catch block- e.printStackTrace();+ Address endAddr = startAddr;+ if (methodDef.getMethodSize() > 0) {+ endAddr = startAddr.add(methodDef.getMethodSize() - 1);}- catch (OverlappingFunctionException e) {- // TODO Auto-generated catch block- e.printStackTrace();+ AddressSetView funcAddrSet = new AddressSet(startAddr, endAddr);++ // Let Ghidra assign a default function name and then try to decode the+ // real one if it exists+ String funcName = null;+ if (methodRow.nameIndex > 0) {+ funcName = metadataStream.getStringsStream().getString(methodRow.nameIndex);}- // Now do extra data sections++ // Do extra data sections in MethodDefif (methodDef.hasMoreSections()) {- int extraOffset = methodDef.toDataType().getLength() + methodDef.getMethodSize();- while (extraOffset % 4 != 0) {- extraOffset++;- }- reader.setPointerIndex(extraOffset);- CliMethodExtraSections extras = new CliMethodExtraSections(reader);- Address extraAddr = addr.add(extraOffset);- PeUtils.createData(program, extraAddr, extras.toDataType(), log);-// program.getBookmarkManager().setBookmark(extraAddr, BookmarkType.INFO, "ExtraSection!", name + " (RVA "+method.RVA+"_10)");+ int extraSectionOffset =+ methodDef.toDataType().getLength() + methodDef.getMethodSize();++ // Round up to the next offset divisible by 4+ extraSectionOffset = ((extraSectionOffset + 3) / 4) * 4;++ reader.setPointerIndex(extraSectionOffset);+ CliMethodExtraSections extraSections = new CliMethodExtraSections(reader);+ Address extraSectionAddr = addr.add(extraSectionOffset);+ PeUtils.createData(program, extraSectionAddr, extraSections.toDataType(), log);}-// program.getBookmarkManager().setBookmark(addr, BookmarkType.INFO, "Method!", name + " (RVA "+method.RVA+"_10)");- // Handle the signature- CliBlob blob = metadataStream.getBlobStream().getBlob(method.sigIndex);- Address sigAddr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor, log,- ntHeader, metadataStream.getBlobStream(), method.sigIndex);- // Create PropertySig object+ // Get the function signature blob+ CliBlob blob = metadataStream.getBlobStream().getBlob(methodRow.sigIndex);+ Address sigAddr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor,+ log, ntHeader, metadataStream.getBlobStream(), methodRow.sigIndex);++ // Get the return type from the function signatureCliSigMethodDef methodSig = new CliSigMethodDef(blob);metadataStream.getBlobStream().updateBlob(methodSig, sigAddr, program);-// program.getBookmarkManager().setBookmark(sigAddr, BookmarkType.INFO, "Signature!", "MethodDefSig (Offset "+method.sigIndex+")");- Function func = program.getFunctionManager().getFunctionAt(startAddr);+ DataType returnType = methodSig.getReturnType().getExecutionDataType();++ // Pull apart the function parameter names and types+ int stackOffset = 0;+ CliParam paramTypes[] = methodSig.getParamTypes();+ CliTableParam paramTable = (CliTableParam) metadataStream.getTable(CliTypeTable.Param);+ ParameterImpl parameters[] = new ParameterImpl[paramTypes.length];++ for (int i = 0; i < paramTypes.length; i++) {+ CliParamRow paramRow = (CliParamRow) paramTable.getRow(methodRow.paramIndex + i);++ String paramName = metadataStream.getStringsStream().getString(paramRow.nameIndex);+ DataType dataType = paramTypes[i].getExecutionDataType();++ try {+ parameters[i] = new ParameterImpl(paramName, dataType, stackOffset, program);+ }+ catch (InvalidInputException e) {+ Msg.warn(this, "Error processing parameter \"" + paramName ++ "\" in function \"" + funcName + "\"");+ }++ stackOffset += dataType.getLength();+ }+try {- if (func != null && methodSig.getReturnType() != null)- func.setReturnType(methodSig.getReturnType().getExecutionDataType(),- SourceType.ANALYSIS);+ Function newFunc = program.getFunctionManager()+ .createFunction(funcName, startAddr, funcAddrSet, SourceType.ANALYSIS);+ newFunc.setReturnType(returnType, SourceType.ANALYSIS);+ newFunc.updateFunction(null, null, FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS,+ true, SourceType.ANALYSIS, parameters);}catch (InvalidInputException e) {- e.printStackTrace(); // TODO+ Msg.warn(this, "Error processing function \"" + funcName + "\"");+ }+ catch (OverlappingFunctionException e) {+ Msg.warn(this, "Error processing function \"" + funcName + "\"");}- // TODO: This way of adding params relies on the language knowing the calling convention, etc.-// try {-// int offset = 0;-// for (DataType dt : methodSig.getParamTypes()) {-// if (dt != null) {-// StackParameterImpl param = new StackParameterImpl("param", dt, offset, "comment", offset, SourceType.ANALYSIS);-// func.addParameter(param, SourceType.ANALYSIS);-// offset += dt.getLength();-// }-// }-// }-// catch (InvalidInputException e) {-// e.printStackTrace();-// }}if (rvaZero > 0) {Msg.warn(this, rvaZero + " methods with RVA 0");@@ -274,7 +278,8 @@ public class CliTableMethodDef extends CliAbstractTable {rowDt.add(CliEnumMethodAttributes.dataType, "Flags", "Bitmask of type MethodAttribute");rowDt.add(metadataStream.getStringIndexDataType(), "Name", "index into String heap");rowDt.add(metadataStream.getBlobIndexDataType(), "Signature", "index into Blob heap");- rowDt.add(metadataStream.getTableIndexDataType(CliTypeTable.Param), "ParamList", "index into Param table");+ rowDt.add(metadataStream.getTableIndexDataType(CliTypeTable.Param), "ParamList",+ "index into Param table");return rowDt;}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMethodSpec.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMethodSpec.javaindex fd28def0e5..8dc63772b4 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMethodSpec.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMethodSpec.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -41,7 +41,7 @@ public class CliTableMethodSpec extends CliAbstractTable {public class CliMethodSpecRow extends CliAbstractTableRow {public int methodIndex;public int instantiationIndex;-+public CliMethodSpecRow(int methodIndex, int instantiationIndex) {super();this.methodIndex = methodIndex;@@ -52,7 +52,9 @@ public class CliTableMethodSpec extends CliAbstractTable {public String getRepresentation() {String methodRep;try {- methodRep = getRowRepresentationSafe(CliIndexMethodDefOrRef.getTableName(methodIndex), CliIndexMethodDefOrRef.getRowIndex(methodIndex));+ methodRep =+ getRowRepresentationSafe(CliIndexMethodDefOrRef.getTableName(methodIndex),+ CliIndexMethodDefOrRef.getRowIndex(methodIndex));}catch (InvalidInputException e) {methodRep = Integer.toHexString(methodIndex);@@ -63,42 +65,49 @@ public class CliTableMethodSpec extends CliAbstractTable {CliSigMethodSpec sig = new CliSigMethodSpec(blob);instantiationRep = sig.getRepresentation();}- catch (Exception e) {}+ catch (Exception e) {+ }return String.format("Method %s Instantiation %s", methodRep, instantiationRep);}}-- public CliTableMethodSpec(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {++ public CliTableMethodSpec(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId)+ throws IOException {super(reader, stream, tableId);for (int i = 0; i < this.numRows; i++) {- CliMethodSpecRow row = new CliMethodSpecRow(CliIndexMethodDefOrRef.readCodedIndex(reader, stream), readBlobIndex(reader));+ CliMethodSpecRow row = new CliMethodSpecRow(+ CliIndexMethodDefOrRef.readCodedIndex(reader, stream), readBlobIndex(reader));rows.add(row);}reader.setPointerIndex(this.readerOffset);}@Override- public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log, NTHeader ntHeader)+ public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,+ NTHeader ntHeader)throws DuplicateNameException, CodeUnitInsertionException, IOException {for (CliAbstractTableRow row : rows) {CliMethodSpecRow methodRow = (CliMethodSpecRow) row;CliBlob blob = metadataStream.getBlobStream().getBlob(methodRow.instantiationIndex);- // Handle the signature- Address sigAddr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor, log,- ntHeader, metadataStream.getBlobStream(), methodRow.instantiationIndex);- // Create MethodSpec sig++ // Create the MethodSpecSig+ Address sigAddr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor,+ log, ntHeader, metadataStream.getBlobStream(), methodRow.instantiationIndex);+CliSigMethodSpec methodSig = new CliSigMethodSpec(blob);metadataStream.getBlobStream().updateBlob(methodSig, sigAddr, program);-// program.getBookmarkManager().setBookmark(sigAddr, BookmarkType.INFO, "Signature!", "MethodSpecSig (Offset "+methodRow.instantiationIndex+")");}}-+@Overridepublic StructureDataType getRowDataType() {- StructureDataType rowDt = new StructureDataType(new CategoryPath(PATH), "MethodSpec Row", 0);- rowDt.add(CliIndexMethodDefOrRef.toDataType(metadataStream), "Method", "MethodDefOrRef coded index");- rowDt.add(metadataStream.getBlobIndexDataType(), "Instantiation", "index into Blob heap, signature of this instantiation");+ StructureDataType rowDt =+ new StructureDataType(new CategoryPath(PATH), "MethodSpec Row", 0);+ rowDt.add(CliIndexMethodDefOrRef.toDataType(metadataStream), "Method",+ "MethodDefOrRef coded index");+ rowDt.add(metadataStream.getBlobIndexDataType(), "Instantiation",+ "index into Blob heap, signature of this instantiation");return rowDt;}-+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableProperty.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableProperty.javaindex f291b80c31..2d5fa0bd0f 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableProperty.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableProperty.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -42,13 +42,13 @@ public class CliTableProperty extends CliAbstractTable {public short flags;public int nameIndex;public int sigIndex;-+public CliPropertyRow(short flags, int nameIndex, int sigIndex) {this.flags = flags;this.nameIndex = nameIndex;this.sigIndex = sigIndex;}-+@Overridepublic String getRepresentation() {String sigRep = Integer.toHexString(sigIndex);@@ -58,44 +58,50 @@ public class CliTableProperty extends CliAbstractTable {propertySig = new CliSigProperty(blob);sigRep = propertySig.getShortRepresentation(metadataStream);}- catch (IOException e) {}+ catch (IOException e) {+ }return String.format("Property %s Signature %s Flags %s",metadataStream.getStringsStream().getString(nameIndex), sigRep,CliEnumPropertyAttributes.dataType.getName(flags & 0xffff));}}-- public CliTableProperty(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {++ public CliTableProperty(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId)+ throws IOException {super(reader, stream, tableId);for (int i = 0; i < this.numRows; i++) {- CliPropertyRow row = new CliPropertyRow(reader.readNextShort(), readStringIndex(reader), readBlobIndex(reader));+ CliPropertyRow row = new CliPropertyRow(reader.readNextShort(), readStringIndex(reader),+ readBlobIndex(reader));rows.add(row);strings.add(row.nameIndex);}reader.setPointerIndex(this.readerOffset);}-+@Overridepublic StructureDataType getRowDataType() {StructureDataType rowDt = new StructureDataType(new CategoryPath(PATH), "Property Row", 0);- rowDt.add(CliEnumPropertyAttributes.dataType, "Flags", "Bitmask of type PropertyAttributes");+ rowDt.add(CliEnumPropertyAttributes.dataType, "Flags",+ "Bitmask of type PropertyAttributes");rowDt.add(metadataStream.getStringIndexDataType(), "Name", null);- rowDt.add(metadataStream.getBlobIndexDataType(), "Type", "Blob index to the signature, not a TypeDef/TypeRef");+ rowDt.add(metadataStream.getBlobIndexDataType(), "Type",+ "Blob index to the signature, not a TypeDef/TypeRef");return rowDt;}-+@Override- public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log, NTHeader ntHeader)+ public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,+ NTHeader ntHeader)throws DuplicateNameException, CodeUnitInsertionException, IOException {for (CliAbstractTableRow row : rows) {CliPropertyRow property = (CliPropertyRow) row;CliBlob blob = metadataStream.getBlobStream().getBlob(property.sigIndex);Address addr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor, log,ntHeader, metadataStream.getBlobStream(), property.sigIndex);+// Create PropertySig objectCliSigProperty propSig = new CliSigProperty(blob);metadataStream.getBlobStream().updateBlob(propSig, addr, program);-// program.getBookmarkManager().setBookmark(addr, BookmarkType.INFO, "Signature!", "PropertySig (Offset "+property.sigIndex+")");}}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableStandAloneSig.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableStandAloneSig.javaindex ad89dd3eec..ca65568b27 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableStandAloneSig.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableStandAloneSig.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -37,11 +37,11 @@ import ghidra.util.task.TaskMonitor;public class CliTableStandAloneSig extends CliAbstractTable {public class CliStandAloneSigRow extends CliAbstractTableRow {public int signatureIndex;-+public CliStandAloneSigRow(int signatureIndex) {this.signatureIndex = signatureIndex;}-+@Overridepublic String getRepresentation() {String sigRep = Integer.toHexString(signatureIndex);@@ -52,8 +52,8 @@ public class CliTableStandAloneSig extends CliAbstractTable {sig = new CliSigLocalVar(sigBlob);}else if (CliSigField.isFieldSig(sigBlob)) {- // UNDOCUMENTED FEATURE ALERT! Microsoft compilers will sometimes put FieldSig references in this table, too,- // despite that not fitting the ISO standard they wrote themselves.+ // UNDOCUMENTED FEATURE ALERT! Contrary to ISO standards Microsoft compilers+ // will sometimes put FieldSig references in this table.sig = new CliSigField(sigBlob);}else {@@ -61,52 +61,54 @@ public class CliTableStandAloneSig extends CliAbstractTable {}sigRep = sig.getRepresentation();}- catch (Exception e) {}+ catch (Exception e) {+ }return String.format("%s", sigRep);}}-- public CliTableStandAloneSig(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {++ public CliTableStandAloneSig(BinaryReader reader, CliStreamMetadata stream,+ CliTypeTable tableId) throws IOException {super(reader, stream, tableId);for (int i = 0; i < this.numRows; i++) {rows.add(new CliStandAloneSigRow(readBlobIndex(reader)));}reader.setPointerIndex(this.readerOffset);}-+@Overridepublic StructureDataType getRowDataType() {- StructureDataType rowDt = new StructureDataType(new CategoryPath(PATH), "StandAloneSig Row", 0);+ StructureDataType rowDt =+ new StructureDataType(new CategoryPath(PATH), "StandAloneSig Row", 0);rowDt.add(metadataStream.getBlobIndexDataType(), "Signature", null);return rowDt;}-+@Override- public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log, NTHeader ntHeader)+ public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,+ NTHeader ntHeader)throws DuplicateNameException, CodeUnitInsertionException, IOException {for (CliAbstractTableRow row : rows) {Integer sigIndex = ((CliStandAloneSigRow) row).signatureIndex;CliBlob blob =metadataStream.getBlobStream().getBlob(((CliStandAloneSigRow) row).signatureIndex);- Address addr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor, log,- ntHeader, metadataStream.getBlobStream(), sigIndex);- // Create Signature object and mark it up+ Address sigAddr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor,+ log, ntHeader, metadataStream.getBlobStream(), sigIndex);++ // Create one of several *Sig objectsif (CliSigLocalVar.isLocalVarSig(blob)) {CliSigLocalVar localSig = new CliSigLocalVar(blob);- metadataStream.getBlobStream().updateBlob(localSig, addr, program);-// program.getBookmarkManager().setBookmark(addr, BookmarkType.INFO, "Signature!", "LocalVarSig (Offset "+sigIndex+")");+ metadataStream.getBlobStream().updateBlob(localSig, sigAddr, program);}else if (CliSigField.isFieldSig(blob)) {- // UNDOCUMENTED FEATURE ALERT! Microsoft compilers will sometimes put FieldSig references in this table, too,- // despite that not fitting the ISO standard they wrote themselves.+ // UNDOCUMENTED FEATURE ALERT! Contrary to ISO standards Microsoft compilers+ // will sometimes put FieldSig references in this table.CliSigField fieldSig = new CliSigField(blob);- metadataStream.getBlobStream().updateBlob(fieldSig, addr, program);-// program.getBookmarkManager().setBookmark(addr, BookmarkType.INFO, "Signature!", "FieldSig (Offset "+sigIndex+")");+ metadataStream.getBlobStream().updateBlob(fieldSig, sigAddr, program);}else {CliSigStandAloneMethod standAloneSig = new CliSigStandAloneMethod(blob);- metadataStream.getBlobStream().updateBlob(standAloneSig, addr, program);-// program.getBookmarkManager().setBookmark(addr, BookmarkType.INFO, "Signature!", "StandAloneSig (Offset "+sigIndex+")");+ metadataStream.getBlobStream().updateBlob(standAloneSig, sigAddr, program);}}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableTypeSpec.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableTypeSpec.javaindex dadfdd7d64..c2f63eafaa 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableTypeSpec.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableTypeSpec.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -38,7 +38,7 @@ import ghidra.util.task.TaskMonitor;public class CliTableTypeSpec extends CliAbstractTable {public class CliTypeSpecRow extends CliAbstractTableRow {public int signatureIndex;-+public CliTypeSpecRow(int signatureIndex) {super();this.signatureIndex = signatureIndex;@@ -52,10 +52,11 @@ public class CliTableTypeSpec extends CliAbstractTable {CliSigTypeSpec sig = new CliSigTypeSpec(blob);sigRep = sig.getRepresentation();}- catch (Exception e) {}+ catch (Exception e) {+ }return String.format("%s", sigRep);}-+@Overridepublic String getRepresentation(CliStreamMetadata stream) {String sigRep = Integer.toHexString(signatureIndex);@@ -64,12 +65,14 @@ public class CliTableTypeSpec extends CliAbstractTable {CliSigTypeSpec sig = new CliSigTypeSpec(blob);sigRep = sig.getRepresentation(stream);}- catch (Exception e) {}+ catch (Exception e) {+ }return String.format("%s", sigRep);}}-- public CliTableTypeSpec(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {++ public CliTableTypeSpec(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId)+ throws IOException {super(reader, stream, tableId);for (int i = 0; i < this.numRows; i++) {CliTypeSpecRow row = new CliTypeSpecRow(readBlobIndex(reader));@@ -79,21 +82,22 @@ public class CliTableTypeSpec extends CliAbstractTable {}@Override- public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log, NTHeader ntHeader)+ public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,+ NTHeader ntHeader)throws DuplicateNameException, CodeUnitInsertionException, IOException {for (CliAbstractTableRow row : rows) {CliTypeSpecRow typeRow = (CliTypeSpecRow) row;CliBlob blob = metadataStream.getBlobStream().getBlob(typeRow.signatureIndex);- // Handle the signature- Address sigAddr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor, log,- ntHeader, metadataStream.getBlobStream(), typeRow.signatureIndex);- // Create PropertySig object++ // Get the address of the signature, create the TypeSpec object+ Address sigAddr = CliAbstractStream.getStreamMarkupAddress(program, isBinary, monitor,+ log, ntHeader, metadataStream.getBlobStream(), typeRow.signatureIndex);+CliSigTypeSpec typeSig = new CliSigTypeSpec(blob);metadataStream.getBlobStream().updateBlob(typeSig, sigAddr, program);-// program.getBookmarkManager().setBookmark(sigAddr, BookmarkType.INFO, "Signature!", "TypeSpecSig (Offset "+typeRow.signatureIndex+")");}}-+@Overridepublic StructureDataType getRowDataType() {StructureDataType rowDt = new StructureDataType(new CategoryPath(PATH), "TypeSpec Row", 0);