Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-7435 more work on golang struct alignment issues

dev7473688f0f136b7b99
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoRegisterInfo.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoRegisterInfo.java
index 8bec883ed6..ad92001aa4 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoRegisterInfo.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/GoRegisterInfo.java
@@ -19,6 +19,7 @@ import java.util.ArrayList;
import java.util.List;
import ghidra.app.util.bin.format.dwarf.DWARFUtil;
+import ghidra.app.util.bin.format.golang.rtti.GoRttiMapper;
import ghidra.program.model.data.*;
import ghidra.program.model.data.Enum;
import ghidra.program.model.lang.Register;
@@ -177,7 +178,7 @@ public class GoRegisterInfo {
? struct.getExplicitMinimumAlignment()
: 1;
for (DataTypeComponent dtc : struct.getDefinedComponents()) {
- align = Math.max(align, isAtomicAlign64(dtc.getDataType())
+ align = Math.max(align, GoRttiMapper.isAtomicAlign64(dtc.getDataType())
? 8
: getAlignmentForType(dtc.getDataType()));
}
@@ -186,16 +187,6 @@ public class GoRegisterInfo {
return maxAlign;
}
- private static boolean isAtomicAlign64(DataType dt) {
- // as cmd/compile, an atomic.align64 field forces 8-byte alignment on all archs
- return switch (dt.getName()) {
- case "sync/atomic.align64", "internal/runtime/atomic.align64",
- "runtime/internal/atomic.align64" ->
- true;
- default -> false;
- };
- }
-
static boolean isIntType(DataType dt) {
return dt instanceof AbstractIntegerDataType || dt instanceof WideCharDataType ||
dt instanceof WideChar16DataType || dt instanceof WideChar32DataType ||
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/rtti/GoApiSnapshot.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/rtti/GoApiSnapshot.java
index 62f6c97f57..85338edb75 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/rtti/GoApiSnapshot.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/rtti/GoApiSnapshot.java
@@ -242,8 +242,8 @@ public class GoApiSnapshot {
public static final GoApiSnapshot EMPTY = new GoApiSnapshot(GoVer.INVALID, Map.of());
public static class GoNameTypePair {
- String Name;
- String DataType;
+ public String Name;
+ public String DataType;
@Override
public String toString() {
@@ -368,8 +368,8 @@ public class GoApiSnapshot {
}
public static class GoStructDef extends GoTypeDef {
- List<GoNameTypePair> Fields;
- List<String> TypeParams;
+ public List<GoNameTypePair> Fields;
+ public List<String> TypeParams;
@Override
public void fixupAfterDeserialization() {
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/rtti/GoRttiMapper.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/rtti/GoRttiMapper.java
index a33ad837a3..fc5bdd1784 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/rtti/GoRttiMapper.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/rtti/GoRttiMapper.java
@@ -283,6 +283,32 @@ public class GoRttiMapper extends DataTypeMapper implements DataTypeMapperContex
return zerobaseSym != null ? zerobaseSym.getAddress() : null;
}
+ /**
+ * {@return true if the DataType is the atomic.align64 empty struct}
+ * @param dt DataType
+ */
+ public static boolean isAtomicAlign64(DataType dt) {
+ return isAtomicAlign64Typename(dt.getName());
+ }
+
+ /**
+ * {@return true if the type name is the atomic.align64 empty struct}
+ * @param typename name of Go type
+ */
+ public static boolean isAtomicAlign64Typename(String typename) {
+ // same as cmd/compile, an atomic.align64 field forces 8-byte alignment on all archs
+ switch (typename) {
+ case "sync/atomic.align64":
+ case "runtime/internal/atomic.align64": // 1.19-1.22
+ case "internal/runtime/atomic.align64": // 1.23+
+ return true;
+
+ case null:
+ default:
+ return false;
+ }
+ }
+
private static final CategoryPath GOLANG_CP = GoConstants.GOLANG_CATEGORYPATH;
private static final CategoryPath VARLEN_STRUCTS_CP = GoConstants.GOLANG_CATEGORYPATH;
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/rtti/GoTypeManager.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/rtti/GoTypeManager.java
index 5ae2b42db9..80d825184f 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/rtti/GoTypeManager.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/golang/rtti/GoTypeManager.java
@@ -94,7 +94,6 @@ public class GoTypeManager {
this.voidPtrDT = dtm.getPointer(VoidDataType.dataType);
}
-
/**
* Discovers available Go types
*
@@ -330,7 +329,6 @@ public class GoTypeManager {
return result != null ? result.type : null;
}
-
/**
* Finds a Ghidra data type by its go-type name.
*
@@ -371,6 +369,22 @@ public class GoTypeManager {
return getDataType(rec);
}
+ /**
+ * Converts the supplied snapshot type definition into a Ghidra data type.
+ * <p>
+ * Mainly for testing.
+ *
+ * @param typeName name of the type
+ * @param typeDef {@link GoTypeDef} api snapshot typedef
+ * @return new Ghidra DataType
+ * @throws IOException if error
+ */
+ public DataType getSnapshotDataType(GoSymbolName typeName, GoTypeDef typeDef)
+ throws IOException {
+ TypeRec rec = convertApiTypeDef(typeName, typeDef);
+ return getDataType(rec);
+ }
+
/**
* Finds a Ghidra data type by its go-type name.
*
@@ -381,8 +395,7 @@ public class GoTypeManager {
* specific {@link DataType} subclass, or {@code NULL} if not found
* @throws IOException if error
*/
- public <T extends DataType> T findDataType(String typeName, Class<T> clazz)
- throws IOException {
+ public <T extends DataType> T findDataType(String typeName, Class<T> clazz) throws IOException {
DataType result = findDataType(typeName);
return clazz.isInstance(result) ? clazz.cast(result) : null;
}
@@ -460,7 +473,7 @@ public class GoTypeManager {
else {
GoKind primitiveTypeKind = GoKind.parseTypename(typeName);
GoTypeDef typeDef;
- if ( primitiveTypeKind.isPrimitive() ) {
+ if (primitiveTypeKind.isPrimitive()) {
result = makeBasicType(typeSymbolName, primitiveTypeKind);
}
else if ((typeDef = apiSnapshot.getTypeDef(typeName)) != null) {
@@ -598,7 +611,17 @@ public class GoTypeManager {
throws IOException {
String baseTypeName = typeName.asString();
- LengthAlignment lenInfo = getDataTypeLength(structDef);
+ if (GoRttiMapper.isAtomicAlign64Typename(baseTypeName)) {
+ StructureDataType a64 = new StructureDataType(getCP(typeName), baseTypeName, 0, dtm);
+ a64.align(8);
+
+ TypeRec rec = new TypeRec();
+ rec.name = typeName.asString();
+ rec.recoveredDT = a64;
+ return rec;
+ }
+
+ LengthAlignment lenInfo = getDataTypeLength(structDef, baseTypeName);
StructureDataType struct =
new StructureDataType(getCP(typeName), baseTypeName, lenInfo.len, dtm);
struct.align(lenInfo.align);
@@ -620,8 +643,8 @@ public class GoTypeManager {
DataType dtcDT = findDataType(field.DataType);
if (dtcDT == null) {
dtcDT = findDataType(field.DataType);
- throw new IOException("Failed to get type for field [%d %s: %s] in %s"
- .formatted(i, field.Name, field.DataType, typeName));
+ throw new IOException("Failed to get type for field [%d %s: %s] in %s".formatted(i,
+ field.Name, field.DataType, typeName));
}
packedStruct.add(dtcDT, field.Name, null);
}
@@ -853,8 +876,8 @@ public class GoTypeManager {
return clazz.cast(dt);
}
else if (dt != null) {
- Msg.warn(this, "Failed to get Ghidra data type from Go type: %s[%x]".formatted(
- rec.name, rec.type.getStructureContext().getStructureStart()));
+ Msg.warn(this, "Failed to get Ghidra data type from Go type: %s[%x]".formatted(rec.name,
+ rec.type.getStructureContext().getStructureStart()));
}
return null;
}
@@ -869,7 +892,6 @@ public class GoTypeManager {
return rec.recoveredDT;
}
-
public CategoryPath getCP() {
return GOLANG_RECOVERED_TYPES_CATEGORYPATH;
}
@@ -973,8 +995,7 @@ public class GoTypeManager {
int arrayPtrComponentIndex = 0; /* HACK, field ordinal of void* data field in slice type */
DataTypeComponent arrayDTC = genericSliceDT.getComponent(arrayPtrComponentIndex);
sliceDT.replace(arrayPtrComponentIndex, dtm.getPointer(element), -1,
- arrayDTC.getFieldName(),
- arrayDTC.getComment());
+ arrayDTC.getFieldName(), arrayDTC.getComment());
return sliceDT;
}
@@ -1015,8 +1036,9 @@ public class GoTypeManager {
FunctionDefinitionDataType funcDef =
new FunctionDefinitionDataType(getCP(), ".closureF", dtm);
- ParameterDefinition[] params = new ParameterDefinition[] { new ParameterDefinitionImpl(
- GOLANG_CLOSURE_CONTEXT_NAME, dtm.getPointer(closureDT), null) };
+ ParameterDefinition[] params =
+ new ParameterDefinition[] { new ParameterDefinitionImpl(GOLANG_CLOSURE_CONTEXT_NAME,
+ dtm.getPointer(closureDT), null) };
funcDef.setArguments(params);
closureDT.add(dtm.getPointer(funcDef), "F", null);
@@ -1031,13 +1053,13 @@ public class GoTypeManager {
public Structure getDefaultMethodWrapperClosureType() {
if (defaultMethodWrapperType == null) {
- StructureDataType closureDT = new StructureDataType(getCP(),
- ".methodwrapper", 0, dtm);
+ StructureDataType closureDT = new StructureDataType(getCP(), ".methodwrapper", 0, dtm);
FunctionDefinitionDataType funcDef =
new FunctionDefinitionDataType(getCP(), ".methodwrapperF", dtm);
- ParameterDefinition[] params = new ParameterDefinition[] { new ParameterDefinitionImpl(
- GOLANG_CLOSURE_CONTEXT_NAME, dtm.getPointer(closureDT), null) };
+ ParameterDefinition[] params =
+ new ParameterDefinition[] { new ParameterDefinitionImpl(GOLANG_CLOSURE_CONTEXT_NAME,
+ dtm.getPointer(closureDT), null) };
funcDef.setArguments(params);
closureDT.add(dtm.getPointer(funcDef), "F", null);
@@ -1143,7 +1165,7 @@ public class GoTypeManager {
GoTypeDef typeDef = apiSnapshot.getTypeDef(name);
if (typeDef != null) {
return switch (typeDef) {
- case GoStructDef x -> getDataTypeLength(x);
+ case GoStructDef x -> getDataTypeLength(x, name);
case GoBasicDef x -> getDataTypeLength(x);
case GoAliasDef x -> getDataTypeLength(x);
case GoFuncTypeDef x -> getDataTypeLength(x);
@@ -1168,7 +1190,8 @@ public class GoTypeManager {
return new LengthAlignment(ptrSize * 2, align(ptrSize));
}
- private LengthAlignment getDataTypeLength(GoStructDef structDef) throws IOException {
+ private LengthAlignment getDataTypeLength(GoStructDef structDef, String structName)
+ throws IOException {
int len = 0;
int align = 1;
for (GoNameTypePair field : structDef.Fields) {
@@ -1177,6 +1200,9 @@ public class GoTypeManager {
len += fieldInfo.len;
align = Math.max(align, fieldInfo.align);
}
+ if (structDef.Fields.isEmpty() && GoRttiMapper.isAtomicAlign64Typename(structName)) {
+ align = 8; // hard-coded logic found in go's cmd/compile
+ }
len = (int) NumericUtilities.getUnsignedAlignedValue(len, align);
return new LengthAlignment(len, align);
diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/bin/format/golang/GoRegisterInfoTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/bin/format/golang/GoRegisterInfoTest.java
index c1b11bea44..cf2875ad02 100644
--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/bin/format/golang/GoRegisterInfoTest.java
+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/bin/format/golang/GoRegisterInfoTest.java
@@ -17,14 +17,21 @@ package ghidra.app.util.bin.format.golang;
import static org.junit.Assert.*;
+import java.util.ArrayList;
+import java.util.List;
+
import org.junit.Test;
+import ghidra.app.util.bin.format.golang.rtti.*;
+import ghidra.app.util.bin.format.golang.rtti.GoApiSnapshot.GoNameTypePair;
+import ghidra.app.util.bin.format.golang.rtti.GoApiSnapshot.GoStructDef;
import ghidra.program.database.ProgramBuilder;
import ghidra.program.model.data.*;
import ghidra.program.model.lang.Language;
import ghidra.program.model.lang.LanguageID;
import ghidra.program.model.listing.Program;
import ghidra.test.AbstractGhidraHeadlessIntegrationTest;
+import ghidra.util.task.TaskMonitor;
public class GoRegisterInfoTest extends AbstractGhidraHeadlessIntegrationTest {
@@ -38,6 +45,19 @@ public class GoRegisterInfoTest extends AbstractGhidraHeadlessIntegrationTest {
return struct;
}
+ private static GoStructDef snapshotStructDef(String... fields) {
+ GoStructDef result = new GoStructDef();
+ result.Fields = new ArrayList<>();
+ for (String field : fields) {
+ GoNameTypePair f = new GoNameTypePair();
+ f.Name = "field_" + result.Fields.size();
+ f.DataType = field;
+ result.Fields.add(f);
+ }
+ result.TypeParams = List.of();
+ return result;
+ }
+
private static DataType atomicInt64() {
return struct(new StructureDataType("sync/atomic.align64", 0), LongLongDataType.dataType);
}
@@ -84,9 +104,86 @@ public class GoRegisterInfoTest extends AbstractGhidraHeadlessIntegrationTest {
assertEquals(4, regInfo.getAlignmentForType(struct(LongLongDataType.dataType)));
}
+ @Test
+ public void testAtomicAlign64FromApiSnapshot_32bitArch() throws Exception {
+
+ // Test the align64 special struct built-into golang that forces 64bit alignment on
+ // all archs, when reading struct defs from the api snapshot.
+
+ // slightly different align64 package names in these 2 versions
+ List<GoVer> align64FeatureRange = List.of(GoVer.parse("1.19"), GoVer.parse("1.23"));
+
+ ProgramBuilder builder = new ProgramBuilder("go386", ProgramBuilder._X86, "golang", this);
+ try {
+ Program program = builder.getProgram();
+ for (GoVer ver : align64FeatureRange) {
+ GoApiSnapshot gas = GoApiSnapshot.get(ver, "386", "linux", TaskMonitor.DUMMY);
+ try (GoRttiMapper goBinary =
+ new GoRttiMapper(program, null, 4 /*sizeof(32bit_ptr)*/, ver, gas)) {
+
+ Structure i64 = (Structure) goBinary.getGoTypes()
+ .getSnapshotDataType(GoSymbolName.parseTypeName("main.PIUS"),
+ snapshotStructDef("byte", "int64", "byte", "byte"));
+
+ assertEquals(4, i64.getAlignment());
+ assertEquals(16, i64.getLength());
+ assertEquals(13, i64.findComponent("field_3").getOffset());
+
+ Structure ai64 = (Structure) goBinary.getGoTypes()
+ .getSnapshotDataType(GoSymbolName.parseTypeName("main.AIUS"),
+ snapshotStructDef("byte", "sync/atomic.Int64", "byte", "byte"));
+
+ assertEquals(8, ai64.getAlignment());
+ assertEquals(24, ai64.getLength());
+ assertEquals(17, ai64.findComponent("field_3").getOffset());
+ }
+ }
+ }
+ finally {
+ builder.dispose();
+ }
+ }
+
+ @Test
+ public void testAtomicAlign64FromApiSnapshot_64bitArch() throws Exception {
+
+ // slightly different align64 package names in these 2 versions
+ List<GoVer> align64FeatureRange = List.of(GoVer.parse("1.19"), GoVer.parse("1.23"));
+
+ ProgramBuilder builder = new ProgramBuilder("go", ProgramBuilder._X64, "golang", this);
+ try {
+ Program program = builder.getProgram();
+ for (GoVer ver : align64FeatureRange) {
+ GoApiSnapshot gas = GoApiSnapshot.get(ver, "amd64", "linux", TaskMonitor.DUMMY);
+ try (GoRttiMapper goBinary =
+ new GoRttiMapper(program, null, 8 /*sizeof(64bit_ptr)*/, ver, gas)) {
+
+ Structure i64 = (Structure) goBinary.getGoTypes()
+ .getSnapshotDataType(GoSymbolName.parseTypeName("main.PIUS"),
+ snapshotStructDef("byte", "int64", "byte", "byte"));
+
+ assertEquals(8, i64.getAlignment());
+ assertEquals(24, i64.getLength());
+ assertEquals(17, i64.findComponent("field_3").getOffset());
+
+ Structure ai64 = (Structure) goBinary.getGoTypes()
+ .getSnapshotDataType(GoSymbolName.parseTypeName("main.AIUS"),
+ snapshotStructDef("byte", "sync/atomic.Int64", "byte", "byte"));
+
+ assertEquals(8, ai64.getAlignment());
+ assertEquals(24, ai64.getLength());
+ assertEquals(17, ai64.findComponent("field_3").getOffset());
+ }
+ }
+ }
+ finally {
+ builder.dispose();
+ }
+ }
+
@Test
public void testStackAlignmentIsRelativeToArgs() throws Exception {
- ProgramBuilder builder = new ProgramBuilder("go386", ProgramBuilder._X86, this);
+ ProgramBuilder builder = new ProgramBuilder("go386", ProgramBuilder._X86, "golang", this);
try {
Program program = builder.getProgram();
GoParamStorageAllocator allocator = new GoParamStorageAllocator(program, GO_VER);