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