File: BfdWrapper.cpp

package info (click to toggle)
tulip 3.7.0dfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 39,428 kB
  • sloc: cpp: 231,403; php: 11,023; python: 1,128; sh: 671; yacc: 522; makefile: 315; xml: 63; lex: 55
file content (343 lines) | stat: -rwxr-xr-x 9,923 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/**
 *
 * This file is part of Tulip (www.tulip-software.org)
 *
 * Authors: David Auber and the Tulip development Team
 * from LaBRI, University of Bordeaux 1 and Inria Bordeaux - Sud Ouest
 *
 * Tulip is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation, either version 3
 * of the License, or (at your option) any later version.
 *
 * Tulip is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 */

#include "BfdWrapper.h"

#include <iostream>
#include <sstream>
#include <vector>
#include <cxxabi.h>
#include <sys/stat.h>

#define INRANGE(foo,bar,baz) (foo(bar))&&((bar)baz)

using namespace std;

static asymbol **
slurp_symtab(bfd *abfd, bool useMini,
             long *nSymbols,
             unsigned int *symbolSize,
             bool *isDynamic) {
  *nSymbols = 0;
  *symbolSize = 0;
  *isDynamic = false;
  asymbol **symbol_table = NULL;

  if ((bfd_get_file_flags (abfd) & HAS_SYMS) == 0) {
    *nSymbols = 0;
    return symbol_table;
  }

  if (useMini) {
    *nSymbols = bfd_read_minisymbols(abfd, false, reinterpret_cast<void **>(&symbol_table), symbolSize);

    if (*nSymbols == 0) {
      *isDynamic = true;
      *nSymbols = bfd_read_minisymbols(abfd, true, reinterpret_cast<void **>(&symbol_table), symbolSize);
    }

    if (*nSymbols < 0) {
      cerr << "Error (bfd_read_minisymbols) in " << bfd_get_filename(abfd) << endl;
      return symbol_table;
    }
  }
  else {

    long storage_needed = bfd_get_symtab_upper_bound(abfd);

    if (storage_needed < 0) {
      cerr << "Error (bfd_get_symtab_upper_bound) slurping symbol table from " << bfd_get_filename(abfd) << endl;
      return symbol_table;
    }

    if (storage_needed != 0)
      symbol_table = reinterpret_cast<asymbol **>(malloc(storage_needed));

    *nSymbols = bfd_canonicalize_symtab(abfd, symbol_table);

    if (*nSymbols < 0) {
      cerr << "Error (bfd_canonicalize_symtab) slurping symbol table from : " << bfd_get_filename(abfd) << endl;
      return symbol_table;
    }
  }

  if (*nSymbols == 0)
    cerr << "No symbols in " << bfd_get_filename(abfd) << endl;

  return symbol_table;
}

int file_exist (const std::string &filename) {
  struct stat   buffer;
  return (stat (filename.c_str(), &buffer) == 0);
}

#ifdef __MINGW32__
static
DWORD GetModuleBase(DWORD dwAddress) {
  MEMORY_BASIC_INFORMATION Buffer;
  return VirtualQuery((LPCVOID) dwAddress, &Buffer, sizeof(Buffer)) ? (DWORD) Buffer.AllocationBase : 0;
}
#endif

static void tokenize(const string& str, vector<string>& tokens, const string& delimiters = " ") {
  string::size_type lastPos = 0;
  string::size_type pos = str.find_first_of(delimiters, lastPos);

  while (string::npos != pos || string::npos != lastPos) {
    tokens.push_back(str.substr(lastPos, pos - lastPos));

    if (pos != string::npos)
      lastPos=pos+1;
    else
      lastPos=string::npos;

    pos = str.find_first_of(delimiters, lastPos);
  }
}

#define PATH_MAX 1024

static bool bfdInit = false;

BfdWrapper::BfdWrapper(const char *dsoName) :
  abfd(NULL), textSection(NULL), symbolTable(NULL),
  nSymbols(0), symbolSize(0), isMini(true), isDynamic(false),
  scratchSymbol(NULL), relocationOffset(-1) {

  filePath = dsoName;

#ifndef __MINGW32__

  // try to find the absolute path of the shared library or executable
  if (!file_exist(filePath)) {

    // if no / character in the filename, it surely is an executable
    // whose location is in the PATH environment variable
    if (filePath.find('/') == string::npos) {
      const string PATH = getenv("PATH");
      vector<string> paths;

      tokenize(PATH, paths, ":");

      bool absolutePathFound = false;

      for (size_t i = 0 ; i < paths.size() ; ++i) {
        if (file_exist((paths[i]+"/"+filePath))) {
          filePath = paths[i]+"/"+filePath;
          absolutePathFound = true;
          break;
        }
      }

      if (!absolutePathFound) {
        cerr << "Can't find " << filePath << " in $PATH\n" << endl;
        return;
      }
    }

    string pwd(getenv("PWD"));

    // maybe it's a relative path otherwise
    if (file_exist(pwd+"/"+filePath)) {
      filePath = pwd + "/" + filePath;
    }
  }

#endif

  if (!bfdInit) {
    bfd_init();
    bfdInit = true;
  }

  abfd = bfd_openr(filePath.c_str(), NULL);

  if (abfd == NULL) {
    cerr << "Can't open file " << filePath << endl;
    return;
  }

  if (!bfd_check_format(abfd, bfd_object)) {
    cerr << "Can't open file " << bfd_get_filename(abfd) << endl;
    bfd_close(abfd);
    return;
  }

  textSection = bfd_get_section_by_name(abfd, ".text");

  if (textSection == NULL) {
    cerr << "Can't find .text section in " << bfd_get_filename(abfd) << endl;
    bfd_close(abfd);
    return;
  }

  isMini = true;
  nSymbols = 0;
  symbolSize = 0;
  isDynamic = false;
  symbolTable = slurp_symtab(abfd, isMini, &nSymbols, &symbolSize, &isDynamic);

  if ((bfd_get_section_flags(abfd, textSection) & SEC_ALLOC) == 0) {
    cerr << "SEC_ALLOC flag not set on .text section (whatever that means) in " << bfd_get_filename(abfd) << endl;
    free(symbolTable);
    bfd_close(abfd);
    return;
  }

  asymbol *scratchSymbol = bfd_make_empty_symbol(abfd);

  if (scratchSymbol == NULL) {
    cerr << "Error (bfd_make_empty_symbol) in " << bfd_get_filename(abfd) << endl;
    free(symbolTable);
    bfd_close(abfd);
    return;
  }
}

BfdWrapper::~BfdWrapper() {
  if (symbolTable != NULL) {
    free(symbolTable);
  }

  if (abfd != NULL) {
    bfd_close(abfd);
  }
}

#ifndef __MINGW32__

pair<const char *, unsigned int> BfdWrapper::getFileAndLineForAddress(const char *mangledSymbol, const int64_t runtimeAddr, const int64_t runtimeOffset) {
  pair<const char *, unsigned int> ret = make_pair("", 0);

  if (!abfd || !isMini || symbolSize == 0)
    return ret;

  bfd_byte *from = (bfd_byte *)symbolTable;
  bfd_byte *fromend = from + nSymbols * symbolSize;
  int index = 0;

  for (; from < fromend; from += symbolSize, index++) {
    asymbol *sym = bfd_minisymbol_to_symbol(abfd, isDynamic, from, scratchSymbol);

    if (sym == NULL) {
      cerr << "Error (bfd_minisymbol_to_symbol) in " << bfd_get_filename(abfd) << endl;
      return ret;
    }

    symbol_info syminfo;
    bfd_get_symbol_info(abfd, sym, &syminfo);

    if (syminfo.type == 'T' || syminfo.type == 'W') {
      int status;

      bool matched = string(syminfo.name) == string(mangledSymbol);

      if (matched) {

        int64_t relocatedSymbolAddress = runtimeAddr - runtimeOffset;
        int64_t unrelocatedSymbolAddress = syminfo.value;

        relocationOffset = relocatedSymbolAddress - unrelocatedSymbolAddress;

        int64_t relocatedAddr = runtimeAddr;
        int64_t unrelocatedAddr = relocatedAddr;

        if (relocationOffset != -1)
          unrelocatedAddr -= relocationOffset;

        const char *funcName = NULL;
        const char *fileName = NULL;
        unsigned int lineno = 0;

        bfd_vma textSection_vma = bfd_get_section_vma(abfd, textSection);
        bfd_size_type textSection_size = bfd_section_size(abfd, textSection);

        if (!INRANGE((int64_t)textSection_vma <=, unrelocatedAddr, <= (int64_t)(textSection_vma+textSection_size))) {
          cerr << "Trying to look up an address that's outside of the range of the text section of " << filePath << "... usually this means the executable or DSO in question has changed since the stack trace was generated" << endl;
          return ret;
        }

        if (!bfd_find_nearest_line(abfd, textSection, symbolTable, unrelocatedAddr - textSection_vma - 1, &fileName, &funcName, &lineno)) {
          cerr << "Can't find line for address " << hex << (unsigned long long)relocatedAddr << " <- " << (unsigned long long)unrelocatedAddr << dec << endl;
          return ret;
        }
        else {
          if (fileName) {
            ret = make_pair(fileName, lineno);
          }

          return ret;
        }
      }
    }
  }

  return ret;
}

#else

pair<const char *, unsigned int> BfdWrapper::getFileAndLineForAddress(const int64_t runtimeAddr) {

  pair<const char *, unsigned int> ret = make_pair("", 0);

  if (!abfd)
    return ret;

  const char *funcName = "";
  const char *fileName = "";
  unsigned int lineno = 0;

  int64_t symbolOffset = runtimeAddr - GetModuleBase(runtimeAddr)  - 0x1000 - 1;
  bfd_size_type textSection_size = bfd_section_size(abfd, textSection);

  if (!INRANGE((int64_t)0 <=, symbolOffset, <= (int64_t)textSection_size)) {
    cerr << "Trying to look up an address that's outside of the range of the text section of " << filePath << "... usually this means the executable or DSO in question has changed since the stack trace was generated" << endl;
  }
  else {
    bfd_find_nearest_line(abfd, textSection, symbolTable, symbolOffset, &fileName, &funcName, &lineno);
  }

  ret = make_pair(fileName, lineno);
  return ret;
}

const char *BfdWrapper::getFunctionForAddress(const int64_t runtimeAddr) {

  const char *funcName = "";
  const char *fileName = "";
  unsigned int lineno = 0;

  if (!abfd)
    return funcName;

  int64_t symbolOffset = runtimeAddr - GetModuleBase(runtimeAddr) - 0x1000 - 1;
  bfd_size_type textSection_size = bfd_section_size(abfd, textSection);

  if (!INRANGE((int64_t)0 <=, symbolOffset, <= (int64_t)textSection_size)) {
    cerr << "Trying to look up an address that's outside of the range of the text section of " << filePath << "... usually this means the executable or DSO in question has changed since the stack trace was generated" << endl;
    return funcName;
  }

  bfd_find_nearest_line(abfd, textSection, symbolTable, symbolOffset, &fileName, &funcName, &lineno);
  return funcName;
}

#endif