diff --git a/cmd/symbol_inject/macho.go b/cmd/symbol_inject/macho.go index 0945293f9..4a3ecc741 100644 --- a/cmd/symbol_inject/macho.go +++ b/cmd/symbol_inject/macho.go @@ -18,6 +18,7 @@ import ( "debug/macho" "fmt" "io" + "sort" ) func findMachoSymbol(r io.ReaderAt, symbolName string) (uint64, uint64, error) { @@ -26,17 +27,25 @@ func findMachoSymbol(r io.ReaderAt, symbolName string) (uint64, uint64, error) { return maxUint64, maxUint64, cantParseError{err} } - // TODO(ccross): why? + // symbols in macho files seem to be prefixed with an underscore symbolName = "_" + symbolName - for i, symbol := range machoFile.Symtab.Syms { + symbols := machoFile.Symtab.Syms + sort.Slice(symbols, func(i, j int) bool { + if symbols[i].Sect != symbols[j].Sect { + return symbols[i].Sect < symbols[j].Sect + } + return symbols[i].Value < symbols[j].Value + }) + + for i, symbol := range symbols { if symbol.Sect == 0 { continue } if symbol.Name == symbolName { var nextSymbol *macho.Symbol - if i+1 < len(machoFile.Symtab.Syms) { - nextSymbol = &machoFile.Symtab.Syms[i+1] + if i+1 < len(symbols) { + nextSymbol = &symbols[i+1] } return calculateMachoSymbolOffset(machoFile, symbol, nextSymbol) } diff --git a/cmd/symbol_inject/pe.go b/cmd/symbol_inject/pe.go index 86f616211..dad530d4d 100644 --- a/cmd/symbol_inject/pe.go +++ b/cmd/symbol_inject/pe.go @@ -27,6 +27,11 @@ func findPESymbol(r io.ReaderAt, symbolName string) (uint64, uint64, error) { return maxUint64, maxUint64, cantParseError{err} } + if peFile.FileHeader.Machine == pe.IMAGE_FILE_MACHINE_I386 { + // symbols in win32 exes seem to be prefixed with an underscore + symbolName = "_" + symbolName + } + sort.Slice(peFile.Symbols, func(i, j int) bool { if peFile.Symbols[i].SectionNumber != peFile.Symbols[j].SectionNumber { return peFile.Symbols[i].SectionNumber < peFile.Symbols[j].SectionNumber