Ghidra is a software reverse engineering (SRE) framework
PDB Universal - new base
ghizardeac9445272d9
diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/AbstractParsableItem.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/AbstractParsableItem.javanew file mode 100644index 0000000000..32b3e86908--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/AbstractParsableItem.java@@ -0,0 +1,39 @@+/* ###+ * 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.pdb;++/**+ * This is the base class for certain record items that get parsed from a PDB and which we would+ * like to have toString() methods on.+ */+public abstract class AbstractParsableItem {++ /**+ * Emits {@link String} output of this class into the provided {@link StringBuilder}.+ * @param builder The {@link StringBuilder} into which the output is created.+ */+ public void emit(StringBuilder builder) {+ builder.append(this.getClass().getSimpleName());+ }++ @Override+ public String toString() {+ StringBuilder builder = new StringBuilder();+ emit(builder);+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/DelimiterState.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/DelimiterState.javanew file mode 100644index 0000000000..5cc2afde98--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/DelimiterState.java@@ -0,0 +1,80 @@+/* ###+ * 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.pdb;++/**+ * This is a utility class, containing state, used for providing delimiters in a sequence+ * of outputs.+ */+public class DelimiterState {++ private String delimStart;+ private String delim;+ private boolean first;++ /**+ * Constructor.+ * @param delimStart {@link String} output to be provided before the first item in a list, only+ * when at least one item is found in the list.+ * @param delim Delimiter char(s) to be output prior to any outputs subsequent to a first+ * output.+ */+ public DelimiterState(String delimStart, String delim) {+ this.delimStart = delimStart;+ this.delim = delim;+ first = true;+ }++ public void reset() {+ first = true;+ }++ /**+ * Method that adds delimiter information (based on the state to the {@link String}+ * representation of the input argument. The boolean argument is available to give the+ * caller a single-line way of calling the method in a conditional sense (i.e., eliminates+ * the need for a conditional block wrapping the call).+ * @param output True: act as though called; false: act as though call was not made.+ * @param item {@link AbstractParsableItem} to be output.+ * @return {@link String} result that contains the {@link AbstractParsableItem} and any+ * delimiter output based on the state.+ */+ public String out(boolean output, AbstractParsableItem item) {+ return out(output, item.toString());+ }++ /**+ * Method that adds delimiter information (based on the state to the {@link String}+ * representation of the input argument. The boolean argument is available to give the+ * caller a single-line way of calling the method in a conditional sense (i.e., eliminates+ * the need for a conditional block wrapping the call).+ * @param output True: act as though called; false: act as though call was not made.+ * @param val {@link String} to be output.+ * @return {@link String} result that contains the {@link String} argument and any delimiter+ * output based on the state.+ */+ public String out(boolean output, String val) {+ if (output) {+ if (first) {+ first = false;+ return delimStart + val;+ }+ return delim + val;+ }+ return "";+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/Hasher.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/Hasher.javanew file mode 100644index 0000000000..d75687dba1--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/Hasher.java@@ -0,0 +1,69 @@+/* ###+ * 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.pdb;++/**+ * Refer to PDB API. This class models HashPbCb.+ */+public class Hasher {++ /**+ * Hashes {@link String}, using unsigned32BitMod, which the user should ensure is <= 0xffffffff.+ * Returns an unsigned short value (16-bit) stored in a long.+ * @param string The input {@link String} to be hashed.+ * @param unsigned32BitMod Modulus to be used for the hash.+ * @return An unsigned short hash value returned as a long.+ * @throws PdbException Upon not enough data left to parse.+ */+ public long hash(String string, long unsigned32BitMod) throws PdbException {+ return hashString32(string, unsigned32BitMod) & 0xffff;+ }++ /**+ * Hashes {@link String}, using unsigned32BitMod, which the user should ensure is <= 0xffffffff.+ * Returns an unsigned integer value (32-bit) returned as a long.+ * @param string The input {@link String} to be hashed.+ * @param unsigned32BitMod Modulus to be used for the hash.+ * @return An unsigned integer hash value returned as a long.+ * @throws PdbException Upon not enough data left to parse.+ */+ protected long hashString32(String string, long unsigned32BitMod) throws PdbException {+ byte[] bytes = string.getBytes();+ PdbByteReader reader = new PdbByteReader(bytes);+ int count = bytes.length;+ //int count = length >> 2; // Processing 32 bits at a time.+ long hash = 0; // represents unsigned int.++ while (count >= 4) {+ count -= 4;+ hash ^= reader.parseUnsignedIntVal();+ }+ if (bytes.length - reader.getIndex() >= 2) {+ hash ^= reader.parseUnsignedShortVal();+ }+ if (bytes.length - reader.getIndex() == 1) {+ hash ^= reader.parseUnsignedByteVal();+ }++ hash |= 0x20202020; // to-lower mask (not sure of effect after the above hashing)+ hash ^= (hash >> 11);+ // Mask down to 32-bits.+ hash &= 0xffffffff;+ // Apply modulus.+ return (hash ^ (hash >> 16)) % unsigned32BitMod;+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/Hasher32.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/Hasher32.javanew file mode 100644index 0000000000..c5566a384e--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/Hasher32.java@@ -0,0 +1,36 @@+/* ###+ * 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.pdb;++/**+ * Refer to PDB API. This class models LHashPbCb.+ */+public class Hasher32 extends Hasher {++ /**+ * Hashes {@link String}, using unsigned32BitMod, which the user should ensure is <= 0xffffffff.+ * Returns an unsigned integer value (32-bit) returned as a long.+ * @param string The input {@link String} to be hashed.+ * @param unsigned32BitMod Modulus to be used for the hash.+ * @return An unsigned integer hash value returned as a long.+ * @throws PdbException Upon not enough data left to parse.+ */+ @Override+ public long hash(String string, long unsigned32BitMod) throws PdbException {+ return hashString32(string, unsigned32BitMod);+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/Hasher32V2.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/Hasher32V2.javanew file mode 100644index 0000000000..feb56460f3--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/Hasher32V2.java@@ -0,0 +1,61 @@+/* ###+ * 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.pdb;++/**+ * Refer to PDB API. This class models HasherV2.+ */+public class Hasher32V2 extends Hasher32 {++ /**+ * Hashes (V2) {@link String}, using unsigned32BitMod, which the user should ensure+ * is <= 0xffffffff. Returns an unsigned integer value (32-bit) returned as a long.+ * @param string The input {@link String} to be hashed.+ * @param unsigned32BitMod Modulus to be used for the hash.+ * @return An unsigned integer hash value returned as a long.+ * @throws PdbException Upon not enough data left to parse.+ */+ @Override+ public long hash(String string, long unsigned32BitMod) throws PdbException {+ byte[] bytes = string.getBytes();+ PdbByteReader reader = new PdbByteReader(bytes);+ int count = bytes.length;+ long hash = 0xb170a1bfL; // represents unsigned 32-bit.++ while (count >= 4) {+ count -= 4;+ hash += reader.parseUnsignedIntVal();+ hash += (hash << 10);+ hash ^= (hash >> 6);+ }+ // Hash remaining bytes.+ while (reader.hasMore()) {+ hash += reader.parseUnsignedByteVal();+ hash += (hash << 10);+ hash ^= (hash >> 6);+ }+ // Mask down to 32-bits.+ hash &= 0xffffffff;+ // Apply modulus.+ return hashUnsigned32Bit(hash) % unsigned32BitMod;+ }++ // From Numeric Recipes in C, second edition, pg 284+ private long hashUnsigned32Bit(long unsigned32BitVal) {+ return (unsigned32BitVal * 1664525L + 1013904223L) & 0xffffffff;+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/PdbByteReader.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/PdbByteReader.javanew file mode 100644index 0000000000..fad88c4ea6--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/PdbByteReader.java@@ -0,0 +1,606 @@+/* ###+ * 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.pdb;++import java.math.BigInteger;+import java.nio.charset.StandardCharsets;+import java.util.Arrays;++import ghidra.app.util.datatype.microsoft.GUID;+import ghidra.util.LittleEndianDataConverter;++/**+ * {@code PdbByteReader} is a utility class used for administering out portions of a byte array.+ * The requests are made with a {@code parse...} method, which interprets data, pointed to by a+ * current {@code index} into the byte array, into the type requested.+ *+ * <P>The {@code PdbByteReader} is intended for PDB (Program Data Base) / MSF (Multi-Stream File)+ * buffer processing which has data stored in a Least-Significant-Byte-First format. Requested+ * values are read out appropriately.+ *+ * <P>When an {@code unsigned} value is requested, the value is returned in a larger integral type+ * than would normally be necessary. This allows for java to be used (which only has signed+ * values) when modeling a capability that was originally designed in a C/C++ world that could+ * contained an unsigned value in the smaller integral type.+ *+ * <P>Other utility methods exist for setting/getting the {@code index} or for moving the+ * {@code index} along to align or pad-out according to how a C/C++ structure would be padded in+ * memory.+ */+public class PdbByteReader {+ // TODO: Regarding String conversions... We expect that US_ASCII could be a problem, but it+ // is probably better than creating the String without any code set chosen at all. Do we+ // need to change all processing of Strings within the PDB so that we are only creating byte+ // arrays with some notional idea (1 byte, 2 byte, possibly utf-8, utf-16, wchar_t, or+ // "unknown" and defer true interpretation/conversion to String until we know or until+ // Ghidra user can ad-hoc apply interpretations to those fields? Needs investigation, but+ // not critical at this time.++ //==============================================================================================+ // Internals+ //==============================================================================================+ /** byte array containing data to be parsed */+ private byte[] bytes;+ /** fixed length of the byte array */+ private int limit;+ /** current index into the byte array from which the next parse method will act */+ private int index;+ /** offset to begin alignment for methods that need to calculate alignment */+ private int alignMarker;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor for a PdbByteReader. Takes byte array of data to be read in particular+ * increments and formats.+ * @param bytes byte[] of data to be read/processed.+ */+ public PdbByteReader(byte[] bytes) {+ this.bytes = bytes;+ limit = (bytes == null) ? 0 : bytes.length;+ index = 0;+ alignMarker = 0;+ }++ /**+ * Resets the index of the PdbByteReader back to zero.+ */+ public void reset() {+ index = 0;+ alignMarker = 0;+ }++ /**+ * Returns the number of bytes remaining in the PdbByteReader.+ * @return The number of bytes remaining.+ */+ public int numRemaining() {+ return limit - index;+ }++ /**+ * Returns the current index of the PdbByteReader.+ * @return The current index.+ */+ public int getIndex() {+ return index;+ }++ /**+ * Returns the limit of the PdbByteReader.+ * @return The index limit.+ */+ public int getLimit() {+ return limit;+ }++ /**+ * Sets the index to the value specified. Silently fails when outside of array.+ * @param index The to set to the index.+ */+ public void setIndex(int index) {+ if (index >= 0 && index < limit) {+ this.index = index;+ }+ }++ /**+ * Returns true if there are more bytes remaining in the PdbByteReader.+ * @return True if more bytes remain.+ */+ public boolean hasMore() {+ return (index < limit);+ }++ /**+ * Returns true if there are more bytes remaining in the PdbByteReader which are non-pad bytes.+ * @return True if more non-pad bytes remain.+ */+ public boolean hasMoreNonPad() {+ if (!hasMore()) {+ return false;+ }+ return (bytes[index] & 0xff) <= 0xf0;+ }++ /**+ * Parses a single byte (unsigned char) of data from the PdbByteReader and returns its+ * positive integer value.+ * @return The positive integer value of the parsed byte.+ * @throws PdbException Upon not enough data left to parse.+ */+ public int parseUnsignedByteVal() throws PdbException {+ checkLimit(1);+ return bytes[index++] & 0xff;+ }++ /**+ * Parses and returns a short from the PdbByteReader.+ * @return The short parsed.+ * @throws PdbException Upon not enough data left to parse.+ */+ public short parseShort() throws PdbException {+ checkLimit(2);+ byte[] selectedBytes = Arrays.copyOfRange(bytes, index, index + 2);+ index += 2;+ return LittleEndianDataConverter.INSTANCE.getShort(selectedBytes);+ }++ /**+ * Parses an unsigned short from the PdbByteReader and returns its positive integer value.+ * @return The positive integer value of the parsed unsigned short.+ * @throws PdbException Upon not enough data left to parse.+ */+ public int parseUnsignedShortVal() throws PdbException {+ checkLimit(2);+ byte[] selectedBytes = Arrays.copyOfRange(bytes, index, index + 2);+ // Resize with padding because of possibility of unsigned overflow into short.+ selectedBytes = Arrays.copyOf(selectedBytes, 4);+ index += 2;+ return LittleEndianDataConverter.INSTANCE.getInt(selectedBytes);+ }++ /**+ * Parses and returns an integer from the PdbByteReader.+ * @return The integer parsed.+ * @throws PdbException Upon not enough data left to parse.+ */+ public int parseInt() throws PdbException {+ checkLimit(4);+ byte[] selectedBytes = Arrays.copyOfRange(bytes, index, index + 4);+ index += 4;+ return LittleEndianDataConverter.INSTANCE.getInt(selectedBytes);+ }++ /**+ * Parses an unsigned int from the PdbByteReader and returns its positive long value.+ * @return The positive long value of the parsed unsigned int.+ * @throws PdbException Upon not enough data left to parse.+ */+ public long parseUnsignedIntVal() throws PdbException {+ checkLimit(4);+ byte[] selectedBytes = Arrays.copyOfRange(bytes, index, index + 4);+ selectedBytes = Arrays.copyOf(selectedBytes, 8);+ index += 4;+ return LittleEndianDataConverter.INSTANCE.getLong(selectedBytes);+ }++ /**+ * Parses and returns a (64-bit) long from the PdbByteReader.+ * @return The integer parsed.+ * @throws PdbException Upon not enough data left to parse.+ */+ public long parseLong() throws PdbException {+ checkLimit(8);+ byte[] selectedBytes = Arrays.copyOfRange(bytes, index, index + 8);+ index += 8;+ return LittleEndianDataConverter.INSTANCE.getLong(selectedBytes);+ }++ /**+ * Parses an (64-bit) unsigned long from the PdbByteReader and returns its positive+ * BigInteger value.+ * @return The positive long value of the parsed unsigned int.+ * @throws PdbException Upon not enough data left to parse.+ */+ public BigInteger parseUnsignedLongVal() throws PdbException {+ checkLimit(8);+ byte[] selectedBytes = Arrays.copyOfRange(bytes, index, index + 8);+ selectedBytes = Arrays.copyOf(selectedBytes, 8);+ index += 8;+ return LittleEndianDataConverter.INSTANCE.getBigInteger(selectedBytes, 8, false);+ }++ /**+ * Parses and returns a short-valued-length-prefixed byte array from the PdbByteReader (not+ * including the 2 bytes of the short-valued-length). An unsigned short is first parsed.+ * This value tells the number of bytes to be read and returned as a byte[].+ * @return The byte[] parsed.+ * @throws PdbException Upon not enough data left to parse.+ */+ public byte[] parseShortLengthPrefixedByteArray() throws PdbException {+ checkLimit(2);+ int length = parseUnsignedShortVal();+ checkLimit(length);+ byte[] selectedBytes = Arrays.copyOfRange(bytes, index, index + length);+ index += length;+ return selectedBytes;+ }++ /**+ * Returns the remaining bytes in the PdbByteReader as a byte array.+ * @return The byte[] containing the remaining bytes.+ */+ public byte[] parseBytesRemaining() {+ int remaining = limit - index;+ byte[] selectedBytes = Arrays.copyOfRange(bytes, index, index + remaining);+ index += remaining;+ return selectedBytes;+ }++ /**+ * Extracts and returns a byte array of bytes from the PdbByteReader, the number of which+ * is specified byte the parameter.+ * @param num The number of bytes to extract and return.+ * @return The byte[] containing the number of bytes requested.+ * @throws PdbException Upon not enough data left to parse.+ */+ public byte[] parseBytes(int num) throws PdbException {+ checkLimit(num);+ byte[] selectedBytes = Arrays.copyOfRange(bytes, index, index + num);+ index += num;+ return selectedBytes;+ }++ /**+ * Returns a sub-PdbByteReader starting at the current index location and limited to the+ * length. The parent PdbByteReader index gets moved forward by length.+ * @param length The length of the sub-PdbByteReader.+ * @return The sub-PdbByteReader.+ * @throws PdbException Upon not enough data left to parse.+ */+ public PdbByteReader getSubPdbByteReader(int length) throws PdbException {+ return new PdbByteReader(parseBytes(length));+ }++ /**+ * Parses an integral MSFT Numeric type from the PdbByteReader.+ * @return A BigInteger containing the Numeric value.+ * @throws PdbException Upon not enough data left to parse.+ */+ public BigInteger parseNumeric() throws PdbException {+ int subTypeIndex = parseUnsignedShortVal();+ if (subTypeIndex >= 0x8000) {+ //TODO: create these as intrinsic types and do proper parsing?+ switch (subTypeIndex) {+ // For each case, parse bytes (to move index forward) and throw bytes away.+ // The number of bytes parsed is based on the size of the integral type+ // represented by subTypeIndex.+ case 0x8000: // char+ return BigInteger.valueOf(parseUnsignedByteVal());+ case 0x8001: // short+ return BigInteger.valueOf(parseShort());+ case 0x8002: // unsigned short+ return BigInteger.valueOf(parseUnsignedShortVal());+ case 0x8003: // 32-bit+ return BigInteger.valueOf(parseInt());+ case 0x8004: // unsigned 32-bit+ return BigInteger.valueOf(parseUnsignedIntVal());+ case 0x8009: // 64-bit+ return BigInteger.valueOf(parseLong());+ case 0x800a: // unsigned 64-bit+ return parseUnsignedLongVal();+ }+ }+ return BigInteger.valueOf(subTypeIndex);+ }++ /**+ * Parses an GUID from the PdbByteReader.+ * @return The GUID parsed.+ * @throws PdbException Upon not enough data left to parse.+ */+ public GUID parseGUID() throws PdbException {+ checkLimit(16);+ int data1 = parseInt();+ short data2 = parseShort();+ short data3 = parseShort();+ byte[] data4 = parseBytes(8);+ return new GUID(data1, data2, data3, data4);+ }++ /**+ * Parses and returns a byte-valued-length-prefixed String from the PdbByteReader. The+ * string length is determined by the first byte of data (not returned)--there is not a null+ * terminator in the source bytes. This number of bytes is extracted and converted to a+ * String and returned.+ * @return The String containing the bytes (excluding the byte containing the length).+ * @throws PdbException upon error parsing string.+ */+ public String parseByteLengthPrefixedString() throws PdbException {+ int length = parseUnsignedByteVal();+ if (length == 0) {+ return "";+ }+ int offset = index;+ index += length;+ // TODO: See note above regarding US_ASCII.+ try {+ return new String(bytes, offset, length, StandardCharsets.US_ASCII);+ }+ catch (IndexOutOfBoundsException e) {+ throw new PdbException("Error parsing String: " + e.toString());+ }+ }++ /**+ * Parses and returns a byte-valued-length-prefixed UTF8 String from the PdbByteReader. The+ * string length is determined by the first byte of data (not returned)--there is not null+ * terminator in the source bytes. This number of bytes is extracted and converted to a+ * {@link String} and returned.+ * @return The String containing the bytes (excluding the byte containing the length).+ * @throws PdbException upon error parsing string.+ */+ public String parseByteLengthPrefixedUtf8String() throws PdbException {+ int length = parseUnsignedByteVal();+ if (length == 0) {+ return "";+ }+ int offset = index;+ index += length;+ try {+ return new String(bytes, offset, length, StandardCharsets.UTF_8);+ }+ catch (IndexOutOfBoundsException e) {+ throw new PdbException("Error parsing String: " + e.toString());+ }+ }++ /**+ * Parses a null-terminated string from the PdbByteReader and returns the {@link String} (minus+ * the terminating null character). If no null, then contract not fulfilled.+ * @return The String parsed.+ * @throws PdbException upon error parsing string.+ */+ public String parseNullTerminatedString() throws PdbException {+ int offset = index;+ int width = 1;+ int end = findNullTerminatorIndex(width);+ index = end + width;+ if (end == offset) {+ return "";+ }+ // TODO: See note above regarding US_ASCII.+ return new String(bytes, offset, end - offset, StandardCharsets.US_ASCII);+ }++ /**+ * Parses a null-terminated UTF-8 string from the PdbByteReader and returns the String (minus+ * the terminating null character). If no null, then contract not fulfilled: returns "".+ * @return The String parsed.+ * @throws PdbException upon error parsing string.+ */+ public String parseNullTerminatedUtf8String() throws PdbException {+ int offset = index;+ int width = 1;+ int end = findNullTerminatorIndex(width);+ index = end + width;+ if (end == offset) {+ return "";+ }+ return new String(bytes, offset, end - offset, StandardCharsets.UTF_8);+ }++ /**+ * Parses a null-terminated wchar_t string from the PdbByteReader and returns the String (minus+ * the terminating null character). If no null, then contract not fulfilled: returns "".+ * @return The String parsed.+ * @throws PdbException upon error parsing string.+ */+ public String parseNullTerminatedWcharString() throws PdbException {+ int offset = index;+ int width = 2;+ int end = findNullTerminatorIndex(width);+ index = end + width;+ if (end == offset) {+ return "";+ }+ return new String(bytes, offset, end - offset, StandardCharsets.UTF_16);+ }++ /**+ * Stores the current index value as a marker for performing alignment. The {@link #align4()}+ * method calculates alignment based on this marker.+ * @param alignMarkerIn Offset to begin alignment calculations.+ */+ public void markAlign(int alignMarkerIn) {+ this.alignMarker = alignMarkerIn;+ }++ /**+ * Moves the index of the PdbByteReader to align on a 4-byte boundary of the initializing+ * byte array, modified by an alignment modifier passed in by {@link #markAlign(int)}.+ * @return The number added to the index.+ */+ public int align4() {+ int excess = (index - alignMarker) & 0x03;+ int pad = (excess == 0) ? 0 : 4 - excess;+ index += pad;+ return pad;+ }++ /**+ * This is a specialized method for PDB that should only be used when the Subject Matter+ * Expert know it is appropriate to use. It looks for and removes padding bytes that are+ * indications of and take the place of alignment padding.+ * @return The number of padding bytes removed (also the increase in index).+ */+ public int skipPadding() {+ int initialIndex = index;+ while ((index < limit) && (bytes[index] & 0xf0) == 0xf0) {+ index++;+ }+ return index - initialIndex;+ }++ /**+ * This method skips the number of bytes specified. Does not skip beyond the end.+ * @param num The number of bytes to skip.+ */+ public void skip(int num) {+ if (num > (limit - index)) {+ index = limit;+ }+ else {+ index += num;+ }+ }++ /**+ * Debug method used the dump bytes of the PdbByteReader to String in a pretty format to a+ * String. Includes header of internal values.+ * @return String of data dumped.+ */+ public String dump() {+ return dump(0, limit);+ }++ /**+ * Debug method used the dump a specified number of bytes of the PdbByteReader in a pretty+ * format to a String, starting at the current index. Includes header of internal values.+ * @param max The max number of bytes to output.+ * @return String of data dumped.+ */+ public String dump(int max) {+ return dump(index, index + max);+ }++ /**+ * Debug method used the dump a specified number of bytes of the PdbByteReader in a pretty+ * format, starting at the first parameter and continuing to the one less than the last+ * parameter. First dumped are the number of bytes in the PdbByteReader, followed by the+ * current index, followed by the number of first and last parameter values, followed byte+ * the bytes specified ((or up to end of buffer if it comes first).+ * @param first Index of first byte to output+ * @param last Index of last byte to output (limited by end of the buffer)+ * @return String containing the pretty output format+ */+ public String dump(int first, int last) {+ StringBuilder builder = new StringBuilder();+ last = last > limit ? limit : last;+ builder.append("limit: ");+ builder.append(limit);+ builder.append("\nindex: ");+ builder.append(index);+ builder.append("\nfirst: ");+ builder.append(first);+ builder.append("\nlast: ");+ builder.append(last);+ builder.append(dumpBytes(first, last));+ return builder.toString();+ }++ /**+ * Debug method used the dump bytes of the PdbByteReader to String in a pretty format to a+ * String.+ * @return String of data dumped.+ */+ public String dumpBytes() {+ return dumpBytes(0, limit);+ }++ /**+ * Debug method used the dump a specified number of bytes of the PdbByteReader in a pretty+ * format to a String, starting at the current index.+ * @param max The max number of bytes to output.+ * @return String of data dumped.+ */+ public String dumpBytes(int max) {+ return dumpBytes(index, index + max);+ }++ /**+ * Debug method used the dump a specified number of bytes of the PdbByteReader in a pretty+ * format, starting at the first parameter and continuing to the one less than the last+ * parameter. Only the bytes are dumped.+ * @param first Index of first byte to output+ * @param last Index of last byte to output (limited by end of the buffer)+ * @return String containing the pretty output format+ */+ public String dumpBytes(int first, int last) {+ if (first > last || first > limit) {+ return "";+ }+ StringBuilder builder = new StringBuilder();+ last = last > limit ? limit : last;+ for (int i = first; i < last;) {+ builder.append(String.format("\n%06x", i));+ for (int j = 0; (j < 16) && (i < last); j++, i++) {+ builder.append(String.format(" %02x", bytes[i]));+ }+ }+ return builder.toString();+ }++ //==============================================================================================+ // Private Methods+ //==============================================================================================+ /**+ * Checks if {@code numNeeded} bytes is available between {@code index} and {@code limit}.+ * Throws PdbException if space is not available. The {@code numNeeded} value is the amount+ * that the caller intends to increment {@code index} by, and the resultant value is allowed+ * to hit {@code limit}, but not exceed {@code limit}, as the {@code index} value is that of+ * what would be the next byte to read, if one was going to read again.+ * @param numNeeded The number of bytes for the check availability.+ * @throws PdbException Upon {@code numNeeded} bytes not available in the reader between+ * {@code index} and {@code limit}.+ */+ private void checkLimit(int numNeeded) throws PdbException {+ if (numNeeded < 0) {+ throw new PdbException("Illegal negative.");+ }+ if (Integer.MAX_VALUE - index < numNeeded) {+ throw new PdbException("Needed data beyond max.");+ }+ if (index + numNeeded > limit) {+ throw new PdbException("Needed data is not available.");+ }+ }++ /**+ * Returns the index of the first character of the null terminator of any width.+ * @param width The width of the terminator.+ * @return The index of the first character of the terminator.+ * @throws PdbException upon not finding a null terminator.+ */+ private int findNullTerminatorIndex(int width) throws PdbException {+ int count = 0;+ int finderIndex = index;+ while (finderIndex < limit) {+ if (bytes[finderIndex++] == 0x00) {+ if (++count == width) {+ return finderIndex - width;+ }+ }+ else {+ count = 0;+ }+ }+ throw new PdbException("Error parsing String: null terminator not found");+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/PdbException.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/PdbException.javanew file mode 100644index 0000000000..1bb16f9fce--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/PdbException.java@@ -0,0 +1,29 @@+/* ###+ * 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.pdb;++/**+ * Exception used when there is an error processing components of the PDB file.+ * This could mean that a data buffer is not long enough, an invalid or unrecognizable value+ * is seen, or values parsed do not correspond with other values.+ */+public class PdbException extends Exception {++ public PdbException(String message) {+ super(message);+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/AbstractMsf.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/AbstractMsf.javanew file mode 100644index 0000000000..c33f7a45ee--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/AbstractMsf.java@@ -0,0 +1,341 @@+/* ###+ * 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.pdb.msfreader;++import java.io.IOException;+import java.io.RandomAccessFile;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class represents the the Multi-Stream Format File used for Windows PDB files.+ * We have intended to implement to the Microsoft PDB API (source); see the API for truth.+ * <P>+ * Derived classes represents the real formats. The file format represents a kind of+ * file system within a file and is based upon pages in order to try to optimize+ * disk I/O and system update. There was also a mechanism to allow for ping-ponged+ * commit for file updates. Our implementation is only used for reading the file+ * format; it is not intended to write or modify an existing file. Much work would+ * need to be done to create a version with those capabilities.+ * <P>+ * The file format consists of a first page that contains identifying header information+ * that consists of an ID string, and limited parameters needed for pointing to+ * directory information and the Free Page Map. We do not use the latter information.+ * <P>+ * Note that the API (source) description on indicates that the original tools could+ * have been built with different parameter sets, which also impacts the page size+ * and other parameters for the format. We intended to create a reader that is capable+ * of reading any of these files.+ * <P>+ * The file header generally contains the following information, but their sizes on disk+ * depends on whether this is a file of the older or newer format. Generally, the fields follow:+ * <PRE>+ * Field Description Size on Disk Old Size on Disk New Java Type+ * ID ID "string" 42 29 byte[]+ * identifying+ * old vs. new+ * ID padding Padding between 2 3 N/A+ * ID and next+ * field+ * Page Size Power-of-2 page 4 4 int+ * size used+ * Free Page Map Page Number of 2 4 int+ * current free+ * page map+ * Number of Pages Number of pages 2 4 int+ * currently used+ * in the file+ * Serialized Sequence of page+ * info about numbers+ * directory+ * stream:+ * -Directory Num of bytes 4+4 4 int+ * Length + (opt addr field)+ * -Page number Page number that 2+2 4+ * contains page+ * numbers for the+ * stream; see note+ * below regarding new!+ * </PRE>+ * The file directory is stored in stream 0, which has its information persisted in+ * the header as described above. However, for the newest format, the page (pointed+ * to in the header) for the directory stream has an extra level of indirection. The+ * page contains page numbers, whose pages contain contain page numbers for the+ * directory stream. Note that the page numbers listed on any of these pages have+ * the following format on disk:+ * <PRE>+ * Field Description Size on Disk Old Size on Disk New Java Type+ * Page Number Page Number 2+2 4 int+ * + (opt addr field)+ * </PRE>+ * The directory stream contain StreamTable information, which is serialized into the+ * directory stream as follows:+ * <PRE>+ * numStreams+ * streamLength[numStreams]+ * serializedStream[numStreams]+ * </PRE>+ * Note that the StreamTable parsed from the directory stream does not have the most+ * up-to-date information about stream 0 (the directory stream); the up-to-date+ * version of stream 0 is what was persisted in the header. So after the StreamTable+ * has been deserialized from the directory stream, the stream 0 information in the+ * StreamTable gets overwritten with the stream 0 that we had already obtained.+ * <P>+ * @see MsfFileReader+ * @see MsfStream+ * @see AbstractMsfDirectoryStream+ * @see AbstractMsfFreePageMap+ * @see AbstractMsfStreamTable+ */+public abstract class AbstractMsf implements AutoCloseable {++ private static final int HEADER_PAGE_NUMBER = 0;+ private static final int DIRECTORY_STREAM_NUMBER = 0;++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected String filename;+ protected MsfFileReader fileReader;++ protected AbstractMsfFreePageMap freePageMap;+ protected AbstractMsfDirectoryStream directoryStream;+ protected AbstractMsfStreamTable streamTable;++ protected int pageSize;+ protected int log2PageSize;+ protected int freePageMapNumSequentialPage;+ protected int pageSizeModMask;++ protected int currentFreePageMapFirstPageNumber;+ protected int numPages = 1; // Set to 1 to allow initial read++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor for this class.+ * @param file The {@link RandomAccessFile} to process for this class.+ * @throws IOException Upon file IO seek/read issues.+ * @throws PdbException Upon unknown value for configuration.+ */+ public AbstractMsf(RandomAccessFile file) throws IOException, PdbException {+ // Do initial configuration with largest possible page size. ConfigureParameters will+ // be called again later with the proper pageSize set.+ pageSize = 0x1000;+ configureParameters();+ // Create components.+ fileReader = new MsfFileReader(this, file);+ create();+ }++ /**+ * Returns the page size employed by this {@link AbstractMsf}.+ * @return Page size.+ */+ public int getPageSize() {+ return pageSize;+ }++ /**+ * Returns the number of streams found in this {@link AbstractMsf}.+ * @return Number of streams.+ */+ public int getNumStreams() {+ return streamTable.getNumStreams();+ }++ /**+ * Returns the {@link MsfStream} specified by {@link AbstractMsf}.+ * @param streamNumber The number of the Stream to return. Must be less than the number+ * of streams returned by {@link #getNumStreams()}.+ * @return {@link MsfStream} or {@code null} if no stream for the streamNumber.+ */+ public MsfStream getStream(int streamNumber) {+ return streamTable.getStream(streamNumber);+ }++ /**+ * Closes resources used by this {@link AbstractMsf}.+ * @throws IOException Under circumstances found when closing a {@link RandomAccessFile}.+ */+ @Override+ public void close() throws IOException {+ if (fileReader != null) {+ fileReader.close();+ }+ }++ //==============================================================================================+ // Package-Protected Utilities+ //==============================================================================================+ /**+ * Returns the value of the floor (greatest integer less than or equal to) of the result+ * upon dividing the dividend by a divisor which is the power-of-two of the log2Divisor.+ * @param dividend The dividend to the operator+ * @param log2Divisor The log2 of the intended divisor value.+ * @return The floor of the division result.+ */+ static final int floorDivisionWithLog2Divisor(int dividend, int log2Divisor) {+ return (dividend + (1 << log2Divisor) - 1) >> log2Divisor;+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ /**+ * Method that returns the identification byte[] required by this format.+ * @return The minimum required number.+ */+ protected abstract byte[] getIdentification();++ /**+ * Returns the offset (in bytes) of the PageSize within the header.+ * @return The offset of the PageSize within the header.+ */+ protected abstract int getPageSizeOffset();++ /**+ * Deserializes the Free Page Map page number from the {@link PdbByteReader}.+ * @param reader {@link PdbByteReader} from which to read.+ * @throws PdbException Upon not enough data left to parse.+ */+ protected abstract void parseFreePageMapPageNumber(PdbByteReader reader) throws PdbException;++ /**+ * Deserializes the value of the number of pages in the MSF.+ * @param reader {@link PdbByteReader} from which to read.+ * @throws PdbException Upon not enough data left to parse.+ */+ protected abstract void parseCurrentNumPages(PdbByteReader reader) throws PdbException;++ /**+ * Method to create the following components: StreamTable, FreePageMap, and DirectoryStream.+ * FreePageMap.+ */+ abstract void create();++ /**+ * Method to set parameters for the file based on version and page size.+ * @throws PdbException Upon unknown value for configuration.+ */+ abstract void configureParameters() throws PdbException;++ /**+ * Method to get the size of the page number (in bytes) when serialized to disc.+ * @return The page size (in bytes).+ */+ abstract protected int getPageNumberSize();++ //==============================================================================================+ // Class Internals+ //==============================================================================================+ /**+ * Returns Log2 value of the page size employed by this MSF.+ * @return The Log2 value of the page size employed by this MSF.+ */+ protected int getLog2PageSize() {+ return log2PageSize;+ }++ /**+ * Returns the the mask used for masking off the upper bits of a value use to get the+ * mod-page-size of the value (pageSizes must be power of two for this to work).+ * @return The mask.+ */+ protected int getPageSizeModMask() {+ return pageSizeModMask;+ }++ /**+ * Returns the number of pages found in sequence that compose the {@link AbstractMsfFreePageMap}+ * (for this {@link AbstractMsf}) when on disk.+ * @return The number of sequential pages in the {@link AbstractMsfFreePageMap}.+ */+ protected int getNumSequentialFreePageMapPages() {+ return freePageMapNumSequentialPage;+ }++ /**+ * Returns the page number containing the header of this MSF file.+ * @return The header page number.+ */+ protected int getHeaderPageNumber() {+ return HEADER_PAGE_NUMBER;+ }++ /**+ * Returns the stream number containing the directory of this MSF file.+ * @return The directory stream number.+ */+ protected int getDirectoryStreamNumber() {+ return DIRECTORY_STREAM_NUMBER;+ }++ //==============================================================================================+ // Internal Data Methods+ //==============================================================================================+ /**+ * Returns the number of pages contained in this MSF file.+ * @return The number of pages in this MSF.+ */+ protected int getNumPages() {+ return numPages;+ }++ /**+ * Returns the first page number of the current Free Page Map.+ * @return The first page number of the current Free Page Map.+ */+ protected int getCurrentFreePageMapFirstPageNumber() {+ return currentFreePageMapFirstPageNumber;+ }++ /**+ * Performs required initialization of this class, needed before trying to read any+ * Streams. Initialization includes deserializing the remainder of the header as well+ * as stream directory information.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException Upon unknown value for configuration.+ * @throws CancelledException Upon user cancellation.+ */+ protected void deserialize(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ byte[] bytes = new byte[getPageSize()];+ fileReader.read(getHeaderPageNumber(), 0, getPageSize(), bytes, 0);++ PdbByteReader reader = new PdbByteReader(bytes);+ reader.setIndex(getPageSizeOffset());+ pageSize = reader.parseInt();+ parseFreePageMapPageNumber(reader);+ parseCurrentNumPages(reader);+ configureParameters();++ directoryStream.deserializeStreamInfo(reader, monitor);++ // Do not need FreePageMap for just reading files.+ freePageMap.deserialize(monitor);+ // For debug: freePageMap.dump();++ streamTable.deserialize(directoryStream, monitor);+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/AbstractMsfDirectoryStream.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/AbstractMsfDirectoryStream.javanew file mode 100644index 0000000000..2213ce205a--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/AbstractMsfDirectoryStream.java@@ -0,0 +1,46 @@+/* ###+ * 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.pdb.msfreader;++/**+ * An MSF has a stream containing directory information. It is called the Directory stream, and+ * in the older style MSF format, it was the same as a user (@link MsfStream}. Newer versions of+ * MSF needed a higher capacity stream+ * Class extends {@link MsfStream} and represents a more complex Stream used as the Directory Stream+ * for the newer {@link AbstractMsf} (and PDB) format. In the older format, a regular+ * Stream is used as the directory Stream.+ * <P>+ * Note: This extended Stream is not used as a user Stream--just as a higher-capacity directory+ * Stream.+ * <P>+ * The format of how this {@link AbstractMsfDirectoryStream} is persisted to disk is described in+ * the main {@link AbstractMsf} documentation.+ */+abstract class AbstractMsfDirectoryStream extends MsfStream {++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Constructor. Sets the byte length of the Stream to -1. This method is used when the+ * Stream knows/reads its length.+ * @param msf The {@link AbstractMsf} to which the Stream belongs.+ */+ AbstractMsfDirectoryStream(AbstractMsf msf) {+ super(msf);+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/AbstractMsfFreePageMap.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/AbstractMsfFreePageMap.javanew file mode 100644index 0000000000..54765468c0--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/AbstractMsfFreePageMap.java@@ -0,0 +1,118 @@+/* ###+ * 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.pdb.msfreader;++import java.io.IOException;+import java.util.*;++import ghidra.util.LittleEndianDataConverter;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class is the Free Page Map for the Multi-Stream Format File (see Microsoft API). The+ * Free Page Map is a bit-encoding of whether a page within the {@link AbstractMsf} is+ * currently used--for purposes of reusing available pages.+ * <P>+ * This class was crafted to take the place of the formal Free Page Map in a complete+ * (read/write/modify) solution, but might not need to be used for a "reader" technology.+ * <P>+ * NOTE: This implementation is incomplete: we are not processing or accessing the bits yet.+ * <P>+ * ENGINEERING PATH: Use java.util.BitSet for storage after processing. Could probably eliminate+ * the {@code List<Integer> map} storage.+ */+abstract class AbstractMsfFreePageMap {++ //==============================================================================================+ // Internals+ //==============================================================================================+ // Make sure the integral type used (e.g., Integer) is the same on the next two lines.+ private List<Integer> map = new ArrayList<>();+ protected static final int MAP_FIELD_SIZE = Integer.BYTES;++ protected AbstractMsf msf;++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Constructor.+ * @param msf The {@link AbstractMsf} to which this class belongs.+ */+ AbstractMsfFreePageMap(AbstractMsf msf) {+ this.msf = msf;+ }++ /**+ * Debug method to dump some of the internals of this class.+ * @return Data dumped in a pretty format.+ */+ String dump() {+ StringBuilder builder = new StringBuilder();+ builder.append("------------------------------------------------------------");+ builder.append("\npageSize: ");+ builder.append(msf.getPageSize());+ builder.append("\nMSFHeaderBig: ");+ builder.append(isBig());+ for (int i = 0; i < map.size(); i++) {+ builder.append(String.format("\n[%d]: ", i));+ builder.append(map.get(i));+ }+ builder.append("\n------------------------------------------------------------");+ return builder.toString();+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ /**+ * Method used to deserialize this class from disk.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws CancelledException Upon user cancellation.+ */+ abstract void deserialize(TaskMonitor monitor) throws IOException, CancelledException;++ /**+ * Method indicating whether the Free Page Map is a "Big" Free Page Map. Currently, we have+ * at least two types extending this class. One is "Big" (the newer v7.00) and the other is+ * not. The {@link #dump()} method makes use of this method.+ * @return true if it is a "Big" version of this class.+ */+ abstract boolean isBig();++ //==============================================================================================+ // Internal Data Methods+ //==============================================================================================+ /**+ * Internal method for adding a records to the map from the {@code byte[]} argument.+ * @param bytes The {@code byte[]} containing the data.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws CancelledException Upon user cancellation.+ */+ protected void addMap(byte[] bytes, TaskMonitor monitor) throws CancelledException {+ // TODO: If we implement FreePageMap further, then consider passing in a PdbByteReader+ // and using the reader to parse the appropriate Integral types.+ for (int index = 0; index < bytes.length - MAP_FIELD_SIZE; index += MAP_FIELD_SIZE) {+ monitor.checkCanceled();+ byte[] selectedBytes = Arrays.copyOfRange(bytes, index, index + MAP_FIELD_SIZE);+ map.add(LittleEndianDataConverter.INSTANCE.getInt(selectedBytes));+ }+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/AbstractMsfStreamTable.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/AbstractMsfStreamTable.javanew file mode 100644index 0000000000..84e40d73fb--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/AbstractMsfStreamTable.java@@ -0,0 +1,162 @@+/* ###+ * 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.pdb.msfreader;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class represents the the Stream Table used by the Multi-Stream Format File within+ * Windows PDB files.+ * We have intended to implement to the Microsoft PDB API (source); see the API for truth.+ */+abstract class AbstractMsfStreamTable {++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected AbstractMsf msf;+ protected List<MsfStream> mapStreamNumberToStream;++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Constructor.+ * @param msf The {@link AbstractMsf} to which this class is associated.+ */+ AbstractMsfStreamTable(AbstractMsf msf) {+ this.msf = msf;+ mapStreamNumberToStream = new ArrayList<>();+ }++ /**+ * Gets the number of streams in the stream table.+ * @return Number of streams.+ */+ int getNumStreams() {+ return mapStreamNumberToStream.size();+ }++ /**+ * Returns the {@link MsfStream} from the stream table indexed by the streamNumber.+ * @param streamNumber The number ID of the stream to retrieve.+ * @return {@link MsfStream} or {@code null} if no stream for the streamNumber.+ */+ MsfStream getStream(int streamNumber) {+ return mapStreamNumberToStream.get(streamNumber);+ }++ /**+ * Loads Stream Table information from the serial stream contained in the Directory Stream.+ * @param directoryStream The {@link MsfStream} that contains the serial information to be+ * deserialized.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException Upon error with PDB format.+ * @throws CancelledException Upon user cancellation.+ */+ void deserialize(MsfStream directoryStream, TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ // Read whole stream and then take selections from the byte array, as needed.+ int length = directoryStream.getLength();+ byte[] bytes = directoryStream.read(0, length, monitor);+ PdbByteReader reader = new PdbByteReader(bytes);++ // V2.00 has short followed by an unused short. We will presume it 0x0000 and process all+ // four bytes into an integer--hopefully not hurting our first short value.+ // This allows the V2.00 and V7.00 to use the same code for getting numStreams.+ int numStreams = reader.parseInt();+ checkMaxStreamsExceeded(numStreams);++ // Get stream lengths and create streams.+ for (int streamNum = 0; streamNum < numStreams; streamNum++) {+ monitor.checkCanceled();+ int streamLength = reader.parseInt();+ parseExtraField(reader);+ MsfStream stream = new MsfStream(msf, streamLength);+ mapStreamNumberToStream.add(stream);+ }++ // Populate the streams with their page information.+ for (int streamNum = 0; streamNum < numStreams; streamNum++) {+ monitor.checkCanceled();+ MsfStream stream = mapStreamNumberToStream.get(streamNum);+ if (stream != null) {+ stream.deserializePageNumbers(reader, monitor);+ }+ }++ // Now replace the directoryStream in the table with the directoryStream taken from the+ // header, as it is more up-to-date than then entry in the table.+ setStream(msf.getDirectoryStreamNumber(), directoryStream, monitor);+ }++ /**+ * Put a {@link MsfStream} into the Stream Table at the index location. If the index location+ * does not exist, then enough dummy Streams are added to the table to allow the new+ * {@link MsfStream} to be added at the index location.+ * @param index The location (reference number) for the {@link MsfStream} to be added+ * (possibly as a replacement).+ * @param stream The {@link MsfStream} to be added or used to replace an existing Stream.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws CancelledException Upon user cancellation.+ */+ void setStream(int index, MsfStream stream, TaskMonitor monitor) throws CancelledException {+ if (index < mapStreamNumberToStream.size()) {+ mapStreamNumberToStream.set(index, stream);+ }+ else {+ for (int i = mapStreamNumberToStream.size(); i < index; i++) {+ monitor.checkCanceled();+ mapStreamNumberToStream.add(null);+ }+ mapStreamNumberToStream.add(stream);+ }+ }++ private void checkMaxStreamsExceeded(int numStreams) throws PdbException {+ if (numStreams >= getMaxNumStreamsAllowed()) {+ throw new PdbException(+ String.format("Maximum number of MsfStream exceeded (0X%X >= 0X%X)", numStreams,+ getMaxNumStreamsAllowed()));+ }+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ /**+ * Abstract method to reads/parse extra field for each entry.+ * @param reader The {@link PdbByteReader} that contains the data/location to parse.+ * @throws PdbException Upon not enough data left to parse.+ */+ protected abstract void parseExtraField(PdbByteReader reader) throws PdbException;++ /**+ * Returns the maximum number of MsfStreams allowed.+ * @return The maximum number of MsfStreams allowed.+ */+ protected abstract int getMaxNumStreamsAllowed();++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/Msf200.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/Msf200.javanew file mode 100644index 0000000000..2b77d0e4a7--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/Msf200.java@@ -0,0 +1,127 @@+/* ###+ * 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.pdb.msfreader;++import java.io.IOException;+import java.io.RandomAccessFile;+import java.util.Arrays;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;++/**+ * This class is the version of {@link AbstractMsf} for Microsoft v2.00 MSF.+ */+public class Msf200 extends AbstractMsf {++ private static final int PAGE_NUMBER_SIZE = 2;+ private static final byte[] IDENTIFICATION =+ "Microsoft C/C++ program database 2.00\r\n\u001aJG".getBytes();+ // Padding between IDENTIFICATION and pageSize+ private static final int IDENTIFICATION_PADDING = 2;++ private static final int PAGE_SIZE_OFFSET = IDENTIFICATION.length + IDENTIFICATION_PADDING;+ static final int NUM_REQUIRED_DETECTION_BYTES_200 = PAGE_SIZE_OFFSET + 4;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param file The {@link RandomAccessFile} to process as a {@link Msf200}.+ * @throws IOException Upon file IO seek/read issues.+ * @throws PdbException Upon unknown value for configuration.+ */+ public Msf200(RandomAccessFile file) throws IOException, PdbException {+ super(file);+ }++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Static method used to detect the header that belongs to this class.+ * @param file The {@link RandomAccessFile} to process as a {@link Msf200}.+ * @return True if the header for this class is positively identified.+ * @throws IOException Upon file IO seek/read issues.+ */+ static boolean detected(RandomAccessFile file) throws IOException {+ byte[] bytes = new byte[IDENTIFICATION.length];+ file.seek(0);+ file.read(bytes, 0, IDENTIFICATION.length);+ return Arrays.equals(bytes, IDENTIFICATION);+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ void create() {+ streamTable = new MsfStreamTable200(this);+ freePageMap = new MsfFreePageMap200(this);+ directoryStream = new MsfDirectoryStream200(this);+ }++ @Override+ void configureParameters() throws PdbException {+ switch (pageSize) {+ case 0x400:+ log2PageSize = 10;+ freePageMapNumSequentialPage = 8;+ break;+ case 0x800:+ log2PageSize = 11;+ freePageMapNumSequentialPage = 4;+ break;+ case 0x1000:+ log2PageSize = 12;+ freePageMapNumSequentialPage = 1;+ break;+ default:+ throw new PdbException(String.format("Unknown page size: 0X%08X", pageSize));+ }+ pageSizeModMask = pageSize - 1;+ }++ //==============================================================================================+ // Class Internals+ //==============================================================================================+ @Override+ protected void parseFreePageMapPageNumber(PdbByteReader reader) throws PdbException {+ currentFreePageMapFirstPageNumber = reader.parseShort();+ }++ @Override+ protected void parseCurrentNumPages(PdbByteReader reader) throws PdbException {+ numPages = reader.parseShort();+ }++ @Override+ protected int getPageNumberSize() {+ return PAGE_NUMBER_SIZE;+ }++ @Override+ protected byte[] getIdentification() {+ return IDENTIFICATION;+ }++ @Override+ protected int getPageSizeOffset() {+ return PAGE_SIZE_OFFSET;+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/Msf700.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/Msf700.javanew file mode 100644index 0000000000..52b418c58b--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/Msf700.java@@ -0,0 +1,130 @@+/* ###+ * 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.pdb.msfreader;++import java.io.IOException;+import java.io.RandomAccessFile;+import java.util.Arrays;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;++/**+ * This class is the version of {@link AbstractMsf} for Microsoft v7.00 MSF.+ */+public class Msf700 extends AbstractMsf {++ private static final int PAGE_NUMBER_SIZE = 4;+ private static final byte[] IDENTIFICATION = "Microsoft C/C++ MSF 7.00\r\n\u001aDS".getBytes();+ // Padding between magic and pageSize+ private static final int IDENTIFICATION_PADDING = 3;++ private static final int PAGE_SIZE_OFFSET = IDENTIFICATION.length + IDENTIFICATION_PADDING;+ static final int NUM_REQUIRED_DETECTION_BYTES_700 = PAGE_SIZE_OFFSET + 4;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param file The {@link RandomAccessFile} to process as a {@link Msf700}.+ * @throws IOException Upon file IO seek/read issues.+ * @throws PdbException Upon unknown value for configuration.+ */+ public Msf700(RandomAccessFile file) throws IOException, PdbException {+ super(file);+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ void create() {+ streamTable = new MsfStreamTable700(this);+ freePageMap = new MsfFreePageMap700(this);+ directoryStream = new MsfDirectoryStream700(this);+ }++ @Override+ protected void parseFreePageMapPageNumber(PdbByteReader reader) throws PdbException {+ currentFreePageMapFirstPageNumber = reader.parseInt();+ }++ @Override+ protected void parseCurrentNumPages(PdbByteReader reader) throws PdbException {+ numPages = reader.parseInt();+ }++ @Override+ void configureParameters() throws PdbException {+ switch (pageSize) {+ case 0x200:+ log2PageSize = 9;+ freePageMapNumSequentialPage = 1;+ break;+ case 0x400:+ log2PageSize = 10;+ freePageMapNumSequentialPage = 1;+ break;+ case 0x800:+ log2PageSize = 11;+ freePageMapNumSequentialPage = 1;+ break;+ case 0x1000:+ log2PageSize = 12;+ freePageMapNumSequentialPage = 1;+ break;+ default:+ throw new PdbException(String.format("Unknown page size: 0X%08X", pageSize));+ }+ pageSizeModMask = pageSize - 1;+ }++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Static method used to detect the header that belongs to this class.+ * @param file The RandomAccessFile to process as a {@link Msf700}.+ * @return True if the header for this class is positively identified.+ * @throws IOException Upon file IO seek/read issues.+ */+ static boolean detected(RandomAccessFile file) throws IOException {+ byte[] bytes = new byte[IDENTIFICATION.length];+ file.seek(0);+ file.read(bytes, 0, IDENTIFICATION.length);+ return Arrays.equals(bytes, IDENTIFICATION);+ }++ //==============================================================================================+ // Class Internals+ //==============================================================================================+ @Override+ protected int getPageNumberSize() {+ return PAGE_NUMBER_SIZE;+ }++ @Override+ protected byte[] getIdentification() {+ return IDENTIFICATION;+ }++ @Override+ public int getPageSizeOffset() {+ return PAGE_SIZE_OFFSET;+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfDirectoryStream200.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfDirectoryStream200.javanew file mode 100644index 0000000000..f94d296fa2--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfDirectoryStream200.java@@ -0,0 +1,37 @@+/* ###+ * 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.pdb.msfreader;++/**+ * This is the v200 of {@link AbstractMsfDirectoryStream}. It is essentially no different than+ * an {@link MsfStream}.+ * @see AbstractMsfDirectoryStream+ */+class MsfDirectoryStream200 extends AbstractMsfDirectoryStream {++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Constructor. Sets the byte length of the Stream to -1. This method is used when the+ * Stream knows/reads its length.+ * @param msf The {@link AbstractMsf} to which the Stream belongs.+ */+ MsfDirectoryStream200(AbstractMsf msf) {+ super(msf);+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfDirectoryStream700.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfDirectoryStream700.javanew file mode 100644index 0000000000..4746380b62--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfDirectoryStream700.java@@ -0,0 +1,85 @@+/* ###+ * 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.pdb.msfreader;++import java.io.IOException;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This is the v700 of {@link AbstractMsfDirectoryStream}. It is essentially no different than+ * an {@link MsfStream}.+ * @see AbstractMsfDirectoryStream+ */+class MsfDirectoryStream700 extends AbstractMsfDirectoryStream {++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Constructor. Sets the byte length of the Stream to -1. This method is used when the+ * Stream knows/reads its length.+ * @param msf The {@link AbstractMsf} to which the Stream belongs.+ */+ MsfDirectoryStream700(AbstractMsf msf) {+ super(msf);+ }++ /**+ * Deserializes Stream information from the bytes parameter starting at the index offset+ * and uses it to provide necessary information for the Stream to be usable.+ * The information from the deserialization of the byte parameter then points to additional+ * {@link AbstractMsf} pages that need to be read as a subStream and deserialized to create+ * the {@link MsfDirectoryStream700}.+ * <P>+ * Generally, deserialization is part of the step of loading the Stream information from+ * persistent storage (disk).+ * @param reader {@link PdbByteReader} from which to parse the information.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException Upon not enough data left to parse.+ * @throws CancelledException Upon user cancellation.+ */+ @Override+ void deserializeStreamInfo(PdbByteReader reader, TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {++ // Parse the length of the overall (larger) stream.+ deserializeStreamLengthAndMapTableAddress(reader);+ // Calculate the length of the subStream which contains all of the page numbers necessary+ // for the overall (larger) stream and create a subStream with this calculated length.+ int subStreamLength =+ AbstractMsf.floorDivisionWithLog2Divisor(streamLength, msf.getLog2PageSize()) *+ msf.getPageNumberSize();++ MsfStream subStream = new MsfStream(msf, subStreamLength);+ // Parse the page numbers of the subStream.+ subStream.deserializePageNumbers(reader, monitor);+ // Now read the whole subStream, creating a new byte array.+ byte[] bytes = subStream.read(0, subStreamLength, monitor);+ PdbByteReader pageNumberReader = new PdbByteReader(bytes);+ // Next parse the page numbers for the overall (larger) stream from this new byte array+ // that was read from the subStream.+ deserializePageNumbers(pageNumberReader, monitor);+ // The overall (larger) stream has now been set up with the overall stream length+ // and its page numbers parsed.+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfFileReader.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfFileReader.javanew file mode 100644index 0000000000..1c0fe67441--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfFileReader.java@@ -0,0 +1,112 @@+/* ###+ * 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.pdb.msfreader;++import java.io.IOException;+import java.io.RandomAccessFile;++/**+ * This class is responsible for reading pages from a {@link RandomAccessFile} for the+ * {@link AbstractMsf} class and its underlying classes.+ */+class MsfFileReader implements AutoCloseable {++ //==============================================================================================+ // Internals+ //==============================================================================================+ private RandomAccessFile file;+ private AbstractMsf msf;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Closes this class, including its underlying file resources.+ * @throws IOException Under circumstances found when closing a {@link RandomAccessFile}.+ */+ @Override+ public void close() throws IOException {+ if (file != null) {+ file.close();+ }+ }++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Constructor.+ * @param msf The {@link AbstractMsf} for which this class is to be associated.+ * @param file {@link RandomAccessFile} underlying this class.+ */+ MsfFileReader(AbstractMsf msf, RandomAccessFile file) {+ this.msf = msf;+ this.file = file;+ }++ /**+ * Reads a single page of bytes from the {@link AbstractMsf} and writes it into the bytes array.+ * @param page The page number to read from the file.+ * @param bytes The byte[] into which the data is to be written.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ */+ void readPage(int page, byte[] bytes) throws IOException {+ read(page, 0, msf.getPageSize(), bytes, 0);+ }++ /**+ * Reads bytes from the {@link AbstractMsf} into a byte[].+ * @param page The page number within which to start the read.+ * @param offset The byte offset within the page to start the read.+ * @param numToRead The total number of bytes to read.+ * @param bytes The byte[] into which the data is to be written.+ * @param bytesOffset The starting offset within the bytes array in which to start writing.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ */+ void read(int page, int offset, int numToRead, byte[] bytes, int bytesOffset)+ throws IOException {++ if (numToRead < 1) {+ throw new IOException("Must request at least one byte in MSF read");+ }++ if (offset < 0 || offset >= msf.getPageSize()) {+ throw new IOException(String.format("Offset must be in range [0, %d) in for MSF read",+ msf.getPageSize()));+ }++ // Calculate true offset within file.+ long fileOffset = offset + page * (long) msf.getPageSize();++ // Fail if file does not contain enough pages for the read--boundary case that assumes+ // everything beyond the offset in the file belongs to this read.+ if (AbstractMsf.floorDivisionWithLog2Divisor(offset + numToRead,+ msf.getLog2PageSize()) > msf.getNumPages()) {+ throw new IOException("Invalid MSF configuration");+ }++ int numBytesRead = 0;+ file.seek(fileOffset);+ numBytesRead = file.read(bytes, bytesOffset, numToRead);++ if (numBytesRead != numToRead) {+ throw new IOException("Could not read required bytes from MSF");+ }+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfFreePageMap200.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfFreePageMap200.javanew file mode 100644index 0000000000..8ae34e18fe--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfFreePageMap200.java@@ -0,0 +1,53 @@+/* ###+ * 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.pdb.msfreader;++import java.io.IOException;++import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class is the version of {@link AbstractMsfFreePageMap} for Microsoft v2.00 Free Page Map.+ */+class MsfFreePageMap200 extends AbstractMsfFreePageMap {++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Constructor.+ * @param msf The {@link AbstractMsf} to which this class belongs.+ */+ MsfFreePageMap200(AbstractMsf msf) {+ super(msf);+ }++ @Override+ boolean isBig() {+ return false;+ }++ @Override+ void deserialize(TaskMonitor monitor) throws IOException, CancelledException {+ int size = msf.getNumSequentialFreePageMapPages() * msf.getPageSize();+ byte[] bytes = new byte[size];+ MsfFileReader fileReader = msf.fileReader;+ fileReader.read(msf.getCurrentFreePageMapFirstPageNumber(), 0, size, bytes, 0);+ addMap(bytes, monitor);+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfFreePageMap700.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfFreePageMap700.javanew file mode 100644index 0000000000..a8fafe01f2--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfFreePageMap700.java@@ -0,0 +1,71 @@+/* ###+ * 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.pdb.msfreader;++import java.io.IOException;++import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class is the version of {@link AbstractMsfFreePageMap} for Microsoft v7.00 Free Page Map.+ */+class MsfFreePageMap700 extends AbstractMsfFreePageMap {++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Constructor.+ * @param msf The {@link AbstractMsf} to which this class belongs.+ */+ MsfFreePageMap700(AbstractMsf msf) {+ super(msf);+ }++ @Override+ boolean isBig() {+ return true;+ }++ @Override+ void deserialize(TaskMonitor monitor) throws IOException, CancelledException {+ // Calculate the number of pages that the FreePageMap occupies on disk.+ int log2BitsPerPage = msf.getLog2PageSize() + 3; // 3 = log2(bitsperbyte)+ long freePageMapNumPages =+ AbstractMsf.floorDivisionWithLog2Divisor(msf.getNumPages(), log2BitsPerPage);++ // Get the First page number of the FreePageMap on disk.+ int nextPageNumber = msf.getCurrentFreePageMapFirstPageNumber();++ // Read the FreePageMap, which is dispersed across the file (see note below).+ MsfFileReader fileReader = msf.fileReader;+ int pageSize = msf.getPageSize();+ while (freePageMapNumPages > 0) {+ monitor.checkCanceled();+ byte[] bytes = new byte[pageSize];+ fileReader.read(nextPageNumber, 0, pageSize, bytes, 0);+ addMap(bytes, monitor);+ freePageMapNumPages--;+ // This is correct. Each page of the FreePageMap700 is located at pageSize number+ // of pages away from the last page. So if the first page of the FreePageMap700+ // is page 1, and if the pageSize is 4096, then the next page used as part of+ // the FreePageMap700 is page 4097. FreePageMap200 is different in that its data+ // resides sequentially on disk.+ nextPageNumber += pageSize;+ }+ }+}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfParser.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfParser.javanew file mode 100644index 0000000000..6debf53d5b--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfParser.java@@ -0,0 +1,64 @@+/* ###+ * 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.pdb.msfreader;++import java.io.IOException;+import java.io.RandomAccessFile;++import ghidra.pdb.PdbException;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * Parser for detecting the appropriate {@link AbstractMsf} format for the filename given.+ * It then creates and returns the appropriate {@link AbstractMsf} object.+ */+public class MsfParser {++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Detects, creates, and returns the appropriate {@link AbstractMsf} object found for+ * the filename given.+ * @param filename Filename of the file to process.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @return Derived {@link AbstractMsf} object.+ * @throws IOException For file I/O reasons+ * @throws PdbException If an appropriate object cannot be created.+ * @throws CancelledException Upon user cancellation.+ */+ public static AbstractMsf parse(String filename, TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ AbstractMsf msf;+ RandomAccessFile file = new RandomAccessFile(filename, "r");+ if (Msf200.detected(file)) {+ msf = new Msf200(file);+ }+ else if (Msf700.detected(file)) {+ msf = new Msf700(file);+ }+ else {+ // Must close the file here. In cases where MSF is created, the MSF takes+ // responsibility for closing the file.+ file.close();+ throw new PdbException("MSF format not detected");+ }+ msf.deserialize(monitor);+ return msf;+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfStream.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfStream.javanew file mode 100644index 0000000000..4f6441fd75--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfStream.java@@ -0,0 +1,276 @@+/* ###+ * 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.pdb.msfreader;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.util.exception.AssertException;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * Class representing a Stream within an {@link AbstractMsf}--see its write-up.+ * <P>+ * The stream can only be read, as it is part of a reader capability, not a read/write/modify+ * capability.+ * <P>+ * The Stream can get initialized through a couple of mechanisms, but the essential information+ * is the stream length, the map of stream page numbers to file page numbers, and the+ * referenced {@link AbstractMsf} to which it belongs, which contains most other+ * information that it needs.+ */+public class MsfStream {++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected int streamLength;+ protected List<Integer> pageList = new ArrayList<>();+ protected AbstractMsf msf;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Returns the length of the Stream.+ * @return Byte-length of Stream.+ */+ public int getLength() {+ return streamLength;+ }++ /**+ * Reads numToRead bytes from the stream starting at streamOffset within the stream.+ * Returns the byte array containing the read information. If not all bytes are available+ * to be read, an IOException will be thrown.+ * @param streamOffset Location within the stream from where to start reading bytes.+ * @param numToRead Number of bytes to read from the stream.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @return byte[] containing the bytes read.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws CancelledException Upon user cancellation.+ */+ public byte[] read(int streamOffset, int numToRead, TaskMonitor monitor)+ throws IOException, CancelledException {+ if (numToRead <= 0) {+ return null;+ }+ byte[] bytes = new byte[numToRead];+ read(streamOffset, bytes, 0, numToRead, monitor);+ return bytes;+ }++ /**+ * Reads numToRead bytes from the stream starting at streamOffset within the stream.+ * The bytes are written into the bytes array starting at the bytesOffset location.+ * If not all bytes are available to be read, an IOException will be thrown.+ * @param streamOffset Location within the stream from where to start reading bytes.+ * @param bytes The array into which to write the data.+ * @param bytesOffset The location within byte array at which to start writing data.+ * @param numToRead Number of bytes to read from the stream.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws CancelledException Upon user cancellation.+ */+ public void read(int streamOffset, byte[] bytes, int bytesOffset, int numToRead,+ TaskMonitor monitor) throws IOException, CancelledException {+ if (streamOffset < 0 || streamOffset > streamLength) {+ throw new IOException("Offset out of range.");+ }+ if (numToRead > streamLength - streamOffset) {+ throw new IOException("Not enough data left.");+ }+ if (numToRead <= 0) {+ return;+ }++ int remainingByteCount = numToRead;+ int pageNumber = streamOffset >> msf.getLog2PageSize();+ int offsetIntoPage = streamOffset & msf.getPageSizeModMask();++ // Read any partial page at beginning first.+ if (offsetIntoPage != 0) {+ int firstNumToRead = Math.min(msf.getPageSize() - offsetIntoPage, remainingByteCount);+ msf.fileReader.read(pageList.get(pageNumber), offsetIntoPage, firstNumToRead, bytes,+ bytesOffset);+ if ((remainingByteCount - firstNumToRead) > remainingByteCount) {+ throw new IOException("Integer count underflow when preparing to read.");+ }+ remainingByteCount -= firstNumToRead;+ pageNumber++;+ bytesOffset += firstNumToRead;+ }+ // Read remaining pages, including last as possible partial page.+ // Outer loop iterates over possible non-sequential groups.+ while (remainingByteCount > 0) {+ monitor.checkCanceled();+ // Inner loop groups together sequential pages into one big read.+ int firstSequentialPageNumber = pageList.get(pageNumber);+ int lastSequentialPageNumber = firstSequentialPageNumber;+ int numToReadInSequentialPages = 0;+ do {+ monitor.checkCanceled();+ pageNumber++;+ lastSequentialPageNumber++;+ int numToReadInPage = Math.min(msf.getPageSize(), remainingByteCount);+ numToReadInSequentialPages += numToReadInPage;+ remainingByteCount -= numToReadInPage;+ }+ while (remainingByteCount > 0 && pageList.get(pageNumber) == lastSequentialPageNumber);+ msf.fileReader.read(firstSequentialPageNumber, 0, numToReadInSequentialPages, bytes,+ bytesOffset);+ bytesOffset += numToReadInSequentialPages;+ }+ }++ /**+ * Debug method to dump the PDB Directory in a pretty format to String.+ * @param maxOut Maximum number of bytes to output.+ * @return {@link String} containing the pretty output.+ */+ public String dump(int maxOut) {+ int outputLength = Math.min(getLength(), maxOut);+ StringBuilder builder = new StringBuilder();+ builder.append("Length: ");+ builder.append(getLength());+ builder.append(String.format(" (0x%08x)", getLength()));+ // If length is zero or negative (e.g., -1), done.+ if (outputLength <= 0) {+ return "";+ }+ byte[] bytes = new byte[outputLength];+ try {+ read(0, bytes, 0, outputLength, TaskMonitor.DUMMY);+ }+ catch (IOException e) {+ // Should not occur. We limited our request to be <= the Stream length.+ throw new AssertException("Total bonkers: PDB Stream does not contain advertised data");+ }+ catch (CancelledException e) {+ // Should not occur. We limited our request to be <= the Stream length.+ throw new AssertException("CancelledException Thrown");+ }+ for (int i = 0; i < outputLength;) {+ builder.append(String.format("\n%06x", i));+ for (int j = 0; (j < 16) && (i < outputLength); j++, i++) {+ builder.append(String.format(" %02x", bytes[i]));+ }+ }+ return builder.toString();+ }++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Package-protected constructor of a PDB Stream. Sets the byte length of the+ * Stream to -1. This method is used when the Stream knows/reads its length.+ * @param msf The {@link AbstractMsf} to which the Stream belongs.+ */+ MsfStream(AbstractMsf msf) {+ streamLength = -1;+ this.msf = msf;+ }++ /**+ * Package-protected constructor of a PDB Stream. This method is used when the+ * stream length comes from an external table.+ * @param msf The {@link AbstractMsf} to which the Stream belongs.+ * @param streamLength The byte length of the Stream.+ */+ MsfStream(AbstractMsf msf, int streamLength) {+ this.msf = msf;+ this.streamLength = streamLength;+ }++ /**+ * Deserializes Stream Length and an extra 4-byte field (which might be the address of the+ * map when it was previously stored in memory) from the bytes parameter starting at the+ * index offset and uses it to provide necessary information for the Stream to be usable.+ * Generally, deserialization is part of the step of loading the Stream information from+ * persistent storage (disk).+ * @param reader {@link PdbByteReader} from which to parse the information.+ * @throws PdbException Upon not enough data left to parse.+ */+ void deserializeStreamLengthAndMapTableAddress(PdbByteReader reader) throws PdbException {+ streamLength = reader.parseInt();+ // The next 4 bytes might be an address of the map table that got pushed to disk.+ reader.parseInt();+ }++ /**+ * Deserializes Stream page number information from the bytes parameter starting at the+ * index offset and uses it to provide necessary information for the Stream to be usable.+ * Generally, deserialization is part of the step of loading the Stream information from+ * persistent storage (disk).+ * @param reader {@link PdbByteReader} from which to parse the information.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws PdbException Upon not enough data left to parse.+ * @throws CancelledException Upon user cancellation.+ */+ void deserializePageNumbers(PdbByteReader reader, TaskMonitor monitor)+ throws PdbException, CancelledException {+ // This calculations works fine for streamLength = 0+ // and even streamLength = -1 (0xffffffff).+ int numPages =+ AbstractMsf.floorDivisionWithLog2Divisor(streamLength, msf.getLog2PageSize());+ if (msf.getPageNumberSize() == 2) {+ for (int i = 0; i < numPages; i++) {+ monitor.checkCanceled();+ int pageNumber = reader.parseUnsignedShortVal();+ if (pageNumber == 0) {+ break;+ }+ pageList.add(pageNumber);+ }+ }+ else if (msf.getPageNumberSize() == 4) {+ for (int i = 0; i < numPages; i++) {+ monitor.checkCanceled();+ int pageNumber = reader.parseInt();+ if (pageNumber == 0) {+ break;+ }+ pageList.add(pageNumber);+ }+ }+ }++ /**+ * Deserializes Stream information from the bytes parameter starting at the index offset+ * and uses it to provide necessary information for the Stream to be usable.+ * Generally, deserialization is part of the step of loading the Stream information from+ * persistent storage (disk).+ * @param reader {@link PdbByteReader} from which to parse the information.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException Upon not enough data left to parse.+ * @throws CancelledException Upon user cancellation.+ */+ void deserializeStreamInfo(PdbByteReader reader, TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ deserializeStreamLengthAndMapTableAddress(reader);+ deserializePageNumbers(reader, monitor);+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfStreamTable200.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfStreamTable200.javanew file mode 100644index 0000000000..77ab76d15e--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfStreamTable200.java@@ -0,0 +1,50 @@+/* ###+ * 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.pdb.msfreader;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;++/**+ * This class is the version of {@link AbstractMsfStreamTable} for Microsoft v2.00 MSF.+ */+class MsfStreamTable200 extends AbstractMsfStreamTable {++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Constructor.+ * @param msf The MSF associated for this class.+ */+ MsfStreamTable200(AbstractMsf msf) {+ super(msf);+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ protected void parseExtraField(PdbByteReader reader) throws PdbException {+ reader.parseInt(); // Extra unknown field.+ }++ @Override+ protected int getMaxNumStreamsAllowed() {+ return 0x1000;+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfStreamTable700.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfStreamTable700.javanew file mode 100644index 0000000000..eba9abd0ac--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/msfreader/MsfStreamTable700.java@@ -0,0 +1,49 @@+/* ###+ * 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.pdb.msfreader;++import ghidra.pdb.PdbByteReader;++/**+ * This class is the version of {@link AbstractMsfStreamTable} for Microsoft v7.00 MSF.+ */+class MsfStreamTable700 extends AbstractMsfStreamTable {++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Constructor.+ * @param msf The MSF associated for this class.+ */+ MsfStreamTable700(AbstractMsf msf) {+ super(msf);+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ protected void parseExtraField(PdbByteReader reader) {+ // Do nothing+ }++ @Override+ protected int getMaxNumStreamsAllowed() {+ return 0x10000;+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractDatabaseInterface.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractDatabaseInterface.javanew file mode 100644index 0000000000..6f127cee6b--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractDatabaseInterface.java@@ -0,0 +1,528 @@+/* ###+ * 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.pdb.pdbreader;++import java.io.IOException;+import java.io.Writer;+import java.util.ArrayList;+import java.util.List;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.pdb.msfreader.MsfStream;+import ghidra.pdb.pdbreader.symbol.AbstractMsSymbol;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class represents Database Interface component of a PDB file. This class is only+ * suitable for reading; not for writing or modifying a PDB.+ * <P>+ * We have intended to implement according to the Microsoft PDB API (source); see the API for+ * truth.+ */+public abstract class AbstractDatabaseInterface {++ protected static final int VERSION_NUMBER_SIZE = 4;++ public static final int STREAM_NUMBER_SIZE = 2;+ public static final int LENGTH_SIZE = 4;++ /**+ * These are Section Contribution Versions (SCV) 6.00 and 14.00. We are building to the MSFT+ * API. They have chosen to mix in some magic along the way for these--perhaps to ensure that+ * the the value will be a large unsigned 32-bit or a negative 32-bit. We store the value+ * in a java long, so that we can maintain the signed-ness of the values, if necessary. MSFT+ * is probably trying to prevent these values from being mimicked by data in the versions+ * prior to v 6.00.+ */+ private static final long SCV600 = 0xeffe0000L + 19970605L;+ private static final long SCV1400 = 0xeffe0000L + 20140516L;++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected AbstractPdb pdb;+ protected int streamNumber;++ protected long versionNumber = 0; // unsigned 32-bit++ protected int streamNumberGlobalStaticSymbols = 0; // unsigned 16-bit+ protected int streamNumberPublicStaticSymbols = 0; // unsigned 16-bit+ protected int streamNumberSymbolRecords = 0; // unsigned 16-bit++ protected int lengthModuleInformationSubstream = 0; // signed 32-bit+ protected int lengthSectionContributionSubstream = 0; // signed 32-bit //TODO: also in parent.+ protected int lengthSectionMap = 0; // signed 32-bit+ protected int lengthFileInformation = 0; // signed 32-bit++ protected List<AbstractModuleInformation> moduleInformationList = new ArrayList<>();+ protected List<AbstractSectionContribution> sectionContributionList = new ArrayList<>();+ protected List<SegmentMapDescription> segmentMapList = new ArrayList<>();++ protected SymbolRecords symbolRecords;+ protected GlobalSymbolInformation globalSymbolInformation;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param pdb {@link AbstractPdb} that owns this Database Interface.+ * @param streamNumber The stream number of the stream containing the Database Interface.+ */+ public AbstractDatabaseInterface(AbstractPdb pdb, int streamNumber) {+ this.pdb = pdb;+ this.streamNumber = streamNumber;+ symbolRecords = new SymbolRecords(pdb);+ }++ /**+ * Returns the number of bytes needed to store the version number.+ * @return The number of bytes needed to store the version number.+ */+ public static int getVersionNumberSize() {+ return VERSION_NUMBER_SIZE;+ }++ /**+ * Deserializes the {@link AbstractDatabaseInterface}-based instance.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @return The version number of the Database Interface.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException upon error parsing a field.+ * @throws CancelledException Upon user cancellation.+ */+ public long deserialize(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ MsfStream stream = pdb.getMsf().getStream(streamNumber);+ byte[] bytes = stream.read(0, stream.getLength(), monitor);+ PdbByteReader reader = new PdbByteReader(bytes);+ deserializeHeader(reader);+ deserializeInternalSubstreams(reader);+ deserializeAdditionalSubstreams(monitor);++ return versionNumber;+ }++ /**+ * Returns the list of {@link AbstractModuleInformation}, indexed by the module number.+ * @return List of {@link AbstractModuleInformation}.+ */+ public List<AbstractModuleInformation> getModuleInformationList() {+ return moduleInformationList;+ }++ /**+ * Returns the {@link AbstractModuleInformation}, based on the moduleNumber.+ * @param moduleNumber The module number being requested.+ * @return {@link AbstractModuleInformation} for the moduleNumber provided.+ * @throws PdbException Upon moduleNumber out of range or no module information.+ */+ public AbstractModuleInformation getModuleInformation(int moduleNumber) throws PdbException {+ if (moduleNumber < 0 || moduleNumber > moduleInformationList.size()) {+ throw new PdbException("ModuleNumber out of range: " + moduleNumber);+ }+ AbstractModuleInformation moduleInfo = moduleInformationList.get(moduleNumber);+ if (moduleInfo == null) {+ throw new PdbException("Null AbstractModuleInformation");+ }+ return moduleInfo;+ }++ /**+ * Return a comprehensive list of {@link AbstractMsSymbol}s, including from modules.+ * <P>+ * <P>+ * Note: This is Ghidra-added functionality that might eventually go away; it is implemented+ * for investigating how to mine the information we need from the PDB. This might go away in+ * future implementations.+ * @return Symbols seen.+ */+ public List<AbstractMsSymbol> getComprehensiveSymbolsList() {+ return symbolRecords.getComprehensiveSymbolsList();+ }++ /**+ * Returns a specific {@link AbstractMsSymbol} based on a Ghidra-specific recordNumber+ * parameter. The record number is not part of a normal PDB, but we assigned a one-up+ * numbering.+ * <P>+ * Note: This is Ghidra-added functionality that might eventually go away; it is implemented+ * for investigating how to mine the information we need from the PDB. This might go away in+ * future implementations.+ * @param recordNumber The Ghidra-specific record number for the {@link AbstractMsSymbol}.+ * @return {@link AbstractMsSymbol} for the recordNumber.+ */+ public AbstractMsSymbol getComprehensiveSymbolRecord(int recordNumber) {+ return symbolRecords.getComprehensiveSymbolRecord(recordNumber);+ }++ /**+ * Returns the list of {@link AbstractMsSymbol} global symbols. TODO: check if global and+ * static.+ * @return {@link AbstractMsSymbol} global symbols. TODO: check if global and static.+ */+ public List<AbstractMsSymbol> getSymbolsList() {+ return symbolRecords.getSymbolsList();+ }++ /**+ * Returns list of {@link AbstractMsSymbol} for the module specified.+ * @param moduleNumber The number ID of the module for which to return the list.+ * @return {@link AbstractMsSymbol} symbols in the specified module.+ */+ public List<AbstractMsSymbol> getModuleSymbolLists(int moduleNumber) {+ return symbolRecords.getModuleSymbolLists(moduleNumber);+ }++ /**+ * Returns list of {@link AbstractSectionContribution} for this Database Interface.+ * @return List of {@link AbstractSectionContribution}.+ */+ public List<AbstractSectionContribution> getSectionContributionList() {+ return sectionContributionList;+ }++ /**+ * Returns list of {@link SegmentMapDescription} for this Database Interface.+ * @return List of {@link SegmentMapDescription}.+ */+ public List<SegmentMapDescription> getSegmentMapList() {+ return segmentMapList;+ }++ /**+ * Returns {@link SymbolRecords} component for this Database Interface.+ * @return {@link SymbolRecords} component.+ */+ public SymbolRecords getSymbolRecords() {+ return symbolRecords;+ }++ /**+ * Returns {@link GlobalSymbolInformation} component for this Database Interface.+ * @return {@link GlobalSymbolInformation} component.+ */+ public GlobalSymbolInformation getGlobalSymbolInformation() {+ return globalSymbolInformation;+ }++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Returns the stream number for the GlobalSymbols component.+ * @return Stream number.+ */+ int getGlobalSymbolsStreamNumber() {+ return streamNumberGlobalStaticSymbols;+ }++ /**+ * Returns the stream number for the PublicStaticSymbols component.+ * @return Stream number.+ */+ int getPublicStaticSymbolsStreamNumber() {+ return streamNumberPublicStaticSymbols;+ }++ /**+ * Returns the stream number for {@link SymbolRecords} component.+ * @return Stream number.+ */+ int getSymbolRecordsStreamNumber() {+ return streamNumberSymbolRecords;+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ /**+ * Deserializes the Header.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @throws PdbException Upon not enough data left to parse.+ */+ protected abstract void deserializeHeader(PdbByteReader reader) throws PdbException;++ /**+ * Deserializes the SubStreams internal to the Database Interface stream.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @throws PdbException upon error parsing a field.+ */+ protected abstract void deserializeInternalSubstreams(PdbByteReader reader) throws PdbException;++ /**+ * Deserializes the AdditionalSubstreams components.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException upon error parsing a field.+ * @throws CancelledException Upon user cancellation.+ */+ protected abstract void deserializeAdditionalSubstreams(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException;++ /**+ * Deserializes/Processes the appropriate {@link AbstractModuleInformation} flavor.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @param skip Skip over the data in the {@link PdbByteReader}.+ * @throws PdbException upon error parsing a field.+ */+ protected abstract void processModuleInformation(PdbByteReader reader, boolean skip)+ throws PdbException;++ /**+ * Dumps the Header. This method is for debugging only.+ * @param writer {@link Writer} to which to write the debug dump.+ * @throws IOException On issue writing to the {@link Writer}.+ */+ protected abstract void dumpHeader(Writer writer) throws IOException;++ /**+ * Dumps the Internal Substreams. This method is for debugging only.+ * @param writer {@link Writer} to which to write the debug dump.+ * @throws IOException On issue writing to the {@link Writer}.+ */+ protected abstract void dumpInternalSubstreams(Writer writer) throws IOException;++ //==============================================================================================+ // Internal Data Methods+ //==============================================================================================+ /**+ * Deserializes/Processes the SectionContributions component.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @param skip Skip over the data in the {@link PdbByteReader}.+ * @throws PdbException Upon not enough data left to parse.+ */+ protected void processSectionContributions(PdbByteReader reader, boolean skip)+ throws PdbException {+ if (lengthSectionContributionSubstream == 0) {+ return;+ }+ if (skip) {+ reader.skip(lengthSectionContributionSubstream);+ return;+ }+ PdbByteReader substreamReader =+ reader.getSubPdbByteReader(lengthSectionContributionSubstream);+ //System.out.println(substreamReader.dump(0x200));+ long version = substreamReader.parseUnsignedIntVal();+ if (version == SCV1400) {+ //long version2 = substreamReader.parseUnsignedIntVal();+ while (substreamReader.hasMore()) {+ AbstractSectionContribution sectionContribution = new SectionContribution1400();+ sectionContribution.deserialize(substreamReader);+ sectionContributionList.add(sectionContribution);+ }+ }+ else if (version == SCV600) {+ //long version2 = substreamReader.parseUnsignedIntVal();+ while (substreamReader.hasMore()) {+ AbstractSectionContribution sectionContribution = new SectionContribution600();+ sectionContribution.deserialize(substreamReader);+ sectionContributionList.add(sectionContribution);+ }+ }+ //TODO: Don't know when SectionContribution200 are the type to use. Dont' know if+ // this part could be the default of processSectionContribs within+ // DatabaseInterface and if the above part (test for SVC600 and SVC1400 would+ // be the override method for DatabaseInformationNew.+ else {+ while (substreamReader.hasMore()) {+ AbstractSectionContribution sectionContribution = new SectionContribution400();+ sectionContribution.deserialize(substreamReader);+ sectionContributionList.add(sectionContribution);+ }+ }+ }++ // TODO: unused value numSegLog?+ // Note: this is SegmentMap or SectionMap (API structs are segment; API code is Section)+ // Suppress "unused" for numSegLog+ /**+ * Deserializes/Processes the {@link SegmentMapDescription}.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @param skip Skip over the data in the {@link PdbByteReader}.+ * @throws PdbException Upon not enough data left to parse.+ */+ @SuppressWarnings("unused")+ protected void processSegmentMap(PdbByteReader reader, boolean skip) throws PdbException {+ if (lengthSectionMap == 0) {+ return;+ }+ if (skip) {+ reader.skip(lengthSectionMap);+ return;+ }+ PdbByteReader substreamReader = reader.getSubPdbByteReader(lengthSectionMap);+ //System.out.println(substreamReader.dump(0x200));+ // Process header+ int numSegments = substreamReader.parseUnsignedShortVal();+ int numSegLog = substreamReader.parseUnsignedShortVal();+ // Process records+ while (substreamReader.hasMore()) {+ SegmentMapDescription segment = new SegmentMapDescription();+ segment.deserialize(substreamReader);+ segmentMapList.add(segment);+ }+ if (numSegments != segmentMapList.size()) {+ assert false;+ }+ }++ /**+ * Deserializes/Processes the FileInformation.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @param skip Skip over the data in the {@link PdbByteReader}.+ * @throws PdbException upon error parsing filename.+ */+ @SuppressWarnings("unused") // pmod is not used below+ protected void processFileInformation(PdbByteReader reader, boolean skip) throws PdbException {+ if (lengthFileInformation == 0) {+ return;+ }+ if (skip) {+ reader.skip(lengthFileInformation);+ return;+ }+ PdbByteReader substreamReader = reader.getSubPdbByteReader(lengthFileInformation);+ //System.out.println(subStreamReader.dump());+ int numInformationModules = substreamReader.parseUnsignedShortVal();+ if (numInformationModules != moduleInformationList.size()) {+ assert false;+ }+ int numRefs = substreamReader.parseUnsignedShortVal();+ int x = 0;+ for (int i = 0; i < numInformationModules; i++) {+ int refIndex = substreamReader.parseUnsignedShortVal();+ AbstractModuleInformation module = moduleInformationList.get(i);+ int num = module.getNumFilesContributing();+ if (refIndex != x) {+ assert false;+ }+ x += num;+ }+ for (int i = 0; i < numInformationModules; i++) {+ // TODO: Is there anything we can do with this?+ int pmod = substreamReader.parseUnsignedShortVal();+ }+ int count = 0;+ for (int i = 0; i < numInformationModules; i++) {+ AbstractModuleInformation module = moduleInformationList.get(i);+ int num = module.getNumFilesContributing();+ for (int j = 0; j < num; j++) {+ int index = substreamReader.parseInt();+ module.offsetsArray.add(index);+ count++;+ }+ }+ if (count != numRefs) {+ assert false;+ }+ //Following is read in and added to ModuleInformation+ byte[] fileNamesBytes = substreamReader.parseBytesRemaining();+ PdbByteReader fileNameReader = new PdbByteReader(fileNamesBytes);++ //System.out.println(fileNameReader.dump());+ for (int i = 0; i < numInformationModules; i++) {+ AbstractModuleInformation module = moduleInformationList.get(i);+ List<Integer> offsetsArray = module.getOffsetsArray();+ List<String> filenameArray = module.getFilenamesArray();+ for (int j = 0; j < offsetsArray.size(); j++) {+ int offset = offsetsArray.get(j);+ //System.out.println(String.format("%04x", offset));+ fileNameReader.setIndex(offset);+ String filename = fileNameReader.parseNullTerminatedString();+ filenameArray.add(filename);+ //System.out.println(filename);+ }+ }+ }++ /**+ * Debug method for dumping information from this {@link AbstractDatabaseInterface}-based+ * instance.+ * @param writer {@link Writer} to which to dump the information.+ * @throws IOException Upon IOException writing to the {@link Writer}.+ */+ protected void dump(Writer writer) throws IOException {+ writer.write("DatabaseInterfaceHeader-------------------------------------\n");+ dumpHeader(writer);+ writer.write("\nEnd DatabaseInterfaceHeader---------------------------------\n");+ writer.write("DatabaseInterfaceInternalSubstreams-------------------------\n");+ dumpInternalSubstreams(writer);+ writer.write("\nEnd DatabaseInterfaceInternalSubstreams---------------------\n");+ writer.write("DatabaseInterfaceAdditionalSubstreams-----------------------\n");+ dumpAdditionalSubstreams(writer);+ writer.write("\nEnd DatabaseInterfaceAdditionalSubstreams-------------------\n");+ }++ /**+ * Debug method for dumping additional substreams from this+ * {@link AbstractDatabaseInterface}-based instance.+ * @param writer {@link Writer} to which to dump the information.+ * @throws IOException Upon IOException writing to the {@link Writer}.+ */+ protected void dumpAdditionalSubstreams(Writer writer) throws IOException {+ symbolRecords.dump(writer);+ //builder.append("\n");+ //builder.append(globalSymbolInformation.dump());+ }++ /**+ * Debug method for dumping module information for all of the {@link AbstractModuleInformation}+ * modules from this {@link AbstractDatabaseInterface}-based instance.+ * @param writer {@link Writer} to which to dump the information.+ * @throws IOException Upon IOException writing to the {@link Writer}.+ */+ protected void dumpModuleInformation(Writer writer) throws IOException {+ for (AbstractModuleInformation information : moduleInformationList) {+ writer.write(information.dump());+ writer.write("\n");+ }+ }++ /**+ * Debug method for dumping section contribution for all of the+ * {@link AbstractSectionContribution} components from this+ * {@link AbstractDatabaseInterface}-based instance.+ * @param writer {@link Writer} to which to dump the information.+ * @throws IOException Upon IOException writing to the {@link Writer}.+ */+ protected void dumpSectionContributions(Writer writer) throws IOException {+ for (AbstractSectionContribution contribution : sectionContributionList) {+ writer.write(contribution.dump());+ writer.write("\n");+ }+ }++ /**+ * Debug method for dumping segment map information for all of the+ * {@link SegmentMapDescription} components from this {@link AbstractDatabaseInterface}-based+ * instance.+ * @param writer {@link Writer} to which to dump the information.+ * @throws IOException Upon IOException writing to the {@link Writer}.+ */+ protected void dumpSegmentMap(Writer writer) throws IOException {+ for (SegmentMapDescription description : segmentMapList) {+ writer.write(description.dump());+ writer.write("\n");+ }+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractModuleInformation.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractModuleInformation.javanew file mode 100644index 0000000000..692aa1ac8b--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractModuleInformation.java@@ -0,0 +1,220 @@+/* ###+ * 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.pdb.pdbreader;++import java.util.ArrayList;+import java.util.List;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;++/**+ * This class represents Module Information component of a PDB file. This class is only+ * suitable for reading; not for writing or modifying a PDB.+ * <P>+ * We have intended to implement according to the Microsoft PDB API (source); see the API for+ * truth.+ */+public abstract class AbstractModuleInformation {++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected long modulePointer;+ protected AbstractSectionContribution sectionContribution;+ protected boolean writtenSinceOpen;+ // TODO: consider what to do (gets parsed for 600 between 500 items. Want only in 600,+ // but would have to break up the deserialize and dumpInternal methods. Issue might be,+ // however, that we want to see the default "false" value for 500 (see API).+ protected boolean ecSymbolicInformationEnabled;+ protected int bitfield;+ protected int spare;+ protected int indexToTSMList;+ protected int streamNumberDebugInformation; // unsigned 16-bit+ protected int sizeLocalSymbolsDebugInformation; //signed 32-bit+ protected int sizeLineNumberDebugInformation; //signed 32-bit+ protected int sizeC13StyleLineNumberInformation; //signed 32-bit+ protected int numFilesContributing; // unsigned 16-bit+ protected List<Integer> offsetsArray = new ArrayList<>(); // signed 32-bit+ protected List<String> filenamesArray = new ArrayList<>();++ protected String moduleName;+ protected String objectFileName;++ protected long nameIndexSourceFile; // unsigned 32-bit+ protected long nameIndexCompilerPdbPath; // unsigned 32-bit++ //==============================================================================================+ // API+ //==============================================================================================+ public AbstractModuleInformation() {+ }++ /**+ * Returns the number of files contributing to the module.+ * @return Number of files.+ */+ public int getNumFilesContributing() {+ return numFilesContributing;+ }++ /**+ * Returns list of offsets for the module.+ * @return Offsets.+ */+ public List<Integer> getOffsetsArray() {+ return offsetsArray;+ }++ /**+ * Returns list of file names for the module.+ * @return File names.+ */+ public List<String> getFilenamesArray() {+ return filenamesArray;+ }++ /**+ * Returns the stream number containing debug information.+ * @return Stream number.+ */+ public int getStreamNumberDebugInformation() {+ return streamNumberDebugInformation;+ }++ /**+ * Returns the size of the local symbols debug information.+ * @return Size of the local symbosl debug information.+ */+ public int getSizeLocalSymbolsDebugInformation() {+ return sizeLocalSymbolsDebugInformation;+ }++ /**+ * Returns the name of the module.+ * @return Name of the module.+ */+ public String getModuleName() {+ return moduleName;+ }++ /**+ * Returns {@link AbstractSectionContribution} of the module.+ * @return {@link AbstractSectionContribution} of the module.+ */+ public AbstractSectionContribution getSectionContribution() {+ return sectionContribution;+ }++ //==============================================================================================+ // Internal Data Methods+ //==============================================================================================+ /**+ * Deserializes the module.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @throws PdbException upon error parsing a string name.+ */+ protected void deserialize(PdbByteReader reader) throws PdbException {+ //System.out.println(reader.dump(0x200));+ modulePointer = reader.parseUnsignedIntVal();+ sectionContribution.deserialize(reader);+ bitfield = reader.parseUnsignedShortVal();+ writtenSinceOpen = ((bitfield & 0x01) == 0x01);+ bitfield >>= 1;+ spare = bitfield & 0x07f;+ bitfield >>= 1;+ indexToTSMList = bitfield & 0x0ff;+ ecSymbolicInformationEnabled = false;+ streamNumberDebugInformation = reader.parseUnsignedShortVal();+ sizeLocalSymbolsDebugInformation = reader.parseInt();+ sizeLineNumberDebugInformation = reader.parseInt();+ sizeC13StyleLineNumberInformation = reader.parseInt();+ numFilesContributing = reader.parseUnsignedShortVal(); //unsigned 16-bit+ reader.align4();+ reader.parseBytes(4); //placeholder for offsetsArray // unsigned 32-bit (unused?)+ parseAdditionals(reader);++// for (int i = 0; i < numFilesContributing; i++) {+// int offsetBufFilename = reader.parseInt();+// offsetsArray.add(offsetBufFilename);+// }+ reader.align4();+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ /**+ * Deserializes the Additionals. Abstract method filled in by instances to parse additional+ * data pertinent to themselves.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @throws PdbException upon error parsing a string name.+ */+ protected abstract void parseAdditionals(PdbByteReader reader) throws PdbException;++ /**+ * Dumps the Additionals. This method is for debugging only.+ * @return {@link String} of pretty output.+ */+ protected abstract String dumpAdditionals();++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Dumps this module. This method is for debugging only.+ * @return {@link String} of pretty output.+ */+ String dump() {+ StringBuilder builder = new StringBuilder();+ builder.append("ModuleInformation-------------------------------------------\n");+ builder.append("modulePointer: ");+ builder.append(modulePointer);+ builder.append("\n");+ builder.append(sectionContribution.dump());+ builder.append("\nwrittenSinceOpen: ");+ builder.append(writtenSinceOpen);++ builder.append("\necSymbolicInformationEnabled: ");+ builder.append(ecSymbolicInformationEnabled);++ builder.append("\nspare: ");+ builder.append(spare);+ builder.append("\nindexToTSMList: ");+ builder.append(indexToTSMList);+ builder.append("\nstreamNumberDebugInformation: ");+ builder.append(streamNumberDebugInformation);+ builder.append("\nsizeLocalSymbolsDebugInformation: ");+ builder.append(sizeLocalSymbolsDebugInformation);+ builder.append("\nsizeLineNumberDebugInformation: ");+ builder.append(sizeLineNumberDebugInformation);+ builder.append("\nsizeC13StyleLineNumberInformation: ");+ builder.append(sizeC13StyleLineNumberInformation);+ builder.append("\nnumFilesContributing: ");+ builder.append(numFilesContributing);++ builder.append(dumpAdditionals());++ builder.append("\nmoduleName: ");+ builder.append(moduleName);+ builder.append("\nobjectFileName: ");+ builder.append(objectFileName);++ builder.append("\nEnd ModuleInformation---------------------------------------\n");+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractPdb.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractPdb.javanew file mode 100644index 0000000000..6ee9e8d35e--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractPdb.java@@ -0,0 +1,803 @@+/* ###+ * 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.pdb.pdbreader;++import java.io.IOException;+import java.io.Writer;+import java.util.*;++import ghidra.app.util.datatype.microsoft.GUID;+import ghidra.pdb.*;+import ghidra.pdb.msfreader.AbstractMsf;+import ghidra.pdb.msfreader.MsfStream;+import ghidra.pdb.pdbreader.symbol.*;+import ghidra.pdb.pdbreader.type.AbstractMsType;+import ghidra.util.exception.CancelledException;+import ghidra.util.graph.DependencyGraph;+import ghidra.util.task.TaskMonitor;++/**+ * This class represents the the Windows PDB file. This class is only suitable for reading; not+ * for writing or modifying a PDB.+ * <P>+ * We have intended to implement according to the Microsoft PDB API (source); see the API for+ * truth.+ */+public abstract class AbstractPdb implements AutoCloseable {++ private static final int PDB_DIRECTORY_STREAM_NUMBER = 1;++ // Items below begin in Pdb200+ private static final int VERSION_NUMBER_SIZE = 4;++ // Items below begin in Pdb400+ // "MINI" = 0x4d 0x49 0x4e 0x49 = 0x494e494d featMinimalDbgInfo+ private static final int MINIMAL_DEBUG_INFO_PARAM = 0x494e494d;+ // "NOTM" = 0x4e 0x4f 0x54 0x4d = 0x4d544f4e featNoTypeMerge+ private static final int NO_TYPE_MERGE_PARAM = 0x4d544f4e;++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected AbstractMsf msf;++ // Items below begin in Pdb200+ protected int versionNumber = 0;+ protected int signature = 0;+ //Number of times PDB updated.+ protected int age = 0;++ protected AbstractTypeProgramInterface typeProgramInterface;+ protected AbstractDatabaseInterface databaseInterface;++ protected int targetProcessorIndexNumber = 0xffff;++ // Items below begin in Pdb400+ protected boolean minimalDebugInfo = false;+ protected boolean noTypeMerge = false;+ protected boolean hasIdStream = false;+ protected List<String> strings;+ protected List<Integer> parameters;+ protected NameTable nameTable;++ protected AbstractTypeProgramInterface itemProgramInterface; //IPI seems to be a TPI.++ // Items below begin in Pdb700+ protected GUID guid; // We can return null by not initializing the guid.+ //protected GUID guid =+ // new GUID(0, (short) 0, (short) 0, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });++ protected boolean substreamsDeserialized = false;++ //==============================================================================================+ private TypeParser typeParser;+ private SymbolParser symbolParser;+ //==============================================================================================+ private Stack<CategoryIndex> dependencyStack = new Stack<>();+ private DependencyGraph<CategoryIndex> dependencyGraph = new DependencyGraph<>();+ private List<CategoryIndex> orderedDependenyIndices = new ArrayList<>();++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Closes the {@link AbstractPdb} and resources that it uses.+ * @throws IOException for file I/O reasons.+ */+ @Override+ public void close() throws IOException {+ if (msf != null) {+ msf.close();+ }+ }++ /**+ * Returns the main {@link PdbIdentifiers} found in the PDB Directory.+ * @return {@link PdbIdentifiers} of information.+ */+ public PdbIdentifiers getIdentifiers() {+ return new PdbIdentifiers(versionNumber, signature, age, guid);+ }++ /**+ * Deserializes this PDB from the underlying {@link AbstractMsf}.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException Upon error in processing components.+ * @throws CancelledException Upon user cancellation.+ */+ public void deserialize(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ // msf should only be null for testing versions of PDB.+ if (msf == null) {+ return;+ }+ deserializeDirectory(monitor);++ //directoryStream.dump(Integer.MAX_VALUE);+ //System.out.println(pdb.dumpDirectory());++ //pdb.dumpStream(2, Integer.MAX_VALUE);+// pdb.dumpStream(2, 0x400);+ // pdb.dumpStream(3, 0x400);+// pdb.dumpStream(4, 0x400);++ deserializeSubstreams(monitor);+// pdb.dumpSubStreams();++ // pdb.dumpGlobalSymbols(); //TODO: evaluate where/who calls.+ // Currently in dumpSubStreams() and parsed in deserializeSubStreams()+ }++ /**+ * Return some post-processing metrics on the PDB+ * @return {@link String} of pretty output.+ */+ public String getPostProcessingReport() {+ StringBuilder builder = new StringBuilder();+ String dataTypesReport = typeParser.getNewDataTypesLog();+ if (!dataTypesReport.isEmpty()) {+ builder.append(dataTypesReport);+ builder.append("\n");+ }+ String symbolTypesReport = symbolParser.getNewSymbolTypesLog();+ if (!symbolTypesReport.isEmpty()) {+ builder.append(symbolTypesReport);+ builder.append("\n");+ }+ return builder.toString();+ }++ /**+ * Returns the {@link TypeParser} created for this PDB.+ * @return {@link TypeParser} for this PDB.+ */+ public TypeParser getTypeParser() {+ return typeParser;+ }++ /**+ * Returns the {@link SymbolParser} created for this PDB.+ * @return {@link SymbolParser} for this PDB.+ */+ public SymbolParser getSymbolParser() {+ return symbolParser;+ }++ /**+ * Returns the Version Number of the PDB.+ * @return Version Number of the PDB.+ */+ public int getVersionNumber() {+ return versionNumber;+ }++ /**+ * Returns the Signature of the PDB.+ * @return Signature of the PDB.+ */+ public int getSignature() {+ return signature;+ }++ /**+ * Returns the Age of the PDB.+ * @return Age of the PDB.+ */+ public int getAge() {+ return age;+ }++ /**+ * Returns the GUID for the PDB.+ * @return {@link GUID} for the PDB.+ */+ public GUID getGuid() {+ return guid;+ }++ /**+ * Tells whether the PDB file has been completely deserialized yet.+ * @return True if has been deserialized.+ */+ public boolean isDeserialized() {+ return substreamsDeserialized;+ }++ /**+ * Get the index number of the target processor used for compilation. Also see+ * {@link ProcessorName} and {@link RegisterName}.+ * @return Index number of the target processor used for compilation.+ */+ public int getTargetProcessorIndexNumber() {+ return targetProcessorIndexNumber;+ }++ /**+ * Set the index number of the target processor used for compilation. Also see+ * {@link ProcessorName} and {@link RegisterName}.+ * @param targetProcessorIndexNumberIn Processor identifier.+ */+ public void setTargetProcessorIndexNumber(int targetProcessorIndexNumberIn) {+ targetProcessorIndexNumber = targetProcessorIndexNumberIn;+ }++ /**+ * Returns the {@link AbstractTypeProgramInterface} component.+ * @return {@link AbstractTypeProgramInterface} component.+ */+ public AbstractTypeProgramInterface getTypeProgramInterface() {+ return typeProgramInterface;+ }++ /**+ * Returns the ItemProgramInterface (of type {@link AbstractTypeProgramInterface})+ * component.+ * @return ItemProgramInterface (of type {@link AbstractTypeProgramInterface}) component.+ */+ public AbstractTypeProgramInterface getItemProgramInterface() {+ return itemProgramInterface;+ }++ /**+ * Returns the {@link AbstractDatabaseInterface} component.+ * @return {@link AbstractDatabaseInterface} component.+ */+ public AbstractDatabaseInterface getDatabaseInterface() {+ return databaseInterface;+ }++ /**+ * Returns the {@link SymbolRecords} component of the PDB.+ * @return {@link SymbolRecords} component.+ */+ public SymbolRecords getSymbolRecords() {+ return databaseInterface.getSymbolRecords();+ }++ /**+ * Returns List of {@link AbstractMsSymbol} encountered everywhere in the PDB+ * (public an module).+ * @return Symbols ({@link AbstractMsSymbol}).+ */+ public List<AbstractMsSymbol> getComprehensiveSymbolsList() {+ return databaseInterface.getComprehensiveSymbolsList();+ }++ /**+ * Returns the type associated with the record number from the Type Program Interface (TPI).+ * @param recordNumber Record Number requested.+ * @return "Type" ({@link AbstractMsType}) for the record number.+ */+ public AbstractMsType getTypeRecord(int recordNumber) {+ return typeProgramInterface.getRecord(recordNumber);+ }++ /**+ * Returns a name from the {@link NameTable} pertaining to the index argument.+ * @param index Index of the name.+ * @return Name.+ */+ public String getNameFromNameIndex(int index) {+ return nameTable.getNameFromStreamNumber(index);+ }++ /**+ * Returns an index of the {@link String} name argument in the {@link NameTable}.+ * @param name Name for which to find the index.+ * @return Index of the name argument.+ */+ public int getNameIndexFromName(String name) {+ return nameTable.getStreamNumberFromName(name);+ }++ /**+ * Returns a name from the {@link NameTable} pertaining to the byte-offset in the block of+ * names for the table.+ * @param offset Byte-offset of the name in the {@link NameTable} block.+ * @return Name at the byte offset in the Name Table.+ */+ public String getNameStringFromOffset(int offset) {+ return nameTable.getNameStringFromOffset(offset);+ }++ /**+ * Returns the Item of type {@link AbstractMsType} associated with the record number from the+ * Item Program Interface (IPI).+ * @param recordNumber Record number.+ * @return "Item" ({@link AbstractMsType}) for the record number.+ */+ public AbstractMsType getItemRecord(int recordNumber) {+ if (hasIdStream) {+ return itemProgramInterface.getRecord(recordNumber);+ }+ return null;+ }++ /**+ * Returns an {@link AbstractMsSymbol} based upon a made-up (non-PDB) record number that+ * we created in order to have a unique identifier across all symbols (whether public or+ * from any of the modules). These numbers were created in a one-up fashion as the+ * records were encountered. This method returns the specific symbol record for that number.+ * @param recordNumber Record number.+ * @return {@link AbstractMsSymbol} for the record number.+ */+ public AbstractMsSymbol getComprehensiveSymbolRecord(int recordNumber) {+ return databaseInterface.getComprehensiveSymbolRecord(recordNumber);+ }++ /**+ * Returns the {@link AbstractParsableItem} (either an {@link AbstractMsType} for DATA or+ * ITEM or an {@link AbstractMsSymbol} for a SYMBOL) identified by the categoryIndex.+ * Note that {@link CategoryIndex} is not a standard part of the PDB, but something we+ * use for Dependency Graph/Order in an investigation of how to analyze and apply the PDB.+ * @param categoryIndex Identifier for the record to be returned.+ * @return {@link AbstractParsableItem} (either an {@link AbstractMsType} for DATA or+ * ITEM or an {@link AbstractMsSymbol} for SYMBOL).+ */+ public AbstractParsableItem getParsableItemFromCategoryIndex(CategoryIndex categoryIndex) {+ if (categoryIndex.getCategory() == CategoryIndex.Category.DATA) {+ return getTypeRecord(categoryIndex.getIndex());+ }+ if (categoryIndex.getCategory() == CategoryIndex.Category.ITEM) {+ return getItemRecord(categoryIndex.getIndex());+ }+ return getComprehensiveSymbolRecord(categoryIndex.getIndex());+ }++ /**+ * Returns the {@link DependencyGraph}<{@link CategoryIndex}>. Dependency order is not+ * a PDB feature. It is something we added (and might be removed in the future) as we+ * have investigated how to analyze and apply the PDB.+ * @return {@link DependencyGraph}<{@link CategoryIndex}>.+ */+ public DependencyGraph<CategoryIndex> getDependencyGraphCopy() {+ return dependencyGraph.copy();+ }++ /**+ * Method to be called during the creation of the {@link DependencyGraph} whenever this node is+ * starting to be processes, in which case it might be a dependent of some parent, or it might+ * have dependents of its own.+ * <P>+ * Only should be called for {@link AbstractParsableItem} that could be DATA or ITEM+ * ({@link AbstractMsType}) or SYMBOL ({@link AbstractMsSymbol}) type.+ * <P>+ * There is no situation where a DATA or ITEM is dependent on a SYMBOL.+ * @param dependeeCategoryIndex {@link CategoryIndex} for the new node. ({@link CategoryIndex}+ * contains the record index and an identifier of which list the index belongs: DATA, ITEM,+ * or SYMBOL.)+ */+ public void pushDependencyStack(CategoryIndex dependeeCategoryIndex) {++ if ((dependeeCategoryIndex.getIndex() == 4774 ||+ dependeeCategoryIndex.getIndex() == 4775) &&+ dependeeCategoryIndex.getCategory() == CategoryIndex.Category.DATA) {+ // The following code is for developmental investigations;+ // set break point on "int a = 1;" instead of a+ // conditional break point.+ int a = 1;+ a = a + 1;+ }+ if (dependencyStack.isEmpty()) {+ dependencyGraph.addValue(dependeeCategoryIndex);+ }+ else {+ CategoryIndex dependentCategoryIndex = dependencyStack.peek();+ dependencyGraph.addDependency(dependentCategoryIndex, dependeeCategoryIndex);+ }+ dependencyStack.add(dependeeCategoryIndex);+ }++ /**+ * Method to be called during the creation of {@link DependencyGraph}<{@link CategoryIndex}>+ * whenever a node (see {@link #pushDependencyStack(CategoryIndex)}) will have no more+ * dependents of its own (or is done being processed).+ */+ public void popDependencyStack() {+ dependencyStack.pop();+ }++ public void processDependencyGraph() {+ if (dependencyGraph.hasCycles()) {+ return;+ }+ DependencyGraph<CategoryIndex> mutableCopy = dependencyGraph.copy();+ Stack<CategoryIndex> stack = new Stack<>();+ while (!mutableCopy.isEmpty()) {+ CategoryIndex dependencyIndex = mutableCopy.pop();+ stack.push(dependencyIndex);+ }+ while (!stack.isEmpty()) {+ CategoryIndex dependencyIndex = stack.pop();+ orderedDependenyIndices.add(dependencyIndex);+ }+ // Template of how one might process the data+// for (CategoryIndex categoryIndex : orderedDependenyIndices) {+// int index = categoryIndex.getIndex();+// if (categoryIndex.getIndexType() == CategoryIndex.Category.DATA) {+// AbstractMsType type = getTypeRecord(index);+// }+// else if (categoryIndex.getIndexType() == CategoryIndex.Category.ITEM) {+// AbstractMsType item = getItemRecord(index);+// }+// else { // dependencyIndex.getIndexType() == IndexType.SYMBOL+// AbstractMsSymbol symbol = getComprehensiveSymbolRecord(index);+// }+// }+ }++ /**+ * Dumps the {@link DependencyGraph}<{@link CategoryIndex}> information. The+ * {@link DependencyGraph}<{@link CategoryIndex}> is not a PDB feature. It is+ * something we added (and might be removed in the future) as we have investigated how to+ * analyze and apply the PDB. This package-protected method is for debugging only.+ * @return {@link String} of pretty output.+ */+ public String dumpDependencyGraph() {+ StringBuilder builder = new StringBuilder();+ builder.append("DependencyGraph---------------------------------------------");+ builder.append("\nSize: ");+ builder.append(dependencyGraph.size());+ builder.append("\n");+ if (dependencyGraph.hasCycles()) {+ builder.append("Has cycles\n");+ }+ else {+ builder.append("Has no cycles\n");+ }+ DependencyGraph<CategoryIndex> mutableCopy = dependencyGraph.copy();+ while (!mutableCopy.isEmpty()) {+ CategoryIndex categoryIndex = mutableCopy.pop();+ int index = categoryIndex.getIndex();+ if (categoryIndex.getCategory() == CategoryIndex.Category.DATA) {+ AbstractMsType type = getTypeRecord(index);+ builder.append(String.format("Dependency (data index: %d) [%s]: %s\n", index,+ type.getClass().getSimpleName(), type.toString()));+ }+ else if (categoryIndex.getCategory() == CategoryIndex.Category.ITEM) {+ AbstractMsType item = getItemRecord(index);+ builder.append(String.format("Dependency (item index: %d) [%s]: %s\n", index,+ item.getClass().getSimpleName(), item.toString()));+ }+ else { // dependencyIndex.getIndexType() == IndexType.SYMBOL+ AbstractMsSymbol symbol = getComprehensiveSymbolRecord(index);+ builder.append(String.format("Dependency (symbol index: %d) [%s]: %s\n", index,+ symbol.getClass().getSimpleName(), symbol.toString()));+ }+ }+ return builder.toString();+ }++ /**+ * Dumps the Dependency Order information as found in the+ * {@link DependencyGraph}<{@link CategoryIndex}>. Dependency order is not a PDB feature.+ * It is something we added (and might be removed in the future) as we have investigated+ * how to analyze and apply the PDB. This package-protected method is for debugging only.+ * @return {@link String} of pretty output.+ */+ protected String dumpDependencyOrder() {+ StringBuilder builder = new StringBuilder();+ builder.append("DependencyOrder---------------------------------------------");+ builder.append("\nSize: ");+ builder.append(orderedDependenyIndices.size());+ builder.append("\n");+ for (CategoryIndex categoryIndex : orderedDependenyIndices) {+ int index = categoryIndex.getIndex();+ if (categoryIndex.getCategory() == CategoryIndex.Category.DATA) {+ AbstractMsType type = getTypeRecord(index);+ builder.append(String.format("Dependency (data index: %d) [%s]: %s\n", index,+ type.getClass().getSimpleName(), type.toString()));+ }+ else if (categoryIndex.getCategory() == CategoryIndex.Category.ITEM) {+ AbstractMsType item = getItemRecord(index);+ builder.append(String.format("Dependency (item index: %d) [%s]: %s\n", index,+ item.getClass().getSimpleName(), item.toString()));+ }+ else { // dependencyIndex.getIndexType() == ICategoryIndex.Category.SYMBOL+ AbstractMsSymbol symbol = getComprehensiveSymbolRecord(index);+ builder.append(String.format("Dependency (symbol index: %d) [%s]: %s\n", index,+ symbol.getClass().getSimpleName(), symbol.toString()));+ }+ }+ return builder.toString();+ }++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Returns the number of bytes needed to store a PDB version number.+ * location.+ * @return Number of bytes needed to store a PDV version number.+ */+ static int getVersionNumberSize() {+ return VERSION_NUMBER_SIZE;+ }++ /**+ * Deserializes PDB Version Number from the PDB Directory Stream in the {@link AbstractMsf}.+ * @param msf {@link AbstractMsf} underlying the PDB of which to probe.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @return Version number.+ * @throws IOException on file I/O issues.+ * @throws PdbException on parsing issues.+ * @throws CancelledException Upon user cancellation.+ */+ static int deserializeVersionNumber(AbstractMsf msf, TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ MsfStream directoryStream = msf.getStream(PDB_DIRECTORY_STREAM_NUMBER);+ if (directoryStream.getLength() < AbstractPdb.getVersionNumberSize()) {+ throw new PdbException("Directory Stream too short");+ }+ byte[] bytes = directoryStream.read(0, AbstractPdb.getVersionNumberSize(), monitor);+ PdbByteReader pdbDirectoryReader = new PdbByteReader(bytes);+ return pdbDirectoryReader.parseInt();+// int versionNumber = AbstractPdb.deserializeVersionNumber(pdbDirectoryReader);+// return versionNumber;+// }+ }++ /**+ * Constructor.+ * @param msf {@link AbstractMsf} foundation for the PDB.+ * @throws IOException Upon file IO seek/read issues.+ * @throws PdbException Upon unknown value for configuration or error in processing components.+ */+ AbstractPdb(AbstractMsf msf) throws IOException, PdbException {+ this.msf = msf;+ strings = new ArrayList<>();+ parameters = new ArrayList<>();+ nameTable = new NameTable(this);++ typeParser = new TypeParser(this);+ symbolParser = new SymbolParser(this);+ }++ /**+ * Deserializes the main {@link PdbIdentifiers} found in the PDB Directory from the+ * {@link PdbByteReader}.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException upon error parsing a field.+ * @throws CancelledException Upon user cancellation.+ */+ abstract void deserializeIdentifiersOnly(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException;++ /**+ * Returns the {@link AbstractMsf} foundation for the PDB.+ * @return {@link AbstractMsf} foundation of the PDB.+ */+ AbstractMsf getMsf() {+ return msf;+ }++ //TODO Not sure if we will keep this method or if more gets added to it.+ /**+ * Deserializes the sub-streams for this {@link AbstractPdb} object.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException Upon error in processing components.+ * @throws CancelledException Upon user cancellation.+ */+ void deserializeSubstreams(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {++ if (substreamsDeserialized) {+ return;+ }++ TypeProgramInterfaceParser tpiParser = new TypeProgramInterfaceParser();+ DatabaseInterfaceParser dbiParser = new DatabaseInterfaceParser();++ typeProgramInterface = tpiParser.parse(this, monitor);+ if (typeProgramInterface != null) {+ typeProgramInterface.deserialize(monitor);+ }++ databaseInterface = dbiParser.parse(this, monitor);+ if (databaseInterface != null) {+ databaseInterface.deserialize(monitor);+ }++ if (hasIdStream) {+ ItemProgramInterfaceParser ipiParser = new ItemProgramInterfaceParser();+ itemProgramInterface = ipiParser.parse(this, monitor);+ if (itemProgramInterface != null) {+ itemProgramInterface.deserialize(monitor);+ }+ //processDependencyIndexPairList();+ //dumpDependencyGraph();+ }++ //processDependencyGraph();+ //dumpDependencyGraph();++ substreamsDeserialized = true;+ }++ /**+ * Debug method to dump the number of bytes for the specified stream to a {@link String}.+ * @param streamNumber The stream number to dump.+ * @param maxOut The maximum number of bytes to dump.+ * @return {@link String} of pretty output.+ */+ String dumpStream(int streamNumber, int maxOut) {+ StringBuilder builder = new StringBuilder();+ builder.append(msf.getStream(streamNumber).dump(maxOut));+ return builder.toString();+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ /**+ * Deserializes PDB Directory from the {@link PdbByteReader}.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException upon error parsing a field.+ * @throws CancelledException Upon user cancellation.+ */+ abstract void deserializeDirectory(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException;++ /**+ * Dumps the PDB Directory to {@link Writer}. This package-protected method is for+ * debugging only.+ * @param writer {@link Writer}.+ * @throws IOException On issue writing to the {@link Writer}.+ */+ abstract void dumpDirectory(Writer writer) throws IOException;++ //==============================================================================================+ // Internal Data Methods+ //==============================================================================================++ /**+ * Reads the Directory stream and returns a {@link PdbByteReader} of its contents.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @return {@link PdbByteReader} requested.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws CancelledException Upon user cancellation.+ */+ protected PdbByteReader getDirectoryReader(TaskMonitor monitor)+ throws IOException, CancelledException {+ MsfStream directoryStream = msf.getStream(PDB_DIRECTORY_STREAM_NUMBER);+ int length = directoryStream.getLength();+ byte[] bytes = directoryStream.read(0, length, monitor);+ return new PdbByteReader(bytes);+ }++ /**+ * Deserializes the Version, Signature, and Age.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @throws PdbException Upon not enough data left to parse.+ */+ protected void deserializeVersionSignatureAge(PdbByteReader reader) throws PdbException {+ versionNumber = reader.parseInt();+ signature = reader.parseInt();+ age = reader.parseInt();+ }++ /**+ * Dumps the Version Signature and Age. This package-protected method is for debugging only.+ * @return {@link String} of pretty output.+ */+ protected String dumpVersionSignatureAge() {+ StringBuilder builder = new StringBuilder();+ builder.append("DirectoryHeader---------------------------------------------");+ builder.append("\nversionNumber: ");+ builder.append(versionNumber);+ builder.append("\nsignature: ");+ builder.append(signature);+ builder.append("\nage: ");+ builder.append(age);+ return builder.toString();+ }++ /**+ * Deserializes the Parameters.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException upon error parsing a string.+ * @throws CancelledException Upon user cancellation.+ */+ protected void deserializeParameters(PdbByteReader reader, TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ nameTable.deserializeDirectory(reader, monitor);+ // Read the parameters.+ while (reader.hasMore()) {+ monitor.checkCanceled();+ int val = reader.parseInt();+ parameters.add(val);+ }+ // Check the parameters for IDs+ for (int param : parameters) {+ monitor.checkCanceled();+ if (param == MINIMAL_DEBUG_INFO_PARAM) {+ minimalDebugInfo = true;+ }+ else if (param == NO_TYPE_MERGE_PARAM) {+ noTypeMerge = true;+ }+ // Putting all of these >= ID after the specific == tests above+ // so that no >= tests in the ID section trigger off of any+ // of the above flags+ else if (param >= PdbParser.VC110_ID) {+ hasIdStream = true;+ }+ }+ }++ /**+ * Dumps the Parameters to a {@link String}. This package-protected method is for+ * debugging only.+ * @return {@link String} of pretty output.+ */+ protected String dumpParameters() {+ StringBuilder builder = new StringBuilder();+ builder.append(nameTable.dump());+ builder.append("\nParameters--------------------------------------------------\n");+ for (int i = 0; i < parameters.size(); i++) {+ builder.append(String.format("parameter[%d]: 0x%08x %d\n", i, parameters.get(i),+ parameters.get(i)));+ }+ builder.append("Booleans----------------------------------------------------");+ builder.append("\nminimalDebugInfo: ");+ builder.append(minimalDebugInfo);+ builder.append("\nnoTypeMerge: ");+ builder.append(noTypeMerge);+ builder.append("\nhasIdStream: ");+ builder.append(hasIdStream);+ builder.append("\n");+ return builder.toString();+ }++ /**+ * Dumps the Sub-Streams to a {@link Writer}. This package-protected method is for+ * debugging only.+ * @param writer {@link Writer}.+ * @throws IOException On issue writing to the {@link Writer}.+ */+ protected void dumpSubStreams(Writer writer) throws IOException {+ writer.write("SubStreams--------------------------------------------------\n");+ if (typeProgramInterface != null) {+ writer.write("TypeProgramInterface----------------------------------------\n");+ typeProgramInterface.dump(writer);+ writer.write("End TypeProgramInterface------------------------------------\n");+ writer.write("\n");+ }+ if (databaseInterface != null) {+ writer.write("DatabaseInterface-------------------------------------------\n");+ databaseInterface.dump(writer);+ writer.write("End DatabaseInterface---------------------------------------\n");+ }+ if (itemProgramInterface != null) {+ writer.write("ItemProgramInterface----------------------------------------\n");+ itemProgramInterface.dump(writer);+ writer.write("End ItemProgramInterface------------------------------------\n");+ }+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractSectionContribution.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractSectionContribution.javanew file mode 100644index 0000000000..15d2ef1a03--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractSectionContribution.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.pdb.pdbreader;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;++/**+ * This class represents Section Contribution component of a PDB file. This class is only+ * suitable for reading; not for writing or modifying a PDB.+ * <P>+ * We have intended to implement according to the Microsoft PDB API (source); see the API for+ * truth.+ */+public abstract class AbstractSectionContribution {++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected int isect; // unsigned 16-bit+ protected int offset; // signed 32-bit+ protected int length; // signed 32-bit+ protected int imod; // unsigned 16-bit++ protected long characteristics; // unsigned 32-bit++ protected long dataCrc; // unsigned 32-bit+ protected long relocationCrc; // unsigned 32-bit+ protected long unknownSectionContributionField; // unknown field for SCV1400++ //==============================================================================================+ // API+ //==============================================================================================+ public AbstractSectionContribution() {+ }++ public int getSection() {+ return isect;+ }++ public int getOffset() {+ return offset;+ }++ public int getLength() {+ return length;+ }++ public int getModule() {+ return imod;+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ /**+ * Deserializes the Section Contribution.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @throws PdbException Upon not enough data left to parse.+ */+ abstract void deserialize(PdbByteReader reader) throws PdbException;++ /**+ * Dumps the SectionContribution. This method is for debugging only.+ * @return {@link String} of pretty output.+ */+ abstract String dumpInternals();++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Dumps the Section Contribution. This method is for debugging only.+ * @return {@link String} of pretty output.+ */+ String dump() {+ StringBuilder builder = new StringBuilder();+ builder.append("SectionContribution-----------------------------------------\n");+ builder.append(dumpInternals());+ builder.append("\nEnd SectionContribution-------------------------------------\n");+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractTypeProgramInterface.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractTypeProgramInterface.javanew file mode 100644index 0000000000..49870685f8--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/AbstractTypeProgramInterface.java@@ -0,0 +1,329 @@+/* ###+ * 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.pdb.pdbreader;++import java.io.IOException;+import java.io.Writer;+import java.util.*;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.pdb.msfreader.MsfStream;+import ghidra.pdb.pdbreader.type.AbstractMsType;+import ghidra.pdb.pdbreader.type.PrimitiveMsType;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class represents Type Program Interface component of a PDB file. This class is only+ * suitable for reading; not for writing or modifying a PDB.+ * <P>+ * We have intended to implement according to the Microsoft PDB API (source); see the API for+ * truth.+ */+public abstract class AbstractTypeProgramInterface {++ public static final int STREAM_NUMBER_SIZE = 2;++ protected static final int VERSION_NUMBER_SIZE = 4;+ protected static final int HEADER_LENGTH_SIZE = 4;+ protected static final int TYPE_INDEX_SIZE = 4;+ protected static final int TYPE_INDEX16_SIZE = 2;+ protected static final int DATA_LENGTH_SIZE = 4;++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected AbstractPdb pdb;+ private int streamNumber;++ protected int typeIndexMin;+ protected int typeIndexMaxExclusive;+ protected int dataLength;++ protected Map<Integer, PrimitiveMsType> primitivesMap = new HashMap<>();+ protected List<AbstractMsType> typeList = new ArrayList<>();++ protected int versionNumber = 0;++ //==============================================================================================+ protected CategoryIndex.Category category;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param pdbIn {@link AbstractPdb} that owns this {@link AbstractTypeProgramInterface}.+ * @param streamNumber The stream number that contains the+ * {@link AbstractTypeProgramInterface} data.+ */+ public AbstractTypeProgramInterface(AbstractPdb pdbIn, int streamNumber) {+ this.pdb = pdbIn;+ this.streamNumber = streamNumber;+ }++ /**+ * Returns the number of bytes needed to store a {@link AbstractTypeProgramInterface}+ * version number.+ * @return The number of bytes read from the bytes array.+ */+ static int getVersionNumberSize() {+ return VERSION_NUMBER_SIZE;+ }++ /**+ * Deserializes Version Number of the {@link AbstractTypeProgramInterface} from the+ * {@link PdbByteReader}.+ * @param reader {@link PdbByteReader} from which to deserialize.+ * @return Version number.+ * @throws PdbException Upon not enough data left to parse.+ */+ static int deserializeVersionNumber(PdbByteReader reader) throws PdbException {+ return reader.parseInt();+ }++ /**+ * Sets the active enum {@link CategoryIndex.Category} for the list that we are processing.+ * This is not a standard part of the PDB, but something we used for creation of a Dependency+ * order/graph. It is something we added (and might be removed in the future) as we have+ * investigated how to analyze and apply the PDB.+ * @param category enum {@link CategoryIndex.Category} to set.+ */+ public void setCategory(CategoryIndex.Category category) {+ this.category = category;+ }++ /**+ * Returns the TypeIndexMin.+ * @return The TypeIndexMin value from the header.+ */+ public int getTypeIndexMin() {+ return typeIndexMin;+ }++ /**+ * Returns the TypeIndexMaxExclusive.+ * @return TypeIndexMaxExclusive value from the header.+ */+ public int getTypeIndexMaxExclusive() {+ return typeIndexMaxExclusive;+ }++ /**+ * Retrieves the {@link AbstractMsType} record indicated by the recordNumber. The record must+ * already have been parsed and inserted into the list.+ * @param recordNumber Record number to look up.+ * @return {@link AbstractMsType} pertaining to the record number.+ */+ public AbstractMsType getRecord(int recordNumber) {+ if (recordNumber < typeIndexMin) {+ PrimitiveMsType primitive = primitivesMap.get(recordNumber);+ if (primitive == null) {+ primitive = new PrimitiveMsType(pdb, recordNumber);+ primitivesMap.put(recordNumber, primitive);+ }+ return primitive;+ }+ return typeList.get(recordNumber - typeIndexMin);+ }++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Deserializes this {@link AbstractTypeProgramInterface}.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @return Version number of the {@link AbstractTypeProgramInterface}.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException Upon not enough data left to parse.+ * @throws CancelledException Upon user cancellation.+ */+ int deserialize(TaskMonitor monitor) throws IOException, PdbException, CancelledException {+ if (pdb.getMsf() == null) {+ // Should only be null dummy PDBs used for testing.+ throw new PdbException("Unexpected null MSF.");+ }+ MsfStream stream = pdb.getMsf().getStream(streamNumber);+ byte[] bytes = stream.read(0, stream.getLength(), monitor);+ PdbByteReader reader = new PdbByteReader(bytes);++ deserializeHeader(reader);+ deserializeTypeRecords(reader);++ return versionNumber;+ }++ /**+ * Dumps this class. This package-protected method is for debugging only.+ * @param writer {@link Writer} to which to write the debug dump.+ * @throws IOException On issue writing to the {@link Writer}.+ */+ void dump(Writer writer) throws IOException {+ StringBuilder builder = new StringBuilder();+ builder.append("TypeProgramInterfaceHeader----------------------------------\n");+ builder.append(dumpHeader());+ builder.append("\nEnd TypeProgramInterfaceHeader------------------------------\n");+ builder.append("TypeProgramInterfaceRecords---------------------------------\n");+ builder.append(dumpTypeRecords());+ builder.append("\nEnd TypeProgramInterfaceRecords-----------------------------\n");+ writer.write(builder.toString());+ }++ /**+ * IMPORTANT: This method is for testing only. It allows us to set a basic object.+ * Note: not all values are initialized. This is a dummy constructor used to create a dummy+ * {@link AbstractTypeProgramInterface}.+ * Note: not all values of this class get initialized by this method.+ * @param pdb {@link AbstractPdb} that owns this this class.+ * @param typeIndexMin The IndexMin to set/use.+ * @param typeIndexMaxExclusive One greater than the MaxIndex to set/use.+ */+ AbstractTypeProgramInterface(AbstractPdb pdb, int typeIndexMin, int typeIndexMaxExclusive) {+ this.pdb = pdb;+ this.typeIndexMin = typeIndexMin;+ this.typeIndexMaxExclusive = typeIndexMaxExclusive;+ }++ /**+ * IMPORTANT: This method is for testing only. It allows us to set a record for a particular+ * record number.+ * @param recordNumber Record number for the {@link AbstractMsType} to be inserted.+ * @param type {@link AbstractMsType} to be inserted.+ * @return True if successful.+ */+ boolean setRecord(int recordNumber, AbstractMsType type) {+ if (recordNumber < typeIndexMin) {+ return false;+ }+ for (int i = typeList.size() + typeIndexMin; i <= recordNumber; i++) {+ // Add the same record for each index up to the one needed.+ typeList.add(type);+ }+ return true;+ }++ /**+ * IMPORTANT: This method is for testing only. It allows us to add a record that gets its+ * record number automatically assigned.+ * @param type {@link AbstractMsType} to be inserted.+ * @return Record number assigned.+ */+ int addRecord(AbstractMsType type) {+ int newRecordNum = typeList.size() + typeIndexMin;+ typeList.add(type);+ return newRecordNum;+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ /**+ * Deserializes the Header of this class.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @throws PdbException Upon not enough data left to parse.+ */+ protected abstract void deserializeHeader(PdbByteReader reader) throws PdbException;++ /**+ * Dumps the Header. This method is for debugging only.+ * @return {@link String} of pretty output.+ */+ protected abstract String dumpHeader();++ //==============================================================================================+ // Internal Data Methods+ //==============================================================================================+ /**+ * Deserializes the Type Records of this class.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @throws PdbException Upon not enough data left to parse.+ */+ protected void deserializeTypeRecords(PdbByteReader reader) throws PdbException {+ int recordLength;+ int recordNumber = typeIndexMin;+ TypeParser parser = pdb.getTypeParser();+ //System.out.println(reader.dump());+ while (reader.hasMore()) {+ int index = reader.getIndex();+ //System.out.println("index: " + index);+ //System.out.println("record: " + recordNumber);+ // The following code is for developmental investigations;+ // set break point on "int a = 1;" instead of a+ // conditional break point.+ if (index == 18) {+ int a = 1;+ a = a + 1;+ }+ // The following code is for developmental investigations;+ // set break point on "int a = 1;" instead of a+ // conditional break point.+ if (recordNumber == 4096) {+ int a = 1;+ a = a + 1;+ }+ recordLength = reader.parseUnsignedShortVal();+ PdbByteReader recordReader = reader.getSubPdbByteReader(recordLength);+ recordReader.markAlign(2);+ pdb.pushDependencyStack(new CategoryIndex(category, recordNumber));+ AbstractMsType type = parser.parse(recordReader);+ pdb.popDependencyStack();+ typeList.add(type);+ //System.out.println(type.getClass().getSimpleName());+ //System.out.println(type.toString());+ recordNumber++;+ }+ //assert (recordNumber == typeIndexMaxExclusive + 1); //not really TI + 1+ }++ //TODO: more to do for outputting individual records (might want a toString or dump method+ // on each).+ /**+ * Dumps the Type Records. This method is for debugging only.+ * @return {@link String} of pretty output.+ */+ protected String dumpTypeRecords() {+ StringBuilder builder = new StringBuilder();+ int recordNum = typeIndexMin;+ for (AbstractMsType type : typeList) {+ builder.append("------------------------------------------------------------\n");+ builder.append("Record: ");+ builder.append(recordNum);+ builder.append("\n");++ // The following code is for developmental investigations;+ // set break point on "int a = 1;" instead of a+ // conditional break point.+ if (recordNum == -2) {+ int a = 1;+ a = a + 1;+ }+ if (type != null) {+ builder.append(type.getClass().getSimpleName());+ builder.append("\n");+ builder.append(type.toString());+ builder.append("\n");+ }+ else {+ builder.append("(null)\n"); //Temporary output value.+ }+ recordNum++;+ }+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/CategoryIndex.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/CategoryIndex.javanew file mode 100644index 0000000000..27ded85c3d--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/CategoryIndex.java@@ -0,0 +1,118 @@+/* ###+ * 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.pdb.pdbreader;++/**+ * The CategoryIndex is used for creating dependency order of types, items, and symbols.+ * Dependency order is not a PDB feature. It is something we added (and might be removed+ * in the future) as we have investigated how to analyze and apply the PDB.+ * <P>+ * It is composed of a {@link CategoryIndex.Category} enum and an index under that enum. The+ * index is just a record number (as in the case of data type or item type; it is a made up,+ * one-up number for symbols).+ */+public class CategoryIndex {++ /**+ * Enum for categories: DATA, ITEM, and SYMBOL.+ */+ public enum Category {+ DATA, ITEM, SYMBOL+ }++ //==============================================================================================+ // Internals+ //==============================================================================================+ private Category category;+ private int index;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param category {@link CategoryIndex.Category} to be assigned.+ * @param index Index (record number) to be assigned.+ */+ public CategoryIndex(Category category, int index) {+ this.category = category;+ this.index = index;+ }++ /**+ * Returns the enum type {@link CategoryIndex.Category} (DATA, ITEM, or SYMBOL)+ * @return {@link CategoryIndex.Category} enum.+ */+ public Category getCategory() {+ return category;+ }++ /**+ * Returns the index value.+ * @return Index (record number).+ */+ public int getIndex() {+ return index;+ }++ @Override+ public int hashCode() {+ final int prime = 31;+ int result = 1;+ result = prime * result + index;+ result = prime * result + ((category == null) ? 0 : category.hashCode());+ return result;+ }++ @Override+ public boolean equals(Object obj) {+ if (this == obj) {+ return true;+ }+ if (obj == null) {+ return false;+ }+ if (getClass() != obj.getClass()) {+ return false;+ }+ CategoryIndex other = (CategoryIndex) obj;+ if (index != other.index) {+ return false;+ }+ if (category != other.category) {+ return false;+ }+ return true;+ }++ @Override+ public String toString() {+ String string = "";+ switch (category) {+ case DATA:+ string = "D:";+ break;+ case ITEM:+ string = "I:";+ break;+ case SYMBOL:+ string = "S:";+ break;+ }+ string += index;+ return string;+ }+}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/DatabaseInterface.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/DatabaseInterface.javanew file mode 100644index 0000000000..e72e515118--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/DatabaseInterface.java@@ -0,0 +1,132 @@+/* ###+ * 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.pdb.pdbreader;++import java.io.IOException;+import java.io.Writer;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class is the version of {@link AbstractDatabaseInterface} for older PDB files.+ * <P>+ * This class uses {@link ModuleInformation500}.+ */+class DatabaseInterface extends AbstractDatabaseInterface {++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param pdb {@link AbstractPdb} that owns this {@link DatabaseInterface}.+ * @param streamNumber The number of the stream that contains the {@link DatabaseInterface}.+ */+ public DatabaseInterface(AbstractPdb pdb, int streamNumber) {+ super(pdb, streamNumber);+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ protected void deserializeHeader(PdbByteReader reader) throws PdbException {+ streamNumberGlobalStaticSymbols = reader.parseUnsignedShortVal();+ streamNumberPublicStaticSymbols = reader.parseUnsignedShortVal();+ streamNumberSymbolRecords = reader.parseUnsignedShortVal();+ lengthModuleInformationSubstream = reader.parseInt();+ lengthSectionContributionSubstream = reader.parseInt();+ lengthSectionMap = reader.parseInt();+ lengthFileInformation = reader.parseInt();+ }++ @Override+ protected void deserializeInternalSubstreams(PdbByteReader reader) throws PdbException {+ processModuleInformation(reader, false);+ processSectionContributions(reader, false);+ processSegmentMap(reader, false);+ processFileInformation(reader, false);+ }++ @Override+ protected void deserializeAdditionalSubstreams(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ symbolRecords.deserialize(monitor);+ // TODO: evaluate. I don't think we need GlobalSymbolInformation (hash) or the+ // PublicSymbolInformation (hash), as they are both are search mechanisms.+// globalSymbolInformation = new GlobalSymbolInformation();+// globalSymbolInformation.deserialize(pdb);++ //TODO: SectionContributions has information about code sections and refers to+ // debug streams for each.+ }++ @Override+ protected void processModuleInformation(PdbByteReader reader, boolean skip)+ throws PdbException {+ if (lengthModuleInformationSubstream == 0) {+ return;+ }+ if (skip) {+ reader.skip(lengthModuleInformationSubstream);+ return;+ }+ PdbByteReader substreamReader =+ reader.getSubPdbByteReader(lengthModuleInformationSubstream);+ while (substreamReader.hasMore()) {+ AbstractModuleInformation moduleInformation = new ModuleInformation500();+ moduleInformation.deserialize(substreamReader);+ moduleInformationList.add(moduleInformation);+ }+ }++ @Override+ protected void dumpHeader(Writer writer) throws IOException {+ StringBuilder builder = new StringBuilder();+ builder.append("streamNumberGlobalStaticSymbols: ");+ builder.append(streamNumberGlobalStaticSymbols);+ builder.append("\nstreamNumberPublicStaticSymbols: ");+ builder.append(streamNumberPublicStaticSymbols);+ builder.append("\nstreamNumberSymbolRecords: ");+ builder.append(streamNumberSymbolRecords);+ builder.append("\nlengthModuleInformationSubstream: ");+ builder.append(lengthModuleInformationSubstream);+ builder.append("\nlengthSectionContributionSubstream: ");+ builder.append(lengthSectionContributionSubstream);+ builder.append("\nlengthSectionMap: ");+ builder.append(lengthSectionMap);+ builder.append("\nlengthFileInformation: ");+ builder.append(lengthFileInformation);+ writer.write(builder.toString());+ }++ @Override+ protected void dumpInternalSubstreams(Writer writer) throws IOException {+ writer.write("ModuleInformationList---------------------------------------\n");+ dumpModuleInformation(writer);+ writer.write("\nEnd ModuleInformationList-----------------------------------\n");+ writer.write("SectionContributionList-------------------------------------\n");+ dumpSectionContributions(writer);+ writer.write("\nEnd SectionContributionList---------------------------------\n");+ writer.write("SegmentMap--------------------------------------------------\n");+ dumpSegmentMap(writer);+ writer.write("\nEnd SegmentMap----------------------------------------------\n");+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/DatabaseInterfaceNew.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/DatabaseInterfaceNew.javanew file mode 100644index 0000000000..df2529a96a--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/DatabaseInterfaceNew.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.pdb.pdbreader;++import java.io.IOException;+import java.io.Writer;+import java.util.ArrayList;+import java.util.List;++import ghidra.pdb.*;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class is the version of {@link AbstractDatabaseInterface} for newer PDB files.+ * <P>+ * This class uses {@link ModuleInformation600}.+ */+public class DatabaseInterfaceNew extends AbstractDatabaseInterface {++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected Hasher hasher; //Might belong in parent? Used in parent (even older Hasher?)++ // The source of these values can overlay other fields in older versions of this type.+ protected long versionSignature = 0; // unsigned 32-bit++ protected long age = 0; // unsigned 32-bit+ protected int universalVersion = 0; // unsigned 16-bit+ protected int pdbDllBuildVersion = 0; // unsigned 16-bit+ protected int pdbDllReleaseBuildVersion = 0; // unsigned 16-bit++ protected int lengthTypeServerMapSubstream = 0; // signed 32-bit+ protected long indexOfMicrosoftFoundationClassTypeServer = 0; // unsigned 32-bit+ protected int lengthOptionalDebugHeader = 0; // signed 32-bit+ protected int lengthEditAndContinueSubstream = 0; // signed 32-bit++ protected int flags = 0; // unsigned 16-bit+ protected int machineType = 0; // unsigned 16-bit+ protected long padReserve = 0; // unsigned 32-bit++ protected List<String> editAndContinueNameList = new ArrayList<>();+ protected List<Integer> debugStreamList = new ArrayList<>(); // TODO: this is a guess.++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param pdb {@link AbstractPdb} that owns this {@link DatabaseInterfaceNew}.+ * @param streamNumber The stream number that contains the {@link DatabaseInterfaceNew} data.+ */+ public DatabaseInterfaceNew(AbstractPdb pdb, int streamNumber) {+ super(pdb, streamNumber);+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ protected void deserializeHeader(PdbByteReader reader) throws PdbException {+ //System.out.println(reader.dump(0x200));+ versionSignature = reader.parseUnsignedIntVal();+ versionNumber = reader.parseUnsignedIntVal();+ age = reader.parseUnsignedIntVal();++ streamNumberGlobalStaticSymbols = reader.parseUnsignedShortVal();++ // Has bit-fields that could be broken out further+ universalVersion = reader.parseUnsignedShortVal();++ streamNumberPublicStaticSymbols = reader.parseUnsignedShortVal();+ pdbDllBuildVersion = reader.parseUnsignedShortVal();++ streamNumberSymbolRecords = reader.parseUnsignedShortVal();+ pdbDllReleaseBuildVersion = reader.parseUnsignedShortVal();++ lengthModuleInformationSubstream = reader.parseInt();+ lengthSectionContributionSubstream = reader.parseInt();+ lengthSectionMap = reader.parseInt();+ lengthFileInformation = reader.parseInt();+ lengthTypeServerMapSubstream = reader.parseInt();+ indexOfMicrosoftFoundationClassTypeServer = reader.parseUnsignedIntVal();+ lengthOptionalDebugHeader = reader.parseInt();+ lengthEditAndContinueSubstream = reader.parseInt();++ flags = reader.parseUnsignedShortVal();+ machineType = reader.parseUnsignedShortVal();++ padReserve = reader.parseUnsignedIntVal();++ }++ @Override+ protected void deserializeInternalSubstreams(PdbByteReader reader) throws PdbException {+ processModuleInformation(reader, false);+ processSectionContributions(reader, false);+ processSegmentMap(reader, false);+ processFileInformation(reader, false);+// super.deserializeInternalSubstreams(reader);+ processTypeServerMap(reader, false);+ //Note that the next two are in reverse order from their length fields in the header.+ processEditAndContinueInformation(reader, false);+ processDebugHeader(reader, false);+ }++ @Override+ protected void deserializeAdditionalSubstreams(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ symbolRecords.deserialize(monitor);+// super.deserializeAdditionalSubstreams();+ //TODO: Process further information that might be found from ProcessTypeServerMap,+ // processEditAndContinueInformation, and processDebugHeader. The last of these created+ // a list of debug streams (also seen in each SectionContributionInformation).+ }++ @Override+ protected void processModuleInformation(PdbByteReader reader, boolean skip)+ throws PdbException {+ if (lengthModuleInformationSubstream == 0) {+ return;+ }+ if (skip) {+ reader.skip(lengthModuleInformationSubstream);+ return;+ }+ PdbByteReader substreamReader =+ reader.getSubPdbByteReader(lengthModuleInformationSubstream);+ while (substreamReader.hasMore()) {+ AbstractModuleInformation moduleInformation = new ModuleInformation600();+ moduleInformation.deserialize(substreamReader);+ moduleInformationList.add(moduleInformation);+ }+ }++ @Override+ protected void dumpHeader(Writer writer) throws IOException {+ StringBuilder builder = new StringBuilder();+ builder.append("versionSignature: ");+ builder.append(versionSignature);+ builder.append("\nversionNumber: ");+ builder.append(versionNumber);+ builder.append("\nage: ");+ builder.append(age);+ builder.append("\nstreamNumberGlobalStaticSymbols: ");+ builder.append(streamNumberGlobalStaticSymbols);+ builder.append(String.format("\nuniversalVersion: 0x%04x", universalVersion));+ builder.append("\nstreamNumberPublicStaticSymbols: ");+ builder.append(streamNumberPublicStaticSymbols);+ builder.append(String.format("\npdbDllBuildVersion: 0x%04x", pdbDllBuildVersion));+ builder.append("\nstreamNumberSymbolRecords: ");+ builder.append(streamNumberSymbolRecords);+ builder.append(+ String.format("\npdbDllReleaseBuildVersion: 0x%04x", pdbDllReleaseBuildVersion));+ builder.append("\nlengthModuleInformationSubstream: ");+ builder.append(lengthModuleInformationSubstream);+ builder.append("\nlengthSectionContributionSubstream: ");+ builder.append(lengthSectionContributionSubstream);+ builder.append("\nlengthSectionMap: ");+ builder.append(lengthSectionMap);+ builder.append("\nlengthFileInformation: ");+ builder.append(lengthFileInformation);++ builder.append("\nlengthTypeServerMapSubstream: ");+ builder.append(lengthTypeServerMapSubstream);+ builder.append("\nindexOfMicrosoftFoundationClassTypeServer: ");+ builder.append(indexOfMicrosoftFoundationClassTypeServer);+ builder.append("\nlengthOptionalDebugHeader: ");+ builder.append(lengthOptionalDebugHeader);+ builder.append("\nlengthEditAndContinueSubstream: ");+ builder.append(lengthEditAndContinueSubstream);+ builder.append(String.format("\nflags: 0x%04x", flags));+ builder.append(String.format("\nmachineType: 0x%04x", machineType));+ builder.append("\npadReserve: ");+ builder.append(padReserve);+ writer.write(builder.toString());+ }++ @Override+ protected void dumpInternalSubstreams(Writer writer) throws IOException {+ writer.write("ModuleInformationList---------------------------------------\n");+ dumpModuleInformation(writer);+ writer.write("\nEnd ModuleInformationList-----------------------------------\n");+ writer.write("SectionContributionList-------------------------------------\n");+ dumpSectionContributions(writer);+ writer.write("\nEnd SectionContributionList---------------------------------\n");+ writer.write("SegmentMap--------------------------------------------------\n");+ dumpSegmentMap(writer);+ writer.write("\nEnd SegmentMap----------------------------------------------\n");+// super.dumpInternalSubstreams();+ writer.write("EditAndContinueNameList-------------------------------------\n");+ dumpEditAndContinueNameList(writer);+ writer.write("\nEditAndContinueNameList-------------------------------------\n");+ writer.write("DebugStreamList---------------------------------------------\n");+ dumpDebugStreamList(writer);+ writer.write("\nEnd DebugStreamList-----------------------------------------\n");+ }++ //==============================================================================================+ // Internal Data Methods+ //==============================================================================================+ //TODO: Find examples that exercise this.+ /**+ * Deserializes/Processes the TypeServerMap.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @param skip Skip over the data in the {@link PdbByteReader}.+ * @throws PdbException Upon not enough data left to parse.+ */+ @SuppressWarnings("unused") // substreamReader+ protected void processTypeServerMap(PdbByteReader reader, boolean skip) throws PdbException {+ // Following for developmental investigation. Set breakpoint on 'a = 1' line.+ if (lengthTypeServerMapSubstream != 0) {+ // The following code is for developmental investigations;+ // set break point on "int a = 1;" instead of a+ // conditional break point.+ int a = 1;+ a = a + 1;+ }+ if (lengthTypeServerMapSubstream == 0) {+ return;+ }+ if (skip) {+ reader.skip(lengthTypeServerMapSubstream);+ return;+ }+ PdbByteReader substreamReader = reader.getSubPdbByteReader(lengthTypeServerMapSubstream);+ //System.out.println(sumbstreamReader.dump(0x1000));+ }++ /**+ * Deserializes/Processes the EditAndContinueInformation.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @param skip Skip over the data in the {@link PdbByteReader}.+ * @throws PdbException upon error parsing a name.+ */+ @SuppressWarnings("unused") // hashVal+ protected void processEditAndContinueInformation(PdbByteReader reader, boolean skip)+ throws PdbException {+ if (lengthEditAndContinueSubstream == 0) {+ return;+ }+ if (skip) {+ reader.skip(lengthEditAndContinueSubstream);+ return;+ }+ PdbByteReader substreamReader = reader.getSubPdbByteReader(lengthEditAndContinueSubstream);+ //System.out.println(substreamReader.dump(0x1000));+ long hdr = substreamReader.parseUnsignedIntVal();+ int ver = substreamReader.parseInt(); // spec says unsigned, but I believe small vals.+ if (hdr != 0xeffeeffeL) {+ return; //For now... we are not going to try to populate this with a conversion.+ }+ switch (ver) {+ case 1:+ hasher = new Hasher32();+ break;+ case 2:+ hasher = new Hasher32V2();+ break;+ case 0: // Maybe should use Hasher()???+ default:+ return;+ }+ int length = substreamReader.parseInt();+ PdbByteReader bufferReader = substreamReader.getSubPdbByteReader(length);+ //System.out.println(bufferReader.dump());+ int tableSize = substreamReader.parseInt();+ int count = tableSize;+ int realEntryCount = 0;+ while (--count >= 0) {+ int offset = substreamReader.parseInt();+ bufferReader.setIndex(offset);+ String name = bufferReader.parseNullTerminatedString();+ //if (name != null) {+ if (name.length() != 0) {+ realEntryCount++;+ }+ editAndContinueNameList.add(name);+ //long hashVal = (name == null) ? 0 : hasher.hash(name, 0xffffffffL);+ long hashVal = (name.length() == 0) ? 0 : hasher.hash(name, 0xffffffffL);+ hashVal %= tableSize;+ //TODO: what to do with hashVal???+ //System.out.println(offset + ": " + name + " " + hashVal);+ }+ int numRealEntries = substreamReader.parseInt();+ if (realEntryCount != numRealEntries) {+ assert false;+ }+ }++ /**+ * Deserializes/Processes the DebugHeader.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @param skip Skip over the data in the {@link PdbByteReader}.+ * @throws PdbException Upon not enough data left to parse.+ */+ protected void processDebugHeader(PdbByteReader reader, boolean skip) throws PdbException {+ if (lengthOptionalDebugHeader == 0) {+ return;+ }+ if (skip) {+ reader.skip(lengthOptionalDebugHeader);+ return;+ }+ PdbByteReader substreamReader = reader.getSubPdbByteReader(lengthOptionalDebugHeader);+ //System.out.println(substreamReader.dump(0x1000));+ while (substreamReader.hasMore()) {+ int debugStreamNumber = substreamReader.parseUnsignedShortVal();+ debugStreamList.add(debugStreamNumber);+ }+ }++ /**+ * Dumps the EditAndContinueNameList. This package-protected method is for debugging only.+ * @param writer {@link Writer} to which to write the debug dump.+ * @throws IOException On issue writing to the {@link Writer}.+ */+ protected void dumpEditAndContinueNameList(Writer writer) throws IOException {+ for (String name : editAndContinueNameList) {+ writer.write(String.format("Name: %s\n", name));+ }+ }++ /**+ * Dumps the DebugStreamList. This package-protected method is for debugging only.+ * @param writer {@link Writer} to which to write the debug dump.+ * @throws IOException On issue writing to the {@link Writer}.+ */+ protected void dumpDebugStreamList(Writer writer) throws IOException {+ for (int strmNumber : debugStreamList) {+ writer.write(String.format("StrmNumber: %04x\n", strmNumber));+ }+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/DatabaseInterfaceParser.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/DatabaseInterfaceParser.javanew file mode 100644index 0000000000..fb545f5cfc--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/DatabaseInterfaceParser.java@@ -0,0 +1,101 @@+/* ###+ * 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.pdb.pdbreader;++import java.io.IOException;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.pdb.msfreader.MsfStream;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * Parser for detecting the appropriate {@link AbstractDatabaseInterface} format for the filename+ * given. It then creates and returns the appropriate {@link AbstractDatabaseInterface} object.+ */+public class DatabaseInterfaceParser {++ private static final int DATABASE_INTERFACE_STREAM_NUMBER = 3;++ //==============================================================================================+ public static final int DBIHDR700_SIG = 0xffffffff;+ public static final int DBI41_ID = 930803; // 0x000e33f3+ public static final int DBI50_ID = 19960307; // 0x013091f3+ public static final int DBI60_ID = 19970606; // 0x0130ba2e+ public static final int DBI70_ID = 19990903; // 0x01310977+ public static final int DBI110_ID = 20091201; // 0x01329141++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Parses information to determine the version of Database Interface to create.+ * @param pdb {@link AbstractPdb} that owns this Database Interface.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @return {@link AbstractDatabaseInterface} of the appropriate Database Interface.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException Upon error in processing components.+ * @throws CancelledException Upon user cancellation.+ */+ public AbstractDatabaseInterface parse(AbstractPdb pdb, TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ AbstractDatabaseInterface databaseInterface;++ int streamNumber = getStreamNumber();+ MsfStream stream = pdb.getMsf().getStream(streamNumber);+ if (stream.getLength() == 0) {+ return null;+ }+ byte[] bytes = stream.read(0, 8, monitor);+ PdbByteReader reader = new PdbByteReader(bytes);+ int headerSignature = reader.parseInt();+ int versionNumber = reader.parseInt();++ if (headerSignature == DBIHDR700_SIG) {+ switch (versionNumber) {+ case DBI41_ID:+ case DBI50_ID:+ case DBI60_ID:+ case DBI70_ID:+ case DBI110_ID:+ databaseInterface = new DatabaseInterfaceNew(pdb, streamNumber);+ break;+ default:+ throw new PdbException("Unknown DBI Version");+ }+ }+ else {+ databaseInterface = new DatabaseInterface(pdb, streamNumber);+ }++ return databaseInterface;+ }++ //==============================================================================================+ // Internal Data Methods+ //==============================================================================================+ /**+ * Returns the standard stream number that contains the serialized Database Interface.+ * @return Stream number that contains the Database Interface.+ */+ protected int getStreamNumber() {+ return DATABASE_INTERFACE_STREAM_NUMBER;++ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/DenseIntegerArray.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/DenseIntegerArray.javanew file mode 100644index 0000000000..3177c58dc2--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/DenseIntegerArray.java@@ -0,0 +1,86 @@+/* ###+ * 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.pdb.pdbreader;++import java.util.ArrayList;+import java.util.List;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class represents Dense Integer Array component of a PDB file. This class is only+ * suitable for reading; not for writing or modifying a PDB.+ * <P>+ * We have intended to implement according to the Microsoft PDB API (source); see the API for+ * truth.+ */+public class DenseIntegerArray {++ private static final int[] bitMask = { 0x00000001, 0x00000002, 0x00000004, 0x00000008,+ 0x00000010, 0x00000020, 0x00000040, 0x00000080, 0x00000100, 0x00000200, 0x00004000,+ 0x00008000, 0x00001000, 0x00002000, 0x00004000, 0x00008000, 0x00010000, 0x00020000,+ 0x00040000, 0x00080000, 0x00100000, 0x00200000, 0x00400000, 0x00800000, 0x01000000,+ 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000 };++ List<Integer> array = new ArrayList<>();++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Deserializes this {@link DenseIntegerArray}.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws PdbException Upon not enough data left to parse.+ * @throws CancelledException Upon user cancellation.+ */+ public void parse(PdbByteReader reader, TaskMonitor monitor)+ throws PdbException, CancelledException {+ array.clear();+ int arraySize = reader.parseInt();+ for (int i = 0; i < arraySize; i++) {+ monitor.checkCanceled();+ int val = reader.parseInt();+ array.add(val);+ }+ }++ /**+ * Returns whether the dense integer array contains the argument val.+ * @param val Value to check.+ * @return True if value is contained.+ */+ public boolean contains(int val) {+ if (val <= 0) {+ return false;+ }+ int index = val >> 5;+ int bit = val & 0x1f;+ return (index < array.size()) && ((array.get(index) & bitMask[bit]) != 0);+ }++ /**+ * Returns the maximum value allowed in the array. Minimum value is zero.+ * @return Value of maximum unsigned integer allowed.+ */+ public long getMaxPossible() {+ return 32L * array.size();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/GlobalSymbolInformation.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/GlobalSymbolInformation.javanew file mode 100644index 0000000000..66ef29c925--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/GlobalSymbolInformation.java@@ -0,0 +1,188 @@+/* ###+ * 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.pdb.pdbreader;++import java.io.IOException;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.pdb.msfreader.MsfStream;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class represents Global Symbol Information component of a PDB file. This class is only+ * suitable for reading; not for writing or modifying a PDB.+ * <P>+ * We have intended to implement according to the Microsoft PDB API (source); see the API for+ * truth.+ */+public class GlobalSymbolInformation {++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected AbstractPdb pdb;+ protected int lengthHashRecordsBitMap;+ protected int numHashRecords;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param pdbIn {@link AbstractPdb} that owns the Global Symbol Information to process.+ */+ public GlobalSymbolInformation(AbstractPdb pdbIn) {+ pdb = pdbIn;+ }++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Deserialize the Global Symbol Information from the appropriate stream in the Pdb.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException Upon not enough data left to parse.+ * @throws CancelledException Upon user cancellation.+ */+ void deserialize(TaskMonitor monitor) throws IOException, PdbException, CancelledException {+ if (pdb.minimalDebugInfo) {+ //Maybe 0x200 for some and 0x201 for others? 0x200 works for cn3.pdb+ lengthHashRecordsBitMap = 0x200;+ numHashRecords = 0x1000;+ }+ else {+ lengthHashRecordsBitMap = 0x8000;+ numHashRecords = 0x3ffff; //0x40000?+ }+ int streamNumber = pdb.databaseInterface.getGlobalSymbolsStreamNumber();+ MsfStream stream = pdb.getMsf().getStream(streamNumber);+ int length = stream.getLength();+ byte[] bytes = stream.read(0, length, monitor);+ PdbByteReader reader = new PdbByteReader(bytes);+ //System.out.println(reader.dump(0x200));+ //SymbolParser parser = new SymbolParser(pdb);+ deserializeHeader(reader);+ //parser.deserializeSymbolRecords(reader);+ //TODO: left off here 20180717+ }++ //==============================================================================================+ //==============================================================================================+ //==============================================================================================+ // TODO: this contains some experiments for investigating hash reconstruction. Not sure+ // that we need the GlobalSymbolInformation hash table. The GlobalSymbolInformation is+ // supposed to be a "search" mechanism for searching based symbol names.+ // The PublicSymbolInformation is for searching (hash) based upon addresses. Don't need+ // it either, I think.+ @SuppressWarnings("unused")+ private void junkCheck(byte[] bytes1, byte[] bytes2) throws PdbException {+ System.out.println("length1: " + bytes1.length);+ System.out.println("length2: " + bytes2.length);++ //Count bits.+ int count = 0;+ byte x;+ for (int i = 0; i < 0x200; i++) {+ x = bytes2[i];+ count += (x & 0x01);+ x >>= 1;+ count += (x & 0x01);+ x >>= 1;+ count += (x & 0x01);+ x >>= 1;+ count += (x & 0x01);+ x >>= 1;+ count += (x & 0x01);+ x >>= 1;+ count += (x & 0x01);+ x >>= 1;+ count += (x & 0x01);+ x >>= 1;+ count += (x & 0x01);+ }+ System.out.println("Bit count: " + count);++ // Bits are used to expand the rest of bytes2. I can see from cn3.cpp, that+ // there are 1530 bits set and this is exactly how many records remain beyond+ // 0x200 offset. See gsi.cpp: ExpandBuckets as called by readHash(), which is the+ // high level mechanism for reconstructing the hash table.++ //Check values.+ PdbByteReader reader = new PdbByteReader(bytes2);+ reader.parseBytes(0x200);+ int minx1 = Integer.MAX_VALUE;+ int maxx1 = Integer.MIN_VALUE;+ while (reader.hasMore()) {+ int x1 = reader.parseInt();+ minx1 = Math.min(minx1, x1);+ maxx1 = Math.max(maxx1, x1);+ }+ if (maxx1 > bytes1.length) {+ // Adjust (/12 then *8) offsets seen like x1 in loop above. These are then offsets+ // into the bytes1. Then a mechanisms like fixHashiIn() from gsi.cpp would need to+ // be done to create full hash table. Also the "hash" routine (see gsi and misc.h)+ // would need to be implemented to hash the "item" (as I'll call it) coming in...+ // see methods like gsi.cpp: getEnumSyms(), which utilizes the hash table and hash+ // alg. IMPORTANT: I do not know if we "have to have this." Can we get all we+ // need without this hash mechanism?+ }+ System.out.println("minx1: " + minx1);+ System.out.println("maxx1: " + maxx1);+ }++ // TODO: this parsing is incomplete.+ // Suppress "unused" for headerSignature, versionNumber, buf1Reader, and buf2Reader+ /**+ * Deserialize the header of the Global Symbol Information from the appropriate stream+ * in the PDB.+ * @param reader {@link PdbByteReader} containing the data buffer to process.+ * @throws PdbException Upon not enough data left to parse.+ */+ @SuppressWarnings("unused")+ void deserializeHeader(PdbByteReader reader) throws PdbException {+ long headerSignature = reader.parseUnsignedIntVal();+ long versionNumber = reader.parseUnsignedIntVal();+ int lengthHashRecords = reader.parseInt();+ int lengthBuckets = reader.parseInt();+// System.out.println(String.format("GSI: %08x %08x %d %d", headerSignature, versionNumber,+// lengthHashRecords, lengthBuckets));+ PdbByteReader buf1Reader = reader.getSubPdbByteReader(lengthHashRecords);+ //System.out.println(buf1Reader.dump());+ PdbByteReader buf2Reader = reader.getSubPdbByteReader(lengthBuckets);+// junkCheck(buf1, buf2); // TODO: this contains experiments if we want to do more.+ //System.out.println(buf2Reader.dump());+ if (reader.hasMore()) {+ assert false;+ }+ }++ /**+ * Outputs dump of class contents as {@link String}.+ * @return {@link String} containing user-viewable results.+ */+ protected String dump() {+ StringBuilder builder = new StringBuilder();+ builder.append("GlobalSymbolInformation-------------------------------------\n");+ //builder.append(": " + );+ builder.append("\nEnd GlobalSymbolInformation---------------------------------\n");+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/ItemProgramInterfaceParser.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/ItemProgramInterfaceParser.javanew file mode 100644index 0000000000..a626d777c9--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/ItemProgramInterfaceParser.java@@ -0,0 +1,51 @@+/* ###+ * 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.pdb.pdbreader;++/**+ * Parser, extending {@link TypeProgramInterfaceParser}, for detecting and returning the+ * appropriate {@link AbstractTypeProgramInterface} format to be used as the Item Program+ * Interface for the filename given.+ */+public class ItemProgramInterfaceParser extends TypeProgramInterfaceParser {++ private static final int ITEM_PROGRAM_INTERFACE_STREAM_NUMBER = 4;++ //==============================================================================================+ // Internal Data Methods+ //==============================================================================================+ /**+ * Returns the standard stream number that contains the serialized Item Program Interface.+ * @return The standard stream number that contains the Item Program Interface.+ */+ @Override+ protected int getStreamNumber() {+ return ITEM_PROGRAM_INTERFACE_STREAM_NUMBER;++ }++ /**+ * Returns the appropriate {@link CategoryIndex.Category} value needed for while processing+ * the Item Program Interface} (vs. Type Program Interface).+ * @return {@link CategoryIndex.Category#ITEM}.+ */+ @Override+ protected CategoryIndex.Category getCategory() {+ return CategoryIndex.Category.ITEM;++ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/ModuleInformation500.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/ModuleInformation500.javanew file mode 100644index 0000000000..b77d5b3d91--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/ModuleInformation500.java@@ -0,0 +1,50 @@+/* ###+ * 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.pdb.pdbreader;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;++/**+ * This class is the version of {@link AbstractModuleInformation} for Microsoft v5.00 PDB.+ */+public class ModuleInformation500 extends AbstractModuleInformation {++ //==============================================================================================+ // API+ //==============================================================================================+ public ModuleInformation500() {+ sectionContribution = new SectionContribution400();+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ protected void parseAdditionals(PdbByteReader reader) throws PdbException {+ ecSymbolicInformationEnabled = false;+ nameIndexSourceFile = 0; // no value available.+ nameIndexCompilerPdbPath = 0; // no value available.+ moduleName = reader.parseNullTerminatedString();+ objectFileName = reader.parseNullTerminatedString();+ }++ @Override+ protected String dumpAdditionals() {+ return "";+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/ModuleInformation600.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/ModuleInformation600.javanew file mode 100644index 0000000000..0a3360f56d--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/ModuleInformation600.java@@ -0,0 +1,56 @@+/* ###+ * 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.pdb.pdbreader;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;++/**+ * This class is the version of {@link AbstractModuleInformation} for Microsoft v6.00 PDB.+ */+public class ModuleInformation600 extends AbstractModuleInformation {++ //==============================================================================================+ // API+ //==============================================================================================+ public ModuleInformation600() {+ sectionContribution = new SectionContribution600();+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ protected void parseAdditionals(PdbByteReader reader) throws PdbException {+ ecSymbolicInformationEnabled = ((spare & 0x01) == 0x01);+ spare >>= 1;+ nameIndexSourceFile = reader.parseUnsignedIntVal();+ nameIndexCompilerPdbPath = reader.parseUnsignedIntVal();+ moduleName = reader.parseNullTerminatedString();+ objectFileName = reader.parseNullTerminatedString();+ }++ @Override+ protected String dumpAdditionals() {+ StringBuilder builder = new StringBuilder();+ builder.append("\nnameIndexSourceFile: ");+ builder.append(nameIndexSourceFile);+ builder.append("\nnameIndexCompilerPdbPath: ");+ builder.append(nameIndexCompilerPdbPath);+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/NameTable.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/NameTable.javanew file mode 100644index 0000000000..e2661f7f9d--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/NameTable.java@@ -0,0 +1,302 @@+/* ###+ * 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.pdb.pdbreader;++import java.io.IOException;+import java.util.HashMap;+import java.util.Map;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.pdb.msfreader.MsfStream;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class represents Name Table component of a PDB file. This class is only+ * suitable for reading; not for writing or modifying a PDB.+ * <P>+ * We have intended to implement according to the Microsoft PDB API (source); see the API for+ * truth.+ */+public class NameTable {++ private static final long HEADER_MAGIC = 0xeffeeffeL;++ //==============================================================================================+ // Internals+ //==============================================================================================+ private AbstractPdb pdb;++ private int nameBufferSize = 0;+ private int numPairs = 0;+ private int domainSize = 0;+ private DenseIntegerArray presentList = new DenseIntegerArray();+ private DenseIntegerArray deletedList = new DenseIntegerArray();+ private String[] names;+ private int[] streamNumbers;+ private Map<String, Integer> mapNameToStreamNumber = new HashMap<>();+ private Map<Integer, String> mapStreamNumberToName = new HashMap<>();+ private Map<Integer, Map<Integer, String>> mapStreamNumberToStringTable = new HashMap<>();++ private Map<Integer, String> namesMap;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param pdb {@link AbstractPdb} that owns this Name Table.+ */+ public NameTable(AbstractPdb pdb) {+ this.pdb = pdb;+ }++ /**+ * Returns a name from the Name Table pertaining to the index argument.+ * @param index Index of the name to retrieve.+ * @return Name retrieved for the index.+ */+ public String getNameFromStreamNumber(int index) {+ return mapStreamNumberToName.get(index);+ }++ /**+ * Returns an index of the name argument in the NameTable.+ * @param name Name to look up.+ * @return Index of the name.+ */+ public int getStreamNumberFromName(String name) {+ Integer x = mapNameToStreamNumber.getOrDefault(name, -1);+ return x;+ }++ /**+ * Returns a name from the Name Table pertaining to the byte-offset in the block of names for+ * the table.+ * @param offset Byte-offset of the name in the NameTable block.+ * @return Name found at offset.+ */+ public String getNameStringFromOffset(int offset) {+ if (namesMap == null) {+ return null;+ }+ return namesMap.get(offset);+ }++ /**+ * IMPORTANT: This method is for testing only. It allows us to set a basic object.+ * Note: not all values are initialized. Add a paired offset and {@link String} name.+ * @param offset Offset part of pair.+ * @param name Name part of pair.+ */+ public void forTestingOnlyAddOffsetNamePair(int offset, String name) {+ if (namesMap == null) {+ namesMap = new HashMap<>();+ }+ namesMap.put(offset, name);++ }++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ // TODO: Regarding String conversions... We expect that US_ASCII could be a problem, but it+ // is probably better than creating the String without any code set chosen at all. Do we+ // need to change all processing of Strings within the PDB so that we are only creating byte+ // arrays with some notional idea (1 byte, 2 byte, possibly utf-8, utf-16, wchar_t, or+ // "unknown" and defer true interpretation/conversion to String until we know or until+ // Ghidra user can ad-hoc apply interpretations to those fields? Needs investigation, but+ // not critical at this time.+ /**+ * Deserializes the Directory.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException upon error parsing a string.+ * @throws CancelledException Upon user cancellation.+ */+ void deserializeDirectory(PdbByteReader reader, TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {++ // Get the buffer of strings+ nameBufferSize = reader.parseInt();+ PdbByteReader nameBufferReader = reader.getSubPdbByteReader(nameBufferSize);++ // Get the number of pairs and the number of entries (which should be 2 * number of pairs)+ numPairs = reader.parseInt();+ domainSize = reader.parseInt();++ // Using an arbitrary-valued check here for a number too big.+ // Really do not expect there to be many names in name table (from experience); could+ // be on the order of 1 or 10.+ if (numPairs > 0x100000) {+ throw new PdbException("Num Pairs too large.");+ }+ if (numPairs < 0) {+ throw new PdbException("Illegal negative value.");+ }++ names = new String[numPairs];+ streamNumbers = new int[numPairs];++ // Read Present Set. Not really needed by us, as we use the java HashMap.+ presentList.parse(reader, monitor);++ // Read Deleted Set. Not really needed by us, as we use the java HashMap.+ deletedList.parse(reader, monitor);++ // Read values of index into buffer and name index. Load the HashMaps.+ // Since we are using the java HashMap, we do not need to mimic the+ // isPresent Dense Bit Array List (which would, instead, use a for-loop limit+ // of domainSize) and do not need to store the domain and range items+ // in a list indexed by i.+ for (int i = 0; i < numPairs; i++) {+ monitor.checkCanceled();+ int bufOffset = reader.parseInt();+ int streamNumber = reader.parseInt();+ nameBufferReader.setIndex(bufOffset);+ String name = nameBufferReader.parseNullTerminatedString();+ streamNumbers[i] = streamNumber;+ names[i] = name;+ mapStreamNumberToName.put(streamNumber, name);+ mapNameToStreamNumber.put(name, streamNumber);+ }+ deserializeNameTableStreams(monitor);+ }++ // TODO: Reduce code complexity once we know the details for the various cases. Probably+ // should create an abstract map class with derived types for each format we eventually+ // find here.+ /**+ * Deserializes Name Table Streams. An offset-to-string map is created for each stream; each+ * map is placed into a stream-number-to-map map.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException upon error parsing a string.+ * @throws CancelledException Upon user cancellation.+ */+ void deserializeNameTableStreams(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ for (int streamNumber : streamNumbers) {+ monitor.checkCanceled();+ Map<Integer, String> mapOffsetToString = new HashMap<>();+ MsfStream stream = pdb.getMsf().getStream(streamNumber);+ if (stream.getLength() >= 12) {+ byte[] buffer = stream.read(0, stream.getLength(), monitor);+ PdbByteReader reader = new PdbByteReader(buffer);+ long hdrMagic = reader.parseUnsignedIntVal();+ int hdrVer = reader.parseInt();+ if ((hdrMagic == HEADER_MAGIC) && (hdrVer != 0)) {+ switch (hdrVer) {+ case 1:+ // We know this works ver hdrVer==1.+ int length = reader.parseInt();+ PdbByteReader stringReader = reader.getSubPdbByteReader(length);+ while (stringReader.hasMore()) {+ int offset = stringReader.getIndex();+ String string = stringReader.parseNullTerminatedUtf8String();+ mapOffsetToString.put(offset, string);+ }+ // TODO: ? process the rest of the data in reader ?+ break;+ case 2:+ default:+ // TODO: unknown format+ break;+ }+ }+ else {+ // Back up for nonexistent hdrMagic and hdrVer.+ reader.setIndex(reader.getIndex() - 8);+ // TODO: unknown format+ }+ }+ mapStreamNumberToStringTable.put(streamNumber, mapOffsetToString);+ }++ int namesStreamNumber = getStreamNumberFromName("/names");+ namesMap = mapStreamNumberToStringTable.get(namesStreamNumber);++ }++ /**+ * Dumps the Name Table. This method is for debugging only.+ * @return {@link String} of pretty output.+ */+ protected String dump() {+ StringBuilder builder = new StringBuilder();+ builder.append("NameTable---------------------------------------------------");+ builder.append("\nnameBufferSize: ");+ builder.append(nameBufferSize);+ builder.append("\nnumPairs: ");+ builder.append(numPairs);+ builder.append("\ndomainSize: ");+ builder.append(domainSize);+ builder.append("\nmaxPossiblePresent: ");+ builder.append(presentList.getMaxPossible());+ builder.append("\nPresent: {");+ boolean firstSeen = false;+ for (int i = 0; i < presentList.getMaxPossible(); i++) {+ if (presentList.contains(i)) {+ if (firstSeen) {+ builder.append(", ");+ }+ else {+ firstSeen = true;+ }+ builder.append(i);+ }+ }+ builder.append("}");+ builder.append("\nmaxPossibleDeleted: ");+ builder.append(deletedList.getMaxPossible());+ builder.append("\nDeleted: {");+ firstSeen = false;+ for (int i = 0; i < deletedList.getMaxPossible(); i++) {+ if (deletedList.contains(i)) {+ if (firstSeen) {+ builder.append(", ");+ }+ else {+ firstSeen = true;+ }+ builder.append(i);+ }+ }+ builder.append("}\n");+ builder.append("------------------------------------------------------------\n");+ for (String name : mapNameToStreamNumber.keySet()) {+ builder.append(name);+ builder.append(" : ");+ builder.append(mapNameToStreamNumber.get(name));+ builder.append("\n");+ }+ builder.append("------------------------------------------------------------\n");+ for (int streamNumber : mapStreamNumberToName.keySet()) {+ builder.append(streamNumber);+ builder.append(" : ");+ builder.append(mapStreamNumberToName.get(streamNumber));+ builder.append("\n");+ }+ // TODO: output map entries for each table.+ builder.append("End NameTable-----------------------------------------------\n");+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/Pdb200.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/Pdb200.javanew file mode 100644index 0000000000..08a34f16dd--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/Pdb200.java@@ -0,0 +1,69 @@+/* ###+ * 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.pdb.pdbreader;++import java.io.IOException;+import java.io.Writer;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.pdb.msfreader.AbstractMsf;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class is the version of {@link AbstractPdb} for Microsoft v2.00 PDB.+ */+public class Pdb200 extends AbstractPdb {++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Constructor.+ * @param msf {@link AbstractMsf} foundation for the PDB.+ * @throws IOException Upon file IO seek/read issues.+ * @throws PdbException Upon unknown value for configuration or error in processing components.+ */+ Pdb200(AbstractMsf msf) throws IOException, PdbException {+ super(msf);+ }++ @Override+ void deserializeIdentifiersOnly(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ PdbByteReader reader = getDirectoryReader(monitor);+ deserializeVersionSignatureAge(reader);+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ void deserializeDirectory(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ PdbByteReader reader = getDirectoryReader(monitor);+ deserializeVersionSignatureAge(reader);+ }++ @Override+ void dumpDirectory(Writer writer) throws IOException {+ StringBuilder builder = new StringBuilder();+ builder.append(dumpVersionSignatureAge());+ writer.write(builder.toString());+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/Pdb400.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/Pdb400.javanew file mode 100644index 0000000000..09f21ccf71--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/Pdb400.java@@ -0,0 +1,72 @@+/* ###+ * 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.pdb.pdbreader;++import java.io.IOException;+import java.io.Writer;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.pdb.msfreader.AbstractMsf;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class is the version of {@link AbstractPdb} for Microsoft v4.00 PDB.+ */+public class Pdb400 extends AbstractPdb {++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Constructor.+ * @param msf {@link AbstractMsf} foundation for the PDB.+ * @throws IOException Upon file IO seek/read issues.+ * @throws PdbException Upon unknown value for configuration or error in processing components.+ */+ Pdb400(AbstractMsf msf) throws IOException, PdbException {+ super(msf);+ }++ @Override+ void deserializeIdentifiersOnly(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ PdbByteReader reader = getDirectoryReader(monitor);+ deserializeVersionSignatureAge(reader);+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ void deserializeDirectory(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ PdbByteReader reader = getDirectoryReader(monitor);+ deserializeVersionSignatureAge(reader);+ deserializeParameters(reader, monitor);+ }++ @Override+ void dumpDirectory(Writer writer) throws IOException {+ StringBuilder builder = new StringBuilder();+ builder.append(dumpVersionSignatureAge());+ builder.append("\n");+ builder.append(dumpParameters());+ writer.write(builder.toString());+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/Pdb700.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/Pdb700.javanew file mode 100644index 0000000000..ccad63d3da--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/Pdb700.java@@ -0,0 +1,93 @@+/* ###+ * 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.pdb.pdbreader;++import java.io.IOException;+import java.io.Writer;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.pdb.msfreader.AbstractMsf;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class is the version of {@link AbstractPdb} for Microsoft v7.00 PDB.+ */+public class Pdb700 extends AbstractPdb {++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Constructor.+ * @param msf {@link AbstractMsf} foundation for the PDB.+ * @throws IOException Upon file IO seek/read issues.+ * @throws PdbException Upon unknown value for configuration or error in processing components.+ */+ Pdb700(AbstractMsf msf) throws IOException, PdbException {+ super(msf);+ }++ @Override+ void deserializeIdentifiersOnly(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ PdbByteReader reader = getDirectoryReader(monitor);+ deserializeVersionSignatureAge(reader);+ guid = reader.parseGUID();+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ void deserializeDirectory(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ PdbByteReader reader = getDirectoryReader(monitor);+ deserializeVersionSignatureAge(reader);+ guid = reader.parseGUID();+ deserializeParameters(reader, monitor);+ }++ @Override+ void dumpDirectory(Writer writer) throws IOException {+ StringBuilder builder = new StringBuilder();+ builder.append(dumpVersionSignatureAge());+ builder.append("\n");+ builder.append(dumpGUID());+ builder.append("\n");+ builder.append(dumpParameters());+ writer.write(builder.toString());+ }++ //==============================================================================================+ // Internal Data Methods+ //==============================================================================================+ /**+ * Dumps the GUID. This method is for debugging only.+ * @return {@link String} of pretty output.+ */+ protected String dumpGUID() {+ if (guid == null) {+ return "";+ }+ StringBuilder builder = new StringBuilder();+ builder.append("GUID: ");+ builder.append(guid);+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/PdbIdentifiers.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/PdbIdentifiers.javanew file mode 100644index 0000000000..ab6482e15f--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/PdbIdentifiers.java@@ -0,0 +1,79 @@+/* ###+ * 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.pdb.pdbreader;++import ghidra.app.util.datatype.microsoft.GUID;++/**+ * This class holds fields used to identify a PDB.+ * <P>+ * These are Version, Signature, Age, and GUID. Som identifiers can be null if not found in+ * the specific version of the PDB.+ */+public class PdbIdentifiers {++ private int version;+ private int signature;+ private int age;+ private GUID guid;++ /**+ * Constructor.+ * @param version The version number.+ * @param signature The signature.+ * @param age The age.+ * @param guid The GUID (can be null for older PDBs).+ */+ PdbIdentifiers(int version, int signature, int age, GUID guid) {+ this.version = version;+ this.signature = signature;+ this.age = age;+ this.guid = guid;+ }++ /**+ * Returns the Version Number of the PDB.+ * @return Version Number of the PDB.+ */+ public int getVersion() {+ return version;+ }++ /**+ * Returns the Signature of the PDB.+ * @return Signature of the PDB.+ */+ public int getSignature() {+ return signature;+ }++ /**+ * Returns the Age of the PDB.+ * @return Age of the PDB.+ */+ public int getAge() {+ return age;+ }++ /**+ * Returns the GUID for the PDB.+ * @return {@link GUID} for the PDB.+ */+ public GUID getGuid() {+ return guid;+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/PdbParser.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/PdbParser.javanew file mode 100644index 0000000000..d071e119d8--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/PdbParser.java@@ -0,0 +1,96 @@+/* ###+ * 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.pdb.pdbreader;++import java.io.IOException;++import ghidra.pdb.PdbException;+import ghidra.pdb.msfreader.AbstractMsf;+import ghidra.pdb.msfreader.MsfParser;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * Parser for detecting the appropriate {@link AbstractPdb} for the filename given.+ * It then creates and returns the appropriate {@link AbstractPdb} object.+ */+public class PdbParser {++ public static final int VC2_ID = 19941610; // 0x013048ea+ public static final int VC4_ID = 19950623; // 0x01306c1f+ public static final int VC41_ID = 19950814; // 0x01306cde+ public static final int VC50_ID = 19960307; // 0x013091f3+ public static final int VC98_ID = 19970604; // 0x0130ba2c+ public static final int VC70DEP_ID = 19990604; // 0x0131084c+ public static final int VC70_ID = 20000404; // 0x01312e94+ public static final int VC80_ID = 20030901; // 0x0131a5b5+ public static final int VC110_ID = 20091201; // 0x01329141+ public static final int VC140_ID = 20140508; // 0x013351dc++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Static method to open a PDB file, determine its version, and return an {@link AbstractPdb}+ * appropriate for that version; it will not have been deserialized. The main method+ * to deserialize it is {@link AbstractPdb#deserialize(TaskMonitor monitor)}; the method+ * used to deserialize its main identifiers (signature, age, guid (if available)) is+ * {@link AbstractPdb#deserializeIdentifiersOnly(TaskMonitor monitor)}.+ * @param filename {@link String} pathname of the PDB file to parse.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @return {@link AbstractPdb} class object for the file.+ * @throws IOException on file I/O issues.+ * @throws PdbException on parsing issues.+ * @throws CancelledException Upon user cancellation.+ */+ public static AbstractPdb parse(String filename, TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {++ // Do not do a try with resources here, as the msf must live within the PDB that is+ // created below.+ AbstractMsf msf = MsfParser.parse(filename, monitor);++ int versionNumber = AbstractPdb.deserializeVersionNumber(msf, monitor);++ AbstractPdb pdb;+ switch (versionNumber) {+ case VC2_ID:+ pdb = new Pdb200(msf);+ break;+ case VC4_ID:+ case VC41_ID:+ case VC50_ID:+ case VC98_ID:+ case VC70DEP_ID:+ pdb = new Pdb400(msf);+ break;+ case VC70_ID:+ case VC80_ID:+ case VC110_ID:+ case VC140_ID:+ pdb = new Pdb700(msf);+ break;+ default:+ // Must close the MSF here. In cases where PDB is created, the PDB takes+ // responsibility for closing the MSF.+ msf.close();+ throw new PdbException("Unknown PDB Version: " + versionNumber);+ }+ pdb.deserializeIdentifiersOnly(monitor);+ return pdb;+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SectionContribution1400.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SectionContribution1400.javanew file mode 100644index 0000000000..3a63eaf031--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SectionContribution1400.java@@ -0,0 +1,65 @@+/* ###+ * 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.pdb.pdbreader;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;++/**+ * This class is the version of {@link AbstractSectionContribution} for Microsoft v14.00 PDB.+ */+public class SectionContribution1400 extends AbstractSectionContribution {++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ void deserialize(PdbByteReader reader) throws PdbException {+ //System.out.println(reader.dump(0x200));+ isect = reader.parseUnsignedShortVal();+ reader.parseBytes(2); // I think there is padding here.+ offset = reader.parseInt();+ length = reader.parseInt();+ characteristics = reader.parseUnsignedIntVal();+ imod = reader.parseUnsignedShortVal();+ reader.align4();+ dataCrc = reader.parseUnsignedIntVal();+ relocationCrc = reader.parseUnsignedIntVal();+ unknownSectionContributionField = reader.parseUnsignedIntVal();+ }++ @Override+ String dumpInternals() {+ StringBuilder builder = new StringBuilder();+ builder.append("isect: ");+ builder.append(isect);+ builder.append("\noffset: ");+ builder.append(offset);+ builder.append("\nlength: ");+ builder.append(length);+ builder.append(String.format("\ncharacteristics: 0X%08X", characteristics));+ builder.append("\nimod: ");+ builder.append(imod);+ builder.append("\ndataCrc: ");+ builder.append(dataCrc);+ builder.append("\nrelocationCrc: ");+ builder.append(relocationCrc);+ builder.append("\nunknownSectionContributionField: ");+ builder.append(unknownSectionContributionField);+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SectionContribution200.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SectionContribution200.javanew file mode 100644index 0000000000..ca3a5cff35--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SectionContribution200.java@@ -0,0 +1,52 @@+/* ###+ * 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.pdb.pdbreader;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;++/**+ * This class is the version of {@link AbstractSectionContribution} for Microsoft v2.00 PDB.+ */+public class SectionContribution200 extends AbstractSectionContribution {++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ void deserialize(PdbByteReader reader) throws PdbException {+ //System.out.println(reader.dump());+ isect = reader.parseUnsignedShortVal();+ offset = reader.parseInt();+ length = reader.parseInt();+ imod = reader.parseUnsignedShortVal();+ }++ @Override+ String dumpInternals() {+ StringBuilder builder = new StringBuilder();+ builder.append("isect: ");+ builder.append(isect);+ builder.append("\noffset: ");+ builder.append(offset);+ builder.append("\nlength: ");+ builder.append(length);+ builder.append("\nimod: ");+ builder.append(imod);+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SectionContribution400.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SectionContribution400.javanew file mode 100644index 0000000000..f01b287156--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SectionContribution400.java@@ -0,0 +1,55 @@+/* ###+ * 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.pdb.pdbreader;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;++/**+ * This class is the version of {@link AbstractSectionContribution} for Microsoft v4.00 PDB.+ */+public class SectionContribution400 extends AbstractSectionContribution {++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ void deserialize(PdbByteReader reader) throws PdbException {+ //System.out.println(reader.dump(0x200));+ isect = reader.parseUnsignedShortVal();+ reader.parseBytes(2); // I think there is padding here.+ offset = reader.parseInt();+ length = reader.parseInt();+ characteristics = reader.parseUnsignedIntVal();+ imod = reader.parseUnsignedShortVal();+ }++ @Override+ String dumpInternals() {+ StringBuilder builder = new StringBuilder();+ builder.append("isect: ");+ builder.append(isect);+ builder.append("\noffset: ");+ builder.append(offset);+ builder.append("\nlength: ");+ builder.append(length);+ builder.append(String.format("\ncharacteristics: 0X%08X", characteristics));+ builder.append("\nimod: ");+ builder.append(imod);+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SectionContribution600.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SectionContribution600.javanew file mode 100644index 0000000000..4a32b6e3e5--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SectionContribution600.java@@ -0,0 +1,62 @@+/* ###+ * 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.pdb.pdbreader;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;++/**+ * This class is the version of {@link AbstractSectionContribution} for Microsoft v6.00 PDB.+ */+public class SectionContribution600 extends AbstractSectionContribution {++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ void deserialize(PdbByteReader reader) throws PdbException {+ //System.out.println(reader.dump(0x200));+ isect = reader.parseUnsignedShortVal();+ reader.parseBytes(2); // I think there is padding here.+ offset = reader.parseInt();+ length = reader.parseInt();+ characteristics = reader.parseUnsignedIntVal();+ imod = reader.parseUnsignedShortVal();+ reader.align4();+ dataCrc = reader.parseUnsignedIntVal();+ relocationCrc = reader.parseUnsignedIntVal();+ }++ @Override+ String dumpInternals() {+ StringBuilder builder = new StringBuilder();+ builder.append("isect: ");+ builder.append(isect);+ builder.append("\noffset: ");+ builder.append(offset);+ builder.append("\nlength: ");+ builder.append(length);+ builder.append(String.format("\ncharacteristics: 0X%08X", characteristics));+ builder.append("\nimod: ");+ builder.append(imod);+ builder.append("\ndataCrc: ");+ builder.append(dataCrc);+ builder.append("\nrelocationCrc: ");+ builder.append(relocationCrc);+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SegmentMapDescription.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SegmentMapDescription.javanew file mode 100644index 0000000000..c720f1c690--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SegmentMapDescription.java@@ -0,0 +1,90 @@+/* ###+ * 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.pdb.pdbreader;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;++/**+ * This class represents Segment Map Description component of a PDB file. This class is only+ * suitable for reading; not for writing or modifying a PDB.+ * <P>+ * We have intended to implement according to the Microsoft PDB API (source); see the API for+ * truth.+ */+public class SegmentMapDescription {++ //==============================================================================================+ // Internals+ //==============================================================================================+ private int flags;+ private int ovl;+ private int group;+ private int frame;+ private int segNameIndex;+ private int classNameIndex;+ private long segOffset;+ private long segLength;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Deserializes the SegmentMapDescription.+ * @param substreamReader {@link PdbByteReader} from which to deserialize the data.+ * @throws PdbException Upon not enough data left to parse.+ */+ void deserialize(PdbByteReader substreamReader) throws PdbException {+ flags = substreamReader.parseUnsignedShortVal();+ ovl = substreamReader.parseUnsignedShortVal();+ group = substreamReader.parseUnsignedShortVal();+ frame = substreamReader.parseUnsignedShortVal();+ segNameIndex = substreamReader.parseUnsignedShortVal();+ classNameIndex = substreamReader.parseUnsignedShortVal();+ segOffset = substreamReader.parseUnsignedIntVal();+ segLength = substreamReader.parseUnsignedIntVal();+ }++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Dumps the SegmentMapDescription. This method is for debugging only.+ * @return {@link String} of pretty output.+ */+ protected String dump() {+ StringBuilder builder = new StringBuilder();+ builder.append("SegmentMapDescription---------------------------------------");+ builder.append("\nflags: ");+ builder.append(flags);+ builder.append("\novl: ");+ builder.append(ovl);+ builder.append("\ngroup: ");+ builder.append(group);+ builder.append("\nframe: ");+ builder.append(frame);+ builder.append("\nsegNameIndex: ");+ builder.append(segNameIndex);+ builder.append("; classNameIndex: ");+ builder.append(classNameIndex);+ builder.append("; segOffset: ");+ builder.append(segOffset);+ builder.append("; segLength: ");+ builder.append(segLength);+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SymbolParser.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SymbolParser.javanew file mode 100644index 0000000000..bea69f963b--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SymbolParser.java@@ -0,0 +1,957 @@+/* ###+ * 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.pdb.pdbreader;++import java.util.HashSet;+import java.util.Set;++import ghidra.pdb.*;+import ghidra.pdb.pdbreader.symbol.*;++/**+ * Parser for detecting the parsing the appropriate Symbol structures ({@link AbstractMsSymbol}) in+ * the PDB.+ */+public class SymbolParser {++ //==============================================================================================+ // Internals+ //==============================================================================================+ private AbstractPdb pdb;++ /**+ * This list indicates which Symbol Types ({@link AbstractMsSymbol}) have been seen in real+ * data, giving us some confidence as to whether we have parsed them OK or not. We can set+ * a break point in the method containing the switch statement to trigger whenever we find a+ * symbol type not in this list.+ */+ private static Set<Integer> symbolTypesSeen = new HashSet<>(); //temporary for filling in types+ private Set<Integer> newSymbolTypesSeen = new HashSet<>();+ static {+ symbolTypesSeen.add(0x0001);+// symbolTypesSeen.add(0x0002);+ symbolTypesSeen.add(0x0003);+// symbolTypesSeen.add(0x0004);+// symbolTypesSeen.add(0x0005);+ symbolTypesSeen.add(0x0006);+// symbolTypesSeen.add(0x0007);+// symbolTypesSeen.add(0x0008);+// symbolTypesSeen.add(0x0009);+// symbolTypesSeen.add(0x000a);+// symbolTypesSeen.add(0x000b);+// symbolTypesSeen.add(0x000c);+// symbolTypesSeen.add(0x000d);+// symbolTypesSeen.add(0x000e);++// symbolTypesSeen.add(0x0100);+// symbolTypesSeen.add(0x0101);+// symbolTypesSeen.add(0x0102);+// symbolTypesSeen.add(0x0103);+// symbolTypesSeen.add(0x0104);+// symbolTypesSeen.add(0x0105);+// symbolTypesSeen.add(0x0106);+// symbolTypesSeen.add(0x0107);+// symbolTypesSeen.add(0x0108);+// symbolTypesSeen.add(0x0109);+// symbolTypesSeen.add(0x010a);+// symbolTypesSeen.add(0x010b);+// symbolTypesSeen.add(0x010c);++// symbolTypesSeen.add(0x0200);+// symbolTypesSeen.add(0x0201);+// symbolTypesSeen.add(0x0202);+// symbolTypesSeen.add(0x0203);+// symbolTypesSeen.add(0x0204);+// symbolTypesSeen.add(0x0205);+// symbolTypesSeen.add(0x0206);+// symbolTypesSeen.add(0x0207);+// symbolTypesSeen.add(0x0208);+// symbolTypesSeen.add(0x0209);+// symbolTypesSeen.add(0x020a);+// symbolTypesSeen.add(0x020b);+// symbolTypesSeen.add(0x020c);+// symbolTypesSeen.add(0x020d);+// symbolTypesSeen.add(0x020e);+// symbolTypesSeen.add(0x020f);++// symbolTypesSeen.add(0x0300);+// symbolTypesSeen.add(0x0301);++// symbolTypesSeen.add(0x0400);+// symbolTypesSeen.add(0x0401);+// symbolTypesSeen.add(0x0402);+// symbolTypesSeen.add(0x0403);+ symbolTypesSeen.add(0x0404);++// symbolTypesSeen.add(0x1001);+ symbolTypesSeen.add(0x1002);+// symbolTypesSeen.add(0x1003);+// symbolTypesSeen.add(0x1004);+// symbolTypesSeen.add(0x1005);+// symbolTypesSeen.add(0x1006);+// symbolTypesSeen.add(0x1007);+// symbolTypesSeen.add(0x1008);+// symbolTypesSeen.add(0x1009);+// symbolTypesSeen.add(0x100a);+// symbolTypesSeen.add(0x100b);+// symbolTypesSeen.add(0x100c);+// symbolTypesSeen.add(0x100d);+// symbolTypesSeen.add(0x100e);+// symbolTypesSeen.add(0x100f);+// symbolTypesSeen.add(0x1010);+// symbolTypesSeen.add(0x1011);+ symbolTypesSeen.add(0x1012);+// symbolTypesSeen.add(0x1013);+// symbolTypesSeen.add(0x1014);+// symbolTypesSeen.add(0x1015);+// symbolTypesSeen.add(0x1016);+// symbolTypesSeen.add(0x1017);+// symbolTypesSeen.add(0x1018);+// symbolTypesSeen.add(0x1019);+// symbolTypesSeen.add(0x101a);+// symbolTypesSeen.add(0x101b);+// symbolTypesSeen.add(0x101c);+// symbolTypesSeen.add(0x101d);+// symbolTypesSeen.add(0x101e);+// symbolTypesSeen.add(0x101f);+// symbolTypesSeen.add(0x1020);+// symbolTypesSeen.add(0x1021);+// symbolTypesSeen.add(0x1022);+// symbolTypesSeen.add(0x1023);+// symbolTypesSeen.add(0x1024);+// symbolTypesSeen.add(0x1025);+// symbolTypesSeen.add(0x1026);+// symbolTypesSeen.add(0x1027);+// symbolTypesSeen.add(0x1028);+// symbolTypesSeen.add(0x1029);++ symbolTypesSeen.add(0x1101);+ symbolTypesSeen.add(0x1102);+ symbolTypesSeen.add(0x1103);+// symbolTypesSeen.add(0x1104);+ symbolTypesSeen.add(0x1105);+ symbolTypesSeen.add(0x1106);+ symbolTypesSeen.add(0x1107);+ symbolTypesSeen.add(0x1108);+// symbolTypesSeen.add(0x1109);+// symbolTypesSeen.add(0x110a);+ symbolTypesSeen.add(0x110b);+ symbolTypesSeen.add(0x110c);+ symbolTypesSeen.add(0x110d);+ symbolTypesSeen.add(0x110e);+ symbolTypesSeen.add(0x110f);+ symbolTypesSeen.add(0x1110);+ symbolTypesSeen.add(0x1111);+// symbolTypesSeen.add(0x1112);+// symbolTypesSeen.add(0x1113);+ symbolTypesSeen.add(0x1114);+ symbolTypesSeen.add(0x1115);+ symbolTypesSeen.add(0x1116);+// symbolTypesSeen.add(0x1117);+// symbolTypesSeen.add(0x1118);+// symbolTypesSeen.add(0x1119);+// symbolTypesSeen.add(0x111a);+// symbolTypesSeen.add(0x111b);+// symbolTypesSeen.add(0x111c);+// symbolTypesSeen.add(0x111d);+// symbolTypesSeen.add(0x111e);+// symbolTypesSeen.add(0x111f);+ symbolTypesSeen.add(0x1120);+// symbolTypesSeen.add(0x1121);+// symbolTypesSeen.add(0x1122);+// symbolTypesSeen.add(0x1123);+ symbolTypesSeen.add(0x1124);+ symbolTypesSeen.add(0x1125);+// symbolTypesSeen.add(0x1126);+ symbolTypesSeen.add(0x1127);+// symbolTypesSeen.add(0x1128);+ symbolTypesSeen.add(0x1129);+ symbolTypesSeen.add(0x112a);+// symbolTypesSeen.add(0x112b);+ symbolTypesSeen.add(0x112c);+ symbolTypesSeen.add(0x112d);+// symbolTypesSeen.add(0x112e);+// symbolTypesSeen.add(0x112f);+// symbolTypesSeen.add(0x1130);+// symbolTypesSeen.add(0x1131);+ symbolTypesSeen.add(0x1132);+// symbolTypesSeen.add(0x1133);+// symbolTypesSeen.add(0x1134);+// symbolTypesSeen.add(0x1135);+ symbolTypesSeen.add(0x1136);+ symbolTypesSeen.add(0x1137);+ symbolTypesSeen.add(0x1138);+ symbolTypesSeen.add(0x1139);+ symbolTypesSeen.add(0x113a);+// symbolTypesSeen.add(0x113b);+ symbolTypesSeen.add(0x113c);+ symbolTypesSeen.add(0x113d);+ symbolTypesSeen.add(0x113e);+// symbolTypesSeen.add(0x113f);+// symbolTypesSeen.add(0x1140);+ symbolTypesSeen.add(0x1141);+ symbolTypesSeen.add(0x1142);+ symbolTypesSeen.add(0x1143);+ symbolTypesSeen.add(0x1144);+ symbolTypesSeen.add(0x1145);+// symbolTypesSeen.add(0x1146);+// symbolTypesSeen.add(0x1147);+// symbolTypesSeen.add(0x1148);+// symbolTypesSeen.add(0x1149);+// symbolTypesSeen.add(0x114a);+// symbolTypesSeen.add(0x114b);+ symbolTypesSeen.add(0x114c);+ symbolTypesSeen.add(0x114d);+ symbolTypesSeen.add(0x114e);+// symbolTypesSeen.add(0x114f);+// symbolTypesSeen.add(0x1150);+// symbolTypesSeen.add(0x1151);+// symbolTypesSeen.add(0x1152);+ symbolTypesSeen.add(0x1153);+// symbolTypesSeen.add(0x1154);+// symbolTypesSeen.add(0x1155);+// symbolTypesSeen.add(0x1156);+// symbolTypesSeen.add(0x1157);+// symbolTypesSeen.add(0x1158);+ symbolTypesSeen.add(0x1159);+ symbolTypesSeen.add(0x115a);+// symbolTypesSeen.add(0x115b);+// symbolTypesSeen.add(0x115c);+// symbolTypesSeen.add(0x115d);+ symbolTypesSeen.add(0x115e);+// symbolTypesSeen.add(0x115f);+// symbolTypesSeen.add(0x1169);+// symbolTypesSeen.add(0x1161);+// symbolTypesSeen.add(0x1162);+// symbolTypesSeen.add(0x1163);+// symbolTypesSeen.add(0x1164);+// symbolTypesSeen.add(0x1165);+// There is not documentation for anything beyond 0x1165.+// symbolTypesSeen.add(0x1166);+ symbolTypesSeen.add(0x1167);+ symbolTypesSeen.add(0x1168);+ }++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param pdb {@link AbstractPdb} that owns the Symbols to be parsed.+ */+ public SymbolParser(AbstractPdb pdb) {+ this.pdb = pdb;+ }++ /**+ * Returns a list of Symbol IDs that we have not seen in real data while testing.+ * @return {@link String} of pretty output message.+ */+ public String getNewSymbolTypesLog() {+ StringBuilder builder = new StringBuilder();+ DelimiterState ds = new DelimiterState("New Symbol IDs Seen: ", ",");+ for (Integer val : newSymbolTypesSeen) {+ builder.append(ds.out(true, String.format("0x04X, ", val)));+ }+ return builder.toString();+ }++ /**+ * Deserializes an {@link AbstractMsSymbol} from the {@link PdbByteReader} and returns it.+ * @param reader {@link PdbByteReader} from which to deserialize the symbol record.+ * @return {@link AbstractMsSymbol} that was parsed.+ * @throws PdbException upon error parsing a field.+ */+ public AbstractMsSymbol parse(PdbByteReader reader) throws PdbException {+ int symbolTypeId = reader.parseUnsignedShortVal();+ AbstractMsSymbol symbol;+ try {+ symbol = parseRecord(symbolTypeId, reader);+ }+ catch (PdbException e) {+ symbol = new BadMsSymbol(pdb, symbolTypeId);+ }+ return symbol;+ }++ /**+ * Deserializes an {@link AbstractMsSymbol} from the {@link PdbByteReader} and returns it.+ * @param reader {@link PdbByteReader} from which to deserialize the symbol record.+ * @return {@link AbstractMsSymbol} that was parsed.+ * @throws PdbException upon error parsing a field.+ */+ private AbstractMsSymbol parseRecord(int symbolTypeId, PdbByteReader reader)+ throws PdbException {+ //System.out.println(reader.dump(0x200));+ if (symbolTypeId == 0x204) {+ // The following code is for developmental investigations;+ // set break point on "int a = 1;" instead of a+ // conditional break point.+ int a = 1;+ a = a + 1;+ }+ if (symbolTypeId >= 0x1000 && symbolTypeId < 0x1100) {+ if (symbolTypeId != 0x1012) {+ // The following code is for developmental investigations;+ // set break point on "int a = 1;" instead of a+ // conditional break point.+ int a = 1;+ a = a + 1;+ }+ }+ if (!symbolTypesSeen.contains(symbolTypeId)) {+ newSymbolTypesSeen.add(symbolTypeId);+ //System.out.println(String.format("Symbol Type not seen before: %04x", symbolTypeId));+ // Set break point on instruction below to trigger on any symbol types that we+ // have not seen in real data. Then step through the parsing for these new+ // symbol types to confirm that our parsing and the real data agree. Also, comment+ // in the line above to show the ID for this type whenever desired.+ int a = 1;+ a = a + 1;+ }++ AbstractMsSymbol symbol = null;+ switch (symbolTypeId) {+// // 0x0000 block+// case CompileFlagsMsSymbol.PDB_ID:+// symbol = new CompileFlagsMsSymbol(pdb, reader);+//// System.out.println(symbol);+//// System.out.flush();+// break;+// case Register16MsSymbol.PDB_ID:+// symbol = new Register16MsSymbol(pdb, reader);+// break;+// case Constant16MsSymbol.PDB_ID:+// symbol = new Constant16MsSymbol(pdb, reader);+// break;+// case UserDefinedType16MsSymbol.PDB_ID:+// symbol = new UserDefinedType16MsSymbol(pdb, reader);+// break;+// case StartSearchMsSymbol.PDB_ID:+// symbol = new StartSearchMsSymbol(pdb, reader);+// break;+// case EndMsSymbol.PDB_ID:+// symbol = new EndMsSymbol(pdb, reader);+// break;+// case SkipMsSymbol.PDB_ID:+// symbol = new SkipMsSymbol(pdb, reader);+// break;+// case CvReservedMsSymbol.PDB_ID:+// symbol = new CvReservedMsSymbol(pdb, reader);+// break;+// case ObjectNameStMsSymbol.PDB_ID:+// symbol = new ObjectNameStMsSymbol(pdb, reader);+// break;+// case EndArgumentsListMsSymbol.PDB_ID:+// symbol = new EndArgumentsListMsSymbol(pdb, reader);+// break;+// case CobolUserDefinedType16MsSymbol.PDB_ID:+// symbol = new CobolUserDefinedType16MsSymbol(pdb, reader);+// break;+// case ManyRegisterVariable16MsSymbol.PDB_ID:+// symbol = new ManyRegisterVariable16MsSymbol(pdb, reader);+// break;+// case ReturnDescriptionMsSymbol.PDB_ID:+// symbol = new ReturnDescriptionMsSymbol(pdb, reader);+// break;+// case EntryThisMsSymbol.PDB_ID:+// symbol = new EntryThisMsSymbol(pdb, reader);+// break;+//+// // 0x0100 block+// case BasePointerRelative16MsSymbol.PDB_ID:+// symbol = new BasePointerRelative16MsSymbol(pdb, reader);+// break;+// case LocalData16MsSymbol.PDB_ID:+// symbol = new LocalData16MsSymbol(pdb, reader);+// break;+// case GlobalData16MsSymbol.PDB_ID:+// symbol = new GlobalData16MsSymbol(pdb, reader);+// break;+// case Public16MsSymbol.PDB_ID:+// symbol = new Public16MsSymbol(pdb, reader);+// break;+// case LocalProcedureStart16MsSymbol.PDB_ID:+// symbol = new LocalProcedureStart16MsSymbol(pdb, reader);+// break;+// case GlobalProcedureStart16MsSymbol.PDB_ID:+// symbol = new GlobalProcedureStart16MsSymbol(pdb, reader);+// break;+// case Thunk16MsSymbol.PDB_ID:+// symbol = new Thunk16MsSymbol(pdb, reader);+// break;+// case Block16MsSymbol.PDB_ID:+// symbol = new Block16MsSymbol(pdb, reader);+// break;+// case With16MsSymbol.PDB_ID:+// symbol = new With16MsSymbol(pdb, reader);+// break;+// case Label16MsSymbol.PDB_ID:+// symbol = new Label16MsSymbol(pdb, reader);+// break;+// case ChangeExecutionModel16MsSymbol.PDB_ID:+// symbol = new ChangeExecutionModel16MsSymbol(pdb, reader);+// break;+// case VirtualFunctionTable16MsSymbol.PDB_ID:+// symbol = new VirtualFunctionTable16MsSymbol(pdb, reader);+// break;+// case RegisterRelativeAddress16MsSymbol.PDB_ID:+// symbol = new RegisterRelativeAddress16MsSymbol(pdb, reader);+// break;+//+// // 0x0200 block+// case BasePointerRelative3216MsSymbol.PDB_ID:+// symbol = new BasePointerRelative3216MsSymbol(pdb, reader);+// break;+// case LocalData3216MsSymbol.PDB_ID:+// symbol = new LocalData3216MsSymbol(pdb, reader);+// break;+// case GlobalData3216MsSymbol.PDB_ID:+// symbol = new GlobalData3216MsSymbol(pdb, reader);+// break;+// case Public3216MsSymbol.PDB_ID:+// symbol = new Public3216MsSymbol(pdb, reader);+// break;+// case LocalProcedureStart3216MsSymbol.PDB_ID:+// symbol = new LocalProcedureStart3216MsSymbol(pdb, reader);+// break;+// case GlobalProcedureStart3216MsSymbol.PDB_ID:+// symbol = new GlobalProcedureStart3216MsSymbol(pdb, reader);+// break;+// case Thunk32StMsSymbol.PDB_ID:+// symbol = new Thunk32StMsSymbol(pdb, reader);+// break;+// case Block32StMsSymbol.PDB_ID:+// symbol = new Block32StMsSymbol(pdb, reader);+// break;+// case With32StMsSymbol.PDB_ID:+// symbol = new With32StMsSymbol(pdb, reader);+// break;+// case Label32StMsSymbol.PDB_ID:+// symbol = new Label32StMsSymbol(pdb, reader);+// break;+// case ChangeExecutionModel32MsSymbol.PDB_ID:+// symbol = new ChangeExecutionModel32MsSymbol(pdb, reader);+// break;+// case VirtualFunctionTable3216MsSymbol.PDB_ID:+// symbol = new VirtualFunctionTable3216MsSymbol(pdb, reader);+// break;+// case RegisterRelativeAddress3216MsSymbol.PDB_ID:+// symbol = new RegisterRelativeAddress3216MsSymbol(pdb, reader);+// break;+// case LocalThreadStorage3216MsSymbol.PDB_ID:+// symbol = new LocalThreadStorage3216MsSymbol(pdb, reader);+// break;+// case GlobalThreadStorage3216MsSymbol.PDB_ID:+// symbol = new GlobalThreadStorage3216MsSymbol(pdb, reader);+// break;+// case StaticLinkForMipsExceptionHandlingMsSymbol.PDB_ID:+// symbol = new StaticLinkForMipsExceptionHandlingMsSymbol(pdb, reader);+// break;+//+// // 0x0300 block+// case LocalProcedureStartMips16MsSymbol.PDB_ID:+// symbol = new LocalProcedureStartMips16MsSymbol(pdb, reader);+// break;+// case GlobalProcedureStartMips16MsSymbol.PDB_ID:+// symbol = new GlobalProcedureStartMips16MsSymbol(pdb, reader);+// break;+//+// // 0x0400 block+// case ProcedureReferenceStMsSymbol.PDB_ID:+// symbol = new ProcedureReferenceStMsSymbol(pdb, reader);+// break;+// case DataReferenceStMsSymbol.PDB_ID:+// symbol = new DataReferenceStMsSymbol(pdb, reader);+// break;+// case AlignMsSymbol.PDB_ID:+// symbol = new AlignMsSymbol(pdb, reader);+// break;+// case LocalProcedureReferenceStMsSymbol.PDB_ID:+// symbol = new LocalProcedureReferenceStMsSymbol(pdb, reader);+// break;+// case OemDefinedMsSymbol.PDB_ID:+// symbol = new OemDefinedMsSymbol(pdb, reader);+// break;+//+// // 0x1000 block+// case RegisterStMsSymbol.PDB_ID:+// symbol = new RegisterStMsSymbol(pdb, reader);+// break;+// case ConstantStMsSymbol.PDB_ID:+// symbol = new ConstantStMsSymbol(pdb, reader);+// break;+// case UserDefinedTypeStMsSymbol.PDB_ID:+// symbol = new UserDefinedTypeStMsSymbol(pdb, reader);+// break;+// case CobolUserDefinedTypeStMsSymbol.PDB_ID:+// symbol = new CobolUserDefinedTypeStMsSymbol(pdb, reader);+// break;+// case ManyRegisterVariableStMsSymbol.PDB_ID:+// symbol = new ManyRegisterVariableStMsSymbol(pdb, reader);+// break;+// case BasePointerRelative32StMsSymbol.PDB_ID:+// symbol = new BasePointerRelative32StMsSymbol(pdb, reader);+// break;+// case LocalData32StMsSymbol.PDB_ID:+// symbol = new LocalData32StMsSymbol(pdb, reader);+// break;+// case GlobalData32StMsSymbol.PDB_ID:+// symbol = new GlobalData32StMsSymbol(pdb, reader);+// break;+// case Public32StMsSymbol.PDB_ID:+// symbol = new Public32StMsSymbol(pdb, reader);+// break;+// case LocalProcedureStart32StMsSymbol.PDB_ID:+// symbol = new LocalProcedureStart32StMsSymbol(pdb, reader);+// break;+// case GlobalProcedureStart32StMsSymbol.PDB_ID:+// symbol = new GlobalProcedureStart32StMsSymbol(pdb, reader);+// break;+// case VirtualFunctionTable32MsSymbol.PDB_ID:+// symbol = new VirtualFunctionTable32MsSymbol(pdb, reader);+// break;+// case RegisterRelativeAddress32StMsSymbol.PDB_ID:+// symbol = new RegisterRelativeAddress32StMsSymbol(pdb, reader);+// break;+// case LocalThreadStorage32StMsSymbol.PDB_ID:+// symbol = new LocalThreadStorage32StMsSymbol(pdb, reader);+// break;+// case GlobalThreadStorage32StMsSymbol.PDB_ID:+// symbol = new GlobalThreadStorage32StMsSymbol(pdb, reader);+// break;+// case LocalProcedureStartMipsStMsSymbol.PDB_ID:+// symbol = new LocalProcedureStartMipsStMsSymbol(pdb, reader);+// break;+// case GlobalProcedureStartMipsStMsSymbol.PDB_ID:+// symbol = new GlobalProcedureStartMipsStMsSymbol(pdb, reader);+// break;+// case ExtraFrameAndProcedureInformationMsSymbol.PDB_ID:+// symbol = new ExtraFrameAndProcedureInformationMsSymbol(pdb, reader);+// break;+// case Compile2StMsSymbol.PDB_ID:+// symbol = new Compile2StMsSymbol(pdb, reader);+// break;+// case ManyRegisterVariable2StMsSymbol.PDB_ID:+// symbol = new ManyRegisterVariable2StMsSymbol(pdb, reader);+// break;+// case LocalProcedureStartIa64StMsSymbol.PDB_ID:+// symbol = new LocalProcedureStartIa64StMsSymbol(pdb, reader);+// break;+// case GlobalProcedureStartIa64StMsSymbol.PDB_ID:+// symbol = new GlobalProcedureStartIa64StMsSymbol(pdb, reader);+// break;+// case LocalIntermediateLanguageSymbolWithLocalSlotIndexFieldStMsSymbol.PDB_ID:+// symbol = new LocalIntermediateLanguageSymbolWithLocalSlotIndexFieldStMsSymbol(pdb,+// reader);+// break;+// case LocalIntermediateLanguageSymbolWithParameterSlotIndexFieldStMsSymbol.PDB_ID:+// symbol = new LocalIntermediateLanguageSymbolWithParameterSlotIndexFieldStMsSymbol(+// pdb, reader);+// break;+// case AnnotationMsSymbol.PDB_ID:+// symbol = new AnnotationMsSymbol(pdb, reader);+// break;+// case GlobalManagedProcedureStMsSymbol.PDB_ID:+// symbol = new GlobalManagedProcedureStMsSymbol(pdb, reader);+// break;+// case LocalManagedProcedureStMsSymbol.PDB_ID:+// symbol = new LocalManagedProcedureStMsSymbol(pdb, reader);+// break;+// case Reserved1MsSymbol.PDB_ID:+// symbol = new Reserved1MsSymbol(pdb, reader);+// break;+// case Reserved2MsSymbol.PDB_ID:+// symbol = new Reserved2MsSymbol(pdb, reader);+// break;+// case Reserved3MsSymbol.PDB_ID:+// symbol = new Reserved3MsSymbol(pdb, reader);+// break;+// case Reserved4MsSymbol.PDB_ID:+// symbol = new Reserved4MsSymbol(pdb, reader);+// break;+// case LocalManagedDataStMsSymbol.PDB_ID:+// symbol = new LocalManagedDataStMsSymbol(pdb, reader);+// break;+// case GlobalManagedDataStMsSymbol.PDB_ID:+// symbol = new GlobalManagedDataStMsSymbol(pdb, reader);+// break;+// case ManagedLocalOrParameterRelativeToVirtualFramePointerStMsSymbol.PDB_ID:+// symbol =+// new ManagedLocalOrParameterRelativeToVirtualFramePointerStMsSymbol(pdb, reader);+// break;+// case ManagedLocalOrParameterStoredInRegisterStMsSymbol.PDB_ID:+// symbol = new ManagedLocalOrParameterStoredInRegisterStMsSymbol(pdb, reader);+// break;+// case ManagedSymbolWithSlotIndexFieldStMsSymbol.PDB_ID:+// symbol = new ManagedSymbolWithSlotIndexFieldStMsSymbol(pdb, reader);+// break;+// case ManagedLocalOrParameterStoredInManyRegisterStMsSymbol.PDB_ID:+// symbol = new ManagedLocalOrParameterStoredInManyRegisterStMsSymbol(pdb, reader);+// break;+// case ManagedLocalOrParameterRelativeToAlternateFramePointerStMsSymbol.PDB_ID:+// symbol = new ManagedLocalOrParameterRelativeToAlternateFramePointerStMsSymbol(pdb,+// reader);+// break;+// case ManagedLocalOrParameterStoredInManyRegister2StMsSymbol.PDB_ID:+// symbol = new ManagedLocalOrParameterStoredInManyRegister2StMsSymbol(pdb, reader);+// break;+// case IndexForTypeReferencedByNameFromMetadataMsSymbol.PDB_ID:+// symbol = new IndexForTypeReferencedByNameFromMetadataMsSymbol(pdb, reader);+// break;+// case UsingNamespaceStMsSymbol.PDB_ID:+// symbol = new UsingNamespaceStMsSymbol(pdb, reader);+// break;+//+// // 0x1100 block+// case ObjectNameMsSymbol.PDB_ID:+// symbol = new ObjectNameMsSymbol(pdb, reader);+// break;+// case Thunk32MsSymbol.PDB_ID:+// symbol = new Thunk32MsSymbol(pdb, reader);+// break;+// case Block32MsSymbol.PDB_ID:+// symbol = new Block32MsSymbol(pdb, reader);+// break;+// case With32MsSymbol.PDB_ID:+// symbol = new With32MsSymbol(pdb, reader);+// break;+// case Label32MsSymbol.PDB_ID:+// symbol = new Label32MsSymbol(pdb, reader);+// break;+// case RegisterMsSymbol.PDB_ID:+// symbol = new RegisterMsSymbol(pdb, reader);+// break;+// case ConstantMsSymbol.PDB_ID:+// symbol = new ConstantMsSymbol(pdb, reader);+// break;+// case UserDefinedTypeMsSymbol.PDB_ID:+// symbol = new UserDefinedTypeMsSymbol(pdb, reader);+// break;+// case CobolUserDefinedTypeMsSymbol.PDB_ID:+// symbol = new CobolUserDefinedTypeMsSymbol(pdb, reader);+// break;+// case ManyRegisterVariableMsSymbol.PDB_ID:+// symbol = new ManyRegisterVariableMsSymbol(pdb, reader);+// break;+// case BasePointerRelative32MsSymbol.PDB_ID:+// symbol = new BasePointerRelative32MsSymbol(pdb, reader);+// break;+// case LocalData32MsSymbol.PDB_ID:+// symbol = new LocalData32MsSymbol(pdb, reader);+// break;+// case GlobalData32MsSymbol.PDB_ID:+// symbol = new GlobalData32MsSymbol(pdb, reader);+// break;+// case Public32MsSymbol.PDB_ID:+// symbol = new Public32MsSymbol(pdb, reader);+// break;+// case LocalProcedureStart32MsSymbol.PDB_ID:+// symbol = new LocalProcedureStart32MsSymbol(pdb, reader);+// break;+// case GlobalProcedureStart32MsSymbol.PDB_ID:+// symbol = new GlobalProcedureStart32MsSymbol(pdb, reader);+// break;+// case RegisterRelativeAddress32MsSymbol.PDB_ID:+// symbol = new RegisterRelativeAddress32MsSymbol(pdb, reader);+// break;+// case LocalThreadStorage32MsSymbol.PDB_ID:+// symbol = new LocalThreadStorage32MsSymbol(pdb, reader);+// break;+// case GlobalThreadStorage32MsSymbol.PDB_ID:+// symbol = new GlobalThreadStorage32MsSymbol(pdb, reader);+// break;+// case LocalProcedureStartMipsMsSymbol.PDB_ID:+// symbol = new LocalProcedureStartMipsMsSymbol(pdb, reader);+// break;+// case GlobalProcedureStartMipsMsSymbol.PDB_ID:+// symbol = new GlobalProcedureStartMipsMsSymbol(pdb, reader);+// break;+// case Compile2MsSymbol.PDB_ID:+// symbol = new Compile2MsSymbol(pdb, reader);+// break;+// case ManyRegisterVariable2MsSymbol.PDB_ID:+// symbol = new ManyRegisterVariable2MsSymbol(pdb, reader);+// break;+// case LocalProcedureStartIa64MsSymbol.PDB_ID:+// symbol = new LocalProcedureStartIa64MsSymbol(pdb, reader);+// break;+// case GlobalProcedureStartIa64MsSymbol.PDB_ID:+// symbol = new GlobalProcedureStartIa64MsSymbol(pdb, reader);+// break;+// case LocalIntermediateLanguageSymbolWithLocalSlotIndexFieldMsSymbol.PDB_ID:+// symbol =+// new LocalIntermediateLanguageSymbolWithLocalSlotIndexFieldMsSymbol(pdb, reader);+// break;+// case LocalIntermediateLanguageSymbolWithParameterSlotIndexFieldMsSymbol.PDB_ID:+// symbol = new LocalIntermediateLanguageSymbolWithParameterSlotIndexFieldMsSymbol(pdb,+// reader);+// break;+// case LocalManagedDataMsSymbol.PDB_ID:+// symbol = new LocalManagedDataMsSymbol(pdb, reader);+// break;+// case GlobalManagedDataMsSymbol.PDB_ID:+// symbol = new GlobalManagedDataMsSymbol(pdb, reader);+// break;+// case ManagedLocalOrParameterRelativeToVirtualFramePointerMsSymbol.PDB_ID:+// symbol =+// new ManagedLocalOrParameterRelativeToVirtualFramePointerMsSymbol(pdb, reader);+// break;+// case ManagedLocalOrParameterStoredInRegisterMsSymbol.PDB_ID:+// symbol = new ManagedLocalOrParameterStoredInRegisterMsSymbol(pdb, reader);+// break;+// case ManagedSymbolWithSlotIndexFieldMsSymbol.PDB_ID:+// symbol = new ManagedSymbolWithSlotIndexFieldMsSymbol(pdb, reader);+// break;+// case ManagedLocalOrParameterStoredInManyRegisterMsSymbol.PDB_ID:+// symbol = new ManagedLocalOrParameterStoredInManyRegisterMsSymbol(pdb, reader);+// break;+// case ManagedLocalOrParameterRelativeToAlternateFramePointerMsSymbol.PDB_ID:+// symbol =+// new ManagedLocalOrParameterRelativeToAlternateFramePointerMsSymbol(pdb, reader);+// break;+// case ManagedLocalOrParameterStoredInManyRegister2MsSymbol.PDB_ID:+// symbol = new ManagedLocalOrParameterStoredInManyRegister2MsSymbol(pdb, reader);+// break;+// case UsingNamespaceMsSymbol.PDB_ID:+// symbol = new UsingNamespaceMsSymbol(pdb, reader);+// break;+// case ProcedureReferenceMsSymbol.PDB_ID:+// symbol = new ProcedureReferenceMsSymbol(pdb, reader);+// break;+// case DataReferenceMsSymbol.PDB_ID:+// symbol = new DataReferenceMsSymbol(pdb, reader);+// break;+// case LocalProcedureReferenceMsSymbol.PDB_ID:+// symbol = new LocalProcedureReferenceMsSymbol(pdb, reader);+// break;+// case AnnotationReferenceMsSymbol.PDB_ID:+// symbol = new AnnotationReferenceMsSymbol(pdb, reader);+// break;+// case TokenReferenceToManagedProcedureMsSymbol.PDB_ID:+// symbol = new TokenReferenceToManagedProcedureMsSymbol(pdb, reader);+// break;+// case GlobalManagedProcedureMsSymbol.PDB_ID:+// symbol = new GlobalManagedProcedureMsSymbol(pdb, reader);+// break;+// case LocalManagedProcedureMsSymbol.PDB_ID:+// symbol = new LocalManagedProcedureMsSymbol(pdb, reader);+// break;+// case TrampolineMsSymbol.PDB_ID:+// symbol = new TrampolineMsSymbol(pdb, reader);+// break;+// case ManagedConstantMsSymbol.PDB_ID:+// symbol = new ManagedConstantMsSymbol(pdb, reader);+// break;+// case AttributedLocalOrParameterRelativeToVirtualFramePointerMsSymbol.PDB_ID:+// symbol = new AttributedLocalOrParameterRelativeToVirtualFramePointerMsSymbol(pdb,+// reader);+// break;+// case AttributedLocalOrParameterStoredInRegisterMsSymbol.PDB_ID:+// symbol = new AttributedLocalOrParameterStoredInRegisterMsSymbol(pdb, reader);+// break;+// case AttributedLocalOrParameterRelativeToAlternateFramePointerMsSymbol.PDB_ID:+// symbol = new AttributedLocalOrParameterRelativeToAlternateFramePointerMsSymbol(pdb,+// reader);+// break;+// case AttributedLocalOrParameterStoredInManyRegisterMsSymbol.PDB_ID:+// symbol = new AttributedLocalOrParameterStoredInManyRegisterMsSymbol(pdb, reader);+// break;+// case SeparatedCodeFromCompilerSupportMsSymbol.PDB_ID:+// symbol = new SeparatedCodeFromCompilerSupportMsSymbol(pdb, reader);+// break;+// case LocalSymbolInOptimizedCode2005MsSymbol.PDB_ID:+// symbol = new LocalSymbolInOptimizedCode2005MsSymbol(pdb, reader);+// break;+// case DefinedSingleAddressRange2005MsSymbol.PDB_ID:+// symbol = new DefinedSingleAddressRange2005MsSymbol(pdb, reader);+// break;+// case DefinedMultipleAddressRanges2005MsSymbol.PDB_ID:+// symbol = new DefinedMultipleAddressRanges2005MsSymbol(pdb, reader);+// break;+// case PeCoffSectionMsSymbol.PDB_ID:+// symbol = new PeCoffSectionMsSymbol(pdb, reader);+// break;+// case PeCoffGroupMsSymbol.PDB_ID:+// symbol = new PeCoffGroupMsSymbol(pdb, reader);+// break;+// case ExportMsSymbol.PDB_ID:+// symbol = new ExportMsSymbol(pdb, reader);+// break;+// case IndirectCallSiteInfoMsSymbol.PDB_ID:+// symbol = new IndirectCallSiteInfoMsSymbol(pdb, reader);+// break;+// case FrameSecurityCookieMsSymbol.PDB_ID:+// symbol = new FrameSecurityCookieMsSymbol(pdb, reader);+// break;+// case DiscardedByLinkMsSymbol.PDB_ID:+// symbol = new DiscardedByLinkMsSymbol(pdb, reader);+// break;+// case Compile3MsSymbol.PDB_ID:+// symbol = new Compile3MsSymbol(pdb, reader);+// break;+// case EnvironmentBlockMsSymbol.PDB_ID:+// symbol = new EnvironmentBlockMsSymbol(pdb, reader);+// break;+// case LocalSymbolInOptimizedCodeMsSymbol.PDB_ID:+// symbol = new LocalSymbolInOptimizedCodeMsSymbol(pdb, reader);+// break;+// case DefinedSingleAddressRangeMsSymbol.PDB_ID:+// symbol = new DefinedSingleAddressRangeMsSymbol(pdb, reader);+// break;+// case DefinedSingleAddressRangeForSubfieldMsSymbol.PDB_ID:+// symbol = new DefinedSingleAddressRangeForSubfieldMsSymbol(pdb, reader);+// break;+// case DefinedSingleAddressRangeForEnregisteredSymbolMsSymbol.PDB_ID:+// symbol = new DefinedSingleAddressRangeForEnregisteredSymbolMsSymbol(pdb, reader);+// break;+// case DefinedSingleAddressRangeForFramePointerRelativeMsSymbol.PDB_ID:+// symbol = new DefinedSingleAddressRangeForFramePointerRelativeMsSymbol(pdb, reader);+// break;+// case DefinedSingleAddressRangeForEnregisteredFieldOfSymbolMsSymbol.PDB_ID:+// symbol =+// new DefinedSingleAddressRangeForEnregisteredFieldOfSymbolMsSymbol(pdb, reader);+// break;+// case DefinedSingleAddressRangeForFramePointerRelativeFullScopeMsSymbol.PDB_ID:+// symbol = new DefinedSingleAddressRangeForFramePointerRelativeFullScopeMsSymbol(pdb,+// reader);+// break;+// case DefinedSingleAddressRangeForEnregisteredSymbolRelativeMsSymbol.PDB_ID:+// symbol =+// new DefinedSingleAddressRangeForEnregisteredSymbolRelativeMsSymbol(pdb, reader);+// break;+// case LocalProcedure32IdMsSymbol.PDB_ID:+// symbol = new LocalProcedure32IdMsSymbol(pdb, reader);+// break;+// case GlobalProcedure32IdMsSymbol.PDB_ID:+// symbol = new GlobalProcedure32IdMsSymbol(pdb, reader);+// break;+// case LocalProcedureMipsIdMsSymbol.PDB_ID:+// symbol = new LocalProcedureMipsIdMsSymbol(pdb, reader);+// break;+// case GlobalProcedureMipsIdMsSymbol.PDB_ID:+// symbol = new GlobalProcedureMipsIdMsSymbol(pdb, reader);+// break;+// case LocalProcedureIa64IdMsSymbol.PDB_ID:+// symbol = new LocalProcedureIa64IdMsSymbol(pdb, reader);+// break;+// case GlobalProcedureIa64IdMsSymbol.PDB_ID:+// symbol = new GlobalProcedureIa64IdMsSymbol(pdb, reader);+// break;+// case BuildInformationMsSymbol.PDB_ID:+// symbol = new BuildInformationMsSymbol(pdb, reader);+// break;+// case InlinedFunctionCallsiteMsSymbol.PDB_ID:+// symbol = new InlinedFunctionCallsiteMsSymbol(pdb, reader);+// break;+// case InlinedFunctionEndMsSymbol.PDB_ID:+// symbol = new InlinedFunctionEndMsSymbol(pdb, reader);+// break;+// case ProcedureIdEndMsSymbol.PDB_ID:+// symbol = new ProcedureIdEndMsSymbol(pdb, reader);+// break;+// case DefinedAddressRangeHighLevelShaderLanguageMsSymbol.PDB_ID:+// symbol = new DefinedAddressRangeHighLevelShaderLanguageMsSymbol(pdb, reader);+// break;+// case GlobalDataHighLevelShaderLanguageMsSymbol.PDB_ID:+// symbol = new GlobalDataHighLevelShaderLanguageMsSymbol(pdb, reader);+// break;+// case LocalDataHighLevelShaderLanguageMsSymbol.PDB_ID:+// symbol = new LocalDataHighLevelShaderLanguageMsSymbol(pdb, reader);+// break;+// case FileStaticMsSymbol.PDB_ID:+// symbol = new FileStaticMsSymbol(pdb, reader);+// break;+// case LocalDeferredProcedureCallGroupSharedMsSymbol.PDB_ID:+// symbol = new LocalDeferredProcedureCallGroupSharedMsSymbol(pdb, reader);+// break;+// case LocalProcedureStart32DeferredProcedureCallMsSymbol.PDB_ID:+// symbol = new LocalProcedureStart32DeferredProcedureCallMsSymbol(pdb, reader);+// break;+// case LocalProcedure32DeferredProcedureCallIdMsSymbol.PDB_ID:+// symbol = new LocalProcedure32DeferredProcedureCallIdMsSymbol(pdb, reader);+// break;+// case DefinedAddressRangeDeferredProcedureCallPointerTagMsSymbol.PDB_ID:+// symbol =+// new DefinedAddressRangeDeferredProcedureCallPointerTagMsSymbol(pdb, reader);+// break;+// case DeferredProcedureCallPointerTagToSymbolRecordMapMsSymbol.PDB_ID:+// symbol = new DeferredProcedureCallPointerTagToSymbolRecordMapMsSymbol(pdb, reader);+// break;+// case ArmSwitchTableMsSymbol.PDB_ID:+// symbol = new ArmSwitchTableMsSymbol(pdb, reader);+// break;+// case CalleesMsSymbol.PDB_ID:+// symbol = new CalleesMsSymbol(pdb, reader);+// break;+// case CallersMsSymbol.PDB_ID:+// symbol = new CallersMsSymbol(pdb, reader);+// break;+// case ProfileGuidedOptimizationDataMsSymbol.PDB_ID:+// symbol = new ProfileGuidedOptimizationDataMsSymbol(pdb, reader);+// break;+// case InlinedFunctionCallsiteExtendedMsSymbol.PDB_ID:+// symbol = new InlinedFunctionCallsiteExtendedMsSymbol(pdb, reader);+// break;+// case HeapAllocationSiteMsSymbol.PDB_ID:+// symbol = new HeapAllocationSiteMsSymbol(pdb, reader);+// break;+// case ModuleTypeReferenceMsSymbol.PDB_ID:+// symbol = new ModuleTypeReferenceMsSymbol(pdb, reader);+// break;+// case MiniPdbReferenceMsSymbol.PDB_ID:+// symbol = new MiniPdbReferenceMsSymbol(pdb, reader);+// break;+// case MapToMiniPdbMsSymbol.PDB_ID:+// symbol = new MapToMiniPdbMsSymbol(pdb, reader);+// break;+// case GlobalDataHighLevelShaderLanguage32MsSymbol.PDB_ID:+// symbol = new GlobalDataHighLevelShaderLanguage32MsSymbol(pdb, reader);+// break;+// case LocalDataHighLevelShaderLanguage32MsSymbol.PDB_ID:+// symbol = new LocalDataHighLevelShaderLanguage32MsSymbol(pdb, reader);+// break;+// case GlobalDataHighLevelShaderLanguage32ExtendedMsSymbol.PDB_ID:+// symbol = new GlobalDataHighLevelShaderLanguage32ExtendedMsSymbol(pdb, reader);+// break;+// case LocalDataHighLevelShaderLanguage32ExtendedMsSymbol.PDB_ID:+// symbol = new LocalDataHighLevelShaderLanguage32ExtendedMsSymbol(pdb, reader);+// break;+//+// // These should never happen (unless we missed something+// // or MSFT has added new in a version we do not handle.+// // We have recently seen 1167 and 1168, which implies that 1166 must exist.+// case UnknownX1166MsSymbol.PDB_ID:+// symbol = new UnknownX1166MsSymbol(pdb, reader);+// break;+// case UnknownX1167MsSymbol.PDB_ID:+// symbol = new UnknownX1167MsSymbol(pdb, reader);+// break;+// case UnknownX1168MsSymbol.PDB_ID:+// symbol = new UnknownX1168MsSymbol(pdb, reader);+// break;+ default:+ //System.out.println(String.format("Unknown symbolType: %04x", symbolType));+ //System.out.println(reader.dump(0x200));+ //assert false;+ symbol = new UnknownMsSymbol(pdb, reader, symbolTypeId);+ break;+ }++ return symbol;+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SymbolRecords.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SymbolRecords.javanew file mode 100644index 0000000000..8f1c2883e3--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/SymbolRecords.java@@ -0,0 +1,228 @@+/* ###+ * 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.pdb.pdbreader;++import java.io.IOException;+import java.io.Writer;+import java.util.ArrayList;+import java.util.List;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.pdb.msfreader.MsfStream;+import ghidra.pdb.pdbreader.symbol.AbstractMsSymbol;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class represents Symbol Records component of a PDB file. This class is only+ * suitable for reading; not for writing or modifying a PDB.+ * <P>+ * We have intended to implement according to the Microsoft PDB API (source); see the API for+ * truth.+ */+public class SymbolRecords {++ //==============================================================================================+ // Internals+ //==============================================================================================+ private AbstractPdb pdb;+ private List<AbstractMsSymbol> symbolList;+ private List<List<AbstractMsSymbol>> moduleSymbolLists = new ArrayList<>();+ private int comprehensiveSymbolCount = 0;+ private List<AbstractMsSymbol> comprehensiveSymbolList = new ArrayList<>();++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param pdb {@link AbstractPdb} to which the SymbolRecords belong.+ */+ public SymbolRecords(AbstractPdb pdb) {+ this.pdb = pdb;+ }++ /**+ * Return a comprehensive list of Symbols, including from modules.+ * <P>+ * Note: This is Ghidra-added functionality that might eventually go away; it is implemented+ * for investigating how to mine the information we need from the PDB. This might go away in+ * future implementations.+ * @return Comprehensive list of {@link AbstractMsSymbol}s seen.+ */+ protected List<AbstractMsSymbol> getComprehensiveSymbolsList() {+ return comprehensiveSymbolList;+ }++ /**+ * Returns a specific Symbol based on a ghidra-specific recordNumber parameter. The record+ * number is not part of a normal PDB, but we assigned a one-up numbering.+ * <P>+ * Note: This is Ghidra-added functionality that might eventually go away; it is implemented+ * for investigating how to mine the information we need from the PDB. This might go away in+ * future implementations.+ * @param recordNumber The ghidra-specific record number for the {@link AbstractMsSymbol}.+ * @return {@link AbstractMsSymbol} for the recordNumber+ */+ protected AbstractMsSymbol getComprehensiveSymbolRecord(int recordNumber) {+ return comprehensiveSymbolList.get(recordNumber);+ }++ /**+ * Returns the list of global symbols. TODO: check if global and static.+ * @return Global {@link AbstractMsSymbol} symbols. TODO: check if global and static.+ */+ protected List<AbstractMsSymbol> getSymbolsList() {+ return symbolList;+ }++ /**+ * Returns the symbol list for the module as specified by moduleNumber.+ * @param moduleNumber The number ID of the module for which to return the list.+ * @return {@link AbstractMsSymbol} Symbols in the specified module.+ */+ protected List<AbstractMsSymbol> getModuleSymbolLists(int moduleNumber) {+ return moduleSymbolLists.get(moduleNumber);+ }++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * Deserializes the {@link SymbolRecords} from the stream noted in the DBI header.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException Upon not enough data left to parse.+ * @throws CancelledException Upon user cancellation.+ */+ void deserialize(TaskMonitor monitor) throws IOException, PdbException, CancelledException {+ int streamNumber;+ PdbByteReader reader;++ streamNumber = pdb.databaseInterface.getSymbolRecordsStreamNumber();+ reader = getReaderForStreamNumber(streamNumber, monitor);+ symbolList = deserializeSymbolRecords(reader);++ for (AbstractModuleInformation module : pdb.databaseInterface.moduleInformationList) {+ streamNumber = module.getStreamNumberDebugInformation();+ if (streamNumber != 0xffff) {+// System.out.println("\n\nStreamNumber: " + streamNumber);+ reader = getReaderForStreamNumber(streamNumber, monitor);+ int x = reader.parseInt(); // TODO: do not know what this value is.+ int sizeDebug = module.getSizeLocalSymbolsDebugInformation();+ sizeDebug -= x; //TODO: seems right, but need to evaluate this+ PdbByteReader debugReader = reader.getSubPdbByteReader(sizeDebug);+ List<AbstractMsSymbol> moduleList = deserializeSymbolRecords(debugReader);+// System.out.println(reader.dump(4));+// System.out.println("stream: " + streamNumber + ", current index: " ++// reader.getIndex() + ", index limit: " + reader.getLimit());+// System.out.println(reader.dump(0x100));+ // TODO: figure out the rest of the bytes in the stream (index of reader)+ moduleSymbolLists.add(moduleList);+ }+ else {+ moduleSymbolLists.add(null);+ }+ }++ }++ /**+ * Deserializes the {@link AbstractMsSymbol} symbols from the {@link PdbByteReader}.+ * @param reader {@link PdbByteReader} containing the symbol records to deserialize.+ * @return {@link AbstractMsSymbol} symbols.+ * @throws PdbException Upon not enough data left to parse.+ */+ public List<AbstractMsSymbol> deserializeSymbolRecords(PdbByteReader reader)+ throws PdbException {+ int recordNumber = 0;+ //System.out.println(reader.dump(0x400));+ SymbolParser parser = pdb.getSymbolParser();+ List<AbstractMsSymbol> mySymbolList = new ArrayList<>();+ while (reader.hasMore()) {+ // Including length in byte array for alignment purposes.+ //System.out.println("Symbol Record: " + recordNumber);+ if (recordNumber == 839) {+ // The following code is for developmental investigations;+ // set break point on "int a = 1;" instead of a+ // conditional break point.+ int a = 1;+ a = a + 1;+ //System.out.println(reader.dump(0x200));+ }+ int recordLength = reader.parseUnsignedShortVal();+ PdbByteReader recordReader = reader.getSubPdbByteReader(recordLength);+ pdb.pushDependencyStack(+ new CategoryIndex(CategoryIndex.Category.SYMBOL, comprehensiveSymbolCount));+ AbstractMsSymbol symbol = parser.parse(recordReader);+ pdb.popDependencyStack();+ mySymbolList.add(symbol);+ recordNumber++;+ comprehensiveSymbolList.add(symbol);+ comprehensiveSymbolCount++;+ }+ return mySymbolList;+ }++ /**+ * Debug method for dumping information from this Symbol Records instance.+ * @param writer {@link Writer} to which to dump the information.+ * @throws IOException Upon IOException writing to the {@link Writer}.+ */+ protected void dump(Writer writer) throws IOException {+ writer.write("SymbolRecords-----------------------------------------------\n");+ writer.write(dumpSymbolList(symbolList));+ for (int i = 0; i < moduleSymbolLists.size(); i++) {+ List<AbstractMsSymbol> list = moduleSymbolLists.get(i);+ if (list != null) {+ writer.write("Module(" + i + ") List:\n");+ writer.write(dumpSymbolList(list));+ }+ }+ writer.write("\nEnd SymbolRecords-------------------------------------------\n");+ }++ //==============================================================================================+ // Internal Data Methods+ //==============================================================================================+ private PdbByteReader getReaderForStreamNumber(int streamNumber, TaskMonitor monitor)+ throws IOException, CancelledException {+ MsfStream stream = pdb.getMsf().getStream(streamNumber);+ int length = stream.getLength();+ byte[] bytes = stream.read(0, length, monitor);+ PdbByteReader reader = new PdbByteReader(bytes);+ return reader;+ }++ /**+ * Debug method for dumping the symbols from a symbol list+ * @param list The symbol list to dump.+ * @return {@link String} of pretty output of symbols dumped.+ */+ protected String dumpSymbolList(List<AbstractMsSymbol> list) {+ StringBuilder builder = new StringBuilder();+ builder.append("SymbolList--------------------------------------------------");+ for (AbstractMsSymbol symbol : list) {+ builder.append("\n------------------------------------------------------------\n");+ builder.append(symbol);+ }+ builder.append("\nEnd SymbolList----------------------------------------------\n");+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeParser.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeParser.javanew file mode 100644index 0000000000..870b69146c--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeParser.java@@ -0,0 +1,677 @@+/* ###+ * 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.pdb.pdbreader;++import java.util.HashSet;+import java.util.Set;++import ghidra.pdb.*;+import ghidra.pdb.pdbreader.type.*;++/**+ * Parser for detecting the parsing the appropriate Data\Item structures ({@link AbstractMsType})+ * in the PDB.+ */+public class TypeParser {++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected AbstractPdb pdb;++ /**+ * This data is used as we develop this capability, and we could actively use it during+ * normal operations to give feedback towards this continued development.+ * <P>+ * The list indicates which Data Types ({@link AbstractMsType}) have been seen in real data,+ * giving us some confidence as to whether we have parsed them OK or not. We can set a break+ * point in the method containing the switch statement to trigger whenever we find a+ * symbol type not in this list.+ */+ private static Set<Integer> dataTypesSeen = new HashSet<>();+ private Set<Integer> newDataTypesSeen = new HashSet<>();+ static {+ dataTypesSeen.add(0x0001);+ dataTypesSeen.add(0x0002);+ dataTypesSeen.add(0x0003);+ dataTypesSeen.add(0x0004);+ dataTypesSeen.add(0x0005);+ dataTypesSeen.add(0x0006);+ dataTypesSeen.add(0x0007);+ dataTypesSeen.add(0x0008);+ dataTypesSeen.add(0x0009);+ dataTypesSeen.add(0x000a);+// dataTypesSeen.add(0x000b);+// dataTypesSeen.add(0x000c);+// dataTypesSeen.add(0x000d);+// dataTypesSeen.add(0x000e);+// dataTypesSeen.add(0x000f);+// dataTypesSeen.add(0x0010);+// dataTypesSeen.add(0x0011);+// dataTypesSeen.add(0x0012);+// dataTypesSeen.add(0x0013);+// dataTypesSeen.add(0x0014);+// dataTypesSeen.add(0x0015);+// dataTypesSeen.add(0x0016);++// dataTypesSeen.add(0x0200);+ dataTypesSeen.add(0x0201);+// dataTypesSeen.add(0x0202);+// dataTypesSeen.add(0x0203);+ dataTypesSeen.add(0x0204);+// dataTypesSeen.add(0x0205);+ dataTypesSeen.add(0x0206);+ dataTypesSeen.add(0x0207);+// dataTypesSeen.add(0x0208);+// dataTypesSeen.add(0x0209);+// dataTypesSeen.add(0x020a);+// dataTypesSeen.add(0x020b);+// dataTypesSeen.add(0x020c);++ dataTypesSeen.add(0x0400);+// dataTypesSeen.add(0x0401);+// dataTypesSeen.add(0x0402);+ dataTypesSeen.add(0x0403);+// dataTypesSeen.add(0x0404);+// dataTypesSeen.add(0x0405);+ dataTypesSeen.add(0x0406);+ dataTypesSeen.add(0x0407);+ dataTypesSeen.add(0x0408);+ dataTypesSeen.add(0x0409);+ dataTypesSeen.add(0x040a);+// dataTypesSeen.add(0x040b);+ dataTypesSeen.add(0x040c);+// dataTypesSeen.add(0x040d);++ dataTypesSeen.add(0x1001);+ dataTypesSeen.add(0x1002);+ dataTypesSeen.add(0x1003);+ dataTypesSeen.add(0x1004);+ dataTypesSeen.add(0x1005);+ dataTypesSeen.add(0x1006);+ dataTypesSeen.add(0x1007);+ dataTypesSeen.add(0x1008);+ dataTypesSeen.add(0x1009);+// dataTypesSeen.add(0x100a);+// dataTypesSeen.add(0x100b);+// dataTypesSeen.add(0x100c);+// dataTypesSeen.add(0x100d);+// dataTypesSeen.add(0x100e);+// dataTypesSeen.add(0x100f);+// dataTypesSeen.add(0x1010);+// dataTypesSeen.add(0x1011);++ dataTypesSeen.add(0x1201);+// dataTypesSeen.add(0x1202);+ dataTypesSeen.add(0x1203);+// dataTypesSeen.add(0x1204);+ dataTypesSeen.add(0x1205); //Bit-fields+ dataTypesSeen.add(0x1206);+// dataTypesSeen.add(0x1207);+// dataTypesSeen.add(0x1209);+// dataTypesSeen.add(0x1209);+// dataTypesSeen.add(0x120a);++ dataTypesSeen.add(0x1400);+ dataTypesSeen.add(0x1401);+ dataTypesSeen.add(0x1402);+// dataTypesSeen.add(0x1403);+ dataTypesSeen.add(0x1404);+ dataTypesSeen.add(0x1405);+ dataTypesSeen.add(0x1406);+ dataTypesSeen.add(0x1407);+ dataTypesSeen.add(0x1408);+ dataTypesSeen.add(0x1409);+// dataTypesSeen.add(0x140a);+ dataTypesSeen.add(0x140b);+// dataTypesSeen.add(0x140c);+// dataTypesSeen.add(0x140d);+// dataTypesSeen.add(0x140e);+// dataTypesSeen.add(0x140f);++// dataTypesSeen.add(0x1501);+ dataTypesSeen.add(0x1502);+ dataTypesSeen.add(0x1503);+ dataTypesSeen.add(0x1504);+ dataTypesSeen.add(0x1505); //Structures+ dataTypesSeen.add(0x1506);+ dataTypesSeen.add(0x1507);+// dataTypesSeen.add(0x1508);+// dataTypesSeen.add(0x1509);+// dataTypesSeen.add(0x150a);+// dataTypesSeen.add(0x150b);+// dataTypesSeen.add(0x150c);+ dataTypesSeen.add(0x150d);+ dataTypesSeen.add(0x150e);+ dataTypesSeen.add(0x150f);+ dataTypesSeen.add(0x1510);+ dataTypesSeen.add(0x1511);+// dataTypesSeen.add(0x1512);+// dataTypesSeen.add(0x1513);+// dataTypesSeen.add(0x1514);+// dataTypesSeen.add(0x1515);+// dataTypesSeen.add(0x1516);+// dataTypesSeen.add(0x1517);+// dataTypesSeen.add(0x1518);+// dataTypesSeen.add(0x1519);+// dataTypesSeen.add(0x151a);+// dataTypesSeen.add(0x151b);+// dataTypesSeen.add(0x151c);+ dataTypesSeen.add(0x151d);++ dataTypesSeen.add(0x1601);+ dataTypesSeen.add(0x1602);+ dataTypesSeen.add(0x1603);+ dataTypesSeen.add(0x1604);+ dataTypesSeen.add(0x1605);+ dataTypesSeen.add(0x1606);+ dataTypesSeen.add(0x1607);+ }++ protected CategoryIndex.Category category;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param pdb {@link AbstractPdb} that owns the Symbols to be parsed.+ */+ public TypeParser(AbstractPdb pdb) {+ this.pdb = pdb;+ }++ /**+ * Returns a list of Symbol IDs that we have not seen in real data while testing.+ * @return {@link String} of pretty output message.+ */+ public String getNewDataTypesLog() {+ StringBuilder builder = new StringBuilder();+ DelimiterState ds = new DelimiterState("New Symbol IDs Seen: ", ",");+ for (Integer val : newDataTypesSeen) {+ builder.append(ds.out(true, String.format("0x04X, ", val)));+ }+ return builder.toString();+ }++ /**+ * Deserializes an {@link AbstractMsType} from the {@link PdbByteReader} and returns it.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @return {@link AbstractMsType} parsed.+ * @throws PdbException upon error parsing a field.+ */+ public AbstractMsType parse(PdbByteReader reader) throws PdbException {+ int dataTypeId = reader.parseUnsignedShortVal();+ AbstractMsType type;+ try {+ type = parseRecord(dataTypeId, reader);+ }+ catch (PdbException e) {+ type = new BadMsType(pdb, dataTypeId);+ }+ return type;+ }++ /**+ * Deserializes an {@link AbstractMsType} from the {@link PdbByteReader} and returns it.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @return {@link AbstractMsType} parsed.+ * @throws PdbException upon error parsing a field.+ */+ private AbstractMsType parseRecord(int dataTypeId, PdbByteReader reader) throws PdbException {+ //Debugging and research investigation+ //System.out.println(reader.dump());+ // Leaving commented-out code here for continued research/development+// if (dataTypeId == 0x204) {+// if ((length >= 4) && (selectedBytes[1] != 0x04) && !((selectedBytes[0] == 0x00) ||+// (selectedBytes[0] == 0x06) || (selectedBytes[0] == 0x0c))) {+// dump(bytes);+// }+// }++ if (!dataTypesSeen.contains(dataTypeId)) {+ newDataTypesSeen.add(dataTypeId);+ //System.out.println(String.format("Data Type not seen before: %04x", dataTypeId));+ // Set break point on instruction below to trigger on any data types that we+ // have not seen in real data. Then step through the parsing for these new+ // data types to confirm that our parsing and the real data agree. Also, comment+ // in the line above to show the ID for this type whenever desired.+ int a = 1;+ a = a + 1;+ }++ AbstractMsType type = null;+ switch (dataTypeId) {+// // 0x0000 block+// case Modifier16MsType.PDB_ID:+// type = new Modifier16MsType(pdb, reader);+// //System.out.println(type.toString());+// //System.out.flush();+// break;+// case Pointer16MsType.PDB_ID:+// type = new Pointer16MsType(pdb, reader);+// break;+// case Array16MsType.PDB_ID:+// type = new Array16MsType(pdb, reader);+// break;+// case Class16MsType.PDB_ID:+// type = new Class16MsType(pdb, reader);+// break;+// case Structure16MsType.PDB_ID:+// type = new Structure16MsType(pdb, reader);+// break;+// case Union16MsType.PDB_ID:+// type = new Union16MsType(pdb, reader);+// break;+// case Enum16MsType.PDB_ID:+// type = new Enum16MsType(pdb, reader);+// break;+// case Procedure16MsType.PDB_ID:+// type = new Procedure16MsType(pdb, reader);+// break;+// case MemberFunction16MsType.PDB_ID:+// type = new MemberFunction16MsType(pdb, reader);+// break;+// case VtShapeMsType.PDB_ID:+// type = new VtShapeMsType(pdb, reader);+// break;+// case Cobol016MsType.PDB_ID:+// type = new Cobol016MsType(pdb, reader);+// break;+// case Cobol1MsType.PDB_ID:+// type = new Cobol1MsType(pdb, reader);+// break;+// case BasicArray16MsType.PDB_ID:+// type = new BasicArray16MsType(pdb, reader);+// break;+// case LabelMsType.PDB_ID:+// type = new LabelMsType(pdb, reader);+// break;+// case NullMsType.PDB_ID:+// type = new NullMsType(pdb, reader);+// break;+// case NotTranMsType.PDB_ID:+// type = new NotTranMsType(pdb, reader);+// break;+// case DimensionedArray16MsType.PDB_ID:+// type = new DimensionedArray16MsType(pdb, reader);+// break;+// case VirtualFunctionTablePath16MsType.PDB_ID:+// type = new VirtualFunctionTablePath16MsType(pdb, reader);+// break;+// case PrecompiledType16MsType.PDB_ID:+// type = new PrecompiledType16MsType(pdb, reader);+// break;+// case EndPrecompiledTypeMsType.PDB_ID:+// type = new EndPrecompiledTypeMsType(pdb, reader);+// break;+// case OemDefinableString16MsType.PDB_ID:+// type = new OemDefinableString16MsType(pdb, reader);+// break;+// case TypeServerStMsType.PDB_ID:+// type = new TypeServerStMsType(pdb, reader);+// break;+//+// // 0x0200 block+// case Skip16MsType.PDB_ID:+// type = new Skip16MsType(pdb, reader);+// break;+// case ArgumentsList16MsType.PDB_ID:+// type = new ArgumentsList16MsType(pdb, reader);+// break;+// case DefaultArguments16MsType.PDB_ID:+// type = new DefaultArguments16MsType(pdb, reader);+// break;+// case ListMsType.PDB_ID:+// type = new ListMsType(pdb, reader);+// break;+// case FieldList16MsType.PDB_ID:+// type = new FieldList16MsType(pdb, reader);+// break;+// case DerivedClassList16MsType.PDB_ID:+// type = new DerivedClassList16MsType(pdb, reader);+// break;+// case Bitfield16MsType.PDB_ID:+// type = new Bitfield16MsType(pdb, reader);+// break;+// case MethodList16MsType.PDB_ID:+// type = new MethodList16MsType(pdb, reader);+// break;+// case DimensionedArrayConstBoundsUpper16MsType.PDB_ID:+// type = new DimensionedArrayConstBoundsUpper16MsType(pdb, reader);+// break;+// case DimensionedArrayConstBoundsLowerUpper16MsType.PDB_ID:+// type = new DimensionedArrayConstBoundsLowerUpper16MsType(pdb, reader);+// break;+// case DimensionedArrayVarBoundsUpper16MsType.PDB_ID:+// type = new DimensionedArrayVarBoundsUpper16MsType(pdb, reader);+// break;+// case DimensionedArrayVarBoundsLowerUpper16MsType.PDB_ID:+// type = new DimensionedArrayVarBoundsLowerUpper16MsType(pdb, reader);+// break;+// case ReferencedSymbolMsType.PDB_ID:+// type = new ReferencedSymbolMsType(pdb, reader);+// break;+//+// // 0x400 block+// case BaseClass16MsType.PDB_ID:+// type = new BaseClass16MsType(pdb, reader);+// break;+// case VirtualBaseClass16MsType.PDB_ID:+// type = new VirtualBaseClass16MsType(pdb, reader);+// break;+// case IndirectVirtualBaseClass16MsType.PDB_ID:+// type = new IndirectVirtualBaseClass16MsType(pdb, reader);+// break;+// case EnumerateStMsType.PDB_ID:+// type = new EnumerateStMsType(pdb, reader);+// break;+// case FriendFunction16MsType.PDB_ID:+// type = new FriendFunction16MsType(pdb, reader);+// break;+// case Index16MsType.PDB_ID:+// type = new Index16MsType(pdb, reader);+// break;+// case Member16MsType.PDB_ID:+// type = new Member16MsType(pdb, reader);+// break;+// case StaticMember16MsType.PDB_ID:+// type = new StaticMember16MsType(pdb, reader);+// break;+// case OverloadedMethod16MsType.PDB_ID:+// type = new OverloadedMethod16MsType(pdb, reader);+// break;+// case NestedType16MsType.PDB_ID:+// type = new NestedType16MsType(pdb, reader);+// break;+// case VirtualFunctionTablePointer16MsType.PDB_ID:+// type = new VirtualFunctionTablePointer16MsType(pdb, reader);+// break;+// case FriendClass16MsType.PDB_ID:+// type = new FriendClass16MsType(pdb, reader);+// break;+// case OneMethod16MsType.PDB_ID:+// type = new OneMethod16MsType(pdb, reader);+// break;+// case VirtualFunctionTablePointerWithOffset16MsType.PDB_ID:+// type = new VirtualFunctionTablePointerWithOffset16MsType(pdb, reader);+// break;+//+// // 0x1000 block+// case ModifierMsType.PDB_ID:+// type = new ModifierMsType(pdb, reader);+// break;+// case PointerMsType.PDB_ID:+// type = new PointerMsType(pdb, reader);+// break;+// case ArrayStMsType.PDB_ID:+// type = new ArrayStMsType(pdb, reader);+// break;+// case ClassStMsType.PDB_ID:+// type = new ClassStMsType(pdb, reader);+// break;+// case StructureStMsType.PDB_ID:+// type = new StructureStMsType(pdb, reader);+// break;+// case UnionStMsType.PDB_ID:+// type = new UnionStMsType(pdb, reader);+// break;+// case EnumStMsType.PDB_ID:+// type = new EnumStMsType(pdb, reader);+// break;+// case ProcedureMsType.PDB_ID:+// type = new ProcedureMsType(pdb, reader);+// break;+// case MemberFunctionMsType.PDB_ID:+// type = new MemberFunctionMsType(pdb, reader);+// break;+// case Cobol0MsType.PDB_ID:+// type = new Cobol0MsType(pdb, reader);+// break;+// case BasicArrayMsType.PDB_ID:+// type = new BasicArrayMsType(pdb, reader);+// break;+// case DimensionedArrayStMsType.PDB_ID:+// type = new DimensionedArrayStMsType(pdb, reader);+// break;+// case VirtualFunctionTablePathMsType.PDB_ID:+// type = new VirtualFunctionTablePathMsType(pdb, reader);+// break;+// case PrecompiledTypeStMsType.PDB_ID:+// type = new PrecompiledTypeStMsType(pdb, reader);+// break;+// case OemDefinableStringMsType.PDB_ID:+// type = new OemDefinableStringMsType(pdb, reader);+// break;+// case AliasStMsType.PDB_ID:+// type = new AliasStMsType(pdb, reader);+// break;+// case OemDefinableString2MsType.PDB_ID:+// type = new OemDefinableString2MsType(pdb, reader);+// break;+//+// // 0x1200 block+// case SkipMsType.PDB_ID:+// type = new SkipMsType(pdb, reader);+// break;+// case ArgumentsListMsType.PDB_ID:+// type = new ArgumentsListMsType(pdb, reader);+// break;+// case DefaultArgumentsStMsType.PDB_ID:+// type = new DefaultArgumentsStMsType(pdb, reader);+// break;+// case FieldListMsType.PDB_ID:+// type = new FieldListMsType(pdb, reader);+// break;+// case DerivedClassListMsType.PDB_ID:+// type = new DerivedClassListMsType(pdb, reader);+// break;+// case BitfieldMsType.PDB_ID:+// type = new BitfieldMsType(pdb, reader);+// break;+// case MethodListMsType.PDB_ID:+// type = new MethodListMsType(pdb, reader);+// break;+// case DimensionedArrayConstBoundsUpperMsType.PDB_ID:+// type = new DimensionedArrayConstBoundsUpperMsType(pdb, reader);+// break;+// case DimensionedArrayConstBoundsLowerUpperMsType.PDB_ID:+// type = new DimensionedArrayConstBoundsLowerUpperMsType(pdb, reader);+// break;+// case DimensionedArrayVarBoundsUpperMsType.PDB_ID:+// type = new DimensionedArrayVarBoundsUpperMsType(pdb, reader);+// break;+// case DimensionedArrayVarBoundsLowerUpperMsType.PDB_ID:+// type = new DimensionedArrayVarBoundsLowerUpperMsType(pdb, reader);+// break;+//+// // 0x1400 block+// case BaseClassMsType.PDB_ID:+// type = new BaseClassMsType(pdb, reader);+// break;+// case VirtualBaseClassMsType.PDB_ID:+// type = new VirtualBaseClassMsType(pdb, reader);+// break;+// case IndirectVirtualBaseClassMsType.PDB_ID:+// type = new IndirectVirtualBaseClassMsType(pdb, reader);+// break;+// case FriendFunctionStMsType.PDB_ID:+// type = new FriendFunctionStMsType(pdb, reader);+// break;+// case IndexMsType.PDB_ID:+// type = new IndexMsType(pdb, reader);+// break;+// case MemberStMsType.PDB_ID:+// type = new MemberStMsType(pdb, reader);+// break;+// case StaticMemberStMsType.PDB_ID:+// type = new StaticMemberStMsType(pdb, reader);+// break;+// case OverloadedMethodStMsType.PDB_ID:+// type = new OverloadedMethodStMsType(pdb, reader);+// break;+// case NestedTypeStMsType.PDB_ID:+// type = new NestedTypeStMsType(pdb, reader);+// break;+// case VirtualFunctionTablePointerMsType.PDB_ID:+// type = new VirtualFunctionTablePointerMsType(pdb, reader);+// break;+// case FriendClassMsType.PDB_ID:+// type = new FriendClassMsType(pdb, reader);+// break;+// case OneMethodStMsType.PDB_ID:+// type = new OneMethodStMsType(pdb, reader);+// break;+// case VirtualFunctionTablePointerWithOffsetMsType.PDB_ID:+// type = new VirtualFunctionTablePointerWithOffsetMsType(pdb, reader);+// break;+// case NestedTypeExtStMsType.PDB_ID:+// type = new NestedTypeExtStMsType(pdb, reader);+// break;+// case MemberModifyStMsType.PDB_ID:+// type = new MemberModifyStMsType(pdb, reader);+// break;+// case ManagedStMsType.PDB_ID:+// type = new ManagedStMsType(pdb, reader);+// break;+//+// // 0x1500 block+// case TypeServerMsType.PDB_ID:+// type = new TypeServerMsType(pdb, reader);+// break;+// case EnumerateMsType.PDB_ID:+// type = new EnumerateMsType(pdb, reader);+// break;+// case ArrayMsType.PDB_ID:+// type = new ArrayMsType(pdb, reader);+// break;+// case ClassMsType.PDB_ID:+// type = new ClassMsType(pdb, reader);+// break;+// case StructureMsType.PDB_ID:+// type = new StructureMsType(pdb, reader);+// break;+// case UnionMsType.PDB_ID:+// type = new UnionMsType(pdb, reader);+// break;+// case EnumMsType.PDB_ID:+// type = new EnumMsType(pdb, reader);+// break;+// case DimensionedArrayMsType.PDB_ID:+// type = new DimensionedArrayMsType(pdb, reader);+// break;+// case PrecompiledTypeMsType.PDB_ID:+// type = new PrecompiledTypeMsType(pdb, reader);+// break;+// case AliasMsType.PDB_ID:+// type = new AliasMsType(pdb, reader);+// break;+// case DefaultArgumentsMsType.PDB_ID:+// type = new DefaultArgumentsMsType(pdb, reader);+// break;+// case FriendFunctionMsType.PDB_ID:+// type = new FriendFunctionMsType(pdb, reader);+// break;+// case MemberMsType.PDB_ID:+// type = new MemberMsType(pdb, reader);+// break;+// case StaticMemberMsType.PDB_ID:+// type = new StaticMemberMsType(pdb, reader);+// break;+// case OverloadedMethodMsType.PDB_ID:+// type = new OverloadedMethodMsType(pdb, reader);+// break;+// case NestedTypeMsType.PDB_ID:+// type = new NestedTypeMsType(pdb, reader);+// break;+// case OneMethodMsType.PDB_ID:+// type = new OneMethodMsType(pdb, reader);+// break;+// case NestedTypeExtMsType.PDB_ID:+// type = new NestedTypeExtMsType(pdb, reader);+// break;+// case MemberModifyMsType.PDB_ID:+// type = new MemberModifyMsType(pdb, reader);+// break;+// case ManagedMsType.PDB_ID:+// type = new ManagedMsType(pdb, reader);+// break;+// case TypeServer2MsType.PDB_ID:+// type = new TypeServer2MsType(pdb, reader);+// break;+// case StridedArrayMsType.PDB_ID:+// type = new StridedArrayMsType(pdb, reader);+// break;+// case HighLevelShaderLanguageMsType.PDB_ID:+// type = new HighLevelShaderLanguageMsType(pdb, reader);+// break;+// case ModifierExMsType.PDB_ID:+// type = new ModifierExMsType(pdb, reader);+// break;+// case InterfaceMsType.PDB_ID:+// type = new InterfaceMsType(pdb, reader);+// break;+// case BaseInterfaceMsType.PDB_ID:+// type = new BaseInterfaceMsType(pdb, reader);+// break;+// case VectorMsType.PDB_ID:+// type = new VectorMsType(pdb, reader);+// break;+// case MatrixMsType.PDB_ID:+// type = new MatrixMsType(pdb, reader);+// break;+// case VirtualFunctionTableMsType.PDB_ID:+// type = new VirtualFunctionTableMsType(pdb, reader);+// break;+//+// // 0x1600 block+// case FunctionIdMsType.PDB_ID:+// type = new FunctionIdMsType(pdb, reader);+// break;+// case MemberFunctionIdMsType.PDB_ID:+// type = new MemberFunctionIdMsType(pdb, reader);+// break;+// case BuildInfoMsType.PDB_ID:+// type = new BuildInfoMsType(pdb, reader);+// break;+// case SubstringListMsType.PDB_ID:+// type = new SubstringListMsType(pdb, reader);+// break;+// case StringIdMsType.PDB_ID:+// type = new StringIdMsType(pdb, reader);+// break;+// case UserDefinedTypeSourceAndLineMsType.PDB_ID:+// type = new UserDefinedTypeSourceAndLineMsType(pdb, reader);+// break;+// case UserDefinedTypeModuleSourceAndLineMsType.PDB_ID:+// type = new UserDefinedTypeModuleSourceAndLineMsType(pdb, reader);+// //TODO: more work+// break;++ // This should never happen (unless we missed something+ // or MSFT has added new in a version we do not handle.+ default:+ // Commented out because we have issue with VC42 file header of IPI.+// System.out.println(reader.dump());+// assert false;+ type = new UnknownMsType(pdb, reader, dataTypeId);+ break;+ }++ return type;+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeProgramInterface200.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeProgramInterface200.javanew file mode 100644index 0000000000..317a89babb--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeProgramInterface200.java@@ -0,0 +1,89 @@+/* ###+ * 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.pdb.pdbreader;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;++/**+ * This class is the version of {@link AbstractTypeProgramInterface} for Microsoft v2.00 PDB.+ */+public class TypeProgramInterface200 extends AbstractTypeProgramInterface {++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected int hashStreamNumber;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param pdb {@link AbstractPdb} that owns this {@link AbstractTypeProgramInterface}.+ * @param streamNumber The stream number that contains the {@link AbstractTypeProgramInterface}.+ */+ public TypeProgramInterface200(AbstractPdb pdb, int streamNumber) {+ super(pdb, streamNumber);+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ protected void deserializeHeader(PdbByteReader reader) throws PdbException {+ //System.out.println(reader.dump(0x100));+ versionNumber = reader.parseInt();+ typeIndexMin = reader.parseUnsignedShortVal();+ typeIndexMaxExclusive = reader.parseUnsignedShortVal();+ dataLength = reader.parseInt();+ hashStreamNumber = reader.parseUnsignedShortVal();+ reader.align4();+ }++ @Override+ protected String dumpHeader() {+ StringBuilder builder = new StringBuilder();+ builder.append("\nversionNumber: ");+ builder.append(versionNumber);+ builder.append("\ntypeIndexMin: ");+ builder.append(typeIndexMin);+ builder.append("\ntypeIndexMaxExclusive: ");+ builder.append(typeIndexMaxExclusive);+ builder.append("\ndataLength: ");+ builder.append(dataLength);+ builder.append("\nhashStreamNumber: ");+ builder.append(hashStreamNumber);+ return builder.toString();+ }++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * IMPORTANT: This method is for testing only. It allows us to set a basic object.+ * Note: not all values are initialized. This is a dummy constructor used to create a dummy+ * {@link AbstractTypeProgramInterface}.+ * Note: not all values are initialized.+ * @param pdb {@link AbstractPdb} that owns this TypeProgramInterface.+ * @param typeIndexMin The IndexMin to set/use.+ * @param typeIndexMaxExclusive One greater than the MaxIndex to set/use.+ */+ TypeProgramInterface200(AbstractPdb pdb, int typeIndexMin, int typeIndexMaxExclusive) {+ super(pdb, typeIndexMin, typeIndexMaxExclusive);+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeProgramInterface500.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeProgramInterface500.javanew file mode 100644index 0000000000..0506dc6f7a--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeProgramInterface500.java@@ -0,0 +1,87 @@+/* ###+ * 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.pdb.pdbreader;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;++/**+ * This class is the version of {@link AbstractTypeProgramInterface} for Microsoft v5.00 PDB.+ */+public class TypeProgramInterface500 extends AbstractTypeProgramInterface {++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected int hashStreamNumber;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param pdb {@link AbstractPdb} that owns this {@link AbstractTypeProgramInterface}.+ * @param streamNumber The stream number that contains the {@link AbstractTypeProgramInterface}.+ */+ public TypeProgramInterface500(AbstractPdb pdb, int streamNumber) {+ super(pdb, streamNumber);+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ protected void deserializeHeader(PdbByteReader reader) throws PdbException {+ versionNumber = reader.parseInt();+ typeIndexMin = reader.parseInt();+ typeIndexMaxExclusive = reader.parseInt();+ dataLength = reader.parseInt();+ hashStreamNumber = reader.parseUnsignedShortVal();+ }++ @Override+ protected String dumpHeader() {+ StringBuilder builder = new StringBuilder();+ builder.append("\nversionNumber: ");+ builder.append(versionNumber);+ builder.append("\ntypeIndexMin: ");+ builder.append(typeIndexMin);+ builder.append("\ntypeIndexMaxExclusive: ");+ builder.append(typeIndexMaxExclusive);+ builder.append("\ndataLength: ");+ builder.append(dataLength);+ builder.append("\nhashStreamNumber: ");+ builder.append(hashStreamNumber);+ return builder.toString();+ }++ //==============================================================================================+ // Package-Protected Internals+ //==============================================================================================+ /**+ * IMPORTANT: This method is for testing only. It allows us to set a basic object.+ * Note: not all values are initialized. This is a dummy constructor used to create a dummy+ * AbstractTypeProgramInterface.+ * Note: not all values are initialized.+ * @param pdb {@link AbstractPdb} that owns this TypeProgramInterface.+ * @param typeIndexMin The IndexMin to set/use.+ * @param typeIndexMaxExclusive One greater than the MaxIndex to set/use.+ */+ TypeProgramInterface500(AbstractPdb pdb, int typeIndexMin, int typeIndexMaxExclusive) {+ super(pdb, typeIndexMin, typeIndexMaxExclusive);+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeProgramInterface800.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeProgramInterface800.javanew file mode 100644index 0000000000..353886d33f--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeProgramInterface800.java@@ -0,0 +1,200 @@+/* ###+ * 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.pdb.pdbreader;++import java.io.IOException;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.pdb.msfreader.MsfStream;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * This class is the version of {@link AbstractTypeProgramInterface} for Microsoft v8.00 PDB.+ */+public class TypeProgramInterface800 extends AbstractTypeProgramInterface {++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected int headerLength;+ protected TypeProgramInterfaceHash hash;++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Constructor.+ * @param pdb {@link AbstractPdb} that owns this {@link AbstractTypeProgramInterface}.+ * @param streamNumber The stream number that contains the {@link AbstractTypeProgramInterface}.+ */+ public TypeProgramInterface800(AbstractPdb pdb, int streamNumber) {+ super(pdb, streamNumber);+ hash = new TypeProgramInterfaceHash();+ }++ //==============================================================================================+ // Abstract Methods+ //==============================================================================================+ @Override+ protected void deserializeHeader(PdbByteReader reader) throws PdbException {+ versionNumber = reader.parseInt();+ headerLength = reader.parseInt();+ typeIndexMin = reader.parseInt();+ typeIndexMaxExclusive = reader.parseInt();+ dataLength = reader.parseInt();+ hash.deserialize(reader);+ // Commented out, but this is currently where we would put this method. See the note+ // place within the method (deserializeHashStreams()) for more information about why+ // we have this commented out.+// try {+// hash.deserializeHashStreams(pdb);+// }+// catch (PdbException e) {+// //TODO: handle exception.+// }+ }++ @Override+ protected String dumpHeader() {+ StringBuilder builder = new StringBuilder();+ builder.append("\nversionNumber: ");+ builder.append(versionNumber);+ builder.append("\nheaderLength: ");+ builder.append(headerLength);+ builder.append("\ntypeIndexMin: ");+ builder.append(typeIndexMin);+ builder.append("\ntypeIndexMaxExclusive: ");+ builder.append(typeIndexMaxExclusive);+ builder.append("\ndataLength: ");+ builder.append(dataLength);+ builder.append("\n");+ builder.append(hash.dump());+ return builder.toString();+ }++ //==============================================================================================+ // Private Classes+ //==============================================================================================+ protected class TypeProgramInterfaceHash {+ int streamNumber;+ int streamNumberAuxilliary;+ int hashKeySize;+ int numHashBins;+ int offsetHashVals;+ int lengthHashVals;+ int offsetTypeInfoOffsetPairs;+ int lengthTypeInfoOffsetPairs;+ int offsetHashAdjustment;+ int lengthHashAdjustment;++ /**+ * Deserializes the {@link TypeProgramInterfaceHash}.+ * @param reader {@link PdbByteReader} from which to deserialize the data.+ * @throws PdbException Upon not enough data left to parse.+ */+ protected void deserialize(PdbByteReader reader) throws PdbException {+ streamNumber = reader.parseUnsignedShortVal();+ streamNumberAuxilliary = reader.parseUnsignedShortVal();+ hashKeySize = reader.parseInt();+ numHashBins = reader.parseInt();+ offsetHashVals = reader.parseInt();+ lengthHashVals = reader.parseInt();+ offsetTypeInfoOffsetPairs = reader.parseInt();+ lengthTypeInfoOffsetPairs = reader.parseInt();+ offsetHashAdjustment = reader.parseInt();+ lengthHashAdjustment = reader.parseInt();+ }++ // TODO: parsing not complete+ // Suppress "unused" for hashBuffer, typeInfoOffsetPairsBuffer, hashAdjustmentBuffer+ /**+ * *UNDER CONSTRUCTION* Deserializes the Hash Streams...+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException Upon error in processing components.+ * @throws CancelledException Upon user cancellation.+ */+ @SuppressWarnings("unused")+ protected void deserializeHashStreams(TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ // I don't believe we need to parse and process the hash table. They seemingly are+ // used to point from a TypeIndex to a raw (byte[]) Type Record. We are not+ // currently maintaining our records in this raw form; we are processing (parsing)+ // them as we read each record buffer.+ // So... we are not going to do anything more with this method. Note: with real+ // data, we could see that each of the subsections notated by offset/length+ // fell nicely into the complete stream. I am commenting this code out below.+ // Also note that we have no evidence of how the Auxilliary stream is used. Its+ // contents might need to get concatenated with the contents of the primary+ // stream before the processing takes place, but the API does not show it being+ // used at all.+ if (streamNumber == 0xffff) {+ return;+ }+ MsfStream stream = pdb.getMsf().getStream(streamNumber);+ byte[] bytes = stream.read(0, stream.getLength(), monitor);+ PdbByteReader reader = new PdbByteReader(bytes);+ //System.out.println(reader.dump());+ reader.setIndex(offsetHashVals);+ byte[] hashBuffer = reader.parseBytes(lengthHashVals);+ reader.setIndex(offsetTypeInfoOffsetPairs);+ byte[] typeInfoOffsetPairsBuffer = reader.parseBytes(lengthTypeInfoOffsetPairs);+ reader.setIndex(offsetHashAdjustment);+ byte[] hashAdjustmentBuffer = reader.parseBytes(lengthHashAdjustment);+ if (streamNumberAuxilliary == 0xffff) {+ return;+ }+ MsfStream streamAuxilliary = pdb.getMsf().getStream(streamNumberAuxilliary);+ byte[] bytesAuxilliary = streamAuxilliary.read(0, stream.getLength(), monitor);+ PdbByteReader readerAuxilliary = new PdbByteReader(bytesAuxilliary);+ //readerAuxilliary.dump();+ }++ /**+ * Dumps the this {@link TypeProgramInterfaceHash}. This method is for debugging only.+ * @return {@link String} of pretty output.+ */+ protected String dump() {+ StringBuilder builder = new StringBuilder();+ builder.append("Hash--------------------------------------------------------");+ builder.append("\nstreamNumber: ");+ builder.append(streamNumber);+ builder.append("\nstreamNumberAuxilliary: ");+ builder.append(streamNumberAuxilliary);+ builder.append("\nhashKeySize: ");+ builder.append(hashKeySize);+ builder.append("\nnumHashBins: ");+ builder.append(numHashBins);+ builder.append("\noffsetHashVals: ");+ builder.append(offsetHashVals);+ builder.append("\nlengthHashVals: ");+ builder.append(lengthHashVals);+ builder.append("\noffsetTypeInfoOffsetPairs: ");+ builder.append(offsetTypeInfoOffsetPairs);+ builder.append("\nlengthTypeInfoOffsetPairs: ");+ builder.append(lengthTypeInfoOffsetPairs);+ builder.append("\noffsetHashAdjustment: ");+ builder.append(offsetHashAdjustment);+ builder.append("\nlengthHashAdjustment: ");+ builder.append(lengthHashAdjustment);+ return builder.toString();+ }+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeProgramInterfaceParser.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeProgramInterfaceParser.javanew file mode 100644index 0000000000..96a7520574--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/TypeProgramInterfaceParser.java@@ -0,0 +1,123 @@+/* ###+ * 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.pdb.pdbreader;++import java.io.IOException;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.PdbException;+import ghidra.pdb.msfreader.MsfStream;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * Parser for detecting the appropriate {@link AbstractTypeProgramInterface} format for the+ * filename given. It then creates and returns the appropriate+ * {@link AbstractTypeProgramInterface} object.+ */+public class TypeProgramInterfaceParser {++ private static final int TYPE_PROGRAM_INTERFACE_STREAM_NUMBER = 2;++ //==============================================================================================+ public static final int TI20_ID = 920924; // 0x00e0ed5c++ public static final int TI40_ID = 19950410; // 0x01306b4a+ public static final int TI41_ID = 19951122; // 0x01306e12+ public static final int TI42_ID = 19951204; // 0x01360e64 not in MSFT doc: in in MFCS42.PDB+ public static final int TI50DEP_ID = 19960307; // 0x013091f3+ public static final int TI50_ID = 19961031; // 0x013094c7+ public static final int TI70_ID = 19990903; // 0x01310977+ public static final int TI80_ID = 20040203; // 0x0131ca0b++ //==============================================================================================+ // API+ //==============================================================================================+ /**+ * Parses information to determine the version of TypeProgramInterface to create.+ * @param pdb {@link AbstractPdb} that owns this TypeProgramInterface.+ * @param monitor {@link TaskMonitor} used for checking cancellation.+ * @return AbstractTypeProgramInterface of the appropriate TypeProgramInterface, or null+ * if the stream does not have enough information to be parsed.+ * @throws IOException On file seek or read, invalid parameters, bad file configuration, or+ * inability to read required bytes.+ * @throws PdbException Upon error in processing components.+ * @throws CancelledException Upon user cancellation.+ */+ public AbstractTypeProgramInterface parse(AbstractPdb pdb, TaskMonitor monitor)+ throws IOException, PdbException, CancelledException {+ AbstractTypeProgramInterface typeProgramInterface;++ int versionNumberSize = AbstractTypeProgramInterface.getVersionNumberSize();+ int streamNumber = getStreamNumber();+ MsfStream stream = pdb.getMsf().getStream(streamNumber);+ if (stream.getLength() < versionNumberSize) {+ return null;+ }+ byte[] bytes = stream.read(0, versionNumberSize, monitor);++ PdbByteReader reader = new PdbByteReader(bytes);+ int versionNumber = AbstractTypeProgramInterface.deserializeVersionNumber(reader);++ // TODO: we do not know where the line should be drawn for each of these+ // TypeProgramInterface instantiations. Had a TI50_ID that was not an 800 instead+ // of a 500. Also believe that TI42_ID was seen to have 500. Rest is guess until+ // we can validate with real data.+ switch (versionNumber) {+ case TI20_ID:+ case TI40_ID:+ case TI41_ID:+ typeProgramInterface = new TypeProgramInterface200(pdb, streamNumber);+ break;+ case TI42_ID:+ case TI50DEP_ID:+ typeProgramInterface = new TypeProgramInterface500(pdb, streamNumber);+ break;+ case TI50_ID:+ case TI70_ID:+ case TI80_ID:+ typeProgramInterface = new TypeProgramInterface800(pdb, streamNumber);+ break;+ default:+ throw new PdbException("Unknown TPI Version: " + versionNumber);+ }++ typeProgramInterface.setCategory(getCategory());+ return typeProgramInterface;+ }++ //==============================================================================================+ // Internal Data Methods+ //==============================================================================================+ /**+ * Returns the standard stream number that contains the serialized Type Program Interface.+ * @return The standard stream number that contains the Type Program Interface.+ */+ protected int getStreamNumber() {+ return TYPE_PROGRAM_INTERFACE_STREAM_NUMBER;+ }++ /**+ * Returns the appropriate {@link CategoryIndex.Category} value needed for while processing+ * the Type Program Interface} (vs. Item Program Interface).+ * @return {@link CategoryIndex.Category#DATA}.+ */+ protected CategoryIndex.Category getCategory() {+ return CategoryIndex.Category.DATA;++ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/symbol/AbstractMsSymbol.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/symbol/AbstractMsSymbol.javanew file mode 100644index 0000000000..80bb765b90--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/symbol/AbstractMsSymbol.java@@ -0,0 +1,69 @@+/* ###+ * 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.pdb.pdbreader.symbol;++import ghidra.pdb.AbstractParsableItem;+import ghidra.pdb.PdbByteReader;+import ghidra.pdb.pdbreader.AbstractPdb;++/**+ * This class extends {@link AbstractParsableItem} as is the base class for PDB Symbol units.+ */+public abstract class AbstractMsSymbol extends AbstractParsableItem {+ //private static final Class[] parameterTypes = { StringBuilder.class };+ protected AbstractPdb pdb;++ /**+ * Constructor.+ * @param pdb {@link AbstractPdb} to which this symbol belongs.+ * @param reader {@link PdbByteReader} from which this symbol is deserialized.+ */+ AbstractMsSymbol(AbstractPdb pdb, PdbByteReader reader) {+ this.pdb = pdb;+ // The following commented-out code is used when trying to discern which SYMBOL types were+ // not yet implemented.++// // Discern whether the derived class is implemented based upon whether it overrides "emit"+// try {+// if (this.getClass().getMethod("emit",+// parameterTypes).getDeclaringClass() == AbstractMsSymbol.class) {+// //System.out.println(this.getClass().getSimpleName());+// //System.out.println(reader.dump(0x200));+// }+// }+// catch (NoSuchMethodException e) {+// System.out.println("No emit method");+// }+ }++ /**+ * Returns the unique ID (PdbId) for this symbol type.+ * @return Identifier for this symbol type.+ */+ public abstract int getPdbId();++ @Override+ public void emit(StringBuilder builder) {+ builder.append("NotImplemented(" + this.getClass().getSimpleName() + ")");+ }++ /**+ * Returns the String representation of the symbol type name, per API.+ * @return String name.+ */+ protected abstract String getSymbolTypeName();++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/symbol/AbstractUnknownMsSymbol.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/symbol/AbstractUnknownMsSymbol.javanew file mode 100644index 0000000000..c1b314d498--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/symbol/AbstractUnknownMsSymbol.java@@ -0,0 +1,41 @@+/* ###+ * 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.pdb.pdbreader.symbol;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.pdbreader.AbstractPdb;++/**+ * An abstract class for a number of specific PDB symbol types that share certain information.+ * <P>+ * This class represents all symbols that are not documented in the API; this gives us a way+ * to represent them as a class.+ * <P>+ * For more information about PDBs, consult the Microsoft PDB API, see+ * <a href="https://devblogs.microsoft.com/cppblog/whats-inside-a-pdb-file">+ * What's inside a PDB File</a>+ */+public abstract class AbstractUnknownMsSymbol extends AbstractMsSymbol {++ /**+ * Constructor for this symbol.+ * @param pdb {@link AbstractPdb} to which this symbol belongs.+ * @param reader {@link PdbByteReader} from which this symbol is deserialized.+ */+ AbstractUnknownMsSymbol(AbstractPdb pdb, PdbByteReader reader) {+ super(pdb, reader);+ }+}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/symbol/BadMsSymbol.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/symbol/BadMsSymbol.javanew file mode 100644index 0000000000..3f87a954a7--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/symbol/BadMsSymbol.java@@ -0,0 +1,62 @@+/* ###+ * 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.pdb.pdbreader.symbol;++import ghidra.pdb.pdbreader.AbstractPdb;++/**+ * This class extends {@link AbstractMsSymbol}.+ * <P>+ * Important: This is not a real symbol. This "Bad" symbol takes the place of a symbol that has+ * encountered a parsing issue vis-a-vis a PdbException.+ */+public class BadMsSymbol extends AbstractMsSymbol {++ /** This should not be a the PDB_ID value of a real AbstractMsType. */+ public static final int PDB_ID = 0xff01;++ // Symbol ID that had an issue;+ int symbolId;++ /**+ * Constructor for this "Bad" symbol.+ * @param pdb {@link AbstractPdb} to which this symbol belongs.+ * @param symbolId The type ID for which an error occurred.+ */+ public BadMsSymbol(AbstractPdb pdb, int symbolId) {+ super(pdb, null);+ this.symbolId = symbolId;+ }++ @Override+ public int getPdbId() {+ return PDB_ID;+ }++ @Override+ public void emit(StringBuilder builder) {+ if (builder.length() != 0) {+ builder.insert(0, " ");+ }+ builder.insert(0, String.format("BAD_SYMBOL: ID=0X%04X", symbolId));+ }++ @Override+ protected String getSymbolTypeName() {+ return "BAD";+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/symbol/UnknownMsSymbol.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/symbol/UnknownMsSymbol.javanew file mode 100644index 0000000000..9a201c060a--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/symbol/UnknownMsSymbol.java@@ -0,0 +1,66 @@+/* ###+ * 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.pdb.pdbreader.symbol;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.pdbreader.AbstractPdb;++/**+ * This is not a real MS Symbol. We made this up to take the place of anticipated, unknown+ * symbols.+ */+public class UnknownMsSymbol extends AbstractUnknownMsSymbol {++ private int id = 0;+ private byte[] data;++ /**+ * Constructor for this symbol.+ * @param pdb {@link AbstractPdb} to which this symbol belongs.+ * @param reader {@link PdbByteReader} from which this symbol is deserialized.+ * @param id Value to be used as the unique PDB ID.+ */+ public UnknownMsSymbol(AbstractPdb pdb, PdbByteReader reader, int id) {+ super(pdb, reader);+ this.id = id;+ data = reader.parseBytesRemaining();+ }++ @Override+ public int getPdbId() {+ return id;+ }++ /**+ * Returns the data of this symbol (we do not know how to interpret it yet).+ * @return {@code byte[]} data.+ */+ public byte[] getData() {+ return data;+ }++ @Override+ public void emit(StringBuilder builder) {+ PdbByteReader reader = new PdbByteReader(data);+ builder.append(String.format("%s: Bytes:%s", getSymbolTypeName(), reader.dumpBytes()));+ }++ @Override+ protected String getSymbolTypeName() {+ return String.format("UNKNOWN_SYMBOL (0X%04X)", id);+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/type/AbstractMsType.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/type/AbstractMsType.javanew file mode 100644index 0000000000..3659d6dc5c--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/type/AbstractMsType.java@@ -0,0 +1,79 @@+/* ###+ * 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.pdb.pdbreader.type;++import ghidra.pdb.AbstractParsableItem;+import ghidra.pdb.PdbByteReader;+import ghidra.pdb.pdbreader.AbstractPdb;++/**+ * This class extends {@link AbstractParsableItem} as is the base class for PDB Data Type units.+ */+public abstract class AbstractMsType extends AbstractParsableItem {+ protected AbstractPdb pdb;++ // Order matters on these.+ public static enum Bind {+ PTR, ARRAY, PROC, NONE+ }++ /**+ * Constructor for this type.+ * @param pdb {@link AbstractPdb} to which this type belongs.+ * @param reader {@link PdbByteReader} from which this type is deserialized.+ */+ AbstractMsType(AbstractPdb pdb, PdbByteReader reader) {+ this.pdb = pdb;+ //System.out.println(reader.dump());+ }++ /**+ * If the type has a name element, returns this name; else returns an empty String.+ * Meant to be overloaded by derived types that have a name element.+ * @return Name.+ */+ public String getName() {+ return "";+ }++ /**+ * Returns the unique ID (PdbId) for this data type.+ * @return Identifier for this data type.+ */+ public abstract int getPdbId();++ @Override+ public void emit(StringBuilder builder) {+ this.emit(builder, Bind.NONE);+ }++ /**+ * Emits {@link String} output of this class into the provided {@link StringBuilder}.+ * @param builder {@link StringBuilder} into which the output is created.+ * @param bind Bind ordinal used for determining when parentheses should surround components.+ */+ public void emit(StringBuilder builder, Bind bind) {+ builder.append("IncompleteImpl(" + this.getClass().getSimpleName() + ")");+ }++ @Override+ public String toString() {+ StringBuilder builder = new StringBuilder();+ emit(builder, Bind.NONE);+ return builder.toString();+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/type/BadMsType.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/type/BadMsType.javanew file mode 100644index 0000000000..5f6fad7212--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/type/BadMsType.java@@ -0,0 +1,57 @@+/* ###+ * 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.pdb.pdbreader.type;++import ghidra.pdb.pdbreader.AbstractPdb;++/**+ * This class extends {@link AbstractMsType}.+ * <P>+ * Important: This is not a real type. This "Bad" type takes the place of a type that has+ * encountered a parsing issue vis-a-vis a PdbException.+ */+public class BadMsType extends AbstractMsType {++ /** This should not be a the PDB_ID value of a real AbstractMsType. */+ public static final int PDB_ID = 0xff01;++ // Type ID that had an issue;+ int typeId;++ /**+ * Constructor for this "Bad" type.+ * @param pdb {@link AbstractPdb} to which this type belongs.+ * @param typeId The type ID for which an error occurred.+ */+ public BadMsType(AbstractPdb pdb, int typeId) {+ super(pdb, null);+ this.typeId = typeId;+ }++ @Override+ public int getPdbId() {+ return PDB_ID;+ }++ @Override+ public void emit(StringBuilder builder, Bind bind) {+ if (builder.length() != 0) {+ builder.insert(0, " ");+ }+ builder.insert(0, String.format("BAD_TYPE: ID=0X%04X", typeId));+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/type/PrimitiveMsType.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/type/PrimitiveMsType.javanew file mode 100644index 0000000000..4760507855--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/type/PrimitiveMsType.java@@ -0,0 +1,1756 @@+/* ###+ * 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.pdb.pdbreader.type;++import ghidra.pdb.pdbreader.AbstractPdb;++/**+ * A class for a specific PDB data type--In this case one of many possible primitive types,+ * specified by the record number.+ * <P>+ * For more information about PDBs, consult the Microsoft PDB API, see+ * <a href="https://devblogs.microsoft.com/cppblog/whats-inside-a-pdb-file">+ * What's inside a PDB File</a>.+ */+public class PrimitiveMsType extends AbstractMsType {++ protected int recordNumber;+ protected String typeString;+ protected int typeSize;++ /**+ * Constructor for PrimitiveMsType+ * @param pdb {@link AbstractPdb} to which this type belongs.+ * @param recordNumber Specific record number (ID) of the primitive type.+ */+ public PrimitiveMsType(AbstractPdb pdb, int recordNumber) {+ super(pdb, null);+ this.recordNumber = recordNumber;+ processType();+ }++ @Override+ public int getPdbId() {+ return -1; // No real PDB_ID+ }++ @Override+ public void emit(StringBuilder builder, Bind bind) {+ if (builder.length() != 0) {+ builder.insert(0, " ");+ }+ builder.insert(0, typeString);+ }++ /**+ * Returns the name of this primitive type.+ * @return Name type of the primitive type.+ */+ @Override+ public String getName() {+ return typeString;+ }++ /**+ * Returns the type name of this primitive type.+ * @return Type name the primitive type.+ */+ public String getTypeString() {+ return typeString;+ }++ /**+ * Returns the record number (ID) that indicates the type of primitive type.+ * @return Specific record number (ID) representing the type of primitive.+ */+ public int getRecordNumber() {+ return recordNumber;+ }++ /**+ * Returns the number of bytes that this primitive takes in instantiation.+ * @return Number of bytes this primitive takes.+ */+ public int getTypeSize() {+ return typeSize;+ }++ //==============================================================================================+ private void processType() {+ switch (recordNumber) {+ //=======================================+ // Special types+ //=======================================+ // No Type (uncharacterized type)+ case 0x0000:+ typeString = "T_NOTYPE";+ typeSize = 0;+ break;+ // Absolute symbol+ case 0x0001:+ typeString = "T_ABS";+ typeSize = 0;+ break;+ // Segment type+ case 0x0002:+ typeString = "T_SEGMENT";+ typeSize = 0;+ break;+ // Void type+ case 0x0003:+ typeString = "void";+ typeSize = 0;+ break;+ // Near pointer to void+ case 0x0103:+ typeString = "void near*";+ typeSize = 2;+ break;+ // Far pointer to void+ case 0x0203:+ typeString = "void far*";+ typeSize = 4;+ break;+ // Huge pointer to void+ case 0x0304:+ typeString = "void huge*";+ typeSize = 4;+ break;+ // 32-bit pointer to void+ case 0x0403:+ typeString = "void *";+ typeSize = 4;+ break;+ // 16:32 pointer to void+ case 0x0503:+ typeString = "T_32PFVOID";+ typeSize = 4;+ break;+ // 64-bit pointer to void+ case 0x0603:+ typeString = "T_64PFVOID";+ typeSize = 8;+ break;+ // BASIC 8 byte currency value+ case 0x0004:+ typeString = "T_CURRENCY";+ typeSize = 8;+ break;+ // Near BASIC string+ case 0x0005:+ typeString = "T_NBASICSTR";+ typeSize = 0;+ break;+ // Far BASIC string+ case 0x0006:+ typeString = "T_FBASICSTR";+ typeSize = 0;+ break;+ // Type not translated by cvpack+ case 0x0007:+ typeString = "T_NOTTRANS";+ typeSize = 0;+ break;+ // OLE/COM HRESULT+ case 0x0008:+ typeString = "T_HRESULT";+ typeSize = 4;+ break;+ // OLE/COM HRESULT __ptr32 *+ case 0x0408:+ typeString = "T_32PHRESULT";+ typeSize = 4;+ break;+ // OLE/COM HRESULT __ptr64 *+ case 0x0608:+ typeString = "T_64PHRESULT";+ typeSize = 8;+ break;+ // bit+ case 0x0060:+ typeString = "T_BIT";+ typeSize = 0;+ break;+ // Pascal CHAR+ case 0x0061:+ typeString = "T_PASCHAR";+ typeSize = 0;+ break;+ // 32-bit BOOL where true is 0xffffffff+ case 0x0062:+ typeString = "T_BOOL32FF";+ typeSize = 0;+ break;++ //=======================================+ // Signed Character types+ //=======================================+ // 8-bit signed+ case 0x0010:+ typeString = "signed char";+ typeSize = 1;+ break;+ // 16-bit pointer to an 8-bit signed+ case 0x0110:+ typeString = "signed char near*";+ typeSize = 2;+ break;+ // 16:16 far pointer to an 8-bit signed+ case 0x0210:+ typeString = "char far*";+ typeSize = 4;+ break;+ // 16:16 huge pointer to an 8-bit signed+ case 0x0310:+ typeString = "char huge*";+ typeSize = 4;+ break;+ // 32-bit pointer to an 8-bit signed+ case 0x0410:+ typeString = "char *";+ typeSize = 4;+ break;+ // 16:32 pointer to an 8-bit signed+ case 0x0510:+ typeString = "T_32PFCHAR";+ typeSize = 6;+ break;+ // 64-bit pointer to an 8-bit signed+ case 0x0610:+ typeString = "T_64PCHAR";+ typeSize = 8;+ break;++ //=======================================+ // Unsigned Character types+ //=======================================+ // 8-bit unsigned+ case 0x0020:+ typeString = "unsigned char";+ typeSize = 0;+ break;+ // 16-bit pointer to an 8-bit unsigned+ case 0x0120:+ typeString = "unsigned char near*";+ typeSize = 2;+ break;+ // 16:16 far pointer to an 8-bit unsigned+ case 0x0220:+ typeString = "unsigned char far*";+ typeSize = 4;+ break;+ // 16:16 huge pointer to an 8-bit unsigned+ case 0x0320:+ typeString = "unsigned char huge*";+ typeSize = 4;+ break;+ // 32-bit pointer to an 8-bit unsigned+ case 0x0420:+ typeString = "unsigned char *";+ typeSize = 4;+ break;+ // 16:32 pointer to an 8-bit unsigned+ case 0x0520:+ typeString = "T_32PFUCHAR";+ typeSize = 6;+ break;+ // 64-bit pointer to an 8-bit unsigned+ case 0x0620:+ typeString = "T_64PUCHAR";+ typeSize = 8;+ break;++ //=======================================+ // Real character types+ //=======================================+ // a real char+ case 0x0070:+ typeString = "char";+ typeSize = 1;+ break;+ // 16-bit pointer to a real char+ case 0x0170:+ typeString = "char near*";+ typeSize = 2;+ break;+ // 16:16 far pointer to a real char+ case 0x0270:+ typeString = "char far*";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a real char+ case 0x0370:+ typeString = "char huge*";+ typeSize = 4;+ break;+ // 32-bit pointer to a real char+ case 0x0470:+ typeString = "char *";+ typeSize = 4;+ break;+ // 16:32 pointer to a real char+ case 0x0570:+ typeString = "T_32PFRCHAR";+ typeSize = 6;+ break;+ // 64-bit pointer to a real char+ case 0x0670:+ typeString = "T_64PRCHAR";+ typeSize = 8;+ break;++ //=======================================+ // Really a wide character types+ //=======================================+ // wide char+ case 0x0071:+ typeString = "wchar_t";+ typeSize = 2;+ break;+ // 16-bit pointer to a wide char+ case 0x0171:+ typeString = "wchar_t near*";+ typeSize = 2;+ break;+ // 16:16 far pointer to a wide char+ case 0x0271:+ typeString = "wchar_t far*";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a wide char+ case 0x0371:+ typeString = "wchar_t huge*";+ typeSize = 4;+ break;+ // 32-bit pointer to a wide char+ case 0x0471:+ typeString = "wchar_t *";+ typeSize = 4;+ break;+ // 16:32 pointer to a wide char+ case 0x0571:+ typeString = "T_32PFWCHAR";+ typeSize = 6;+ break;+ // 64-bit pointer to a wide char+ case 0x0671:+ typeString = "T_64PWCHAR";+ typeSize = 8;+ break;++ //=======================================+ // 16-bit char types+ //=======================================+ // 16-bit unicode char+ case 0x007a:+ typeString = "T_CHAR16";+ typeSize = 2;+ break;+ // 16-bit pointer to a 16-bit unicode char+ case 0x017a:+ typeString = "T_PCHAR16";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 16-bit unicode char+ case 0x027a:+ typeString = "T_PFCHAR16";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 16-bit unicode char+ case 0x037a:+ typeString = "T_PHCHAR16";+ typeSize = 4;+ break;+ // 32-bit pointer to a 16-bit unicode char+ case 0x047a:+ typeString = "T_32PCHAR16";+ typeSize = 4;+ break;+ // 16:32 pointer to a 16-bit unicode char+ case 0x057a:+ typeString = "T_32PFCHAR16";+ typeSize = 6;+ break;+ // 64-bit pointer to a 16-bit unicode char+ case 0x067a:+ typeString = "T_64PCHAR16";+ typeSize = 8;+ break;++ //=======================================+ // 32-bit unicode char types+ //=======================================+ // 32-bit unicode char+ case 0x007b:+ typeString = "T_CHAR32";+ typeSize = 4;+ break;+ // 16-bit pointer to a 32-bit unicode char+ case 0x017b:+ typeString = "T_PCHAR32";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 32-bit unicode char+ case 0x027b:+ typeString = "T_PFCHAR32";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 32-bit unicode char+ case 0x037b:+ typeString = "T_PHCHAR32";+ typeSize = 4;+ break;+ // 32-bit pointer to a 32-bit unicode char+ case 0x047b:+ typeString = "T_32PCHAR32";+ typeSize = 4;+ break;+ // 16:32 pointer to a 32-bit unicode char+ case 0x057b:+ typeString = "T_32PFCHAR32";+ typeSize = 6;+ break;+ // 64-bit pointer to a 32-bit unicode char+ case 0x067b:+ typeString = "T_64PCHAR32";+ typeSize = 8;+ break;++ //=======================================+ // 8-bit int types+ //=======================================+ // 8-bit int+ case 0x0068:+ typeString = "T_INT1";+ typeSize = 1;+ break;+ // 16-bit pointer to an 8-bit int+ case 0x0168:+ typeString = "T_PINT1";+ typeSize = 2;+ break;+ // 16:16 far pointer to an 8-bit int+ case 0x0268:+ typeString = "T_PFINT1";+ typeSize = 4;+ break;+ // 16:16 huge pointer to an 8-bit int+ case 0x0368:+ typeString = "T_PHINT1";+ typeSize = 4;+ break;+ // 32-bit pointer to an 8-bit int+ case 0x0468:+ typeString = "T_32PINT1";+ typeSize = 4;+ break;+ // 16:32 pointer to an 8-bit int+ case 0x0568:+ typeString = "T_32PFINT1";+ typeSize = 6;+ break;+ // 64-bit pointer to an 8-bit int+ case 0x0668:+ typeString = "T_64PINT1";+ typeSize = 8;+ break;++ //=======================================+ // 8-bit unsigned int types+ //=======================================+ // 8-bit unsigned int+ case 0x0069:+ typeString = "T_UINT1";+ typeSize = 1;+ break;+ // 16-bit pointer to an 8-bit unsigned int+ case 0x0169:+ typeString = "T_PUINT1";+ typeSize = 2;+ break;+ // 16:16 far pointer to an 8-bit unsigned int+ case 0x0269:+ typeString = "T_PFUINT1";+ typeSize = 4;+ break;+ // 16:16 huge pointer to an 8-bit unsigned int+ case 0x0369:+ typeString = "T_PHUINT1";+ typeSize = 4;+ break;+ // 32-bit pointer to an 8-bit unsigned int+ case 0x0469:+ typeString = "T_32PUINT1";+ typeSize = 4;+ break;+ // 16:32 pointer to an 8-bit unsigned int+ case 0x0569:+ typeString = "T_32PFUINT1";+ typeSize = 6;+ break;+ // 64-bit pointer to an 8-bit unsigned int+ case 0x0669:+ typeString = "T_64PUINT1";+ typeSize = 8;+ break;++ //=======================================+ // 16-bit short types+ //=======================================+ // 16-bit signed short+ case 0x0011:+ typeString = "short";+ typeSize = 2;+ break;+ // 16-bit pointer to a 16-bit signed short+ case 0x0111:+ typeString = "short near*";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 16-bit signed short+ case 0x0211:+ typeString = "short far*";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 16-bit signed short+ case 0x0311:+ typeString = "short huge*";+ typeSize = 4;+ break;+ // 32-bit pointer to a 16-bit signed short+ case 0x0411:+ typeString = "T_32PSHORT";+ typeSize = 4;+ break;+ // 16:32 pointer to a 16-bit signed short+ case 0x0511:+ typeString = "T_32PFSHORT";+ typeSize = 6;+ break;+ // 64-bit pointer to a 16-bit signed short+ case 0x0611:+ typeString = "T_64PSHORT";+ typeSize = 8;+ break;++ //=======================================+ // 16-bit unsigned short types+ //=======================================+ // 16-bit unsigned signed short+ case 0x0021:+ typeString = "unsigned short";+ typeSize = 2;+ break;+ // 16-bit pointer to a 16-bit unsigned signed short+ case 0x0121:+ typeString = "unsigned short near*";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 16-bit unsigned signed short+ case 0x0221:+ typeString = "unsigned short far*";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 16-bit unsigned signed short+ case 0x0321:+ typeString = "unsigned short huge*";+ typeSize = 4;+ break;+ // 32-bit pointer to a 16-bit unsigned signed short+ case 0x0421:+ typeString = "T_32PUSHORT";+ typeSize = 4;+ break;+ // 16:32 pointer to a 16-bit unsigned signed short+ case 0x0521:+ typeString = "T_32PFUSHORT";+ typeSize = 6;+ break;+ // 64-bit pointer to a 16-bit unsigned signed short+ case 0x0621:+ typeString = "T_64PUSHORT";+ typeSize = 8;+ break;++ //=======================================+ // 16-bit signed int types+ //=======================================+ // 16-bit signed int+ case 0x0072:+ typeString = "int16";+ typeSize = 2;+ break;+ // 16-bit pointer to a 16-bit signed int+ case 0x0172:+ typeString = "int16 near*";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 16-bit signed int+ case 0x0272:+ typeString = "int16 far*";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 16-bit signed int+ case 0x0372:+ typeString = "int16 huge*";+ typeSize = 4;+ break;+ // 32-bit pointer to a 16-bit signed int+ case 0x0472:+ typeString = "T_32PINT2";+ typeSize = 4;+ break;+ // 16:32 pointer to a 16-bit signed int+ case 0x0572:+ typeString = "T_32PFINT2";+ typeSize = 6;+ break;+ // 64-bit pointer to a 16-bit signed int+ case 0x0672:+ typeString = "T_64PINT2";+ typeSize = 8;+ break;++ //=======================================+ // 16-bit unsigned int types+ //=======================================+ // 16-bit unsigned int+ case 0x0073:+ typeString = "unsigned int16";+ typeSize = 2;+ break;+ // 16-bit pointer to a 16-bit unsigned int+ case 0x0173:+ typeString = "unsigned int16 near*";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 16-bit unsigned int+ case 0x0273:+ typeString = "unsigned int16 far*";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 16-bit unsigned int+ case 0x0373:+ typeString = "unsigned int16 huge*";+ typeSize = 4;+ break;+ // 32-bit pointer to a 16-bit unsigned int+ case 0x0473:+ typeString = "T_32PUINT2";+ typeSize = 4;+ break;+ // 16:32 pointer to a 16-bit unsigned int+ case 0x0573:+ typeString = "T_32PFUINT2";+ typeSize = 6;+ break;+ // 64-bit pointer to a 16-bit unsigned int+ case 0x0673:+ typeString = "T_64PUINT2";+ typeSize = 8;+ break;++ //=======================================+ // 32-bit long types+ //=======================================+ // 32-bit signed long+ case 0x0012:+ typeString = "long";+ typeSize = 4;+ break;+ // 16-bit pointer to a 32-bit signed long+ case 0x0112:+ typeString = "long near*";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 32-bit signed long+ case 0x0212:+ typeString = "long far*";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 32-bit signed long+ case 0x0312:+ typeString = "long huge*";+ typeSize = 4;+ break;+ // 32-bit pointer to a 32-bit signed long+ case 0x0412:+ typeString = "T_32PLONG";+ typeSize = 4;+ break;+ // 16:32 pointer to a 32-bit signed long+ case 0x0512:+ typeString = "T_32PFLONG";+ typeSize = 6;+ break;+ // 64-bit pointer to a 32-bit signed long+ case 0x0612:+ typeString = "T_64PLONG";+ typeSize = 8;+ break;++ //=======================================+ // 32-bit unsigned long types+ //=======================================+ // 32-bit unsigned signed long+ case 0x0022:+ typeString = "unsigned long";+ typeSize = 4;+ break;+ // 16-bit pointer to a 32-bit unsigned signed long+ case 0x0122:+ typeString = "unsigned long near*";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 32-bit unsigned signed long+ case 0x0222:+ typeString = "unsigned long far*";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 32-bit unsigned signed long+ case 0x0322:+ typeString = "unsigned long huge*";+ typeSize = 4;+ break;+ // 32-bit pointer to a 32-bit unsigned signed long+ case 0x0422:+ typeString = "T_32PULONG";+ typeSize = 4;+ break;+ // 16:32 pointer to a 32-bit unsigned signed long+ case 0x0522:+ typeString = "T_32PFULONG";+ typeSize = 6;+ break;+ // 64-bit pointer to a 32-bit unsigned signed long+ case 0x0622:+ typeString = "T_64PULONG";+ typeSize = 8;+ break;++ //=======================================+ // 32-bit signed int types+ //=======================================+ // 32-bit signed int+ case 0x0074:+ typeString = "int";+ typeSize = 4;+ break;+ // 16-bit pointer to a 32-bit signed int+ case 0x0174:+ typeString = "PINT4";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 32-bit signed int+ case 0x0274:+ typeString = "PFINT4";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 32-bit signed int+ case 0x0374:+ typeString = "PHINT4";+ typeSize = 4;+ break;+ // 32-bit pointer to a 32-bit signed int+ case 0x0474:+ typeString = "T_32PINT4";+ typeSize = 4;+ break;+ // 16:32 pointer to a 32-bit signed int+ case 0x0574:+ typeString = "T_32PFINT4";+ typeSize = 6;+ break;+ // 64-bit pointer to a 32-bit signed int+ case 0x0674:+ typeString = "T_64PINT4";+ typeSize = 8;+ break;++ //=======================================+ // 32-bit unsigned int types+ //=======================================+ // 32-bit unsigned int+ case 0x0075:+ typeString = "unsigned";+ typeSize = 4;+ break;+ // 16-bit pointer to a 32-bit unsigned int+ case 0x0175:+ typeString = "PUINT4";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 32-bit unsigned int+ case 0x0275:+ typeString = "PFUINT4";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 32-bit unsigned int+ case 0x0375:+ typeString = "PHUINT4";+ typeSize = 4;+ break;+ // 32-bit pointer to a 32-bit unsigned int+ case 0x0475:+ typeString = "T_32PUINT4";+ typeSize = 4;+ break;+ // 16:32 pointer to a 32-bit unsigned int+ case 0x0575:+ typeString = "T_32PFUINT4";+ typeSize = 6;+ break;+ // 64-bit pointer to a 32-bit unsigned int+ case 0x0675:+ typeString = "T_64PUINT4";+ typeSize = 8;+ break;++ //=======================================+ // 64-bit quad types+ //=======================================+ // 64-bit signed long+ case 0x0013:+ typeString = "T_QUAD";+ typeSize = 8;+ break;+ // 16-bit pointer to a 64-bit signed long+ case 0x0113:+ typeString = "T_PQUAD";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 64-bit signed long+ case 0x0213:+ typeString = "T_PFQUAD";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 64-bit signed long+ case 0x0313:+ typeString = "T_PHQUAD";+ typeSize = 4;+ break;+ // 32-bit pointer to a 64-bit signed long+ case 0x0413:+ typeString = "T_32PQUAD";+ typeSize = 4;+ break;+ // 16:32 pointer to a 64-bit signed long+ case 0x0513:+ typeString = "T_32PFQUAD";+ typeSize = 6;+ break;+ // 64-bit pointer to a 64-bit signed long+ case 0x0613:+ typeString = "T_64PQUAD";+ typeSize = 8;+ break;++ //=======================================+ // 64-bit unsigned quad types+ //=======================================+ // 64-bit unsigned signed long+ case 0x0023:+ typeString = "T_UQUAD";+ typeSize = 8;+ break;+ // 16-bit pointer to a 64-bit unsigned signed long+ case 0x0123:+ typeString = "T_PUQUAD";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 64-bit unsigned signed long+ case 0x0223:+ typeString = "T_PFUQUAD";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 64-bit unsigned signed long+ case 0x0323:+ typeString = "T_PHUQUAD";+ typeSize = 4;+ break;+ // 32-bit pointer to a 64-bit unsigned signed long+ case 0x0423:+ typeString = "T_32PUQUAD";+ typeSize = 4;+ break;+ // 16:32 pointer to a 64-bit unsigned signed long+ case 0x0523:+ typeString = "T_32PFUQUAD";+ typeSize = 6;+ break;+ // 64-bit pointer to a 64-bit unsigned signed long+ case 0x0623:+ typeString = "T_64PUQUAD";+ typeSize = 8;+ break;++ //=======================================+ // 64-bit signed int types+ //=======================================+ // 64-bit signed int+ case 0x0076:+ typeString = "T_INT8";+ typeSize = 8;+ break;+ // 16-bit pointer to a 64-bit signed int+ case 0x0176:+ typeString = "T_PINT8";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 64-bit signed int+ case 0x0276:+ typeString = "T_PFINT8";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 64-bit signed int+ case 0x0376:+ typeString = "T_PHINT8";+ typeSize = 4;+ break;+ // 32-bit pointer to a 64-bit signed int+ case 0x0476:+ typeString = "T_32PINT8";+ typeSize = 4;+ break;+ // 16:32 pointer to a 64-bit signed int+ case 0x0576:+ typeString = "T_32PFINT8";+ typeSize = 6;+ break;+ // 64-bit pointer to a 64-bit signed int+ case 0x0676:+ typeString = "T_64PINT8";+ typeSize = 8;+ break;++ //=======================================+ // 64-bit unsigned int types+ //=======================================+ // 64-bit unsigned int+ case 0x0077:+ typeString = "T_UINT8";+ typeSize = 8;+ break;+ // 16-bit pointer to a 64-bit unsigned int+ case 0x0177:+ typeString = "T_PUINT8";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 64-bit unsigned int+ case 0x0277:+ typeString = "T_PFUINT8";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 64-bit unsigned int+ case 0x0377:+ typeString = "T_PHUINT8";+ typeSize = 4;+ break;+ // 32-bit pointer to a 64-bit unsigned int+ case 0x0477:+ typeString = "T_32PUINT8";+ typeSize = 4;+ break;+ // 16:32 pointer to a 64-bit unsigned int+ case 0x0577:+ typeString = "T_32PFUINT8";+ typeSize = 6;+ break;+ // 64-bit pointer to a 64-bit unsigned int+ case 0x0677:+ typeString = "T_64PUINT8";+ typeSize = 8;+ break;++ //=======================================+ // 128-bit octet types+ //=======================================+ // 128-bit signed long+ case 0x0014:+ typeString = "T_OCT";+ typeSize = 16;+ break;+ // 16-bit pointer to a 128-bit signed long+ case 0x0114:+ typeString = "T_POCT";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 128-bit signed long+ case 0x0214:+ typeString = "T_PFOCT";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 128-bit signed long+ case 0x0314:+ typeString = "T_PHOCT";+ typeSize = 4;+ break;+ // 32-bit pointer to a 128-bit signed long+ case 0x0414:+ typeString = "T_32POCT";+ typeSize = 4;+ break;+ // 16:32 pointer to a 128-bit signed long+ case 0x0514:+ typeString = "T_32PFOCT";+ typeSize = 6;+ break;+ // 64-bit pointer to a 128-bit signed long+ case 0x0614:+ typeString = "T_64POCT";+ typeSize = 8;+ break;++ //=======================================+ // 128-bit unsigned octet types+ //=======================================+ // 128-bit unsigned signed long+ case 0x0024:+ typeString = "T_UOCT";+ typeSize = 16;+ break;+ // 16-bit pointer to a 128-bit unsigned signed long+ case 0x0124:+ typeString = "T_PUOCT";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 128-bit unsigned signed long+ case 0x0224:+ typeString = "T_PFUOCT";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 128-bit unsigned signed long+ case 0x0324:+ typeString = "T_PHUOCT";+ typeSize = 4;+ break;+ // 32-bit pointer to a 128-bit unsigned signed long+ case 0x0424:+ typeString = "T_32PUOCT";+ typeSize = 4;+ break;+ // 16:32 pointer to a 128-bit unsigned signed long+ case 0x0524:+ typeString = "T_32PFUOCT";+ typeSize = 6;+ break;+ // 64-bit pointer to a 128-bit unsigned signed long+ case 0x0624:+ typeString = "T_64PUOCT";+ typeSize = 8;+ break;++ //=======================================+ // 128-bit signed int types+ //=======================================+ // 128-bit signed int+ case 0x0078:+ typeString = "T_INT16";+ typeSize = 16;+ break;+ // 16-bit pointer to a 128-bit signed int+ case 0x0178:+ typeString = "T_PINT16";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 128-bit signed int+ case 0x0278:+ typeString = "T_PFINT16";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 128-bit signed int+ case 0x0378:+ typeString = "T_PHINT16";+ typeSize = 4;+ break;+ // 32-bit pointer to a 128-bit signed int+ case 0x0478:+ typeString = "T_32PINT16";+ typeSize = 4;+ break;+ // 16:32 pointer to a 128-bit signed int+ case 0x0578:+ typeString = "T_32PFINT16";+ typeSize = 6;+ break;+ // 64-bit pointer to a 128-bit signed int+ case 0x0678:+ typeString = "T_64PINT16";+ typeSize = 8;+ break;++ //=======================================+ // 128-bit unsigned int types+ //=======================================+ // 128-bit unsigned int+ case 0x0079:+ typeString = "T_UINT16";+ typeSize = 16;+ break;+ // 16-bit pointer to a 128-bit unsigned int+ case 0x0179:+ typeString = "T_PUINT16";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 128-bit unsigned int+ case 0x0279:+ typeString = "T_PFUINT16";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 128-bit unsigned int+ case 0x0379:+ typeString = "T_PHUINT16";+ typeSize = 4;+ break;+ // 32-bit pointer to a 128-bit unsigned int+ case 0x0479:+ typeString = "T_32PUINT16";+ typeSize = 4;+ break;+ // 16:32 pointer to a 128-bit unsigned int+ case 0x0579:+ typeString = "T_32PFUINT16";+ typeSize = 6;+ break;+ // 64-bit pointer to a 128-bit unsigned int+ case 0x0679:+ typeString = "T_64PUINT16";+ typeSize = 8;+ break;++ //=======================================+ // 16-bit real types+ //=======================================+ // 16-bit real+ case 0x0046:+ typeString = "T_REAL16";+ typeSize = 2;+ break;+ // 16-bit pointer to a 16-bit real+ case 0x0146:+ typeString = "T_PREAL16";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 16-bit real+ case 0x0246:+ typeString = "T_PFREAL16";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 16-bit real+ case 0x0346:+ typeString = "T_PHREAL16";+ typeSize = 4;+ break;+ // 32-bit pointer to a 16-bit real+ case 0x0446:+ typeString = "T_32PREAL16";+ typeSize = 4;+ break;+ // 16:32 pointer to a 16-bit real+ case 0x0546:+ typeString = "T_32PFREAL16";+ typeSize = 6;+ break;+ // 64-bit pointer to a 16-bit real+ case 0x0646:+ typeString = "T_64PREAL16";+ typeSize = 8;+ break;++ //=======================================+ // 32-bit real types+ //=======================================+ // 32-bit real+ case 0x0040:+ typeString = "T_REAL32";+ typeSize = 4;+ break;+ // 16-bit pointer to a 32-bit real+ case 0x0140:+ typeString = "T_PREAL32";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 32-bit real+ case 0x0240:+ typeString = "T_PFREAL32";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 32-bit real+ case 0x0340:+ typeString = "T_PHREAL32";+ typeSize = 4;+ break;+ // 32-bit pointer to a 32-bit real+ case 0x0440:+ typeString = "T_32PREAL32";+ typeSize = 4;+ break;+ // 16:32 pointer to a 32-bit real+ case 0x0540:+ typeString = "T_32PFREAL32";+ typeSize = 6;+ break;+ // 64-bit pointer to a 32-bit real+ case 0x0640:+ typeString = "T_64PREAL32";+ typeSize = 8;+ break;++ //=======================================+ // 32-bit partial-precision real types+ //=======================================+ // 32-bit real+ case 0x0045:+ typeString = "T_REAL32PP";+ typeSize = 4;+ break;+ // 16-bit pointer to a 32-bit real+ case 0x0145:+ typeString = "T_PREAL32PP";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 32-bit real+ case 0x0245:+ typeString = "T_PFREAL32PP";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 32-bit real+ case 0x0345:+ typeString = "T_PHREAL32PP";+ typeSize = 4;+ break;+ // 32-bit pointer to a 32-bit real+ case 0x0445:+ typeString = "T_32PREAL32PP";+ typeSize = 4;+ break;+ // 16:32 pointer to a 32-bit real+ case 0x0545:+ typeString = "T_32PFREAL32PP";+ typeSize = 6;+ break;+ // 64-bit pointer to a 32-bit real+ case 0x0645:+ typeString = "T_64PREAL32PP";+ typeSize = 8;+ break;++ //=======================================+ // 48-bit real types+ //=======================================+ // 48-bit real+ case 0x0044:+ typeString = "T_REAL48";+ typeSize = 6;+ break;+ // 16-bit pointer to a 48-bit real+ case 0x0144:+ typeString = "T_PREAL48";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 48-bit real+ case 0x0244:+ typeString = "T_PFREAL48";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 48-bit real+ case 0x0344:+ typeString = "T_PHREAL48";+ typeSize = 4;+ break;+ // 32-bit pointer to a 48-bit real+ case 0x0444:+ typeString = "T_32PREAL48";+ typeSize = 4;+ break;+ // 16:32 pointer to a 48-bit real+ case 0x0544:+ typeString = "T_32PFREAL48";+ typeSize = 6;+ break;+ // 64-bit pointer to a 48-bit real+ case 0x0644:+ typeString = "T_64PREAL48";+ typeSize = 8;+ break;++ //=======================================+ // 64-bit real types+ //=======================================+ // 64-bit real+ case 0x0041:+ typeString = "T_REAL64";+ typeSize = 8;+ break;+ // 16-bit pointer to a 64-bit real+ case 0x0141:+ typeString = "T_PREAL64";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 64-bit real+ case 0x0241:+ typeString = "T_PFREAL64";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 64-bit real+ case 0x0341:+ typeString = "T_PHREAL64";+ typeSize = 4;+ break;+ // 32-bit pointer to a 64-bit real+ case 0x0441:+ typeString = "T_32PREAL64";+ typeSize = 4;+ break;+ // 16:32 pointer to a 64-bit real+ case 0x0541:+ typeString = "T_32PFREAL64";+ typeSize = 6;+ break;+ // 64-bit pointer to a 64-bit real+ case 0x0641:+ typeString = "T_64PREAL64";+ typeSize = 8;+ break;++ //=======================================+ // 80-bit real types+ //=======================================+ // 80-bit real+ case 0x0042:+ typeString = "T_REAL80";+ typeSize = 10;+ break;+ // 16-bit pointer to an 80-bit real+ case 0x0142:+ typeString = "T_PREAL80";+ typeSize = 2;+ break;+ // 16:16 far pointer to an 80-bit real+ case 0x0242:+ typeString = "T_PFREAL80";+ typeSize = 4;+ break;+ // 16:16 huge pointer to an 80-bit real+ case 0x0342:+ typeString = "T_PHREAL80";+ typeSize = 4;+ break;+ // 32-bit pointer to an 80-bit real+ case 0x0442:+ typeString = "T_32PREAL80";+ typeSize = 4;+ break;+ // 16:32 pointer to an 80-bit real+ case 0x0542:+ typeString = "T_32PFREAL80";+ typeSize = 6;+ break;+ // 64-bit pointer to an 80-bit real+ case 0x0642:+ typeString = "T_64PREAL80";+ typeSize = 8;+ break;++ //=======================================+ // 128-bit real types+ //=======================================+ // 128-bit real+ case 0x0043:+ typeString = "T_REAL128";+ typeSize = 16;+ break;+ // 16-bit pointer to a 128-bit real+ case 0x0143:+ typeString = "T_PREAL128";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 128-bit real+ case 0x0243:+ typeString = "T_PFREAL128";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 128-bit real+ case 0x0343:+ typeString = "T_PHREAL128";+ typeSize = 4;+ break;+ // 32-bit pointer to a 128-bit real+ case 0x0443:+ typeString = "T_32PREAL128";+ typeSize = 4;+ break;+ // 16:32 pointer to a 128-bit real+ case 0x0543:+ typeString = "T_32PFREAL128";+ typeSize = 6;+ break;+ // 64-bit pointer to a 1128-bit real+ case 0x0643:+ typeString = "T_64PREAL128";+ typeSize = 8;+ break;++ //=======================================+ // 32-bit complex types+ //=======================================+ // 32-bit complex+ case 0x0050:+ typeString = "T_CPLX32";+ typeSize = 4;+ break;+ // 16-bit pointer to a 32-bit complex+ case 0x0150:+ typeString = "T_PCPLX32";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 32-bit complex+ case 0x0250:+ typeString = "T_PFCPLX32";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 32-bit complex+ case 0x0350:+ typeString = "T_PHCPLX32";+ typeSize = 4;+ break;+ // 32-bit pointer to an 32-bit complex+ case 0x0450:+ typeString = "T_32PCPLX32";+ typeSize = 4;+ break;+ // 16:32 pointer to an 32-bit complex+ case 0x0550:+ typeString = "T_32PFCPLX32";+ typeSize = 6;+ break;+ // 64-bit pointer to an 32-bit complex+ case 0x0650:+ typeString = "T_64PCPLX32";+ typeSize = 8;+ break;++ //=======================================+ // 64-bit complex types+ //=======================================+ // 64-bit complex+ case 0x0051:+ typeString = "T_CPLX64";+ typeSize = 8;+ break;+ // 16-bit pointer to a 64-bit complex+ case 0x0151:+ typeString = "T_PCPLX64";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 64-bit complex+ case 0x0251:+ typeString = "T_PFCPLX64";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 64-bit complex+ case 0x0351:+ typeString = "T_PHCPLX64";+ typeSize = 4;+ break;+ // 32-bit pointer to a 64-bit complex+ case 0x0451:+ typeString = "T_32PCPLX64";+ typeSize = 4;+ break;+ // 16:32 pointer to a 64-bit complex+ case 0x0551:+ typeString = "T_32PFCPLX64";+ typeSize = 6;+ break;+ // 64-bit pointer to a 64-bit complex+ case 0x0651:+ typeString = "T_64PCPLX64";+ typeSize = 8;+ break;++ //=======================================+ // 80-bit complex types+ //=======================================+ // 80-bit complex+ case 0x0052:+ typeString = "T_CPLX80";+ typeSize = 10;+ break;+ // 16-bit pointer to an 80-bit complex+ case 0x0152:+ typeString = "T_PCPLX80";+ typeSize = 2;+ break;+ // 16:16 far pointer to an 80-bit complex+ case 0x0252:+ typeString = "T_PFCPLX80";+ typeSize = 4;+ break;+ // 16:16 huge pointer to an 80-bit complex+ case 0x0352:+ typeString = "T_PHCPLX80";+ typeSize = 4;+ break;+ // 32-bit pointer to an 80-bit complex+ case 0x0452:+ typeString = "T_32PCPLX80";+ typeSize = 4;+ break;+ // 16:32 pointer to an 80-bit complex+ case 0x0552:+ typeString = "T_32PFCPLX80";+ typeSize = 6;+ break;+ // 64-bit pointer to an 80-bit complex+ case 0x0652:+ typeString = "T_64PCPLX80";+ typeSize = 8;+ break;++ //=======================================+ // 128-bit complex types+ //=======================================+ // 128-bit complex+ case 0x0053:+ typeString = "T_CPLX128";+ typeSize = 16;+ break;+ // 16-bit pointer to a 128-bit complex+ case 0x0153:+ typeString = "T_PCPLX128";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 128-bit complex+ case 0x0253:+ typeString = "T_PFCPLX128";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 128-bit complex+ case 0x0353:+ typeString = "T_PHCPLX128";+ typeSize = 4;+ break;+ // 32-bit pointer to a 128-bit complex+ case 0x0453:+ typeString = "T_32PCPLX128";+ typeSize = 4;+ break;+ // 16:32 pointer to a 128-bit complex+ case 0x0553:+ typeString = "T_32PFCPLX128";+ typeSize = 6;+ break;+ // 64-bit pointer to a 128-bit complex+ case 0x0653:+ typeString = "T_64PCPLX128";+ typeSize = 8;+ break;++ //=======================================+ // 8-bit boolean types+ //=======================================+ // 8-bit boolean+ case 0x0030:+ typeString = "T_BOOL08";+ typeSize = 1;+ break;+ // 16-bit pointer to an 8-bit boolean+ case 0x0130:+ typeString = "T_PBOOL08";+ typeSize = 2;+ break;+ // 16:16 far pointer to an 8-bit boolean+ case 0x0230:+ typeString = "T_PFBOOL08";+ typeSize = 4;+ break;+ // 16:16 huge pointer to an 8-bit boolean+ case 0x0330:+ typeString = "T_PHBOOL08";+ typeSize = 4;+ break;+ // 32-bit pointer to an 8-bit boolean+ case 0x0430:+ typeString = "T_32PBOOL08";+ typeSize = 4;+ break;+ // 16:32 pointer to an 8-bit boolean+ case 0x0530:+ typeString = "T_32PFBOOL08";+ typeSize = 6;+ break;+ // 64-bit pointer to an 8-bit boolean+ case 0x0630:+ typeString = "T_64PBOOL08";+ typeSize = 8;+ break;++ //=======================================+ // 16-bit boolean types+ //=======================================+ // 16-bit boolean+ case 0x0031:+ typeString = "T_BOOL16";+ typeSize = 2;+ break;+ // 16-bit pointer to a 16-bit boolean+ case 0x0131:+ typeString = "T_PBOOL16";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 16-bit boolean+ case 0x0231:+ typeString = "T_PFBOOL16";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 16-bit boolean+ case 0x0331:+ typeString = "T_PHBOOL16";+ typeSize = 4;+ break;+ // 32-bit pointer to a 16-bit boolean+ case 0x0431:+ typeString = "T_32PBOOL16";+ typeSize = 4;+ break;+ // 16:32 pointer to a 16-bit boolean+ case 0x0531:+ typeString = "T_32PFBOOL16";+ typeSize = 6;+ break;+ // 64-bit pointer to a 16-bit boolean+ case 0x0631:+ typeString = "T_64PBOOL16";+ typeSize = 8;+ break;++ //=======================================+ // 32-bit boolean types+ //=======================================+ // 32-bit boolean+ case 0x0032:+ typeString = "T_BOOL32";+ typeSize = 2;+ break;+ // 16-bit pointer to a 32-bit boolean+ case 0x0132:+ typeString = "T_PBOOL32";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 32-bit boolean+ case 0x0232:+ typeString = "T_PFBOOL32";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 32-bit boolean+ case 0x0332:+ typeString = "T_PHBOOL32";+ typeSize = 4;+ break;+ // 32-bit pointer to a 32-bit boolean+ case 0x0432:+ typeString = "T_32PBOOL32";+ typeSize = 4;+ break;+ // 16:32 pointer to a 32-bit boolean+ case 0x0532:+ typeString = "T_32PFBOOL32";+ typeSize = 6;+ break;+ // 64-bit pointer to a 32-bit boolean+ case 0x0632:+ typeString = "T_64PBOOL32";+ typeSize = 8;+ break;++ //=======================================+ // 64-bit boolean types+ //=======================================+ // 64-bit boolean+ case 0x0033:+ typeString = "T_BOOL64";+ typeSize = 2;+ break;+ // 16-bit pointer to a 64-bit boolean+ case 0x0133:+ typeString = "T_PBOOL64";+ typeSize = 2;+ break;+ // 16:16 far pointer to a 64-bit boolean+ case 0x0233:+ typeString = "T_PFBOOL64";+ typeSize = 4;+ break;+ // 16:16 huge pointer to a 64-bit boolean+ case 0x0333:+ typeString = "T_PHBOOL64";+ typeSize = 4;+ break;+ // 32-bit pointer to a 64-bit boolean+ case 0x0433:+ typeString = "T_32PBOOL64";+ typeSize = 4;+ break;+ // 16:32 pointer to a 64-bit boolean+ case 0x0533:+ typeString = "T_32PFBOOL64";+ typeSize = 6;+ break;+ // 64-bit pointer to a 64-bit boolean+ case 0x0633:+ typeString = "T_64PBOOL64";+ typeSize = 8;+ break;++ //=======================================+ // Internal type with pointers+ //=======================================+ // CV Internal type for created near pointers+ case 0x01f0:+ typeString = "T_NCVPTR";+ typeSize = 2;+ break;+ // CV Internal type for created far pointers+ case 0x02f0:+ typeString = "T_FCVPTR";+ typeSize = 4;+ break;+ // CV Internal type for created huge pointers+ case 0x03f0:+ typeString = "T_HCVPTR";+ typeSize = 4;+ break;+ // CV Internal type for created near 32-bit pointers+ case 0x04f0:+ typeString = "T_32NCVPTR";+ typeSize = 4;+ break;+ // CV Internal type for created far 32-bit pointers+ case 0x05f0:+ typeString = "T_32FCVPTR";+ typeSize = 6;+ break;+ // CV Internal type for created near 64-bit pointers+ case 0x06f0:+ typeString = "T_64NCVPTR";+ typeSize = 8;+ break;++ }+ }++}diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/type/UnknownMsType.java b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/type/UnknownMsType.javanew file mode 100644index 0000000000..b65f042b3a--- /dev/null+++ b/Ghidra/Features/PDB/src/main/java/ghidra/pdb/pdbreader/type/UnknownMsType.java@@ -0,0 +1,61 @@+/* ###+ * 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.pdb.pdbreader.type;++import ghidra.pdb.PdbByteReader;+import ghidra.pdb.pdbreader.AbstractPdb;++/**+ * This is not a real MS Type. We made this up to take the place of anticipated, unknown+ * types.+ */+public class UnknownMsType extends AbstractMsType {++ private int id = 0;+ private byte[] data;++ /**+ * Constructor for this type.+ * @param pdb {@link AbstractPdb} to which this symbol belongs.+ * @param reader {@link PdbByteReader} from which this symbol is deserialized.+ * @param id Value to be used as the unique PDB ID.+ */+ public UnknownMsType(AbstractPdb pdb, PdbByteReader reader, int id) {+ super(pdb, reader);+ this.id = id;+ data = reader.parseBytesRemaining();+ }++ @Override+ public int getPdbId() {+ return id;+ }++ /**+ * Returns the data of this symbol (we do not know how to interpret it yet).+ * @return {@code byte[]} data.+ */+ public byte[] getData() {+ return data;+ }++ @Override+ public void emit(StringBuilder builder, Bind bind) {+ PdbByteReader reader = new PdbByteReader(data);+ builder.append(String.format("UNKNOWN_TYPE (0X%04X): Bytes:%s", id, reader.dumpBytes()));+ }++}diff --git a/Ghidra/Features/PDB/src/test/java/ghidra/pdb/PdbByteWriter.java b/Ghidra/Features/PDB/src/test/java/ghidra/pdb/PdbByteWriter.javanew file mode 100644index 0000000000..ebe1a2c527--- /dev/null+++ b/Ghidra/Features/PDB/src/test/java/ghidra/pdb/PdbByteWriter.java@@ -0,0 +1,336 @@+/* ###+ * 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.pdb;++import java.math.BigInteger;+import java.nio.charset.StandardCharsets;+import java.util.*;++import ghidra.util.LittleEndianDataConverter;+import ghidra.util.exception.AssertException;++/**+ * This is a utility class for testing parts of the PDB Reader, which has data predominantly+ * stored in Little Endian order in byte array buffers. This utility is used for+ * writing byte arrays for the purpose of testing classes that parse byte arrays for their+ * construction/instantiation. The class that generally reads (the reverse process) the byte+ * arrays for the PDB Reader is the {@link PdbByteReader}, which reads in Little Endian order.+ * <P>+ * This utility class should be used as follows:+ * <OL>+ * <LI> Instantiate a {@code ByteWriter}.</LI>+ * <LI> Do a sequence of "put" methods.</LI>+ * <LI> Call {@link #get()} to retrieve the byte array.</LI>+ * <LI> Repeat process, starting with a new instantiation or call the {@link #reset()} method.</LI>+ * </OL>+ */+public class PdbByteWriter {++ private static byte[] paddingBytes = { (byte) 0xf4, (byte) 0xf3, (byte) 0xf2, (byte) 0xf1 };+ private static byte[] alignBytes = { 0x00, 0x00, 0x00, 0x00 };++ //==============================================================================================+ // Internals+ //==============================================================================================+ private byte[] byteArray = new byte[8];+ private List<Byte> byteList = new ArrayList<>();++ //==============================================================================================+ // API+ //==============================================================================================+ public PdbByteWriter() {+ reset();+ }++ public void reset() {+ byteList = new ArrayList<>();+ // We do not need to reset the bytes variable here. It is created when access to it is+ // attempted with the get() method.+ }++ /**+ * Get the number of bytes in the ByteWriter.+ * @return The integer number of bytes in the ByteWriter.+ */+ public int getSize() {+ return byteList.size();+ }++ /**+ * Method to get the resultant, desired byte array that has been populated by the "put"+ * methods.+ * @return The byte[] containing the result.+ */+ public byte[] get() {+ int length = byteList.size();+ byte[] bytes = new byte[length];+ int i = 0;+ for (byte b : byteList) {+ bytes[i++] = b;+ }+ return bytes;+ }++ /**+ * Put the data to occupy the next byte sequence in the byte array.+ * @param bytes The input byte array to write to the output byte array+ */+ public void putBytes(byte[] bytes) {+ putBytes(bytes, bytes.length);+ }++ /**+ * Put the data to occupy the next byte sequence in the byte array.+ * @param bytes The input byte array to write to the output byte array+ * @param num The number of bytes to write from the byte array; must be within size of input.+ */+ public void putBytes(byte[] bytes, int num) {+ for (int i = 0; i < num; i++) {+ byteList.add(bytes[i]);+ }+ }++ /**+ * Puts padding into the byte array. Pads the buffer to a multiple of four bytes, assuming+ * that there were a {@code disallow} number of bytes were previously written to the buffer.+ * <P>+ * This method is older than the {@link #putAlign(int)} method. It uses specific padding+ * values.+ * @param disallow The number of bytes to disallow from the calculation.+ */+ public void putPadding(int disallow) {+ int mod = 4 * ((byteList.size() - disallow + 3) / 4) - (byteList.size() - disallow);+ putBytes(Arrays.copyOfRange(paddingBytes, paddingBytes.length - mod, paddingBytes.length),+ mod);+ }++ /**+ * Puts padding into the byte array. Pads the buffer to a multiple of four bytes, assuming+ * that there were a {@code disallow} number of bytes were previously written to the buffer.+ * <P>+ * This method is newer than the {@link #putPadding(int)} method. It uses 0x00 values.+ * @param disallow The number of bytes to disallow from the calculation.+ */+ public void putAlign(int disallow) {+ int mod = 4 * ((byteList.size() - disallow + 3) / 4) - (byteList.size() - disallow);+ putBytes(alignBytes, mod);+ }++ /**+ * Put the data to occupy the next byte space in the byte array.+ * @param value The integer value of the byte to be written.+ */+ public void putUnsignedByte(int value) {+ byteArray[0] = (byte) (value & 0xff);+ putBytes(byteArray, 1);+ }++ /**+ * Put the data to occupy the next short space in the byte array.+ * @param value The short value of the short to be written.+ */+ public void putShort(short value) {+ LittleEndianDataConverter.INSTANCE.putShort(byteArray, value);+ putBytes(byteArray, 2);+ }++ /**+ * Put the data to occupy the next unsigned short space in the byte array.+ * @param value The integer value of the unsigned short to be written.+ */+ public void putUnsignedShort(int value) {+ LittleEndianDataConverter.INSTANCE.putShort(byteArray, (short) (value & 0xffff));+ putBytes(byteArray, 2);+ }++ /**+ * Put the data to occupy the next integer space in the byte array.+ * @param value The integer value of the integer to be written.+ */+ public void putInt(int value) {+ LittleEndianDataConverter.INSTANCE.putInt(byteArray, value);+ putBytes(byteArray, 4);+ }++ /**+ * Put the data to occupy the next unsigned integer space in the byte array.+ * @param value The long value of the unsigned integer to be written.+ */+ public void putUnsignedInt(long value) {+ LittleEndianDataConverter.INSTANCE.putInt(byteArray, (int) (value & 0xffffffffffL));+ putBytes(byteArray, 4);+ }++ /**+ * Put the data to occupy the next long space in the byte array.+ * @param value The long value of the long to be written.+ */+ public void putLong(long value) {+ LittleEndianDataConverter.INSTANCE.putLong(byteArray, value);+ putBytes(byteArray, 8);+ }++ /**+ * Put the data to occupy the next unsigned long space in the byte array.+ * @param value The BigInteger value of the unsigned long to be written.+ */+ public void putUnsignedLong(BigInteger value) {+ BigInteger arg = value.and(new BigInteger("ffffffffffffffff", 16));+ LittleEndianDataConverter.INSTANCE.putLong(byteArray, arg.longValue());+ putBytes(byteArray, 8);+ }++ /**+ * Put the data to occupy the next Numeric field in the byte array. For Numeric definition,+ * see the PdbByteReader method for reading such a field. If value is too large for the+ * encoding code, the value is masked.+ * @param value The BigInteger containing the value to be written into the Numeric field.+ * @param code The encoding code for representing the Numeric field+ */+ public void putNumeric(BigInteger value, int code) {+ // Drop bits. Letting value become signed too.+ BigInteger arg = value.and(new BigInteger("ffffffffffffffff", 16));+ long longValue;+ try {+ longValue = value.longValueExact();+ }+ catch (ArithmeticException e) {+ // Should not happen since we "ANDed" the value. Fail silently+ return;+ }+ switch (code) {+ // For each case, parse bytes (to move index forward) and throw bytes away.+ // The number of bytes parsed is based on the size of the integral type+ // represented by subTypeIndex.+ case 0x8000: // char+ putUnsignedShort(code);+ putUnsignedByte((int) (longValue & 0xff));+ break;+ case 0x8001: // short+ putUnsignedShort(code);+ putShort((short) (longValue & 0xffff));+ break;+ case 0x8002: // unsigned short+ putUnsignedShort(code);+ putUnsignedShort((int) (longValue & 0xffff));+ break;+ case 0x8003: // 32-bit+ putUnsignedShort(code);+ putInt((int) (longValue & 0xffffffff));+ break;+ case 0x8004: // unsigned 32-bit+ putUnsignedShort(code);+ putUnsignedInt(longValue & 0xffffffff);+ break;+ case 0x8009: // 64-bit+ putUnsignedShort(code);+ putLong(longValue);+ break;+ case 0x800a: // unsigned 64-bit+ putUnsignedShort(code);+ putUnsignedLong(arg);+ break;+ default:+ return; // Fail silently.+ }+ }++ /**+ * Put a GUID into the byte array. The GUID is represented by the standard arguments used,+ * and these are accepted as arguments to this method.+ * @param data1 An int, as first constituent piece.+ * @param data2 A short, as second constituent piece.+ * @param data3 A short, as third constituent piece.+ * @param data4 A byte[8], as fourth constituent piece.+ */+ public void putGUID(int data1, short data2, short data3, byte[] data4) {+ assert data4.length == 8;+ putInt(data1);+ putShort(data2);+ putShort(data3);+ putBytes(data4);+ }++ /**+ * Put the data to occupy the next byte-length-prefixed string in the byte array.+ * @param string The String representation of the data to written.+ */+ public void putByteLengthPrefixedString(String string) {+ int length = string.length();+ if (length > 255) {+ throw new AssertException("length > 255");+ }+ byte[] bytes = new byte[1];+ bytes[0] = (byte) length;+ putBytes(bytes);+ bytes = string.getBytes(StandardCharsets.US_ASCII);+ putBytes(bytes);+ }++ /**+ * Put the data to occupy the next byte-length-prefixed UTF8 string in the byte array.+ * @param string The String representation of the data to written.+ */+ public void putByteLengthPrefixedUtf8String(String string) {+ int length = string.length();+ if (length > 255) {+ throw new AssertException("length > 255");+ }+ byte[] bytes = new byte[1];+ bytes[0] = (byte) length;+ putBytes(bytes);+ bytes = string.getBytes(StandardCharsets.UTF_8);+ putBytes(bytes);+ }++ /**+ * Put the data to occupy the next null-terminated string in the byte array.+ * @param string The String representation of the data to written.+ */+ public void putNullTerminatedString(String string) {+ byte[] bytes = string.getBytes(StandardCharsets.US_ASCII);+ putBytes(bytes);+ bytes = new byte[1];+ bytes[0] = 0;+ putBytes(bytes);+ }++ /**+ * Put the data to occupy the next null-terminated UTF8 string in the byte array.+ * @param string The String representation of the data to written.+ */+ public void putNullTerminatedUtf8String(String string) {+ byte[] bytes = string.getBytes(StandardCharsets.UTF_8);+ putBytes(bytes);+ bytes = new byte[1];+ bytes[0] = 0;+ putBytes(bytes);+ }++ /**+ * Put the data to occupy the next null-terminated wchar_t string in the byte array.+ * @param string The String representation of the data to written.+ */+ public void putNullTerminatedWchartString(String string) {+ byte[] bytes = string.getBytes(StandardCharsets.UTF_16);+ putBytes(bytes);+ bytes = new byte[2];+ bytes[0] = 0;+ bytes[1] = 0;+ putBytes(bytes);+ }++}diff --git a/Ghidra/Features/PDB/src/test/java/ghidra/pdb/PdbByteWriterReaderTest.java b/Ghidra/Features/PDB/src/test/java/ghidra/pdb/PdbByteWriterReaderTest.javanew file mode 100644index 0000000000..b2c0c2e399--- /dev/null+++ b/Ghidra/Features/PDB/src/test/java/ghidra/pdb/PdbByteWriterReaderTest.java@@ -0,0 +1,206 @@+/* ###+ * 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.pdb;++import static org.junit.Assert.assertArrayEquals;+import static org.junit.Assert.assertEquals;++import java.math.BigInteger;++import org.junit.Test;++import generic.test.AbstractGenericTest;+import ghidra.app.util.datatype.microsoft.GUID;++public class PdbByteWriterReaderTest extends AbstractGenericTest {++ //==============================================================================================+ // Tests+ //==============================================================================================+ @Test+ public void testWriter() throws PdbException {+ PdbByteWriter writer = new PdbByteWriter();++ byte[] byteArrayTest1 = new byte[3];+ byteArrayTest1[0] = (byte) 0xe7;+ byteArrayTest1[1] = (byte) 0xc3;+ byteArrayTest1[2] = (byte) 0x81;++ int byteValueTest1 = 0xff;+ int byteValueTest2 = 0x00;++ short shortValueTest1 = Short.MAX_VALUE;+ short shortValueTest2 = Short.MIN_VALUE;++ int unsignedShortValueTest1 = 0xffff;+ int unsignedShortValueTest2 = 0x0123;++ int intValueTest1 = Integer.MAX_VALUE;+ int intValueTest2 = Integer.MIN_VALUE;++ long unsignedIntValueTest1 = 0xffffffffL;+ long unsignedIntValueTest2 = 0x01234567L;++ long longValueTest1 = Long.MAX_VALUE;+ long longValueTest2 = Long.MIN_VALUE;++ BigInteger unsignedLongValueTest1 = new BigInteger("ffffffffffffffff", 16);+ BigInteger unsignedLongValueTest2 = new BigInteger("0123456789abcdef", 16);++ BigInteger numericValueTest1 = new BigInteger("12", 16);+ int numericCodeTest1 = 0x8000;+ BigInteger numericValueTest2 = new BigInteger("2345", 16);+ int numericCodeTest2 = 0x8001;+ BigInteger numericValueTest3 = new BigInteger("3456", 16);+ int numericCodeTest3 = 0x8002;+ BigInteger numericValueTest4 = new BigInteger("456789ab", 16);+ int numericCodeTest4 = 0x8003;+ BigInteger numericValueTest5 = new BigInteger("56789abc", 16);+ int numericCodeTest5 = 0x8004;+ BigInteger numericValueTest6 = new BigInteger("6789abcdef012345", 16);+ int numericCodeTest6 = 0x8009;+ BigInteger numericValueTest7 = new BigInteger("789abcdef0123456", 16);+ int numericCodeTest7 = 0x800a;++ String stringTest1 = new String("abcd");+ String stringTest2 = new String("efgh");+ String stringTest3 = new String("ijkl");+ String stringTest4 = new String("mnop");+ String stringTest5 = new String("qrst");++ writer.putBytes(byteArrayTest1, byteArrayTest1.length);+ writer.putUnsignedByte(byteValueTest1);+ writer.putUnsignedByte(byteValueTest2);+ writer.putShort(shortValueTest1);+ writer.putShort(shortValueTest2);+ writer.putUnsignedShort(unsignedShortValueTest1);+ writer.putUnsignedShort(unsignedShortValueTest2);+ writer.putInt(intValueTest1);+ writer.putInt(intValueTest2);+ writer.putUnsignedInt(unsignedIntValueTest1);+ writer.putUnsignedInt(unsignedIntValueTest2);+ writer.putLong(longValueTest1);+ writer.putLong(longValueTest2);+ writer.putUnsignedLong(unsignedLongValueTest1);+ writer.putUnsignedLong(unsignedLongValueTest2);+ writer.putNumeric(numericValueTest1, numericCodeTest1);+ writer.putNumeric(numericValueTest2, numericCodeTest2);+ writer.putNumeric(numericValueTest3, numericCodeTest3);+ writer.putNumeric(numericValueTest4, numericCodeTest4);+ writer.putNumeric(numericValueTest5, numericCodeTest5);+ writer.putNumeric(numericValueTest6, numericCodeTest6);+ writer.putNumeric(numericValueTest7, numericCodeTest7);+ writer.putByteLengthPrefixedString(stringTest1);+ writer.putByteLengthPrefixedUtf8String(stringTest2);+ writer.putNullTerminatedString(stringTest3);+ writer.putNullTerminatedUtf8String(stringTest4);+ writer.putNullTerminatedWchartString(stringTest5);++ writer.putGUID(0x0f0e0d0c, (short) 0x0b0a, (short) 0x0908,+ new byte[] { 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00 });++ writer.putAlign(1);+ writer.putPadding(2);++ byte[] byteArrayValue;+ int byteValue;+ short shortValue;+ int unsignedShortValue;+ int intValue;+ long unsignedIntValue;+ long longValue;+ BigInteger unsignedLongValue;+ BigInteger numericValue;+ String string;+ GUID guid;++ byte[] buffer = writer.get();+ PdbByteReader reader = new PdbByteReader(buffer);++ byteArrayValue = reader.parseBytes(3);+ assertArrayEquals(byteArrayTest1, byteArrayValue);++ byteValue = reader.parseUnsignedByteVal();+ assertEquals(byteValue, byteValueTest1);+ byteValue = reader.parseUnsignedByteVal();+ assertEquals(byteValue, byteValueTest2);++ shortValue = reader.parseShort();+ assertEquals(shortValue, shortValueTest1);+ shortValue = reader.parseShort();+ assertEquals(shortValue, shortValueTest2);++ unsignedShortValue = reader.parseUnsignedShortVal();+ assertEquals(unsignedShortValue, unsignedShortValueTest1);+ unsignedShortValue = reader.parseUnsignedShortVal();+ assertEquals(unsignedShortValue, unsignedShortValueTest2);++ intValue = reader.parseInt();+ assertEquals(intValue, intValueTest1);+ intValue = reader.parseInt();+ assertEquals(intValue, intValueTest2);++ unsignedIntValue = reader.parseUnsignedIntVal();+ assertEquals(unsignedIntValue, unsignedIntValueTest1);+ unsignedIntValue = reader.parseUnsignedIntVal();+ assertEquals(unsignedIntValue, unsignedIntValueTest2);++ longValue = reader.parseLong();+ assertEquals(longValue, longValueTest1);+ longValue = reader.parseLong();+ assertEquals(longValue, longValueTest2);++ unsignedLongValue = reader.parseUnsignedLongVal();+ assertEquals(unsignedLongValue.compareTo(unsignedLongValueTest1), 0);+ unsignedLongValue = reader.parseUnsignedLongVal();+ assertEquals(unsignedLongValue.compareTo(unsignedLongValueTest2), 0);++ numericValue = reader.parseNumeric();+ assertEquals(numericValue.compareTo(numericValueTest1), 0);+ numericValue = reader.parseNumeric();+ assertEquals(numericValue.compareTo(numericValueTest2), 0);+ numericValue = reader.parseNumeric();+ assertEquals(numericValue.compareTo(numericValueTest3), 0);+ numericValue = reader.parseNumeric();+ assertEquals(numericValue.compareTo(numericValueTest4), 0);+ numericValue = reader.parseNumeric();+ assertEquals(numericValue.compareTo(numericValueTest5), 0);+ numericValue = reader.parseNumeric();+ assertEquals(numericValue.compareTo(numericValueTest6), 0);+ numericValue = reader.parseNumeric();+ assertEquals(numericValue.compareTo(numericValueTest7), 0);++ string = reader.parseByteLengthPrefixedString();+ assertEquals(string, stringTest1);+ string = reader.parseByteLengthPrefixedUtf8String();+ assertEquals(string, stringTest2);+ string = reader.parseNullTerminatedString();+ assertEquals(string, stringTest3);+ string = reader.parseNullTerminatedUtf8String();+ assertEquals(string, stringTest4);+ string = reader.parseNullTerminatedWcharString();+ assertEquals(string, stringTest5);++ guid = reader.parseGUID();+ assertEquals("0f0e0d0c-0b0a-0908-0706-050403020100", guid.toString());++ byteArrayValue = reader.parseBytesRemaining();+ assertEquals(byteArrayValue.length, 2);+ assertEquals(byteArrayValue[0], 0x00);+ assertEquals(byteArrayValue[1], (byte) 0xf1);+ }++}diff --git a/Ghidra/Features/PDB/src/test/java/ghidra/pdb/msfreader/MsfReaderUnitTest.java b/Ghidra/Features/PDB/src/test/java/ghidra/pdb/msfreader/MsfReaderUnitTest.javanew file mode 100644index 0000000000..c498570a19--- /dev/null+++ b/Ghidra/Features/PDB/src/test/java/ghidra/pdb/msfreader/MsfReaderUnitTest.java@@ -0,0 +1,591 @@+/* ###+ * 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.pdb.msfreader;++import static org.junit.Assert.assertEquals;++import java.io.*;+import java.util.*;++import org.junit.*;++import generic.test.AbstractGenericTest;+import ghidra.pdb.PdbByteWriter;+import ghidra.util.Msg;+import ghidra.util.task.TaskMonitor;++public class MsfReaderUnitTest extends AbstractGenericTest {++ private static final int STREAM_OUTPUT_MAX = 0x80;++ // "Microsoft C/C++ program database 2.00\r\n" + (char) 0x1a + "JG";+ private static final byte[] IDENTIFICATION_200 =+ "Microsoft C/C++ program database 2.00\r\n\u001aJG".getBytes();+ // Padding between IDENTIFICATION and pageSize+ private static final byte[] padding200 = new byte[] { 0x00, 0x00 };++ // "Microsoft C/C++ MSF 7.00\r\n" + (char) 0x1a + "DS"+ private static final byte[] IDENTIFICATION_700 =+ "Microsoft C/C++ MSF 7.00\r\n\u001aDS".getBytes();+ // Padding between magic and pageSize+ private static final byte[] padding700 = new byte[] { 0x00, 0x00, 0x00 };++ //==============================================================================================+ // Internals+ //==============================================================================================+ protected static File tDir;+ protected static String testFileName200;+ protected static File testFile200;+ protected static String testFileName700;+ protected static File testFile700;++ //==============================================================================================+ /**+ * @throws IOException Upon file IO issues.+ */+ @Before+ public void setUp() throws IOException {+ if (tDir == null) {+ tDir = createTempDirectory("msfreader");+ }+ if (testFile200 == null) {+ testFile200 = new File(tDir, "msfreader200.pdb");+ testFileName200 = testFile200.getAbsolutePath();+ byte[] buffer = createStreamFile200();+ FileOutputStream stream = new FileOutputStream(testFile200);+ stream.write(buffer);+ stream.close();+ }+ if (testFile700 == null) {+ testFile700 = new File(tDir, "msfreader700.pdb");+ testFileName700 = testFile700.getAbsolutePath();+ byte[] buffer = createStreamFile700();+ FileOutputStream stream = new FileOutputStream(testFile700);+ stream.write(buffer);+ stream.close();+ }+ }++ @AfterClass+ public static void tearDown() throws Throwable {+ if (testFileName200 != null) {+ Msg.info(MsfReaderUnitTest.class, "MSF test file used: " + testFileName200);+ }+ if (testFileName700 != null) {+ Msg.info(MsfReaderUnitTest.class, "MSF test file used: " + testFileName700);+ }+ }++ //==============================================================================================+ /**+ * Dumps a number bytes of information from a Stream in the AbstractStreamFile to String.+ * for debug purposes.+ * @param streamFile The AbstractStreamFile to be used.+ * @param streamNumber The streamNumber of the file to dump.+ * @param maxOut Maximum number of bytes to dump.+ * @return String containing the output.+ */+ public static String dumpStream(AbstractMsf streamFile, int streamNumber, int maxOut) {+ MsfStream stream = streamFile.getStream(streamNumber);+ StringBuilder builder = new StringBuilder();+ builder.append("Stream: " + streamNumber + "\n");+ builder.append(stream.dump(maxOut));+ return builder.toString();+ }++ //==============================================================================================+ // Tests+ //==============================================================================================+ @Test+ public void testStreamFile200Header() {+ try (AbstractMsf streamFile = MsfParser.parse(testFileName200, TaskMonitor.DUMMY)) {+ int numStreams = streamFile.getNumStreams();+ StringBuilder builder = new StringBuilder();+ builder.append("NumStreams: " + numStreams + "\n");+ for (int streamNumber = 0; streamNumber < numStreams; streamNumber++) {+ builder.append(dumpStream(streamFile, streamNumber, STREAM_OUTPUT_MAX));+ builder.append("\n");+ }+ Msg.info(this, builder.toString());+ }+ catch (Exception e) {+ assertEquals(e.getClass(), FileNotFoundException.class);+ }+ }++ @Test+ public void testStreamFile700Header() {+ try (AbstractMsf streamFile = MsfParser.parse(testFileName700, TaskMonitor.DUMMY)) {+ int numStreams = streamFile.getNumStreams();+ StringBuilder builder = new StringBuilder();+ builder.append("NumStreams: " + numStreams + "\n");+ for (int streamNumber = 0; streamNumber < numStreams; streamNumber++) {+ builder.append(dumpStream(streamFile, streamNumber, STREAM_OUTPUT_MAX));+ builder.append("\n");+ }+ Msg.info(this, builder.toString());+ }+ catch (Exception e) {+ assertEquals(e.getClass(), FileNotFoundException.class);+ }+ }++ //==============================================================================================+ // Private Methods+ //==============================================================================================+ private byte[] createStreamFile200() {+ int pageSize = 0x1000;+ MultiStreamFile msf200 = new MultiStreamFile(MsfVer.V200, pageSize);+ Stream stream = msf200.createStream();+ byte[] dataStreamBuffer = createDataForStream(pageSize);+ stream.putData(dataStreamBuffer);++ return msf200.serialize();+ }++ private byte[] createStreamFile700() {+ int pageSize = 0x1000;+ MultiStreamFile msf700 = new MultiStreamFile(MsfVer.V700, pageSize);+ Stream stream = msf700.createStream();+ byte[] dataStreamBuffer = createDataForStream(pageSize);+ stream.putData(dataStreamBuffer);++ return msf700.serialize();+ }++ //==============================================================================================+ // Private Classes+ //==============================================================================================+ private static enum MsfVer {+ V200, V700+ }++ //==============================================================================================+ private class MsfHeader {+ private MultiStreamFile msf;+ private List<Integer> serializationPageList;++ MsfHeader(MultiStreamFile msfSpec) {+ msf = msfSpec;+ serializationPageList = new ArrayList<>();+ }++ void init() {+ // By definition, header gets page 0.+ msf.fpm.reservePage(0);+ serializationPageList.add(0);+ }++ void serialize(int numPages, int fpmPn, byte[] directoryStreamInfoBytes) {+ byte[] bytes;+ if (msf.ver == MsfVer.V200) {+ bytes = createStreamFile200Header(msf.pageSize, fpmPn, numPages,+ directoryStreamInfoBytes);+ }+ else {+ bytes = createStreamFile700Header(msf.pageSize, fpmPn, numPages,+ directoryStreamInfoBytes);+ }+ msf.fillPages(bytes, serializationPageList);+ }++ private byte[] createStreamFile200Header(int pageSize, int freePageMapPageNumber,+ int numPages, byte[] directoryStreamInfo) {+ if (pageSize != 0x400 && pageSize != 0x800 && pageSize != 0x1000) {+ return null;+ }+ if (freePageMapPageNumber < 1 || freePageMapPageNumber > 0xffff) {+ return null;+ }+ if (numPages < 1 || numPages > 0xffff) {+ return null;+ }+ PdbByteWriter writer = new PdbByteWriter();+ writer.putBytes(IDENTIFICATION_200);+ writer.putBytes(padding200);+ writer.putInt(pageSize);+ writer.putUnsignedShort(freePageMapPageNumber);+ writer.putUnsignedShort(numPages);+ writer.putBytes(directoryStreamInfo);+ return writer.get();+ }++ private byte[] createStreamFile700Header(int pageSize, int freePageMapPageNumber,+ int numPages, byte[] directoryStreamInfo) {+ if (pageSize != 0x200 && pageSize != 0x400 && pageSize != 0x800 && pageSize != 0x1000) {+ return null;+ }+ if (freePageMapPageNumber < 1) { // not checking upper limit+ return null;+ }+ if (numPages < 1) { // not checking upper limit+ return null;+ }+ PdbByteWriter writer = new PdbByteWriter();+ writer.putBytes(IDENTIFICATION_700);+ writer.putBytes(padding700);+ writer.putInt(pageSize);+ writer.putInt(freePageMapPageNumber);+ writer.putInt(numPages);+ writer.putBytes(directoryStreamInfo);+ return writer.get();+ }++ }++ //==============================================================================================+ private class FreePageMap {+ private MultiStreamFile msf;+ private List<Integer> serializationPageList;+ // numUsedPages not used, but would be if we allowed it fpm to grow or allowed modification+ // model, in which case we would need to search the list first before adding to the list.+ // Having the value could short-cut the need for searching.+ //private int numUsedPages;+ boolean[] freePage;++ FreePageMap(MultiStreamFile msfSpec) {+ msf = msfSpec;+ serializationPageList = new ArrayList<>();+ //numUsedPages = 0;+ freePage = new boolean[msf.totalPages];+ for (int i = 0; i < msf.totalPages; i++) {+ freePage[i] = true;+ }+ }++ void init() {+ // Taking page 1 for FreePageMap.+ reservePage(1);+ serializationPageList.add(1);+ }++ void reservePage(int pageNumber) {+ assert freePage[pageNumber];+ freePage[pageNumber] = false;+ }++ List<Integer> reservePages(int dataLength) {+ int numPages = 1 + (dataLength - 1) / msf.pageSize;+ List<Integer> pageList = new ArrayList<>();+ for (int i = 0; i < numPages; i++) {+ pageList.add(msf.fpm.getFreePage());+ }+ return pageList;+ }++ void serialize() {+ byte[] bytes;+ if (msf.ver == MsfVer.V200) {+ bytes = serializedFreePageMap200();+ }+ else {+ bytes = serializedFreePageMap700();+ }+ msf.fillPages(bytes, serializationPageList);+ }++ private int getFreePage() {+ for (int i = 0; i < freePage.length; i++) {+ if (freePage[i]) {+ freePage[i] = false;+ //numUsedPages++;+ return i;+ }+ }+ assert false;+ return -1;+ }++ private byte[] serializedFreePageMap200() {+ // TODO: detailed work.+ int bits = 0x00;+ PdbByteWriter writer = new PdbByteWriter();+ writer.putUnsignedByte(bits);+ return writer.get();+ }++ private byte[] serializedFreePageMap700() {+ // TODO: detailed work.+ int bits = 0x00;+ PdbByteWriter writer = new PdbByteWriter();+ writer.putUnsignedByte(bits);+ return writer.get();+ }+ }++ //==============================================================================================+ private class Stream {+ MultiStreamFile msf;+ int streamNum;+ private List<Integer> serializationPageList;+ private byte[] data;++ Stream(MultiStreamFile msfSpec) {+ msf = msfSpec;+ serializationPageList = new ArrayList<>();+ streamNum = msf.st.addStream(this);+ data = new byte[0];+ }++ void serialize() {+ msf.fillPages(data, serializationPageList);+ }++ byte[] serializeStreamInfo() {+ PdbByteWriter writer = new PdbByteWriter();+ writer.putBytes(serializeLengthAndMapTableAddress());+ writer.putBytes(serializePageNumbers());+ return writer.get();+ }++ // Not supporting incremental writing.+ void putData(byte[] dataIn) {+ data = dataIn;+ serializationPageList = msf.fpm.reservePages(data.length);+ }++// int getLength() {+// return data.length;+// }+//+// byte[] getData() {+// return data;+// }+//+ protected byte[] serializeLength() {+ PdbByteWriter writer = new PdbByteWriter();+ writer.putInt(data.length);+ return writer.get();+ }++ protected byte[] serializeLengthAndMapTableAddress() {+ PdbByteWriter writer = new PdbByteWriter();+ writer.putInt(data.length);+ writer.putInt(0); // MapTable address?+ return writer.get();+ }++ protected byte[] serializePageNumbers() {+ if (msf.ver == MsfVer.V200) {+ return serializePageNumbers200(serializationPageList);+ }+ return serializePageNumbers700(serializationPageList);+ }++ protected byte[] serializePageNumbers200(List<Integer> pageList) {+ PdbByteWriter writer = new PdbByteWriter();+ for (int page : pageList) {+ writer.putUnsignedShort(page);+ }+ return writer.get();+ }++ protected byte[] serializePageNumbers700(List<Integer> pageList) {+ PdbByteWriter writer = new PdbByteWriter();+ for (int page : pageList) {+ writer.putInt(page);+ }+ return writer.get();+ }+ }++ //==============================================================================================+ private class DirectoryStream extends Stream {++ List<Integer> superSerializationPageList;+ byte[] superData;++ DirectoryStream(MultiStreamFile msfSpec) {+ super(msfSpec);+ superSerializationPageList = new ArrayList<>();+ superData = new byte[0];+ }++ @Override+ void putData(byte[] dataIn) {+ superData = dataIn;+ superSerializationPageList = msf.fpm.reservePages(superData.length);+ super.putData(serializePageNumbers700(superSerializationPageList));+ }++ @Override+ void serialize() {+ msf.fillPages(superData, superSerializationPageList);+ super.serialize();+ }++ @Override+ protected byte[] serializeLength() {+ PdbByteWriter writer = new PdbByteWriter();+ writer.putInt(superData.length);+ return writer.get();+ }++ @Override+ protected byte[] serializeLengthAndMapTableAddress() {+ PdbByteWriter writer = new PdbByteWriter();+ writer.putInt(superData.length);+ writer.putInt(0); // MapTable address?+ return writer.get();+ }++ }++ //==============================================================================================+ private class StreamTable {+ MultiStreamFile msf;+ int nextStreamNum;+ List<Integer> streamNumbers;+ Map<Integer, Stream> streamMap;++ StreamTable(MultiStreamFile msfSpec) {+ msf = msfSpec;+ nextStreamNum = 0;+ streamNumbers = new ArrayList<>();+ streamMap = new HashMap<>();+ }++ void init() {+ // nothing at the moment+ }++ int addStream(Stream stream) {+ streamMap.put(nextStreamNum, stream);+ streamNumbers.add(nextStreamNum);+ return nextStreamNum++;+ }++ List<Integer> getStreamNumbers() {+ return streamNumbers;+ }++ Stream getStream(int streamNumber) {+ return streamMap.get(streamNumber);+ }++ byte[] serialize() {+ PdbByteWriter writer = new PdbByteWriter();+ writer.putInt(streamMap.size());+ if (msf.ver == MsfVer.V200) {+ for (int streamNumber : streamMap.keySet()) {+ Stream stream = streamMap.get(streamNumber);+ writer.putBytes(stream.serializeLengthAndMapTableAddress());+ }+ }+ else {+ for (int streamNumber : streamMap.keySet()) {+ Stream stream = streamMap.get(streamNumber);+ writer.putBytes(stream.serializeLength());+ }+ }++ for (int streamNumber : streamMap.keySet()) {+ Stream stream = streamMap.get(streamNumber);+ writer.putBytes(stream.serializePageNumbers());+ }+ return writer.get();+ }+ }++ //==============================================================================================+ private class MultiStreamFile {+ private MsfVer ver;+ private int pageSize;+ private MsfHeader header;+ private FreePageMap fpm;+ private StreamTable st;+ private Stream ds;+ private int totalPages = 0x20; // Doing a fixed size.+ private byte[] outputBuffer;++ MultiStreamFile(MsfVer verSpec, int pageSizeSpec) {+ ver = verSpec;+ pageSize = pageSizeSpec;+ header = new MsfHeader(this);+ fpm = new FreePageMap(this);+ st = new StreamTable(this);+ if (ver == MsfVer.V200) {+ ds = new Stream(this);+ }+ else {+ ds = new DirectoryStream(this);+ }+ assert ds.streamNum == 0;+ header.init();+ fpm.init();+ st.init();+ }++ Stream createStream() {+ return new Stream(this);+ }++// Strm getStream(int streamNumber) {+// return st.getStream(streamNumber);+// }+//+ byte[] serialize() {+ outputBuffer = new byte[pageSize * totalPages];+ ds.putData(st.serialize());+ fpm.serialize();+ for (int streamNumber : st.getStreamNumbers()) {+ Stream stream = st.getStream(streamNumber);+ stream.serialize();+ }+ header.serialize(totalPages, fpm.serializationPageList.get(0),+ ds.serializeStreamInfo());+ return outputBuffer;+ }++ void fillPages(byte[] inputBuffer, List<Integer> pageList) {+ assert outputBuffer != null;+ assert pageList.size() > 0;+ int outputIndex;+ int inputIndex = 0;+ for (int i = 0; i < pageList.size() - 1; i++) {+ outputIndex = pageSize * pageList.get(i);+ for (int j = 0; j < pageSize; j++) {+ outputBuffer[outputIndex++] = inputBuffer[inputIndex++];+ }+ }+ outputIndex = pageSize * pageList.get(pageList.size() - 1);+ int numRemaining = inputBuffer.length - inputIndex;+ int j;+ for (j = 0; j < numRemaining; j++) {+ outputBuffer[outputIndex++] = inputBuffer[inputIndex++];+ }+ for (j = numRemaining; j < pageSize; j++) {+ outputBuffer[outputIndex++] = 0x00;+ }+ }++ }++ //==============================================================================================+ // Junk/test data for a data stream.+ private static byte[] createDataForStream(int pageSize) {+ PdbByteWriter writer = new PdbByteWriter();+ for (int i = 0; i < 16; i++) {+ writer.putUnsignedByte(0x55);+ writer.putUnsignedByte(0xaa);+ }+ for (int i = 0; i < 16; i++) {+ writer.putUnsignedShort(0x1111);+ writer.putUnsignedShort(0xeeee);+ }+ return writer.get();+ }+}