blob: 0945293f97697edc5ab716e5af110de0c0ea5f37 [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/macho"
19 "fmt"
20 "io"
21)
22
23func findMachoSymbol(r io.ReaderAt, symbolName string) (uint64, uint64, error) {
24 machoFile, err := macho.NewFile(r)
25 if err != nil {
26 return maxUint64, maxUint64, cantParseError{err}
27 }
28
29 // TODO(ccross): why?
30 symbolName = "_" + symbolName
31
32 for i, symbol := range machoFile.Symtab.Syms {
33 if symbol.Sect == 0 {
34 continue
35 }
36 if symbol.Name == symbolName {
37 var nextSymbol *macho.Symbol
38 if i+1 < len(machoFile.Symtab.Syms) {
39 nextSymbol = &machoFile.Symtab.Syms[i+1]
40 }
41 return calculateMachoSymbolOffset(machoFile, symbol, nextSymbol)
42 }
43 }
44
45 return maxUint64, maxUint64, fmt.Errorf("symbol not found")
46}
47
48func calculateMachoSymbolOffset(file *macho.File, symbol macho.Symbol, nextSymbol *macho.Symbol) (uint64, uint64, error) {
49 section := file.Sections[symbol.Sect-1]
50
51 var end uint64
52 if nextSymbol != nil && nextSymbol.Sect != symbol.Sect {
53 nextSymbol = nil
54 }
55 if nextSymbol != nil {
56 end = nextSymbol.Value
57 } else {
58 end = section.Addr + section.Size
59 }
60
61 size := end - symbol.Value - 1
62 offset := uint64(section.Offset) + (symbol.Value - section.Addr)
63
64 return offset, size, nil
65}