Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-1777 - PDB Universal - Improve segment address calculation

ghizard70e7ae6e5916
diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dump/pagedump/Pagedump.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dump/pagedump/Pagedump.java
index f6477945e0..7c36344d55 100644
--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dump/pagedump/Pagedump.java
+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dump/pagedump/Pagedump.java
@@ -202,7 +202,7 @@ public class Pagedump extends DumpFile {
try (AbstractPdb pdb = PdbParser.parse(pdbFile.getPath(), readerOptions, monitor)) {
monitor.setMessage("PDB: Parsing " + pdbFile + "...");
pdb.deserialize(monitor);
- PdbApplicator applicator = new PdbApplicator(pdbFile.getPath(), pdb);
+ DefaultPdbApplicator applicator = new DefaultPdbApplicator(pdbFile.getPath(), pdb);
applicator.applyTo(program, dtm, program.getImageBase(),
applicatorOptions, monitor,
(MessageLog) null);
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/plugin/core/analysis/PdbUniversalAnalyzer.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/plugin/core/analysis/PdbUniversalAnalyzer.java
index a02db87386..54abd0f22b 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/plugin/core/analysis/PdbUniversalAnalyzer.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/plugin/core/analysis/PdbUniversalAnalyzer.java
@@ -23,7 +23,7 @@ import ghidra.app.services.*;
import ghidra.app.util.bin.format.pdb2.pdbreader.*;
import ghidra.app.util.importer.MessageLog;
import ghidra.app.util.pdb.PdbProgramAttributes;
-import ghidra.app.util.pdb.pdbapplicator.PdbApplicator;
+import ghidra.app.util.pdb.pdbapplicator.DefaultPdbApplicator;
import ghidra.app.util.pdb.pdbapplicator.PdbApplicatorOptions;
import ghidra.framework.*;
import ghidra.framework.options.OptionType;
@@ -181,7 +181,7 @@ public class PdbUniversalAnalyzer extends AbstractAnalyzer {
try (AbstractPdb pdb = PdbParser.parse(pdbFile.getPath(), pdbReaderOptions, monitor)) {
monitor.setMessage("PDB: Parsing " + pdbFile + "...");
pdb.deserialize(monitor);
- PdbApplicator applicator = new PdbApplicator(pdbFile.getPath(), pdb);
+ DefaultPdbApplicator applicator = new DefaultPdbApplicator(pdbFile.getPath(), pdb);
applicator.applyTo(program, program.getDataTypeManager(), program.getImageBase(),
pdbApplicatorOptions, monitor, log);
@@ -251,7 +251,7 @@ public class PdbUniversalAnalyzer extends AbstractAnalyzer {
* Normally the analyzer would locate the PDB file on its own, but if a
* headless script wishes to override the analyzer's behaivor, it can
* use this method to specify a file.
- *
+ *
* @param program {@link Program}
* @param pdbFile the pdb file
*/
@@ -266,7 +266,7 @@ public class PdbUniversalAnalyzer extends AbstractAnalyzer {
* Normally when the analyzer attempts to locate a matching PDB file it
* will default to NOT searching remote symbol servers. A headless script could
* use this method to allow the analyzer to search remote symbol servers.
- *
+ *
* @param program {@link Program}
* @param allowRemote boolean flag, true means analyzer can search remote symbol
* servers
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/PdbOldDebugInfo.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/PdbOldDebugInfo.java
index 7a25e3743e..ff1b8cf51e 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/PdbOldDebugInfo.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/PdbOldDebugInfo.java
@@ -26,7 +26,7 @@ import ghidra.util.task.TaskMonitor;
* <P>
* This class uses {@link ModuleInformation500}.
*/
-class PdbOldDebugInfo extends PdbDebugInfo {
+public class PdbOldDebugInfo extends PdbDebugInfo {
private static final int OLD_DBI_HEADER_LENGTH = 22;
@@ -74,7 +74,7 @@ class PdbOldDebugInfo extends PdbDebugInfo {
protected void deserializeAdditionalSubstreams(TaskMonitor monitor)
throws IOException, PdbException, CancelledException {
// TODO: evaluate. I don't think we need GlobalSymbolInformation (hash) or the
- // PublicSymbolInformation (hash), as they are both are search mechanisms.
+ // PublicSymbolInformation (hash), as they are both are search mechanisms.
symbolRecords.deserialize(monitor);
globalSymbolInformation.deserialize(getGlobalSymbolsHashMaybeStreamNumber(), monitor);
publicSymbolInformation.deserialize(getPublicStaticSymbolsHashMaybeStreamNumber(), monitor);
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/SegmentMapDescription.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/SegmentMapDescription.java
index 7068f3195d..7109f3629d 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/SegmentMapDescription.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/SegmentMapDescription.java
@@ -33,6 +33,62 @@ public class SegmentMapDescription {
private long segOffset;
private long segLength;
+ /**
+ * Returns the {@link SegmentMapDescription} flags.
+ * @return the flags.
+ */
+ public int getFlags() {
+ return flags;
+ }
+
+ /**
+ * Returns the {@link SegmentMapDescription} ovl (overlay?).
+ * @return the ovl.
+ */
+ public int getOvl() {
+ return ovl;
+ }
+
+ /**
+ * Returns the {@link SegmentMapDescription} group.
+ * @return the group.
+ */
+ public int getGroup() {
+ return group;
+ }
+
+ /**
+ * Returns the {@link SegmentMapDescription} frame.
+ * @return the frame.
+ */
+ public int getFrame() {
+ return frame;
+ }
+
+ /**
+ * Returns the {@link SegmentMapDescription} segNameIndex.
+ * @return the segNameIndex.
+ */
+ public int getSegNameIndex() {
+ return segNameIndex;
+ }
+
+ /**
+ * Returns the {@link SegmentMapDescription} classNameIndex.
+ * @return the classNameIndex.
+ */
+ public int getClassNameIndex() {
+ return classNameIndex;
+ }
+
+ /**
+ * Returns the {@link SegmentMapDescription} segment offset.
+ * @return the segment offset.
+ */
+ public long getOffset() {
+ return segOffset;
+ }
+
/**
* Returns the segment offset.
* @return The offset of the segment.
@@ -42,7 +98,7 @@ public class SegmentMapDescription {
}
/**
- * Returns the segment length.
+ * Returns the {@link SegmentMapDescription} segment length.
* @return The length of the segment.
*/
public long getLength() {
@@ -73,7 +129,7 @@ public class SegmentMapDescription {
StringBuilder builder = new StringBuilder();
builder.append("SegmentMapDescription---------------------------------------");
builder.append("\nflags: ");
- builder.append(flags);
+ builder.append(String.format("0x%04x", flags));
builder.append("\novl: ");
builder.append(ovl);
builder.append("\ngroup: ");
@@ -88,6 +144,7 @@ public class SegmentMapDescription {
builder.append(segOffset);
builder.append("; segLength: ");
builder.append(segLength);
+ builder.append("\nEnd SegmentMapDescription-----------------------------------\n");
return builder.toString();
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/symbol/AbstractCompile2MsSymbol.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/symbol/AbstractCompile2MsSymbol.java
index 5baff124e3..8fee03bef5 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/symbol/AbstractCompile2MsSymbol.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/symbol/AbstractCompile2MsSymbol.java
@@ -28,6 +28,7 @@ import ghidra.app.util.bin.format.pdb2.pdbreader.*;
*/
public abstract class AbstractCompile2MsSymbol extends AbstractMsSymbol {
+ protected long flags;
protected LanguageName language;
protected boolean compiledForEditAndContinue;
protected boolean notCompiledWithDebugInfo;
@@ -59,7 +60,8 @@ public abstract class AbstractCompile2MsSymbol extends AbstractMsSymbol {
public AbstractCompile2MsSymbol(AbstractPdb pdb, PdbByteReader reader, StringParseType strType)
throws PdbException {
super(pdb, reader);
- processFlags(reader.parseUnsignedIntVal());
+ flags = reader.parseUnsignedIntVal();
+ processFlags(flags);
processor = Processor.fromValue(reader.parseUnsignedShortVal());
frontEndMajorVersionNumber = reader.parseUnsignedShortVal();
frontEndMinorVersionNumber = reader.parseUnsignedShortVal();
@@ -84,6 +86,14 @@ public abstract class AbstractCompile2MsSymbol extends AbstractMsSymbol {
pdb.setTargetProcessor(processor);
}
+ /**
+ * Returns the packed flags.
+ * @return the packed flags.
+ */
+ public long getFlags() {
+ return flags;
+ }
+
/**
* Returns the language used.
* @return Language.
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/symbol/Compile3MsSymbol.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/symbol/Compile3MsSymbol.java
index e8c9c0b635..077dd1b060 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/symbol/Compile3MsSymbol.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/symbol/Compile3MsSymbol.java
@@ -27,6 +27,7 @@ public class Compile3MsSymbol extends AbstractMsSymbol {
public static final int PDB_ID = 0x113c;
+ protected long flags;
protected LanguageName language;
protected boolean compiledForEditAndContinue;
protected boolean notCompiledWithDebugInfo;
@@ -60,7 +61,8 @@ public class Compile3MsSymbol extends AbstractMsSymbol {
*/
public Compile3MsSymbol(AbstractPdb pdb, PdbByteReader reader) throws PdbException {
super(pdb, reader);
- processFlags(reader.parseUnsignedIntVal());
+ flags = reader.parseUnsignedIntVal();
+ processFlags(flags);
processor = Processor.fromValue(reader.parseUnsignedShortVal());
frontEndMajorVersionNumber = reader.parseUnsignedShortVal();
frontEndMinorVersionNumber = reader.parseUnsignedShortVal();
@@ -82,6 +84,14 @@ public class Compile3MsSymbol extends AbstractMsSymbol {
return PDB_ID;
}
+ /**
+ * Returns the packed flags.
+ * @return the packed flags.
+ */
+ public long getFlags() {
+ return flags;
+ }
+
/**
* Returns the language.
* @return Language.
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/AbstractComplexTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/AbstractComplexTypeApplier.java
index 82660bf418..8fd28a7201 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/AbstractComplexTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/AbstractComplexTypeApplier.java
@@ -34,7 +34,7 @@ public abstract class AbstractComplexTypeApplier extends MsTypeApplier {
protected AbstractComplexTypeApplier definitionApplier = null;
protected AbstractComplexTypeApplier forwardReferenceApplier = null;
- public static AbstractComplexTypeApplier getComplexApplier(PdbApplicator applicator,
+ public static AbstractComplexTypeApplier getComplexApplier(DefaultPdbApplicator applicator,
RecordNumber recordNumber) throws PdbException {
return (AbstractComplexTypeApplier) applicator.getApplierSpec(recordNumber,
AbstractComplexTypeApplier.class);
@@ -42,10 +42,10 @@ public abstract class AbstractComplexTypeApplier extends MsTypeApplier {
/**
* Constructor for complex type applier.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractComplexMsType} to process.
*/
- public AbstractComplexTypeApplier(PdbApplicator applicator, AbstractComplexMsType msType) {
+ public AbstractComplexTypeApplier(DefaultPdbApplicator applicator, AbstractComplexMsType msType) {
super(applicator, msType);
String fullPathName = msType.getName();
symbolPath = new SymbolPath(SymbolPathParser.parse(fullPathName));
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/AbstractFunctionTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/AbstractFunctionTypeApplier.java
index fca5de8702..9eadb40511 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/AbstractFunctionTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/AbstractFunctionTypeApplier.java
@@ -38,10 +38,10 @@ public abstract class AbstractFunctionTypeApplier extends MsTypeApplier {
/**
* Constructor for the applicator that applies a "function" type, transforming it into a
* Ghidra DataType.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractMsType} to processes
*/
- public AbstractFunctionTypeApplier(PdbApplicator applicator, AbstractMsType msType) {
+ public AbstractFunctionTypeApplier(DefaultPdbApplicator applicator, AbstractMsType msType) {
super(applicator, msType);
// String funcName = applicator.getNextAnonymousFunctionName();
functionDefinition = new FunctionDefinitionDataType(
@@ -224,8 +224,8 @@ public abstract class AbstractFunctionTypeApplier extends MsTypeApplier {
return true;
}
- private void setCallingConvention(PdbApplicator applicator, CallingConvention callingConvention,
- boolean hasThisPointer) {
+ private void setCallingConvention(DefaultPdbApplicator applicator,
+ CallingConvention callingConvention, boolean hasThisPointer) {
GenericCallingConvention convention;
if (hasThisPointer) {
convention = GenericCallingConvention.thiscall;
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ArgumentsListTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ArgumentsListTypeApplier.java
index 81de55596a..125253b4a8 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ArgumentsListTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ArgumentsListTypeApplier.java
@@ -32,12 +32,12 @@ public class ArgumentsListTypeApplier extends MsTypeApplier {
/**
* Constructor for the applicator that applies a arguments list.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractArgumentsListMsType} to processes.
* @throws IllegalArgumentException Upon invalid arguments.
*/
- public ArgumentsListTypeApplier(PdbApplicator applicator, AbstractArgumentsListMsType msType)
- throws IllegalArgumentException {
+ public ArgumentsListTypeApplier(DefaultPdbApplicator applicator,
+ AbstractArgumentsListMsType msType) throws IllegalArgumentException {
super(applicator, msType);
}
@@ -110,7 +110,7 @@ public class ArgumentsListTypeApplier extends MsTypeApplier {
}
/**
- * Apply this to function ({@link AbstractFunctionTypeApplier}).
+ * Apply this to function ({@link AbstractFunctionTypeApplier}).
* @param functionApplier the {@link AbstractFunctionTypeApplier} to which to apply the
* arguments.
* @throws CancelledException Upon user cancellation
@@ -172,7 +172,7 @@ public class ArgumentsListTypeApplier extends MsTypeApplier {
}
// /**
-// * Apply this to function ({@link AbstractFunctionTypeApplier}).
+// * Apply this to function ({@link AbstractFunctionTypeApplier}).
// * @param functionApplier the {@link AbstractFunctionTypeApplier} to which to apply the
// * arguments.
// * @throws PdbException when unexpected function internals are found.
@@ -221,5 +221,5 @@ public class ArgumentsListTypeApplier extends MsTypeApplier {
// functionDefinition.setArguments(parameterDefinitionList.toArray(
// new ParameterDefinition[parameterDefinitionList.size()]));
// }
-//
+//
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ArrayTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ArrayTypeApplier.java
index ff1f637ca5..d37a310a20 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ArrayTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ArrayTypeApplier.java
@@ -34,10 +34,10 @@ public class ArrayTypeApplier extends MsTypeApplier {
/**
* Constructor for the applicator that applies a "array" type, transforming it into a
* Ghidra DataType.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractArrayMsType} to processes.
*/
- public ArrayTypeApplier(PdbApplicator applicator, AbstractArrayMsType msType) {
+ public ArrayTypeApplier(DefaultPdbApplicator applicator, AbstractArrayMsType msType) {
super(applicator, msType);
}
@@ -117,7 +117,7 @@ public class ArrayTypeApplier extends MsTypeApplier {
}
long longUnderlyingSize =
- PdbApplicator.bigIntegerToLong(applicator, underlyingTypeApplier.getSize());
+ DefaultPdbApplicator.bigIntegerToLong(applicator, underlyingTypeApplier.getSize());
DataType underlyingDataType = underlyingTypeApplier.getDataType();
if (underlyingDataType == null) {
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BaseClassTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BaseClassTypeApplier.java
index 696873cfda..1e931b8ffe 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BaseClassTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BaseClassTypeApplier.java
@@ -30,12 +30,12 @@ public class BaseClassTypeApplier extends MsTypeApplier {
/**
* Constructor for base class applier.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractBaseClassMsType}, {@link AbstractVirtualBaseClassMsType}, or
* {@link AbstractIndirectVirtualBaseClassMsType} to processes.
* @throws IllegalArgumentException Upon invalid arguments.
*/
- public BaseClassTypeApplier(PdbApplicator applicator, AbstractMsType msType)
+ public BaseClassTypeApplier(DefaultPdbApplicator applicator, AbstractMsType msType)
throws IllegalArgumentException {
super(applicator, validateType(msType));
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BitfieldTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BitfieldTypeApplier.java
index adb08e2a52..1352a17292 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BitfieldTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BitfieldTypeApplier.java
@@ -32,10 +32,10 @@ public class BitfieldTypeApplier extends MsTypeApplier {
/**
* Constructor for bitfield applier.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractBitfieldMsType} to processes
*/
- public BitfieldTypeApplier(PdbApplicator applicator, AbstractBitfieldMsType msType) {
+ public BitfieldTypeApplier(DefaultPdbApplicator applicator, AbstractBitfieldMsType msType) {
super(applicator, msType);
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BlockSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BlockSymbolApplier.java
index 98cefa55c2..c88b62d4f7 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BlockSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BlockSymbolApplier.java
@@ -32,10 +32,10 @@ public class BlockSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public BlockSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public BlockSymbolApplier(DefaultPdbApplicator applicator, AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
if (!(abstractSymbol instanceof AbstractBlockMsSymbol)) {
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ComplexTypeApplierMapper.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ComplexTypeApplierMapper.java
index 51157a5228..e77a408636 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ComplexTypeApplierMapper.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ComplexTypeApplierMapper.java
@@ -33,14 +33,14 @@ import ghidra.util.task.TaskMonitor;
// tried.
public class ComplexTypeApplierMapper {
- private PdbApplicator applicator;
+ private DefaultPdbApplicator applicator;
// private Map<SymbolPath, AbstractComplexTypeApplier> complexTypeAppliersBySymbolPath;
private Map<SymbolPath, LinkedList<AbstractComplexTypeApplier>> compositeAppliersQueueBySymbolPath;
private Map<SymbolPath, LinkedList<AbstractComplexTypeApplier>> enumAppliersQueueBySymbolPath;
//==============================================================================================
- public ComplexTypeApplierMapper(PdbApplicator applicator) {
+ public ComplexTypeApplierMapper(DefaultPdbApplicator applicator) {
Objects.requireNonNull(applicator, "applicator cannot be null");
this.applicator = applicator;
// complexTypeAppliersBySymbolPath = new HashMap<>();
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/CompositeTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/CompositeTypeApplier.java
index e282741957..8534b5b2ec 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/CompositeTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/CompositeTypeApplier.java
@@ -58,10 +58,10 @@ public class CompositeTypeApplier extends AbstractComplexTypeApplier {
/**
* Constructor for composite type applier, for transforming a composite into a
* Ghidra DataType.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractCompositeMsType} to process.
*/
- public CompositeTypeApplier(PdbApplicator applicator, AbstractCompositeMsType msType) {
+ public CompositeTypeApplier(DefaultPdbApplicator applicator, AbstractCompositeMsType msType) {
super(applicator, msType);
String fullPathName = msType.getName();
symbolPath = new SymbolPath(SymbolPathParser.parse(fullPathName));
@@ -101,7 +101,7 @@ public class CompositeTypeApplier extends AbstractComplexTypeApplier {
String mangledName = ((AbstractCompositeMsType) msType).getMangledName();
classType = new CppCompositeType((Composite) dataType, mangledName);
classType.setName(getName());
- classType.setSize(PdbApplicator.bigIntegerToInt(applicator, getSize()));
+ classType.setSize(DefaultPdbApplicator.bigIntegerToInt(applicator, getSize()));
if (msType instanceof AbstractClassMsType) {
classType.setClass();
}
@@ -137,7 +137,7 @@ public class CompositeTypeApplier extends AbstractComplexTypeApplier {
void resolve() {
// NOTE: Until we know better we do not want to explicitly
- // apply nested composite datatypes and allow them to be
+ // apply nested composite datatypes and allow them to be
// created as-needed (e.g., function definition). This is
// done to minimize duplication of anonymous/unnamed nested
// composites since the parent composite reconstruction performed
@@ -401,7 +401,7 @@ public class CompositeTypeApplier extends AbstractComplexTypeApplier {
return ((AbstractCompositeMsType) getDependencyApplier().getMsType()).getSize();
}
- // TODO:
+ // TODO:
// Taken from PdbUtil without change. Would have had to change access on class PdbUtil and
// this ensureSize method to public to make it accessible. Can revert to using PdbUtil
// once we move this new module from Contrib to Features/PDB.
@@ -545,7 +545,7 @@ public class CompositeTypeApplier extends AbstractComplexTypeApplier {
return;
}
ClassFieldMsAttributes atts = base.getAttributes();
- int offset = PdbApplicator.bigIntegerToInt(applicator, base.getOffset());
+ int offset = DefaultPdbApplicator.bigIntegerToInt(applicator, base.getOffset());
classType.addDirectBaseClass(underlyingClassType, convertAttributes(atts), offset);
}
@@ -559,8 +559,9 @@ public class CompositeTypeApplier extends AbstractComplexTypeApplier {
getVirtualBaseTablePointerDataType(base.getVirtualBasePointerRecordNumber());
ClassFieldMsAttributes atts = base.getAttributes();
int basePointerOffset =
- PdbApplicator.bigIntegerToInt(applicator, base.getBasePointerOffset());
- int offsetFromVbt = PdbApplicator.bigIntegerToInt(applicator, base.getBaseOffsetFromVbt());
+ DefaultPdbApplicator.bigIntegerToInt(applicator, base.getBasePointerOffset());
+ int offsetFromVbt =
+ DefaultPdbApplicator.bigIntegerToInt(applicator, base.getBaseOffsetFromVbt());
classType.addDirectVirtualBaseClass(underlyingCt, convertAttributes(atts),
basePointerOffset, vbtptr, offsetFromVbt);
}
@@ -575,8 +576,9 @@ public class CompositeTypeApplier extends AbstractComplexTypeApplier {
getVirtualBaseTablePointerDataType(base.getVirtualBasePointerRecordNumber());
ClassFieldMsAttributes atts = base.getAttributes();
int basePointerOffset =
- PdbApplicator.bigIntegerToInt(applicator, base.getBasePointerOffset());
- int offsetFromVbt = PdbApplicator.bigIntegerToInt(applicator, base.getBaseOffsetFromVbt());
+ DefaultPdbApplicator.bigIntegerToInt(applicator, base.getBasePointerOffset());
+ int offsetFromVbt =
+ DefaultPdbApplicator.bigIntegerToInt(applicator, base.getBaseOffsetFromVbt());
classType.addIndirectVirtualBaseClass(underlyingCt, convertAttributes(atts),
basePointerOffset, vbtptr, offsetFromVbt);
}
@@ -653,7 +655,7 @@ public class CompositeTypeApplier extends AbstractComplexTypeApplier {
String memberName = memberTypeApplier.getName();
int offset =
- PdbApplicator.bigIntegerToInt(applicator, memberTypeApplier.getOffset());
+ DefaultPdbApplicator.bigIntegerToInt(applicator, memberTypeApplier.getOffset());
ClassFieldMsAttributes memberAttributes = memberTypeApplier.getAttribute();
memberAttributes.getAccess(); // TODO: do something with this and other attributes
MsTypeApplier fieldApplier = memberTypeApplier.getFieldTypeApplier();
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DataSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DataSymbolApplier.java
index c6b888ee21..6e6dd95ee8 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DataSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DataSymbolApplier.java
@@ -37,10 +37,10 @@ public class DataSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public DataSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public DataSymbolApplier(DefaultPdbApplicator applicator, AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
if (!(abstractSymbol instanceof AbstractDataMsSymbol)) {
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DefaultPdbApplicator.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DefaultPdbApplicator.java
new file mode 100644
index 0000000000..89b4e5fd86
--- /dev/null
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DefaultPdbApplicator.java
@@ -0,0 +1,1776 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.pdb.pdbapplicator;
+
+import java.math.BigInteger;
+import java.util.*;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.lang3.StringUtils;
+
+import ghidra.app.cmd.comments.SetCommentCmd;
+import ghidra.app.cmd.label.SetLabelPrimaryCmd;
+import ghidra.app.util.NamespaceUtils;
+import ghidra.app.util.SymbolPath;
+import ghidra.app.util.bin.format.pdb.PdbParserConstants;
+import ghidra.app.util.bin.format.pdb2.pdbreader.*;
+import ghidra.app.util.bin.format.pdb2.pdbreader.symbol.*;
+import ghidra.app.util.bin.format.pdb2.pdbreader.type.AbstractMsType;
+import ghidra.app.util.bin.format.pe.cli.tables.CliAbstractTableRow;
+import ghidra.app.util.importer.MessageLog;
+import ghidra.app.util.pdb.PdbCategories;
+import ghidra.app.util.pdb.pdbapplicator.SymbolGroup.AbstractMsSymbolIterator;
+import ghidra.framework.options.Options;
+import ghidra.graph.*;
+import ghidra.graph.algo.GraphNavigator;
+import ghidra.graph.jung.JungDirectedGraph;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.data.*;
+import ghidra.program.model.lang.Register;
+import ghidra.program.model.listing.*;
+import ghidra.program.model.symbol.*;
+import ghidra.util.Msg;
+import ghidra.util.exception.*;
+import ghidra.util.task.CancelOnlyWrappingTaskMonitor;
+import ghidra.util.task.TaskMonitor;
+
+/**
+ * The main engine for applying an AbstractPdb to Ghidra, whether a Program or DataTypeManager.
+ * The class is to be constructed first.
+ * <p>
+ * The
+ * {@link #applyTo(Program, DataTypeManager, Address, PdbApplicatorOptions, TaskMonitor, MessageLog)}
+ * method is then called with the appropriate {@link PdbApplicatorOptions} along with a
+ * {@link Program} and/or {@link DataTypeManager}. Either, but not both can be null.
+ * If the Program is not null but the DatatypeManager is null, then the DataTypeManager is gotten
+ * from the Program. If the Program is null, then data types can be applied to a DataTypeManager.
+ * The validation logic for the parameters is found in
+ * {@link #validateAndSetParameters(Program, DataTypeManager, Address, PdbApplicatorOptions, TaskMonitor, MessageLog)}.
+ * <p>
+ * Once the parameters are validated, appropriate classes and storage containers are constructed.
+ * Then processing commences, first with data types, followed by symbol-related processing.
+ * <p>
+ * {@link PdbApplicatorMetrics} are captured during the processing and status and logging is
+ * reported to various mechanisms including {@link Msg}, {@link MessageLog}, and {@link PdbLog}.
+ */
+public class DefaultPdbApplicator implements PdbApplicator {
+
+ private static final String THUNK_NAME_PREFIX = "[thunk]:";
+
+ //==============================================================================================
+ /**
+ * Returns integer value of BigInteger or Integer.MAX_VALUE if does not fit.
+ * @param myApplicator PdbApplicator for which we are working.
+ * @param big BigInteger value to convert.
+ * @return the integer value.
+ */
+ static long bigIntegerToLong(DefaultPdbApplicator myApplicator, BigInteger big) {
+ try {
+ return big.longValueExact();
+ }
+ catch (ArithmeticException e) {
+ String msg = "BigInteger value greater than max Long: " + big;
+ PdbLog.message(msg);
+ myApplicator.appendLogMsg(msg);
+ return Long.MAX_VALUE;
+ }
+ }
+
+ /**
+ * Returns integer value of BigInteger or Integer.MAX_VALUE if does not fit.
+ * @param myApplicator PdbApplicator for which we are working.
+ * @param big BigInteger value to convert.
+ * @return the integer value.
+ */
+ static int bigIntegerToInt(DefaultPdbApplicator myApplicator, BigInteger big) {
+ try {
+ return big.intValueExact();
+ }
+ catch (ArithmeticException e) {
+ String msg = "BigInteger value greater than max Integer: " + big;
+ PdbLog.message(msg);
+ myApplicator.appendLogMsg(msg);
+ return Integer.MAX_VALUE;
+ }
+ }
+
+ //==============================================================================================
+ private String pdbFilename;
+ private AbstractPdb pdb;
+
+ private PdbApplicatorMetrics pdbApplicatorMetrics;
+
+ //==============================================================================================
+ private Program program;
+
+ private PdbApplicatorOptions applicatorOptions;
+ private MessageLog log;
+ private TaskMonitor monitor;
+ private CancelOnlyWrappingTaskMonitor cancelOnlyWrappingMonitor;
+
+ //==============================================================================================
+ private Address imageBase;
+ private int linkerModuleNumber = -1;
+ private DataTypeManager dataTypeManager;
+ private PdbAddressManager pdbAddressManager;
+ private List<SymbolGroup> symbolGroups;
+
+ private PdbPeHeaderInfoManager pdbPeHeaderInfoManager;
+
+ private List<PeCoffSectionMsSymbol> linkerPeCoffSectionSymbols = null;
+ private AbstractMsSymbol compileSymbolForLinkerModule = null;
+ private boolean processedLinkerModule = false;
+
+ //==============================================================================================
+ // If we have symbols and memory with VBTs in them, then a better VbtManager is created.
+ VbtManager vbtManager;
+ PdbRegisterNameToProgramRegisterMapper registerNameToRegisterMapper;
+
+ //==============================================================================================
+ private int resolveCount;
+ private PdbCategories categoryUtils;
+ private PdbPrimitiveTypeApplicator pdbPrimitiveTypeApplicator;
+ private TypeApplierFactory typeApplierParser;
+ private ComplexTypeApplierMapper complexApplierMapper;
+ private JungDirectedGraph<MsTypeApplier, GEdge<MsTypeApplier>> applierDependencyGraph;
+ /**
+ * This namespace map documents as follows:
+ * <PRE>
+ * false = simple namespace
+ * true = class namespace
+ * </PRE>
+ */
+ private Map<SymbolPath, Boolean> isClassByNamespace;
+
+ //==============================================================================================
+ private SymbolApplierFactory symbolApplierParser;
+
+ // Investigating... might change from String to AbstractSymbolApplier.
+ private Map<Address, Set<String>> labelsByAddress;
+ // Investigations into source/line info
+ private Map<String, Set<RecordNumber>> recordNumbersByFileName;
+ private Map<Integer, Set<RecordNumber>> recordNumbersByModuleNumber;
+
+ //==============================================================================================
+ // TODO: eventually put access methods on AbstractPdb to get filename from it (deep down).
+ public DefaultPdbApplicator(String pdbFilename, AbstractPdb pdb) {
+ Objects.requireNonNull(pdbFilename, "pdbFilename cannot be null");
+ Objects.requireNonNull(pdb, "pdb cannot be null");
+ this.pdbFilename = pdbFilename;
+ this.pdb = pdb;
+ }
+
+ //==============================================================================================
+ //==============================================================================================
+ /**
+ * Applies the PDB to the {@link Program} or {@link DataTypeManager}. Either, but not both,
+ * can be null.
+ * @param programParam The {@link Program} to which to apply the PDB. Can be null in certain
+ * circumstances.
+ * @param dataTypeManagerParam The {@link DataTypeManager} to which to apply data types. Can be
+ * null in certain circumstances.
+ * @param imageBaseParam Address bases from which symbol addresses are based. If null, uses
+ * the image base of the program (both cannot be null).
+ * @param applicatorOptionsParam {@link PdbApplicatorOptions} used for applying the PDB.
+ * @param monitorParam TaskMonitor uses for watching progress and cancellation notices.
+ * @param logParam The MessageLog to which to output messages.
+ * @throws PdbException if there was a problem processing the data.
+ * @throws CancelledException Upon user cancellation
+ */
+ public void applyTo(Program programParam, DataTypeManager dataTypeManagerParam,
+ Address imageBaseParam, PdbApplicatorOptions applicatorOptionsParam,
+ TaskMonitor monitorParam, MessageLog logParam) throws PdbException, CancelledException {
+
+ // FIXME: should not support use of DataTypeManager-only since it will not have the correct data
+ // organization if it corresponds to a data type archive. Need to evaulate archive use case
+ // and determine if a program must always be used.
+
+ initializeApplyTo(programParam, dataTypeManagerParam, imageBaseParam,
+ applicatorOptionsParam, monitorParam, logParam);
+
+ switch (applicatorOptions.getProcessingControl()) {
+ case DATA_TYPES_ONLY:
+ processTypes();
+ break;
+ case PUBLIC_SYMBOLS_ONLY:
+ processPublicSymbols();
+ break;
+ case ALL:
+ processTypes();
+ processSymbols();
+ break;
+ default:
+ throw new PdbException("PDB: Invalid Application Control: " +
+ applicatorOptions.getProcessingControl());
+ }
+
+ if (program != null) {
+ Options options = program.getOptions(Program.PROGRAM_INFO);
+ options.setBoolean(PdbParserConstants.PDB_LOADED, true);
+ }
+
+ pdbAddressManager.logReport();
+
+ pdbApplicatorMetrics.logReport();
+
+ Msg.info(this, "PDB Terminated Normally");
+ }
+
+ //==============================================================================================
+ private void processTypes() throws CancelledException, PdbException {
+ setMonitorMessage("PDB: Applying to DTM " + dataTypeManager.getName() + "...");
+
+ PdbResearch.initBreakPointRecordNumbers(); // for developmental debug
+
+ resolveCount = 0;
+
+// PdbResearch.childWalk(this, monitor);
+
+// PdbResearch.studyDataTypeConflicts(this, monitor);
+// PdbResearch.studyCompositeFwdRefDef(pdb, monitor);
+// PdbResearch.study1(pdb, monitor);
+
+ complexApplierMapper.mapAppliers(monitor);
+
+ processSequentially();
+
+// dumpSourceFileRecordNumbers();
+
+// PdbResearch.developerDebugOrder(this, monitor);
+
+ processDeferred();
+
+ resolveSequentially();
+
+ Msg.info(this, "resolveCount: " + resolveCount);
+
+ // Currently, defining classes needs to have a program. When this is no longer true,
+ // then this call can be performed with the data types only work.
+ if (program != null) {
+ defineClasses();
+ }
+
+ // Process typedefs, which are in the symbols.
+ processGlobalTypdefSymbols();
+ }
+
+ //==============================================================================================
+ private void processSymbols() throws CancelledException, PdbException {
+// PdbResearch.studyAggregateSymbols(this, monitor);
+
+ // TODO: not sure if the following will be relevant here, elsewhere, or nowhere.
+// if (!pdbAddressManager.garnerSectionSegmentInformation()) {
+// return;
+// }
+
+ // Doing globals before publics, as publics are those that can have mangled names. By
+ // applying the non-mangled symbols first, we can get full type information from the
+ // underlying type. Then we can apply the mangled symbols and demangle them without
+ // affecting our ability to lay down PDB type information--any type information from
+ // the mangled symbols can happen afterward.
+ processGlobalSymbolsNoTypedefs();
+ processPublicSymbols();
+
+ // Seems that we shouldn't do the following, as it could be a buffer of invalid symbols
+ // that hadn't been gone through for garbage collection of sorts.
+ //processNonPublicOrGlobalSymbols();
+
+ // Seems that we shouldn't do the following, as the ones that are needed seem to be
+ // referenced from a global symbol using a ReferencedSymbol. If we process the module
+ // symbols, as below, then collisions can start to appear at addresses. This has
+ // happened to me when I forgot to clear the results from a previous build, in which
+ // case I could find symbols referring to a location within the old build and within
+ // the latest build at the particular address corresponding to its location within that
+ // build. So a module might have symbols that had not been garbage-collected.
+ processModuleSymbols();
+
+ // These are good to process (one particular module for the linker).
+// processLinkerSymbols();
+
+ // Get additional thunks (that old pdb analyzer got).
+ processThunkSymbolsFromNonLinkerModules();
+
+ //processAllSymbols();
+
+// dumpLabels();
+ }
+
+ //==============================================================================================
+ //==============================================================================================
+ private void initializeApplyTo(Program programParam, DataTypeManager dataTypeManagerParam,
+ Address imageBaseParam, PdbApplicatorOptions applicatorOptionsParam,
+ TaskMonitor monitorParam, MessageLog logParam) throws PdbException, CancelledException {
+
+ validateAndSetParameters(programParam, dataTypeManagerParam, imageBaseParam,
+ applicatorOptionsParam, monitorParam, logParam);
+
+ cancelOnlyWrappingMonitor = new CancelOnlyWrappingTaskMonitor(monitor);
+ pdbApplicatorMetrics = new PdbApplicatorMetrics();
+
+ pdbPeHeaderInfoManager = new PdbPeHeaderInfoManager(this);
+
+ symbolGroups = createSymbolGroups();
+ linkerModuleNumber = findLinkerModuleNumber();
+
+ pdbAddressManager = new PdbAddressManager(this, imageBase);
+
+ categoryUtils = setPdbCatogoryUtils(pdbFilename);
+ pdbPrimitiveTypeApplicator = new PdbPrimitiveTypeApplicator(dataTypeManager);
+ typeApplierParser = new TypeApplierFactory(this);
+ complexApplierMapper = new ComplexTypeApplierMapper(this);
+ applierDependencyGraph = new JungDirectedGraph<>();
+ isClassByNamespace = new TreeMap<>();
+
+ symbolApplierParser = new SymbolApplierFactory(this);
+
+ if (program != null) {
+ // Currently, this must happen after symbolGroups are created.
+ PdbVbtManager pdbVbtManager = new PdbVbtManager(this);
+ //pdbVbtManager.CreateVirtualBaseTables(); // Depends on symbolGroups
+ vbtManager = pdbVbtManager;
+ registerNameToRegisterMapper = new PdbRegisterNameToProgramRegisterMapper(program);
+ }
+ else {
+ vbtManager = new VbtManager(getDataTypeManager());
+ }
+
+ // Investigations
+ labelsByAddress = new HashMap<>();
+ // Investigations into source/line info
+ recordNumbersByFileName = new HashMap<>();
+ recordNumbersByModuleNumber = new HashMap<>();
+ }
+
+ private void validateAndSetParameters(Program programParam,
+ DataTypeManager dataTypeManagerParam, Address imageBaseParam,
+ PdbApplicatorOptions applicatorOptionsParam, TaskMonitor monitorParam,
+ MessageLog logParam) throws PdbException {
+ applicatorOptions =
+ (applicatorOptionsParam != null) ? applicatorOptionsParam : new PdbApplicatorOptions();
+ if (programParam == null) {
+ if (dataTypeManagerParam == null) {
+ throw new PdbException(
+ "PDB: programParam and dataTypeManagerParam may not both be null.");
+ }
+ if (imageBaseParam == null) {
+ throw new PdbException(
+ "PDB: programParam and imageBaseParam may not both be null.");
+ }
+ if (applicatorOptions.getProcessingControl() != PdbApplicatorControl.DATA_TYPES_ONLY) {
+ throw new PdbException(
+ "PDB: programParam may not be null for the chosen Applicator Control: " +
+ applicatorOptions.getProcessingControl());
+ }
+ }
+ monitor = (monitorParam != null) ? monitorParam : TaskMonitor.DUMMY;
+ log = (logParam != null) ? logParam : new MessageLog();
+ program = programParam;
+ dataTypeManager =
+ (dataTypeManagerParam != null) ? dataTypeManagerParam : program.getDataTypeManager();
+ imageBase = (imageBaseParam != null) ? imageBaseParam : program.getImageBase();
+ }
+
+ private List<SymbolGroup> createSymbolGroups() throws CancelledException, PdbException {
+ List<SymbolGroup> mySymbolGroups = new ArrayList<>();
+ PdbDebugInfo debugInfo = pdb.getDebugInfo();
+ if (debugInfo == null) {
+ return mySymbolGroups;
+ }
+
+ int num = debugInfo.getNumModules();
+ // moduleNumber zero is our global/public group.
+ for (int moduleNumber = 0; moduleNumber <= num; moduleNumber++) {
+ monitor.checkCanceled();
+ Map<Long, AbstractMsSymbol> symbols = debugInfo.getModuleSymbolsByOffset(moduleNumber);
+ SymbolGroup symbolGroup = new SymbolGroup(symbols, moduleNumber);
+ mySymbolGroups.add(symbolGroup);
+ }
+ return mySymbolGroups;
+ }
+
+ //==============================================================================================
+ // Basic utility methods.
+ //==============================================================================================
+ /**
+ * Returns the {@link PdbApplicatorOptions} for this PdbApplicator.
+ * @return the {@link PdbApplicatorOptions} for this PdbApplicator.
+ */
+ PdbApplicatorOptions getPdbApplicatorOptions() {
+ return applicatorOptions;
+ }
+
+ /**
+ * Check to see if this monitor has been canceled
+ * @throws CancelledException if monitor has been cancelled
+ */
+ void checkCanceled() throws CancelledException {
+ monitor.checkCanceled();
+ }
+
+ /**
+ * Sets the message displayed on the task monitor
+ * @param message the message to display
+ */
+ void setMonitorMessage(String message) {
+ monitor.setMessage(message);
+ }
+
+ /**
+ * Sets the message displayed on the task monitor
+ * @param message the message to display
+ */
+ void appendLogMsg(String message) {
+ log.appendMsg(message);
+ }
+
+ /**
+ * Returns the MessageLog.
+ * @return the MessageLog
+ */
+ MessageLog getMessageLog() {
+ return log;
+ }
+
+ /**
+ * Puts message to {@link PdbLog} and to Msg.info()
+ * @param originator a Logger instance, "this", or YourClass.class
+ * @param message the message to display
+ */
+ void pdbLogAndInfoMessage(Object originator, String message) {
+ PdbLog.message(message);
+ Msg.info(originator, message);
+ }
+
+ /**
+ * Puts error message to {@link PdbLog} and to Msg.error() which will
+ * also log a stack trace if exception is specified.
+ * @param originator a Logger instance, "this", or YourClass.class
+ * @param message the error message to display/log
+ * @param exc exception whose stack trace should be reported or null
+ */
+ void pdbLogAndErrorMessage(Object originator, String message, Exception exc) {
+ PdbLog.message(message);
+ if (exc != null) {
+ Msg.error(originator, message);
+ }
+ else {
+ Msg.error(originator, message, exc);
+ }
+ }
+
+ /**
+ * Returns the {@link TaskMonitor} to available for this analyzer.
+ * @return the monitor.
+ */
+ TaskMonitor getMonitor() {
+ return monitor;
+ }
+
+ /**
+ * Returns the {@link CancelOnlyWrappingTaskMonitor} to available for this analyzer. This is
+ * useful for the user to be able to control the monitor progress bar without called commands
+ * changing its progress on smaller tasks.
+ * @return the monitor.
+ */
+ TaskMonitor getCancelOnlyWrappingMonitor() {
+ return cancelOnlyWrappingMonitor;
+ }
+
+ /**
+ * Returns the {@link PdbApplicatorMetrics} being used for this applicator.
+ * @return the {@link PdbApplicatorMetrics}.
+ */
+ PdbApplicatorMetrics getPdbApplicatorMetrics() {
+ return pdbApplicatorMetrics;
+ }
+
+ /**
+ * Returns the {@link AbstractPdb} being analyzed.
+ * @return {@link AbstractPdb} being analyzed.
+ */
+ @Override
+ public AbstractPdb getPdb() {
+ return pdb;
+ }
+
+ /**
+ * Returns the {@link Program} for which this analyzer is working.
+ * @return {@link Program} for which this analyzer is working.
+ */
+ @Override
+ public Program getProgram() {
+ return program;
+ }
+
+ //==============================================================================================
+ // Information for a putative PdbTypeApplicator:
+
+ /**
+ * Returns the {@link DataTypeManager} associated with this analyzer.
+ * @return DataTypeManager which this analyzer is using.
+ */
+ DataTypeManager getDataTypeManager() {
+ return dataTypeManager;
+ }
+
+ // for PdbTypeApplicator (new)
+ DataOrganization getDataOrganization() {
+ return dataTypeManager.getDataOrganization();
+ }
+
+ PdbPrimitiveTypeApplicator getPdbPrimitiveTypeApplicator() {
+ return pdbPrimitiveTypeApplicator;
+ }
+
+ //==============================================================================================
+ // CategoryPath-related methods.
+ //==============================================================================================
+ /**
+ * Get the {@link CategoryPath} associated with the {@link SymbolPath} specified, rooting
+ * it either at the PDB Category.
+ * @param symbolPath Symbol path to be used to create the CategoryPath. Null represents global
+ * namespace.
+ * @return {@link CategoryPath} created for the input.
+ */
+ CategoryPath getCategory(SymbolPath symbolPath) {
+ return categoryUtils.getCategory(symbolPath);
+ }
+
+ /**
+ * Returns the {@link CategoryPath} for a typedef with with the give {@link SymbolPath} and
+ * module number; 1 <= moduleNumber <= {@link PdbDebugInfo#getNumModules()},
+ * except that modeleNumber of 0 represents publics/globals.
+ * @param moduleNumber module number
+ * @param symbolPath SymbolPath of the symbol
+ * @return the CategoryPath
+ */
+ CategoryPath getTypedefsCategory(int moduleNumber, SymbolPath symbolPath) {
+ return categoryUtils.getTypedefsCategory(moduleNumber, symbolPath);
+ }
+
+ /**
+ * Returns the {@link CategoryPath} for Anonymous Functions Category for the PDB.
+ * @return the {@link CategoryPath}
+ */
+ CategoryPath getAnonymousFunctionsCategory() {
+ return categoryUtils.getAnonymousFunctionsCategory();
+ }
+
+ /**
+ * Returns the {@link CategoryPath} for Anonymous Types Category for the PDB.
+ * @return the {@link CategoryPath}
+ */
+ CategoryPath getAnonymousTypesCategory() {
+ return categoryUtils.getAnonymousTypesCategory();
+ }
+
+// /**
+// * Returns the name of what should be the next Anonymous Function (based on the count of
+// * the number of anonymous functions) so that there is a unique name for the function.
+// * @return the name for the next anonymous function.
+// */
+// String getNextAnonymousFunctionName() {
+// return categoryUtils.getNextAnonymousFunctionName();
+// }
+
+// /**
+// * Updates the count of the anonymous functions. This is a separate call from
+// * {@link #getNextAnonymousFunctionName()} because the count should only be updated after
+// * the previous anonymous function has been successfully created/stored.
+// */
+// void incrementNextAnonymousFunctionName() {
+// categoryUtils.incrementNextAnonymousFunctionName();
+// }
+
+ private PdbCategories setPdbCatogoryUtils(String pdbFilename)
+ throws CancelledException, PdbException {
+
+ List<String> categoryNames = new ArrayList<>();
+
+ PdbDebugInfo debugInfo = pdb.getDebugInfo();
+ if (debugInfo != null) {
+
+ int num = debugInfo.getNumModules();
+ for (int index = 1; index <= num; index++) {
+ monitor.checkCanceled();
+ String moduleName = debugInfo.getModuleInformation(index).getModuleName();
+ categoryNames.add(moduleName);
+ }
+ }
+
+ return new PdbCategories(FilenameUtils.getName(pdbFilename), categoryNames);
+ }
+
+ //==============================================================================================
+ // Applier-based-DataType-dependency-related methods.
+ //==============================================================================================
+ void addApplierDependency(MsTypeApplier depender) {
+ Objects.requireNonNull(depender);
+ applierDependencyGraph.addVertex(depender.getDependencyApplier());
+ }
+
+ void addApplierDependency(MsTypeApplier depender, MsTypeApplier dependee) {
+ Objects.requireNonNull(depender);
+ Objects.requireNonNull(dependee);
+ // TODO: Possibly do checks on dependee and depender types for actual creation
+ // of dependency--making this the one-stop-shop of this logic. Then make calls to
+ // this method from all possibly places. (Perhaps, for example, if depender is a
+ // pointer, then the logic would say "no.")
+ //
+ // Examples of where dependency should possibly be created (by not doing it, we are
+ // getting .conflict data types) include:
+ // structure or enum as a function return type or argument type.
+ //
+ applierDependencyGraph.addEdge(
+ new DefaultGEdge<>(depender.getDependencyApplier(), dependee.getDependencyApplier()));
+ }
+
+ List<MsTypeApplier> getVerticesInPostOrder() {
+ setMonitorMessage("PDB: Determining data type dependency order...");
+ return GraphAlgorithms.getVerticesInPostOrder(applierDependencyGraph,
+ GraphNavigator.topDownNavigator());
+ }
+
+ //==============================================================================================
+ //==============================================================================================
+ //==============================================================================================
+ MsTypeApplier getApplierSpec(RecordNumber recordNumber, Class<? extends MsTypeApplier> expected)
+ throws PdbException {
+ return typeApplierParser.getApplierSpec(recordNumber, expected);
+ }
+
+ MsTypeApplier getApplierOrNoTypeSpec(RecordNumber recordNumber,
+ Class<? extends MsTypeApplier> expected) throws PdbException {
+ return typeApplierParser.getApplierOrNoTypeSpec(recordNumber, expected);
+ }
+
+ MsTypeApplier getTypeApplier(RecordNumber recordNumber) {
+ //PdbResearch.checkBreak(recordNumber.getNumber());
+ return typeApplierParser.getTypeApplier(recordNumber);
+ }
+
+ MsTypeApplier getTypeApplier(AbstractMsType type) {
+ return typeApplierParser.getTypeApplier(type);
+ }
+
+ //==============================================================================================
+ //==============================================================================================
+ //==============================================================================================
+ int findModuleNumberBySectionOffsetContribution(int section, long offset) throws PdbException {
+ PdbDebugInfo debugInfo = pdb.getDebugInfo();
+ if (debugInfo == null) {
+ throw new PdbException("PDB: DebugInfo is null");
+ }
+
+ for (AbstractSectionContribution sectionContribution : debugInfo.getSectionContributionList()) {
+ int sectionContributionOffset = sectionContribution.getOffset();
+ int maxSectionContributionOffset =
+ sectionContributionOffset + sectionContribution.getLength();
+ if (offset >= sectionContributionOffset && offset < maxSectionContributionOffset) {
+ return sectionContribution.getModule();
+ }
+ }
+ throw new PdbException("PDB: Module not found for section/offset");
+ }
+
+ //==============================================================================================
+ private void processDataTypesSequentially() throws CancelledException, PdbException {
+ AbstractTypeProgramInterface tpi = pdb.getTypeProgramInterface();
+ if (tpi == null) {
+ return;
+ }
+ int num = tpi.getTypeIndexMaxExclusive() - tpi.getTypeIndexMin();
+ monitor.initialize(num);
+ setMonitorMessage("PDB: Processing " + num + " data type components...");
+ for (int indexNumber =
+ tpi.getTypeIndexMin(); indexNumber < tpi.getTypeIndexMaxExclusive(); indexNumber++) {
+ monitor.checkCanceled();
+ //PdbResearch.checkBreak(indexNumber);
+ MsTypeApplier applier = getTypeApplier(RecordNumber.typeRecordNumber(indexNumber));
+ //PdbResearch.checkBreak(indexNumber, applier);
+ applier.apply();
+ monitor.incrementProgress(1);
+ }
+ }
+
+ //==============================================================================================
+ //==============================================================================================
+ //==============================================================================================
+ // Investigations into source/line info
+ void putRecordNumberByFileName(RecordNumber recordNumber, String filename) {
+ Set<RecordNumber> recordNumbers = recordNumbersByFileName.get(filename);
+ if (recordNumbers == null) {
+ recordNumbers = new HashSet<>();
+ recordNumbersByFileName.put(filename, recordNumbers);
+ }
+ recordNumbers.add(recordNumber);
+ }
+
+ //==============================================================================================
+ void putRecordNumberByModuleNumber(RecordNumber recordNumber, int moduleNumber) {
+ Set<RecordNumber> recordNumbers = recordNumbersByModuleNumber.get(moduleNumber);
+ if (recordNumbers == null) {
+ recordNumbers = new HashSet<>();
+ recordNumbersByModuleNumber.put(moduleNumber, recordNumbers);
+ }
+ recordNumbers.add(recordNumber);
+ }
+
+ //==============================================================================================
+ void dumpSourceFileRecordNumbers() {
+ PdbLog.message("RecordNumbersByFileName");
+ for (Map.Entry<String, Set<RecordNumber>> entry : recordNumbersByFileName.entrySet()) {
+ String filename = entry.getKey();
+ PdbLog.message("FileName: " + filename);
+ for (RecordNumber recordNumber : entry.getValue()) {
+ AbstractMsType msType = pdb.getTypeRecord(recordNumber);
+ PdbLog.message(recordNumber.toString() + "\n" + msType);
+ }
+ }
+ PdbLog.message("RecordNumbersByModuleNumber");
+ for (Map.Entry<Integer, Set<RecordNumber>> entry : recordNumbersByModuleNumber.entrySet()) {
+ int moduleNumber = entry.getKey();
+ PdbLog.message("ModuleNumber: " + moduleNumber);
+ for (RecordNumber recordNumber : entry.getValue()) {
+ AbstractMsType msType = pdb.getTypeRecord(recordNumber);
+ PdbLog.message(recordNumber.toString() + "\n" + msType);
+ }
+ }
+ }
+
+ //==============================================================================================
+ //==============================================================================================
+ //==============================================================================================
+ private void processItemTypesSequentially() throws CancelledException, PdbException {
+ AbstractTypeProgramInterface ipi = pdb.getItemProgramInterface();
+ if (ipi == null) {
+ return;
+ }
+ int num = ipi.getTypeIndexMaxExclusive() - ipi.getTypeIndexMin();
+ monitor.initialize(num);
+ setMonitorMessage("PDB: Processing " + num + " item type components...");
+ for (int indexNumber =
+ ipi.getTypeIndexMin(); indexNumber < ipi.getTypeIndexMaxExclusive(); indexNumber++) {
+ monitor.checkCanceled();
+ MsTypeApplier applier = getTypeApplier(RecordNumber.itemRecordNumber(indexNumber));
+ applier.apply();
+ monitor.incrementProgress(1);
+ }
+ }
+
+ //==============================================================================================
+ private void processSequentially() throws CancelledException, PdbException {
+ processDataTypesSequentially();
+ processItemTypesSequentially();
+ }
+
+ //==============================================================================================
+ private void processDeferred() throws CancelledException, PdbException {
+ List<MsTypeApplier> verticesInPostOrder = getVerticesInPostOrder();
+ monitor.initialize(verticesInPostOrder.size());
+ setMonitorMessage("PDB: Processing " + verticesInPostOrder.size() +
+ " deferred data type dependencies...");
+ for (MsTypeApplier applier : verticesInPostOrder) {
+ monitor.checkCanceled();
+ //PdbResearch.checkBreak(applier.index);
+ //checkBreak(applier.index, applier);
+ if (applier.isDeferred()) {
+ applier.deferredApply();
+ }
+ monitor.incrementProgress(1);
+ }
+ }
+
+ //==============================================================================================
+ private void resolveSequentially() throws CancelledException {
+ AbstractTypeProgramInterface tpi = pdb.getTypeProgramInterface();
+ if (tpi == null) {
+ return;
+ }
+ int num = tpi.getTypeIndexMaxExclusive() - tpi.getTypeIndexMin();
+ monitor.initialize(num);
+ setMonitorMessage("PDB: Resolving " + num + " data type components...");
+ long longStart = System.currentTimeMillis();
+ for (int indexNumber =
+ tpi.getTypeIndexMin(); indexNumber < tpi.getTypeIndexMaxExclusive(); indexNumber++) {
+ monitor.checkCanceled();
+ //PdbResearch.checkBreak(indexNumber);
+ MsTypeApplier applier = getTypeApplier(RecordNumber.typeRecordNumber(indexNumber));
+ //PdbResearch.checkBreak(indexNumber, applier);
+ applier.resolve();
+ monitor.incrementProgress(1);
+ }
+ long longStop = System.currentTimeMillis();
+ long timeDiff = longStop - longStart;
+ Msg.info(this, "Resolve time: " + timeDiff + " mS");
+ }
+
+ //==============================================================================================
+ //==============================================================================================
+ //==============================================================================================
+ DataType resolve(DataType dataType) {
+ DataType resolved = getDataTypeManager().resolve(dataType,
+ DataTypeConflictHandler.REPLACE_EMPTY_STRUCTS_OR_RENAME_AND_ADD_HANDLER);
+ resolveCount++;
+ return resolved;
+ }
+
+ //==============================================================================================
+ //==============================================================================================
+ //==============================================================================================
+
+ //==============================================================================================
+ // SymbolGroup-related methods.
+ //==============================================================================================
+ SymbolGroup getSymbolGroup() {
+ return getSymbolGroupForModule(0);
+ }
+
+ SymbolGroup getSymbolGroupForModule(int moduleNumber) {
+ if (moduleNumber < 0 || moduleNumber >= symbolGroups.size()) {
+ return null;
+ }
+ return symbolGroups.get(moduleNumber);
+ }
+
+// public AbstractMsSymbol getSymbolForModuleAndOffset(int moduleNumber, long offset)
+// throws PdbException {
+// return pdb.getDebugInfo().getSymbolForModuleAndOffsetOfRecord(moduleNumber, offset);
+// }
+
+ //==============================================================================================
+ // Address-related methods.
+ //==============================================================================================
+ /**
+ * Returns true if the {@link Address} is an invalid address for continuing application of
+ * information to the program. Will report Error or message for an invalid address and will
+ * report a "External address" message for the name when the address is external.
+ * @param address the address to test
+ * @param name name associated with the address used for reporting error/info situations.
+ * @return {@code true} if the address should be processed.
+ */
+ boolean isInvalidAddress(Address address, String name) {
+ if (address == PdbAddressManager.BAD_ADDRESS) {
+ appendLogMsg("Invalid address encountered for: " + name);
+ return true;
+ }
+ if (address == PdbAddressManager.ZERO_ADDRESS) {
+ // Symbol OMAP resulted in 0 RVA - Discard silently
+ return true;
+ }
+ if (address == PdbAddressManager.EXTERNAL_ADDRESS) {
+ //Msg.info(this, "External address not known for: " + name);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Returns the image base Address being used by the applicator.
+ * @return The Address
+ */
+ Address getImageBase() {
+ return imageBase;
+ }
+
+ /**
+ * Returns the Address for the given section and offset.
+ * @param symbol The {@link AddressMsSymbol}
+ * @return The Address, which can be {@code Address.NO_ADDRESS} if invalid or
+ * {@code Address.EXTERNAL_ADDRESS} if the address is external to the program.
+ */
+ Address getAddress(AddressMsSymbol symbol) {
+ return pdbAddressManager.getAddress(symbol);
+ }
+
+ /**
+ * Returns the Address for the given section and offset.
+ * @param segment The segment
+ * @param offset The offset
+ * @return The Address
+ */
+ Address getAddress(int segment, long offset) {
+ return pdbAddressManager.getRawAddress(segment, offset);
+ }
+
+ /**
+ * Returns the Address for the given section and offset.
+ * @param symbol The {@link AddressMsSymbol}
+ * @return The Address, which can be {@code Address.NO_ADDRESS} if invalid or
+ * {@code Address.EXTERNAL_ADDRESS} if the address is external to the program.
+ */
+ Address getRawAddress(AddressMsSymbol symbol) {
+ return pdbAddressManager.getRawAddress(symbol);
+ }
+
+ /**
+ * Indicate to the {@link PdbAddressManager} that a new symbol with the given name has the
+ * associated address. This allows the PdbAddressManager to create and organize the
+ * re-mapped address and supply them. Also returns the address of the pre-existing symbol
+ * of the same name if the name was unique, otherwise null if it didn't exist or wasn't
+ * unique.
+ * @param name the symbol name
+ * @param address its associated address
+ * @return the {@link Address} of existing symbol or null
+ */
+ Address witnessSymbolNameAtAddress(String name, Address address) {
+ return pdbAddressManager.witnessSymbolNameAtAddress(name, address);
+ }
+
+ /**
+ * Returns the Address of an existing symbol for the query address, where the mapping is
+ * derived by using a the address of a PDB symbol as the key and finding the address of
+ * a symbol in the program of the same "unique" name. This is accomplished using public
+ * mangled symbols. If the program symbol came from the PDB, then it maps to itself.
+ * @param address the query address
+ * @return the remapAddress
+ */
+ Address getRemapAddressByAddress(Address address) {
+ return pdbAddressManager.getRemapAddressByAddress(address);
+ }
+
+ /**
+ * Method for callee to add a Memory Group symbol to the Memory Group list.
+ * @param symbol the symbol.
+ */
+ void addMemoryGroupRefinement(PeCoffGroupMsSymbol symbol) {
+ pdbAddressManager.addMemoryGroupRefinement(symbol);
+ }
+
+ /**
+ * Method for callee to add a Memory Section symbol to the Memory Section list.
+ * @param symbol the symbol.
+ */
+ void addMemorySectionRefinement(PeCoffSectionMsSymbol symbol) {
+ pdbAddressManager.addMemorySectionRefinement(symbol);
+ }
+
+ //==============================================================================================
+ // PdbPeHeaderInfoManager access methods.
+ //==============================================================================================
+
+ boolean isDll() {
+ return pdbPeHeaderInfoManager.isDll();
+ }
+
+ boolean isAslr() {
+ return pdbPeHeaderInfoManager.isAslr();
+ }
+
+ @Override
+ public long getOriginalImageBase() {
+ // TODO: If/when this becomes a program property, then get it from the program.
+ return pdbPeHeaderInfoManager.getOriginalImageBase();
+ }
+
+ /**
+ * Get CLI metadata for specified tableNum and rowNum within the CLI
+ * metadata stream.
+ * @param tableNum CLI metadata stream table index
+ * @param rowNum table row number
+ * @return CLI metadata or null if specified tableNum not found
+ * @throws PdbException if CLI metadata stream is not found in program file bytes
+ * @throws IndexOutOfBoundsException if specified rowNum is invalid
+ */
+ CliAbstractTableRow getCliTableRow(int tableNum, int rowNum) throws PdbException {
+ return pdbPeHeaderInfoManager.getCliTableRow(tableNum, rowNum);
+ }
+
+ //==============================================================================================
+ // Virtual-Base-Table-related methods.
+ //==============================================================================================
+ VbtManager getVbtManager() {
+ return vbtManager;
+ }
+
+ //==============================================================================================
+ //
+ //==============================================================================================
+ Register getRegister(String pdbRegisterName) {
+ return registerNameToRegisterMapper.getRegister(pdbRegisterName);
+ }
+
+ //==============================================================================================
+ //==============================================================================================
+ @SuppressWarnings("unused") // for method not being called.
+ /**
+ * Process all symbols. User should not then call other methods:
+ * {@link #processGlobalSymbolsNoTypedefs()}, (@link #processPublicSymbols()}, and
+ * {@link #processNonPublicOrGlobalSymbols()}.
+ * @throws CancelledException upon user cancellation
+ * @throws PdbException upon issue processing the request
+ */
+ private void processAllSymbols() throws CancelledException, PdbException {
+ processMainSymbols();
+ processModuleSymbols();
+ }
+
+ //==============================================================================================
+ @SuppressWarnings("unused") // for method not being called.
+ private void processMainSymbols() throws CancelledException, PdbException {
+ // Get a count
+ SymbolGroup symbolGroup = getSymbolGroup();
+ if (symbolGroup == null) {
+ return;
+ }
+ int totalCount = symbolGroup.size();
+ setMonitorMessage("PDB: Applying " + totalCount + " main symbol components...");
+ monitor.initialize(totalCount);
+ AbstractMsSymbolIterator iter = symbolGroup.iterator();
+ processSymbolGroup(0, iter);
+ }
+
+ //==============================================================================================
+ private void processModuleSymbols() throws CancelledException {
+ PdbDebugInfo debugInfo = pdb.getDebugInfo();
+ if (debugInfo == null) {
+ return;
+ }
+
+ int totalCount = 0;
+ int num = debugInfo.getNumModules();
+ for (int moduleNumber = 1; moduleNumber <= num; moduleNumber++) {
+ monitor.checkCanceled();
+ SymbolGroup symbolGroup = getSymbolGroupForModule(moduleNumber);
+ if (symbolGroup == null) {
+ continue; // should not happen
+ }
+ totalCount += symbolGroup.size();
+ }
+ setMonitorMessage("PDB: Applying " + totalCount + " module symbol components...");
+ monitor.initialize(totalCount);
+
+ // Process symbols list for each module
+ for (int moduleNumber = 1; moduleNumber <= num; moduleNumber++) {
+ monitor.checkCanceled();
+ // Process module symbols list
+ SymbolGroup symbolGroup = getSymbolGroupForModule(moduleNumber);
+ if (symbolGroup == null) {
+ continue; // should not happen
+ }
+ AbstractMsSymbolIterator iter = symbolGroup.iterator();
+ processSymbolGroup(moduleNumber, iter);
+// catelogSymbols(index, symbolGroup);
+ // do not call monitor.incrementProgress(1) here, as it is updated inside of
+ // processSymbolGroup.
+ }
+ }
+
+// private Set<Class<? extends AbstractMsSymbol>> moduleSymbols = new HashSet<>();
+//
+// private void catelogSymbols(int moduleNumber, SymbolGroup symbolGroup)
+// throws CancelledException {
+// symbolGroup.initGet();
+// while (symbolGroup.hasNext()) {
+// monitor.checkCanceled();
+// AbstractMsSymbol symbol = symbolGroup.peek();
+// moduleSymbols.add(symbol.getClass());
+// symbolGroup.next();
+// }
+// }
+//
+ //==============================================================================================
+ private void processSymbolGroup(int moduleNumber, AbstractMsSymbolIterator iter)
+ throws CancelledException {
+ iter.initGet();
+ while (iter.hasNext()) {
+ monitor.checkCanceled();
+ procSym(iter);
+ monitor.incrementProgress(1);
+ }
+ }
+
+ //==============================================================================================
+ /**
+ * Process public symbols. User should not then call {@link #processAllSymbols()}; but
+ * has these other methods available to supplement this one: {@link #processGlobalSymbolsNoTypedefs()}
+ * and {@link #processNonPublicOrGlobalSymbols()}.
+ * @throws CancelledException upon user cancellation
+ * @throws PdbException upon issue processing the request
+ */
+ private void processPublicSymbols() throws CancelledException, PdbException {
+
+ PdbDebugInfo debugInfo = pdb.getDebugInfo();
+ if (debugInfo == null) {
+ return;
+ }
+
+ SymbolGroup symbolGroup = getSymbolGroup();
+ if (symbolGroup == null) {
+ return;
+ }
+
+ PublicSymbolInformation publicSymbolInformation = debugInfo.getPublicSymbolInformation();
+ List<Long> offsets = publicSymbolInformation.getModifiedHashRecordSymbolOffsets();
+ setMonitorMessage("PDB: Applying " + offsets.size() + " public symbol components...");
+ monitor.initialize(offsets.size());
+
+ AbstractMsSymbolIterator iter = symbolGroup.iterator();
+ for (long offset : offsets) {
+ monitor.checkCanceled();
+ iter.initGetByOffset(offset);
+ if (!iter.hasNext()) {
+ break;
+ }
+ pdbApplicatorMetrics.witnessPublicSymbolType(iter.peek());
+ procSym(iter);
+ monitor.incrementProgress(1);
+ }
+ }
+
+ /**
+ * Process global symbols--no typedef. User should not then call {@link #processAllSymbols()};
+ * but has these other methods available to supplement this one: (@link #processPublicSymbols()}
+ * and {@link #processNonPublicOrGlobalSymbols()}.
+ * @throws CancelledException upon user cancellation
+ * @throws PdbException upon issue processing the request
+ */
+ private void processGlobalSymbolsNoTypedefs() throws CancelledException, PdbException {
+
+ PdbDebugInfo debugInfo = pdb.getDebugInfo();
+ if (debugInfo == null) {
+ return;
+ }
+
+ SymbolGroup symbolGroup = getSymbolGroup();
+ if (symbolGroup == null) {
+ return;
+ }
+
+ GlobalSymbolInformation globalSymbolInformation = debugInfo.getGlobalSymbolInformation();
+ List<Long> offsets = globalSymbolInformation.getModifiedHashRecordSymbolOffsets();
+ setMonitorMessage("PDB: Applying global symbols...");
+ monitor.initialize(offsets.size());
+
+ AbstractMsSymbolIterator iter = symbolGroup.iterator();
+ for (long offset : offsets) {
+ monitor.checkCanceled();
+ iter.initGetByOffset(offset);
+ if (!iter.hasNext()) {
+ break;
+ }
+ AbstractMsSymbol symbol = iter.peek();
+ pdbApplicatorMetrics.witnessGlobalSymbolType(symbol);
+ if (!(symbol instanceof AbstractUserDefinedTypeMsSymbol)) { // Not doing typedefs here
+ procSym(iter);
+ }
+ monitor.incrementProgress(1);
+ }
+ }
+
+ /**
+ * Process global typdef symbols.
+ * @throws CancelledException upon user cancellation
+ * @throws PdbException upon issue processing the request
+ */
+ private void processGlobalTypdefSymbols() throws CancelledException, PdbException {
+
+ PdbDebugInfo debugInfo = pdb.getDebugInfo();
+ if (debugInfo == null) {
+ return;
+ }
+
+ SymbolGroup symbolGroup = getSymbolGroup();
+ if (symbolGroup == null) {
+ return;
+ }
+
+ GlobalSymbolInformation globalSymbolInformation = debugInfo.getGlobalSymbolInformation();
+ List<Long> offsets = globalSymbolInformation.getModifiedHashRecordSymbolOffsets();
+ setMonitorMessage("PDB: Applying typedefs...");
+ monitor.initialize(offsets.size());
+
+ AbstractMsSymbolIterator iter = symbolGroup.iterator();
+ for (long offset : offsets) {
+ monitor.checkCanceled();
+ iter.initGetByOffset(offset);
+ if (!iter.hasNext()) {
+ break;
+ }
+ AbstractMsSymbol symbol = iter.peek();
+ if (symbol instanceof AbstractUserDefinedTypeMsSymbol) { // Doing typedefs here
+ procSym(iter);
+ }
+ monitor.incrementProgress(1);
+ }
+ }
+
+ /**
+ * Processing non-public, non-global symbols. User should not then call
+ * {@link #processAllSymbols()}; but has these other methods available to supplement this one:
+ * {@link #processGlobalSymbolsNoTypedefs()} and (@link #processPublicSymbols()}.
+ * @throws CancelledException upon user cancellation
+ * @throws PdbException upon issue processing the request
+ */
+ @SuppressWarnings("unused") // for method not being called.
+ private void processNonPublicOrGlobalSymbols() throws CancelledException, PdbException {
+ PdbDebugInfo debugInfo = pdb.getDebugInfo();
+ if (debugInfo == null) {
+ return;
+ }
+
+ SymbolGroup symbolGroup = getSymbolGroup();
+ if (symbolGroup == null) {
+ return;
+ }
+
+ Set<Long> offsetsRemaining = symbolGroup.getOffsets();
+ for (long off : debugInfo.getPublicSymbolInformation().getModifiedHashRecordSymbolOffsets()) {
+ monitor.checkCanceled();
+ offsetsRemaining.remove(off);
+ }
+ for (long off : debugInfo.getGlobalSymbolInformation().getModifiedHashRecordSymbolOffsets()) {
+ monitor.checkCanceled();
+ offsetsRemaining.remove(off);
+ }
+
+ setMonitorMessage(
+ "PDB: Applying " + offsetsRemaining.size() + " other symbol components...");
+ monitor.initialize(offsetsRemaining.size());
+ //getCategoryUtils().setModuleTypedefsCategory(null);
+
+ AbstractMsSymbolIterator iter = symbolGroup.iterator();
+ for (long offset : offsetsRemaining) {
+ monitor.checkCanceled();
+ iter.initGetByOffset(offset);
+ AbstractMsSymbol symbol = iter.peek();
+ procSym(iter);
+ monitor.incrementProgress(1);
+ }
+ }
+
+ //==============================================================================================
+ int getLinkerModuleNumber() {
+ return linkerModuleNumber;
+ }
+
+ private int findLinkerModuleNumber() {
+ PdbDebugInfo debugInfo = pdb.getDebugInfo();
+ if (debugInfo != null) {
+ int num = 1;
+ for (AbstractModuleInformation module : debugInfo.getModuleInformationList()) {
+ if (isLinkerModule(module.getModuleName())) {
+ return num;
+ }
+ num++;
+ }
+ }
+ pdbLogAndInfoMessage(this, "Not processing linker symbols because linker module not found");
+ return -1;
+ }
+
+ private boolean isLinkerModule(String name) {
+ return "* Linker *".equals(name);
+ }
+
+ //==============================================================================================
+ @SuppressWarnings("unused") // for method not being called.
+ private boolean processLinkerSymbols() throws CancelledException {
+
+ SymbolGroup symbolGroup = getSymbolGroupForModule(linkerModuleNumber);
+ if (symbolGroup == null) {
+ Msg.info(this, "No symbols to process from linker module.");
+ return false;
+ }
+
+ setMonitorMessage("PDB: Applying " + symbolGroup.size() + " linker symbol components...");
+ monitor.initialize(symbolGroup.size());
+
+ AbstractMsSymbolIterator iter = symbolGroup.iterator();
+ while (iter.hasNext()) {
+ checkCanceled();
+ pdbApplicatorMetrics.witnessLinkerSymbolType(iter.peek());
+ procSym(iter);
+ monitor.incrementProgress(1);
+ }
+ return true;
+ }
+
+ //==============================================================================================
+ @Override
+ public List<PeCoffSectionMsSymbol> getLinkerPeCoffSectionSymbols() throws CancelledException {
+ processLinkerModuleSpecialInformation();
+ return linkerPeCoffSectionSymbols;
+ }
+
+ //==============================================================================================
+ @Override
+ public AbstractMsSymbol getLinkerModuleCompileSymbol() throws CancelledException {
+ processLinkerModuleSpecialInformation();
+ return compileSymbolForLinkerModule;
+ }
+
+ //==============================================================================================
+ private void processLinkerModuleSpecialInformation() throws CancelledException {
+
+ if (processedLinkerModule) {
+ return;
+ }
+
+ List<PeCoffSectionMsSymbol> symbols = new ArrayList<>();
+ AbstractMsSymbol compileSymbol = null;
+
+ SymbolGroup symbolGroup = getSymbolGroupForModule(linkerModuleNumber);
+ if (symbolGroup != null) {
+
+ getMonitor().initialize(symbolGroup.size());
+ AbstractMsSymbolIterator iter = symbolGroup.iterator();
+ int numCompileSymbols = 0;
+ int compileSymbolNumForCoffSymbols = -1;
+ while (iter.hasNext()) {
+ checkCanceled();
+ AbstractMsSymbol symbol = iter.next();
+ getPdbApplicatorMetrics().witnessLinkerSymbolType(symbol);
+ if (symbol instanceof PeCoffSectionMsSymbol) {
+ symbols.add((PeCoffSectionMsSymbol) symbol);
+ // Putting this test and log information here if our processing hypothesis is
+ // in correct in regard to theory that PE COFF symbols will be found after a
+ // COMPILE symbol for those COFF symbols.
+ if (numCompileSymbols == 0) {
+ Msg.info(this, "PE COFF symbol found before linker compile symbol");
+ }
+ if (compileSymbolNumForCoffSymbols == -1) {
+ compileSymbolNumForCoffSymbols = numCompileSymbols;
+ }
+ else if (compileSymbolNumForCoffSymbols != numCompileSymbols) {
+ Msg.info(this, "Linker COFF symbols found under multiple compiler symbols");
+ }
+ }
+ else if (symbol instanceof Compile3MsSymbol ||
+ symbol instanceof AbstractCompile2MsSymbol) {
+ numCompileSymbols++;
+ // Doing this check because we do not know if there can be more than one
+ // compile symbol. If there is more than one, we want the one that
+ // immediately precedes the PE COFF symbols, However, there are multiple
+ // compile symbols that have PE COFF symbols following them, then we
+ // would probably have to change this code and the code that uses this
+ // information,
+ if (symbols.isEmpty()) {
+ compileSymbol = symbol;
+ }
+ }
+ monitor.incrementProgress(1);
+ }
+ }
+
+ // Deferring assignment because above loop can be canceled.
+ linkerPeCoffSectionSymbols = symbols;
+ compileSymbolForLinkerModule = compileSymbol;
+ processedLinkerModule = true;
+ }
+
+ //==============================================================================================
+ private void processThunkSymbolsFromNonLinkerModules() throws CancelledException {
+
+ PdbDebugInfo debugInfo = pdb.getDebugInfo();
+ if (debugInfo == null) {
+ return;
+ }
+
+ int totalCount = 0;
+ int num = debugInfo.getNumModules();
+ for (int index = 1; index <= num; index++) {
+ monitor.checkCanceled();
+ if (index == linkerModuleNumber) {
+ continue;
+ }
+ SymbolGroup symbolGroup = getSymbolGroupForModule(index);
+ if (symbolGroup == null) {
+ continue; // should not happen
+ }
+ totalCount += symbolGroup.size();
+ }
+ setMonitorMessage("PDB: Processing module thunks...");
+ monitor.initialize(totalCount);
+
+ // Process symbols list for each module
+ for (int index = 1; index <= num; index++) {
+ monitor.checkCanceled();
+ if (index == linkerModuleNumber) {
+ continue;
+ }
+ SymbolGroup symbolGroup = getSymbolGroupForModule(index);
+ if (symbolGroup == null) {
+ continue; // should not happen
+ }
+ AbstractMsSymbolIterator iter = symbolGroup.iterator();
+ while (iter.hasNext()) {
+ monitor.checkCanceled();
+ AbstractMsSymbol symbol = iter.peek();
+ if (symbol instanceof AbstractThunkMsSymbol) {
+ procSym(iter);
+ }
+ else {
+ iter.next();
+ }
+ monitor.incrementProgress(1);
+ }
+ }
+
+ }
+
+ //==============================================================================================
+ //==============================================================================================
+ //==============================================================================================
+ MsSymbolApplier getSymbolApplier(AbstractMsSymbolIterator iter) throws CancelledException {
+ return symbolApplierParser.getSymbolApplier(iter);
+ }
+
+ //==============================================================================================
+ void procSym(AbstractMsSymbolIterator iter) throws CancelledException {
+ try {
+ MsSymbolApplier applier = getSymbolApplier(iter);
+ applier.apply();
+ }
+ catch (PdbException e) {
+ // skipping symbol
+ Msg.info(this, "Error applying symbol to program: " + e.toString());
+ }
+ }
+
+ //==============================================================================================
+ //==============================================================================================
+ //==============================================================================================
+ boolean isClass(SymbolPath path) {
+ return isClassByNamespace.get(path);
+ }
+
+ //==============================================================================================
+ void predefineClass(SymbolPath classPath) {
+ isClassByNamespace.put(classPath, true);
+ for (SymbolPath path = classPath.getParent(); path != null; path = path.getParent()) {
+ if (!isClassByNamespace.containsKey(path)) {
+ isClassByNamespace.put(path, false); // path is simple namespace
+ }
+ }
+ }
+
+ //==============================================================================================
+ private void defineClasses() throws CancelledException {
+ // create namespace and classes in an ordered fashion use tree map
+ monitor.initialize(isClassByNamespace.size());
+ setMonitorMessage("PDB: Defining classes...");
+ for (Map.Entry<SymbolPath, Boolean> entry : isClassByNamespace.entrySet()) {
+ monitor.checkCanceled();
+ SymbolPath path = entry.getKey();
+ boolean isClass = entry.getValue();
+ Namespace parentNamespace =
+ NamespaceUtils.getNonFunctionNamespace(program, path.getParent());
+ if (parentNamespace == null) {
+ String type = isClass ? "class" : "namespace";
+ log.appendMsg(
+ "PDB Warning: Because parent namespace does not exist, failed to define " +
+ type + ": " + path);
+ continue;
+ }
+ defineNamespace(parentNamespace, path.getName(), isClass);
+ monitor.incrementProgress(1);
+
+ }
+ }
+
+ //==============================================================================================
+ private void defineNamespace(Namespace parentNamespace, String name, boolean isClass) {
+
+ try {
+ SymbolTable symbolTable = program.getSymbolTable();
+ Namespace namespace = symbolTable.getNamespace(name, parentNamespace);
+ if (namespace != null) {
+ if (isClass) {
+ if (namespace instanceof GhidraClass) {
+ return;
+ }
+ if (isSimpleNamespaceSymbol(namespace)) {
+ NamespaceUtils.convertNamespaceToClass(namespace);
+ return;
+ }
+ }
+ else if (namespace.getSymbol().getSymbolType() == SymbolType.NAMESPACE) {
+ return;
+ }
+ log.appendMsg(
+ "PDB Warning: Unable to create class namespace due to conflicting symbol: " +
+ namespace.getName(true));
+ }
+ else if (isClass) {
+ symbolTable.createClass(parentNamespace, name, SourceType.IMPORTED);
+ }
+ else {
+ symbolTable.createNameSpace(parentNamespace, name, SourceType.IMPORTED);
+ }
+ }
+ catch (InvalidInputException | DuplicateNameException e) {
+ log.appendMsg(
+ "PDB Warning: Unable to create class namespace due to exception: " + e.toString() +
+ "; Namespace: " + parentNamespace.getName(true) + Namespace.DELIMITER + name);
+ }
+ }
+
+ //==============================================================================================
+ private boolean isSimpleNamespaceSymbol(Namespace namespace) {
+ Symbol s = namespace.getSymbol();
+ if (s.getSymbolType() != SymbolType.NAMESPACE) {
+ return false;
+ }
+ Namespace n = namespace;
+ while (n != null) {
+ if (n instanceof Function) {
+ return false;
+ }
+ n = n.getParentNamespace();
+ }
+ return true;
+ }
+
+ //==============================================================================================
+ //==============================================================================================
+ //==============================================================================================
+ @SuppressWarnings("unused") // for method not being called.
+ private void storeLabelByAddress(Address address, String label) {
+ Set<String> labels = labelsByAddress.get(address);
+ if (labels == null) {
+ labels = new TreeSet<>();
+ labelsByAddress.put(address, labels);
+ }
+ if (labels.contains(label)) {
+ // TODO investigate why we would see it again.
+ }
+ labels.add(label);
+ }
+
+ @SuppressWarnings("unused") // for method not being called.
+ private void dumpLabels() {
+ for (Map.Entry<Address, Set<String>> entry : labelsByAddress.entrySet()) {
+ Address address = entry.getKey();
+ Set<String> labels = entry.getValue();
+ System.out.println("\nAddress: " + address);
+ for (String label : labels) {
+ System.out.println(label);
+ }
+ }
+ }
+
+ //==============================================================================================
+ boolean shouldForcePrimarySymbol(Address address, boolean forceIfMangled) {
+ Symbol primarySymbol = program.getSymbolTable().getPrimarySymbol(address);
+ if (primarySymbol != null) {
+
+ if (primarySymbol.getName().startsWith("?") && forceIfMangled &&
+ applicatorOptions.allowDemotePrimaryMangledSymbols()) {
+ return true;
+ }
+
+ SourceType primarySymbolSource = primarySymbol.getSource();
+
+ if (!SourceType.ANALYSIS.isHigherPriorityThan(primarySymbolSource)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ //==============================================================================================
+ @SuppressWarnings("unused") // For method not being called. In process of removing this version
+ boolean createSymbolOld(Address address, String symbolPathString, boolean forcePrimary) {
+
+// storeLabelByAddress(address, symbolPathString);
+
+ try {
+ Namespace namespace = program.getGlobalNamespace();
+ if (symbolPathString.startsWith(THUNK_NAME_PREFIX)) {
+ symbolPathString = symbolPathString.substring(THUNK_NAME_PREFIX.length(),
+ symbolPathString.length());
+ }
+ SymbolPath symbolPath = new SymbolPath(symbolPathString);
+ symbolPath = symbolPath.replaceInvalidChars();
+ String name = symbolPath.getName();
+ String namespacePath = symbolPath.getParentPath();
+ if (namespacePath != null) {
+ namespace = NamespaceUtils.createNamespaceHierarchy(namespacePath, namespace,
+ program, address, SourceType.IMPORTED);
+ }
+
+ Symbol s = SymbolUtilities.createPreferredLabelOrFunctionSymbol(program, address,
+ namespace, name, SourceType.IMPORTED);
+ if (s != null && forcePrimary) {
+ // PDB contains both mangled, namespace names, and global names
+ // If mangled name does not remain primary it will not get demamgled
+ // and we may not get signature information applied
+ SetLabelPrimaryCmd cmd =
+ new SetLabelPrimaryCmd(address, s.getName(), s.getParentNamespace());
+ cmd.applyTo(program);
+ }
+ return true;
+ }
+ catch (InvalidInputException e) {
+ log.appendMsg("PDB Warning: Unable to create symbol: " + e.getMessage());
+ }
+ return false;
+ }
+
+ //==============================================================================================
+ private static class PrimarySymbolInfo {
+ private Symbol symbol;
+ private boolean isNewSymbol;
+
+ private PrimarySymbolInfo(Symbol symbol, boolean isNewSymbol) {
+ this.symbol = symbol;
+ this.isNewSymbol = isNewSymbol;
+ }
+
+ private boolean canBePrimaryForceOverriddenBy(String newName) {
+ if (getSource().isLowerPriorityThan(SourceType.IMPORTED)) {
+ return true;
+ }
+ if (isMangled() && !DefaultPdbApplicator.isMangled(newName)) {
+ return true;
+ }
+ if (isNewSymbol()) {
+ return false;
+ }
+ return false;
+ }
+
+ private SourceType getSource() {
+ return symbol.getSource();
+ }
+
+ private boolean isMangled() {
+ return symbol.getName().startsWith("?");
+ }
+
+ private boolean isNewSymbol() {
+ return isNewSymbol;
+ }
+ }
+
+ private Map<Address, PrimarySymbolInfo> primarySymbolInfoByAddress = new HashMap<>();
+
+ //==============================================================================================
+ Symbol createSymbol(Address address, String symbolPathString,
+ boolean forcePrimaryIfExistingIsMangled) {
+ return createSymbol(address, symbolPathString, forcePrimaryIfExistingIsMangled, null);
+ }
+
+ Symbol createSymbol(Address address, String symbolPathString,
+ boolean forcePrimaryIfExistingIsMangled, String plateAddition) {
+
+ // Must get existing info before creating new symbol, as we do not want "existing"
+ // to include the new one
+ PrimarySymbolInfo existingPrimarySymbolInfo = getExistingPrimarySymbolInfo(address);
+ Symbol newSymbol = createSymbol(address, symbolPathString);
+ if (newSymbol == null) {
+ return null;
+ }
+
+ boolean forcePrimary = false;
+ if (existingPrimarySymbolInfo != null) {
+ if (existingPrimarySymbolInfo.canBePrimaryForceOverriddenBy(symbolPathString) &&
+ forcePrimaryIfExistingIsMangled &&
+ applicatorOptions.allowDemotePrimaryMangledSymbols()) {
+ forcePrimary = true;
+ }
+ }
+
+ boolean forcePrimarySucceeded = false;
+ if (forcePrimary) {
+ SetLabelPrimaryCmd cmd = new SetLabelPrimaryCmd(address, newSymbol.getName(),
+ newSymbol.getParentNamespace());
+ if (cmd.applyTo(program)) {
+ forcePrimarySucceeded = true;
+ }
+ }
+
+ if (existingPrimarySymbolInfo == null || forcePrimarySucceeded) {
+ PrimarySymbolInfo primarySymbolInfo = new PrimarySymbolInfo(newSymbol, true);
+ setExistingPrimarySymbolInfo(address, primarySymbolInfo);
+ }
+
+ addToPlateUnique(address, plateAddition);
+
+ return newSymbol;
+ }
+
+ private boolean addToPlateUnique(Address address, String comment) {
+ if (StringUtils.isBlank(comment)) {
+ return false;
+ }
+ String plate = program.getListing().getComment(CodeUnit.PLATE_COMMENT, address);
+ if (plate == null) {
+ plate = "";
+ }
+ else if (plate.contains(comment)) {
+ return true;
+ }
+ else if (!plate.endsWith("\n")) {
+ plate += '\n';
+ }
+ plate += comment;
+ SetCommentCmd.createComment(program, address, comment, CodeUnit.PLATE_COMMENT);
+ return true;
+ }
+
+ private static boolean isMangled(String name) {
+ return name.startsWith("?");
+ }
+
+ private void setExistingPrimarySymbolInfo(Address address, PrimarySymbolInfo info) {
+ primarySymbolInfoByAddress.put(address, info);
+ }
+
+ private PrimarySymbolInfo getExistingPrimarySymbolInfo(Address address) {
+ PrimarySymbolInfo info = primarySymbolInfoByAddress.get(address);
+ if (info != null) {
+ return info;
+ }
+ Symbol primarySymbol = pdbAddressManager.getPrimarySymbol(address);
+ if (primarySymbol == null ||
+ primarySymbol.getSource().isLowerPriorityThan(SourceType.IMPORTED)) {
+ return null;
+ }
+ info = new PrimarySymbolInfo(primarySymbol, false);
+ primarySymbolInfoByAddress.put(address, info);
+ return info;
+ }
+
+ private Symbol createSymbol(Address address, String symbolPathString) {
+ Symbol symbol = null;
+ try {
+ Namespace namespace = program.getGlobalNamespace();
+ if (symbolPathString.startsWith(THUNK_NAME_PREFIX)) {
+ symbolPathString = symbolPathString.substring(THUNK_NAME_PREFIX.length(),
+ symbolPathString.length());
+ }
+ SymbolPath symbolPath = new SymbolPath(symbolPathString);
+ symbolPath = symbolPath.replaceInvalidChars();
+ String name = symbolPath.getName();
+ String namespacePath = symbolPath.getParentPath();
+ if (namespacePath != null) {
+ namespace = NamespaceUtils.createNamespaceHierarchy(namespacePath, namespace,
+ program, address, SourceType.IMPORTED);
+ }
+
+ symbol =
+ program.getSymbolTable().createLabel(address, name, namespace, SourceType.IMPORTED);
+ }
+ catch (InvalidInputException e) {
+ log.appendMsg("PDB Warning: Unable to create symbol at " + address +
+ " due to exception: " + e.toString() + "; symbolPathName: " + symbolPathString);
+ }
+ return symbol;
+ }
+
+}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DefaultPdbUniversalMember.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DefaultPdbUniversalMember.java
index 87452478b9..f52254e855 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DefaultPdbUniversalMember.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DefaultPdbUniversalMember.java
@@ -32,14 +32,14 @@ public class DefaultPdbUniversalMember extends PdbMember {
/**
* Default PDB member construction
- * @param applicator {@link PdbApplicator} for which we are working.
+ * @param applicator {@link DefaultPdbApplicator} for which we are working.
* @param name member field name. For bitfields this also conveys the bit-size
* and optionally the bit-offset.
* @param applier fieldApplier for the field datatype or base datatype associated with the
* bitfield.
* @param offset member's byte offset within the root composite.
*/
- DefaultPdbUniversalMember(PdbApplicator applicator, String name, MsTypeApplier applier,
+ DefaultPdbUniversalMember(DefaultPdbApplicator applicator, String name, MsTypeApplier applier,
int offset) {
super(name, (applier.getDataType()).getName(), offset, null);
this.applier = applier;
@@ -48,13 +48,13 @@ public class DefaultPdbUniversalMember extends PdbMember {
/**
* Default PDB member construction
- * @param applicator {@link PdbApplicator} for which we are working.
+ * @param applicator {@link DefaultPdbApplicator} for which we are working.
* @param name member field name. For bitfields this also conveys the bit-size
* and optionally the bit-offset.
* @param dataType for the field.
* @param offset member's byte offset within the root composite.
*/
- DefaultPdbUniversalMember(PdbApplicator applicator, String name, DataType dataType,
+ DefaultPdbUniversalMember(DefaultPdbApplicator applicator, String name, DataType dataType,
int offset) {
super(name, dataType.getName(), offset, null);
this.applier = null;
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DefinedSingleAddressRangeSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DefinedSingleAddressRangeSymbolApplier.java
index 8fa9ee6e66..6e1e2fe02c 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DefinedSingleAddressRangeSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/DefinedSingleAddressRangeSymbolApplier.java
@@ -30,10 +30,10 @@ public class DefinedSingleAddressRangeSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public DefinedSingleAddressRangeSymbolApplier(PdbApplicator applicator,
+ public DefinedSingleAddressRangeSymbolApplier(DefaultPdbApplicator applicator,
AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/EndSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/EndSymbolApplier.java
index 6c7b35adf5..8a1b6e19ab 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/EndSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/EndSymbolApplier.java
@@ -29,11 +29,11 @@ public class EndSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
* @throws CancelledException upon user cancellation
*/
- public EndSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public EndSymbolApplier(DefaultPdbApplicator applicator, AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
if (!(abstractSymbol instanceof EndMsSymbol)) {
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/EnumTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/EnumTypeApplier.java
index 03bc7827e3..83c9a0e650 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/EnumTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/EnumTypeApplier.java
@@ -40,10 +40,10 @@ public class EnumTypeApplier extends AbstractComplexTypeApplier {
/**
* Constructor for enum type applier, for transforming a enum into a
* Ghidra DataType.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractEnumMsType} to process.
*/
- public EnumTypeApplier(PdbApplicator applicator, AbstractEnumMsType msType) {
+ public EnumTypeApplier(DefaultPdbApplicator applicator, AbstractEnumMsType msType) {
super(applicator, msType);
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/EnumerateTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/EnumerateTypeApplier.java
index d104c45c0a..375c1ecac6 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/EnumerateTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/EnumerateTypeApplier.java
@@ -33,10 +33,10 @@ public class EnumerateTypeApplier extends MsTypeApplier {
/**
* Constructor for enumerate type applier, for transforming a enumerate into a
* Ghidra DataType.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractEnumerateMsType} to process.
*/
- public EnumerateTypeApplier(PdbApplicator applicator, AbstractEnumerateMsType msType) {
+ public EnumerateTypeApplier(DefaultPdbApplicator applicator, AbstractEnumerateMsType msType) {
super(applicator, msType);
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/FieldListTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/FieldListTypeApplier.java
index f87d9fcc16..780fd18993 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/FieldListTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/FieldListTypeApplier.java
@@ -36,7 +36,7 @@ public class FieldListTypeApplier extends MsTypeApplier {
private boolean isEmpty;
// return can be null
- static FieldListTypeApplier getFieldListApplierSpecial(PdbApplicator applicator,
+ static FieldListTypeApplier getFieldListApplierSpecial(DefaultPdbApplicator applicator,
RecordNumber recordNumber) throws PdbException {
MsTypeApplier applier =
applicator.getApplierOrNoTypeSpec(recordNumber, FieldListTypeApplier.class);
@@ -59,24 +59,24 @@ public class FieldListTypeApplier extends MsTypeApplier {
/**
* Constructor.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractFieldListMsType} or {@link PrimitiveMsType} of {@code NO_TYPE}
* @throws IllegalArgumentException Upon invalid arguments.
*/
- public FieldListTypeApplier(PdbApplicator applicator, AbstractMsType msType)
+ public FieldListTypeApplier(DefaultPdbApplicator applicator, AbstractMsType msType)
throws IllegalArgumentException {
this(applicator, msType, false);
}
/**
* Constructor with override for NO_TYPE Primitive.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractFieldListMsType} or {@link PrimitiveMsType} of {@code NO_TYPE}
* @param noType {@code true} to specify that {@code msType} is NO_TYPE.
* @throws IllegalArgumentException Upon invalid arguments.
*/
- public FieldListTypeApplier(PdbApplicator applicator, AbstractMsType msType, boolean noType)
- throws IllegalArgumentException {
+ public FieldListTypeApplier(DefaultPdbApplicator applicator, AbstractMsType msType,
+ boolean noType) throws IllegalArgumentException {
super(applicator, msType);
if (noType && msType instanceof PrimitiveMsType && ((PrimitiveMsType) msType).isNoType()) {
this.isEmpty = true;
@@ -146,9 +146,8 @@ public class FieldListTypeApplier extends MsTypeApplier {
private void applyBaseClasses(List<MsTypeField> baseClasses)
throws CancelledException, PdbException {
for (MsTypeField typeIterated : baseClasses) {
- // Use dummy index of zero.
- MsTypeApplier applier =
- applicator.getTypeApplier((AbstractMsType) typeIterated);
+ // Use dummy index of zero.
+ MsTypeApplier applier = applicator.getTypeApplier((AbstractMsType) typeIterated);
applier.apply(); // Need to apply here, as these are embedded records
baseClassList.add(applier);
}
@@ -157,8 +156,7 @@ public class FieldListTypeApplier extends MsTypeApplier {
private void applyMembers(List<MsTypeField> members) throws CancelledException, PdbException {
for (MsTypeField typeIterated : members) {
// Use dummy index of zero.
- MsTypeApplier applier =
- applicator.getTypeApplier((AbstractMsType) typeIterated);
+ MsTypeApplier applier = applicator.getTypeApplier((AbstractMsType) typeIterated);
applier.apply(); // Need to apply here, as these are embedded records
memberList.add(applier);
}
@@ -167,8 +165,7 @@ public class FieldListTypeApplier extends MsTypeApplier {
private void applyMethods(List<MsTypeField> methods) throws CancelledException, PdbException {
for (MsTypeField typeIterated : methods) {
// Use dummy index of zero.
- MsTypeApplier applier =
- applicator.getTypeApplier((AbstractMsType) typeIterated);
+ MsTypeApplier applier = applicator.getTypeApplier((AbstractMsType) typeIterated);
// TODO: note that these are likely NoTypeAppliers at the moment, as we had not
// yet implemented appliers for AbstractOneMethodMsType and
// AbstractOverloadedMethodMsType
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/FrameAndProcedureInformationSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/FrameAndProcedureInformationSymbolApplier.java
index e18666119a..d8f5f0cecf 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/FrameAndProcedureInformationSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/FrameAndProcedureInformationSymbolApplier.java
@@ -31,10 +31,10 @@ public class FrameAndProcedureInformationSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public FrameAndProcedureInformationSymbolApplier(PdbApplicator applicator,
+ public FrameAndProcedureInformationSymbolApplier(DefaultPdbApplicator applicator,
AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/FunctionSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/FunctionSymbolApplier.java
index 1ef26f727a..ca34fd87ad 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/FunctionSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/FunctionSymbolApplier.java
@@ -63,11 +63,11 @@ public class FunctionSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
* @throws CancelledException upon user cancellation
*/
- public FunctionSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter)
+ public FunctionSymbolApplier(DefaultPdbApplicator applicator, AbstractMsSymbolIterator iter)
throws CancelledException {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
@@ -449,7 +449,7 @@ public class FunctionSymbolApplier extends MsSymbolApplier {
return new CallDepthChangeInfo(function, scopeSet, frameReg, monitor);
}
- Integer getRegChange(PdbApplicator applicator, Register register) {
+ Integer getRegChange(DefaultPdbApplicator applicator, Register register) {
if (callDepthChangeInfo == null || register == null) {
return null;
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/LabelSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/LabelSymbolApplier.java
index d90dd6dae3..639ea7133a 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/LabelSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/LabelSymbolApplier.java
@@ -36,11 +36,11 @@ public class LabelSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
* @throws CancelledException upon user cancellation
*/
- public LabelSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public LabelSymbolApplier(DefaultPdbApplicator applicator, AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
if (!(abstractSymbol instanceof AbstractLabelMsSymbol)) {
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/LocalOptimizedSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/LocalOptimizedSymbolApplier.java
index 5b73796100..83841639a3 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/LocalOptimizedSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/LocalOptimizedSymbolApplier.java
@@ -30,10 +30,11 @@ public class LocalOptimizedSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public LocalOptimizedSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public LocalOptimizedSymbolApplier(DefaultPdbApplicator applicator,
+ AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
if (!(abstractSymbol instanceof AbstractLocalSymbolInOptimizedCodeMsSymbol)) {
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ManagedProcedureSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ManagedProcedureSymbolApplier.java
index d6e9e796bc..b9eb1e10f2 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ManagedProcedureSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ManagedProcedureSymbolApplier.java
@@ -76,12 +76,12 @@ public class ManagedProcedureSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
* @throws CancelledException upon user cancellation
*/
- public ManagedProcedureSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter)
- throws CancelledException {
+ public ManagedProcedureSymbolApplier(DefaultPdbApplicator applicator,
+ AbstractMsSymbolIterator iter) throws CancelledException {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
symbolBlockNestingLevel = 0;
@@ -493,7 +493,7 @@ public class ManagedProcedureSymbolApplier extends MsSymbolApplier {
return new CallDepthChangeInfo(function, scopeSet, frameReg, monitor);
}
- Integer getRegChange(PdbApplicator applicator, Register register) {
+ Integer getRegChange(DefaultPdbApplicator applicator, Register register) {
if (callDepthChangeInfo == null || register == null) {
return null;
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MemberFunctionTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MemberFunctionTypeApplier.java
index d659b94cf9..4ee4bdc0a5 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MemberFunctionTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MemberFunctionTypeApplier.java
@@ -35,12 +35,12 @@ public class MemberFunctionTypeApplier extends AbstractFunctionTypeApplier {
/**
* Constructor for the applicator that applies {@link AbstractMemberFunctionMsType},
* transforming it into a Ghidra {@link DataType}.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractMemberFunctionMsType} to processes.
* @throws IllegalArgumentException Upon type mismatch.
*/
- public MemberFunctionTypeApplier(PdbApplicator applicator, AbstractMemberFunctionMsType msType)
- throws IllegalArgumentException {
+ public MemberFunctionTypeApplier(DefaultPdbApplicator applicator,
+ AbstractMemberFunctionMsType msType) throws IllegalArgumentException {
super(applicator, msType);
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MemberTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MemberTypeApplier.java
index cae3cf4a65..c87262cd12 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MemberTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MemberTypeApplier.java
@@ -30,10 +30,10 @@ public class MemberTypeApplier extends MsTypeApplier {
/**
* Constructor for member type applier.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractMemberMsType} to process.
*/
- public MemberTypeApplier(PdbApplicator applicator, AbstractMemberMsType msType) {
+ public MemberTypeApplier(DefaultPdbApplicator applicator, AbstractMemberMsType msType) {
super(applicator, msType);
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ModifierTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ModifierTypeApplier.java
index b92df8681c..63159b22e3 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ModifierTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ModifierTypeApplier.java
@@ -31,10 +31,10 @@ public class ModifierTypeApplier extends MsTypeApplier {
/**
* Constructor for modifier type applier.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractModifierMsType} to processes.
*/
- public ModifierTypeApplier(PdbApplicator applicator, AbstractModifierMsType msType) {
+ public ModifierTypeApplier(DefaultPdbApplicator applicator, AbstractModifierMsType msType) {
super(applicator, msType);
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MsSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MsSymbolApplier.java
index d48d76bf2d..946beef1df 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MsSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MsSymbolApplier.java
@@ -32,16 +32,16 @@ import ghidra.util.exception.CancelledException;
* make fields available to the user from the {@link AbstractMsSymbol}.
*/
public abstract class MsSymbolApplier {
- protected PdbApplicator applicator;
+ protected DefaultPdbApplicator applicator;
protected AbstractMsSymbolIterator iter;
protected long currentOffset;
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public MsSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public MsSymbolApplier(DefaultPdbApplicator applicator, AbstractMsSymbolIterator iter) {
Objects.requireNonNull(applicator, "applicator cannot be null");
Objects.requireNonNull(iter, "iter cannot be null");
this.applicator = applicator;
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MsTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MsTypeApplier.java
index fd3f44f4a0..111391fe06 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MsTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/MsTypeApplier.java
@@ -32,7 +32,7 @@ import ghidra.util.exception.CancelledException;
*/
public abstract class MsTypeApplier {
- protected PdbApplicator applicator;
+ protected DefaultPdbApplicator applicator;
protected AbstractMsType msType;
protected int index;
protected DataType dataType;
@@ -48,10 +48,10 @@ public abstract class MsTypeApplier {
/**
* Constructor.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractMsType} to apply.
*/
- public MsTypeApplier(PdbApplicator applicator, AbstractMsType msType) {
+ public MsTypeApplier(DefaultPdbApplicator applicator, AbstractMsType msType) {
this.applicator = applicator;
this.msType = msType;
RecordNumber recordNumber = msType.getRecordNumber();
@@ -100,7 +100,7 @@ public abstract class MsTypeApplier {
* Returns {@code true} if the application as been deferred (during the {@link #apply()}
* method. The {@link #deferredApply()} method will need to be applied at the appropriate
* place in the processing sequence (depending on data dependency ordering) as determined
- * and driven by the {@link PdbApplicator}.
+ * and driven by the {@link DefaultPdbApplicator}.
* @return {@code true} if application was deferred
*/
boolean isDeferred() {
@@ -109,7 +109,7 @@ public abstract class MsTypeApplier {
/**
* Performs the work required in a deferred application of the data type. This method
- * is used by the {@link PdbApplicator} in the correct data dependency sequence.
+ * is used by the {@link DefaultPdbApplicator} in the correct data dependency sequence.
* @throws PdbException on error applying the data type
* @throws CancelledException on user cancellation
*/
@@ -187,7 +187,7 @@ public abstract class MsTypeApplier {
* @return the size; zero if unknown.
*/
long getSizeLong() {
- return PdbApplicator.bigIntegerToLong(applicator, getSize());
+ return DefaultPdbApplicator.bigIntegerToLong(applicator, getSize());
}
/**
@@ -195,7 +195,7 @@ public abstract class MsTypeApplier {
* @return the size; zero if unknown.
*/
int getSizeInt() {
- return PdbApplicator.bigIntegerToInt(applicator, getSize());
+ return DefaultPdbApplicator.bigIntegerToInt(applicator, getSize());
}
@Override
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/NestedTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/NestedTypeApplier.java
index bffd709ee3..5bc2b36269 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/NestedTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/NestedTypeApplier.java
@@ -32,12 +32,12 @@ public class NestedTypeApplier extends MsTypeApplier {
/**
* Constructor for nested type applier.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractNestedTypeMsType} or {@link AbstractNestedTypeExtMsType} to
* process.
* @throws IllegalArgumentException Upon invalid arguments.
*/
- public NestedTypeApplier(PdbApplicator applicator, AbstractMsType msType)
+ public NestedTypeApplier(DefaultPdbApplicator applicator, AbstractMsType msType)
throws IllegalArgumentException {
super(applicator, validateType(msType));
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/NoSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/NoSymbolApplier.java
index f12f6a1178..e9a3d498bb 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/NoSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/NoSymbolApplier.java
@@ -29,10 +29,10 @@ public class NoSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public NoSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public NoSymbolApplier(DefaultPdbApplicator applicator, AbstractMsSymbolIterator iter) {
super(applicator, iter);
symbol = iter.next();
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/NoTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/NoTypeApplier.java
index 56f185caa1..74d896af2c 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/NoTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/NoTypeApplier.java
@@ -27,11 +27,11 @@ public class NoTypeApplier extends MsTypeApplier {
/**
* Constructor for nested type applier.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractMsType} to process.
* @throws IllegalArgumentException Upon invalid arguments.
*/
- public NoTypeApplier(PdbApplicator applicator, AbstractMsType msType)
+ public NoTypeApplier(DefaultPdbApplicator applicator, AbstractMsType msType)
throws IllegalArgumentException {
super(applicator, msType);
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbAddressCalculator.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbAddressCalculator.java
new file mode 100644
index 0000000000..09da627263
--- /dev/null
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbAddressCalculator.java
@@ -0,0 +1,349 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.pdb.pdbapplicator;
+
+import java.util.*;
+
+import org.apache.commons.collections4.CollectionUtils;
+
+import ghidra.app.util.bin.format.pdb2.pdbreader.*;
+import ghidra.app.util.bin.format.pdb2.pdbreader.symbol.*;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.listing.Program;
+import ghidra.program.model.mem.MemoryBlock;
+import ghidra.util.exception.CancelledException;
+
+/**
+ * Calculates Addresses for PDB items.
+ */
+abstract class PdbAddressCalculator {
+ private Address imageBase;
+ protected List<SegmentInfo> segmentInfo = new ArrayList<>();
+ private int maxSegment;
+
+ static PdbAddressCalculator chooseAddressCalculator(PdbApplicator applicator, Address imageBase)
+ throws CancelledException {
+
+ AbstractPdb pdb = applicator.getPdb();
+ PdbDebugInfo dbi = pdb.getDebugInfo();
+
+ if (dbi instanceof PdbNewDebugInfo) {
+ DebugData debugData = ((PdbNewDebugInfo) dbi).getDebugData();
+ List<ImageSectionHeader> imageSectionHeaders;
+ imageSectionHeaders = debugData.getImageSectionHeadersOrig();
+ if (imageSectionHeaders != null) {
+ SortedMap<Long, Long> omapFromSource = debugData.getOmapFromSource();
+ if (omapFromSource != null) {
+ return new ImageHeaderWithOmapAddressCalculator(imageBase, imageSectionHeaders,
+ omapFromSource);
+ }
+ // Using "Orig" image section headers here (as opposed to below)
+ return new ImageHeaderAddressCalculator(imageBase, imageSectionHeaders);
+ }
+ imageSectionHeaders = debugData.getImageSectionHeaders();
+ if (imageSectionHeaders != null) {
+ //Not "Orig" image section headers
+ return new ImageHeaderAddressCalculator(imageBase, imageSectionHeaders);
+ }
+ }
+
+ // Fall-through to here: PdbOldDebugInfo and the case of PdbNewDebugInfo where both
+ // imageSectionHeaderOrig and imageSectionHeader are null.
+ if (dbi != null) {
+ List<SegmentMapDescription> segmentMapDescription = dbi.getSegmentMapList();
+ if (segmentMapDescription != null) {
+ return new SegmentMapAddressCalculator(imageBase, segmentMapDescription);
+ }
+ }
+
+ List<PeCoffSectionMsSymbol> peCoffSectionSymbols =
+ applicator.getLinkerPeCoffSectionSymbols();
+ if (!CollectionUtils.isEmpty(peCoffSectionSymbols)) {
+ //long originalImageBase = applicator.getOriginalImageBase();
+ long correction = getCorrection(applicator);
+ return new PeCoffSectionAddressCalculator(imageBase, correction, peCoffSectionSymbols);
+ }
+
+ Program program = applicator.getProgram();
+ if (program != null) {
+ MemoryBlock[] memoryBlocks = program.getMemory().getBlocks();
+ if (!CollectionUtils.sizeIsEmpty(memoryBlocks)) {
+ return new MemoryMapAddressCalculator(imageBase, memoryBlocks);
+ }
+ }
+
+ return null;
+ }
+
+ // We wouldn't have this method if we hadn't found an example where what is supposed to be
+ // an RVA in PeCoffSection is instead a VA. Issue found in one Delphi example. All other
+ // non-Delphi examples seem to have RVA.
+ static long getCorrection(PdbApplicator applicator) throws CancelledException {
+
+ AbstractMsSymbol symbol = applicator.getLinkerModuleCompileSymbol();
+ String name = "";
+ if (symbol instanceof Compile3MsSymbol) {
+ Compile3MsSymbol compile3MsSymbol = (Compile3MsSymbol) symbol;
+ name = compile3MsSymbol.getCompilerVersionString();
+ }
+ else if (symbol instanceof AbstractCompile2MsSymbol) {
+ AbstractCompile2MsSymbol compile2MsSymbol = (AbstractCompile2MsSymbol) symbol;
+ name = compile2MsSymbol.getCompilerVersionString();
+ }
+
+ // Note, that we can also check version numbers if different versions of map2pdb (in the
+ // compile symbol).
+ if ("map2pdb".equals(name)) {
+ return applicator.getOriginalImageBase();
+ }
+ return 0L;
+
+ // We considered going the route of checking the program for Delphi tool chain, but instead
+ // went the route above in checking where the COFF symbols came from and that the fact
+ // that we've seen them contain Virtual Address instead of Relative Virtual Address could
+ // instead be due to map2pdb instead of the Delphi compiler. We just don't know at this
+ // time. This deserved more investigation with more data.
+// CompilerSpec spec = applicator.getProgram().getCompilerSpec();
+// String compiler = applicator.getProgram().getCompiler();
+// if ("borland::pascal".equals(compiler)) {
+// }
+// CompilerSpecDescription desc = spec.getCompilerSpecDescription();
+// String specName = desc.getCompilerSpecName();
+// if ("Delphi".equals(specName)) {
+// }
+// CompilerSpecID id = desc.getCompilerSpecID();
+ }
+
+ //==============================================================================================
+ PdbAddressCalculator(Address imageBase, List<SegmentInfo> segmentInfo) {
+ this.segmentInfo = segmentInfo;
+ this.imageBase = imageBase;
+ maxSegment = segmentInfo.size() + 1;
+ }
+
+ Address getAddress(int segment, long offset) {
+ if (segment > maxSegment) {
+ return PdbAddressManager.BAD_ADDRESS;
+ }
+ else if (segment == 0 || segment == maxSegment) {
+ // External address.
+ return PdbAddressManager.EXTERNAL_ADDRESS;
+ }
+ Long rva = getRva(segment, offset);
+ if (rva == null) {
+ return PdbAddressManager.BAD_ADDRESS;
+ }
+ if (rva == 0) {
+ return PdbAddressManager.ZERO_ADDRESS;
+ }
+ return imageBase.add(rva);
+ }
+
+ protected Long getRva(int segment, long offset) {
+ return segmentInfo.get(segment - 1).getStart() + offset;
+ }
+
+ /**
+ * Clean up possibly incomplete segment information, by synthesizing missing offset data.
+ * @param segments segments to correct
+ * @param firstSectionOffset "known" first section offset
+ * @param imageAlign section alignment
+ * @return new synthesized segment info with synthesized offsets
+ */
+ protected static List<SegmentInfo> synthesizeSegmentInfo(List<SegmentInfo> segments,
+ long firstSectionOffset, long imageAlign) {
+
+ long mask = -imageAlign;
+ long addend = imageAlign - 1;
+
+ long determinedSectionOffset = firstSectionOffset;
+ long origSectionOffset;
+ long sectionLength = 0; // setting "previous" section length to zero for first pass.
+
+ List<SegmentInfo> synthesizedSegmentInfo = new ArrayList<>();
+ for (SegmentInfo info : segments) {
+ origSectionOffset = info.getStart();
+ if (origSectionOffset != 0x00L) {
+ determinedSectionOffset = origSectionOffset;
+ }
+ else {
+ // Performing "least integer" (ceiling) function with imageAlign:
+ // resultAlign = (long)(imageAlign * leastInteger((double) val / (double) imageAlign))
+ // where imageAlign must be a non-zero power of two for this calculation.
+ // Uses previous section length.
+ determinedSectionOffset += (sectionLength + addend) & mask;
+ }
+
+ // the current section length is used for next section offset calculation.
+ sectionLength = info.getLength();
+ SegmentInfo synthesized = new SegmentInfo(determinedSectionOffset, sectionLength);
+ synthesizedSegmentInfo.add(synthesized);
+ }
+
+ return synthesizedSegmentInfo;
+ }
+
+ //----------------------------------------------------------------------------------------------
+ static class ImageHeaderAddressCalculator extends PdbAddressCalculator {
+ ImageHeaderAddressCalculator(Address imageBase,
+ List<ImageSectionHeader> imageSectionHeaders) {
+ super(imageBase, init(imageBase, imageSectionHeaders));
+ }
+
+ static List<SegmentInfo> init(Address imageBase,
+ List<ImageSectionHeader> imageSectionHeaders) {
+ List<SegmentInfo> segments = new ArrayList<>();
+ for (ImageSectionHeader imageSectionHeader : imageSectionHeaders) {
+ SegmentInfo segment = new SegmentInfo(imageSectionHeader.getVirtualAddress(),
+ imageSectionHeader.getRawDataSize());
+ segments.add(segment);
+ }
+ return segments;
+ }
+ }
+
+ static class ImageHeaderWithOmapAddressCalculator extends PdbAddressCalculator {
+ private SortedMap<Long, Long> omapFromSource;
+
+ ImageHeaderWithOmapAddressCalculator(Address imageBase,
+ List<ImageSectionHeader> imageSectionHeaders,
+ SortedMap<Long, Long> omapFromSource) {
+ super(imageBase, ImageHeaderAddressCalculator.init(imageBase, imageSectionHeaders));
+ this.omapFromSource = omapFromSource;
+ }
+
+ @Override
+ protected Long getRva(int segment, long offset) {
+ return applyOMap(super.getRva(segment, offset));
+ }
+
+ private Long applyOMap(Long relativeVirtualAddress) {
+ // NOTE: Original map entries are 32-bit values zero-extended to a java long (64-bits)
+ SortedMap<Long, Long> headMap = omapFromSource.headMap(relativeVirtualAddress + 1);
+ if (headMap.isEmpty()) {
+ return null;
+ }
+ long from = headMap.lastKey();
+ long to = headMap.get(from);
+ if (to == 0) {
+ return 0L;
+ }
+ return to + (relativeVirtualAddress - from);
+ }
+
+ }
+
+ static class SegmentMapAddressCalculator extends PdbAddressCalculator {
+ SegmentMapAddressCalculator(Address imageBase,
+ List<SegmentMapDescription> segmentMapDescriptions) {
+ super(imageBase, init(imageBase, segmentMapDescriptions));
+ }
+
+ private static List<SegmentInfo> init(Address imageBase,
+ List<SegmentMapDescription> segmentMapDescriptions) {
+ List<SegmentInfo> segments = new ArrayList<>();
+
+ for (SegmentMapDescription smd : segmentMapDescriptions) {
+ SegmentInfo segment = new SegmentInfo(smd.getOffset(), smd.getLength());
+ segments.add(segment);
+ }
+ // Currently, this is the only calculator using synthesis to correct offset.
+ // If all used it, we would put this in the parent class constructor.
+ //
+ // We have the defaults for offset of initial segment and for segment align size to both
+ // be 0x1000. If we determine that these need to be different for the various data
+ // sources, then the AddressCalculator constructor can take these values as parameters
+ // and pass them to the following synthesize method.
+ return synthesizeSegmentInfo(segments, 0x1000L, 0x1000L);
+ }
+
+ }
+
+ static class PeCoffSectionAddressCalculator extends PdbAddressCalculator {
+ PeCoffSectionAddressCalculator(Address imageBase, long correction,
+ List<PeCoffSectionMsSymbol> peCoffSectionSymbols) {
+ super(imageBase, init(imageBase, correction, peCoffSectionSymbols));
+ }
+
+ private static List<SegmentInfo> init(Address imageBase, long correction,
+ List<PeCoffSectionMsSymbol> peCoffSectionSymbols) {
+ List<SegmentInfo> segments = new ArrayList<>();
+
+ // One last check to see if we should apply the correction. If the original image
+ // base is greater than any of the addresses here, then the addresses cannot be
+ // Virtual Addresses, but instead Relative Virtual Addresses. So set correction back
+ // to zero (if not already zero).
+ for (PeCoffSectionMsSymbol symbol : peCoffSectionSymbols) {
+ long rva = symbol.getRva();
+ if (rva != 0 && rva < correction) {
+ correction = 0L;
+ break;
+ }
+ }
+
+ for (PeCoffSectionMsSymbol symbol : peCoffSectionSymbols) {
+ int offset = symbol.getRva();
+ if (offset != 0) {
+ offset -= correction;
+ }
+ SegmentInfo segment = new SegmentInfo(offset, symbol.getLength());
+ segments.add(segment);
+ }
+ return segments;
+ }
+ }
+
+ static class MemoryMapAddressCalculator extends PdbAddressCalculator {
+ MemoryMapAddressCalculator(Address imageBase, MemoryBlock[] memoryBlocks) {
+ super(imageBase, init(imageBase, memoryBlocks));
+ }
+
+ private static List<SegmentInfo> init(Address imageBase, MemoryBlock[] blocks) {
+ List<SegmentInfo> segments = new ArrayList<>();
+ for (MemoryBlock block : blocks) {
+ long offset = block.getStart().subtract(imageBase);
+ SegmentInfo segment = new SegmentInfo(offset, block.getSize());
+ segments.add(segment);
+ }
+ return segments;
+ }
+ }
+
+ //==============================================================================================
+ private static class SegmentInfo {
+ private long start;
+ private long length;
+
+ SegmentInfo(long startIn, long lengthIn) {
+ start = startIn;
+ length = lengthIn;
+ }
+
+ public long getStart() {
+ return start;
+ }
+
+ public long getLength() {
+ return length;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("start: %08x length: %08x", start, length);
+ }
+ }
+
+}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbAddressManager.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbAddressManager.java
index c6222a0175..7fe758a909 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbAddressManager.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbAddressManager.java
@@ -43,7 +43,6 @@ public class PdbAddressManager {
static final Address BAD_ADDRESS = Address.NO_ADDRESS;
//==============================================================================================
- private Map<Integer, Long> realAddressesBySection;
private List<SegmentMapDescription> segmentMapList;
private List<ImageSectionHeader> imageSectionHeaders;
private SortedMap<Long, Long> omapFromSource;
@@ -66,30 +65,37 @@ public class PdbAddressManager {
private Map<Address, Address> remapAddressByAddress;
- private PdbApplicator applicator;
+ private DefaultPdbApplicator applicator;
private Address imageBase;
+ private PdbAddressCalculator addressCalculator;
+
//==============================================================================================
// API
//==============================================================================================
/**
* Manager
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param imageBase Address from which all other addresses are based.
* @throws PdbException If Program is null;
+ * @throws CancelledException upon user cancellation
*/
- PdbAddressManager(PdbApplicator applicator, Address imageBase) throws PdbException {
+ PdbAddressManager(DefaultPdbApplicator applicator, Address imageBase)
+ throws PdbException, CancelledException {
Objects.requireNonNull(applicator, "applicator may not be null");
Objects.requireNonNull(imageBase, "imageBase may not be null");
this.applicator = applicator;
this.imageBase = imageBase;
- realAddressesBySection = new HashMap<>();
memoryGroupRefinement = new ArrayList<>();
memorySectionRefinement = new ArrayList<>();
- // TODO allSegmentInfo might go away if we use ImageSectionHeader. Under investigation.
-// allSegmentsInfo = new ArrayList<>();
+
addressByPreExistingSymbolName = new HashMap<>();
primarySymbolByAddress = new HashMap<>();
+ addressCalculator = PdbAddressCalculator.chooseAddressCalculator(applicator, imageBase);
+ if (addressCalculator == null) {
+ throw new PdbException("PDB: Could not create an Address Calculator");
+ }
+
determineMemoryBlocks();
// determineMemoryBlocks_orig();
mapPreExistingSymbols();
@@ -146,6 +152,19 @@ public class PdbAddressManager {
* {@code Address.EXTERNAL_ADDRESS} if the address is external to the program.
*/
Address getRawAddress(int segment, long offset) {
+// return getRawAddress_orig(segment, offset);
+ return addressCalculator.getAddress(segment, offset);
+ }
+
+ /**
+ * Returns the Address for the given section and offset. Will attempt to map the address
+ * to a new address if the {@link PdbApplicatorOptions}
+ * @param segment The segment
+ * @param offset The offset
+ * @return The Address, which can be {@code Address.NO_ADDRESS} if invalid or
+ * {@code Address.EXTERNAL_ADDRESS} if the address is external to the program.
+ */
+ private Address getRawAddress_orig(int segment, long offset) {
if (segment < 0) {
return BAD_ADDRESS;
}
@@ -239,15 +258,6 @@ public class PdbAddressManager {
return existingAddress;
}
- /**
- * Method for callee to set the real address for the section.
- * @param sectionNum the section number
- * @param realAddress The Address
- */
- void putRealAddressesBySection(int sectionNum, long realAddress) {
- realAddressesBySection.put(sectionNum, realAddress);
- }
-
/**
* Method for callee to add a Memory Group symbol to the Memory Group list.
* @param symbol the symbol.
@@ -329,9 +339,6 @@ public class PdbAddressManager {
private void determineMemoryBlocks() {
AbstractPdb pdb = applicator.getPdb();
PdbDebugInfo debugInfo = pdb.getDebugInfo();
- if (debugInfo == null) {
- return;
- }
segmentMapList = debugInfo.getSegmentMapList();
if (debugInfo instanceof PdbNewDebugInfo) {
DebugData debugData = ((PdbNewDebugInfo) debugInfo).getDebugData();
@@ -572,54 +579,4 @@ public class PdbAddressManager {
}
}
- //==============================================================================================
- // TODO: This is not complete... It was a research thought, which might get looked at in the
- // future.
- @SuppressWarnings("unused") // for method not being called.
- private boolean garnerSectionSegmentInformation() throws PdbException {
- AbstractPdb pdb = applicator.getPdb();
-
- PdbDebugInfo debugInfo = pdb.getDebugInfo();
- if (debugInfo == null) {
- return false;
- }
-
-// ImageSectionHeader imageSectionHeader =
-// pdb.getDebugInfo().getDebugData().getImageSectionHeader();
-
- int num = 1;
- for (AbstractModuleInformation module : debugInfo.getModuleInformationList()) {
- if ("* Linker *".equals(module.getModuleName())) {
- SymbolGroup symbolGroup = applicator.getSymbolGroupForModule(num);
- if (symbolGroup == null) {
- continue; // should not happen
- }
- List<AbstractMsSymbol> linkerSymbolList = symbolGroup.getSymbols();
- for (AbstractMsSymbol symbol : linkerSymbolList) {
- if (symbol instanceof PeCoffSectionMsSymbol) {
- PeCoffSectionMsSymbol section = (PeCoffSectionMsSymbol) symbol;
- int sectionNum = section.getSectionNumber();
- long realAddress = section.getRva();
- section.getLength();
- section.getCharacteristics();
- section.getAlign();
- section.getName();
- realAddressesBySection.put(sectionNum, realAddress);
- }
- if (symbol instanceof PeCoffGroupMsSymbol) {
- PeCoffGroupMsSymbol group = (PeCoffGroupMsSymbol) symbol;
- group.getName();
- group.getSegment();
- group.getLength();
- group.getOffset();
- group.getCharacteristics();
- }
- }
- return true;
- }
- num++;
- }
- return false;
- }
-
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbApplicator.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbApplicator.java
index 9c77020b11..39b3953c4b 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbApplicator.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbApplicator.java
@@ -15,1696 +15,55 @@
*/
package ghidra.app.util.pdb.pdbapplicator;
-import java.math.BigInteger;
-import java.util.*;
+import java.util.List;
-import org.apache.commons.lang3.StringUtils;
-
-import ghidra.app.cmd.comments.SetCommentCmd;
-import ghidra.app.cmd.label.SetLabelPrimaryCmd;
-import ghidra.app.util.NamespaceUtils;
-import ghidra.app.util.SymbolPath;
-import ghidra.app.util.bin.format.pdb.PdbParserConstants;
-import ghidra.app.util.bin.format.pdb2.pdbreader.*;
+import ghidra.app.util.bin.format.pdb2.pdbreader.AbstractPdb;
import ghidra.app.util.bin.format.pdb2.pdbreader.symbol.*;
-import ghidra.app.util.bin.format.pdb2.pdbreader.type.AbstractMsType;
-import ghidra.app.util.bin.format.pe.cli.tables.CliAbstractTableRow;
-import ghidra.app.util.importer.MessageLog;
-import ghidra.app.util.pdb.PdbCategories;
-import ghidra.app.util.pdb.pdbapplicator.SymbolGroup.AbstractMsSymbolIterator;
-import ghidra.framework.options.Options;
-import ghidra.graph.*;
-import ghidra.graph.algo.GraphNavigator;
-import ghidra.graph.jung.JungDirectedGraph;
-import ghidra.program.model.address.Address;
-import ghidra.program.model.data.*;
-import ghidra.program.model.lang.Register;
-import ghidra.program.model.listing.*;
-import ghidra.program.model.symbol.*;
-import ghidra.util.Msg;
-import ghidra.util.exception.*;
-import ghidra.util.task.CancelOnlyWrappingTaskMonitor;
-import ghidra.util.task.TaskMonitor;
+import ghidra.program.model.listing.Program;
+import ghidra.util.exception.CancelledException;
/**
+ * Interface for PDB Applicator.
+ * <p>
* The main engine for applying an AbstractPdb to Ghidra, whether a Program or DataTypeManager.
* The class is to be constructed first.
* <p>
- * The
- * {@link #applyTo(Program, DataTypeManager, Address, PdbApplicatorOptions, TaskMonitor, MessageLog)}
- * method is then called with the appropriate {@link PdbApplicatorOptions} along with a
- * {@link Program} and/or {@link DataTypeManager}. Either, but not both can be null.
- * If the Program is not null but the DatatypeManager is null, then the DataTypeManager is gotten
- * from the Program. If the Program is null, then data types can be applied to a DataTypeManager.
- * The validation logic for the parameters is found in
- * {@link #validateAndSetParameters(Program, DataTypeManager, Address, PdbApplicatorOptions, TaskMonitor, MessageLog)}.
- * <p>
- * Once the parameters are validated, appropriate classes and storage containers are constructed.
- * Then processing commences, first with data types, followed by symbol-related processing.
- * <p>
- * {@link PdbApplicatorMetrics} are captured during the processing and status and logging is
- * reported to various mechanisms including {@link Msg}, {@link MessageLog}, and {@link PdbLog}.
+ * <b>NOTE: The plan is that this interface will be grown to a be a full/true interface, but it
+ * is currently only being created to allow for creating a stub for testing.</b>
*/
-public class PdbApplicator {
-
- private static final String THUNK_NAME_PREFIX = "[thunk]:";
-
- //==============================================================================================
- /**
- * Returns integer value of BigInteger or Integer.MAX_VALUE if does not fit.
- * @param myApplicator PdbApplicator for which we are working.
- * @param big BigInteger value to convert.
- * @return the integer value.
- */
- static long bigIntegerToLong(PdbApplicator myApplicator, BigInteger big) {
- try {
- return big.longValueExact();
- }
- catch (ArithmeticException e) {
- String msg = "BigInteger value greater than max Long: " + big;
- PdbLog.message(msg);
- myApplicator.appendLogMsg(msg);
- return Long.MAX_VALUE;
- }
- }
-
- /**
- * Returns integer value of BigInteger or Integer.MAX_VALUE if does not fit.
- * @param myApplicator PdbApplicator for which we are working.
- * @param big BigInteger value to convert.
- * @return the integer value.
- */
- static int bigIntegerToInt(PdbApplicator myApplicator, BigInteger big) {
- try {
- return big.intValueExact();
- }
- catch (ArithmeticException e) {
- String msg = "BigInteger value greater than max Integer: " + big;
- PdbLog.message(msg);
- myApplicator.appendLogMsg(msg);
- return Integer.MAX_VALUE;
- }
- }
-
- //==============================================================================================
- private String pdbFilename;
- private AbstractPdb pdb;
-
- private PdbApplicatorMetrics pdbApplicatorMetrics;
-
- //==============================================================================================
- private Program program;
-
- private PdbApplicatorOptions applicatorOptions;
- private MessageLog log;
- private TaskMonitor monitor;
- private CancelOnlyWrappingTaskMonitor cancelOnlyWrappingMonitor;
-
- //==============================================================================================
- private Address imageBase;
- private DataTypeManager dataTypeManager;
- private PdbAddressManager pdbAddressManager;
- private List<SymbolGroup> symbolGroups;
-
- private PdbCliInfoManager pdbCliManagedInfoManager;
-
- //==============================================================================================
- // If we have symbols and memory with VBTs in them, then a better VbtManager is created.
- VbtManager vbtManager;
- PdbRegisterNameToProgramRegisterMapper registerNameToRegisterMapper;
-
- //==============================================================================================
- private int resolveCount;
- private PdbCategories categoryUtils;
- private PdbPrimitiveTypeApplicator pdbPrimitiveTypeApplicator;
- private TypeApplierFactory typeApplierParser;
- private ComplexTypeApplierMapper complexApplierMapper;
- private JungDirectedGraph<MsTypeApplier, GEdge<MsTypeApplier>> applierDependencyGraph;
- /**
- * This namespace map documents as follows:
- * <PRE>
- * false = simple namespace
- * true = class namespace
- * </PRE>
- */
- private Map<SymbolPath, Boolean> isClassByNamespace;
-
- //==============================================================================================
- private SymbolApplierFactory symbolApplierParser;
-
- // Investigating... might change from String to AbstractSymbolApplier.
- private Map<Address, Set<String>> labelsByAddress;
- // Investigations into source/line info
- private Map<String, Set<RecordNumber>> recordNumbersByFileName;
- private Map<Integer, Set<RecordNumber>> recordNumbersByModuleNumber;
-
- //==============================================================================================
- // TODO: eventually put access methods on AbstractPdb to get filename from it (deep down).
- public PdbApplicator(String pdbFilename, AbstractPdb pdb) {
- Objects.requireNonNull(pdbFilename, "pdbFilename cannot be null");
- Objects.requireNonNull(pdb, "pdb cannot be null");
- this.pdbFilename = pdbFilename;
- this.pdb = pdb;
- }
-
- //==============================================================================================
- //==============================================================================================
- /**
- * Applies the PDB to the {@link Program} or {@link DataTypeManager}. Either, but not both,
- * can be null.
- * @param programParam The {@link Program} to which to apply the PDB. Can be null in certain
- * circumstances.
- * @param dataTypeManagerParam The {@link DataTypeManager} to which to apply data types. Can be
- * null in certain circumstances.
- * @param imageBaseParam Address bases from which symbol addresses are based. If null, uses
- * the image base of the program (both cannot be null).
- * @param applicatorOptionsParam {@link PdbApplicatorOptions} used for applying the PDB.
- * @param monitorParam TaskMonitor uses for watching progress and cancellation notices.
- * @param logParam The MessageLog to which to output messages.
- * @throws PdbException if there was a problem processing the data.
- * @throws CancelledException Upon user cancellation
- */
- public void applyTo(Program programParam, DataTypeManager dataTypeManagerParam,
- Address imageBaseParam, PdbApplicatorOptions applicatorOptionsParam,
- TaskMonitor monitorParam, MessageLog logParam) throws PdbException, CancelledException {
-
- // FIXME: should not support use of DataTypeManager-only since it will not have the correct data
- // organization if it corresponds to a data type archive. Need to evaulate archive use case
- // and determine if a program must always be used.
-
- initializeApplyTo(programParam, dataTypeManagerParam, imageBaseParam,
- applicatorOptionsParam, monitorParam, logParam);
-
- switch (applicatorOptions.getProcessingControl()) {
- case DATA_TYPES_ONLY:
- processTypes();
- break;
- case PUBLIC_SYMBOLS_ONLY:
- processPublicSymbols();
- break;
- case ALL:
- processTypes();
- processSymbols();
- break;
- default:
- throw new PdbException("PDB: Invalid Application Control: " +
- applicatorOptions.getProcessingControl());
- }
-
- if (program != null) {
- Options options = program.getOptions(Program.PROGRAM_INFO);
- options.setBoolean(PdbParserConstants.PDB_LOADED, true);
- }
-
- pdbAddressManager.logReport();
-
- pdbApplicatorMetrics.logReport();
-
- Msg.info(this, "PDB Terminated Normally");
- }
-
- //==============================================================================================
- private void processTypes() throws CancelledException, PdbException {
- setMonitorMessage("PDB: Applying to DTM " + dataTypeManager.getName() + "...");
-
- PdbResearch.initBreakPointRecordNumbers(); // for developmental debug
-
- resolveCount = 0;
-
-// PdbResearch.childWalk(this, monitor);
-
-// PdbResearch.studyDataTypeConflicts(this, monitor);
-// PdbResearch.studyCompositeFwdRefDef(pdb, monitor);
-// PdbResearch.study1(pdb, monitor);
-
- complexApplierMapper.mapAppliers(monitor);
-
- processSequentially();
-
-// dumpSourceFileRecordNumbers();
-
-// PdbResearch.developerDebugOrder(this, monitor);
-
- processDeferred();
-
- resolveSequentially();
-
- Msg.info(this, "resolveCount: " + resolveCount);
-
- // Currently, defining classes needs to have a program. When this is no longer true,
- // then this call can be performed with the data types only work.
- if (program != null) {
- defineClasses();
- }
-
- // Process typedefs, which are in the symbols.
- processGlobalTypdefSymbols();
- }
-
- //==============================================================================================
- private void processSymbols() throws CancelledException, PdbException {
-// PdbResearch.studyAggregateSymbols(this, monitor);
-
- // TODO: not sure if the following will be relevant here, elsewhere, or nowhere.
-// if (!pdbAddressManager.garnerSectionSegmentInformation()) {
-// return;
-// }
-
- // Doing globals before publics, as publics are those that can have mangled names. By
- // applying the non-mangled symbols first, we can get full type information from the
- // underlying type. Then we can apply the mangled symbols and demangle them without
- // affecting our ability to lay down PDB type information--any type information from
- // the mangled symbols can happen afterward.
- processGlobalSymbolsNoTypedefs();
- processPublicSymbols();
-
- // Seems that we shouldn't do the following, as it could be a buffer of invalid symbols
- // that hadn't been gone through for garbage collection of sorts.
- //processNonPublicOrGlobalSymbols();
-
- // Seems that we shouldn't do the following, as the ones that are needed seem to be
- // referenced from a global symbol using a ReferencedSymbol. If we process the module
- // symbols, as below, then collisions can start to appear at addresses. This has
- // happened to me when I forgot to clear the results from a previous build, in which
- // case I could find symbols referring to a location within the old build and within
- // the latest build at the particular address corresponding to its location within that
- // build. So a module might have symbols that had not been garbage-collected.
- processModuleSymbols();
-
- // These are good to process (one particular module for the linker).
-// processLinkerSymbols();
-
- // Get additional thunks (that old pdb analyzer got).
- processThunkSymbolsFromNonLinkerModules();
-
- //processAllSymbols();
-
-// dumpLabels();
- }
-
- //==============================================================================================
- //==============================================================================================
- private void initializeApplyTo(Program programParam, DataTypeManager dataTypeManagerParam,
- Address imageBaseParam, PdbApplicatorOptions applicatorOptionsParam,
- TaskMonitor monitorParam, MessageLog logParam) throws PdbException, CancelledException {
-
- validateAndSetParameters(programParam, dataTypeManagerParam, imageBaseParam,
- applicatorOptionsParam, monitorParam, logParam);
-
- cancelOnlyWrappingMonitor = new CancelOnlyWrappingTaskMonitor(monitor);
- pdbApplicatorMetrics = new PdbApplicatorMetrics();
-
- pdbAddressManager = new PdbAddressManager(this, imageBase);
-
- pdbCliManagedInfoManager = new PdbCliInfoManager(this);
-
- symbolGroups = createSymbolGroups();
-
- categoryUtils = setPdbCatogoryUtils(pdbFilename);
- pdbPrimitiveTypeApplicator = new PdbPrimitiveTypeApplicator(dataTypeManager);
- typeApplierParser = new TypeApplierFactory(this);
- complexApplierMapper = new ComplexTypeApplierMapper(this);
- applierDependencyGraph = new JungDirectedGraph<>();
- isClassByNamespace = new TreeMap<>();
- if (program != null) {
- // Currently, this must happen after symbolGroups are created.
- PdbVbtManager pdbVbtManager = new PdbVbtManager(this);
- //pdbVbtManager.CreateVirtualBaseTables(); // Depends on symbolGroups
- vbtManager = pdbVbtManager;
- registerNameToRegisterMapper = new PdbRegisterNameToProgramRegisterMapper(program);
- }
- else {
- vbtManager = new VbtManager(getDataTypeManager());
- }
-
- symbolApplierParser = new SymbolApplierFactory(this);
-
- // Investigations
- labelsByAddress = new HashMap<>();
- // Investigations into source/line info
- recordNumbersByFileName = new HashMap<>();
- recordNumbersByModuleNumber = new HashMap<>();
- }
-
- private void validateAndSetParameters(Program programParam,
- DataTypeManager dataTypeManagerParam, Address imageBaseParam,
- PdbApplicatorOptions applicatorOptionsParam, TaskMonitor monitorParam,
- MessageLog logParam) throws PdbException {
- applicatorOptions =
- (applicatorOptionsParam != null) ? applicatorOptionsParam : new PdbApplicatorOptions();
- if (programParam == null) {
- if (dataTypeManagerParam == null) {
- throw new PdbException(
- "PDB: programParam and dataTypeManagerParam may not both be null.");
- }
- if (imageBaseParam == null) {
- throw new PdbException(
- "PDB: programParam and imageBaseParam may not both be null.");
- }
- if (applicatorOptions.getProcessingControl() != PdbApplicatorControl.DATA_TYPES_ONLY) {
- throw new PdbException(
- "PDB: programParam may not be null for the chosen Applicator Control: " +
- applicatorOptions.getProcessingControl());
- }
- }
- monitor = (monitorParam != null) ? monitorParam : TaskMonitor.DUMMY;
- log = (logParam != null) ? logParam : new MessageLog();
- program = programParam;
- dataTypeManager =
- (dataTypeManagerParam != null) ? dataTypeManagerParam : program.getDataTypeManager();
- imageBase = (imageBaseParam != null) ? imageBaseParam : program.getImageBase();
- }
-
- private List<SymbolGroup> createSymbolGroups() throws CancelledException, PdbException {
- List<SymbolGroup> mySymbolGroups = new ArrayList<>();
- PdbDebugInfo debugInfo = pdb.getDebugInfo();
- if (debugInfo == null) {
- return mySymbolGroups;
- }
-
- int num = debugInfo.getNumModules();
- // moduleNumber zero is our global/public group.
- for (int moduleNumber = 0; moduleNumber <= num; moduleNumber++) {
- monitor.checkCanceled();
- Map<Long, AbstractMsSymbol> symbols = debugInfo.getModuleSymbolsByOffset(moduleNumber);
- SymbolGroup symbolGroup = new SymbolGroup(symbols, moduleNumber);
- mySymbolGroups.add(symbolGroup);
- }
- return mySymbolGroups;
- }
-
- //==============================================================================================
- // Basic utility methods.
- //==============================================================================================
- /**
- * Returns the {@link PdbApplicatorOptions} for this PdbApplicator.
- * @return the {@link PdbApplicatorOptions} for this PdbApplicator.
- */
- PdbApplicatorOptions getPdbApplicatorOptions() {
- return applicatorOptions;
- }
-
- /**
- * Check to see if this monitor has been canceled
- * @throws CancelledException if monitor has been cancelled
- */
- void checkCanceled() throws CancelledException {
- monitor.checkCanceled();
- }
-
- /**
- * Sets the message displayed on the task monitor
- * @param message the message to display
- */
- void setMonitorMessage(String message) {
- monitor.setMessage(message);
- }
-
- /**
- * Sets the message displayed on the task monitor
- * @param message the message to display
- */
- void appendLogMsg(String message) {
- log.appendMsg(message);
- }
-
- /**
- * Returns the MessageLog.
- * @return the MessageLog
- */
- MessageLog getMessageLog() {
- return log;
- }
-
- /**
- * Puts message to {@link PdbLog} and to Msg.info()
- * @param originator a Logger instance, "this", or YourClass.class
- * @param message the message to display
- */
- void pdbLogAndInfoMessage(Object originator, String message) {
- PdbLog.message(message);
- Msg.info(originator, message);
- }
-
- /**
- * Puts error message to {@link PdbLog} and to Msg.error() which will
- * also log a stack trace if exception is specified.
- * @param originator a Logger instance, "this", or YourClass.class
- * @param message the error message to display/log
- * @param exc exception whose stack trace should be reported or null
- */
- void pdbLogAndErrorMessage(Object originator, String message, Exception exc) {
- PdbLog.message(message);
- if (exc != null) {
- Msg.error(originator, message);
- }
- else {
- Msg.error(originator, message, exc);
- }
- }
-
- /**
- * Returns the {@link TaskMonitor} to available for this analyzer.
- * @return the monitor.
- */
- TaskMonitor getMonitor() {
- return monitor;
- }
-
- /**
- * Returns the {@link CancelOnlyWrappingTaskMonitor} to available for this analyzer. This is
- * useful for the user to be able to control the monitor progress bar without called commands
- * changing its progress on smaller tasks.
- * @return the monitor.
- */
- TaskMonitor getCancelOnlyWrappingMonitor() {
- return cancelOnlyWrappingMonitor;
- }
-
- /**
- * Returns the {@link PdbApplicatorMetrics} being used for this applicator.
- * @return the {@link PdbApplicatorMetrics}.
- */
- PdbApplicatorMetrics getPdbApplicatorMetrics() {
- return pdbApplicatorMetrics;
- }
+public interface PdbApplicator {
/**
* Returns the {@link AbstractPdb} being analyzed.
* @return {@link AbstractPdb} being analyzed.
*/
- AbstractPdb getPdb() {
- return pdb;
- }
+ public AbstractPdb getPdb();
/**
* Returns the {@link Program} for which this analyzer is working.
* @return {@link Program} for which this analyzer is working.
*/
- Program getProgram() {
- return program;
- }
-
- //==============================================================================================
- // Information for a putative PdbTypeApplicator:
+ Program getProgram();
/**
- * Returns the {@link DataTypeManager} associated with this analyzer.
- * @return DataTypeManager which this analyzer is using.
+ * Returns the original image base value from the PE Header.
+ * @return the original image base for the binary
*/
- DataTypeManager getDataTypeManager() {
- return dataTypeManager;
- }
-
- // for PdbTypeApplicator (new)
- DataOrganization getDataOrganization() {
- return dataTypeManager.getDataOrganization();
- }
+ public long getOriginalImageBase();
- PdbPrimitiveTypeApplicator getPdbPrimitiveTypeApplicator() {
- return pdbPrimitiveTypeApplicator;
- }
-
- //==============================================================================================
- // CategoryPath-related methods.
- //==============================================================================================
/**
- * Get the {@link CategoryPath} associated with the {@link SymbolPath} specified, rooting
- * it either at the PDB Category.
- * @param symbolPath Symbol path to be used to create the CategoryPath. Null represents global
- * namespace.
- * @return {@link CategoryPath} created for the input.
- */
- CategoryPath getCategory(SymbolPath symbolPath) {
- return categoryUtils.getCategory(symbolPath);
- }
-
- /**
- * Returns the {@link CategoryPath} for a typedef with with the give {@link SymbolPath} and
- * module number; 1 <= moduleNumber <= {@link PdbDebugInfo#getNumModules()},
- * except that modeleNumber of 0 represents publics/globals.
- * @param moduleNumber module number
- * @param symbolPath SymbolPath of the symbol
- * @return the CategoryPath
- */
- CategoryPath getTypedefsCategory(int moduleNumber, SymbolPath symbolPath) {
- return categoryUtils.getTypedefsCategory(moduleNumber, symbolPath);
- }
-
- /**
- * Returns the {@link CategoryPath} for Anonymous Functions Category for the PDB.
- * @return the {@link CategoryPath}
- */
- CategoryPath getAnonymousFunctionsCategory() {
- return categoryUtils.getAnonymousFunctionsCategory();
- }
-
- /**
- * Returns the {@link CategoryPath} for Anonymous Types Category for the PDB.
- * @return the {@link CategoryPath}
- */
- CategoryPath getAnonymousTypesCategory() {
- return categoryUtils.getAnonymousTypesCategory();
- }
-
-// /**
-// * Returns the name of what should be the next Anonymous Function (based on the count of
-// * the number of anonymous functions) so that there is a unique name for the function.
-// * @return the name for the next anonymous function.
-// */
-// String getNextAnonymousFunctionName() {
-// return categoryUtils.getNextAnonymousFunctionName();
-// }
-
-// /**
-// * Updates the count of the anonymous functions. This is a separate call from
-// * {@link #getNextAnonymousFunctionName()} because the count should only be updated after
-// * the previous anonymous function has been successfully created/stored.
-// */
-// void incrementNextAnonymousFunctionName() {
-// categoryUtils.incrementNextAnonymousFunctionName();
-// }
-
- private PdbCategories setPdbCatogoryUtils(String pdbFilename)
- throws CancelledException, PdbException {
-
- List<String> categoryNames = new ArrayList<>();
-
- PdbDebugInfo debugInfo = pdb.getDebugInfo();
- if (debugInfo != null) {
-
- int num = debugInfo.getNumModules();
- for (int index = 1; index <= num; index++) {
- monitor.checkCanceled();
- String moduleName = debugInfo.getModuleInformation(index).getModuleName();
- categoryNames.add(moduleName);
- }
- }
-
- int index = pdbFilename.lastIndexOf("\\");
- if (index == -1) {
- index = pdbFilename.lastIndexOf("/");
- }
- return new PdbCategories(pdbFilename.substring(index + 1), categoryNames);
- }
-
- //==============================================================================================
- // Applier-based-DataType-dependency-related methods.
- //==============================================================================================
- void addApplierDependency(MsTypeApplier depender) {
- Objects.requireNonNull(depender);
- applierDependencyGraph.addVertex(depender.getDependencyApplier());
- }
-
- void addApplierDependency(MsTypeApplier depender, MsTypeApplier dependee) {
- Objects.requireNonNull(depender);
- Objects.requireNonNull(dependee);
- // TODO: Possibly do checks on dependee and depender types for actual creation
- // of dependency--making this the one-stop-shop of this logic. Then make calls to
- // this method from all possibly places. (Perhaps, for example, if depender is a
- // pointer, then the logic would say "no.")
- //
- // Examples of where dependency should possibly be created (by not doing it, we are
- // getting .conflict data types) include:
- // structure or enum as a function return type or argument type.
- //
- applierDependencyGraph.addEdge(
- new DefaultGEdge<>(depender.getDependencyApplier(), dependee.getDependencyApplier()));
- }
-
- List<MsTypeApplier> getVerticesInPostOrder() {
- setMonitorMessage("PDB: Determining data type dependency order...");
- return GraphAlgorithms.getVerticesInPostOrder(applierDependencyGraph,
- GraphNavigator.topDownNavigator());
- }
-
- //==============================================================================================
- //==============================================================================================
- //==============================================================================================
- MsTypeApplier getApplierSpec(RecordNumber recordNumber, Class<? extends MsTypeApplier> expected)
- throws PdbException {
- return typeApplierParser.getApplierSpec(recordNumber, expected);
- }
-
- MsTypeApplier getApplierOrNoTypeSpec(RecordNumber recordNumber,
- Class<? extends MsTypeApplier> expected) throws PdbException {
- return typeApplierParser.getApplierOrNoTypeSpec(recordNumber, expected);
- }
-
- MsTypeApplier getTypeApplier(RecordNumber recordNumber) {
- //PdbResearch.checkBreak(recordNumber.getNumber());
- return typeApplierParser.getTypeApplier(recordNumber);
- }
-
- MsTypeApplier getTypeApplier(AbstractMsType type) {
- return typeApplierParser.getTypeApplier(type);
- }
-
- //==============================================================================================
- //==============================================================================================
- //==============================================================================================
- int findModuleNumberBySectionOffsetContribution(int section, long offset) throws PdbException {
- PdbDebugInfo debugInfo = pdb.getDebugInfo();
- if (debugInfo == null) {
- throw new PdbException("PDB: DebugInfo is null");
- }
-
- for (AbstractSectionContribution sectionContribution : debugInfo
- .getSectionContributionList()) {
- int sectionContributionOffset = sectionContribution.getOffset();
- int maxSectionContributionOffset =
- sectionContributionOffset + sectionContribution.getLength();
- if (offset >= sectionContributionOffset && offset < maxSectionContributionOffset) {
- return sectionContribution.getModule();
- }
- }
- throw new PdbException("PDB: Module not found for section/offset");
- }
-
- //==============================================================================================
- private void processDataTypesSequentially() throws CancelledException, PdbException {
- AbstractTypeProgramInterface tpi = pdb.getTypeProgramInterface();
- if (tpi == null) {
- return;
- }
- int num = tpi.getTypeIndexMaxExclusive() - tpi.getTypeIndexMin();
- monitor.initialize(num);
- setMonitorMessage("PDB: Processing " + num + " data type components...");
- for (int indexNumber = tpi.getTypeIndexMin(); indexNumber < tpi
- .getTypeIndexMaxExclusive(); indexNumber++) {
- monitor.checkCanceled();
- //PdbResearch.checkBreak(indexNumber);
- MsTypeApplier applier = getTypeApplier(RecordNumber.typeRecordNumber(indexNumber));
- //PdbResearch.checkBreak(indexNumber, applier);
- applier.apply();
- monitor.incrementProgress(1);
- }
- }
-
- //==============================================================================================
- //==============================================================================================
- //==============================================================================================
- // Investigations into source/line info
- void putRecordNumberByFileName(RecordNumber recordNumber, String filename) {
- Set<RecordNumber> recordNumbers = recordNumbersByFileName.get(filename);
- if (recordNumbers == null) {
- recordNumbers = new HashSet<>();
- recordNumbersByFileName.put(filename, recordNumbers);
- }
- recordNumbers.add(recordNumber);
- }
-
- //==============================================================================================
- void putRecordNumberByModuleNumber(RecordNumber recordNumber, int moduleNumber) {
- Set<RecordNumber> recordNumbers = recordNumbersByModuleNumber.get(moduleNumber);
- if (recordNumbers == null) {
- recordNumbers = new HashSet<>();
- recordNumbersByModuleNumber.put(moduleNumber, recordNumbers);
- }
- recordNumbers.add(recordNumber);
- }
-
- //==============================================================================================
- void dumpSourceFileRecordNumbers() {
- PdbLog.message("RecordNumbersByFileName");
- for (Map.Entry<String, Set<RecordNumber>> entry : recordNumbersByFileName.entrySet()) {
- String filename = entry.getKey();
- PdbLog.message("FileName: " + filename);
- for (RecordNumber recordNumber : entry.getValue()) {
- AbstractMsType msType = pdb.getTypeRecord(recordNumber);
- PdbLog.message(recordNumber.toString() + "\n" + msType);
- }
- }
- PdbLog.message("RecordNumbersByModuleNumber");
- for (Map.Entry<Integer, Set<RecordNumber>> entry : recordNumbersByModuleNumber.entrySet()) {
- int moduleNumber = entry.getKey();
- PdbLog.message("ModuleNumber: " + moduleNumber);
- for (RecordNumber recordNumber : entry.getValue()) {
- AbstractMsType msType = pdb.getTypeRecord(recordNumber);
- PdbLog.message(recordNumber.toString() + "\n" + msType);
- }
- }
- }
-
- //==============================================================================================
- //==============================================================================================
- //==============================================================================================
- private void processItemTypesSequentially() throws CancelledException, PdbException {
- AbstractTypeProgramInterface ipi = pdb.getItemProgramInterface();
- if (ipi == null) {
- return;
- }
- int num = ipi.getTypeIndexMaxExclusive() - ipi.getTypeIndexMin();
- monitor.initialize(num);
- setMonitorMessage("PDB: Processing " + num + " item type components...");
- for (int indexNumber = ipi.getTypeIndexMin(); indexNumber < ipi
- .getTypeIndexMaxExclusive(); indexNumber++) {
- monitor.checkCanceled();
- MsTypeApplier applier = getTypeApplier(RecordNumber.itemRecordNumber(indexNumber));
- applier.apply();
- monitor.incrementProgress(1);
- }
- }
-
- //==============================================================================================
- private void processSequentially() throws CancelledException, PdbException {
- processDataTypesSequentially();
- processItemTypesSequentially();
- }
-
- //==============================================================================================
- private void processDeferred() throws CancelledException, PdbException {
- List<MsTypeApplier> verticesInPostOrder = getVerticesInPostOrder();
- monitor.initialize(verticesInPostOrder.size());
- setMonitorMessage("PDB: Processing " + verticesInPostOrder.size() +
- " deferred data type dependencies...");
- for (MsTypeApplier applier : verticesInPostOrder) {
- monitor.checkCanceled();
- //PdbResearch.checkBreak(applier.index);
- //checkBreak(applier.index, applier);
- if (applier.isDeferred()) {
- applier.deferredApply();
- }
- monitor.incrementProgress(1);
- }
- }
-
- //==============================================================================================
- private void resolveSequentially() throws CancelledException {
- AbstractTypeProgramInterface tpi = pdb.getTypeProgramInterface();
- if (tpi == null) {
- return;
- }
- int num = tpi.getTypeIndexMaxExclusive() - tpi.getTypeIndexMin();
- monitor.initialize(num);
- setMonitorMessage("PDB: Resolving " + num + " data type components...");
- Date start = new Date();
- long longStart = start.getTime();
- for (int indexNumber = tpi.getTypeIndexMin(); indexNumber < tpi
- .getTypeIndexMaxExclusive(); indexNumber++) {
- monitor.checkCanceled();
- //PdbResearch.checkBreak(indexNumber);
- MsTypeApplier applier = getTypeApplier(RecordNumber.typeRecordNumber(indexNumber));
- //PdbResearch.checkBreak(indexNumber, applier);
- applier.resolve();
- monitor.incrementProgress(1);
- }
- Date stop = new Date();
- long longStop = stop.getTime();
- long timeDiff = longStop - longStart;
- Msg.info(this, "Resolve time: " + timeDiff + " mS");
- }
-
- //==============================================================================================
- //==============================================================================================
- //==============================================================================================
- DataType resolve(DataType dataType) {
- DataType resolved = getDataTypeManager().resolve(dataType,
- DataTypeConflictHandler.REPLACE_EMPTY_STRUCTS_OR_RENAME_AND_ADD_HANDLER);
- resolveCount++;
- return resolved;
- }
-
- //==============================================================================================
- //==============================================================================================
- //==============================================================================================
-
- //==============================================================================================
- // SymbolGroup-related methods.
- //==============================================================================================
- SymbolGroup getSymbolGroup() {
- return getSymbolGroupForModule(0);
- }
-
- SymbolGroup getSymbolGroupForModule(int moduleNumber) {
- if (moduleNumber < 0 || moduleNumber >= symbolGroups.size()) {
- return null;
- }
- return symbolGroups.get(moduleNumber);
- }
-
-// public AbstractMsSymbol getSymbolForModuleAndOffset(int moduleNumber, long offset)
-// throws PdbException {
-// return pdb.getDebugInfo().getSymbolForModuleAndOffsetOfRecord(moduleNumber, offset);
-// }
-
- //==============================================================================================
- // Address-related methods.
- //==============================================================================================
- /**
- * Returns true if the {@link Address} is an invalid address for continuing application of
- * information to the program. Will report Error or message for an invalid address and will
- * report a "External address" message for the name when the address is external.
- * @param address the address to test
- * @param name name associated with the address used for reporting error/info situations.
- * @return {@code true} if the address should be processed.
- */
- boolean isInvalidAddress(Address address, String name) {
- if (address == PdbAddressManager.BAD_ADDRESS) {
- appendLogMsg("Invalid address encountered for: " + name);
- return true;
- }
- if (address == PdbAddressManager.ZERO_ADDRESS) {
- // Symbol OMAP resulted in 0 RVA - Discard silently
- return true;
- }
- if (address == PdbAddressManager.EXTERNAL_ADDRESS) {
- //Msg.info(this, "External address not known for: " + name);
- return true;
- }
- return false;
- }
-
- /**
- * Returns the image base Address being used by the applicator.
- * @return The Address
- */
- Address getImageBase() {
- return imageBase;
- }
-
- /**
- * Returns the Address for the given section and offset.
- * @param symbol The {@link AddressMsSymbol}
- * @return The Address, which can be {@code Address.NO_ADDRESS} if invalid or
- * {@code Address.EXTERNAL_ADDRESS} if the address is external to the program.
- */
- Address getAddress(AddressMsSymbol symbol) {
- return pdbAddressManager.getAddress(symbol);
- }
-
- /**
- * Returns the Address for the given section and offset.
- * @param segment The segment
- * @param offset The offset
- * @return The Address
- */
- Address getAddress(int segment, long offset) {
- return pdbAddressManager.getRawAddress(segment, offset);
- }
-
- /**
- * Returns the Address for the given section and offset.
- * @param symbol The {@link AddressMsSymbol}
- * @return The Address, which can be {@code Address.NO_ADDRESS} if invalid or
- * {@code Address.EXTERNAL_ADDRESS} if the address is external to the program.
- */
- Address getRawAddress(AddressMsSymbol symbol) {
- return pdbAddressManager.getRawAddress(symbol);
- }
-
- /**
- * Indicate to the {@link PdbAddressManager} that a new symbol with the given name has the
- * associated address. This allows the PdbAddressManager to create and organize the
- * re-mapped address and supply them. Also returns the address of the pre-existing symbol
- * of the same name if the name was unique, otherwise null if it didn't exist or wasn't
- * unique.
- * @param name the symbol name
- * @param address its associated address
- * @return the {@link Address} of existing symbol or null
- */
- Address witnessSymbolNameAtAddress(String name, Address address) {
- return pdbAddressManager.witnessSymbolNameAtAddress(name, address);
- }
-
- /**
- * Returns the Address of an existing symbol for the query address, where the mapping is
- * derived by using a the address of a PDB symbol as the key and finding the address of
- * a symbol in the program of the same "unique" name. This is accomplished using public
- * mangled symbols. If the program symbol came from the PDB, then it maps to itself.
- * @param address the query address
- * @return the remapAddress
- */
- Address getRemapAddressByAddress(Address address) {
- return pdbAddressManager.getRemapAddressByAddress(address);
- }
-
- /**
- * Method for callee to set the real address for the section.
- * @param sectionNum the section number
- * @param realAddress The Address
- */
- void putRealAddressesBySection(int sectionNum, long realAddress) {
- pdbAddressManager.putRealAddressesBySection(sectionNum, realAddress);
- }
-
- /**
- * Method for callee to add a Memory Group symbol to the Memory Group list.
- * @param symbol the symbol.
- */
- void addMemoryGroupRefinement(PeCoffGroupMsSymbol symbol) {
- pdbAddressManager.addMemoryGroupRefinement(symbol);
- }
-
- /**
- * Method for callee to add a Memory Section symbol to the Memory Section list.
- * @param symbol the symbol.
- */
- void addMemorySectionRefinement(PeCoffSectionMsSymbol symbol) {
- pdbAddressManager.addMemorySectionRefinement(symbol);
- }
-
- //==============================================================================================
- // CLI-Managed infor methods.
- //==============================================================================================
-
- // Currently in CLI, but could move.
- boolean isDll() {
- return pdbCliManagedInfoManager.isDll();
- }
-
- // Currently in CLI, but could move.
- boolean isAslr() {
- return pdbCliManagedInfoManager.isAslr();
- }
-
- /**
- * Get CLI metadata for specified tableNum and rowNum within the CLI
- * metadata stream.
- * @param tableNum CLI metadata stream table index
- * @param rowNum table row number
- * @return CLI metadata or null if specified tableNum not found
- * @throws PdbException if CLI metadata stream is not found in program file bytes
- * @throws IndexOutOfBoundsException if specified rowNum is invalid
- */
- CliAbstractTableRow getCliTableRow(int tableNum, int rowNum) throws PdbException {
- return pdbCliManagedInfoManager.getCliTableRow(tableNum, rowNum);
- }
-
- //==============================================================================================
- // Virtual-Base-Table-related methods.
- //==============================================================================================
- VbtManager getVbtManager() {
- return vbtManager;
- }
-
- //==============================================================================================
- //
- //==============================================================================================
- Register getRegister(String pdbRegisterName) {
- return registerNameToRegisterMapper.getRegister(pdbRegisterName);
- }
-
- //==============================================================================================
- //==============================================================================================
- @SuppressWarnings("unused") // for method not being called.
- /**
- * Process all symbols. User should not then call other methods:
- * {@link #processGlobalSymbolsNoTypedefs()}, (@link #processPublicSymbols()}, and
- * {@link #processNonPublicOrGlobalSymbols()}.
+ * Returns the {@link PeCoffSectionMsSymbol}s from the "Linker" module
+ * @return list of symbols
* @throws CancelledException upon user cancellation
- * @throws PdbException upon issue processing the request
*/
- private void processAllSymbols() throws CancelledException, PdbException {
- processMainSymbols();
- processModuleSymbols();
- }
-
- //==============================================================================================
- @SuppressWarnings("unused") // for method not being called.
- private void processMainSymbols() throws CancelledException, PdbException {
- // Get a count
- SymbolGroup symbolGroup = getSymbolGroup();
- if (symbolGroup == null) {
- return;
- }
- int totalCount = symbolGroup.size();
- setMonitorMessage("PDB: Applying " + totalCount + " main symbol components...");
- monitor.initialize(totalCount);
- AbstractMsSymbolIterator iter = symbolGroup.iterator();
- processSymbolGroup(0, iter);
- }
-
- //==============================================================================================
- private void processModuleSymbols() throws CancelledException {
- PdbDebugInfo debugInfo = pdb.getDebugInfo();
- if (debugInfo == null) {
- return;
- }
-
- int totalCount = 0;
- int num = debugInfo.getNumModules();
- for (int moduleNumber = 1; moduleNumber <= num; moduleNumber++) {
- monitor.checkCanceled();
- SymbolGroup symbolGroup = getSymbolGroupForModule(moduleNumber);
- if (symbolGroup == null) {
- continue; // should not happen
- }
- totalCount += symbolGroup.size();
- }
- setMonitorMessage("PDB: Applying " + totalCount + " module symbol components...");
- monitor.initialize(totalCount);
-
- // Process symbols list for each module
- for (int moduleNumber = 1; moduleNumber <= num; moduleNumber++) {
- monitor.checkCanceled();
- // Process module symbols list
- SymbolGroup symbolGroup = getSymbolGroupForModule(moduleNumber);
- if (symbolGroup == null) {
- continue; // should not happen
- }
- AbstractMsSymbolIterator iter = symbolGroup.iterator();
- processSymbolGroup(moduleNumber, iter);
-// catelogSymbols(index, symbolGroup);
- // do not call monitor.incrementProgress(1) here, as it is updated inside of
- // processSymbolGroup.
- }
- }
-
-// private Set<Class<? extends AbstractMsSymbol>> moduleSymbols = new HashSet<>();
-//
-// private void catelogSymbols(int moduleNumber, SymbolGroup symbolGroup)
-// throws CancelledException {
-// symbolGroup.initGet();
-// while (symbolGroup.hasNext()) {
-// monitor.checkCanceled();
-// AbstractMsSymbol symbol = symbolGroup.peek();
-// moduleSymbols.add(symbol.getClass());
-// symbolGroup.next();
-// }
-// }
-//
- //==============================================================================================
- private void processSymbolGroup(int moduleNumber, AbstractMsSymbolIterator iter)
- throws CancelledException {
- iter.initGet();
- while (iter.hasNext()) {
- monitor.checkCanceled();
- procSym(iter);
- monitor.incrementProgress(1);
- }
- }
-
- //==============================================================================================
- /**
- * Process public symbols. User should not then call {@link #processAllSymbols()}; but
- * has these other methods available to supplement this one: {@link #processGlobalSymbolsNoTypedefs()}
- * and {@link #processNonPublicOrGlobalSymbols()}.
- * @throws CancelledException upon user cancellation
- * @throws PdbException upon issue processing the request
- */
- private void processPublicSymbols() throws CancelledException, PdbException {
-
- PdbDebugInfo debugInfo = pdb.getDebugInfo();
- if (debugInfo == null) {
- return;
- }
-
- SymbolGroup symbolGroup = getSymbolGroup();
- if (symbolGroup == null) {
- return;
- }
-
- PublicSymbolInformation publicSymbolInformation = debugInfo.getPublicSymbolInformation();
- List<Long> offsets = publicSymbolInformation.getModifiedHashRecordSymbolOffsets();
- setMonitorMessage("PDB: Applying " + offsets.size() + " public symbol components...");
- monitor.initialize(offsets.size());
-
- AbstractMsSymbolIterator iter = symbolGroup.iterator();
- for (long offset : offsets) {
- monitor.checkCanceled();
- iter.initGetByOffset(offset);
- if (!iter.hasNext()) {
- break;
- }
- pdbApplicatorMetrics.witnessPublicSymbolType(iter.peek());
- procSym(iter);
- monitor.incrementProgress(1);
- }
- }
+ public List<PeCoffSectionMsSymbol> getLinkerPeCoffSectionSymbols() throws CancelledException;
/**
- * Process global symbols--no typedef. User should not then call {@link #processAllSymbols()};
- * but has these other methods available to supplement this one: (@link #processPublicSymbols()}
- * and {@link #processNonPublicOrGlobalSymbols()}.
+ * Returns the compile symbol seen in the "Linker" module. Should be one of
+ * {@link Compile3MsSymbol} or {@link AbstractCompile2MsSymbol}.
+ * @return the compile symbol
* @throws CancelledException upon user cancellation
- * @throws PdbException upon issue processing the request
*/
- private void processGlobalSymbolsNoTypedefs() throws CancelledException, PdbException {
-
- PdbDebugInfo debugInfo = pdb.getDebugInfo();
- if (debugInfo == null) {
- return;
- }
-
- SymbolGroup symbolGroup = getSymbolGroup();
- if (symbolGroup == null) {
- return;
- }
-
- GlobalSymbolInformation globalSymbolInformation = debugInfo.getGlobalSymbolInformation();
- List<Long> offsets = globalSymbolInformation.getModifiedHashRecordSymbolOffsets();
- setMonitorMessage("PDB: Applying global symbols...");
- monitor.initialize(offsets.size());
-
- AbstractMsSymbolIterator iter = symbolGroup.iterator();
- for (long offset : offsets) {
- monitor.checkCanceled();
- iter.initGetByOffset(offset);
- if (!iter.hasNext()) {
- break;
- }
- AbstractMsSymbol symbol = iter.peek();
- pdbApplicatorMetrics.witnessGlobalSymbolType(symbol);
- if (!(symbol instanceof AbstractUserDefinedTypeMsSymbol)) { // Not doing typedefs here
- procSym(iter);
- }
- monitor.incrementProgress(1);
- }
- }
-
- /**
- * Process global typdef symbols.
- * @throws CancelledException upon user cancellation
- * @throws PdbException upon issue processing the request
- */
- private void processGlobalTypdefSymbols() throws CancelledException, PdbException {
-
- PdbDebugInfo debugInfo = pdb.getDebugInfo();
- if (debugInfo == null) {
- return;
- }
-
- SymbolGroup symbolGroup = getSymbolGroup();
- if (symbolGroup == null) {
- return;
- }
-
- GlobalSymbolInformation globalSymbolInformation = debugInfo.getGlobalSymbolInformation();
- List<Long> offsets = globalSymbolInformation.getModifiedHashRecordSymbolOffsets();
- setMonitorMessage("PDB: Applying typedefs...");
- monitor.initialize(offsets.size());
-
- AbstractMsSymbolIterator iter = symbolGroup.iterator();
- for (long offset : offsets) {
- monitor.checkCanceled();
- iter.initGetByOffset(offset);
- if (!iter.hasNext()) {
- break;
- }
- AbstractMsSymbol symbol = iter.peek();
- if (symbol instanceof AbstractUserDefinedTypeMsSymbol) { // Doing typedefs here
- procSym(iter);
- }
- monitor.incrementProgress(1);
- }
- }
-
- /**
- * Processing non-public, non-global symbols. User should not then call
- * {@link #processAllSymbols()}; but has these other methods available to supplement this one:
- * {@link #processGlobalSymbolsNoTypedefs()} and (@link #processPublicSymbols()}.
- * @throws CancelledException upon user cancellation
- * @throws PdbException upon issue processing the request
- */
- @SuppressWarnings("unused") // for method not being called.
- private void processNonPublicOrGlobalSymbols() throws CancelledException, PdbException {
- PdbDebugInfo debugInfo = pdb.getDebugInfo();
- if (debugInfo == null) {
- return;
- }
-
- SymbolGroup symbolGroup = getSymbolGroup();
- if (symbolGroup == null) {
- return;
- }
-
- Set<Long> offsetsRemaining = symbolGroup.getOffsets();
- for (long off : debugInfo.getPublicSymbolInformation()
- .getModifiedHashRecordSymbolOffsets()) {
- monitor.checkCanceled();
- offsetsRemaining.remove(off);
- }
- for (long off : debugInfo.getGlobalSymbolInformation()
- .getModifiedHashRecordSymbolOffsets()) {
- monitor.checkCanceled();
- offsetsRemaining.remove(off);
- }
-
- setMonitorMessage(
- "PDB: Applying " + offsetsRemaining.size() + " other symbol components...");
- monitor.initialize(offsetsRemaining.size());
- //getCategoryUtils().setModuleTypedefsCategory(null);
-
- AbstractMsSymbolIterator iter = symbolGroup.iterator();
- for (long offset : offsetsRemaining) {
- monitor.checkCanceled();
- iter.initGetByOffset(offset);
- AbstractMsSymbol symbol = iter.peek();
- procSym(iter);
- monitor.incrementProgress(1);
- }
- }
-
- //==============================================================================================
- private int findLinkerModuleNumber() {
- PdbDebugInfo debugInfo = pdb.getDebugInfo();
- if (debugInfo != null) {
- int num = 1;
- for (AbstractModuleInformation module : debugInfo.getModuleInformationList()) {
- if (isLinkerModule(module.getModuleName())) {
- return num;
- }
- num++;
- }
- }
- pdbLogAndInfoMessage(this, "Not processing linker symbols because linker module not found");
- return -1;
- }
-
- private boolean isLinkerModule(String name) {
- return "* Linker *".equals(name);
- }
-
- //==============================================================================================
- @SuppressWarnings("unused") // for method not being called.
- private boolean processLinkerSymbols() throws CancelledException {
-
- int linkerModuleNumber = findLinkerModuleNumber();
- if (linkerModuleNumber == -1) {
- return false;
- }
-
- SymbolGroup symbolGroup = getSymbolGroupForModule(linkerModuleNumber);
- if (symbolGroup == null) {
- Msg.info(this, "No symbols to process from linker module.");
- return false;
- }
-
- setMonitorMessage("PDB: Applying " + symbolGroup.size() + " linker symbol components...");
- monitor.initialize(symbolGroup.size());
-
- AbstractMsSymbolIterator iter = symbolGroup.iterator();
- while (iter.hasNext()) {
- checkCanceled();
- pdbApplicatorMetrics.witnessLinkerSymbolType(iter.peek());
- procSym(iter);
- monitor.incrementProgress(1);
- }
- return true;
- }
-
- //==============================================================================================
- private void processThunkSymbolsFromNonLinkerModules() throws CancelledException {
-
- PdbDebugInfo debugInfo = pdb.getDebugInfo();
- if (debugInfo == null) {
- return;
- }
-
- int linkerModuleNumber = findLinkerModuleNumber();
-
- int totalCount = 0;
- int num = debugInfo.getNumModules();
- for (int index = 1; index <= num; index++) {
- monitor.checkCanceled();
- if (index == linkerModuleNumber) {
- continue;
- }
- SymbolGroup symbolGroup = getSymbolGroupForModule(index);
- if (symbolGroup == null) {
- continue; // should not happen
- }
- totalCount += symbolGroup.size();
- }
- setMonitorMessage("PDB: Processing module thunks...");
- monitor.initialize(totalCount);
-
- // Process symbols list for each module
- for (int index = 1; index <= num; index++) {
- monitor.checkCanceled();
- if (index == linkerModuleNumber) {
- continue;
- }
- SymbolGroup symbolGroup = getSymbolGroupForModule(index);
- if (symbolGroup == null) {
- continue; // should not happen
- }
- AbstractMsSymbolIterator iter = symbolGroup.iterator();
- while (iter.hasNext()) {
- monitor.checkCanceled();
- AbstractMsSymbol symbol = iter.peek();
- if (symbol instanceof AbstractThunkMsSymbol) {
- procSym(iter);
- }
- else {
- iter.next();
- }
- monitor.incrementProgress(1);
- }
- }
-
- }
-
- //==============================================================================================
- //==============================================================================================
- //==============================================================================================
- MsSymbolApplier getSymbolApplier(AbstractMsSymbolIterator iter) throws CancelledException {
- return symbolApplierParser.getSymbolApplier(iter);
- }
-
- //==============================================================================================
- void procSym(AbstractMsSymbolIterator iter) throws CancelledException {
- try {
- MsSymbolApplier applier = getSymbolApplier(iter);
- applier.apply();
- }
- catch (PdbException e) {
- // skipping symbol
- Msg.info(this, "Error applying symbol to program: " + e.toString());
- }
- }
-
- //==============================================================================================
- //==============================================================================================
- //==============================================================================================
- boolean isClass(SymbolPath path) {
- return isClassByNamespace.get(path);
- }
-
- //==============================================================================================
- void predefineClass(SymbolPath classPath) {
- isClassByNamespace.put(classPath, true);
- for (SymbolPath path = classPath.getParent(); path != null; path = path.getParent()) {
- if (!isClassByNamespace.containsKey(path)) {
- isClassByNamespace.put(path, false); // path is simple namespace
- }
- }
- }
-
- //==============================================================================================
- private void defineClasses() throws CancelledException {
- // create namespace and classes in an ordered fashion use tree map
- monitor.initialize(isClassByNamespace.size());
- setMonitorMessage("PDB: Defining classes...");
- for (Map.Entry<SymbolPath, Boolean> entry : isClassByNamespace.entrySet()) {
- monitor.checkCanceled();
- SymbolPath path = entry.getKey();
- boolean isClass = entry.getValue();
- Namespace parentNamespace =
- NamespaceUtils.getNonFunctionNamespace(program, path.getParent());
- if (parentNamespace == null) {
- String type = isClass ? "class" : "namespace";
- log.appendMsg(
- "PDB Warning: Because parent namespace does not exist, failed to define " +
- type + ": " + path);
- continue;
- }
- defineNamespace(parentNamespace, path.getName(), isClass);
- monitor.incrementProgress(1);
-
- }
- }
-
- //==============================================================================================
- private void defineNamespace(Namespace parentNamespace, String name, boolean isClass) {
-
- try {
- SymbolTable symbolTable = program.getSymbolTable();
- Namespace namespace = symbolTable.getNamespace(name, parentNamespace);
- if (namespace != null) {
- if (isClass) {
- if (namespace instanceof GhidraClass) {
- return;
- }
- if (isSimpleNamespaceSymbol(namespace)) {
- NamespaceUtils.convertNamespaceToClass(namespace);
- return;
- }
- }
- else if (namespace.getSymbol().getSymbolType() == SymbolType.NAMESPACE) {
- return;
- }
- log.appendMsg(
- "PDB Warning: Unable to create class namespace due to conflicting symbol: " +
- namespace.getName(true));
- }
- else if (isClass) {
- symbolTable.createClass(parentNamespace, name, SourceType.IMPORTED);
- }
- else {
- symbolTable.createNameSpace(parentNamespace, name, SourceType.IMPORTED);
- }
- }
- catch (InvalidInputException | DuplicateNameException e) {
- log.appendMsg(
- "PDB Warning: Unable to create class namespace due to exception: " + e.toString() +
- "; Namespace: " + parentNamespace.getName(true) + Namespace.DELIMITER + name);
- }
- }
-
- //==============================================================================================
- private boolean isSimpleNamespaceSymbol(Namespace namespace) {
- Symbol s = namespace.getSymbol();
- if (s.getSymbolType() != SymbolType.NAMESPACE) {
- return false;
- }
- Namespace n = namespace;
- while (n != null) {
- if (n instanceof Function) {
- return false;
- }
- n = n.getParentNamespace();
- }
- return true;
- }
-
- //==============================================================================================
- //==============================================================================================
- //==============================================================================================
- @SuppressWarnings("unused") // for method not being called.
- private void storeLabelByAddress(Address address, String label) {
- Set<String> labels = labelsByAddress.get(address);
- if (labels == null) {
- labels = new TreeSet<>();
- labelsByAddress.put(address, labels);
- }
- if (labels.contains(label)) {
- // TODO investigate why we would see it again.
- }
- labels.add(label);
- }
-
- @SuppressWarnings("unused") // for method not being called.
- private void dumpLabels() {
- for (Map.Entry<Address, Set<String>> entry : labelsByAddress.entrySet()) {
- Address address = entry.getKey();
- Set<String> labels = entry.getValue();
- System.out.println("\nAddress: " + address);
- for (String label : labels) {
- System.out.println(label);
- }
- }
- }
-
- //==============================================================================================
- boolean shouldForcePrimarySymbol(Address address, boolean forceIfMangled) {
- Symbol primarySymbol = program.getSymbolTable().getPrimarySymbol(address);
- if (primarySymbol != null) {
-
- if (primarySymbol.getName().startsWith("?") && forceIfMangled &&
- applicatorOptions.allowDemotePrimaryMangledSymbols()) {
- return true;
- }
-
- SourceType primarySymbolSource = primarySymbol.getSource();
-
- if (!SourceType.ANALYSIS.isHigherPriorityThan(primarySymbolSource)) {
- return true;
- }
- }
- return false;
- }
-
- //==============================================================================================
- @SuppressWarnings("unused") // For method not being called. In process of removing this version
- boolean createSymbolOld(Address address, String symbolPathString, boolean forcePrimary) {
-
-// storeLabelByAddress(address, symbolPathString);
-
- try {
- Namespace namespace = program.getGlobalNamespace();
- if (symbolPathString.startsWith(THUNK_NAME_PREFIX)) {
- symbolPathString = symbolPathString.substring(THUNK_NAME_PREFIX.length(),
- symbolPathString.length());
- }
- SymbolPath symbolPath = new SymbolPath(symbolPathString);
- symbolPath = symbolPath.replaceInvalidChars();
- String name = symbolPath.getName();
- String namespacePath = symbolPath.getParentPath();
- if (namespacePath != null) {
- namespace = NamespaceUtils.createNamespaceHierarchy(namespacePath, namespace,
- program, address, SourceType.IMPORTED);
- }
-
- Symbol s = SymbolUtilities.createPreferredLabelOrFunctionSymbol(program, address,
- namespace, name, SourceType.IMPORTED);
- if (s != null && forcePrimary) {
- // PDB contains both mangled, namespace names, and global names
- // If mangled name does not remain primary it will not get demamgled
- // and we may not get signature information applied
- SetLabelPrimaryCmd cmd =
- new SetLabelPrimaryCmd(address, s.getName(), s.getParentNamespace());
- cmd.applyTo(program);
- }
- return true;
- }
- catch (InvalidInputException e) {
- log.appendMsg("PDB Warning: Unable to create symbol: " + e.getMessage());
- }
- return false;
- }
-
- //==============================================================================================
- private static class PrimarySymbolInfo {
- private Symbol symbol;
- private boolean isNewSymbol;
-
- private PrimarySymbolInfo(Symbol symbol, boolean isNewSymbol) {
- this.symbol = symbol;
- this.isNewSymbol = isNewSymbol;
- }
-
- private boolean canBePrimaryForceOverriddenBy(String newName) {
- if (getSource().isLowerPriorityThan(SourceType.IMPORTED)) {
- return true;
- }
- if (isMangled() && !PdbApplicator.isMangled(newName)) {
- return true;
- }
- if (isNewSymbol()) {
- return false;
- }
- return false;
- }
-
- private SourceType getSource() {
- return symbol.getSource();
- }
-
- private boolean isMangled() {
- return symbol.getName().startsWith("?");
- }
-
- private boolean isNewSymbol() {
- return isNewSymbol;
- }
- }
-
- private Map<Address, PrimarySymbolInfo> primarySymbolInfoByAddress = new HashMap<>();
-
- //==============================================================================================
- Symbol createSymbol(Address address, String symbolPathString,
- boolean forcePrimaryIfExistingIsMangled) {
- return createSymbol(address, symbolPathString, forcePrimaryIfExistingIsMangled, null);
- }
-
- Symbol createSymbol(Address address, String symbolPathString,
- boolean forcePrimaryIfExistingIsMangled, String plateAddition) {
-
- // Must get existing info before creating new symbol, as we do not want "existing"
- // to include the new one
- PrimarySymbolInfo existingPrimarySymbolInfo = getExistingPrimarySymbolInfo(address);
- Symbol newSymbol = createSymbol(address, symbolPathString);
- if (newSymbol == null) {
- return null;
- }
-
- boolean forcePrimary = false;
- if (existingPrimarySymbolInfo != null) {
- if (existingPrimarySymbolInfo.canBePrimaryForceOverriddenBy(symbolPathString) &&
- forcePrimaryIfExistingIsMangled &&
- applicatorOptions.allowDemotePrimaryMangledSymbols()) {
- forcePrimary = true;
- }
- }
-
- boolean forcePrimarySucceeded = false;
- if (forcePrimary) {
- SetLabelPrimaryCmd cmd = new SetLabelPrimaryCmd(address, newSymbol.getName(),
- newSymbol.getParentNamespace());
- if (cmd.applyTo(program)) {
- forcePrimarySucceeded = true;
- }
- }
-
- if (existingPrimarySymbolInfo == null || forcePrimarySucceeded) {
- PrimarySymbolInfo primarySymbolInfo = new PrimarySymbolInfo(newSymbol, true);
- setExistingPrimarySymbolInfo(address, primarySymbolInfo);
- }
-
- addToPlateUnique(address, plateAddition);
-
- return newSymbol;
- }
-
- private boolean addToPlateUnique(Address address, String comment) {
- if (StringUtils.isBlank(comment)) {
- return false;
- }
- String plate = program.getListing().getComment(CodeUnit.PLATE_COMMENT, address);
- if (plate == null) {
- plate = "";
- }
- else if (plate.contains(comment)) {
- return true;
- }
- else if (!plate.endsWith("\n")) {
- plate += '\n';
- }
- plate += comment;
- SetCommentCmd.createComment(program, address, comment, CodeUnit.PLATE_COMMENT);
- return true;
- }
-
- private static boolean isMangled(String name) {
- return name.startsWith("?");
- }
-
- private void setExistingPrimarySymbolInfo(Address address, PrimarySymbolInfo info) {
- primarySymbolInfoByAddress.put(address, info);
- }
-
- private PrimarySymbolInfo getExistingPrimarySymbolInfo(Address address) {
- PrimarySymbolInfo info = primarySymbolInfoByAddress.get(address);
- if (info != null) {
- return info;
- }
- Symbol primarySymbol = pdbAddressManager.getPrimarySymbol(address);
- if (primarySymbol == null ||
- primarySymbol.getSource().isLowerPriorityThan(SourceType.IMPORTED)) {
- return null;
- }
- info = new PrimarySymbolInfo(primarySymbol, false);
- primarySymbolInfoByAddress.put(address, info);
- return info;
- }
-
- private Symbol createSymbol(Address address, String symbolPathString) {
- Symbol symbol = null;
- try {
- Namespace namespace = program.getGlobalNamespace();
- if (symbolPathString.startsWith(THUNK_NAME_PREFIX)) {
- symbolPathString = symbolPathString.substring(THUNK_NAME_PREFIX.length(),
- symbolPathString.length());
- }
- SymbolPath symbolPath = new SymbolPath(symbolPathString);
- symbolPath = symbolPath.replaceInvalidChars();
- String name = symbolPath.getName();
- String namespacePath = symbolPath.getParentPath();
- if (namespacePath != null) {
- namespace = NamespaceUtils.createNamespaceHierarchy(namespacePath, namespace,
- program, address, SourceType.IMPORTED);
- }
-
- symbol =
- program.getSymbolTable().createLabel(address, name, namespace, SourceType.IMPORTED);
- }
- catch (InvalidInputException e) {
- log.appendMsg("PDB Warning: Unable to create symbol at " + address +
- " due to exception: " + e.toString() + "; symbolPathName: " + symbolPathString);
- }
- return symbol;
- }
+ public AbstractMsSymbol getLinkerModuleCompileSymbol() throws CancelledException;
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbApplicatorOptions.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbApplicatorOptions.java
index cdc811cb68..81a64bebb6 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbApplicatorOptions.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbApplicatorOptions.java
@@ -20,7 +20,7 @@ import ghidra.framework.options.Options;
import ghidra.util.HelpLocation;
/**
- * Options used while using a {@link PdbApplicator} to apply a PDB ({@link AbstractPdb}) to a
+ * Options used while using a {@link DefaultPdbApplicator} to apply a PDB ({@link AbstractPdb}) to a
* Ghidra program. These can be optional values used during our development of this PdbApplicator,
* and thus might not be found in the finished product.
*/
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbCliInfoManager.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbPeHeaderInfoManager.java
similarity index 76%
rename from Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbCliInfoManager.java
rename to Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbPeHeaderInfoManager.java
index 21411e3cf8..df1ad3cea8 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbCliInfoManager.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbPeHeaderInfoManager.java
@@ -31,25 +31,25 @@ import ghidra.program.database.mem.FileBytes;
import ghidra.program.model.listing.Program;
/**
- * Manages CLI-Managed information, the bounds of which we do not yet know.
+ * Manages PE Header information that we need that is not retained in the Program.
+ * Current data includes CLI-Managed information and original image base.
*/
-public class PdbCliInfoManager {
-
- private PdbApplicator applicator;
+public class PdbPeHeaderInfoManager {
+ private DefaultPdbApplicator applicator;
private boolean initComplete = false;
- private CliStreamMetadata metadataStream;
- // TODO: May move these out from this class to a higher level. Would mean passing in
- // the appropriate header to this constructor if we want to reuse that code.
+ private CliStreamMetadata metadataStream;
private boolean isDll = false;
private boolean isAslr = false;
+ private long originalImageBase = 0;
/**
* Manager of CLI-related tables that we might need access to for PDB processing.
- * @param applicator {@link PdbApplicator} for which this class is working (used for logging purposes only).
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working (used for
+ * logging purposes only).
*/
- PdbCliInfoManager(PdbApplicator applicator) {
+ PdbPeHeaderInfoManager(DefaultPdbApplicator applicator) {
Objects.requireNonNull(applicator, "applicator may not be null");
this.applicator = applicator;
}
@@ -58,8 +58,8 @@ public class PdbCliInfoManager {
if (initComplete) {
return;
}
+ retrievePEHeaderInformation();
initComplete = true;
- metadataStream = getCliStreamMetadata();
}
boolean isDll() {
@@ -72,6 +72,11 @@ public class PdbCliInfoManager {
return isAslr;
}
+ long getOriginalImageBase() {
+ initialize();
+ return originalImageBase;
+ }
+
/**
* Get CLI metadata for specified tableNum and rowNum within the CLI
* metadata stream.
@@ -95,20 +100,21 @@ public class PdbCliInfoManager {
}
/**
- * Get CLI stream metadata
- * @return CLI stream metadata or null if not found or error occured
+ * Get CLI stream metadata. Results directly filled into data members
*/
- private CliStreamMetadata getCliStreamMetadata() {
+ private void retrievePEHeaderInformation() {
Program program = applicator.getProgram();
if (program == null) {
- return null;
+ applicator.pdbLogAndErrorMessage(this,
+ "Unable to retrieve Program header: program null", null);
+ return;
}
List<FileBytes> allFileBytes = program.getMemory().getAllFileBytes();
if (allFileBytes.isEmpty()) {
applicator.pdbLogAndErrorMessage(this,
- "Unable to retrieve CliStreamMetadata: no FileBytes", null);
- return null;
+ "Unable to retrieve Program header: no FileBytes", null);
+ return;
}
FileBytes fileBytes = allFileBytes.get(0); // Should be that of main imported file
ByteProvider provider = new FileBytesProvider(fileBytes); // close not required
@@ -117,11 +123,11 @@ public class PdbCliInfoManager {
new PortableExecutable(provider, SectionLayout.FILE, true, true);
NTHeader ntHeader = pe.getNTHeader(); // will be null if header parse fails
if (ntHeader == null) {
- applicator.pdbLogAndErrorMessage(this,
- "Unable to retrieve CliStreamMetadata: NTHeader file bytes not found", null);
- return null;
+ applicator.pdbLogAndErrorMessage(this, "Unable to retrieve NTHeader from PE", null);
+ return;
}
OptionalHeader optionalHeader = ntHeader.getOptionalHeader();
+ originalImageBase = optionalHeader.getImageBase();
int characteristics = ntHeader.getFileHeader().getCharacteristics();
isDll = (characteristics & FileHeader.IMAGE_FILE_DLL) == FileHeader.IMAGE_FILE_DLL;
DataDirectory[] dataDirectory = optionalHeader.getDataDirectories();
@@ -130,30 +136,28 @@ public class PdbCliInfoManager {
OptionalHeader.IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA) == OptionalHeader.IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA;
if (OptionalHeader.IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR >= dataDirectory.length) {
applicator.pdbLogAndErrorMessage(this,
- "Unable to retrieve CliStreamMetadata: Bad index (" +
- OptionalHeader.IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR +
+ "Bad index (" + OptionalHeader.IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR +
") for COMDescriptorDataDirectory in DataDirectory array of size " +
dataDirectory.length,
null);
- return null;
+ return;
}
COMDescriptorDataDirectory comDir =
(COMDescriptorDataDirectory) dataDirectory[OptionalHeader.IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR];
ImageCor20Header header = comDir.getHeader();
if (header == null) {
- applicator.pdbLogAndErrorMessage(this,
- "Unable to retrieve CliStreamMetadata: no COMDir header", null);
- return null;
+ applicator.pdbLogAndErrorMessage(this, "COMDir header not available", null);
+ return;
}
- return header.getMetadata().getMetadataRoot().getMetadataStream();
+ metadataStream = header.getMetadata().getMetadataRoot().getMetadataStream();
}
catch (RuntimeException | IOException e) {
// We do not know what can go wrong. Some of the header parsing might have issues,
// and we'd rather log the error and limp on by with whatever other processing we can
// do than to fail here.
applicator.pdbLogAndErrorMessage(this,
- "Unable to retrieve CliStreamMetadata: " + e.getMessage(), e);
- return null;
+ "Unable to retrieve program header information: " + e.getMessage(), e);
+ return;
}
}
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbPrimitiveTypeApplicator.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbPrimitiveTypeApplicator.java
index a9aadbaeaa..1a438ee2c9 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbPrimitiveTypeApplicator.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbPrimitiveTypeApplicator.java
@@ -23,8 +23,9 @@ import ghidra.program.model.data.*;
import ghidra.util.exception.AssertException;
/**
- * Takes care of allocating unique instances of primitive data types for the {@link PdbApplicator},
- * and is used principally by the many instances of {@link PrimitiveTypeApplier}.
+ * Takes care of allocating unique instances of primitive data types for the
+ * {@link DefaultPdbApplicator}, and is used principally by the many instances of
+ * {@link PrimitiveTypeApplier}.
*/
public class PdbPrimitiveTypeApplicator {
@@ -59,7 +60,7 @@ public class PdbPrimitiveTypeApplicator {
}
/**
- * Returns the {@link DataTypeManager} associated with this analyzer.
+ * Returns the {@link DataTypeManager} associated with this analyzer.
* @return DataTypeManager which this analyzer is using.
*/
private DataTypeManager getDataTypeManager() {
@@ -516,7 +517,7 @@ public class PdbPrimitiveTypeApplicator {
return getRealType(16, "float128");
}
- /*
+ /*
* First get type from "other" list, which are typedefs to underlying primitives. If it does
* not exist, then find the proper underlying primitive, create the typedef, and cache this
* newly minted (typedef) unique primitive type.
@@ -629,7 +630,7 @@ public class PdbPrimitiveTypeApplicator {
return getBooleanType(16, "T_BOOL128");
}
- /*
+ /*
* First get type from "other" list, which are typedefs to underlying primitives. If it does
* not exist, then find the proper underlying primitive, create the typedef, and cache this
* newly minted (typedef) unique primitive type.
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbResearch.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbResearch.java
index 669506b80d..ba0f76cc5a 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbResearch.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbResearch.java
@@ -334,8 +334,8 @@ public class PdbResearch {
static void checkBreak(int recordNumber, MsTypeApplier applier) {
String nn = applier.getMsType().getName();
- if ("std::__1::__map_value_compare<std::__1::basic_string<char>,std::__1::__value_type<std::__1::basic_string<char>,std::__1::basic_string<wchar_t> >,std::__1::less<void>,1>"
- .equals(nn)) {
+ if ("std::__1::__map_value_compare<std::__1::basic_string<char>,std::__1::__value_type<std::__1::basic_string<char>,std::__1::basic_string<wchar_t> >,std::__1::less<void>,1>".equals(
+ nn)) {
doNothingSetBreakPointHere();
}
if ("class std::__1::__iostream_category".equals(nn)) {
@@ -394,7 +394,7 @@ public class PdbResearch {
// developerDebugOrderIndexNumbers.add(5051); // fwdref is 4505
}
- static void developerDebugOrder(PdbApplicator applicator, TaskMonitor monitor)
+ static void developerDebugOrder(DefaultPdbApplicator applicator, TaskMonitor monitor)
throws CancelledException, PdbException {
initDeveloperOrderRecordNumbers();
for (int indexNumber : developerDebugOrderIndexNumbers) {
@@ -409,7 +409,7 @@ public class PdbResearch {
//==============================================================================================
//==============================================================================================
- static void childWalk(PdbApplicator applicator, TaskMonitor monitor)
+ static void childWalk(DefaultPdbApplicator applicator, TaskMonitor monitor)
throws CancelledException, PdbException {
PdbDebugInfo debugInfo = applicator.getPdb().getDebugInfo();
@@ -438,7 +438,7 @@ public class PdbResearch {
}
}
- static private boolean childWalkSym(PdbApplicator applicator, int moduleNumber,
+ static private boolean childWalkSym(DefaultPdbApplicator applicator, int moduleNumber,
AbstractMsSymbolIterator iter) throws PdbException, CancelledException {
if (!iter.hasNext()) {
return false;
@@ -496,7 +496,7 @@ public class PdbResearch {
//==============================================================================================
//==============================================================================================
//==============================================================================================
- static void studyDataTypeConflicts(PdbApplicator applicator, TaskMonitor monitor)
+ static void studyDataTypeConflicts(DefaultPdbApplicator applicator, TaskMonitor monitor)
throws CancelledException {
DataTypeConflictHandler handler =
DataTypeConflictHandler.REPLACE_EMPTY_STRUCTS_OR_RENAME_AND_ADD_HANDLER;
@@ -616,7 +616,7 @@ public class PdbResearch {
* Studying names of functions where they might involve function definition
* reuse caused by Templates and/or Identical Code Folding.
*/
- static void studyAggregateSymbols(PdbApplicator applicator, TaskMonitor monitor)
+ static void studyAggregateSymbols(DefaultPdbApplicator applicator, TaskMonitor monitor)
throws CancelledException {
Map<Address, List<Stuff>> mapByAddress = new HashMap<>();
processPublicSymbols(applicator, mapByAddress, monitor);
@@ -625,7 +625,7 @@ public class PdbResearch {
dumpMap(mapByAddress);
}
- private static void processPublicSymbols(PdbApplicator applicator,
+ private static void processPublicSymbols(DefaultPdbApplicator applicator,
Map<Address, List<Stuff>> map, TaskMonitor monitor) throws CancelledException {
AbstractPdb pdb = applicator.getPdb();
@@ -660,7 +660,7 @@ public class PdbResearch {
}
}
- private static void processGlobalSymbols(PdbApplicator applicator,
+ private static void processGlobalSymbols(DefaultPdbApplicator applicator,
Map<Address, List<Stuff>> map, TaskMonitor monitor) throws CancelledException {
AbstractPdb pdb = applicator.getPdb();
@@ -694,7 +694,7 @@ public class PdbResearch {
}
}
- private static void processModuleSymbols(PdbApplicator applicator,
+ private static void processModuleSymbols(DefaultPdbApplicator applicator,
Map<Address, List<Stuff>> map, TaskMonitor monitor) throws CancelledException {
AbstractPdb pdb = applicator.getPdb();
PdbDebugInfo debugInfo = pdb.getDebugInfo();
@@ -712,8 +712,8 @@ public class PdbResearch {
}
totalCount += symbolGroup.size();
}
- applicator
- .setMonitorMessage("PDB: Applying " + totalCount + " module symbol components...");
+ applicator.setMonitorMessage(
+ "PDB: Applying " + totalCount + " module symbol components...");
monitor.initialize(totalCount);
// Process symbols list for each module
@@ -735,9 +735,9 @@ public class PdbResearch {
}
}
- private static void processSymbolGroup(PdbApplicator applicator, Map<Address, List<Stuff>> map,
- int moduleNumber, AbstractMsSymbolIterator iter, TaskMonitor monitor)
- throws CancelledException {
+ private static void processSymbolGroup(DefaultPdbApplicator applicator,
+ Map<Address, List<Stuff>> map, int moduleNumber, AbstractMsSymbolIterator iter,
+ TaskMonitor monitor) throws CancelledException {
iter.initGet();
while (iter.hasNext()) {
monitor.checkCanceled();
@@ -750,8 +750,8 @@ public class PdbResearch {
}
}
- private static void processPublicSymbol(PdbApplicator applicator, Map<Address, List<Stuff>> map,
- AbstractMsSymbol symbol) {
+ private static void processPublicSymbol(DefaultPdbApplicator applicator,
+ Map<Address, List<Stuff>> map, AbstractMsSymbol symbol) {
Stuff stuff;
if (!(symbol instanceof AbstractPublicMsSymbol)) {
return;
@@ -776,7 +776,7 @@ public class PdbResearch {
addStuff(map, address, stuff);
}
- private static void processProcedureSymbol(PdbApplicator applicator,
+ private static void processProcedureSymbol(DefaultPdbApplicator applicator,
Map<Address, List<Stuff>> map, AbstractMsSymbol symbol) {
if (symbol instanceof AbstractProcedureMsSymbol) {
String name = ((AbstractProcedureMsSymbol) symbol).getName();
@@ -900,8 +900,7 @@ public class PdbResearch {
// if count is zero for a definition, then, the field list record
// number refers to an actual field list.
// So... seems we can trust forward reference and ignore count.
- if (compType
- .getFieldDescriptorListRecordNumber() == RecordNumber.NO_TYPE) {
+ if (compType.getFieldDescriptorListRecordNumber() == RecordNumber.NO_TYPE) {
doNothingSetBreakPointHere();
}
}
@@ -946,8 +945,7 @@ public class PdbResearch {
// the field list record number refers to an actual field
// list. So... seems we can trust forward reference and
// ignore count.
- if (compType
- .getFieldDescriptorListRecordNumber() == RecordNumber.NO_TYPE) {
+ if (compType.getFieldDescriptorListRecordNumber() == RecordNumber.NO_TYPE) {
doNothingSetBreakPointHere();
}
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbVbtManager.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbVbtManager.java
index 6f04d45692..6b494d1485 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbVbtManager.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PdbVbtManager.java
@@ -38,7 +38,7 @@ public class PdbVbtManager extends VbtManager {
private Map<String, Address> addressByMangledName;
private Memory memory;
- private static Memory getMemory(PdbApplicator applicator) throws PdbException {
+ private static Memory getMemory(DefaultPdbApplicator applicator) throws PdbException {
Program program = applicator.getProgram();
if (program == null) {
throw new PdbException("Program null for VbtManager");
@@ -49,7 +49,7 @@ public class PdbVbtManager extends VbtManager {
// TODO: Research whether we ever find VBT symbols put into the program by the "loader."
// If we find some this way, then need to modify PdbVbtManager to also look
// through the loader symbol for them.
- private static Map<String, Address> findVirtualBaseTableSymbols(PdbApplicator applicator)
+ private static Map<String, Address> findVirtualBaseTableSymbols(DefaultPdbApplicator applicator)
throws CancelledException {
TaskMonitor monitor = applicator.getMonitor();
@@ -96,11 +96,11 @@ public class PdbVbtManager extends VbtManager {
/**
* Virtual Base Table Lookup Manager
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @throws PdbException If Program is null;
* @throws CancelledException upon user cancellation
*/
- PdbVbtManager(PdbApplicator applicator) throws PdbException, CancelledException {
+ PdbVbtManager(DefaultPdbApplicator applicator) throws PdbException, CancelledException {
this(applicator.getDataTypeManager(), getMemory(applicator),
findVirtualBaseTableSymbols(applicator));
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PeCoffGroupSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PeCoffGroupSymbolApplier.java
index 4e0f0bc21b..17362acd6f 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PeCoffGroupSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PeCoffGroupSymbolApplier.java
@@ -32,10 +32,11 @@ public class PeCoffGroupSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public PeCoffGroupSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public PeCoffGroupSymbolApplier(DefaultPdbApplicator applicator,
+ AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
if (!(abstractSymbol instanceof PeCoffGroupMsSymbol)) {
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PeCoffSectionSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PeCoffSectionSymbolApplier.java
index 31daaea5bf..3e37b0baf5 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PeCoffSectionSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PeCoffSectionSymbolApplier.java
@@ -31,10 +31,11 @@ public class PeCoffSectionSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public PeCoffSectionSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public PeCoffSectionSymbolApplier(DefaultPdbApplicator applicator,
+ AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
if (!(abstractSymbol instanceof PeCoffSectionMsSymbol)) {
@@ -52,8 +53,11 @@ public class PeCoffSectionSymbolApplier extends MsSymbolApplier {
symbol.getCharacteristics();
symbol.getAlign();
symbol.getName();
- applicator.putRealAddressesBySection(sectionNum, realAddress);
- applicator.addMemorySectionRefinement(symbol);
+ // 20220712: The gathering of these and other Linker symbols has been moved to a special
+ // PdbApplicator method.
+ // We need to revisit what work we would like done here (and in PeCoffGroupSymbolApplier).
+// applicator.putRealAddressesBySection(sectionNum, realAddress);
+// applicator.addMemorySectionRefinement(symbol);
}
@Override
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PointerTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PointerTypeApplier.java
index d82b377af7..81c35c39ac 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PointerTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PointerTypeApplier.java
@@ -33,11 +33,11 @@ public class PointerTypeApplier extends MsTypeApplier {
/**
* Constructor for pointer type applier, for transforming a enum into a
* Ghidra DataType.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractPointerMsType} to process
* @throws IllegalArgumentException Upon invalid arguments.
*/
- public PointerTypeApplier(PdbApplicator applicator, AbstractPointerMsType msType)
+ public PointerTypeApplier(DefaultPdbApplicator applicator, AbstractPointerMsType msType)
throws IllegalArgumentException {
super(applicator, msType);
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PrimitiveTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PrimitiveTypeApplier.java
index 2deab63405..9dd295225c 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PrimitiveTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PrimitiveTypeApplier.java
@@ -28,10 +28,10 @@ public class PrimitiveTypeApplier extends MsTypeApplier {
/**
* Constructor for primitive type applier, for transforming a primitive into a
* Ghidra DataType.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link PrimitiveMsType} to process.
*/
- public PrimitiveTypeApplier(PdbApplicator applicator, PrimitiveMsType msType) {
+ public PrimitiveTypeApplier(DefaultPdbApplicator applicator, PrimitiveMsType msType) {
super(applicator, msType);
apply(); // Only apply in constructor for primitives
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ProcedureTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ProcedureTypeApplier.java
index c21e51b9d8..dc72477dc8 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ProcedureTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ProcedureTypeApplier.java
@@ -32,11 +32,11 @@ public class ProcedureTypeApplier extends AbstractFunctionTypeApplier {
/**
* Constructor for the applicator that applies {@link AbstractProcedureMsType},
* transforming it into a Ghidra {@link DataType}.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractProcedureMsType} to processes.
* @throws IllegalArgumentException Upon invalid arguments.
*/
- public ProcedureTypeApplier(PdbApplicator applicator, AbstractProcedureMsType msType)
+ public ProcedureTypeApplier(DefaultPdbApplicator applicator, AbstractProcedureMsType msType)
throws IllegalArgumentException {
super(applicator, msType);
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PublicSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PublicSymbolApplier.java
index 0a7f236fed..4c2e6d7bdd 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PublicSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/PublicSymbolApplier.java
@@ -40,10 +40,10 @@ public class PublicSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public PublicSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public PublicSymbolApplier(DefaultPdbApplicator applicator, AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
if (!(abstractSymbol instanceof AbstractPublicMsSymbol)) {
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ReferenceSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ReferenceSymbolApplier.java
index 61511823ac..925fd708f2 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ReferenceSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/ReferenceSymbolApplier.java
@@ -31,10 +31,10 @@ public class ReferenceSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public ReferenceSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public ReferenceSymbolApplier(DefaultPdbApplicator applicator, AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
if (!(abstractSymbol instanceof AbstractReferenceMsSymbol)) {
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/RegisterRelativeSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/RegisterRelativeSymbolApplier.java
index 891216278d..fd3c00c169 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/RegisterRelativeSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/RegisterRelativeSymbolApplier.java
@@ -36,10 +36,11 @@ public class RegisterRelativeSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public RegisterRelativeSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public RegisterRelativeSymbolApplier(DefaultPdbApplicator applicator,
+ AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
if (!(abstractSymbol instanceof AbstractRegisterRelativeAddressMsSymbol)) {
@@ -104,8 +105,7 @@ public class RegisterRelativeSymbolApplier extends MsSymbolApplier {
// }
int offset = (int) (relativeOffset & 0xffffffffL);
- MsTypeApplier dataTypeApplier =
- applicator.getTypeApplier(symbol.getTypeRecordNumber());
+ MsTypeApplier dataTypeApplier = applicator.getTypeApplier(symbol.getTypeRecordNumber());
DataType dt = dataTypeApplier.getDataType();
if (dt != null) {
// Variable m16 = stackFrame.getVariableContaining(-16);
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/SeparatedCodeSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/SeparatedCodeSymbolApplier.java
index 50a7d84978..e80cf0c6f9 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/SeparatedCodeSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/SeparatedCodeSymbolApplier.java
@@ -28,7 +28,7 @@ import ghidra.util.Msg;
import ghidra.util.exception.CancelledException;
/**
- * Applier for {@link SeparatedCodeFromCompilerSupportMsSymbol} symbol.
+ * Applier for {@link SeparatedCodeFromCompilerSupportMsSymbol} symbol.
*/
// TODO: Need to evaluate relationship to function symbols.
// TODO: Need to create anonymous name for this as a function?
@@ -55,12 +55,12 @@ public class SeparatedCodeSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
* @throws CancelledException upon user cancellation
*/
- public SeparatedCodeSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter)
- throws CancelledException {
+ public SeparatedCodeSymbolApplier(DefaultPdbApplicator applicator,
+ AbstractMsSymbolIterator iter) throws CancelledException {
super(applicator, validateSymbol(iter));
symbol = (SeparatedCodeFromCompilerSupportMsSymbol) iter.next();
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/SymbolApplierFactory.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/SymbolApplierFactory.java
index dc5ee2e7d1..3d28a0604e 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/SymbolApplierFactory.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/SymbolApplierFactory.java
@@ -25,9 +25,9 @@ import ghidra.util.exception.CancelledException;
*/
public class SymbolApplierFactory {
- private PdbApplicator applicator;
+ private DefaultPdbApplicator applicator;
- SymbolApplierFactory(PdbApplicator applicator) {
+ SymbolApplierFactory(DefaultPdbApplicator applicator) {
this.applicator = applicator;
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/TrampolineSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/TrampolineSymbolApplier.java
index a5871b6c9d..f2df0a04c1 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/TrampolineSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/TrampolineSymbolApplier.java
@@ -36,10 +36,10 @@ public class TrampolineSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public TrampolineSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public TrampolineSymbolApplier(DefaultPdbApplicator applicator, AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
if (!(abstractSymbol instanceof TrampolineMsSymbol)) {
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/TypeApplierFactory.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/TypeApplierFactory.java
index b5d499f45e..e9a3ad40d4 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/TypeApplierFactory.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/TypeApplierFactory.java
@@ -29,10 +29,10 @@ import ghidra.app.util.bin.format.pdb2.pdbreader.type.*;
*/
public class TypeApplierFactory {
- private PdbApplicator applicator;
+ private DefaultPdbApplicator applicator;
private Map<RecordNumber, MsTypeApplier> appliersByRecordNumber;
- TypeApplierFactory(PdbApplicator applicator) {
+ TypeApplierFactory(DefaultPdbApplicator applicator) {
this.applicator = applicator;
appliersByRecordNumber = new HashMap<>();
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/TypedefSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/TypedefSymbolApplier.java
index 91b79724f6..877766f9cb 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/TypedefSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/TypedefSymbolApplier.java
@@ -35,10 +35,10 @@ public class TypedefSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public TypedefSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public TypedefSymbolApplier(DefaultPdbApplicator applicator, AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
if (!(abstractSymbol instanceof AbstractUserDefinedTypeMsSymbol)) {
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/UdtSourceLineTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/UdtSourceLineTypeApplier.java
index 14ef2af0f5..6671dd59bb 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/UdtSourceLineTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/UdtSourceLineTypeApplier.java
@@ -30,12 +30,12 @@ public class UdtSourceLineTypeApplier extends MsTypeApplier {
/**
* Constructor for base class applier.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link AbstractBaseClassMsType}, {@link AbstractVirtualBaseClassMsType}, or
* {@link AbstractIndirectVirtualBaseClassMsType} to processes.
* @throws IllegalArgumentException Upon invalid arguments.
*/
- public UdtSourceLineTypeApplier(PdbApplicator applicator, AbstractMsType msType)
+ public UdtSourceLineTypeApplier(DefaultPdbApplicator applicator, AbstractMsType msType)
throws IllegalArgumentException {
super(applicator, validateType(msType));
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/VirtualFunctionTablePointerTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/VirtualFunctionTablePointerTypeApplier.java
index cfcfab7680..e4b851e67a 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/VirtualFunctionTablePointerTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/VirtualFunctionTablePointerTypeApplier.java
@@ -32,13 +32,13 @@ public class VirtualFunctionTablePointerTypeApplier extends MsTypeApplier {
/**
* Constructor for enum type applier, for transforming a enum into a
* Ghidra DataType.
- * @param applicator {@link PdbApplicator} for which this class is working.
- * @param msType {@link AbstractVirtualFunctionTablePointerMsType} or
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
+ * @param msType {@link AbstractVirtualFunctionTablePointerMsType} or
* {@link AbstractVirtualFunctionTablePointerWithOffsetMsType} to process.
* @throws IllegalArgumentException Upon invalid arguments.
*/
- public VirtualFunctionTablePointerTypeApplier(PdbApplicator applicator, AbstractMsType msType)
- throws IllegalArgumentException {
+ public VirtualFunctionTablePointerTypeApplier(DefaultPdbApplicator applicator,
+ AbstractMsType msType) throws IllegalArgumentException {
super(applicator, validateType(msType));
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/VtShapeTypeApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/VtShapeTypeApplier.java
index b85b472540..4ae42c1a87 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/VtShapeTypeApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/VtShapeTypeApplier.java
@@ -34,10 +34,10 @@ public class VtShapeTypeApplier extends MsTypeApplier {
/**
* Constructor for vtshape type applier.
- * @param applicator {@link PdbApplicator} for which this class is working.
+ * @param applicator {@link DefaultPdbApplicator} for which this class is working.
* @param msType {@link VtShapeMsType} to process.
*/
- public VtShapeTypeApplier(PdbApplicator applicator, VtShapeMsType msType) {
+ public VtShapeTypeApplier(DefaultPdbApplicator applicator, VtShapeMsType msType) {
super(applicator, msType);
}
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/WithSymbolApplier.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/WithSymbolApplier.java
index 524fc8e150..9e8ea4885d 100644
--- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/WithSymbolApplier.java
+++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/WithSymbolApplier.java
@@ -34,10 +34,10 @@ public class WithSymbolApplier extends MsSymbolApplier {
/**
* Constructor
- * @param applicator the {@link PdbApplicator} for which we are working.
+ * @param applicator the {@link DefaultPdbApplicator} for which we are working.
* @param iter the Iterator containing the symbol sequence being processed
*/
- public WithSymbolApplier(PdbApplicator applicator, AbstractMsSymbolIterator iter) {
+ public WithSymbolApplier(DefaultPdbApplicator applicator, AbstractMsSymbolIterator iter) {
super(applicator, iter);
AbstractMsSymbol abstractSymbol = iter.next();
if (!(abstractSymbol instanceof AbstractWithMsSymbol)) {
diff --git a/Ghidra/Features/PDB/src/main/java/pdb/LoadPdbTask.java b/Ghidra/Features/PDB/src/main/java/pdb/LoadPdbTask.java
index 9d6fd80aa3..a94b88b0c4 100644
--- a/Ghidra/Features/PDB/src/main/java/pdb/LoadPdbTask.java
+++ b/Ghidra/Features/PDB/src/main/java/pdb/LoadPdbTask.java
@@ -145,7 +145,8 @@ class LoadPdbTask extends Task {
pdbFile.getAbsolutePath(), pdbReaderOptions, monitor)) {
monitor.setMessage("PDB: Parsing " + pdbFile + "...");
pdb.deserialize(monitor);
- PdbApplicator applicator = new PdbApplicator(pdbFile.getAbsolutePath(), pdb);
+ DefaultPdbApplicator applicator =
+ new DefaultPdbApplicator(pdbFile.getAbsolutePath(), pdb);
applicator.applyTo(program, program.getDataTypeManager(), program.getImageBase(),
pdbApplicatorOptions, monitor, log);
diff --git a/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDebugData.java b/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDebugData.java
new file mode 100644
index 0000000000..b1940ac0f7
--- /dev/null
+++ b/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDebugData.java
@@ -0,0 +1,97 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.pdb2.pdbreader;
+
+import java.util.List;
+import java.util.SortedMap;
+
+/**
+ * This class is an extension of {@link DebugData}. The purpose of this class is to allow for
+ * testing of internal components of {@link AbstractPdb} and external classes that use them.
+ * It is not part of the production PDB Reader.
+ */
+public class DummyDebugData extends DebugData {
+
+ // Private set of these (different from parent class)
+ private SortedMap<Long, Long> omapFromSource;
+ private List<ImageSectionHeader> imageSectionHeaders;
+ private List<ImageSectionHeader> imageSectionHeadersOrig;
+
+ /**
+ * IMPORTANT: This method is for testing only. It allows us to set a basic object.
+ * Note: not all values are initialized.
+ * @param pdb The AbstractPdb foundation for the {@link PdbOldDebugInfo}.
+ */
+ DummyDebugData(AbstractPdb pdb) {
+ super(pdb);
+ }
+
+ //==============================================================================================
+ /**
+ * Returns the OMAP_FROM_SOURCE mapping of RVA to RVA
+ * @return the omapFromSource or null if does not exist.
+ */
+ @Override
+ public SortedMap<Long, Long> getOmapFromSource() {
+ return omapFromSource;
+ }
+
+ /**
+ * Returns the {@link List}&lt;{@link ImageSectionHeader}&gt;.
+ * @return the imageSectionHeaders or null if does not exist.
+ */
+ @Override
+ public List<ImageSectionHeader> getImageSectionHeaders() {
+ return imageSectionHeaders;
+ }
+
+ /**
+ * Returns the {@link List}&lt;{@link ImageSectionHeader}&gt;.
+ * When this return a non-null list the OMAP_FROM_SRC should be
+ * used for remapping global symbols.
+ * @return the imageSectionHeadersOrig or null if does not exist.
+ */
+ @Override
+ public List<ImageSectionHeader> getImageSectionHeadersOrig() {
+ return imageSectionHeadersOrig;
+ }
+
+ //==============================================================================================
+ /**
+ * Sets the OMAP_FROM_SOURCE mapping of RVA to RVA
+ * @param omapFromSource the OMAP_FROM_SOURCE map
+ */
+ public void setOmapFromSource(SortedMap<Long, Long> omapFromSource) {
+ this.omapFromSource = omapFromSource;
+ }
+
+ /**
+ * Sets the {@link ImageSectionHeader} list
+ * @param imageSectionHeaders {@link ImageSectionHeader} list
+ */
+ public void setImageSectionHeaders(List<ImageSectionHeader> imageSectionHeaders) {
+ this.imageSectionHeaders = imageSectionHeaders;
+ }
+
+ /**
+ * Sets the {@link ImageSectionHeader} original list
+ * @param imageSectionHeadersOrig {@link ImageSectionHeader} list
+ */
+ public void setImageSectionHeadersOrig(List<ImageSectionHeader> imageSectionHeadersOrig) {
+ this.imageSectionHeadersOrig = imageSectionHeadersOrig;
+ }
+
+}
diff --git a/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDatabaseInterface.java b/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDebugInfo.java
similarity index 84%
rename from Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDatabaseInterface.java
rename to Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDebugInfo.java
index c67d3d15e0..b78062becf 100644
--- a/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDatabaseInterface.java
+++ b/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDebugInfo.java
@@ -15,23 +15,28 @@
*/
package ghidra.app.util.bin.format.pdb2.pdbreader;
+import java.util.List;
+
/**
* This class is an extension of {@link PdbOldDebugInfo}, whose sole purpose
* is to allow for testing of internal components of {@link AbstractPdb} classes. It is not
* part of the production PDB Reader.
*/
-class DummyDebugInfo extends PdbOldDebugInfo {
+public class DummyDebugInfo extends PdbOldDebugInfo {
//==============================================================================================
// Package-Protected Internals
//==============================================================================================
/**
* IMPORTANT: This method is for testing only. It allows us to set a basic object.
- * Note: not all values are initialized.
+ * Note: not all values are initialized.
* @param pdb The AbstractPdb foundation for the {@link PdbOldDebugInfo}.
*/
DummyDebugInfo(AbstractPdb pdb) {
super(pdb, 0);
}
+ public void setSegmentMapList(List<SegmentMapDescription> segmentMapList) {
+ this.segmentMapList = segmentMapList;
+ }
}
diff --git a/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDatabaseInterfaceNew.java b/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDebugInfoNew.java
similarity index 82%
rename from Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDatabaseInterfaceNew.java
rename to Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDebugInfoNew.java
index 7ce11c1397..201884934d 100644
--- a/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDatabaseInterfaceNew.java
+++ b/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyDebugInfoNew.java
@@ -15,23 +15,29 @@
*/
package ghidra.app.util.bin.format.pdb2.pdbreader;
+import java.util.List;
+
/**
* This class is an extension of {@link PdbNewDebugInfo}, whose sole purpose
* is to allow for testing of internal components of {@link AbstractPdb} classes. It is not
* part of the production PDB Reader.
*/
-class DummyDebugInfoNew extends PdbNewDebugInfo {
+public class DummyDebugInfoNew extends PdbNewDebugInfo {
//==============================================================================================
// Package-Protected Internals
//==============================================================================================
/**
* IMPORTANT: This method is for testing only. It allows us to set a basic object.
- * Note: not all values are initialized.
+ * Note: not all values are initialized.
* @param pdb The AbstractPdb foundation for the {@link PdbNewDebugInfo}.
*/
DummyDebugInfoNew(AbstractPdb pdb) {
super(pdb, -1);
+ debugData = new DummyDebugData(pdb);
}
+ public void setSegmentMapList(List<SegmentMapDescription> segmentMapList) {
+ this.segmentMapList = segmentMapList;
+ }
}
diff --git a/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyPdb700.java b/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyPdb700.java
index 83c179aee6..30aed7986c 100644
--- a/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyPdb700.java
+++ b/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/DummyPdb700.java
@@ -26,6 +26,8 @@ import ghidra.app.util.bin.format.pdb2.pdbreader.type.AbstractMsType;
*/
public class DummyPdb700 extends Pdb700 {
+ private boolean debugInfoAvailable = true;
+
//==============================================================================================
// API
//==============================================================================================
@@ -55,6 +57,20 @@ public class DummyPdb700 extends Pdb700 {
nameTable.forTestingOnlyAddOffsetNamePair(1, "NameTableTestString");
}
+ /**
+ * Set true to make existing debug information available; when set false {@link #getDebugInfo()}
+ * returns null (as though it does not exist)
+ * @param setAvailable true to return actual value; false to have it return null
+ */
+ public void setDebugInfoAvailable(boolean setAvailable) {
+ debugInfoAvailable = setAvailable;
+ }
+
+ @Override
+ public PdbDebugInfo getDebugInfo() {
+ return debugInfoAvailable ? debugInfo : null;
+ }
+
/**
* IMPORTANT: This method is for testing only. It allows us to set a "type" record for a
* particular record number.
diff --git a/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/PdbTestUtils.java b/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/PdbTestUtils.java
new file mode 100644
index 0000000000..4edee9b899
--- /dev/null
+++ b/Ghidra/Features/PDB/src/test/java/ghidra/app/util/bin/format/pdb2/pdbreader/PdbTestUtils.java
@@ -0,0 +1,371 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.pdb2.pdbreader;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import ghidra.app.util.bin.format.pdb2.pdbreader.symbol.*;
+
+/**
+ * Utilities in support of testing PdbReader and PdbApplicator.
+ *
+ */
+public class PdbTestUtils {
+
+ /**
+ * Creates an {@link ImageSectionHeader} from parameters. Non-listed parameters are set to zero
+ * @param pdb PDB that the ImageSectionHeader belongs to
+ * @param name of the section (must be 7 characters or less)
+ * @param virtualAddress DWORD (unsigned 32-bit) virtual address passed in as a long
+ * @param rawDataSize DWORD (unsigned 32-bit) data size passed in as a long
+ * @return the initialized ImageSectionHeader
+ */
+ public static ImageSectionHeader createImageSectionHeader(AbstractPdb pdb, String name,
+ long virtualAddress, long rawDataSize) {
+ return createImageSectionHeader(pdb, name, 0L, virtualAddress, rawDataSize, 0L, 0L, 0L, 0,
+ 0, 0L);
+ }
+
+ /**
+ * Creates an {@link ImageSectionHeader} from parameters
+ * @param pdb PDB that the ImageSectionHeader belongs to
+ * @param name of the section (must be 7 characters or less)
+ * @param unionPAVS a unionPAVS value
+ * @param virtualAddress DWORD (unsigned 32-bit) virtual address passed in as a long
+ * @param rawDataSize DWORD (unsigned 32-bit) data size passed in as a long
+ * @param rawDataPointer DWORD (unsigned 32-bit) data pointer passed in as a long
+ * @param relocationsPointer DWORD (unsigned 32-bit) relocation pointer passed in as a long
+ * @param lineNumbersPointer DWORD (unsigned 32-bit) line numbers pointer passed in as a long
+ * @param numRelocations WORD (unsigned 16-bit) number of relocations passed in as an int
+ * @param numLineNumbers WORD (unsigned 16-bit) num line numbers passed in as an int
+ * @param characteristics DWORD (unsigned 32-bit) characteristics passed in as a long
+ * @return initialized ImageSectionHeader
+ */
+ public static ImageSectionHeader createImageSectionHeader(AbstractPdb pdb, String name,
+ long unionPAVS, long virtualAddress, long rawDataSize, long rawDataPointer,
+ long relocationsPointer, long lineNumbersPointer, int numRelocations,
+ int numLineNumbers, long characteristics) {
+
+ int len = name.length();
+ if (len > 7) {
+ fail("ImageSectionHeader name to long for creation");
+ }
+
+ PdbByteWriter writer = new PdbByteWriter();
+ writer.putNullTerminatedString(name);
+ if (len < 7) {
+ byte[] pad = new byte[7 - len];
+ while (len < 7) {
+ pad[6 - len++] = 0;
+ }
+ writer.putBytes(pad);
+ }
+
+ writer.putUnsignedInt(unionPAVS);
+ writer.putUnsignedInt(virtualAddress);
+ writer.putUnsignedInt(rawDataSize);
+ writer.putUnsignedInt(rawDataPointer);
+ writer.putUnsignedInt(relocationsPointer);
+ writer.putUnsignedInt(lineNumbersPointer);
+ writer.putUnsignedShort(numRelocations);
+ writer.putUnsignedShort(numLineNumbers);
+ writer.putUnsignedInt(characteristics);
+
+ ImageSectionHeader header = new ImageSectionHeader(pdb);
+ PdbByteReader reader = new PdbByteReader(writer.get());
+ try {
+ header.parse(reader);
+ }
+ catch (PdbException e) {
+ e.printStackTrace();
+ fail("Failed to initialize ImageSectionHeader during parse");
+ }
+
+ // Sanity check by reading values back out.
+ assertEquals(name, header.getName());
+ assertEquals(unionPAVS, header.getUnionPAVS());
+ assertEquals(virtualAddress, header.getVirtualAddress());
+ assertEquals(rawDataSize, header.getRawDataSize());
+ assertEquals(rawDataPointer, header.getRawDataPointer());
+ assertEquals(relocationsPointer, header.getRelocationsPointer());
+ assertEquals(lineNumbersPointer, header.getLineNumbersPointer());
+ assertEquals(numRelocations, header.getNumRelocations());
+ assertEquals(numLineNumbers, header.getNumLineNumbers());
+ assertEquals(characteristics, header.getCharacteristics());
+
+ return header;
+ }
+
+ /**
+ * Create an {@link SegmentMapDescription} from parameters. Non-listed parameters are set to
+ * zero or similar values
+ * @param pdb PDB that the SegmentMapDescription belongs to
+ * @param segOffset DWORD (unsigned 32-bit) segment offset passed in as an long
+ * @param segLength DWORD (unsigned 32-bit) segment length passed in as an long
+ * @return initialized SegmentMapDescription
+ */
+ public static SegmentMapDescription createSegmentMapDescription(AbstractPdb pdb, long segOffset,
+ long segLength) {
+ return createSegmentMapDescription(pdb, 0, 0, 0, 0, 0xffff, 0xffff, segOffset, segLength);
+ }
+
+ /**
+ * Creates an {@link SegmentMapDescription} from parameters
+ * @param pdb PDB that the SegmentMapDescription belongs to
+ * @param flags WORD (unsigned 16-bit) flags passed in as an int
+ * @param ovl WORD (unsigned 16-bit) ovl passed in as an int
+ * @param group WORD (unsigned 16-bit) group passed in as an int
+ * @param frame WORD (unsigned 16-bit) frame passed in as an int
+ * @param segNameIndex WORD (unsigned 16-bit) segment name index passed in as an int
+ * @param classNameIndex WORD (unsigned 16-bit) class name index passed in as an int
+ * @param segOffset DWORD (unsigned 32-bit) segment offset passed in as an long
+ * @param segLength DWORD (unsigned 32-bit) segment length passed in as an long
+ * @return initialized SegmentMapDescription
+ */
+ public static SegmentMapDescription createSegmentMapDescription(AbstractPdb pdb, int flags,
+ int ovl, int group, int frame, int segNameIndex, int classNameIndex, long segOffset,
+ long segLength) {
+
+ PdbByteWriter writer = new PdbByteWriter();
+
+ writer.putUnsignedShort(flags);
+ writer.putUnsignedShort(ovl);
+ writer.putUnsignedShort(group);
+ writer.putUnsignedShort(frame);
+ writer.putUnsignedShort(segNameIndex);
+ writer.putUnsignedShort(classNameIndex);
+ writer.putUnsignedInt(segOffset);
+ writer.putUnsignedInt(segLength);
+
+ SegmentMapDescription segmentMapDescription = new SegmentMapDescription();
+ PdbByteReader reader = new PdbByteReader(writer.get());
+ try {
+ segmentMapDescription.deserialize(reader);
+ }
+ catch (PdbException e) {
+ e.printStackTrace();
+ fail("Failed to initialize SegmentMapDescription during parse");
+ }
+
+ assertEquals(flags, segmentMapDescription.getFlags());
+ assertEquals(ovl, segmentMapDescription.getOvl());
+ assertEquals(group, segmentMapDescription.getGroup());
+ assertEquals(frame, segmentMapDescription.getFrame());
+ assertEquals(segNameIndex, segmentMapDescription.getSegNameIndex());
+ assertEquals(classNameIndex, segmentMapDescription.getClassNameIndex());
+ assertEquals(segOffset, segmentMapDescription.getSegmentOffset());
+ assertEquals(segLength, segmentMapDescription.getLength());
+
+ return segmentMapDescription;
+ }
+
+ /**
+ * Creates an {@link PeCoffSectionMsSymbol} from parameters. Non-listed parameters are set to
+ * zero or similar values
+ * @param pdb PDB that the PeCoffSectionMsSymbol belongs to
+ * @param sectionNumber WORD (unsigned 16-bit) segment name index passed in as an int
+ * @param rva relative virtual address of the section (DWORD (unsigned 32-bit)) so pass
+ * appropriate negative value that has same bytes as what would be the unsigned bytes)
+ * @param length the length of the section (DWORD (unsigned 32-bit)) so pass appropriate
+ * negative value that has same bytes as what would be the unsigned bytes)
+ * @param name name of the section (believe UTF8 is charset)
+ * @return initialized PeCoffSectionMsSymbol
+ */
+ public static PeCoffSectionMsSymbol createPeCoffSectionMsSymbol(AbstractPdb pdb,
+ int sectionNumber, int rva, int length, String name) {
+ return createPeCoffSectionMsSymbol(pdb, sectionNumber, 0, 0, rva, length, 0, name);
+ }
+
+ // Taken from SymbolsTest.testPeCoffSectionMsSymbol().
+ // Envisioning future of moving this and all other "writer" mechanisms used in tests (symbols,
+ // data types, etc) into additional utility classes. Might then rename this containing class
+ // (PdbTestUtils) to something more specific to the classes it helps with testing.
+ // ALTERNATIVELY, We could modify target classes to have "write" capability, writing back
+ // to a PdbByteWriter; move PdbByteWriter from test packages to reader packages and actually
+ // rename from PdbReader some PdbReaderWriter or something more simple. If we do this, then
+ // we also need to deal with the try/catch exception differently.
+ // Note that we would also have to decide where the PDB_ID is written. Might be in an outer
+ // method, but our other tests that call into the big switch parser are putting the value.
+ // This is: writer.putUnsignedShort(PeCoffSectionMsSymbol.PDB_ID);
+
+ /**
+ * Creates an {@link PeCoffSectionMsSymbol} from parameters
+ * @param pdb PDB that the PeCoffSectionMsSymbol belongs to
+ * @param sectionNumber WORD (unsigned 16-bit) segment name index passed in as an int
+ * @param align BYTE (unsigned 8-bit) segment name index passed in as a short
+ * @param reserved BYTE (unsigned 8-bit) segment name index passed in as a short
+ * @param rva relative virtual address of the section (DWORD (unsigned 32-bit)) so pass
+ * appropriate negative value that has same bytes as what would be the unsigned bytes)
+ * @param length the length of the section (DWORD (unsigned 32-bit)) so pass appropriate
+ * negative value that has same bytes as what would be the unsigned bytes)
+ * @param characteristics the characteristics of the section (DWORD (unsigned 32-bit)) so pass
+ * appropriate negative value that has same bytes as what would be the unsigned bytes)
+ * @param name name of the section (believe UTF8 is charset)
+ * @return initialized PeCoffSectionMsSymbol
+ */
+ public static PeCoffSectionMsSymbol createPeCoffSectionMsSymbol(AbstractPdb pdb,
+ int sectionNumber, int align, int reserved, int rva, int length, int characteristics,
+ String name) {
+
+ assertEquals(reserved, 0); // Must be zero
+
+ PdbByteWriter writer = new PdbByteWriter();
+
+ writer.putUnsignedShort(sectionNumber);
+ writer.putUnsignedByte(align);
+ writer.putUnsignedByte(reserved);
+ writer.putUnsignedInt(rva);
+ writer.putUnsignedInt(length);
+ writer.putUnsignedInt(characteristics);
+ writer.putNullTerminatedUtf8String(name);
+ writer.putAlign(0);
+
+ PdbByteReader reader = new PdbByteReader(writer.get());
+ PeCoffSectionMsSymbol peCoffSectionMsSymbol = null;
+ try {
+ peCoffSectionMsSymbol = new PeCoffSectionMsSymbol(pdb, reader);
+ }
+ catch (PdbException e) {
+ e.printStackTrace();
+ fail("Failed to construct PeCoffSectionMsSymbol");
+ }
+
+ assertEquals(reader.getLimit(), writer.getSize()); // assuring properly putAlign() argument
+
+ assertEquals(sectionNumber, peCoffSectionMsSymbol.getSectionNumber());
+ assertEquals(align, peCoffSectionMsSymbol.getAlign());
+ assertEquals(reserved, peCoffSectionMsSymbol.getReserved());
+ assertEquals(rva, peCoffSectionMsSymbol.getRva());
+ assertEquals(length, peCoffSectionMsSymbol.getLength());
+ assertEquals(characteristics, peCoffSectionMsSymbol.getCharacteristics());
+ assertEquals(name, peCoffSectionMsSymbol.getName());
+
+ return peCoffSectionMsSymbol;
+ }
+
+ /**
+ * Packs an unsigned int (java long) with values from the parameters here.
+ * @param language the language
+ * @param compiledForEditAndContinue true if compiled fro edit-and-continue
+ * @param notCompiledWithDebugInfo true if <b>not</b> compiled with debug info
+ * @param compiledWithLinkTimeCodeGeneration true if compiled with link-time code generation
+ * @param compiledWithBzalignNoDataAlign tru if compiled with BS align no data align
+ * @param managedCodeDataPresent tru if managed code data is present
+ * @param compiledWithGsBufferSecurityChecks true if compiled with GS Buffer security checks
+ * @param compiledWithHotPatch true if compiled with ability to hot-patch
+ * @param convertedWithCvtcil true if converted from (.NET IL) Common Intermediate Language Module
+ * @param microsoftIntermediateLanguageNetModule true if MSFT intermediate language net module
+ * @param compiledWithSdl true if compiledwith SDL
+ * @param compiledWithLtcgPgoOrPgu true if compiled with light PGO or PGU
+ * @param dotExpModule true if dot exp module
+ * @return the flags packed into single integral form/value
+ */
+ public long buildCompile3MsSymbolFlags(LanguageName language,
+ boolean compiledForEditAndContinue, boolean notCompiledWithDebugInfo,
+ boolean compiledWithLinkTimeCodeGeneration, boolean compiledWithBzalignNoDataAlign,
+ boolean managedCodeDataPresent, boolean compiledWithGsBufferSecurityChecks,
+ boolean compiledWithHotPatch, boolean convertedWithCvtcil,
+ boolean microsoftIntermediateLanguageNetModule, boolean compiledWithSdl,
+ boolean compiledWithLtcgPgoOrPgu, boolean dotExpModule) {
+ return 0L;
+ }
+
+ /**
+ * Creates an {@link Compile3MsSymbol} from parameters. Non-listed parameters are set to
+ * zero or similar values
+ * @param pdb PDB that the Compile3MsSymbol belongs to
+ * @param compilerVersionString the compiler version string
+ * @return initialized Compile3MsSymbol
+ */
+ public static Compile3MsSymbol createCompile3MsSymbol(AbstractPdb pdb,
+ String compilerVersionString) {
+ return createCompile3MsSymbol(pdb, 0L, Processor.X64_AMD64, 0, 0, 0, 0, 0, 0, 0, 0,
+ compilerVersionString);
+ }
+
+ /**
+ * Creates an {@link Compile3MsSymbol} from parameters
+ * @param pdb PDB that the Compile3MsSymbol belongs to
+ * @param flags the packed flags (see buildCompile3MsSymbolFlags) unsigned int stored in long
+ * @param processor the processor value
+ * @param frontEndMajorVersionNumber the front end major version number
+ * @param frontEndMinorVersionNumber the front end minor version number
+ * @param frontEndBuildVersionNumber the front end build version number
+ * @param frontEndQuickFixEngineeringVersionNumber the front end quick-fix version number
+ * @param backEndMajorVersionNumber the back end major version number
+ * @param backEndMinorVersionNumber the back end minor version number
+ * @param backEndBuildVersionNumber the back end build version number
+ * @param backEndQuickFixEngineeringVersionNumber the back end quick-fix version number
+ * @param compilerVersionString the compiler version string
+ * @return initialized Compile3MsSymbol
+ */
+ public static Compile3MsSymbol createCompile3MsSymbol(AbstractPdb pdb, long flags,
+ Processor processor, int frontEndMajorVersionNumber, int frontEndMinorVersionNumber,
+ int frontEndBuildVersionNumber, int frontEndQuickFixEngineeringVersionNumber,
+ int backEndMajorVersionNumber, int backEndMinorVersionNumber,
+ int backEndBuildVersionNumber, int backEndQuickFixEngineeringVersionNumber,
+ String compilerVersionString) {
+
+ PdbByteWriter writer = new PdbByteWriter();
+
+ writer.putUnsignedInt(flags);
+ writer.putUnsignedShort(processor.getValue());
+ writer.putUnsignedShort(frontEndMajorVersionNumber);
+ writer.putUnsignedShort(frontEndMinorVersionNumber);
+ writer.putUnsignedShort(frontEndBuildVersionNumber);
+ writer.putUnsignedShort(frontEndQuickFixEngineeringVersionNumber);
+ writer.putUnsignedShort(backEndMajorVersionNumber);
+ writer.putUnsignedShort(backEndMinorVersionNumber);
+ writer.putUnsignedShort(backEndBuildVersionNumber);
+ writer.putUnsignedShort(backEndQuickFixEngineeringVersionNumber);
+ writer.putNullTerminatedUtf8String(compilerVersionString);
+
+ PdbByteReader reader = new PdbByteReader(writer.get());
+
+ Compile3MsSymbol compile3MsSymbol = null;
+ try {
+ compile3MsSymbol = new Compile3MsSymbol(pdb, reader);
+ }
+ catch (PdbException e) {
+ e.printStackTrace();
+ fail("Failed to construct Compile3MsSymbol");
+ }
+
+ assertEquals(reader.getLimit(), writer.getSize());
+
+ assertEquals(flags, compile3MsSymbol.getFlags());
+ assertEquals(frontEndMajorVersionNumber, compile3MsSymbol.getFrontEndMajorVersionNumber());
+ assertEquals(frontEndMinorVersionNumber, compile3MsSymbol.getFrontEndMinorVersionNumber());
+ assertEquals(frontEndBuildVersionNumber, compile3MsSymbol.getFrontEndBuildVersionNumber());
+ assertEquals(frontEndQuickFixEngineeringVersionNumber,
+ compile3MsSymbol.getFrontEndQuickFixEngineeringVersionNumber());
+ assertEquals(backEndMajorVersionNumber, compile3MsSymbol.getBackEndMajorVersionNumber());
+ assertEquals(backEndMinorVersionNumber, compile3MsSymbol.getBackEndMinorVersionNumber());
+ assertEquals(backEndBuildVersionNumber, compile3MsSymbol.getBackEndBuildVersionNumber());
+ assertEquals(backEndQuickFixEngineeringVersionNumber,
+ compile3MsSymbol.getBackEndQuickFixEngineeringVersionNumber());
+ assertEquals(compilerVersionString, compile3MsSymbol.getCompilerVersionString());
+
+ // Very important: Store target machine information. It is used elsewhere, including
+ // in RegisterName. I think it is just as important here, but maybe should allow
+ // reader to set the value, but for testing, that part of the code might not be activated,
+ // as we might only be testing small portions of the reader
+ pdb.setTargetProcessor(processor);
+
+ return compile3MsSymbol;
+ }
+}
diff --git a/Ghidra/Features/PDB/src/test/java/ghidra/app/util/pdb/pdbapplicator/PdbAddressCalculatorTest.java b/Ghidra/Features/PDB/src/test/java/ghidra/app/util/pdb/pdbapplicator/PdbAddressCalculatorTest.java
new file mode 100644
index 0000000000..a59b15eb88
--- /dev/null
+++ b/Ghidra/Features/PDB/src/test/java/ghidra/app/util/pdb/pdbapplicator/PdbAddressCalculatorTest.java
@@ -0,0 +1,376 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.pdb.pdbapplicator;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import generic.test.AbstractGenericTest;
+import ghidra.app.util.bin.format.pdb2.pdbreader.*;
+import ghidra.app.util.bin.format.pdb2.pdbreader.symbol.Compile3MsSymbol;
+import ghidra.app.util.bin.format.pdb2.pdbreader.symbol.PeCoffSectionMsSymbol;
+import ghidra.app.util.pdb.pdbapplicator.PdbAddressCalculator.*;
+import ghidra.program.database.ProgramBuilder;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.address.AddressSpace;
+import ghidra.program.model.listing.Program;
+import ghidra.program.model.mem.MemoryBlock;
+
+/**
+ * Tests for PDB {@link PdbAddressCalculator}s.
+ */
+public class PdbAddressCalculatorTest extends AbstractGenericTest {
+
+ private Program program;
+ private AddressSpace addressSpace = null;
+
+ private AbstractPdb pdb;
+ private static Processor processor;
+
+ private Address imageBase = null;
+ private long originalImageBase = 0L;
+ private List<ImageSectionHeader> imageSectionHeaders = null;
+ private List<ImageSectionHeader> imageSectionHeadersOrig = null;
+ private SortedMap<Long, Long> omapFromSource = null;
+ private List<SegmentMapDescription> segmentMapDescriptions = null;
+ private List<SegmentMapDescription> segmentMapDescriptionsZeroOffsets = null;
+ private List<PeCoffSectionMsSymbol> peCoffSectionSymbols = null;
+ private MemoryBlock[] memoryBlocks = null;
+
+ // Modeled from MemoryMapProvider1Test
+ private Program buildProgram(String programName, long imageBaseOffset) throws Exception {
+ ProgramBuilder builder = new ProgramBuilder(programName, ProgramBuilder._TOY);
+ MemoryBlock[] blocks = new MemoryBlock[3];
+ blocks[0] = builder.createMemory(".sect1", Long.toHexString(0x1000), 0x1000);
+ blocks[1] = builder.createMemory(".sect2", Long.toHexString(0x2000), 0x1000);
+ blocks[2] = builder.createMemory(".sect3", Long.toHexString(0x3000), 0x1000);
+ Program newProgram = builder.getProgram();
+
+ int transactionID = newProgram.startTransaction("Test Transaction");
+ newProgram.setImageBase(
+ newProgram.getAddressFactory().getDefaultAddressSpace().getAddress(imageBaseOffset),
+ true);
+ newProgram.endTransaction(transactionID, true);
+
+ return newProgram;
+ }
+
+ private Address addr(long offset) {
+ return addressSpace.getAddress(offset);
+ }
+
+ // Modeled from SymbolsTest
+ private AbstractPdb buildPdb() {
+ try (DummyPdb700 dummyPdb700 = new DummyPdb700(4096, 4096, 4096, 4096)) {
+ // Important: Must also use this processor value in any tests below that need it to
+ // ensure consistency across the tests. We are setting it in the pdb here (in the
+ // static assignment block), but we do not know the order that any tests are run,
+ // so having the same value will ensure consistent results.
+ processor = Processor.I8080;
+ dummyPdb700.setTargetProcessor(processor);
+ return dummyPdb700;
+ }
+ catch (Exception e) {
+ fail("Error in static initialization of test: " + e);
+ return null; // to satisfy compile warning
+ }
+ }
+
+ private List<ImageSectionHeader> setupImageSectionHeaders(AbstractPdb myPdb) {
+ List<ImageSectionHeader> headers = new ArrayList<>();
+ headers.add(PdbTestUtils.createImageSectionHeader(myPdb, ".sect1", 0x1000L, 0x1000L));
+ headers.add(PdbTestUtils.createImageSectionHeader(myPdb, ".sect2", 0x2000L, 0x1000L));
+ headers.add(PdbTestUtils.createImageSectionHeader(myPdb, ".sect3", 0x3000L, 0x1000L));
+ return headers;
+ }
+
+ private List<ImageSectionHeader> setupImageSectionHeadersOrig(AbstractPdb myPdb) {
+ List<ImageSectionHeader> headers = new ArrayList<>();
+ headers.add(PdbTestUtils.createImageSectionHeader(myPdb, ".sect1", 0x1000L, 0x3000L));
+ headers.add(PdbTestUtils.createImageSectionHeader(myPdb, ".sect2", 0x4000L, 0x3000L));
+ headers.add(PdbTestUtils.createImageSectionHeader(myPdb, ".sect3", 0x7000L, 0x3000L));
+ return headers;
+ }
+
+ private SortedMap<Long, Long> setupOmapFromSource() {
+ SortedMap<Long, Long> omap = new TreeMap<>();
+ omap.put(0x1000L, 0x19000L);
+ omap.put(0x4000L, 0x28000L);
+ omap.put(0x7000L, 0x37000L);
+ return omap;
+ }
+
+ private List<SegmentMapDescription> setupSegmentMapDescriptions(AbstractPdb myPdb) {
+ List<SegmentMapDescription> segments = new ArrayList<>();
+ segments.add(PdbTestUtils.createSegmentMapDescription(myPdb, 0x1000L, 0x1000));
+ segments.add(PdbTestUtils.createSegmentMapDescription(myPdb, 0x2000L, 0x1000));
+ segments.add(PdbTestUtils.createSegmentMapDescription(myPdb, 0x3000L, 0x1000));
+ return segments;
+ }
+
+ private List<SegmentMapDescription> setupSegmentMapDescriptionsZeroOffsets(AbstractPdb myPdb) {
+ List<SegmentMapDescription> segments = new ArrayList<>();
+ segments.add(PdbTestUtils.createSegmentMapDescription(myPdb, 0x0L, 0x1000));
+ segments.add(PdbTestUtils.createSegmentMapDescription(myPdb, 0x0L, 0x1000));
+ segments.add(PdbTestUtils.createSegmentMapDescription(myPdb, 0x0L, 0x1000));
+ return segments;
+ }
+
+ private List<PeCoffSectionMsSymbol> setupPeCoffSectionSymbols(AbstractPdb myPdb) {
+ List<PeCoffSectionMsSymbol> symbols = new ArrayList<>();
+ symbols.add(PdbTestUtils.createPeCoffSectionMsSymbol(myPdb, 1, 0x1000, 0x1000, ".sect1"));
+ symbols.add(PdbTestUtils.createPeCoffSectionMsSymbol(myPdb, 2, 0x2000, 0x1000, ".sect2"));
+ symbols.add(PdbTestUtils.createPeCoffSectionMsSymbol(myPdb, 3, 0x3000, 0x1000, ".sect3"));
+ return symbols;
+ }
+
+ //----------------------------------------------------------------------------------------------
+ @Before
+ public void setUp() throws Exception {
+ program = buildProgram("testProgram", 0x400000L);
+ pdb = buildPdb();
+ addressSpace = program.getAddressFactory().getDefaultAddressSpace();
+
+ imageBase = program.getImageBase();
+
+ memoryBlocks = program.getMemory().getBlocks();
+ originalImageBase = 0L;
+
+ imageSectionHeaders = setupImageSectionHeaders(pdb);
+ imageSectionHeadersOrig = setupImageSectionHeadersOrig(pdb);
+ omapFromSource = setupOmapFromSource();
+
+ segmentMapDescriptions = setupSegmentMapDescriptions(pdb);
+ segmentMapDescriptionsZeroOffsets = setupSegmentMapDescriptionsZeroOffsets(pdb);
+
+ peCoffSectionSymbols = setupPeCoffSectionSymbols(pdb);
+ }
+
+ //----------------------------------------------------------------------------------------------
+ @Test
+ public void testImageHeaderAddressCalculator() throws Exception {
+ PdbAddressCalculator calculator =
+ new PdbAddressCalculator.ImageHeaderAddressCalculator(imageBase, imageSectionHeaders);
+
+ Address expectedAddress = addr(0x401000L);
+ Address calculatedAddress = calculator.getAddress(1, 0x0L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ expectedAddress = addr(0x401100L);
+ calculatedAddress = calculator.getAddress(1, 0x100L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ expectedAddress = addr(0x402200L);
+ calculatedAddress = calculator.getAddress(2, 0x200L);
+ assertEquals(expectedAddress, calculatedAddress);
+ }
+
+ @Test
+ public void testImageHeaderWithOmapAddressCalculator() throws Exception {
+ PdbAddressCalculator calculator =
+ new PdbAddressCalculator.ImageHeaderWithOmapAddressCalculator(imageBase,
+ imageSectionHeadersOrig, omapFromSource);
+
+ Address expectedAddress = addr(0x419000L);
+ Address calculatedAddress = calculator.getAddress(1, 0x0L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ expectedAddress = addr(0x419100L);
+ calculatedAddress = calculator.getAddress(1, 0x100L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ expectedAddress = addr(0x428200L);
+ calculatedAddress = calculator.getAddress(2, 0x200L);
+ assertEquals(expectedAddress, calculatedAddress);
+ }
+
+ @Test
+ public void testSegmentMapAddressCalculator() throws Exception {
+ PdbAddressCalculator calculator =
+ new PdbAddressCalculator.SegmentMapAddressCalculator(imageBase, segmentMapDescriptions);
+
+ Address expectedAddress = addr(0x401000L);
+ Address calculatedAddress = calculator.getAddress(1, 0x0L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ expectedAddress = addr(0x401100L);
+ calculatedAddress = calculator.getAddress(1, 0x100L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ expectedAddress = addr(0x402200L);
+ calculatedAddress = calculator.getAddress(2, 0x200L);
+ assertEquals(expectedAddress, calculatedAddress);
+ }
+
+ @Test
+ public void testSegmentMapAddressCalculatorWithSynthesis() throws Exception {
+ PdbAddressCalculator calculator = new PdbAddressCalculator.SegmentMapAddressCalculator(
+ imageBase, segmentMapDescriptionsZeroOffsets);
+
+ Address expectedAddress = addr(0x401000L);
+ Address calculatedAddress = calculator.getAddress(1, 0x0L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ expectedAddress = addr(0x401100L);
+ calculatedAddress = calculator.getAddress(1, 0x100L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ expectedAddress = addr(0x402200L);
+ calculatedAddress = calculator.getAddress(2, 0x200L);
+ assertEquals(expectedAddress, calculatedAddress);
+ }
+
+ @Test
+ public void testPeCoffSectionAddressCalculator() throws Exception {
+ PdbAddressCalculator calculator = new PdbAddressCalculator.PeCoffSectionAddressCalculator(
+ imageBase, originalImageBase, peCoffSectionSymbols);
+
+ Address expectedAddress = addr(0x401000L);
+ Address calculatedAddress = calculator.getAddress(1, 0x0L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ expectedAddress = addr(0x401100L);
+ calculatedAddress = calculator.getAddress(1, 0x100L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ expectedAddress = addr(0x402200L);
+ calculatedAddress = calculator.getAddress(2, 0x200L);
+ assertEquals(expectedAddress, calculatedAddress);
+ }
+
+ @Test
+ public void testMemoryMapAddressCalculator() throws Exception {
+ PdbAddressCalculator calculator =
+ new PdbAddressCalculator.MemoryMapAddressCalculator(imageBase, memoryBlocks);
+
+ Address expectedAddress = addr(0x401000L);
+ Address calculatedAddress = calculator.getAddress(1, 0x0L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ expectedAddress = addr(0x401100L);
+ calculatedAddress = calculator.getAddress(1, 0x100L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ expectedAddress = addr(0x402200L);
+ calculatedAddress = calculator.getAddress(2, 0x200L);
+ assertEquals(expectedAddress, calculatedAddress);
+ }
+
+ //----------------------------------------------------------------------------------------------
+ @Test
+ public void testAddressCorrectionValue() throws Exception {
+ Compile3MsSymbol compileSymbol;
+ long correction;
+
+ StubPdbApplicator applicator = new StubPdbApplicator();
+ applicator.setProgram(program).setPdb(pdb).setOriginalImageBase(originalImageBase);
+
+ compileSymbol = PdbTestUtils.createCompile3MsSymbol(pdb, "anythingbutmap2pdb");
+ applicator.setLinkerModuleCompileSymbol(compileSymbol);
+ correction = PdbAddressCalculator.getCorrection(applicator);
+ assertEquals(0x0L, correction);
+
+ compileSymbol = PdbTestUtils.createCompile3MsSymbol(pdb, "map2pdb");
+ applicator.setLinkerModuleCompileSymbol(compileSymbol);
+ correction = PdbAddressCalculator.getCorrection(applicator);
+ assertEquals(originalImageBase, correction);
+ }
+
+ @Test
+ public void testAddressCalculatorFactory() throws Exception {
+ PdbAddressCalculator calculator;
+ Compile3MsSymbol compileSymbol;
+ Address expectedAddress;
+ Address calculatedAddress;
+ StubPdbApplicator applicator = new StubPdbApplicator();
+
+ // These applicator modifications and tests are done in an order based upon the known
+ // order of exclusion of PdbAddressCalculators, but in the reverse order to ensure the
+ // exclusions.
+
+ // Make it seem as though PDB does not have debug info
+ ((DummyPdb700) pdb).setDebugInfoAvailable(false);
+
+ applicator.setProgram(program).setPdb(pdb);
+ calculator = PdbAddressCalculator.chooseAddressCalculator(applicator, imageBase);
+ assertTrue(calculator instanceof MemoryMapAddressCalculator);
+
+ applicator.setLinkerPeCoffSectionSymbols(peCoffSectionSymbols);
+ compileSymbol = PdbTestUtils.createCompile3MsSymbol(pdb, "anythingbutmap2pdb");
+ applicator.setLinkerModuleCompileSymbol(compileSymbol);
+ calculator = PdbAddressCalculator.chooseAddressCalculator(applicator, imageBase);
+ assertTrue(calculator instanceof PeCoffSectionAddressCalculator);
+ // test address value. maybe??
+ expectedAddress = addr(0x402200L);
+ calculatedAddress = calculator.getAddress(2, 0x200L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ compileSymbol = PdbTestUtils.createCompile3MsSymbol(pdb, "map2pdb");
+ applicator.setLinkerModuleCompileSymbol(compileSymbol);
+ calculator = PdbAddressCalculator.chooseAddressCalculator(applicator, imageBase);
+ assertTrue(calculator instanceof PeCoffSectionAddressCalculator);
+ // test address value. maybe??
+ expectedAddress = addr(0x402200L);
+ calculatedAddress = calculator.getAddress(2, 0x200L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ // Make debug info available again and get nested resources
+ ((DummyPdb700) pdb).setDebugInfoAvailable(true);
+ PdbDebugInfo dbi = pdb.getDebugInfo();
+ assertTrue(dbi instanceof DummyDebugInfoNew);
+ DummyDebugInfoNew dummyDebugInfoNew = (DummyDebugInfoNew) dbi;
+ DebugData debugData = dummyDebugInfoNew.getDebugData();
+ assertTrue(debugData instanceof DummyDebugData);
+ DummyDebugData dummyDebugData = (DummyDebugData) debugData;
+
+ dummyDebugData.setImageSectionHeaders(null);
+ dummyDebugData.setImageSectionHeadersOrig(null);
+ dummyDebugData.setOmapFromSource(null);
+ dummyDebugInfoNew.setSegmentMapList(segmentMapDescriptions);
+ calculator = PdbAddressCalculator.chooseAddressCalculator(applicator, imageBase);
+ assertTrue(calculator instanceof SegmentMapAddressCalculator);
+ expectedAddress = addr(0x402200L);
+ calculatedAddress = calculator.getAddress(2, 0x200L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ dummyDebugData.setImageSectionHeaders(imageSectionHeaders);
+ calculator = PdbAddressCalculator.chooseAddressCalculator(applicator, imageBase);
+ assertTrue(calculator instanceof ImageHeaderAddressCalculator);
+ expectedAddress = addr(0x402200L);
+ calculatedAddress = calculator.getAddress(2, 0x200L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ dummyDebugData.setImageSectionHeadersOrig(imageSectionHeadersOrig);
+ calculator = PdbAddressCalculator.chooseAddressCalculator(applicator, imageBase);
+ assertTrue(calculator instanceof ImageHeaderAddressCalculator);
+ expectedAddress = addr(0x404200L);
+ calculatedAddress = calculator.getAddress(2, 0x200L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ dummyDebugData.setOmapFromSource(omapFromSource);
+ calculator = PdbAddressCalculator.chooseAddressCalculator(applicator, imageBase);
+ assertTrue(calculator instanceof ImageHeaderWithOmapAddressCalculator);
+ expectedAddress = addr(0x428200L);
+ calculatedAddress = calculator.getAddress(2, 0x200L);
+ assertEquals(expectedAddress, calculatedAddress);
+
+ }
+
+}
diff --git a/Ghidra/Features/PDB/src/test/java/ghidra/app/util/pdb/pdbapplicator/StubPdbApplicator.java b/Ghidra/Features/PDB/src/test/java/ghidra/app/util/pdb/pdbapplicator/StubPdbApplicator.java
new file mode 100644
index 0000000000..fb83febaf6
--- /dev/null
+++ b/Ghidra/Features/PDB/src/test/java/ghidra/app/util/pdb/pdbapplicator/StubPdbApplicator.java
@@ -0,0 +1,91 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.pdb.pdbapplicator;
+
+import java.util.List;
+
+import ghidra.app.util.bin.format.pdb2.pdbreader.AbstractPdb;
+import ghidra.app.util.bin.format.pdb2.pdbreader.symbol.AbstractMsSymbol;
+import ghidra.app.util.bin.format.pdb2.pdbreader.symbol.PeCoffSectionMsSymbol;
+import ghidra.program.model.listing.Program;
+
+/**
+ * Stub PDB Applicator for testing.
+ */
+public class StubPdbApplicator implements PdbApplicator {
+
+ private AbstractPdb pdb = null;
+ private long originalImageBase = 0L;
+
+ private Program program = null;
+
+ private List<PeCoffSectionMsSymbol> linkerPeCoffSectionSymbols = null;
+ private AbstractMsSymbol compileSymbolForLinkerModule = null;
+
+//==================================================================================================
+ @Override
+ public AbstractPdb getPdb() {
+ return pdb;
+ }
+
+ @Override
+ public Program getProgram() {
+ return program;
+ }
+
+ @Override
+ public long getOriginalImageBase() {
+ return originalImageBase;
+ }
+
+ @Override
+ public List<PeCoffSectionMsSymbol> getLinkerPeCoffSectionSymbols() {
+ return linkerPeCoffSectionSymbols;
+ }
+
+ @Override
+ public AbstractMsSymbol getLinkerModuleCompileSymbol() {
+ return compileSymbolForLinkerModule;
+ }
+
+//==================================================================================================
+ StubPdbApplicator setPdb(AbstractPdb pdb) {
+ this.pdb = pdb;
+ return this;
+ }
+
+ StubPdbApplicator setProgram(Program program) {
+ this.program = program;
+ return this;
+ }
+
+ StubPdbApplicator setOriginalImageBase(long originalImageBase) {
+ this.originalImageBase = originalImageBase;
+ return this;
+ }
+
+ StubPdbApplicator setLinkerPeCoffSectionSymbols(
+ List<PeCoffSectionMsSymbol> linkerPeCoffSectionSymbols) {
+ this.linkerPeCoffSectionSymbols = linkerPeCoffSectionSymbols;
+ return this;
+ }
+
+ StubPdbApplicator setLinkerModuleCompileSymbol(AbstractMsSymbol compileSymbolForLinkerModule) {
+ this.compileSymbolForLinkerModule = compileSymbolForLinkerModule;
+ return this;
+ }
+
+}