porting_aix.cpp revision 6856:5217fa82f1a4
1/*
2 * Copyright 2012, 2013 SAP AG. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25#include "asm/assembler.hpp"
26#include "memory/allocation.hpp"
27#include "memory/allocation.inline.hpp"
28#include "runtime/os.hpp"
29#include "loadlib_aix.hpp"
30#include "porting_aix.hpp"
31#include "utilities/debug.hpp"
32
33#include <demangle.h>
34#include <sys/debug.h>
35
36//////////////////////////////////
37// Provide implementation for dladdr based on LoadedLibraries pool and
38// traceback table scan (see getFuncName).
39
40// Search traceback table in stack,
41// return procedure name from trace back table.
42#define MAX_FUNC_SEARCH_LEN 0x10000
43// Any PC below this value is considered toast.
44#define MINIMUM_VALUE_FOR_PC ((unsigned int*)0x1024)
45
46#define PTRDIFF_BYTES(p1,p2) (((ptrdiff_t)p1) - ((ptrdiff_t)p2))
47
48// Align a pointer without having to cast.
49inline char* align_ptr_up(char* ptr, intptr_t alignment) {
50  return (char*) align_size_up((intptr_t)ptr, alignment);
51}
52
53// Trace if verbose to tty.
54// I use these now instead of the Xtrace system because the latter is
55// not available at init time, hence worthless. Until we fix this, all
56// tracing here is done with -XX:+Verbose.
57#define trcVerbose(fmt, ...) { \
58  if (Verbose) { \
59    fprintf(stderr, fmt, ##__VA_ARGS__); \
60    fputc('\n', stderr); fflush(stderr); \
61  } \
62}
63#define ERRBYE(s) { trcVerbose(s); return -1; }
64
65// Unfortunately, the interface of dladdr makes the implementator
66// responsible for maintaining memory for function name/library
67// name. I guess this is because most OS's keep those values as part
68// of the mapped executable image ready to use. On AIX, this doesn't
69// work, so I have to keep the returned strings. For now, I do this in
70// a primitive string map. Should this turn out to be a performance
71// problem, a better hashmap has to be used.
72class fixed_strings {
73  struct node : public CHeapObj<mtInternal> {
74    char* v;
75    node* next;
76  };
77
78  node* first;
79
80  public:
81
82  fixed_strings() : first(0) {}
83  ~fixed_strings() {
84    node* n = first;
85    while (n) {
86      node* p = n;
87      n = n->next;
88      os::free(p->v);
89      delete p;
90    }
91  }
92
93  char* intern(const char* s) {
94    for (node* n = first; n; n = n->next) {
95      if (strcmp(n->v, s) == 0) {
96        return n->v;
97      }
98    }
99    node* p = new node;
100    p->v = os::strdup_check_oom(s);
101    p->next = first;
102    first = p;
103    return p->v;
104  }
105};
106
107static fixed_strings dladdr_fixed_strings;
108
109// Given a code pointer, returns the function name and the displacement.
110// Function looks for the traceback table at the end of the function.
111extern "C" int getFuncName(
112    codeptr_t pc,                    // [in] program counter
113    char* p_name, size_t namelen,    // [out] optional: function name ("" if not available)
114    int* p_displacement,             // [out] optional: displacement (-1 if not available)
115    const struct tbtable** p_tb,     // [out] optional: ptr to traceback table to get further
116                                     //                 information (NULL if not available)
117    char* p_errmsg, size_t errmsglen // [out] optional: user provided buffer for error messages
118  ) {
119  struct tbtable* tb = 0;
120  unsigned int searchcount = 0;
121
122  // initialize output parameters
123  if (p_name && namelen > 0) {
124    *p_name = '\0';
125  }
126  if (p_errmsg && errmsglen > 0) {
127    *p_errmsg = '\0';
128  }
129  if (p_displacement) {
130    *p_displacement = -1;
131  }
132  if (p_tb) {
133    *p_tb = NULL;
134  }
135
136  // weed out obvious bogus states
137  if (pc < MINIMUM_VALUE_FOR_PC) {
138    ERRBYE("invalid program counter");
139  }
140
141  codeptr_t pc2 = pc;
142
143  // make sure the pointer is word aligned.
144  pc2 = (codeptr_t) align_ptr_up((char*)pc2, 4);
145
146  // Find start of traceback table.
147  // (starts after code, is marked by word-aligned (32bit) zeros)
148  while ((*pc2 != NULL) && (searchcount++ < MAX_FUNC_SEARCH_LEN)) {
149    pc2++;
150  }
151  if (*pc2 != 0) {
152    ERRBYE("could not find traceback table within 5000 bytes of program counter");
153  }
154  //
155  // Set up addressability to the traceback table
156  //
157  tb = (struct tbtable*) (pc2 + 1);
158
159  // Is this really a traceback table? No way to be sure but
160  // some indicators we can check.
161  if (tb->tb.lang >= 0xf && tb->tb.lang <= 0xfb) {
162    // Language specifiers, go from 0 (C) to 14 (Objective C).
163    // According to spec, 0xf-0xfa reserved, 0xfb-0xff reserved for ibm.
164    ERRBYE("not a traceback table");
165  }
166
167  // Existence of fields in the tbtable extension are contingent upon
168  // specific fields in the base table.  Check for their existence so
169  // that we can address the function name if it exists.
170  pc2 = (codeptr_t) tb +
171    sizeof(struct tbtable_short)/sizeof(int);
172  if (tb->tb.fixedparms != 0 || tb->tb.floatparms != 0)
173    pc2++;
174
175  if (tb->tb.has_tboff == TRUE) {
176
177    // I want to know the displacement
178    const unsigned int tb_offset = *pc2;
179    codeptr_t start_of_procedure =
180    (codeptr_t)(((char*)tb) - 4 - tb_offset);  // (-4 to omit leading 0000)
181
182    // Weed out the cases where we did find the wrong traceback table.
183    if (pc < start_of_procedure) {
184      ERRBYE("could not find (the real) traceback table within 5000 bytes of program counter");
185    }
186
187    // return the displacement
188    if (p_displacement) {
189      (*p_displacement) = (int) PTRDIFF_BYTES(pc, start_of_procedure);
190    }
191
192    pc2++;
193  } else {
194    // return -1 for displacement
195    if (p_displacement) {
196      (*p_displacement) = -1;
197    }
198  }
199
200  if (tb->tb.int_hndl == TRUE)
201    pc2++;
202
203  if (tb->tb.has_ctl == TRUE)
204    pc2 += (*pc2) + 1; // don't care
205
206  //
207  // return function name if it exists.
208  //
209  if (p_name && namelen > 0) {
210    if (tb->tb.name_present) {
211      char buf[256];
212      const short l = MIN2<short>(*((short*)pc2), sizeof(buf) - 1);
213      memcpy(buf, (char*)pc2 + sizeof(short), l);
214      buf[l] = '\0';
215
216      p_name[0] = '\0';
217
218      // If it is a C++ name, try and demangle it using the Demangle interface (see demangle.h).
219      char* rest;
220      Name* const name = Demangle(buf, rest);
221      if (name) {
222        const char* const demangled_name = name->Text();
223        if (demangled_name) {
224          strncpy(p_name, demangled_name, namelen-1);
225          p_name[namelen-1] = '\0';
226        }
227        delete name;
228      }
229
230      // Fallback: if demangling did not work, just provide the unmangled name.
231      if (p_name[0] == '\0') {
232        strncpy(p_name, buf, namelen-1);
233        p_name[namelen-1] = '\0';
234      }
235
236    } else {
237      strncpy(p_name, "<nameless function>", namelen-1);
238      p_name[namelen-1] = '\0';
239    }
240  }
241  // Return traceback table, if user wants it.
242  if (p_tb) {
243    (*p_tb) = tb;
244  }
245
246  return 0;
247}
248
249// Special implementation of dladdr for Aix based on LoadedLibraries
250// Note: dladdr returns non-zero for ok, 0 for error!
251// Note: dladdr is not posix, but a non-standard GNU extension. So this tries to
252//   fulfill the contract of dladdr on Linux (see http://linux.die.net/man/3/dladdr)
253// Note: addr may be both an AIX function descriptor or a real code pointer
254//   to the entry of a function.
255extern "C"
256int dladdr(void* addr, Dl_info* info) {
257
258  if (!addr) {
259    return 0;
260  }
261
262  assert(info, "");
263
264  int rc = 0;
265
266  const char* const ZEROSTRING = "";
267
268  // Always return a string, even if a "" one. Linux dladdr manpage
269  // does not say anything about returning NULL
270  info->dli_fname = ZEROSTRING;
271  info->dli_sname = ZEROSTRING;
272  info->dli_saddr = NULL;
273
274  address p = (address) addr;
275  const LoadedLibraryModule* lib = NULL;
276
277  enum { noclue, code, data } type = noclue;
278
279  trcVerbose("dladdr(%p)...", p);
280
281  // Note: input address may be a function. I accept both a pointer to
282  // the entry of a function and a pointer to the function decriptor.
283  // (see ppc64 ABI)
284  lib = LoadedLibraries::find_for_text_address(p);
285  if (lib) {
286    type = code;
287  }
288
289  if (!lib) {
290    // Not a pointer into any text segment. Is it a function descriptor?
291    const FunctionDescriptor* const pfd = (const FunctionDescriptor*) p;
292    p = pfd->entry();
293    if (p) {
294      lib = LoadedLibraries::find_for_text_address(p);
295      if (lib) {
296        type = code;
297      }
298    }
299  }
300
301  if (!lib) {
302    // Neither direct code pointer nor function descriptor. A data ptr?
303    p = (address)addr;
304    lib = LoadedLibraries::find_for_data_address(p);
305    if (lib) {
306      type = data;
307    }
308  }
309
310  // If we did find the shared library this address belongs to (either
311  // code or data segment) resolve library path and, if possible, the
312  // symbol name.
313  if (lib) {
314    const char* const interned_libpath =
315      dladdr_fixed_strings.intern(lib->get_fullpath());
316    if (interned_libpath) {
317      info->dli_fname = interned_libpath;
318    }
319
320    if (type == code) {
321
322      // For code symbols resolve function name and displacement. Use
323      // displacement to calc start of function.
324      char funcname[256] = "";
325      int displacement = 0;
326
327      if (getFuncName((codeptr_t) p, funcname, sizeof(funcname), &displacement,
328                      NULL, NULL, 0) == 0) {
329        if (funcname[0] != '\0') {
330          const char* const interned = dladdr_fixed_strings.intern(funcname);
331          info->dli_sname = interned;
332          trcVerbose("... function name: %s ...", interned);
333        }
334
335        // From the displacement calculate the start of the function.
336        if (displacement != -1) {
337          info->dli_saddr = p - displacement;
338        } else {
339          info->dli_saddr = p;
340        }
341      } else {
342
343        // No traceback table found. Just assume the pointer is it.
344        info->dli_saddr = p;
345
346      }
347
348    } else if (type == data) {
349
350      // For data symbols.
351      info->dli_saddr = p;
352
353    } else {
354      ShouldNotReachHere();
355    }
356
357    rc = 1; // success: return 1 [sic]
358
359  }
360
361  // sanity checks.
362  if (rc) {
363    assert(info->dli_fname, "");
364    assert(info->dli_sname, "");
365    assert(info->dli_saddr, "");
366  }
367
368  return rc; // error: return 0 [sic]
369
370}
371