blob: 86f61621147092665650647c2a3f49019cbbb5ae [file] [log] [blame]
Colin Cross5498f852018-01-03 23:39:54 -08001// 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
15package main
16
17import (
18 "debug/pe"
19 "fmt"
20 "io"
21 "sort"
22)
23
24func 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
30 sort.Slice(peFile.Symbols, func(i, j int) bool {
31 if peFile.Symbols[i].SectionNumber != peFile.Symbols[j].SectionNumber {
32 return peFile.Symbols[i].SectionNumber < peFile.Symbols[j].SectionNumber
33 }
34 return peFile.Symbols[i].Value < peFile.Symbols[j].Value
35 })
36
37 for i, symbol := range peFile.Symbols {
38 if symbol.Name == symbolName {
39 var nextSymbol *pe.Symbol
40 if i+1 < len(peFile.Symbols) {
41 nextSymbol = peFile.Symbols[i+1]
42 }
43 return calculatePESymbolOffset(peFile, symbol, nextSymbol)
44 }
45 }
46
47 return maxUint64, maxUint64, fmt.Errorf("symbol not found")
48}
49
50func calculatePESymbolOffset(file *pe.File, symbol *pe.Symbol, nextSymbol *pe.Symbol) (uint64, uint64, error) {
51 section := file.Sections[symbol.SectionNumber-1]
52
53 var end uint32
54 if nextSymbol != nil && nextSymbol.SectionNumber != symbol.SectionNumber {
55 nextSymbol = nil
56 }
57 if nextSymbol != nil {
58 end = nextSymbol.Value
59 } else {
60 end = section.Size
61 }
62
63 size := end - symbol.Value - 1
64 offset := section.Offset + symbol.Value
65
66 return uint64(offset), uint64(size), nil
67}