summaryrefslogtreecommitdiff
path: root/mysys/my_addr_resolve.c
blob: 72b04119855accef1c67c86218fa16a98f38b973 (plain)
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
/* Copyright (C) 2011 Monty Program Ab

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program 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.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */

#include "mysys_priv.h"
#include <m_string.h>
#include <my_sys.h>
#include <my_stacktrace.h>

/**
  strip the path, leave the file name and the last dirname
*/
static const char *strip_path(const char *s) __attribute__((unused));
static const char *strip_path(const char *s)
{
  const char *prev, *last;
  for(prev= last= s; *s; s++)
    if (*s == '/' || *s == '\\')
    {
      prev= last;
      last= s + 1;
    }
  return prev;
}

/*
  The following is very much single-threaded code and it's only supposed
  to be used on shutdown or for a crash report
  Or the caller should take care and use mutexes.

  Also it does not free any its memory. For the same reason -
  it's only used for crash reports or on shutdown when we already
  have a memory leak.
*/

#ifdef HAVE_BFD_H
#include <bfd.h>
static bfd *bfdh= 0;
static asymbol **symtable= 0;

/**
  finds a file name, a line number, and a function name corresponding to addr.

  the function name is demangled.
  the file name is stripped of its path, only the two last components are kept
  the resolving logic is mostly based on addr2line of binutils-2.17

  @return 0 on success, 1 on failure
*/
int my_addr_resolve(void *ptr, my_addr_loc *loc)
{
  bfd_vma addr= (intptr)ptr;
  asection *sec;

  for (sec= bfdh->sections; sec; sec= sec->next)
  {
    bfd_vma start;

    if ((bfd_get_section_flags(bfdh, sec) & SEC_ALLOC) == 0)
      continue;

    start = bfd_get_section_vma(bfdh, sec);
    if (addr < start || addr >= start + bfd_get_section_size(sec))
      continue;

    if (bfd_find_nearest_line(bfdh, sec, symtable, addr - start,
                              &loc->file, &loc->func, &loc->line))
    {
      if (loc->file)
        loc->file= strip_path(loc->file);
      else
        loc->file= "";

      if (loc->func)
      {
        const char *str= bfd_demangle(bfdh, loc->func, 3);
        if (str)
          loc->func= str;
      }

      return 0;
    }
  }
  
  return 1;
}

const char *my_addr_resolve_init()
{
  if (!bfdh)
  {
    uint unused;
    char **matching;

    bfdh= bfd_openr(my_progname, NULL);
    if (!bfdh)
      goto err;

    if (bfd_check_format(bfdh, bfd_archive))
      goto err;
    if (!bfd_check_format_matches (bfdh, bfd_object, &matching))
      goto err;

    if (bfd_read_minisymbols(bfdh, FALSE, (void *)&symtable, &unused) < 0)
      goto err;
  }
  return 0;

err:
  return bfd_errmsg(bfd_get_error());
}
#elif defined(HAVE_LIBELF_H)
/*
  another possible implementation.
*/
#elif defined(MY_ADDR_RESOLVE_FORK)
/*
  yet another - just execute addr2line pipe the addresses to it, and parse the
  output
*/

#include <m_string.h>
#include <ctype.h>

#if defined(HAVE_LINK_H) && defined(HAVE_DLOPEN)
#include <link.h>
static ptrdiff_t offset= 0;
#else
#define offset 0
#endif

static int in[2], out[2];
static int initialized= 0;
static char output[1024];
int my_addr_resolve(void *ptr, my_addr_loc *loc)
{
  char input[32];
  size_t len;

  ssize_t total_bytes_read = 0;
  ssize_t extra_bytes_read = 0;

  fd_set set;
  struct timeval timeout;

  int filename_start = -1;
  int line_number_start = -1;
  ssize_t i;

  FD_ZERO(&set);
  FD_SET(out[0], &set);

  len= my_snprintf(input, sizeof(input), "%p\n", ptr - offset);
  if (write(in[1], input, len) <= 0)
    return 1;

  /* 10 ms should be plenty of time for addr2line to issue a response. */
  timeout.tv_sec = 0;
  timeout.tv_usec = 10000;
  /* Read in a loop till all the output from addr2line is complete. */
  while (select(out[0] + 1, &set, NULL, NULL, &timeout) > 0)
  {
    extra_bytes_read= read(out[0], output + total_bytes_read,
                           sizeof(output) - total_bytes_read);
    if (extra_bytes_read < 0)
      return 1;
    /* Timeout or max bytes read. */
    if (extra_bytes_read == 0)
      break;

    total_bytes_read += extra_bytes_read;
  }

  /* Failed starting addr2line. */
  if (total_bytes_read == 0)
    return 1;

  /* Go through the addr2line response and get the required data.
     The response is structured in 2 lines. The first line contains the function
     name, while the second one contains <filename>:<line number> */
  for (i = 0; i < total_bytes_read; i++) {
    if (output[i] == '\n') {
      filename_start = i + 1;
      output[i] = '\0';
    }
    if (filename_start != -1 && output[i] == ':') {
      line_number_start = i + 1;
      output[i] = '\0';
    }
    if (line_number_start != -1) {
      loc->line= atoi(output + line_number_start);
      break;
    }
  }
  /* Response is malformed. */
  if (filename_start == -1 || line_number_start == -1)
   return 1;

  loc->func= output;
  loc->file= output + filename_start;

  /* Addr2line was unable to extract any meaningful information. */
  if (strcmp(loc->file, "??") == 0)
    return 1;

  loc->file= strip_path(loc->file);

  return 0;
}

const char *my_addr_resolve_init()
{
  if (!initialized)
  {
    pid_t pid;

#if defined(HAVE_LINK_H) && defined(HAVE_DLOPEN)
    struct link_map *lm = (struct link_map*) dlopen(0, RTLD_NOW);
    if (lm)
      offset= lm->l_addr;
#endif

    if (pipe(in) < 0)
      return "pipe(in)";
    if (pipe(out) < 0)
      return "pipe(out)";

    pid = fork();
    if (pid == -1)
      return "fork";

    if (!pid) /* child */
    {
      dup2(in[0], 0);
      dup2(out[1], 1);
      close(in[0]);
      close(in[1]);
      close(out[0]);
      close(out[1]);
      execlp("addr2line", "addr2line", "-C", "-f", "-e", my_progname, NULL);
      exit(1);
    }
    
    close(in[0]);
    close(out[1]);
    initialized= 1;
  }
  return 0;
}
#endif