porting_aix.cpp revision 13200:54010cf75b26
1/*
2 * Copyright (c) 2012, 2013 SAP SE. 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 "compiler/disassembler.hpp"
27#include "loadlib_aix.hpp"
28#include "memory/allocation.hpp"
29#include "memory/allocation.inline.hpp"
30#include "misc_aix.hpp"
31#include "porting_aix.hpp"
32#include "runtime/os.hpp"
33#include "runtime/thread.hpp"
34#include "utilities/debug.hpp"
35
36#include <demangle.h>
37#include <sys/debug.h>
38#include <pthread.h>
39#include <ucontext.h>
40
41//////////////////////////////////
42// Provide implementation for dladdr based on LoadedLibraries pool and
43// traceback table scan
44
45// Search traceback table in stack,
46// return procedure name from trace back table.
47#define MAX_FUNC_SEARCH_LEN 0x10000
48
49#define PTRDIFF_BYTES(p1,p2) (((ptrdiff_t)p1) - ((ptrdiff_t)p2))
50
51// Typedefs for stackslots, stack pointers, pointers to op codes.
52typedef unsigned long stackslot_t;
53typedef stackslot_t* stackptr_t;
54typedef unsigned int* codeptr_t;
55
56// Unfortunately, the interface of dladdr makes the implementator
57// responsible for maintaining memory for function name/library
58// name. I guess this is because most OS's keep those values as part
59// of the mapped executable image ready to use. On AIX, this doesn't
60// work, so I have to keep the returned strings. For now, I do this in
61// a primitive string map. Should this turn out to be a performance
62// problem, a better hashmap has to be used.
63class fixed_strings {
64  struct node : public CHeapObj<mtInternal> {
65    char* v;
66    node* next;
67  };
68
69  node* first;
70
71  public:
72
73  fixed_strings() : first(0) {}
74  ~fixed_strings() {
75    node* n = first;
76    while (n) {
77      node* p = n;
78      n = n->next;
79      os::free(p->v);
80      delete p;
81    }
82  }
83
84  char* intern(const char* s) {
85    for (node* n = first; n; n = n->next) {
86      if (strcmp(n->v, s) == 0) {
87        return n->v;
88      }
89    }
90    node* p = new node;
91    p->v = os::strdup_check_oom(s);
92    p->next = first;
93    first = p;
94    return p->v;
95  }
96};
97
98static fixed_strings dladdr_fixed_strings;
99
100bool AixSymbols::get_function_name (
101    address pc0,                     // [in] program counter
102    char* p_name, size_t namelen,    // [out] optional: function name ("" if not available)
103    int* p_displacement,             // [out] optional: displacement (-1 if not available)
104    const struct tbtable** p_tb,     // [out] optional: ptr to traceback table to get further
105                                     //                 information (NULL if not available)
106    bool demangle                    // [in] whether to demangle the name
107  ) {
108  struct tbtable* tb = 0;
109  unsigned int searchcount = 0;
110
111  // initialize output parameters
112  if (p_name && namelen > 0) {
113    *p_name = '\0';
114  }
115  if (p_displacement) {
116    *p_displacement = -1;
117  }
118  if (p_tb) {
119    *p_tb = NULL;
120  }
121
122  codeptr_t pc = (codeptr_t)pc0;
123
124  // weed out obvious bogus states
125  if (pc < (codeptr_t)0x1000) {
126    trcVerbose("invalid program counter");
127    return false;
128  }
129
130  // We see random but frequent crashes in this function since some months mainly on shutdown
131  // (-XX:+DumpInfoAtExit). It appears the page we are reading is randomly disappearing while
132  // we read it (?).
133  // As the pc cannot be trusted to be anything sensible lets make all reads via SafeFetch. Also
134  // bail if this is not a text address right now.
135  if (!LoadedLibraries::find_for_text_address(pc, NULL)) {
136    trcVerbose("not a text address");
137    return false;
138  }
139
140  // .. (Note that is_readable_pointer returns true if safefetch stubs are not there yet;
141  // in that case I try reading the traceback table unsafe - I rather risk secondary crashes in
142  // error files than not having a callstack.)
143#define CHECK_POINTER_READABLE(p) \
144  if (!MiscUtils::is_readable_pointer(p)) { \
145    trcVerbose("pc not readable"); \
146    return false; \
147  }
148
149  codeptr_t pc2 = (codeptr_t) pc;
150
151  // Make sure the pointer is word aligned.
152  pc2 = (codeptr_t) align_ptr_up((char*)pc2, 4);
153  CHECK_POINTER_READABLE(pc2)
154
155  // Find start of traceback table.
156  // (starts after code, is marked by word-aligned (32bit) zeros)
157  while ((*pc2 != NULL) && (searchcount++ < MAX_FUNC_SEARCH_LEN)) {
158    CHECK_POINTER_READABLE(pc2)
159    pc2++;
160  }
161  if (*pc2 != 0) {
162    trcVerbose("no traceback table found");
163    return false;
164  }
165  //
166  // Set up addressability to the traceback table
167  //
168  tb = (struct tbtable*) (pc2 + 1);
169
170  // Is this really a traceback table? No way to be sure but
171  // some indicators we can check.
172  if (tb->tb.lang >= 0xf && tb->tb.lang <= 0xfb) {
173    // Language specifiers, go from 0 (C) to 14 (Objective C).
174    // According to spec, 0xf-0xfa reserved, 0xfb-0xff reserved for ibm.
175    trcVerbose("no traceback table found");
176    return false;
177  }
178
179  // Existence of fields in the tbtable extension are contingent upon
180  // specific fields in the base table.  Check for their existence so
181  // that we can address the function name if it exists.
182  pc2 = (codeptr_t) tb +
183    sizeof(struct tbtable_short)/sizeof(int);
184  if (tb->tb.fixedparms != 0 || tb->tb.floatparms != 0)
185    pc2++;
186
187  CHECK_POINTER_READABLE(pc2)
188
189  if (tb->tb.has_tboff == TRUE) {
190
191    // I want to know the displacement
192    const unsigned int tb_offset = *pc2;
193    codeptr_t start_of_procedure =
194    (codeptr_t)(((char*)tb) - 4 - tb_offset);  // (-4 to omit leading 0000)
195
196    // Weed out the cases where we did find the wrong traceback table.
197    if (pc < start_of_procedure) {
198      trcVerbose("no traceback table found");
199      return false;
200    }
201
202    // return the displacement
203    if (p_displacement) {
204      (*p_displacement) = (int) PTRDIFF_BYTES(pc, start_of_procedure);
205    }
206
207    pc2++;
208  } else {
209    // return -1 for displacement
210    if (p_displacement) {
211      (*p_displacement) = -1;
212    }
213  }
214
215  if (tb->tb.int_hndl == TRUE)
216    pc2++;
217
218  if (tb->tb.has_ctl == TRUE)
219    pc2 += (*pc2) + 1; // don't care
220
221  CHECK_POINTER_READABLE(pc2)
222
223  //
224  // return function name if it exists.
225  //
226  if (p_name && namelen > 0) {
227    if (tb->tb.name_present) {
228      // Copy name from text because it may not be zero terminated.
229      const short l = MIN2<short>(*((short*)pc2), namelen - 1);
230      // Be very careful.
231      int i = 0; char* const p = (char*)pc2 + sizeof(short);
232      while (i < l && MiscUtils::is_readable_pointer(p + i)) {
233        p_name[i] = p[i];
234        i++;
235      }
236      p_name[i] = '\0';
237
238      // If it is a C++ name, try and demangle it using the Demangle interface (see demangle.h).
239      if (demangle) {
240        char* rest;
241        Name* const name = Demangle(p_name, rest);
242        if (name) {
243          const char* const demangled_name = name->Text();
244          if (demangled_name) {
245            strncpy(p_name, demangled_name, namelen-1);
246            p_name[namelen-1] = '\0';
247          }
248          delete name;
249        }
250      }
251    } else {
252      strncpy(p_name, "<nameless function>", namelen-1);
253      p_name[namelen-1] = '\0';
254    }
255  }
256
257  // Return traceback table, if user wants it.
258  if (p_tb) {
259    (*p_tb) = tb;
260  }
261
262  return true;
263
264}
265
266bool AixSymbols::get_module_name(address pc,
267                         char* p_name, size_t namelen) {
268
269  if (p_name && namelen > 0) {
270    p_name[0] = '\0';
271    loaded_module_t lm;
272    if (LoadedLibraries::find_for_text_address(pc, &lm) != NULL) {
273      strncpy(p_name, lm.shortname, namelen);
274      p_name[namelen - 1] = '\0';
275      return true;
276    }
277  }
278
279  return false;
280}
281
282// Special implementation of dladdr for Aix based on LoadedLibraries
283// Note: dladdr returns non-zero for ok, 0 for error!
284// Note: dladdr is not posix, but a non-standard GNU extension. So this tries to
285//   fulfill the contract of dladdr on Linux (see http://linux.die.net/man/3/dladdr)
286// Note: addr may be both an AIX function descriptor or a real code pointer
287//   to the entry of a function.
288extern "C"
289int dladdr(void* addr, Dl_info* info) {
290
291  if (!addr) {
292    return 0;
293  }
294
295  assert(info, "");
296
297  int rc = 0;
298
299  const char* const ZEROSTRING = "";
300
301  // Always return a string, even if a "" one. Linux dladdr manpage
302  // does not say anything about returning NULL
303  info->dli_fname = ZEROSTRING;
304  info->dli_sname = ZEROSTRING;
305  info->dli_saddr = NULL;
306
307  address p = (address) addr;
308  loaded_module_t lm;
309  bool found = false;
310
311  enum { noclue, code, data } type = noclue;
312
313  trcVerbose("dladdr(%p)...", p);
314
315  // Note: input address may be a function. I accept both a pointer to
316  // the entry of a function and a pointer to the function decriptor.
317  // (see ppc64 ABI)
318  found = LoadedLibraries::find_for_text_address(p, &lm);
319  if (found) {
320    type = code;
321  }
322
323  if (!found) {
324    // Not a pointer into any text segment. Is it a function descriptor?
325    const FunctionDescriptor* const pfd = (const FunctionDescriptor*) p;
326    p = pfd->entry();
327    if (p) {
328      found = LoadedLibraries::find_for_text_address(p, &lm);
329      if (found) {
330        type = code;
331      }
332    }
333  }
334
335  if (!found) {
336    // Neither direct code pointer nor function descriptor. A data ptr?
337    p = (address)addr;
338    found = LoadedLibraries::find_for_data_address(p, &lm);
339    if (found) {
340      type = data;
341    }
342  }
343
344  // If we did find the shared library this address belongs to (either
345  // code or data segment) resolve library path and, if possible, the
346  // symbol name.
347  if (found) {
348
349    // No need to intern the libpath, that one is already interned one layer below.
350    info->dli_fname = lm.path;
351
352    if (type == code) {
353
354      // For code symbols resolve function name and displacement. Use
355      // displacement to calc start of function.
356      char funcname[256] = "";
357      int displacement = 0;
358
359      if (AixSymbols::get_function_name(p, funcname, sizeof(funcname),
360                      &displacement, NULL, true)) {
361        if (funcname[0] != '\0') {
362          const char* const interned = dladdr_fixed_strings.intern(funcname);
363          info->dli_sname = interned;
364          trcVerbose("... function name: %s ...", interned);
365        }
366
367        // From the displacement calculate the start of the function.
368        if (displacement != -1) {
369          info->dli_saddr = p - displacement;
370        } else {
371          info->dli_saddr = p;
372        }
373      } else {
374
375        // No traceback table found. Just assume the pointer is it.
376        info->dli_saddr = p;
377
378      }
379
380    } else if (type == data) {
381
382      // For data symbols.
383      info->dli_saddr = p;
384
385    } else {
386      ShouldNotReachHere();
387    }
388
389    rc = 1; // success: return 1 [sic]
390
391  }
392
393  // sanity checks.
394  if (rc) {
395    assert(info->dli_fname, "");
396    assert(info->dli_sname, "");
397    assert(info->dli_saddr, "");
398  }
399
400  return rc; // error: return 0 [sic]
401
402}
403
404/////////////////////////////////////////////////////////////////////////////
405// Native callstack dumping
406
407// Print the traceback table for one stack frame.
408static void print_tbtable (outputStream* st, const struct tbtable* p_tb) {
409
410  if (p_tb == NULL) {
411    st->print("<null>");
412    return;
413  }
414
415  switch(p_tb->tb.lang) {
416    case TB_C: st->print("C"); break;
417    case TB_FORTRAN: st->print("FORTRAN"); break;
418    case TB_PASCAL: st->print("PASCAL"); break;
419    case TB_ADA: st->print("ADA"); break;
420    case TB_PL1: st->print("PL1"); break;
421    case TB_BASIC: st->print("BASIC"); break;
422    case TB_LISP: st->print("LISP"); break;
423    case TB_COBOL: st->print("COBOL"); break;
424    case TB_MODULA2: st->print("MODULA2"); break;
425    case TB_CPLUSPLUS: st->print("C++"); break;
426    case TB_RPG: st->print("RPG"); break;
427    case TB_PL8: st->print("PL8"); break;
428    case TB_ASM: st->print("ASM"); break;
429    case TB_HPJ: st->print("HPJ"); break;
430    default: st->print("unknown");
431  }
432  st->print(" ");
433
434  if (p_tb->tb.globallink) {
435    st->print("globallink ");
436  }
437  if (p_tb->tb.is_eprol) {
438    st->print("eprol ");
439  }
440  if (p_tb->tb.int_proc) {
441    st->print("int_proc ");
442  }
443  if (p_tb->tb.tocless) {
444    st->print("tocless ");
445  }
446  if (p_tb->tb.fp_present) {
447    st->print("fp_present ");
448  }
449  if (p_tb->tb.int_hndl) {
450    st->print("interrupt_handler ");
451  }
452  if (p_tb->tb.uses_alloca) {
453    st->print("uses_alloca ");
454  }
455  if (p_tb->tb.saves_cr) {
456    st->print("saves_cr ");
457  }
458  if (p_tb->tb.saves_lr) {
459    st->print("saves_lr ");
460  }
461  if (p_tb->tb.stores_bc) {
462    st->print("stores_bc ");
463  }
464  if (p_tb->tb.fixup) {
465    st->print("fixup ");
466  }
467  if (p_tb->tb.fpr_saved > 0) {
468    st->print("fpr_saved:%d ", p_tb->tb.fpr_saved);
469  }
470  if (p_tb->tb.gpr_saved > 0) {
471    st->print("gpr_saved:%d ", p_tb->tb.gpr_saved);
472  }
473  if (p_tb->tb.fixedparms > 0) {
474    st->print("fixedparms:%d ", p_tb->tb.fixedparms);
475  }
476  if (p_tb->tb.floatparms > 0) {
477    st->print("floatparms:%d ", p_tb->tb.floatparms);
478  }
479  if (p_tb->tb.parmsonstk > 0) {
480    st->print("parmsonstk:%d", p_tb->tb.parmsonstk);
481  }
482}
483
484// Print information for pc (module, function, displacement, traceback table)
485// on one line.
486static void print_info_for_pc (outputStream* st, codeptr_t pc, char* buf,
487                               size_t buf_size, bool demangle) {
488  const struct tbtable* tb = NULL;
489  int displacement = -1;
490
491  if (!MiscUtils::is_readable_pointer(pc)) {
492    st->print("(invalid)");
493    return;
494  }
495
496  if (AixSymbols::get_module_name((address)pc, buf, buf_size)) {
497    st->print("%s", buf);
498  } else {
499    st->print("(unknown module)");
500  }
501  st->print("::");
502  if (AixSymbols::get_function_name((address)pc, buf, buf_size,
503                                     &displacement, &tb, demangle)) {
504    st->print("%s", buf);
505  } else {
506    st->print("(unknown function)");
507  }
508  if (displacement == -1) {
509    st->print("+?");
510  } else {
511    st->print("+0x%x", displacement);
512  }
513  if (tb) {
514    st->fill_to(64);
515    st->print("  (");
516    print_tbtable(st, tb);
517    st->print(")");
518  }
519}
520
521static void print_stackframe(outputStream* st, stackptr_t sp, char* buf,
522                             size_t buf_size, bool demangle) {
523
524  stackptr_t sp2 = sp;
525
526  // skip backchain
527
528  sp2++;
529
530  // skip crsave
531
532  sp2++;
533
534  // retrieve lrsave. That is the only info I need to get the function/displacement
535
536  codeptr_t lrsave = (codeptr_t) *(sp2);
537  st->print (PTR64_FORMAT " - " PTR64_FORMAT " ", sp2, lrsave);
538
539  if (lrsave != NULL) {
540    print_info_for_pc(st, lrsave, buf, buf_size, demangle);
541  }
542
543}
544
545// Function to check a given stack pointer against given stack limits.
546static bool is_valid_stackpointer(stackptr_t sp, stackptr_t stack_base, size_t stack_size) {
547  if (((uintptr_t)sp) & 0x7) {
548    return false;
549  }
550  if (sp > stack_base) {
551    return false;
552  }
553  if (sp < (stackptr_t) ((address)stack_base - stack_size)) {
554    return false;
555  }
556  return true;
557}
558
559// Returns true if function is a valid codepointer.
560static bool is_valid_codepointer(codeptr_t p) {
561  if (!p) {
562    return false;
563  }
564  if (((uintptr_t)p) & 0x3) {
565    return false;
566  }
567  if (LoadedLibraries::find_for_text_address(p, NULL) == NULL) {
568    return false;
569  }
570  return true;
571}
572
573// Function tries to guess if the given combination of stack pointer, stack base
574// and stack size is a valid stack frame.
575static bool is_valid_frame (stackptr_t p, stackptr_t stack_base, size_t stack_size) {
576
577  if (!is_valid_stackpointer(p, stack_base, stack_size)) {
578    return false;
579  }
580
581  // First check - the occurrence of a valid backchain pointer up the stack, followed by a
582  // valid codeptr, counts as a good candidate.
583  stackptr_t sp2 = (stackptr_t) *p;
584  if (is_valid_stackpointer(sp2, stack_base, stack_size) && // found a valid stack pointer in the stack...
585     ((sp2 - p) > 6) &&  // ... pointing upwards and not into my frame...
586     is_valid_codepointer((codeptr_t)(*(sp2 + 2)))) // ... followed by a code pointer after two slots...
587  {
588    return true;
589  }
590
591  return false;
592}
593
594// Try to relocate a stack back chain in a given stack.
595// Used in callstack dumping, when the backchain is broken by an overwriter
596static stackptr_t try_find_backchain (stackptr_t last_known_good_frame,
597                                      stackptr_t stack_base, size_t stack_size)
598{
599  if (!is_valid_stackpointer(last_known_good_frame, stack_base, stack_size)) {
600    return NULL;
601  }
602
603  stackptr_t sp = last_known_good_frame;
604
605  sp += 6; // Omit next fixed frame slots.
606  while (sp < stack_base) {
607    if (is_valid_frame(sp, stack_base, stack_size)) {
608      return sp;
609    }
610    sp ++;
611  }
612
613  return NULL;
614}
615
616static void decode_instructions_at_pc(const char* header,
617                                      codeptr_t pc, int num_before,
618                                      int num_after, outputStream* st) {
619  // TODO: PPC port Disassembler::decode(pc, 16, 16, st);
620}
621
622
623void AixNativeCallstack::print_callstack_for_context(outputStream* st, const ucontext_t* context,
624                                                     bool demangle, char* buf, size_t buf_size) {
625
626#define MAX_CALLSTACK_DEPTH 50
627
628  unsigned long* sp;
629  unsigned long* sp_last;
630  int frame;
631
632  // To print the first frame, use the current value of iar:
633  // current entry indicated by iar (the current pc)
634  codeptr_t cur_iar = 0;
635  stackptr_t cur_sp = 0;
636  codeptr_t cur_rtoc = 0;
637  codeptr_t cur_lr = 0;
638
639  const ucontext_t* uc = (const ucontext_t*) context;
640
641  // fallback: use the current context
642  ucontext_t local_context;
643  if (!uc) {
644    st->print_cr("No context given, using current context.");
645    if (getcontext(&local_context) == 0) {
646      uc = &local_context;
647    } else {
648      st->print_cr("No context given and getcontext failed. ");
649      return;
650    }
651  }
652
653  cur_iar = (codeptr_t)uc->uc_mcontext.jmp_context.iar;
654  cur_sp = (stackptr_t)uc->uc_mcontext.jmp_context.gpr[1];
655  cur_rtoc = (codeptr_t)uc->uc_mcontext.jmp_context.gpr[2];
656  cur_lr = (codeptr_t)uc->uc_mcontext.jmp_context.lr;
657
658  // syntax used here:
659  //  n   --------------   <-- stack_base,   stack_to
660  //  n-1 |            |
661  //  ... | older      |
662  //  ... |   frames   | |
663  //      |            | | stack grows downward
664  //  ... | younger    | |
665  //  ... |   frames   | V
666  //      |            |
667  //      |------------|   <-- cur_sp, current stack ptr
668  //      |            |
669  //      |  unsused   |
670  //      |    stack   |
671  //      |            |
672  //      .            .
673  //      .            .
674  //      .            .
675  //      .            .
676  //      |            |
677  //   0  --------------   <-- stack_from
678  //
679
680  // Retrieve current stack base, size from the current thread. If there is none,
681  // retrieve it from the OS.
682  stackptr_t stack_base = NULL;
683  size_t stack_size = NULL;
684  {
685    AixMisc::stackbounds_t stackbounds;
686    if (!AixMisc::query_stack_bounds_for_current_thread(&stackbounds)) {
687      st->print_cr("Cannot retrieve stack bounds.");
688      return;
689    }
690    stack_base = (stackptr_t)stackbounds.base;
691    stack_size = stackbounds.size;
692  }
693
694  st->print_cr("------ current frame:");
695  st->print("iar:  " PTR64_FORMAT " ", p2i(cur_iar));
696  print_info_for_pc(st, cur_iar, buf, buf_size, demangle);
697  st->cr();
698
699  if (cur_iar && MiscUtils::is_readable_pointer(cur_iar)) {
700    decode_instructions_at_pc(
701      "Decoded instructions at iar:",
702      cur_iar, 32, 16, st);
703  }
704
705  // Print out lr too, which may be interesting if we did jump to some bogus location;
706  // in those cases the new frame is not built up yet and the caller location is only
707  // preserved via lr register.
708  st->print("lr:   " PTR64_FORMAT " ", p2i(cur_lr));
709  print_info_for_pc(st, cur_lr, buf, buf_size, demangle);
710  st->cr();
711
712  if (cur_lr && MiscUtils::is_readable_pointer(cur_lr)) {
713    decode_instructions_at_pc(
714      "Decoded instructions at lr:",
715      cur_lr, 32, 16, st);
716  }
717
718  // Check and print sp.
719  st->print("sp:   " PTR64_FORMAT " ", p2i(cur_sp));
720  if (!is_valid_stackpointer(cur_sp, stack_base, stack_size)) {
721    st->print("(invalid) ");
722    goto cleanup;
723  } else {
724    st->print("(base - 0x%X) ", PTRDIFF_BYTES(stack_base, cur_sp));
725  }
726  st->cr();
727
728  // Check and print rtoc.
729  st->print("rtoc: "  PTR64_FORMAT " ", p2i(cur_rtoc));
730  if (cur_rtoc == NULL || cur_rtoc == (codeptr_t)-1 ||
731      !MiscUtils::is_readable_pointer(cur_rtoc)) {
732    st->print("(invalid)");
733  } else if (((uintptr_t)cur_rtoc) & 0x7) {
734    st->print("(unaligned)");
735  }
736  st->cr();
737
738  st->print_cr("|---stackaddr----|   |----lrsave------|:   <function name>");
739
740  ///
741  // Walk callstack.
742  //
743  // (if no context was given, use the current stack)
744  sp = (unsigned long*)(*(unsigned long*)cur_sp); // Stack pointer
745  sp_last = cur_sp;
746
747  frame = 0;
748
749  while (frame < MAX_CALLSTACK_DEPTH) {
750
751    // Check sp.
752    bool retry = false;
753    if (sp == NULL) {
754      // The backchain pointer was NULL. This normally means the end of the chain. But the
755      // stack might be corrupted, and it may be worth looking for the stack chain.
756      if (is_valid_stackpointer(sp_last, stack_base, stack_size) && (stack_base - 0x10) > sp_last) {
757        // If we are not within <guess> 0x10 stackslots of the stack base, we assume that this
758        // is indeed not the end of the chain but that the stack was corrupted. So lets try to
759        // find the end of the chain.
760        st->print_cr("*** back chain pointer is NULL - end of stack or broken backchain ? ***");
761        retry = true;
762      } else {
763        st->print_cr("*** end of backchain ***");
764        goto end_walk_callstack;
765      }
766    } else if (!is_valid_stackpointer(sp, stack_base, stack_size)) {
767      st->print_cr("*** stack pointer invalid - backchain corrupted (" PTR_FORMAT ") ***", p2i(sp));
768      retry = true;
769    } else if (sp < sp_last) {
770      st->print_cr("invalid stack pointer: " PTR_FORMAT " (not monotone raising)", p2i(sp));
771      retry = true;
772    }
773
774    // If backchain is broken, try to recover, by manually scanning the stack for a pattern
775    // which looks like a valid stack.
776    if (retry) {
777      st->print_cr("trying to recover and find backchain...");
778      sp = try_find_backchain(sp_last, stack_base, stack_size);
779      if (sp) {
780        st->print_cr("found something which looks like a backchain at " PTR64_FORMAT ", after 0x%x bytes... ",
781            p2i(sp), PTRDIFF_BYTES(sp, sp_last));
782      } else {
783        st->print_cr("did not find a backchain, giving up.");
784        goto end_walk_callstack;
785      }
786    }
787
788    // Print stackframe.
789    print_stackframe(st, sp, buf, buf_size, demangle);
790    st->cr();
791    frame ++;
792
793    // Next stack frame and link area.
794    sp_last = sp;
795    sp = (unsigned long*)(*sp);
796  }
797
798  // Prevent endless loops in case of invalid callstacks.
799  if (frame == MAX_CALLSTACK_DEPTH) {
800    st->print_cr("...(stopping after %d frames.", MAX_CALLSTACK_DEPTH);
801  }
802
803end_walk_callstack:
804
805  st->print_cr("-----------------------");
806
807cleanup:
808
809  return;
810
811}
812
813
814bool AixMisc::query_stack_bounds_for_current_thread(stackbounds_t* out) {
815
816  // Information about this api can be found (a) in the pthread.h header and
817  // (b) in http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf1/pthread_getthrds_np.htm
818  //
819  // The use of this API to find out the current stack is kind of undefined.
820  // But after a lot of tries and asking IBM about it, I concluded that it is safe
821  // enough for cases where I let the pthread library create its stacks. For cases
822  // where I create an own stack and pass this to pthread_create, it seems not to
823  // work (the returned stack size in that case is 0).
824
825  pthread_t tid = pthread_self();
826  struct __pthrdsinfo pinfo;
827  char dummy[1]; // Just needed to satisfy pthread_getthrds_np.
828  int dummy_size = sizeof(dummy);
829
830  memset(&pinfo, 0, sizeof(pinfo));
831
832  const int rc = pthread_getthrds_np(&tid, PTHRDSINFO_QUERY_ALL, &pinfo,
833                                     sizeof(pinfo), dummy, &dummy_size);
834
835  if (rc != 0) {
836    fprintf(stderr, "pthread_getthrds_np failed (%d)\n", rc);
837    fflush(stdout);
838    return false;
839  }
840
841  // The following may happen when invoking pthread_getthrds_np on a pthread
842  // running on a user provided stack (when handing down a stack to pthread
843  // create, see pthread_attr_setstackaddr).
844  // Not sure what to do then.
845  if (pinfo.__pi_stackend == NULL || pinfo.__pi_stackaddr == NULL) {
846    fprintf(stderr, "pthread_getthrds_np - invalid values\n");
847    fflush(stdout);
848    return false;
849  }
850
851  // Note: we get three values from pthread_getthrds_np:
852  //       __pi_stackaddr, __pi_stacksize, __pi_stackend
853  //
854  // high addr    ---------------------                                                           base, high
855  //
856  //    |         pthread internal data, like ~2K
857  //    |
858  //    |         ---------------------   __pi_stackend   (usually not page aligned, (xxxxF890))
859  //    |
860  //    |
861  //    |
862  //    |
863  //    |
864  //    |
865  //    |          ---------------------   (__pi_stackend - __pi_stacksize)
866  //    |
867  //    |          padding to align the following AIX guard pages, if enabled.
868  //    |
869  //    V          ---------------------   __pi_stackaddr                                        low, base - size
870  //
871  // low addr      AIX guard pages, if enabled (AIXTHREAD_GUARDPAGES > 0)
872  //
873
874  out->base = (address)pinfo.__pi_stackend;
875  address low = (address)pinfo.__pi_stackaddr;
876  out->size = out->base - low;
877  return true;
878
879}
880
881
882
883
884