fix size report parser for elf

This commit is contained in:
Li Jie
2025-11-17 15:31:34 +08:00
parent faa5330b69
commit dc39b84187

View File

@@ -206,6 +206,11 @@ func parseReadelfOutput(r io.Reader) (*readelfData, error) {
symbols: make(map[int][]symbolInfo), symbols: make(map[int][]symbolInfo),
} }
// readelf outputs section references differently:
// - Mach-O: section numbers are 1-based in symbol references
// - ELF: section numbers in symbol references match the Index directly
secIndexBase := 1 // default to Mach-O behavior; switch to 0 for ELF once detected
var currentSection *sectionInfo var currentSection *sectionInfo
var currentSymbol *symbolInfo var currentSymbol *symbolInfo
@@ -215,6 +220,16 @@ func parseReadelfOutput(r io.Reader) (*readelfData, error) {
if trimmed == "" { if trimmed == "" {
continue continue
} }
// Detect object format early to adjust section index base
if strings.HasPrefix(trimmed, "Format:") {
lower := strings.ToLower(trimmed)
if strings.Contains(lower, "mach-o") {
secIndexBase = 1
} else if strings.Contains(lower, "elf") {
secIndexBase = 0
}
}
indent := countLeadingSpaces(raw) indent := countLeadingSpaces(raw)
top := current() top := current()
@@ -282,7 +297,7 @@ func parseReadelfOutput(r io.Reader) (*readelfData, error) {
case strings.HasPrefix(trimmed, "Name: "): case strings.HasPrefix(trimmed, "Name: "):
currentSymbol.Name = parseNameField(trimmed[len("Name: "):]) currentSymbol.Name = parseNameField(trimmed[len("Name: "):])
case strings.HasPrefix(trimmed, "Section: "): case strings.HasPrefix(trimmed, "Section: "):
name, idx := parseSectionRef(trimmed[len("Section: "):]) name, idx := parseSectionRef(trimmed[len("Section: "):], secIndexBase)
currentSymbol.SectionIndex = idx currentSymbol.SectionIndex = idx
if currentSymbol.Name == "" { if currentSymbol.Name == "" {
currentSymbol.Name = name currentSymbol.Name = name
@@ -531,7 +546,7 @@ func parseNameField(field string) string {
return val return val
} }
func parseSectionRef(field string) (string, int) { func parseSectionRef(field string, indexBase int) (string, int) {
name := parseNameField(field) name := parseNameField(field)
idx := strings.Index(field, "(") idx := strings.Index(field, "(")
if idx < 0 { if idx < 0 {
@@ -550,11 +565,21 @@ func parseSectionRef(field string) (string, int) {
if err != nil { if err != nil {
return name, -1 return name, -1
} }
// Check for valid section index (1-based in readelf output) if num == 0 {
if num == 0 || num > math.MaxInt {
return name, -1 return name, -1
} }
return name, int(num - 1) if indexBase == 0 && num >= 0xFFF0 {
// Special ELF indices such as SHN_ABS/SHN_COMMON.
return name, -1
}
if num > math.MaxInt {
return name, -1
}
res := int(num) - indexBase
if res < 0 {
return name, -1
}
return name, res
} }
func parseUintField(field string) (uint64, error) { func parseUintField(field string) (uint64, error) {