1 /*
   2  * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2012, 2016 SAP SE. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 // no precompiled headers
  27 #include "asm/assembler.inline.hpp"
  28 #include "classfile/classLoader.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "classfile/vmSymbols.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "code/icBuffer.hpp"
  33 #include "code/vtableStubs.hpp"
  34 #include "interpreter/interpreter.hpp"
  35 #include "jvm_linux.h"
  36 #include "memory/allocation.inline.hpp"
  37 #include "mutex_linux.inline.hpp"
  38 #include "nativeInst_ppc.hpp"
  39 #include "os_share_linux.hpp"
  40 #include "prims/jniFastGetField.hpp"
  41 #include "prims/jvm.h"
  42 #include "prims/jvm_misc.hpp"
  43 #include "runtime/arguments.hpp"
  44 #include "runtime/extendedPC.hpp"
  45 #include "runtime/frame.inline.hpp"
  46 #include "runtime/interfaceSupport.hpp"
  47 #include "runtime/java.hpp"
  48 #include "runtime/javaCalls.hpp"
  49 #include "runtime/mutexLocker.hpp"
  50 #include "runtime/osThread.hpp"
  51 #include "runtime/sharedRuntime.hpp"
  52 #include "runtime/stubRoutines.hpp"
  53 #include "runtime/thread.inline.hpp"
  54 #include "runtime/timer.hpp"
  55 #include "utilities/events.hpp"
  56 #include "utilities/vmError.hpp"
  57 
  58 // put OS-includes here
  59 # include <sys/types.h>
  60 # include <sys/mman.h>
  61 # include <pthread.h>
  62 # include <signal.h>
  63 # include <errno.h>
  64 # include <dlfcn.h>
  65 # include <stdlib.h>
  66 # include <stdio.h>
  67 # include <unistd.h>
  68 # include <sys/resource.h>
  69 # include <pthread.h>
  70 # include <sys/stat.h>
  71 # include <sys/time.h>
  72 # include <sys/utsname.h>
  73 # include <sys/socket.h>
  74 # include <sys/wait.h>
  75 # include <pwd.h>
  76 # include <poll.h>
  77 # include <ucontext.h>
  78 
  79 
  80 address os::current_stack_pointer() {
  81   intptr_t* csp;
  82 
  83   // inline assembly `mr regno(csp), R1_SP':
  84   __asm__ __volatile__ ("mr %0, 1":"=r"(csp):);
  85 
  86   return (address) csp;
  87 }
  88 
  89 char* os::non_memory_address_word() {
  90   // Must never look like an address returned by reserve_memory,
  91   // even in its subfields (as defined by the CPU immediate fields,
  92   // if the CPU splits constants across multiple instructions).
  93 
  94   return (char*) -1;
  95 }
  96 
  97 void os::initialize_thread(Thread *thread) { }
  98 
  99 // Frame information (pc, sp, fp) retrieved via ucontext
 100 // always looks like a C-frame according to the frame
 101 // conventions in frame_ppc64.hpp.
 102 address os::Linux::ucontext_get_pc(const ucontext_t * uc) {
 103   // On powerpc64, ucontext_t is not selfcontained but contains
 104   // a pointer to an optional substructure (mcontext_t.regs) containing the volatile
 105   // registers - NIP, among others.
 106   // This substructure may or may not be there depending where uc came from:
 107   // - if uc was handed over as the argument to a sigaction handler, a pointer to the
 108   //   substructure was provided by the kernel when calling the signal handler, and
 109   //   regs->nip can be accessed.
 110   // - if uc was filled by getcontext(), it is undefined - getcontext() does not fill
 111   //   it because the volatile registers are not needed to make setcontext() work.
 112   //   Hopefully it was zero'd out beforehand.
 113   guarantee(uc->uc_mcontext.regs != NULL, "only use ucontext_get_pc in sigaction context");
 114   return (address)uc->uc_mcontext.regs->nip;
 115 }
 116 
 117 // modify PC in ucontext.
 118 // Note: Only use this for an ucontext handed down to a signal handler. See comment
 119 // in ucontext_get_pc.
 120 void os::Linux::ucontext_set_pc(ucontext_t * uc, address pc) {
 121   guarantee(uc->uc_mcontext.regs != NULL, "only use ucontext_set_pc in sigaction context");
 122   uc->uc_mcontext.regs->nip = (unsigned long)pc;
 123 }
 124 
 125 intptr_t* os::Linux::ucontext_get_sp(const ucontext_t * uc) {
 126   return (intptr_t*)uc->uc_mcontext.regs->gpr[1/*REG_SP*/];
 127 }
 128 
 129 intptr_t* os::Linux::ucontext_get_fp(const ucontext_t * uc) {
 130   return NULL;
 131 }
 132 
 133 ExtendedPC os::fetch_frame_from_context(const void* ucVoid,
 134                     intptr_t** ret_sp, intptr_t** ret_fp) {
 135 
 136   ExtendedPC  epc;
 137   const ucontext_t* uc = (const ucontext_t*)ucVoid;
 138 
 139   if (uc != NULL) {
 140     epc = ExtendedPC(os::Linux::ucontext_get_pc(uc));
 141     if (ret_sp) *ret_sp = os::Linux::ucontext_get_sp(uc);
 142     if (ret_fp) *ret_fp = os::Linux::ucontext_get_fp(uc);
 143   } else {
 144     // construct empty ExtendedPC for return value checking
 145     epc = ExtendedPC(NULL);
 146     if (ret_sp) *ret_sp = (intptr_t *)NULL;
 147     if (ret_fp) *ret_fp = (intptr_t *)NULL;
 148   }
 149 
 150   return epc;
 151 }
 152 
 153 frame os::fetch_frame_from_context(const void* ucVoid) {
 154   intptr_t* sp;
 155   intptr_t* fp;
 156   ExtendedPC epc = fetch_frame_from_context(ucVoid, &sp, &fp);
 157   return frame(sp, epc.pc());
 158 }
 159 
 160 bool os::Linux::get_frame_at_stack_banging_point(JavaThread* thread, ucontext_t* uc, frame* fr) {
 161   address pc = (address) os::Linux::ucontext_get_pc(uc);
 162   if (Interpreter::contains(pc)) {
 163     // Interpreter performs stack banging after the fixed frame header has
 164     // been generated while the compilers perform it before. To maintain
 165     // semantic consistency between interpreted and compiled frames, the
 166     // method returns the Java sender of the current frame.
 167     *fr = os::fetch_frame_from_context(uc);
 168     if (!fr->is_first_java_frame()) {
 169       assert(fr->safe_for_sender(thread), "Safety check");
 170       *fr = fr->java_sender();
 171     }
 172   } else {
 173     // More complex code with compiled code.
 174     assert(!Interpreter::contains(pc), "Interpreted methods should have been handled above");
 175     CodeBlob* cb = CodeCache::find_blob(pc);
 176     if (cb == NULL || !cb->is_nmethod() || cb->is_frame_complete_at(pc)) {
 177       // Not sure where the pc points to, fallback to default
 178       // stack overflow handling. In compiled code, we bang before
 179       // the frame is complete.
 180       return false;
 181     } else {
 182       intptr_t* fp = os::Linux::ucontext_get_fp(uc);
 183       intptr_t* sp = os::Linux::ucontext_get_sp(uc);
 184       *fr = frame(sp, (address)*sp);
 185       if (!fr->is_java_frame()) {
 186         assert(fr->safe_for_sender(thread), "Safety check");
 187         assert(!fr->is_first_frame(), "Safety check");
 188         *fr = fr->java_sender();
 189       }
 190     }
 191   }
 192   assert(fr->is_java_frame(), "Safety check");
 193   return true;
 194 }
 195 
 196 frame os::get_sender_for_C_frame(frame* fr) {
 197   if (*fr->sp() == 0) {
 198     // fr is the last C frame
 199     return frame(NULL, NULL);
 200   }
 201   return frame(fr->sender_sp(), fr->sender_pc());
 202 }
 203 
 204 
 205 frame os::current_frame() {
 206   intptr_t* csp = (intptr_t*) *((intptr_t*) os::current_stack_pointer());
 207   // hack.
 208   frame topframe(csp, (address)0x8);
 209   // return sender of current topframe which hopefully has pc != NULL.
 210   return os::get_sender_for_C_frame(&topframe);
 211 }
 212 
 213 // Utility functions
 214 
 215 extern "C" JNIEXPORT int
 216 JVM_handle_linux_signal(int sig,
 217                         siginfo_t* info,
 218                         void* ucVoid,
 219                         int abort_if_unrecognized) {
 220   ucontext_t* uc = (ucontext_t*) ucVoid;
 221 
 222   Thread* t = Thread::current_or_null_safe();
 223 
 224   SignalHandlerMark shm(t);
 225 
 226   // Note: it's not uncommon that JNI code uses signal/sigset to install
 227   // then restore certain signal handler (e.g. to temporarily block SIGPIPE,
 228   // or have a SIGILL handler when detecting CPU type). When that happens,
 229   // JVM_handle_linux_signal() might be invoked with junk info/ucVoid. To
 230   // avoid unnecessary crash when libjsig is not preloaded, try handle signals
 231   // that do not require siginfo/ucontext first.
 232 
 233   if (sig == SIGPIPE) {
 234     if (os::Linux::chained_handler(sig, info, ucVoid)) {
 235       return true;
 236     } else {
 237       // Ignoring SIGPIPE - see bugs 4229104
 238       return true;
 239     }
 240   }
 241 
 242   JavaThread* thread = NULL;
 243   VMThread* vmthread = NULL;
 244   if (os::Linux::signal_handlers_are_installed) {
 245     if (t != NULL) {
 246       if(t->is_Java_thread()) {
 247         thread = (JavaThread*)t;
 248       } else if(t->is_VM_thread()) {
 249         vmthread = (VMThread *)t;
 250       }
 251     }
 252   }
 253 
 254   // Moved SafeFetch32 handling outside thread!=NULL conditional block to make
 255   // it work if no associated JavaThread object exists.
 256   if (uc) {
 257     address const pc = os::Linux::ucontext_get_pc(uc);
 258     if (pc && StubRoutines::is_safefetch_fault(pc)) {
 259       os::Linux::ucontext_set_pc(uc, StubRoutines::continuation_for_safefetch_fault(pc));
 260       return true;
 261     }
 262   }
 263 
 264   // decide if this trap can be handled by a stub
 265   address stub = NULL;
 266   address pc   = NULL;
 267 
 268   //%note os_trap_1
 269   if (info != NULL && uc != NULL && thread != NULL) {
 270     pc = (address) os::Linux::ucontext_get_pc(uc);
 271 
 272     // Handle ALL stack overflow variations here
 273     if (sig == SIGSEGV) {
 274       // Si_addr may not be valid due to a bug in the linux-ppc64 kernel (see
 275       // comment below). Use get_stack_bang_address instead of si_addr.
 276       address addr = ((NativeInstruction*)pc)->get_stack_bang_address(uc);
 277 
 278       // Check if fault address is within thread stack.
 279       if (thread->on_local_stack(addr)) {
 280         // stack overflow
 281         if (thread->in_stack_yellow_reserved_zone(addr)) {
 282           if (thread->thread_state() == _thread_in_Java) {
 283             if (thread->in_stack_reserved_zone(addr)) {
 284               frame fr;
 285               if (os::Linux::get_frame_at_stack_banging_point(thread, uc, &fr)) {
 286                 assert(fr.is_java_frame(), "Must be a Javac frame");
 287                 frame activation =
 288                   SharedRuntime::look_for_reserved_stack_annotated_method(thread, fr);
 289                 if (activation.sp() != NULL) {
 290                   thread->disable_stack_reserved_zone();
 291                   if (activation.is_interpreted_frame()) {
 292                     thread->set_reserved_stack_activation((address)activation.fp());
 293                   } else {
 294                     thread->set_reserved_stack_activation((address)activation.unextended_sp());
 295                   }
 296                   return 1;
 297                 }
 298               }
 299             }
 300             // Throw a stack overflow exception.
 301             // Guard pages will be reenabled while unwinding the stack.
 302             thread->disable_stack_yellow_reserved_zone();
 303             stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW);
 304           } else {
 305             // Thread was in the vm or native code. Return and try to finish.
 306             thread->disable_stack_yellow_reserved_zone();
 307             return 1;
 308           }
 309         } else if (thread->in_stack_red_zone(addr)) {
 310           // Fatal red zone violation.  Disable the guard pages and fall through
 311           // to handle_unexpected_exception way down below.
 312           thread->disable_stack_red_zone();
 313           tty->print_raw_cr("An irrecoverable stack overflow has occurred.");
 314 
 315           // This is a likely cause, but hard to verify. Let's just print
 316           // it as a hint.
 317           tty->print_raw_cr("Please check if any of your loaded .so files has "
 318                             "enabled executable stack (see man page execstack(8))");
 319         } else {
 320           // Accessing stack address below sp may cause SEGV if current
 321           // thread has MAP_GROWSDOWN stack. This should only happen when
 322           // current thread was created by user code with MAP_GROWSDOWN flag
 323           // and then attached to VM. See notes in os_linux.cpp.
 324           if (thread->osthread()->expanding_stack() == 0) {
 325              thread->osthread()->set_expanding_stack();
 326              if (os::Linux::manually_expand_stack(thread, addr)) {
 327                thread->osthread()->clear_expanding_stack();
 328                return 1;
 329              }
 330              thread->osthread()->clear_expanding_stack();
 331           } else {
 332              fatal("recursive segv. expanding stack.");
 333           }
 334         }
 335       }
 336     }
 337 
 338     if (thread->thread_state() == _thread_in_Java) {
 339       // Java thread running in Java code => find exception handler if any
 340       // a fault inside compiled code, the interpreter, or a stub
 341 
 342       // A VM-related SIGILL may only occur if we are not in the zero page.
 343       // On AIX, we get a SIGILL if we jump to 0x0 or to somewhere else
 344       // in the zero page, because it is filled with 0x0. We ignore
 345       // explicit SIGILLs in the zero page.
 346       if (sig == SIGILL && (pc < (address) 0x200)) {
 347         if (TraceTraps) {
 348           tty->print_raw_cr("SIGILL happened inside zero page.");
 349         }
 350         goto report_and_die;
 351       }
 352 
 353       CodeBlob *cb = NULL;
 354       // Handle signal from NativeJump::patch_verified_entry().
 355       if (( TrapBasedNotEntrantChecks && sig == SIGTRAP && nativeInstruction_at(pc)->is_sigtrap_zombie_not_entrant()) ||
 356           (!TrapBasedNotEntrantChecks && sig == SIGILL  && nativeInstruction_at(pc)->is_sigill_zombie_not_entrant())) {
 357         if (TraceTraps) {
 358           tty->print_cr("trap: zombie_not_entrant (%s)", (sig == SIGTRAP) ? "SIGTRAP" : "SIGILL");
 359         }
 360         stub = SharedRuntime::get_handle_wrong_method_stub();
 361       }
 362 
 363       else if (sig == SIGSEGV &&
 364                // A linux-ppc64 kernel before 2.6.6 doesn't set si_addr on some segfaults
 365                // in 64bit mode (cf. http://www.kernel.org/pub/linux/kernel/v2.6/ChangeLog-2.6.6),
 366                // especially when we try to read from the safepoint polling page. So the check
 367                //   (address)info->si_addr == os::get_standard_polling_page()
 368                // doesn't work for us. We use:
 369                ((NativeInstruction*)pc)->is_safepoint_poll() &&
 370                CodeCache::contains((void*) pc) &&
 371                ((cb = CodeCache::find_blob(pc)) != NULL) &&
 372                cb->is_compiled()) {
 373         if (TraceTraps) {
 374           tty->print_cr("trap: safepoint_poll at " INTPTR_FORMAT " (SIGSEGV)", p2i(pc));
 375         }
 376         stub = SharedRuntime::get_poll_stub(pc);
 377       }
 378 
 379       // SIGTRAP-based ic miss check in compiled code.
 380       else if (sig == SIGTRAP && TrapBasedICMissChecks &&
 381                nativeInstruction_at(pc)->is_sigtrap_ic_miss_check()) {
 382         if (TraceTraps) {
 383           tty->print_cr("trap: ic_miss_check at " INTPTR_FORMAT " (SIGTRAP)", p2i(pc));
 384         }
 385         stub = SharedRuntime::get_ic_miss_stub();
 386       }
 387 
 388       // SIGTRAP-based implicit null check in compiled code.
 389       else if (sig == SIGTRAP && TrapBasedNullChecks &&
 390                nativeInstruction_at(pc)->is_sigtrap_null_check()) {
 391         if (TraceTraps) {
 392           tty->print_cr("trap: null_check at " INTPTR_FORMAT " (SIGTRAP)", p2i(pc));
 393         }
 394         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
 395       }
 396 
 397       // SIGSEGV-based implicit null check in compiled code.
 398       else if (sig == SIGSEGV && ImplicitNullChecks &&
 399                CodeCache::contains((void*) pc) &&
 400                !MacroAssembler::needs_explicit_null_check((intptr_t) info->si_addr)) {
 401         if (TraceTraps) {
 402           tty->print_cr("trap: null_check at " INTPTR_FORMAT " (SIGSEGV)", p2i(pc));
 403         }
 404         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
 405       }
 406 
 407 #ifdef COMPILER2
 408       // SIGTRAP-based implicit range check in compiled code.
 409       else if (sig == SIGTRAP && TrapBasedRangeChecks &&
 410                nativeInstruction_at(pc)->is_sigtrap_range_check()) {
 411         if (TraceTraps) {
 412           tty->print_cr("trap: range_check at " INTPTR_FORMAT " (SIGTRAP)", p2i(pc));
 413         }
 414         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
 415       }
 416 #endif
 417       else if (sig == SIGBUS) {
 418         // BugId 4454115: A read from a MappedByteBuffer can fault here if the
 419         // underlying file has been truncated. Do not crash the VM in such a case.
 420         CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
 421         CompiledMethod* nm = (cb != NULL) ? cb->as_compiled_method_or_null() : NULL;
 422         if (nm != NULL && nm->has_unsafe_access()) {
 423           address next_pc = pc + 4;
 424           next_pc = SharedRuntime::handle_unsafe_access(thread, next_pc);
 425           os::Linux::ucontext_set_pc(uc, next_pc);
 426           return true;
 427         }
 428       }
 429     }
 430 
 431     else { // thread->thread_state() != _thread_in_Java
 432       if (sig == SIGILL && VM_Version::is_determine_features_test_running()) {
 433         // SIGILL must be caused by VM_Version::determine_features().
 434         *(int *)pc = 0; // patch instruction to 0 to indicate that it causes a SIGILL,
 435                         // flushing of icache is not necessary.
 436         stub = pc + 4;  // continue with next instruction.
 437       }
 438       else if (thread->thread_state() == _thread_in_vm &&
 439                sig == SIGBUS && thread->doing_unsafe_access()) {
 440         address next_pc = pc + 4;
 441         next_pc = SharedRuntime::handle_unsafe_access(thread, next_pc);
 442         os::Linux::ucontext_set_pc(uc, pc + 4);
 443         return true;
 444       }
 445     }
 446 
 447     // Check to see if we caught the safepoint code in the
 448     // process of write protecting the memory serialization page.
 449     // It write enables the page immediately after protecting it
 450     // so we can just return to retry the write.
 451     if ((sig == SIGSEGV) &&
 452         // Si_addr may not be valid due to a bug in the linux-ppc64 kernel (see comment above).
 453         // Use is_memory_serialization instead of si_addr.
 454         ((NativeInstruction*)pc)->is_memory_serialization(thread, ucVoid)) {
 455       // Synchronization problem in the pseudo memory barrier code (bug id 6546278)
 456       // Block current thread until the memory serialize page permission restored.
 457       os::block_on_serialize_page_trap();
 458       return true;
 459     }
 460   }
 461 
 462   if (stub != NULL) {
 463     // Save all thread context in case we need to restore it.
 464     if (thread != NULL) thread->set_saved_exception_pc(pc);
 465     os::Linux::ucontext_set_pc(uc, stub);
 466     return true;
 467   }
 468 
 469   // signal-chaining
 470   if (os::Linux::chained_handler(sig, info, ucVoid)) {
 471     return true;
 472   }
 473 
 474   if (!abort_if_unrecognized) {
 475     // caller wants another chance, so give it to him
 476     return false;
 477   }
 478 
 479   if (pc == NULL && uc != NULL) {
 480     pc = os::Linux::ucontext_get_pc(uc);
 481   }
 482 
 483 report_and_die:
 484   // unmask current signal
 485   sigset_t newset;
 486   sigemptyset(&newset);
 487   sigaddset(&newset, sig);
 488   sigprocmask(SIG_UNBLOCK, &newset, NULL);
 489 
 490   VMError::report_and_die(t, sig, pc, info, ucVoid);
 491 
 492   ShouldNotReachHere();
 493   return false;
 494 }
 495 
 496 void os::Linux::init_thread_fpu_state(void) {
 497   // Disable FP exceptions.
 498   __asm__ __volatile__ ("mtfsfi 6,0");
 499 }
 500 
 501 int os::Linux::get_fpu_control_word(void) {
 502   // x86 has problems with FPU precision after pthread_cond_timedwait().
 503   // nothing to do on ppc64.
 504   return 0;
 505 }
 506 
 507 void os::Linux::set_fpu_control_word(int fpu_control) {
 508   // x86 has problems with FPU precision after pthread_cond_timedwait().
 509   // nothing to do on ppc64.
 510 }
 511 
 512 ////////////////////////////////////////////////////////////////////////////////
 513 // thread stack
 514 
 515 size_t os::Linux::min_stack_allowed = 128*K;
 516 
 517 // return default stack size for thr_type
 518 size_t os::Linux::default_stack_size(os::ThreadType thr_type) {
 519   // default stack size (compiler thread needs larger stack)
 520   // Notice that the setting for compiler threads here have no impact
 521   // because of the strange 'fallback logic' in os::create_thread().
 522   // Better set CompilerThreadStackSize in globals_<os_cpu>.hpp if you want to
 523   // specify a different stack size for compiler threads!
 524   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1024 * K);
 525   return s;
 526 }
 527 
 528 size_t os::Linux::default_guard_size(os::ThreadType thr_type) {
 529   return 2 * page_size();
 530 }
 531 
 532 // Java thread:
 533 //
 534 //   Low memory addresses
 535 //    +------------------------+
 536 //    |                        |\  JavaThread created by VM does not have glibc
 537 //    |    glibc guard page    | - guard, attached Java thread usually has
 538 //    |                        |/  1 page glibc guard.
 539 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
 540 //    |                        |\
 541 //    |  HotSpot Guard Pages   | - red and yellow pages
 542 //    |                        |/
 543 //    +------------------------+ JavaThread::stack_yellow_zone_base()
 544 //    |                        |\
 545 //    |      Normal Stack      | -
 546 //    |                        |/
 547 // P2 +------------------------+ Thread::stack_base()
 548 //
 549 // Non-Java thread:
 550 //
 551 //   Low memory addresses
 552 //    +------------------------+
 553 //    |                        |\
 554 //    |  glibc guard page      | - usually 1 page
 555 //    |                        |/
 556 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
 557 //    |                        |\
 558 //    |      Normal Stack      | -
 559 //    |                        |/
 560 // P2 +------------------------+ Thread::stack_base()
 561 //
 562 // ** P1 (aka bottom) and size ( P2 = P1 - size) are the address and stack size returned from
 563 //    pthread_attr_getstack()
 564 
 565 static void current_stack_region(address * bottom, size_t * size) {
 566   if (os::Linux::is_initial_thread()) {
 567      // initial thread needs special handling because pthread_getattr_np()
 568      // may return bogus value.
 569     *bottom = os::Linux::initial_thread_stack_bottom();
 570     *size   = os::Linux::initial_thread_stack_size();
 571   } else {
 572     pthread_attr_t attr;
 573 
 574     int rslt = pthread_getattr_np(pthread_self(), &attr);
 575 
 576     // JVM needs to know exact stack location, abort if it fails
 577     if (rslt != 0) {
 578       if (rslt == ENOMEM) {
 579         vm_exit_out_of_memory(0, OOM_MMAP_ERROR, "pthread_getattr_np");
 580       } else {
 581         fatal("pthread_getattr_np failed with errno = %d", rslt);
 582       }
 583     }
 584 
 585     if (pthread_attr_getstack(&attr, (void **)bottom, size) != 0) {
 586       fatal("Can not locate current stack attributes!");
 587     }
 588 
 589     pthread_attr_destroy(&attr);
 590 
 591   }
 592   assert(os::current_stack_pointer() >= *bottom &&
 593          os::current_stack_pointer() < *bottom + *size, "just checking");
 594 }
 595 
 596 address os::current_stack_base() {
 597   address bottom;
 598   size_t size;
 599   current_stack_region(&bottom, &size);
 600   return (bottom + size);
 601 }
 602 
 603 size_t os::current_stack_size() {
 604   // stack size includes normal stack and HotSpot guard pages
 605   address bottom;
 606   size_t size;
 607   current_stack_region(&bottom, &size);
 608   return size;
 609 }
 610 
 611 /////////////////////////////////////////////////////////////////////////////
 612 // helper functions for fatal error handler
 613 
 614 void os::print_context(outputStream *st, const void *context) {
 615   if (context == NULL) return;
 616 
 617   const ucontext_t* uc = (const ucontext_t*)context;
 618 
 619   st->print_cr("Registers:");
 620   st->print("pc =" INTPTR_FORMAT "  ", uc->uc_mcontext.regs->nip);
 621   st->print("lr =" INTPTR_FORMAT "  ", uc->uc_mcontext.regs->link);
 622   st->print("ctr=" INTPTR_FORMAT "  ", uc->uc_mcontext.regs->ctr);
 623   st->cr();
 624   for (int i = 0; i < 32; i++) {
 625     st->print("r%-2d=" INTPTR_FORMAT "  ", i, uc->uc_mcontext.regs->gpr[i]);
 626     if (i % 3 == 2) st->cr();
 627   }
 628   st->cr();
 629   st->cr();
 630 
 631   intptr_t *sp = (intptr_t *)os::Linux::ucontext_get_sp(uc);
 632   st->print_cr("Top of Stack: (sp=" PTR_FORMAT ")", p2i(sp));
 633   print_hex_dump(st, (address)sp, (address)(sp + 128), sizeof(intptr_t));
 634   st->cr();
 635 
 636   // Note: it may be unsafe to inspect memory near pc. For example, pc may
 637   // point to garbage if entry point in an nmethod is corrupted. Leave
 638   // this at the end, and hope for the best.
 639   address pc = os::Linux::ucontext_get_pc(uc);
 640   st->print_cr("Instructions: (pc=" PTR_FORMAT ")", p2i(pc));
 641   print_hex_dump(st, pc - 64, pc + 64, /*instrsize=*/4);
 642   st->cr();
 643 }
 644 
 645 void os::print_register_info(outputStream *st, const void *context) {
 646   if (context == NULL) return;
 647 
 648   const ucontext_t *uc = (const ucontext_t*)context;
 649 
 650   st->print_cr("Register to memory mapping:");
 651   st->cr();
 652 
 653   // this is only for the "general purpose" registers
 654   for (int i = 0; i < 32; i++) {
 655     st->print("r%-2d=", i);
 656     print_location(st, uc->uc_mcontext.regs->gpr[i]);
 657   }
 658   st->cr();
 659 }
 660 
 661 extern "C" {
 662   int SpinPause() {
 663     return 0;
 664   }
 665 }
 666 
 667 #ifndef PRODUCT
 668 void os::verify_stack_alignment() {
 669   assert(((intptr_t)os::current_stack_pointer() & (StackAlignmentInBytes-1)) == 0, "incorrect stack alignment");
 670 }
 671 #endif
 672 
 673 int os::extra_bang_size_in_bytes() {
 674   // PPC does not require the additional stack bang.
 675   return 0;
 676 }