Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-2111 organize ELF note, build-id handling, add Golang build-id

dev74736847e389ac118a
diff --git a/Ghidra/Features/Base/data/ExtensionPoint.manifest b/Ghidra/Features/Base/data/ExtensionPoint.manifest
index b0f36eb07d..273587cd9c 100644
--- a/Ghidra/Features/Base/data/ExtensionPoint.manifest
+++ b/Ghidra/Features/Base/data/ExtensionPoint.manifest
@@ -19,4 +19,4 @@ InstructionSkipper
DataTypeReferenceFinder
ChecksumAlgorithm
OverviewColorService
-
+ElfInfoProducer
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/BinaryReader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/BinaryReader.java
index 5867d96645..e2c364d582 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/BinaryReader.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/BinaryReader.java
@@ -51,6 +51,30 @@ public class BinaryReader {
*/
public final static int SIZEOF_LONG = 8;
+ /**
+ * Reads and returns an object from the current position in the specified BinaryReader.
+ * <p>
+ * When reading from the BinaryReader, use "readNext" methods to consume the location where
+ * the object was located.
+ * <p>
+ * See {@link #get(BinaryReader)}
+ *
+ * @param <T> the type of object that will be returned
+ */
+ public interface ReaderFunction<T> {
+ /**
+ * Reads from the specified {@link BinaryReader} and returns a new object instance.
+ * <p>
+ * When reading from the BinaryReader, use "readNext" methods to consume the location where
+ * the object was located.
+ *
+ * @param reader {@link BinaryReader}
+ * @return new object
+ * @throws IOException if error reading
+ */
+ T get(BinaryReader reader) throws IOException;
+ }
+
private final ByteProvider provider;
private DataConverter converter;
private long currentIndex;
@@ -254,8 +278,6 @@ public class BinaryReader {
return (int) (currentIndex - prevIndex);
}
- ////////////////////////////////////////////////////////////////////
-
/**
* A convenience method for setting the index using a 32 bit integer.
*
@@ -402,6 +424,32 @@ public class BinaryReader {
return l;
}
+ /**
+ * Returns the signed value of the integer (of the specified length) at the current index.
+ *
+ * @param len the number of bytes that the integer occupies, 1 to 8
+ * @return value of requested length, with sign bit extended, in a long
+ * @throws IOException
+ */
+ public long readNextValue(int len) throws IOException {
+ long result = readValue(currentIndex, len);
+ currentIndex += len;
+ return result;
+ }
+
+ /**
+ * Returns the unsigned value of the integer (of the specified length) at the current index.
+ *
+ * @param len the number of bytes that the integer occupies, 1 to 8
+ * @return unsigned value of requested length, in a long
+ * @throws IOException
+ */
+ public long readNextUnsignedValue(int len) throws IOException {
+ long result = readUnsignedValue(currentIndex, len);
+ currentIndex += len;
+ return result;
+ }
+
/**
* Reads a null terminated US-ASCII string starting at the current index,
* advancing the current index by the length of the string that was found.
@@ -508,7 +556,6 @@ public class BinaryReader {
* Trailing null terminator characters will be removed. (suitable for reading
* a string from a fixed length field that is padded with trailing null chars)
* <p>
- * @param index the index where the string begins
* @param charCount the number of charLen character elements to read
* @param charset {@link Charset}, see {@link StandardCharsets}
* @param charLen number of bytes in each character
@@ -579,6 +626,25 @@ public class BinaryReader {
return l;
}
+ /**
+ * Reads an unsigned int32 value, and returns it as a java int (instead of a java long).
+ * <p>
+ * If the value is outside the range of 0..Integer.MAX_VALUE, an InvalidDataException is thrown.
+ * <p>
+ * Useful for reading uint32 values that are going to be used in java to allocate arrays or
+ * other similar cases where the value must be a java integer.
+ *
+ * @return the uint32 value read from the stream, if it fits into the range [0..MAX_VALUE]
+ * of a java integer
+ * @throws IOException if there was an error reading
+ * @throws InvalidDataException if value can not be held in a java integer
+ */
+ public int readNextUnsignedIntExact() throws IOException, InvalidDataException {
+ long i = readNextUnsignedInt();
+ ensureInt32u(i);
+ return (int) i;
+ }
+
//--------------------------------------------------------------------------------------------
// String stuff
//--------------------------------------------------------------------------------------------
@@ -608,6 +674,7 @@ public class BinaryReader {
break; // fall thru to throw new EOF(unterminate string)
}
}
+ // we've wrapped around the end of a 64bit address space and curPos is less than starting position
throw new EOFException("Unterminated string at 0x%s..0x%s"
.formatted(Long.toUnsignedString(index, 16), Long.toUnsignedString(curPos, 16)));
}
@@ -846,9 +913,8 @@ public class BinaryReader {
/**
* Returns the signed value of the integer (of the specified length) at the specified offset.
*
- * @param index offset the offset from the membuffers origin (the address that it is set at)
- * @param len the number of bytes that the integer occupies. Valid values are 1 (byte), 2 (short),
- * 4 (int), 8 (long)
+ * @param index where the value begins
+ * @param len the number of bytes that the integer occupies, 1 to 8
* @return value of requested length, with sign bit extended, in a long
* @throws IOException
*/
@@ -860,9 +926,8 @@ public class BinaryReader {
/**
* Returns the unsigned value of the integer (of the specified length) at the specified offset.
*
- * @param index offset the offset from the membuffers origin (the address that it is set at)
- * @param len the number of bytes that the integer occupies. Valid values are 1 (byte), 2 (short),
- * 4 (int), 8 (long)
+ * @param index where the value begins
+ * @param len the number of bytes that the integer occupies, 1 to 8
* @return unsigned value of requested length, in a long
* @throws IOException
*/
@@ -954,4 +1019,64 @@ public class BinaryReader {
return provider;
}
+ /**
+ * Reads a variable length / unknown format integer from the current position, using the
+ * supplied reader function, returning it (if it fits) as a 32 bit java integer.
+ *
+ * @param func {@link ReaderFunction}
+ * @return signed int32
+ * @throws IOException if error reading or if the value does not fit into a 32 bit java int
+ * @throws InvalidDataException if value can not be held in a java integer
+ */
+ public int readNextVarInt(ReaderFunction<Long> func) throws IOException, InvalidDataException {
+ long value = func.get(this);
+ ensureInt32s(value);
+ return (int) value;
+ }
+
+ /**
+ * Reads a variable length / unknown format unsigned integer from the current position, using
+ * the supplied reader function, returning it (if it fits) as a 32 bit java integer.
+ *
+ * @param func {@link ReaderFunction}
+ * @return unsigned int32
+ * @throws IOException if error reading data
+ * @throws InvalidDataException if value can not be held in a java integer
+ */
+ public int readNextUnsignedVarIntExact(ReaderFunction<Long> func)
+ throws IOException, InvalidDataException {
+ long value = func.get(this);
+ ensureInt32u(value);
+ return (int) value;
+ }
+
+ /**
+ * Reads an object from the current position, using the supplied reader function.
+ *
+ * @param <T> type of the object that will be returned
+ * @param func {@link ReaderFunction} that will read and return an object
+ * @return new object of type T
+ * @throws IOException if error reading
+ */
+ public <T> T readNext(ReaderFunction<T> func) throws IOException {
+ T obj = func.get(this);
+ return obj;
+ }
+
+ //-------------------------------------------------------------------------------------
+ private static void ensureInt32u(long value) throws InvalidDataException {
+ if (value < 0 || value > Integer.MAX_VALUE) {
+ throw new InvalidDataException(
+ "Value out of range for positive java 32 bit unsigned int: %s"
+ .formatted(Long.toUnsignedString(value)));
+ }
+ }
+
+ private static void ensureInt32s(long value) throws InvalidDataException {
+ if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
+ throw new InvalidDataException(
+ "Value out of range for java 32 bit signed int: %d".formatted(value));
+ }
+ }
+
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/InvalidDataException.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/InvalidDataException.java
new file mode 100644
index 0000000000..aaad50c5aa
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/InvalidDataException.java
@@ -0,0 +1,42 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin;
+
+import java.io.IOException;
+
+/**
+ * An {@link IOException} that indicates that the data being transmitted was invalid or bad format.
+ */
+public class InvalidDataException extends IOException {
+ private static final long serialVersionUID = 1L;
+
+ public InvalidDataException() {
+ // empty
+ }
+
+ public InvalidDataException(String message) {
+ super(message);
+ }
+
+ public InvalidDataException(Throwable cause) {
+ super(cause);
+ }
+
+ public InvalidDataException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf4/LEB128.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf4/LEB128.java
index e9b3e19e52..9c97078eb8 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf4/LEB128.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf4/LEB128.java
@@ -228,6 +228,23 @@ public class LEB128 {
return value;
}
+ /**
+ * Reads a LEB128 number from the BinaryReader and returns it as a java 64 bit long int.
+ * <p>
+ * Large unsigned integers that use all 64 bits are be returned in a java native
+ * 'long' type, which is signed. It is up to the caller to treat the value as unsigned.
+ * <p>
+ * Large integers that use more than 64 bits will cause an IOException to be thrown.
+ * <p>
+ * @param reader {@link BinaryReader} to read bytes from
+ * @return long integer value
+ * @throws IOException if an I/O error occurs or value is outside the range of a java
+ * 64 bit int
+ */
+ public static long readUnsignedAsLong(BinaryReader reader) throws IOException {
+ return readAsLong(reader, false);
+ }
+
/**
* Decodes a LEB128 number from a byte array and returns it as a long.
* <p>
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf4/external/ExternalDebugInfo.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf4/external/ExternalDebugInfo.java
index c6e82a7b05..6b9135b1a1 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf4/external/ExternalDebugInfo.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf4/external/ExternalDebugInfo.java
@@ -15,10 +15,8 @@
*/
package ghidra.app.util.bin.format.dwarf4.external;
-import ghidra.app.util.bin.format.elf.GnuBuildIdSection;
-import ghidra.app.util.bin.format.elf.GnuBuildIdSection.GnuBuildIdValues;
-import ghidra.app.util.bin.format.elf.GnuDebugLinkSection;
-import ghidra.app.util.bin.format.elf.GnuDebugLinkSection.GnuDebugLinkSectionValues;
+import ghidra.app.util.bin.format.elf.info.GnuDebugLink;
+import ghidra.app.util.bin.format.elf.info.NoteGnuBuildId;
import ghidra.program.model.listing.Program;
import ghidra.util.NumericUtilities;
@@ -39,18 +37,15 @@ public class ExternalDebugInfo {
* program
*/
public static ExternalDebugInfo fromProgram(Program program) {
- GnuDebugLinkSectionValues debugLinkValues = GnuDebugLinkSection.fromProgram(program);
- GnuBuildIdValues buildIdValues = GnuBuildIdSection.fromProgram(program);
- if (buildIdValues != null && !buildIdValues.isValid()) {
- buildIdValues = null;
- }
- if (debugLinkValues == null && buildIdValues == null) {
+ GnuDebugLink debugLink = GnuDebugLink.fromProgram(program);
+ NoteGnuBuildId buildId = NoteGnuBuildId.fromProgram(program);
+ if (debugLink == null && buildId == null) {
return null;
}
- String filename = debugLinkValues != null ? debugLinkValues.getFilename() : null;
- int crc = debugLinkValues != null ? debugLinkValues.getCrc() : 0;
- byte[] hash = buildIdValues != null ? buildIdValues.getDescription() : null;
+ String filename = debugLink != null ? debugLink.getFilename() : null;
+ int crc = debugLink != null ? debugLink.getCrc() : 0;
+ byte[] hash = buildId != null ? buildId.getHash() : null;
return new ExternalDebugInfo(filename, crc, hash);
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/GnuBuildIdSection.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/GnuBuildIdSection.java
deleted file mode 100644
index 710519a89f..0000000000
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/GnuBuildIdSection.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/* ###
- * IP: GHIDRA
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package ghidra.app.util.bin.format.elf;
-
-import static ghidra.app.util.bin.StructConverter.*;
-
-import java.io.IOException;
-
-import ghidra.app.util.bin.*;
-import ghidra.program.model.data.*;
-import ghidra.program.model.listing.Program;
-import ghidra.program.model.mem.*;
-import ghidra.util.exception.DuplicateNameException;
-
-/**
- * Factory data type that marks up a Gnu Build-Id record from a
- * ELF .note.gnu.build-id section
- */
-public class GnuBuildIdSection extends FactoryStructureDataType {
- public static final String BUILD_ID_SECTION_NAME = ".note.gnu.build-id";
- private static final int MAX_SANE_STR_LENS = 1024;
-
- public static GnuBuildIdValues fromProgram(Program program) {
- MemoryBlock buildIdSection = program.getMemory().getBlock(BUILD_ID_SECTION_NAME);
- if (buildIdSection == null) {
- return null;
- }
- try (ByteProvider bp = MemoryByteProvider.createMemoryBlockByteProvider(program.getMemory(),
- buildIdSection)) {
- BinaryReader br = new BinaryReader(bp, !program.getMemory().isBigEndian());
- long nameLen = br.readNextUnsignedInt();
- long descLen = br.readNextUnsignedInt();
- int vendorType = br.readNextInt();
- if (nameLen > MAX_SANE_STR_LENS || descLen > MAX_SANE_STR_LENS) {
- return null;
- }
- String name = br.readNextAsciiString((int) nameLen);
- byte[] desc = br.readNextByteArray((int) descLen);
- return new GnuBuildIdValues(name, desc, vendorType);
- }
- catch (IOException e) {
- // fall thru and return null
- }
- return null;
- }
-
- public static class GnuBuildIdValues {
- private static final int SHA1_DESC_LEN = 20; // 160bit SHA1 == 20 bytes
-
- private String name; // ie. "gnu"
- private byte[] description; // the hash
- private int vendorType;
-
- private GnuBuildIdValues(String name, byte[] description, int vendorType) {
- this.name = name;
- this.description = description;
- this.vendorType = vendorType;
- }
-
- public String getName() {
- return name;
- }
-
- public byte[] getDescription() {
- return description;
- }
-
- public int getVendorType() {
- return vendorType;
- }
-
- public boolean isValid() {
- return "GNU".equals(name) && description.length == SHA1_DESC_LEN;
- }
- }
-
- private long sectionSize;
-
- /**
- * Creates a new GnuBuildIdDataType instance.
- *
- * @param dtm the {@link DataTypeManager} for the program
- * @param sectionSize the size of the section (for bounds checking, assumes this
- * is the only record in the section)
- */
- public GnuBuildIdSection(DataTypeManager dtm, long sectionSize) {
- super("Gnu_BuildId", dtm);
- this.sectionSize = sectionSize;
- }
-
- @Override
- public DataType clone(DataTypeManager dtm) {
- if (dtm == dataMgr) {
- return this;
- }
- return new GnuBuildIdSection(dtm, sectionSize);
- }
-
- @Override
- protected void populateDynamicStructure(MemBuffer buf, Structure es) {
- try {
- long nameLen = buf.getUnsignedInt(0);
- long descLen = buf.getUnsignedInt(4);
- if (nameLen > MAX_SANE_STR_LENS || descLen > MAX_SANE_STR_LENS ||
- nameLen + descLen + 12 /* sizeof int fields */ > sectionSize) {
- return;
- }
-
- es.add(DWORD, "namesz", "Length of name field");
- es.add(DWORD, "descsz", "Length of description field");
- es.add(DWORD, "type", "Vendor specific type");
- if (nameLen > 0) {
- es.add(StringDataType.dataType, (int) nameLen, "name", "Build-id vendor name");
- }
- if (descLen > 0) {
- es.add(new ArrayDataType(BYTE, (int) descLen, BYTE.getLength(), dataMgr),
- "description", "Build-id value");
- }
- }
- catch (MemoryAccessException e) {
- // ignore and drop thru with partial defined structure type
- }
-
- }
-
- @Override
- protected Structure setCategoryPath(Structure struct, MemBuffer buf) {
- try {
- struct.setCategoryPath(new CategoryPath("/ELF"));
- }
- catch (DuplicateNameException e) {
- // ignore - will not happen
- }
- return struct;
- }
-
-}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/GnuDebugLinkSection.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/GnuDebugLinkSection.java
deleted file mode 100644
index 3bb897fb85..0000000000
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/GnuDebugLinkSection.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/* ###
- * IP: GHIDRA
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package ghidra.app.util.bin.format.elf;
-
-import static ghidra.app.util.bin.StructConverter.*;
-
-import java.io.IOException;
-
-import ghidra.app.util.bin.*;
-import ghidra.docking.settings.SettingsImpl;
-import ghidra.program.model.data.*;
-import ghidra.program.model.listing.Program;
-import ghidra.program.model.mem.MemBuffer;
-import ghidra.program.model.mem.MemoryBlock;
-import ghidra.util.NumericUtilities;
-import ghidra.util.exception.DuplicateNameException;
-
-/**
- * Factory data type that marks up a ELF .gnu_debuglink section.
- */
-public class GnuDebugLinkSection extends FactoryStructureDataType {
- public static final String DEBUG_LINK_SECTION_NAME = ".gnu_debuglink";
-
- public static GnuDebugLinkSectionValues fromProgram(Program program) {
- MemoryBlock debugLinkSection = program.getMemory().getBlock(DEBUG_LINK_SECTION_NAME);
- if (debugLinkSection == null) {
- return null;
- }
- try (ByteProvider bp = MemoryByteProvider.createMemoryBlockByteProvider(program.getMemory(),
- debugLinkSection)) {
- BinaryReader br = new BinaryReader(bp, !program.getMemory().isBigEndian());
- String filename = br.readNextAsciiString();
- br.setPointerIndex(NumericUtilities.getUnsignedAlignedValue(br.getPointerIndex(), 4));
- int crc = br.readNextInt();
- return new GnuDebugLinkSectionValues(filename, crc);
- }
- catch (IOException e) {
- // fall thru and return null
- }
- return null;
- }
-
- public static class GnuDebugLinkSectionValues {
- private String filename;
- private int crc;
-
- public GnuDebugLinkSectionValues(String filename, int crc) {
- this.filename = filename;
- this.crc = crc;
- }
-
- public String getFilename() {
- return filename;
- }
-
- public int getCrc() {
- return crc;
- }
- }
-
- private long sectionSize;
-
- /**
- * Creates a new GnuDebugLinkDataType instance.
- *
- * @param dtm the program's {@link DataTypeManager}
- * @param sectionSize the size of the section (for bounds checking)
- */
- public GnuDebugLinkSection(DataTypeManager dtm, long sectionSize) {
- super("Gnu_DebugLink", dtm);
- this.sectionSize = sectionSize;
- }
-
- @Override
- public DataType clone(DataTypeManager dtm) {
- if (dtm == dataMgr) {
- return this;
- }
- return new GnuDebugLinkSection(dtm, sectionSize);
- }
-
- @Override
- protected void populateDynamicStructure(MemBuffer buf, Structure es) {
- StringDataInstance filenameStr = StringDataInstance.getStringDataInstance(
- StringDataType.dataType, buf, SettingsImpl.NO_SETTINGS, -1);
- int filenameLen = filenameStr.getStringLength();
- if (filenameLen <= 0 || filenameLen + 4 /* crc field */ > sectionSize) {
- return;
- }
- filenameLen = (int) NumericUtilities.getUnsignedAlignedValue(filenameLen, 4);
- es.add(StringDataType.dataType, filenameLen, "filename", "Debug file name");
- es.add(DWORD, "crc", null);
- }
-
- @Override
- protected Structure setCategoryPath(Structure struct, MemBuffer buf) {
- try {
- struct.setCategoryPath(new CategoryPath("/ELF"));
- }
- catch (DuplicateNameException e) {
- // ignore - will not happen
- }
- return struct;
- }
-
-}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/ElfComment.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/ElfComment.java
new file mode 100644
index 0000000000..94ae737d4d
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/ElfComment.java
@@ -0,0 +1,121 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.elf.info;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import java.io.IOException;
+
+import ghidra.app.util.bin.BinaryReader;
+import ghidra.framework.options.Options;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.data.StringUTF8DataType;
+import ghidra.program.model.listing.Listing;
+import ghidra.program.model.listing.Program;
+import ghidra.program.model.symbol.SourceType;
+import ghidra.program.model.symbol.SymbolTable;
+import ghidra.program.model.util.CodeUnitInsertionException;
+import ghidra.util.Msg;
+import ghidra.util.exception.InvalidInputException;
+
+/**
+ * An Elf section that contains null-terminated strings, typically added by the compiler to
+ * the binary
+ */
+public class ElfComment implements ElfInfoItem {
+
+ public static final String SECTION_NAME = ".comment";
+
+ /**
+ * Reads an ElfComment from the standard ".comment" section in the specified Program.
+ *
+ * @param program Program to read from
+ * @return new instance, or null if not found or data error
+ */
+ public static ElfComment fromProgram(Program program) {
+ ItemWithAddress<ElfComment> wrappedItem = ElfInfoItem.readItemFromSection(program,
+ SECTION_NAME, ElfComment::read);
+ return wrappedItem != null ? wrappedItem.item() : null;
+ }
+
+ /**
+ * Reads a ElfComment from the specified BinaryReader.
+ *
+ * @param br BinaryReader to read from
+ * @param program unused, present to match the signature of {@link ElfInfoItem.ReaderFunc}
+ * @return new instance, or null if data error
+ */
+ public static ElfComment read(BinaryReader br, Program program) {
+ try {
+ List<String> commentStrings = new ArrayList<>();
+ List<Integer> commentStringLengths = new ArrayList<>();
+ while (br.hasNext()) {
+ long start = br.getPointerIndex();
+ String str = br.readNextUtf8String();
+ commentStrings.add(str);
+ commentStringLengths.add((int) (br.getPointerIndex() - start));
+ }
+ return new ElfComment(commentStrings, commentStringLengths);
+ }
+ catch (IOException e) {
+ // fall thru and return null
+ }
+ return null;
+ }
+
+ private final List<String> commentStrings;
+ private final List<Integer> commentStringLengths; // retain original string lengths so we can correctly markup memory
+
+ public ElfComment(List<String> commentStrings, List<Integer> commentStringLengths) {
+ this.commentStrings = commentStrings;
+ this.commentStringLengths = commentStringLengths;
+ }
+
+ public List<String> getCommentStrings() {
+ return commentStrings;
+ }
+
+ @Override
+ public void markupProgram(Program program, Address address) {
+ try {
+ Options progInfo = program.getOptions(Program.PROGRAM_INFO);
+ Listing listing = program.getListing();
+ SymbolTable symTable = program.getSymbolTable();
+
+ for (int commentNum = 0; commentNum < commentStrings.size(); commentNum++) {
+ String commentStr = commentStrings.get(commentNum);
+ Integer strLen = commentStringLengths.get(commentNum);
+
+ progInfo.setString("Elf Comment[%d]".formatted(commentNum), commentStr);
+ symTable.createLabel(address, "ElfComment[%d]".formatted(commentNum),
+ SourceType.IMPORTED);
+ listing.createData(address, StringUTF8DataType.dataType, strLen);
+ address = address.addWrap(strLen); // need to allow wrap so we don't error when hitting end-of-section
+ }
+ }
+ catch (CodeUnitInsertionException | InvalidInputException e) {
+ Msg.error(this, "Failed to markup ElfComment at %s: %s".formatted(address, this));
+ }
+
+ }
+
+ @Override
+ public String toString() {
+ return String.format("ElfComment [commentStrings=%s]", commentStrings);
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/ElfInfoItem.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/ElfInfoItem.java
new file mode 100644
index 0000000000..7de89c3250
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/ElfInfoItem.java
@@ -0,0 +1,91 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.elf.info;
+
+import java.io.IOException;
+
+import ghidra.app.util.bin.*;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.listing.Program;
+import ghidra.program.model.mem.MemoryBlock;
+import ghidra.util.Msg;
+
+/**
+ * Interface and helper functions to read and markup things that have been read from an
+ * Elf program.
+ */
+public interface ElfInfoItem {
+
+ /**
+ * Markup a program's info and memory with this item.
+ *
+ * @param program {@link Program} to markup
+ * @param address {@link Address} of the item in the program
+ */
+ void markupProgram(Program program, Address address);
+
+ public record ItemWithAddress<T> (T item, Address address) {};
+ public interface ReaderFunc<T extends ElfInfoItem> {
+ T read(BinaryReader br, Program program) throws IOException;
+ }
+
+ /**
+ * Helper method to markup a program if it contains the specified item in the specified
+ * memory section.
+ *
+ * @param program {@link Program}
+ * @param sectionName name of memory section that contains the item
+ * @param readFunc {@link ReaderFunc} that will deserialize an instance of the item
+ */
+ public static void markupElfInfoItemSection(Program program, String sectionName,
+ ReaderFunc<ElfInfoItem> readFunc) {
+ ItemWithAddress<ElfInfoItem> wrappedItem =
+ readItemFromSection(program, sectionName, readFunc);
+ if (wrappedItem != null) {
+ wrappedItem.item().markupProgram(program, wrappedItem.address());
+ }
+ }
+
+ /**
+ * Helper method to read an item from a program's memory section.
+ *
+ * @param <T> type of the item that will be read
+ * @param program {@link Program} to read from
+ * @param sectionName name of memory section that contains the item
+ * @param readFunc {@link ReaderFunc} that will deserialize an instance of the item
+ * @return a wrapped instance of the item, or null if the memory section does not exist
+ * or there was an error while reading the item from the section
+ */
+ public static <T extends ElfInfoItem> ItemWithAddress<T> readItemFromSection(Program program,
+ String sectionName, ReaderFunc<T> readFunc) {
+ MemoryBlock memBlock = program.getMemory().getBlock(sectionName);
+ if (memBlock != null) {
+ try (ByteProvider bp =
+ MemoryByteProvider.createMemoryBlockByteProvider(program.getMemory(), memBlock)) {
+ BinaryReader br = new BinaryReader(bp, !program.getMemory().isBigEndian());
+
+ T item = readFunc.read(br, program);
+ return item != null ? new ItemWithAddress<>(item, memBlock.getStart()) : null;
+ }
+ catch (IOException e) {
+ Msg.warn(ElfInfoItem.class,
+ "Unable to read Elf item in section: %s".formatted(sectionName), e);
+ }
+ }
+ return null;
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/ElfInfoProducer.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/ElfInfoProducer.java
new file mode 100644
index 0000000000..250e091eda
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/ElfInfoProducer.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.app.util.bin.format.elf.info;
+
+import java.util.List;
+
+import ghidra.app.util.bin.format.elf.ElfLoadHelper;
+import ghidra.util.classfinder.ClassSearcher;
+import ghidra.util.classfinder.ExtensionPoint;
+import ghidra.util.exception.CancelledException;
+import ghidra.util.task.TaskMonitor;
+
+/**
+ * Something that adds nice-to-have markup and program info to Elf binaries.
+ * <p>
+ * Classes that implement this ExtensionPoint must have names that end with "ElfInfoProducer" for
+ * the class searcher to find them.
+ * <p>
+ * Instances are created for each Elf binary that is being loaded.
+ */
+public interface ElfInfoProducer extends ExtensionPoint {
+
+ /**
+ * Returns a sorted list of new and initialized ElfInfoProducer instances.
+ *
+ * @param elfLoadHelper {@link ElfLoadHelper} with contents of file being loaded
+ * @return List of ElfInfoProducers
+ */
+ public static List<ElfInfoProducer> getElfInfoProducers(ElfLoadHelper elfLoadHelper) {
+ List<ElfInfoProducer> result = ClassSearcher.getInstances(ElfInfoProducer.class);
+ for (ElfInfoProducer eip : result) {
+ eip.init(elfLoadHelper);
+ }
+ return result;
+ }
+
+ /**
+ * Initializes this instance.
+ *
+ * @param elfLoadHelper the Elf binary
+ */
+ void init(ElfLoadHelper elfLoadHelper);
+
+ /**
+ * Called by the Elf loader to give this ElfInfoProducer the opportunity to markup the Elf
+ * binary.
+ *
+ * @param monitor {@link TaskMonitor}
+ */
+ void markupElfInfo(TaskMonitor monitor) throws CancelledException;
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/ElfNote.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/ElfNote.java
new file mode 100644
index 0000000000..712788c728
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/ElfNote.java
@@ -0,0 +1,291 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.elf.info;
+
+import static ghidra.app.util.bin.StructConverter.BYTE;
+import static ghidra.app.util.bin.StructConverter.DWORD;
+
+import java.io.IOException;
+
+import ghidra.app.util.bin.*;
+import ghidra.framework.options.Options;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.data.*;
+import ghidra.program.model.listing.Program;
+import ghidra.program.model.util.CodeUnitInsertionException;
+import ghidra.util.Msg;
+import ghidra.util.NumericUtilities;
+
+/**
+ * ELF note sections have a well-defined format that combines identity information along with a
+ * binary blob that is specific to each type of note.
+ * <p>
+ * Notes are identified by the combination of a name string and vendorType number, and are usually
+ * stored in a ELF section with a specific name.
+ */
+public class ElfNote implements ElfInfoItem {
+ private static final int MAX_SANE_NAME_LEN = 1024;
+ private static final int MAX_SANE_DESC_LEN = 1024 * 1024;
+
+ @FunctionalInterface
+ public interface NoteReaderFunc<T extends ElfNote> {
+ /**
+ * Returns a more specific Note type, typically using the data found in the generic note's
+ * {@link ElfNote#getDescription()} and the supplied Program.
+ *
+ * @param note generic note instance
+ * @param program Program containing the note
+ * @return new note instance
+ * @throws IOException if error reading
+ */
+ T read(ElfNote note, Program program) throws IOException;
+ }
+
+ /**
+ * Reads a generic {@link ElfNote} instance from the supplied BinaryReader.
+ *
+ * @param reader BinaryReader to read from
+ * @return new {@link ElfNote} instance, never null
+ * @throws IOException if bad data or error reading
+ */
+ public static ElfNote read(BinaryReader reader) throws IOException {
+ int nameLen = reader.readNextUnsignedIntExact();
+ int descLen = reader.readNextUnsignedIntExact();
+ int vendorType = reader.readNextInt();
+ if (nameLen > MAX_SANE_NAME_LEN || descLen > MAX_SANE_DESC_LEN) {
+ throw new IOException("Invalid Note lengths: %d, %d".formatted(nameLen, descLen));
+ }
+ String name = reader.readNextAsciiString(nameLen);
+ nameLen += reader.align(4);
+
+ byte[] desc = reader.readNextByteArray(descLen);
+
+ return new ElfNote(nameLen, name, vendorType, desc);
+ }
+
+ /**
+ * A helper method for {@code read()} methods defined in specific Note classes to attempt to
+ * read a specific Note type from a Program.
+ *
+ * @param <T> Note type
+ * @param program {@link Program}
+ * @param sectionName name of the note section
+ * @param readerFunc {@link NoteReaderFunc} that converts a generic note instance into a
+ * specialized note.<br>
+ * Example: <code>(note, programContext) -> new MyNote(....)</code>
+ * @return new Note instance, or null if not present or error reading
+ */
+ protected static <T extends ElfNote> T readFromProgramHelper(Program program,
+ String sectionName, NoteReaderFunc<T> readerFunc) {
+
+ ItemWithAddress<ElfNote> wrappedNote = ElfInfoItem.readItemFromSection(program, sectionName,
+ (br, _unused) -> ElfNote.read(br));
+ if (wrappedNote != null) {
+ try {
+ return readerFunc.read(wrappedNote.item(), program);
+ }
+ catch (IOException e) {
+ // fall thru
+ }
+ }
+ return null;
+ }
+
+ protected final int nameLen;
+ protected final String name;
+ protected final int vendorType;
+ protected final byte[] description;
+
+ protected ElfNote(int nameLen, String name, int vendorType, byte[] description) {
+ this.nameLen = nameLen;
+ this.name = name;
+ this.vendorType = vendorType;
+ this.description = description;
+ }
+
+ protected ElfNote(int nameLen, String name, int vendorType) {
+ this(nameLen, name, vendorType, null);
+ }
+
+ /**
+ * Shortcut test of name == "GNU"
+ *
+ * @return true if name is "GNU"
+ */
+ public boolean isGnu() {
+ return "GNU".equals(name);
+ }
+
+ /**
+ * Returns the name value of this note.
+ *
+ * @return string name
+ */
+ public String getName() {
+ return name;
+ }
+
+ public int getNameLen() {
+ return nameLen;
+ }
+
+ /**
+ * Returns the bytes in the description portion of the note.
+ *
+ * @return byte array
+ */
+ public byte[] getDescription() {
+ return description;
+ }
+
+ public int getDescriptionLen() {
+ return description != null ? description.length : 0;
+ }
+
+ /**
+ * Returns a hex string of the description bytes.
+ *
+ * @return hex string
+ */
+ public String getDescriptionAsHexString() {
+ return NumericUtilities.convertBytesToString(description);
+ }
+
+ /**
+ * Returns a {@link BinaryReader} that reads from this note's description blob.
+ *
+ * @param isLittleEndian flag, see {@link BinaryReader#BinaryReader(ByteProvider, boolean)}
+ * @return new BinaryReader
+ */
+ public BinaryReader getDescriptionReader(boolean isLittleEndian) {
+ ByteArrayProvider bap = new ByteArrayProvider(description);
+ BinaryReader descReader = new BinaryReader(bap, isLittleEndian);
+ return descReader;
+ }
+
+ /**
+ * Returns the vendor type 'enum' value of this note.
+ *
+ * @return vendor type 'enum' value
+ */
+ public int getVendorType() {
+ return vendorType;
+ }
+
+ /**
+ * Returns a string that describes this note's type, used when creating the default
+ * {@link #getProgramInfoKey()} value.
+ * <p>
+ * Specific Note subclasses can override this to return a better string than this default
+ * implementation, or can override the {@link #getProgramInfoKey()} method.
+ *
+ * @return descriptive string
+ */
+ public String getNoteTypeName() {
+ return "%s, %d".formatted(name, vendorType);
+ }
+
+ /**
+ * Returns a string representation of this note's 'value', used when creating the
+ * PROGRAM_INFO entry.
+ * <p>
+ * Specific Note subclasses should override this to return a better string than this default
+ * implementation.
+ *
+ * @return string describing this note's value
+ */
+ public String getNoteValueString() {
+ return getDescriptionAsHexString();
+ }
+
+ /**
+ * Returns a string that is used to build a PROGRAM_INFO entry's key.
+ * <p>
+ * Specific Note subclasses can override this to return a better key string.
+ *
+ * @return key string (avoid using '.' characters as they will be converted to '_'s)
+ */
+ public String getProgramInfoKey() {
+ return "ELF Note[%s]".formatted(getNoteTypeName());
+ }
+
+ /**
+ * Adds a single entry to the Options, built from the {@link #getProgramInfoKey()} value and
+ * {@link #getNoteValueString()} value.
+ *
+ * @param programInfoOptions {@link Options} to add entry to
+ */
+ public void decorateProgramInfo(Options programInfoOptions) {
+ programInfoOptions.setString(getProgramInfoKey().replaceAll("\\.", "_"),
+ getNoteValueString());
+ }
+
+ @Override
+ public void markupProgram(Program program, Address address) {
+ decorateProgramInfo(program.getOptions(Program.PROGRAM_INFO));
+
+ StructureDataType dt = toStructure(program.getDataTypeManager());
+ if (dt != null) {
+ try {
+ program.getListing().createData(address, dt);
+ }
+ catch (CodeUnitInsertionException e) {
+ Msg.error(this, "Failed to markup Elf Note at %s: %s".formatted(address, this), e);
+ }
+ }
+ }
+
+ /**
+ * Returns a Structure datatype that matches the format of this ElfNote, or null if this
+ * ElfNote shouldn't be represented/marked up.
+ *
+ * @param dtm {@link DataTypeManager} that will receive the structure
+ * @return StructureDataType that specifies the layout of the ElfNote, or null
+ */
+ public StructureDataType toStructure(DataTypeManager dtm) {
+ return createNoteStructure(StandardElfInfoProducer.ELF_CATEGORYPATH, "ElfNote", true,
+ getNameLen(), getDescriptionLen(), dtm);
+ }
+
+ @Override
+ public String toString() {
+ return "ELF Note[%s]: %s".formatted(getNoteTypeName(), getNoteValueString());
+ }
+
+ protected static StructureDataType createNoteStructure(CategoryPath cp, String structName,
+ boolean templatedName, int noteNameLen, int noteDescLen, DataTypeManager dtm) {
+ if (templatedName) {
+ structName = "%s_%d_%d".formatted(structName, noteNameLen, noteDescLen);
+ }
+ if (cp == null) {
+ cp = StandardElfInfoProducer.ELF_CATEGORYPATH;
+ }
+ StructureDataType result = new StructureDataType(cp, structName, 0, dtm);
+ result.add(DWORD, "namesz", "Length of name field");
+ result.add(DWORD, "descsz", "Length of description field");
+ result.add(DWORD, "type", "Vendor specific type");
+ if (noteNameLen > 0) {
+ result.add(StringDataType.dataType, noteNameLen, "name", "Vendor name");
+ }
+ if (noteDescLen > 0) {
+ result.add(new ArrayDataType(BYTE, noteDescLen, BYTE.getLength(), dtm), "description",
+ "Blob value");
+ }
+
+ return result;
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/GnuDebugLink.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/GnuDebugLink.java
new file mode 100644
index 0000000000..9e58c4e390
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/GnuDebugLink.java
@@ -0,0 +1,129 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.elf.info;
+
+import static ghidra.app.util.bin.StructConverter.DWORD;
+
+import java.io.IOException;
+
+import ghidra.app.util.bin.BinaryReader;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.data.*;
+import ghidra.program.model.listing.Program;
+import ghidra.program.model.util.CodeUnitInsertionException;
+import ghidra.util.Msg;
+
+/**
+ * An ELF section (almost like a {@link ElfNote}) that contains information about an external
+ * DWARF debug file.
+ * <p>
+ * External DWARF debug files can also be specified with a {@link NoteGnuBuildId}.
+ */
+public class GnuDebugLink implements ElfInfoItem {
+ public static final String SECTION_NAME = ".gnu_debuglink";
+
+ /**
+ * Reads a GnuDebugLink from the standard ".gnu_debuglink" section in the specified Program.
+ *
+ * @param program Program to read from
+ * @return new instance, or null if not found or data error
+ */
+ public static GnuDebugLink fromProgram(Program program) {
+ ItemWithAddress<GnuDebugLink> wrappedItem = ElfInfoItem.readItemFromSection(program,
+ SECTION_NAME, GnuDebugLink::read);
+ return wrappedItem != null ? wrappedItem.item() : null;
+ }
+
+ /**
+ * Reads a GnuDebugLink from the specified BinaryReader.
+ *
+ * @param br BinaryReader to read from
+ * @param program unused, present to match the signature of {@link ElfInfoItem.ReaderFunc}
+ * @return new instance, or null if data error
+ */
+ public static GnuDebugLink read(BinaryReader br, Program program) {
+ try {
+ long filenameStart = br.getPointerIndex();
+ String filename = br.readNextAsciiString();
+ br.align(4);
+ int filenameLen = (int) (br.getPointerIndex() - filenameStart);
+ int crc = br.readNextInt();
+ return new GnuDebugLink(filenameLen, filename, crc);
+ }
+ catch (IOException e) {
+ // fall thru and return null
+ }
+ return null;
+ }
+
+ private final int filenameLen;
+ private final String filename;
+ private final int crc;
+
+ public GnuDebugLink(int filenameLen, String filename, int crc) {
+ this.filenameLen = filenameLen;
+ this.filename = filename;
+ this.crc = crc;
+ }
+
+ public String getFilename() {
+ return filename;
+ }
+
+ public int getFilenameLen() {
+ return filenameLen;
+ }
+
+ public int getCrc() {
+ return crc;
+ }
+
+ @Override
+ public void markupProgram(Program program, Address address) {
+ program.getOptions(Program.PROGRAM_INFO).setString("GNU DebugLink", getFilename());
+
+ try {
+ StructureDataType struct = toStructure(program.getDataTypeManager());
+ if (struct != null) {
+ program.getListing().createData(address, struct);
+ }
+ }
+ catch (CodeUnitInsertionException e) {
+ Msg.error(this, "Failed to markup GnuDebugLink at %s: %s".formatted(address, this));
+ }
+
+ }
+
+ private StructureDataType toStructure(DataTypeManager dtm) {
+ if (filenameLen <= 0) {
+ return null;
+ }
+
+ StructureDataType result =
+ new StructureDataType(StandardElfInfoProducer.ELF_CATEGORYPATH,
+ "GnuDebugLink_%d".formatted(filenameLen), 0, dtm);
+ result.add(StringDataType.dataType, filenameLen, "filename", null);
+ result.add(DWORD, "crc", null);
+
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("GnuDebugLink [filename=%s, crc=%s]", filename, crc);
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/NoteAbiTag.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/NoteAbiTag.java
new file mode 100644
index 0000000000..a7899f9ebe
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/NoteAbiTag.java
@@ -0,0 +1,114 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.elf.info;
+
+import static ghidra.app.util.bin.StructConverter.DWORD;
+
+import java.io.IOException;
+
+import ghidra.app.util.bin.BinaryReader;
+import ghidra.program.model.data.*;
+import ghidra.program.model.listing.Program;
+
+/**
+ * An ELF note that specifies the minimum kernel ABI required by this binary
+ */
+public class NoteAbiTag extends ElfNote {
+ private static final int MIN_ABI_TAB_LEN = 0x10;
+ public static final String SECTION_NAME = ".note.ABI-tag";
+
+ /**
+ * Deserializes a NoteAbiTag from an already read generic Note.
+ *
+ * @param note generic Note
+ * @param program context
+ * @return new NoteAbiTag instance, never null
+ * @throws IOException if data error
+ */
+ public static NoteAbiTag read(ElfNote note, Program program) throws IOException {
+ byte[] desc = note.getDescription();
+ if (!note.isGnu() || desc.length < MIN_ABI_TAB_LEN) {
+ throw new IOException(
+ "Invalid .note.ABI-tag values: %s, %d".formatted(note.getName(), desc.length));
+ }
+
+ BinaryReader descReader = note.getDescriptionReader(!program.getMemory().isBigEndian());
+ int abiType = descReader.readNextInt();
+ int[] requiredKernelVersion = descReader.readNextIntArray(3);
+
+ return new NoteAbiTag(note.getNameLen(), note.getName(), note.getVendorType(), abiType,
+ requiredKernelVersion);
+ }
+
+ /**
+ * Reads a NoteAbiTag from the standard ".note.ABI-tag" section in the specified Program.
+ *
+ * @param program Program to read from
+ * @return new instance, or null if not found or data error
+ */
+ public static NoteAbiTag fromProgram(Program program) {
+ return ElfNote.readFromProgramHelper(program, SECTION_NAME, NoteAbiTag::read);
+ }
+
+ private final int abiType; // 0 == linux
+ private final int[] requiredKernelVersion; // int[3] { A, B, C } == kernel ver A.B.C
+
+ public NoteAbiTag(int nameLen, String name, int vendorType, int abiType,
+ int[] requiredKernelVersion) {
+ super(nameLen, name, vendorType);
+
+ this.abiType = abiType;
+ this.requiredKernelVersion = requiredKernelVersion;
+ }
+
+ public int getAbiType() {
+ return abiType;
+ }
+
+ public String getAbiTypeString() {
+ return switch (abiType) {
+ case 0 -> "Linux";
+ default -> "Unknown(%d)".formatted(abiType);
+ };
+ }
+
+ public String getRequiredKernelVersion() {
+ return "%s %d.%d.%d".formatted(getAbiTypeString(), requiredKernelVersion[0],
+ requiredKernelVersion[1], requiredKernelVersion[2]);
+ }
+
+ @Override
+ public String getNoteValueString() {
+ return getRequiredKernelVersion();
+ }
+
+ @Override
+ public String getNoteTypeName() {
+ return "required kernel ABI";
+ }
+
+ @Override
+ public StructureDataType toStructure(DataTypeManager dtm) {
+ StructureDataType result =
+ createNoteStructure(null, "NoteAbiTag", false, getNameLen(), 0, dtm);
+ result.add(DWORD, "abiType", "0 == Linux");
+ result.add(new ArrayDataType(DWORD, 3, -1, dtm), "requiredKernelVersion",
+ "Major.minor.patch");
+ return result;
+ }
+
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/NoteGnuBuildId.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/NoteGnuBuildId.java
new file mode 100644
index 0000000000..fc6c5f4aa1
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/NoteGnuBuildId.java
@@ -0,0 +1,84 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.elf.info;
+
+import static ghidra.app.util.bin.StructConverter.BYTE;
+
+import java.io.IOException;
+
+import ghidra.program.model.data.*;
+import ghidra.program.model.listing.Program;
+
+/**
+ * An ELF note that specifies the build-id hash of the containing program.
+ * <p>
+ * The build-id hash is useful to find an external debug file.
+ */
+public class NoteGnuBuildId extends ElfNote {
+ private static final int SHA1_DESC_LEN = 20; // 160bit SHA1 == 20 bytes
+ public static final String SECTION_NAME = ".note.gnu.build-id";
+
+ /**
+ * Deserializes a NoteGnuBuildId from an already read generic Note.
+ *
+ * @param note generic Note
+ * @param program context
+ * @return new NoteGnuBuildId instance, never null
+ * @throws IOException if data error
+ */
+ public static NoteGnuBuildId read(ElfNote note, Program program) throws IOException {
+ if (!note.isGnu() || note.getDescription().length != SHA1_DESC_LEN) {
+ throw new IOException("Invalid .note.gnu.build-id values: %s, %d"
+ .formatted(note.getName(), note.getDescription().length));
+ }
+ return new NoteGnuBuildId(note.getNameLen(), note.getName(), note.getVendorType(),
+ note.getDescription());
+ }
+
+ /**
+ * Reads a NoteGnuBuildId from the standard ".note.gnu.build-id" section in the
+ * specified Program.
+ *
+ * @param program Program to read from
+ * @return new instance, or null if not found or data error
+ */
+ public static NoteGnuBuildId fromProgram(Program program) {
+ return ElfNote.readFromProgramHelper(program, SECTION_NAME, NoteGnuBuildId::read);
+ }
+
+ protected NoteGnuBuildId(int nameLen, String name, int vendorType, byte[] description) {
+ super(nameLen, name, vendorType, description);
+ }
+
+ public byte[] getHash() {
+ return getDescription();
+ }
+
+ @Override
+ public String getNoteTypeName() {
+ return "GNU BuildId";
+ }
+
+ @Override
+ public StructureDataType toStructure(DataTypeManager dtm) {
+ StructureDataType result =
+ createNoteStructure(null, "GnuBuildId", false, getNameLen(), 0, dtm);
+ result.add(new ArrayDataType(BYTE, getDescriptionLen(), -1, dtm), "hash", "SHA1");
+
+ return result;
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/NoteGnuProperty.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/NoteGnuProperty.java
new file mode 100644
index 0000000000..f677cc0337
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/NoteGnuProperty.java
@@ -0,0 +1,218 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.elf.info;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import java.io.IOException;
+
+import ghidra.app.util.bin.BinaryReader;
+import ghidra.app.util.bin.StructConverter;
+import ghidra.framework.options.Options;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.data.*;
+import ghidra.program.model.listing.*;
+import ghidra.program.model.util.CodeUnitInsertionException;
+import ghidra.util.Msg;
+import ghidra.util.NumericUtilities;
+
+/**
+ * An ELF note that contains a list of enumerated "properties".
+ * <p>
+ * Currently known property types are stack_size and no_copy_on_protected (flag).
+ * <p>
+ * <pre>
+ * array of Elf_Prop {
+ * word pr_type;
+ * word pr_datasz;
+ * byte pr_data[pr_datasz];
+ * byte padding[]
+ * }
+ * </pre>
+ */
+public class NoteGnuProperty extends ElfNote {
+ public static final String SECTION_NAME = ".note.gnu.property";
+
+ // Elf_Prop pr_types
+ private static final int GNU_PROPERTY_STACK_SIZE = 1;
+ private static final int GNU_PROPERTY_NO_COPY_ON_PROTECTED = 2;
+
+ // properties specific to processor options
+ private static final int GNU_PROPERTY_LOPROC = 0xc0000000;
+ private static final int GNU_PROPERTY_HIPROC = 0xdfffffff;
+
+ // properties specific to application / user defined
+ private static final int GNU_PROPERTY_LOUSER = 0xe0000000;
+ private static final int GNU_PROPERTY_HIUSER = 0xffffffff;
+
+ /**
+ * Parses a NoteGnuProperty instance from the specified generic note.
+ *
+ * @param note generic note that contains the data from a .note.gnu.property section
+ * @param program Program that contains the note section
+ * @return {@link NoteGnuProperty} instance
+ * @throws IOException if IO error parsing data
+ */
+ public static NoteGnuProperty read(ElfNote note, Program program) throws IOException {
+ List<NotePropertyElement> elements = new ArrayList<>();
+ BinaryReader descReader = note.getDescriptionReader(!program.getMemory().isBigEndian());
+ while (descReader.hasNext()) {
+ NotePropertyElement element =
+ readNextNotePropertyElement(descReader, program.getDefaultPointerSize());
+ elements.add(element);
+ }
+
+ return new NoteGnuProperty(note.getNameLen(), note.getName(), note.getVendorType(),
+ elements);
+ }
+
+ /**
+ * Contains the information of an individual note property.
+ */
+ public record NotePropertyElement(int type, String typeName, String value, int length) {}
+
+ private static NotePropertyElement readNextNotePropertyElement(BinaryReader reader, int intSize)
+ throws IOException {
+ int prType = reader.readNextInt();
+ int prDatasz = reader.readNextUnsignedIntExact();
+ long dataStart = reader.getPointerIndex();
+
+ String typeName;
+ String value = "???";
+ switch (prType) {
+ case GNU_PROPERTY_STACK_SIZE: {
+ typeName = "stack_size";
+ long tmp = reader.readNextUnsignedValue(intSize);
+ value = "%d (0x%08x)".formatted(tmp, tmp);
+ break;
+ }
+ case GNU_PROPERTY_NO_COPY_ON_PROTECTED:
+ typeName = "no_copy_on_protected";
+ value = "set";
+ break;
+ default:
+ if (GNU_PROPERTY_LOPROC <= prType && prType <= GNU_PROPERTY_HIPROC) {
+ typeName = "processor opt 0x%08x".formatted(prType);
+ }
+ else if (GNU_PROPERTY_LOUSER <= prType && prType <= GNU_PROPERTY_HIUSER) {
+ typeName = "app opt 0x%08x".formatted(prType);
+ }
+ else {
+ typeName = "unknown opt 0x%08x".formatted(prType);
+ }
+ if (prDatasz > 0) {
+ byte[] valueBytes = reader.readNextByteArray(prDatasz);
+ value = NumericUtilities.convertBytesToString(valueBytes, " ");
+ }
+ }
+ // TODO: the logic for getting to next element isn't well tested and the docs are not very
+ // clear.
+ reader.setPointerIndex(dataStart + prDatasz);
+ reader.align(intSize);
+
+ return new NotePropertyElement(prType, typeName, value, prDatasz);
+ }
+
+ /**
+ * Returns a NoteGnuProperty instance containing the information found in the program's
+ * ".note.gnu.property" section, or null if there is no section.
+ *
+ * @param program {@link Program} to read from
+ * @return {@link NoteGnuProperty}
+ */
+ public static NoteGnuProperty fromProgram(Program program) {
+ return ElfNote.readFromProgramHelper(program, SECTION_NAME, NoteGnuProperty::read);
+ }
+
+ private final List<NotePropertyElement> elements;
+
+ /**
+ * Creates a instance using the specified values.
+ *
+ * @param name name of property
+ * @param vendorType vendor type of property
+ * @param elements list of NotePropertyElements
+ */
+ public NoteGnuProperty(int nameLen, String name, int vendorType,
+ List<NotePropertyElement> elements) {
+ super(nameLen, name, vendorType);
+
+ this.elements = elements;
+ }
+
+ @Override
+ public String getNoteTypeName() {
+ return SECTION_NAME;
+ }
+
+ @Override
+ public void decorateProgramInfo(Options programInfoOptions) {
+ for (NotePropertyElement element : elements) {
+ // TODO: de-dup keys that collide?
+ String key =
+ "ELF GNU Program Prop[%s]".formatted(element.typeName).replaceAll("\\.", "_");
+ programInfoOptions.setString(key, element.value);
+ }
+ }
+
+ @Override
+ public void markupProgram(Program program, Address address) {
+ super.markupProgram(program, address);
+
+ ProgramBasedDataTypeManager dtm = program.getDataTypeManager();
+ Listing listing = program.getListing();
+
+ try {
+ StructureDataType struct =
+ createNoteStructure(null, "NoteGnuProperty_%d".formatted(getNameLen()), false,
+ getNameLen(), 0, program.getDataTypeManager());
+ Data propData = listing.createData(address, struct);
+ address = propData.getMaxAddress().next();
+
+ for (NotePropertyElement element : elements) {
+ DataType elementDT = getElementDataType(dtm, element);
+ Data elementData = listing.createData(address, elementDT);
+ listing.setComment(address, CodeUnit.EOL_COMMENT,
+ element.typeName() + "=" + element.value());
+ address = elementData.getMaxAddress().next();
+ }
+ }
+ catch (CodeUnitInsertionException e) {
+ Msg.error(this, "Failed to markup NoteGnuProperty at %s, %s".formatted(address, this));
+ }
+
+ }
+
+ private DataType getElementDataType(DataTypeManager dtm, NotePropertyElement element) {
+ StructureDataType result =
+ new StructureDataType("NoteGnuPropertyElement_%d".formatted(element.length()), 0, dtm);
+
+ result.add(StructConverter.DWORD, "prType", null);
+ result.add(StructConverter.DWORD, "prDatasz", null);
+ result.add(new ArrayDataType(StructConverter.BYTE, element.length, -1, dtm), "data", null);
+
+ return result;
+ }
+
+ @Override
+ public StructureDataType toStructure(DataTypeManager dtm) {
+ // defer creating data types until our custom markupProgram method so it can create
+ // more than 1 element.
+ return null;
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/StandardElfInfoProducer.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/StandardElfInfoProducer.java
new file mode 100644
index 0000000000..ed34fedd9f
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/StandardElfInfoProducer.java
@@ -0,0 +1,129 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.elf.info;
+
+import java.util.Map;
+import java.util.Map.Entry;
+
+import java.io.IOException;
+
+import ghidra.app.util.bin.*;
+import ghidra.app.util.bin.format.elf.*;
+import ghidra.app.util.bin.format.elf.info.ElfInfoItem.ReaderFunc;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.data.CategoryPath;
+import ghidra.program.model.data.StructureDataType;
+import ghidra.program.model.listing.CodeUnit;
+import ghidra.program.model.listing.Program;
+import ghidra.program.model.mem.Memory;
+import ghidra.program.model.mem.MemoryBlock;
+import ghidra.program.model.util.CodeUnitInsertionException;
+import ghidra.util.Msg;
+import ghidra.util.classfinder.ExtensionPointProperties;
+import ghidra.util.exception.CancelledException;
+import ghidra.util.task.TaskMonitor;
+
+/**
+ * Handles marking up and program info for basic ELF note (and note-like) sections.
+ * <ul>
+ * <li>NoteAbiTag
+ * <li>NoteGnuBuildId
+ * <li>NoteGnuProperty
+ * <li>GnuDebugLink (not a note)
+ * <li>ElfComment (not a note)
+ * </ul>
+ * <p>
+ * Runs after other ElfInfoProducers that have a normal priority.
+ */
+@ExtensionPointProperties(priority = -1000)
+public class StandardElfInfoProducer implements ElfInfoProducer {
+
+ public static final CategoryPath ELF_CATEGORYPATH = new CategoryPath("/ELF");
+
+ private static final Map<String, ReaderFunc<ElfInfoItem>> STANDARD_READERS = Map.of(
+ GnuDebugLink.SECTION_NAME, GnuDebugLink::read,
+ NoteAbiTag.SECTION_NAME, (br, prg) -> NoteAbiTag.read(ElfNote.read(br), prg),
+ NoteGnuBuildId.SECTION_NAME, (br, prg) -> NoteGnuBuildId.read(ElfNote.read(br), prg),
+ NoteGnuProperty.SECTION_NAME, (br, prg) -> NoteGnuProperty.read(ElfNote.read(br), prg),
+ ElfComment.SECTION_NAME, ElfComment::read);
+
+ private ElfLoadHelper elfLoadHelper;
+
+ @Override
+ public void init(ElfLoadHelper elfLoadHelper) {
+ this.elfLoadHelper = elfLoadHelper;
+ }
+
+ @Override
+ public void markupElfInfo(TaskMonitor monitor) throws CancelledException {
+ Program program = elfLoadHelper.getProgram();
+
+ for (Entry<String, ReaderFunc<ElfInfoItem>> noteEntry : STANDARD_READERS.entrySet()) {
+ monitor.checkCanceled();
+
+ String sectionName = noteEntry.getKey();
+ ReaderFunc<ElfInfoItem> readFunc = noteEntry.getValue();
+
+ ElfInfoItem.markupElfInfoItemSection(program, sectionName, readFunc);
+ }
+ markupPTNOTESections(monitor);
+ }
+
+ private void markupPTNOTESections(TaskMonitor monitor) throws CancelledException {
+ Program program = elfLoadHelper.getProgram();
+ Memory memory = program.getMemory();
+ for (ElfProgramHeader elfProgramHeader : elfLoadHelper.getElfHeader()
+ .getProgramHeaders(ElfProgramHeaderConstants.PT_NOTE)) {
+ monitor.checkCanceled();
+
+ Address addr = elfLoadHelper.findLoadAddress(elfProgramHeader, 0);
+ MemoryBlock memBlock = memory.getBlock(addr);
+ if (memBlock == null) {
+ continue;
+ }
+ try (ByteProvider bp =
+ MemoryByteProvider.createMemoryBlockByteProvider(program.getMemory(), memBlock)) {
+ BinaryReader br = new BinaryReader(bp, !program.getMemory().isBigEndian());
+ while (br.hasNext()) {
+ monitor.checkCanceled();
+
+ long start = br.getPointerIndex();
+ ElfNote note = br.readNext(ElfNote::read);
+ br.align(4); // fix any notes with non-aligned size payloads
+ long noteLength = br.getPointerIndex() - start;
+
+ try {
+ StructureDataType struct = note.toStructure(program.getDataTypeManager());
+ program.getListing().createData(addr, struct);
+ String comment =
+ "ELF Note \"%s\", %xh".formatted(note.getName(), note.getVendorType());
+ program.getListing().setComment(addr, CodeUnit.EOL_COMMENT, comment);
+ }
+ catch (CodeUnitInsertionException e) {
+ // ignore, continue to next note
+ }
+
+ addr = addr.addWrap(noteLength);
+ }
+ }
+ catch (IOException e) {
+ Msg.warn(this, "Failed to read ELF Note at %s".formatted(addr), e);
+ }
+
+ }
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoBuildInfo.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoBuildInfo.java
new file mode 100644
index 0000000000..29e26dd6ae
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoBuildInfo.java
@@ -0,0 +1,363 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.golang;
+
+import static ghidra.app.util.bin.StructConverter.ASCII;
+import static ghidra.app.util.bin.StructConverter.BYTE;
+
+import java.util.*;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+
+import ghidra.app.util.bin.BinaryReader;
+import ghidra.app.util.bin.MemoryByteProvider;
+import ghidra.app.util.bin.format.dwarf4.LEB128;
+import ghidra.app.util.bin.format.elf.info.ElfInfoItem;
+import ghidra.framework.options.Options;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.data.*;
+import ghidra.program.model.lang.Endian;
+import ghidra.program.model.listing.Program;
+import ghidra.program.model.util.CodeUnitInsertionException;
+import ghidra.util.Msg;
+import ghidra.util.NumericUtilities;
+
+/**
+ * A program section that contains Go build information strings, namely go module package names,
+ * go module dependencies, and build/compiler flags, as well as the golang version itself.
+ */
+public class GoBuildInfo implements ElfInfoItem {
+
+ public static final String SECTION_NAME = ".go.buildinfo";
+
+ // Defined in golang src/debug/buildinfo/buildinfo.go
+ // NOTE: ISO_8859_1 charset is required to not mangle the \u00ff when converting to bytes
+ private static final byte[] GO_BUILDINF_MAGIC =
+ "\u00ff Go buildinf:".getBytes(StandardCharsets.ISO_8859_1);
+
+ // Defined in golang src/cmd/go/internal/modload/build.go
+ private static final byte[] INFOSTART_SENTINEL =
+ NumericUtilities.convertStringToBytes("3077af0c9274080241e1c107e6d618e6");
+ private static final byte[] INFOEND_SENTINEL =
+ NumericUtilities.convertStringToBytes("f932433186182072008242104116d8f2");
+
+ private static final int FLAG_ENDIAN = (1 << 0);
+ private static final int FLAG_INLINE_STRING = (1 << 1);
+
+
+ /**
+ * Reads a GoBuildInfo ".go.buildinfo" section from the specified Program, if present.
+ *
+ * @param program {@link Program} that contains the ".go.buildinfo" section
+ * @return new {@link GoBuildInfo} section, if present, null if missing or error
+ */
+ public static GoBuildInfo fromProgram(Program program) {
+ ItemWithAddress<GoBuildInfo> wrappedItem =
+ ElfInfoItem.readItemFromSection(program, SECTION_NAME, GoBuildInfo::read);
+ return wrappedItem != null ? wrappedItem.item() : null;
+ }
+
+ /**
+ * Reads a GoBuildInfo ".go.buildinfo" section from the specified stream.
+ *
+ * @param reader BinaryReader that contains the ".go.buildinfo" section
+ * @param program Program that contains the ".go.buildinfo" section
+ * @return new {@link GoBuildInfo} instance, never null
+ * @throws IOException if error reading or bad data
+ */
+ public static GoBuildInfo read(BinaryReader reader, Program program) throws IOException {
+ byte[] magicBytes = reader.readNextByteArray(GO_BUILDINF_MAGIC.length /* 14 */);
+ if (!Arrays.equals(magicBytes, GO_BUILDINF_MAGIC)) {
+ throw new IOException("Missing GoBuildInfo magic");
+ }
+ int pointerSize = reader.readNextUnsignedByte();
+ int flags = reader.readNextUnsignedByte();
+ Endian endian = (flags & FLAG_ENDIAN) == 0 ? Endian.LITTLE : Endian.BIG;
+ boolean inlineStr = (flags & FLAG_INLINE_STRING) != 0;
+
+ if (reader.isBigEndian() && endian != Endian.BIG) {
+ throw new IOException("Mixed endian-ness");
+ }
+
+ return readStringInfo(reader, inlineStr, program, pointerSize);
+ }
+
+ private final int pointerSize;
+ private final Endian endian;
+ private final String version; // golang compiler version
+ private final String path;
+ private final GoModuleInfo moduleInfo; // info about the module that contains the main package. version typically will be "(devel)"
+ private final List<GoModuleInfo> dependencies;
+ private final List<GoBuildSettings> buildSettings; // compile/linker flags used during build process
+
+ public GoBuildInfo(int pointerSize, Endian endian, String version, String path,
+ GoModuleInfo moduleInfo, List<GoModuleInfo> dependencies,
+ List<GoBuildSettings> buildSettings) {
+ this.pointerSize = pointerSize;
+ this.endian = endian;
+ this.version = version;
+ this.path = path;
+ this.moduleInfo = moduleInfo;
+ this.dependencies = dependencies;
+ this.buildSettings = buildSettings;
+ }
+
+ public int getPointerSize() {
+ return pointerSize;
+ }
+
+ public Endian getEndian() {
+ return endian;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public GoVer getVerEnum() {
+ return GoVer.parse(version);
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public GoModuleInfo getModuleInfo() {
+ return moduleInfo;
+ }
+
+ public List<GoModuleInfo> getDependencies() {
+ return dependencies;
+ }
+
+ public List<GoBuildSettings> getBuildSettings() {
+ return buildSettings;
+ }
+
+ @Override
+ public void markupProgram(Program program, Address address) {
+ decorateProgramInfo(program.getOptions(Program.PROGRAM_INFO));
+
+ try {
+ StructureDataType struct = toStructure(program.getDataTypeManager());
+ if (struct != null) {
+ program.getListing().createData(address, struct);
+ }
+ }
+ catch (CodeUnitInsertionException e) {
+ Msg.error(this, "Failed to markup GoBuildInfo at %s: %s".formatted(address, this));
+ }
+ }
+
+ public void decorateProgramInfo(Options props) {
+ props.setString("Golang go version", getVersion());
+ props.setString("Golang app path", getPath());
+ if (getModuleInfo() != null) {
+ getModuleInfo()
+ .asKeyValuePairs("Golang main package ")
+ .entrySet()
+ .stream()
+ .forEach(entry -> props.setString(entry.getKey(), entry.getValue()));
+ }
+ int depNum = 0;
+ for (GoModuleInfo dep : getDependencies()) {
+ String key = "Golang dep[%4d]".formatted(depNum++);
+ props.setString(key, dep.getFormattedString());
+ }
+ for (GoBuildSettings buildSetting : getBuildSettings()) {
+ props.setString("Golang build[" + buildSetting.key().replaceAll("\\.", "_") + "]",
+ buildSetting.value());
+ }
+ }
+
+ StructureDataType toStructure(DataTypeManager dtm) {
+ StructureDataType result =
+ new StructureDataType(GolangElfInfoProducer.GO_CATEGORYPATH, "GoBuildInfo", 0, dtm);
+ result.add(new ArrayDataType(ASCII, 14, -1, dtm), "magic", "\\xff Go buildinf:");
+ result.add(BYTE, "ptrSize", null);
+ result.add(BYTE, "flags", null);
+
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("GoBuildInfo [pointerSize=%s, endian=%s, version=%s, path=%s]",
+ pointerSize, endian, version, path);
+ }
+
+ //---------------------------------------------------------------------------------------------
+
+ private static GoBuildInfo readStringInfo(BinaryReader reader, boolean inlineStr,
+ Program program, int ptrSize) throws IOException {
+
+ String moduleString;
+ String versionString;
+
+ if (inlineStr) {
+ reader.setPointerIndex(32 /* static start of inline strings */);
+
+ versionString = reader.readNext(GoBuildInfo::varlenString);
+ byte[] modelStringBytes = reader.readNext(GoBuildInfo::varlenBytes);
+
+ moduleString = extractModuleString(modelStringBytes);
+ }
+ else {
+ reader.setPointerIndex(16 /* static start of 2 string pointers */);
+ long versionStrOffset = reader.readNextUnsignedValue(ptrSize);
+ long moduleStrOffset = reader.readNextUnsignedValue(ptrSize);
+
+ MemoryByteProvider memBP = new MemoryByteProvider(program.getMemory(),
+ program.getImageBase().getAddressSpace());
+ BinaryReader fullReader = new BinaryReader(memBP, reader.isLittleEndian());
+
+ fullReader.setPointerIndex(versionStrOffset);
+ versionString = readGoString(fullReader, ptrSize);
+
+ fullReader.setPointerIndex(moduleStrOffset);
+ byte[] moduleStrBytes = readRawGoString(fullReader, ptrSize);
+ moduleString = extractModuleString(moduleStrBytes);
+ }
+
+ return parseBuildInfo(ptrSize, reader.isBigEndian() ? Endian.BIG : Endian.LITTLE,
+ versionString, moduleString);
+ }
+
+ private static GoBuildInfo parseBuildInfo(int pointerSize, Endian endian, String versionString,
+ String moduleString) throws IOException {
+ String path = null;
+ GoModuleInfo module = null;
+ List<GoModuleInfo> deps = new ArrayList<>();
+ List<GoBuildSettings> buildSettings = new ArrayList<>();
+
+ String[] lines = moduleString.split("\n");
+ for (int lineNum = 0; lineNum < lines.length; lineNum++) {
+ String line = lines[lineNum];
+ String replaceInfo =
+ (lineNum + 1 < lines.length && lines[lineNum + 1].startsWith("=>\t"))
+ ? lines[++lineNum].substring(3)
+ : null;
+
+ if (line.isBlank()) {
+ continue;
+ }
+
+ /*
+ * lines start with key of "path", "mod", "dep", "=>" (replacement info attached
+ * to previous line), and "build"
+ */
+ String[] lineParts = line.split("\t", 2);
+ switch (lineParts[0]) {
+ case "path":
+ path = lineParts[1];
+ break;
+ case "mod": {
+ GoModuleInfo replace = replaceInfo != null
+ ? GoModuleInfo.fromString(replaceInfo, null)
+ : null;
+ module = GoModuleInfo.fromString(lineParts[1], replace);
+ break;
+ }
+ case "dep": {
+ GoModuleInfo dep = GoModuleInfo.fromString(lineParts[1], null);
+ deps.add(dep);
+ break;
+ }
+ case "build":
+ GoBuildSettings build = GoBuildSettings.fromString(lineParts[1]);
+ buildSettings.add(build);
+ break;
+ }
+ }
+
+ if (versionString.startsWith("go")) {
+ versionString = versionString.substring(2); // skip the "go"
+ }
+
+ return new GoBuildInfo(pointerSize, endian, versionString, path, module, deps,
+ buildSettings);
+ }
+
+ private static String extractModuleString(byte[] bytes) throws IOException {
+ int sentLen = INFOSTART_SENTINEL.length; // both are same len
+ if (bytes.length < sentLen * 2) {
+ return "";
+ }
+
+ int sentEndStart = bytes.length - sentLen;
+ if (!Arrays.equals(INFOSTART_SENTINEL, 0, sentLen, bytes, 0, sentLen) ||
+ !Arrays.equals(INFOEND_SENTINEL, 0, sentLen, bytes, sentEndStart, bytes.length)) {
+ throw new IOException("bad sentinel");
+ }
+ return new String(bytes, sentLen, bytes.length - (sentLen * 2), StandardCharsets.UTF_8);
+
+ }
+
+ /**
+ * Reads a pascal-ish string used by go in lower level file format.
+ * <p>
+ * Not to be confused with a real golang string produced when strings are created in
+ * a golang program.
+ *
+ * @param reader BinaryReader
+ * @return string at the current index of the BinaryReader
+ * @throws IOException if error
+ */
+ private static String varlenString(BinaryReader reader) throws IOException {
+ byte[] bytes = varlenBytes(reader);
+ return new String(bytes, StandardCharsets.UTF_8);
+ }
+
+ /**
+ * Reads a variable length byte array.
+ *
+ * @param reader BinaryReader
+ * @return variable length byte array at the current index of the BinaryReader
+ * @throws IOException if error
+ */
+ private static byte[] varlenBytes(BinaryReader reader) throws IOException {
+ int strLen = reader.readNextUnsignedVarIntExact(LEB128::readUnsignedAsLong);
+ byte[] bytes = reader.readNextByteArray(strLen);
+ return bytes;
+ }
+
+ private static String readGoString(BinaryReader reader, int ptrSize) throws IOException {
+ byte[] bytes = readRawGoString(reader, ptrSize);
+ return new String(bytes, StandardCharsets.UTF_8);
+ }
+
+ /**
+ * Low-level reading a golang string structure (without using rtti info).
+ *
+ * @param reader BinaryReader that has access to the program's entire address space
+ * @param ptrSize size of golang pointers
+ * @return bytes of the string
+ * @throws IOException if error reading the bytes
+ */
+ private static byte[] readRawGoString(BinaryReader reader, int ptrSize) throws IOException {
+ // struct { void *; long len }
+ long dataAddr = reader.readNextUnsignedValue(ptrSize);
+ long dataLen = reader.readNextUnsignedValue(ptrSize);
+ if (dataAddr == 0 || dataLen == 0) {
+ return new byte[0];
+ }
+
+ byte[] bytes = reader.readByteArray(dataAddr, (int) dataLen);
+ return bytes;
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoBuildSettings.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoBuildSettings.java
new file mode 100644
index 0000000000..3abf5a8d65
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoBuildSettings.java
@@ -0,0 +1,31 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.golang;
+
+import java.io.IOException;
+
+/**
+ * Key=value element of Golang Build settings
+ */
+public record GoBuildSettings(String key, String value) {
+ public static GoBuildSettings fromString(String s) throws IOException {
+ String[] parts = s.split("=", 2);
+ if (parts.length != 2) {
+ throw new IOException();
+ }
+ return new GoBuildSettings(parts[0], parts[1]);
+ }
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoModuleInfo.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoModuleInfo.java
new file mode 100644
index 0000000000..cdc2f17854
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoModuleInfo.java
@@ -0,0 +1,73 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.golang;
+
+import java.util.*;
+
+import java.io.IOException;
+
+/**
+ * Represents information about a single golang module dependency.
+ */
+public record GoModuleInfo(String path, String version, String sum, GoModuleInfo replace) {
+
+ /**
+ * Parses a GoModuleInfo from a formatted string "path[tab]version[tab]checksum".
+ *
+ * @param s string to parse
+ * @param replace GoModuleInfo that is the replacement for this module
+ * @return new GoModuleInfo instance, never null
+ * @throws IOException if error parsing string
+ */
+ public static GoModuleInfo fromString(String s, GoModuleInfo replace) throws IOException {
+ String[] parts = s.split("\t");
+ if (parts.length != 2 && parts.length != 3) {
+ throw new IOException();
+ }
+ return new GoModuleInfo(parts[0], parts[1], parts.length == 3 ? parts[2] : null, replace);
+ }
+
+ /**
+ * Returns a formatted version of the information in this instance.
+ *
+ * @return formatted string
+ */
+ public String getFormattedString() {
+ return replace == null
+ ? "%s %s %s".formatted(path, version, sum != null ? sum : "")
+ : "%s %s => %s".formatted(path, version, replace.getFormattedString());
+ }
+
+ /**
+ * Returns the values in this object as elements of a map.
+ *
+ * @param prefix String prefix to put in front of each value name
+ * @return map of String &rarr; String
+ */
+ public Map<String, String> asKeyValuePairs(String prefix) {
+ Map<String, String> result = new HashMap<>();
+ result.put(prefix + "path", Objects.requireNonNullElse(path, "-missing-"));
+ result.put(prefix + "version", Objects.requireNonNullElse(version, "-missing-"));
+ if (sum != null) {
+ result.put(prefix + "sum", sum);
+ }
+ if (replace != null) {
+ result.put(prefix + "replace", replace.getFormattedString());
+ }
+ return result;
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoVer.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoVer.java
new file mode 100644
index 0000000000..e1a533b54d
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoVer.java
@@ -0,0 +1,91 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.golang;
+
+/**
+ * Golang version numbers
+ */
+public enum GoVer {
+ UNKNOWN(0, 0),
+ V1_2(1, 2),
+ V1_16(1, 16),
+ V1_17(1, 17),
+ V1_18(1, 18);
+
+ private final int major;
+ private final int minor;
+
+ private GoVer(int major, int minor) {
+ this.major = major;
+ this.minor = minor;
+ }
+
+ /**
+ * Major value
+ *
+ * @return major
+ */
+ public int getMajor() {
+ return major;
+ }
+
+ /**
+ * Minor value
+ *
+ * @return minor
+ */
+ public int getMinor() {
+ return minor;
+ }
+
+ /**
+ * Compares this version to the specified other version and returns true if this version
+ * is greater than or equal to the other version.
+ *
+ * @param otherVersion version info to compare
+ * @return true if this version is gte other version
+ */
+ public boolean isAtLeast(GoVer otherVersion) {
+ return this.ordinal() >= otherVersion.ordinal();
+ }
+
+ /**
+ * Parses a version string ("1.2") and returns the matching GoVer enum instance, or
+ * UNKNOWN if no matching version or bad data.
+ *
+ * @param s string to parse
+ * @return GoVer enum instance, or UNKNOWN
+ */
+ public static GoVer parse(String s) {
+ String[] parts = s.split("\\.");
+ if (parts.length < 2) {
+ return UNKNOWN;
+ }
+ try {
+ int major = Integer.parseInt(parts[0]);
+ int minor = Integer.parseInt(parts[1]);
+ for (GoVer ver : values()) {
+ if (ver.major == major && ver.minor == minor) {
+ return ver;
+ }
+ }
+ }
+ catch (NumberFormatException e) {
+ return UNKNOWN;
+ }
+ return UNKNOWN;
+ }
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GolangElfInfoProducer.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GolangElfInfoProducer.java
new file mode 100644
index 0000000000..a525b3f3a8
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GolangElfInfoProducer.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.app.util.bin.format.golang;
+
+import java.util.Map;
+import java.util.Map.Entry;
+
+import ghidra.app.util.bin.format.elf.ElfLoadHelper;
+import ghidra.app.util.bin.format.elf.info.ElfInfoItem;
+import ghidra.app.util.bin.format.elf.info.ElfInfoItem.ReaderFunc;
+import ghidra.app.util.bin.format.elf.info.ElfInfoProducer;
+import ghidra.program.model.data.CategoryPath;
+import ghidra.program.model.listing.Program;
+import ghidra.util.exception.CancelledException;
+import ghidra.util.task.TaskMonitor;
+
+/**
+ * Handles marking up and program info for Golang binaries.
+ * <p>
+ * <ul>
+ * <li>NoteGoBuildId
+ * <li>GoBuildInfo
+ * <ul>
+ * <li>Go version
+ * <li>App path, main package
+ * <li>Module dependency list
+ * <li>Build settings / flags
+ * </ul>
+ * </ul>
+ */
+public class GolangElfInfoProducer implements ElfInfoProducer {
+ public static final CategoryPath GO_CATEGORYPATH = new CategoryPath("/golang");
+
+ private static final Map<String, ReaderFunc<ElfInfoItem>> GOLANGINFO_READERS = Map.of(
+ GoBuildInfo.SECTION_NAME, GoBuildInfo::read,
+ NoteGoBuildId.SECTION_NAME, NoteGoBuildId::read);
+
+ private ElfLoadHelper elfLoadHelper;
+
+ @Override
+ public void init(ElfLoadHelper elfLoadHelper) {
+ this.elfLoadHelper = elfLoadHelper;
+ }
+
+ @Override
+ public void markupElfInfo(TaskMonitor monitor) throws CancelledException {
+ Program program = elfLoadHelper.getProgram();
+
+ for (Entry<String, ReaderFunc<ElfInfoItem>> itemEntry : GOLANGINFO_READERS.entrySet()) {
+ monitor.checkCanceled();
+
+ String sectionName = itemEntry.getKey();
+ ReaderFunc<ElfInfoItem> readFunc = itemEntry.getValue();
+
+ ElfInfoItem.markupElfInfoItemSection(program, sectionName, readFunc);
+ }
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/NoteGoBuildId.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/NoteGoBuildId.java
new file mode 100644
index 0000000000..7611bb82a0
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/NoteGoBuildId.java
@@ -0,0 +1,88 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.bin.format.golang;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+
+import ghidra.app.util.bin.BinaryReader;
+import ghidra.app.util.bin.format.elf.info.ElfInfoItem;
+import ghidra.app.util.bin.format.elf.info.ElfNote;
+import ghidra.program.model.data.*;
+import ghidra.program.model.listing.Program;
+
+/**
+ * An ELF note that specifies the golang build-id.
+ */
+public class NoteGoBuildId extends ElfNote {
+ public static final String SECTION_NAME = ".note.go.buildid";
+
+ /**
+ * Reads a NoteGoBuildId from the specified BinaryReader, matching the signature of
+ * {@link ElfInfoItem.ReaderFunc}.
+ *
+ * @param br BinaryReader
+ * @param unusedProgram context (unused but needed to match signature)
+ * @return new NoteGoBuildId instance, never null
+ * @throws IOException if data error
+ */
+ public static NoteGoBuildId read(BinaryReader br, Program unusedProgram) throws IOException {
+ ElfNote note = ElfNote.read(br);
+ if (!"Go".equals(note.getName())) {
+ throw new IOException("Invalid note name: %s".formatted(note.getName()));
+ }
+ return new NoteGoBuildId(note.getNameLen(), note.getName(), note.getVendorType(),
+ note.getDescription());
+ }
+
+ public NoteGoBuildId(int nameLen, String name, int vendorType, byte[] description) {
+ super(nameLen, name, vendorType, description);
+ }
+
+ /**
+ * Returns the go buildid value
+ *
+ * @return go buildid value
+ */
+ public String getBuildId() {
+ return new String(getDescription(), StandardCharsets.UTF_8);
+ }
+
+ @Override
+ public String getNoteTypeName() {
+ return SECTION_NAME;
+ }
+
+ @Override
+ public String getProgramInfoKey() {
+ return "Golang BuildId";
+ }
+
+ @Override
+ public String getNoteValueString() {
+ return getBuildId();
+ }
+
+ @Override
+ public StructureDataType toStructure(DataTypeManager dtm) {
+ StructureDataType struct =
+ ElfNote.createNoteStructure(GolangElfInfoProducer.GO_CATEGORYPATH,
+ "NoteGoBuildId_%d".formatted(description.length), false, nameLen, 0, dtm);
+ struct.add(StringUTF8DataType.dataType, description.length, "BuildId", null);
+ return struct;
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.java
index 7d15af6b79..0caeb9613b 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.java
@@ -15,11 +15,12 @@
*/
package ghidra.app.util.opinion;
+import java.util.*;
+
import java.io.*;
import java.math.BigInteger;
import java.nio.file.AccessMode;
import java.text.NumberFormat;
-import java.util.*;
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
import org.apache.commons.lang3.StringUtils;
@@ -31,6 +32,7 @@ import ghidra.app.util.bin.format.MemoryLoadable;
import ghidra.app.util.bin.format.elf.*;
import ghidra.app.util.bin.format.elf.ElfDynamicType.ElfDynamicValueType;
import ghidra.app.util.bin.format.elf.extend.ElfLoadAdapter;
+import ghidra.app.util.bin.format.elf.info.ElfInfoProducer;
import ghidra.app.util.bin.format.elf.relocation.*;
import ghidra.app.util.importer.MessageLog;
import ghidra.framework.options.Options;
@@ -182,12 +184,12 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
markupHashTable(monitor);
markupGnuHashTable(monitor);
markupGnuXHashTable(monitor);
- markupGnuBuildId(monitor);
- markupGnuDebugLink(monitor);
processGNU(monitor);
adjustReadOnlyMemoryRegions(monitor);
+ markupElfInfoProducers(monitor);
+
success = true;
}
finally {
@@ -2277,35 +2279,12 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
// return new AddressRangeImpl(alignedAddress, freeRange.getMaxAddress());
// }
- private void markupGnuBuildId(TaskMonitor monitor) {
-
- ElfSectionHeader sh = elf.getSection(".note.gnu.build-id");
- Address addr = findLoadAddress(sh, 0);
- if (addr == null) {
- return;
- }
- try {
- listing.createData(addr,
- new GnuBuildIdSection(program.getDataTypeManager(), sh.getSize()));
- }
- catch (Exception e) {
- log("Failed to properly markup Gnu Build-Id at " + addr + ": " + getMessage(e));
- }
- }
-
- private void markupGnuDebugLink(TaskMonitor monitor) {
+ private void markupElfInfoProducers(TaskMonitor monitor) throws CancelledException {
+ List<ElfInfoProducer> elfInfoProducers = ElfInfoProducer.getElfInfoProducers(this);
+ for (ElfInfoProducer elfInfoProducer : elfInfoProducers) {
+ monitor.checkCanceled();
- ElfSectionHeader sh = elf.getSection(".gnu_debuglink");
- Address addr = findLoadAddress(sh, 0);
- if (addr == null) {
- return;
- }
- try {
- listing.createData(addr,
- new GnuDebugLinkSection(program.getDataTypeManager(), sh.getSize()));
- }
- catch (Exception e) {
- log("Failed to properly markup Gnu DebugLink at " + addr + ": " + getMessage(e));
+ elfInfoProducer.markupElfInfo(monitor);
}
}