Colin Cross | 5498f85 | 2018-01-03 23:39:54 -0800 | [diff] [blame] | 1 | // Copyright 2018 Google Inc. All rights reserved. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package main |
| 16 | |
| 17 | import ( |
| 18 | "debug/pe" |
| 19 | "fmt" |
| 20 | "io" |
| 21 | "sort" |
| 22 | ) |
| 23 | |
| 24 | func findPESymbol(r io.ReaderAt, symbolName string) (uint64, uint64, error) { |
| 25 | peFile, err := pe.NewFile(r) |
| 26 | if err != nil { |
| 27 | return maxUint64, maxUint64, cantParseError{err} |
| 28 | } |
| 29 | |
Colin Cross | 64c6d4b | 2018-02-23 17:10:34 -0800 | [diff] [blame^] | 30 | if peFile.FileHeader.Machine == pe.IMAGE_FILE_MACHINE_I386 { |
| 31 | // symbols in win32 exes seem to be prefixed with an underscore |
| 32 | symbolName = "_" + symbolName |
| 33 | } |
| 34 | |
Colin Cross | 5498f85 | 2018-01-03 23:39:54 -0800 | [diff] [blame] | 35 | sort.Slice(peFile.Symbols, func(i, j int) bool { |
| 36 | if peFile.Symbols[i].SectionNumber != peFile.Symbols[j].SectionNumber { |
| 37 | return peFile.Symbols[i].SectionNumber < peFile.Symbols[j].SectionNumber |
| 38 | } |
| 39 | return peFile.Symbols[i].Value < peFile.Symbols[j].Value |
| 40 | }) |
| 41 | |
| 42 | for i, symbol := range peFile.Symbols { |
| 43 | if symbol.Name == symbolName { |
| 44 | var nextSymbol *pe.Symbol |
| 45 | if i+1 < len(peFile.Symbols) { |
| 46 | nextSymbol = peFile.Symbols[i+1] |
| 47 | } |
| 48 | return calculatePESymbolOffset(peFile, symbol, nextSymbol) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | return maxUint64, maxUint64, fmt.Errorf("symbol not found") |
| 53 | } |
| 54 | |
| 55 | func calculatePESymbolOffset(file *pe.File, symbol *pe.Symbol, nextSymbol *pe.Symbol) (uint64, uint64, error) { |
| 56 | section := file.Sections[symbol.SectionNumber-1] |
| 57 | |
| 58 | var end uint32 |
| 59 | if nextSymbol != nil && nextSymbol.SectionNumber != symbol.SectionNumber { |
| 60 | nextSymbol = nil |
| 61 | } |
| 62 | if nextSymbol != nil { |
| 63 | end = nextSymbol.Value |
| 64 | } else { |
| 65 | end = section.Size |
| 66 | } |
| 67 | |
| 68 | size := end - symbol.Value - 1 |
| 69 | offset := section.Offset + symbol.Value |
| 70 | |
| 71 | return uint64(offset), uint64(size), nil |
| 72 | } |