1 /*
   2  * Copyright (c) 1999, 2014, Oracle and/or its affiliates. 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 // no precompiled headers
  26 #include "asm/macroAssembler.hpp"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/systemDictionary.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "code/icBuffer.hpp"
  31 #include "code/vtableStubs.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 #include "jvm_bsd.h"
  34 #include "memory/allocation.inline.hpp"
  35 #include "mutex_bsd.inline.hpp"
  36 #include "os_share_bsd.hpp"
  37 #include "prims/jniFastGetField.hpp"
  38 #include "prims/jvm.h"
  39 #include "prims/jvm_misc.hpp"
  40 #include "runtime/arguments.hpp"
  41 #include "runtime/extendedPC.hpp"
  42 #include "runtime/frame.inline.hpp"
  43 #include "runtime/interfaceSupport.hpp"
  44 #include "runtime/java.hpp"
  45 #include "runtime/javaCalls.hpp"
  46 #include "runtime/mutexLocker.hpp"
  47 #include "runtime/osThread.hpp"
  48 #include "runtime/sharedRuntime.hpp"
  49 #include "runtime/stubRoutines.hpp"
  50 #include "runtime/thread.inline.hpp"
  51 #include "runtime/timer.hpp"
  52 #include "utilities/events.hpp"
  53 #include "utilities/vmError.hpp"
  54 
  55 // put OS-includes here
  56 # include <sys/types.h>
  57 # include <sys/mman.h>
  58 # include <pthread.h>
  59 # include <signal.h>
  60 # include <errno.h>
  61 # include <dlfcn.h>
  62 # include <stdlib.h>
  63 # include <stdio.h>
  64 # include <unistd.h>
  65 # include <sys/resource.h>
  66 # include <pthread.h>
  67 # include <sys/stat.h>
  68 # include <sys/time.h>
  69 # include <sys/utsname.h>
  70 # include <sys/socket.h>
  71 # include <sys/wait.h>
  72 # include <pwd.h>
  73 # include <poll.h>
  74 #ifndef __OpenBSD__
  75 # include <ucontext.h>
  76 #endif
  77 
  78 #if !defined(__APPLE__) && !defined(__NetBSD__)
  79 # include <pthread_np.h>
  80 #endif
  81 
  82 // needed by current_stack_region() workaround for Mavericks
  83 #if defined(__APPLE__)
  84 # include <errno.h>
  85 # include <sys/types.h>
  86 # include <sys/sysctl.h>
  87 # define DEFAULT_MAIN_THREAD_STACK_PAGES 2048
  88 # define OS_X_10_9_0_KERNEL_MAJOR_VERSION 13
  89 #endif
  90 
  91 #ifdef AMD64
  92 #define SPELL_REG_SP "rsp"
  93 #define SPELL_REG_FP "rbp"
  94 #else
  95 #define SPELL_REG_SP "esp"
  96 #define SPELL_REG_FP "ebp"
  97 #endif // AMD64
  98 
  99 #ifdef __FreeBSD__
 100 # define context_trapno uc_mcontext.mc_trapno
 101 # ifdef AMD64
 102 #  define context_pc uc_mcontext.mc_rip
 103 #  define context_sp uc_mcontext.mc_rsp
 104 #  define context_fp uc_mcontext.mc_rbp
 105 #  define context_rip uc_mcontext.mc_rip
 106 #  define context_rsp uc_mcontext.mc_rsp
 107 #  define context_rbp uc_mcontext.mc_rbp
 108 #  define context_rax uc_mcontext.mc_rax
 109 #  define context_rbx uc_mcontext.mc_rbx
 110 #  define context_rcx uc_mcontext.mc_rcx
 111 #  define context_rdx uc_mcontext.mc_rdx
 112 #  define context_rsi uc_mcontext.mc_rsi
 113 #  define context_rdi uc_mcontext.mc_rdi
 114 #  define context_r8  uc_mcontext.mc_r8
 115 #  define context_r9  uc_mcontext.mc_r9
 116 #  define context_r10 uc_mcontext.mc_r10
 117 #  define context_r11 uc_mcontext.mc_r11
 118 #  define context_r12 uc_mcontext.mc_r12
 119 #  define context_r13 uc_mcontext.mc_r13
 120 #  define context_r14 uc_mcontext.mc_r14
 121 #  define context_r15 uc_mcontext.mc_r15
 122 #  define context_flags uc_mcontext.mc_flags
 123 #  define context_err uc_mcontext.mc_err
 124 # else
 125 #  define context_pc uc_mcontext.mc_eip
 126 #  define context_sp uc_mcontext.mc_esp
 127 #  define context_fp uc_mcontext.mc_ebp
 128 #  define context_eip uc_mcontext.mc_eip
 129 #  define context_esp uc_mcontext.mc_esp
 130 #  define context_eax uc_mcontext.mc_eax
 131 #  define context_ebx uc_mcontext.mc_ebx
 132 #  define context_ecx uc_mcontext.mc_ecx
 133 #  define context_edx uc_mcontext.mc_edx
 134 #  define context_ebp uc_mcontext.mc_ebp
 135 #  define context_esi uc_mcontext.mc_esi
 136 #  define context_edi uc_mcontext.mc_edi
 137 #  define context_eflags uc_mcontext.mc_eflags
 138 #  define context_trapno uc_mcontext.mc_trapno
 139 # endif
 140 #endif
 141 
 142 #ifdef __APPLE__
 143 # if __DARWIN_UNIX03 && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
 144   // 10.5 UNIX03 member name prefixes
 145   #define DU3_PREFIX(s, m) __ ## s.__ ## m
 146 # else
 147   #define DU3_PREFIX(s, m) s ## . ## m
 148 # endif
 149 
 150 # ifdef AMD64
 151 #  define context_pc context_rip
 152 #  define context_sp context_rsp
 153 #  define context_fp context_rbp
 154 #  define context_rip uc_mcontext->DU3_PREFIX(ss,rip)
 155 #  define context_rsp uc_mcontext->DU3_PREFIX(ss,rsp)
 156 #  define context_rax uc_mcontext->DU3_PREFIX(ss,rax)
 157 #  define context_rbx uc_mcontext->DU3_PREFIX(ss,rbx)
 158 #  define context_rcx uc_mcontext->DU3_PREFIX(ss,rcx)
 159 #  define context_rdx uc_mcontext->DU3_PREFIX(ss,rdx)
 160 #  define context_rbp uc_mcontext->DU3_PREFIX(ss,rbp)
 161 #  define context_rsi uc_mcontext->DU3_PREFIX(ss,rsi)
 162 #  define context_rdi uc_mcontext->DU3_PREFIX(ss,rdi)
 163 #  define context_r8  uc_mcontext->DU3_PREFIX(ss,r8)
 164 #  define context_r9  uc_mcontext->DU3_PREFIX(ss,r9)
 165 #  define context_r10 uc_mcontext->DU3_PREFIX(ss,r10)
 166 #  define context_r11 uc_mcontext->DU3_PREFIX(ss,r11)
 167 #  define context_r12 uc_mcontext->DU3_PREFIX(ss,r12)
 168 #  define context_r13 uc_mcontext->DU3_PREFIX(ss,r13)
 169 #  define context_r14 uc_mcontext->DU3_PREFIX(ss,r14)
 170 #  define context_r15 uc_mcontext->DU3_PREFIX(ss,r15)
 171 #  define context_flags uc_mcontext->DU3_PREFIX(ss,rflags)
 172 #  define context_trapno uc_mcontext->DU3_PREFIX(es,trapno)
 173 #  define context_err uc_mcontext->DU3_PREFIX(es,err)
 174 # else
 175 #  define context_pc context_eip
 176 #  define context_sp context_esp
 177 #  define context_fp context_ebp
 178 #  define context_eip uc_mcontext->DU3_PREFIX(ss,eip)
 179 #  define context_esp uc_mcontext->DU3_PREFIX(ss,esp)
 180 #  define context_eax uc_mcontext->DU3_PREFIX(ss,eax)
 181 #  define context_ebx uc_mcontext->DU3_PREFIX(ss,ebx)
 182 #  define context_ecx uc_mcontext->DU3_PREFIX(ss,ecx)
 183 #  define context_edx uc_mcontext->DU3_PREFIX(ss,edx)
 184 #  define context_ebp uc_mcontext->DU3_PREFIX(ss,ebp)
 185 #  define context_esi uc_mcontext->DU3_PREFIX(ss,esi)
 186 #  define context_edi uc_mcontext->DU3_PREFIX(ss,edi)
 187 #  define context_eflags uc_mcontext->DU3_PREFIX(ss,eflags)
 188 #  define context_trapno uc_mcontext->DU3_PREFIX(es,trapno)
 189 # endif
 190 #endif
 191 
 192 #ifdef __OpenBSD__
 193 # define context_trapno sc_trapno
 194 # ifdef AMD64
 195 #  define context_pc sc_rip
 196 #  define context_sp sc_rsp
 197 #  define context_fp sc_rbp
 198 #  define context_rip sc_rip
 199 #  define context_rsp sc_rsp
 200 #  define context_rbp sc_rbp
 201 #  define context_rax sc_rax
 202 #  define context_rbx sc_rbx
 203 #  define context_rcx sc_rcx
 204 #  define context_rdx sc_rdx
 205 #  define context_rsi sc_rsi
 206 #  define context_rdi sc_rdi
 207 #  define context_r8  sc_r8
 208 #  define context_r9  sc_r9
 209 #  define context_r10 sc_r10
 210 #  define context_r11 sc_r11
 211 #  define context_r12 sc_r12
 212 #  define context_r13 sc_r13
 213 #  define context_r14 sc_r14
 214 #  define context_r15 sc_r15
 215 #  define context_flags sc_rflags
 216 #  define context_err sc_err
 217 # else
 218 #  define context_pc sc_eip
 219 #  define context_sp sc_esp
 220 #  define context_fp sc_ebp
 221 #  define context_eip sc_eip
 222 #  define context_esp sc_esp
 223 #  define context_eax sc_eax
 224 #  define context_ebx sc_ebx
 225 #  define context_ecx sc_ecx
 226 #  define context_edx sc_edx
 227 #  define context_ebp sc_ebp
 228 #  define context_esi sc_esi
 229 #  define context_edi sc_edi
 230 #  define context_eflags sc_eflags
 231 #  define context_trapno sc_trapno
 232 # endif
 233 #endif
 234 
 235 #ifdef __NetBSD__
 236 # define context_trapno uc_mcontext.__gregs[_REG_TRAPNO]
 237 # ifdef AMD64
 238 #  define __register_t __greg_t
 239 #  define context_pc uc_mcontext.__gregs[_REG_RIP]
 240 #  define context_sp uc_mcontext.__gregs[_REG_URSP]
 241 #  define context_fp uc_mcontext.__gregs[_REG_RBP]
 242 #  define context_rip uc_mcontext.__gregs[_REG_RIP]
 243 #  define context_rsp uc_mcontext.__gregs[_REG_URSP]
 244 #  define context_rax uc_mcontext.__gregs[_REG_RAX]
 245 #  define context_rbx uc_mcontext.__gregs[_REG_RBX]
 246 #  define context_rcx uc_mcontext.__gregs[_REG_RCX]
 247 #  define context_rdx uc_mcontext.__gregs[_REG_RDX]
 248 #  define context_rbp uc_mcontext.__gregs[_REG_RBP]
 249 #  define context_rsi uc_mcontext.__gregs[_REG_RSI]
 250 #  define context_rdi uc_mcontext.__gregs[_REG_RDI]
 251 #  define context_r8  uc_mcontext.__gregs[_REG_R8]
 252 #  define context_r9  uc_mcontext.__gregs[_REG_R9]
 253 #  define context_r10 uc_mcontext.__gregs[_REG_R10]
 254 #  define context_r11 uc_mcontext.__gregs[_REG_R11]
 255 #  define context_r12 uc_mcontext.__gregs[_REG_R12]
 256 #  define context_r13 uc_mcontext.__gregs[_REG_R13]
 257 #  define context_r14 uc_mcontext.__gregs[_REG_R14]
 258 #  define context_r15 uc_mcontext.__gregs[_REG_R15]
 259 #  define context_flags uc_mcontext.__gregs[_REG_RFL]
 260 #  define context_err uc_mcontext.__gregs[_REG_ERR]
 261 # else
 262 #  define context_pc uc_mcontext.__gregs[_REG_EIP]
 263 #  define context_sp uc_mcontext.__gregs[_REG_UESP]
 264 #  define context_fp uc_mcontext.__gregs[_REG_EBP]
 265 #  define context_eip uc_mcontext.__gregs[_REG_EIP]
 266 #  define context_esp uc_mcontext.__gregs[_REG_UESP]
 267 #  define context_eax uc_mcontext.__gregs[_REG_EAX]
 268 #  define context_ebx uc_mcontext.__gregs[_REG_EBX]
 269 #  define context_ecx uc_mcontext.__gregs[_REG_ECX]
 270 #  define context_edx uc_mcontext.__gregs[_REG_EDX]
 271 #  define context_ebp uc_mcontext.__gregs[_REG_EBP]
 272 #  define context_esi uc_mcontext.__gregs[_REG_ESI]
 273 #  define context_edi uc_mcontext.__gregs[_REG_EDI]
 274 #  define context_eflags uc_mcontext.__gregs[_REG_EFL]
 275 #  define context_trapno uc_mcontext.__gregs[_REG_TRAPNO]
 276 # endif
 277 #endif
 278 
 279 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
 280 
 281 address os::current_stack_pointer() {
 282 #if defined(__clang__) || defined(__llvm__)
 283   register void *esp;
 284   __asm__("mov %%"SPELL_REG_SP", %0":"=r"(esp));
 285   return (address) esp;
 286 #elif defined(SPARC_WORKS)
 287   register void *esp;
 288   __asm__("mov %%"SPELL_REG_SP", %0":"=r"(esp));
 289   return (address) ((char*)esp + sizeof(long)*2);
 290 #else
 291   register void *esp __asm__ (SPELL_REG_SP);
 292   return (address) esp;
 293 #endif
 294 }
 295 
 296 char* os::non_memory_address_word() {
 297   // Must never look like an address returned by reserve_memory,
 298   // even in its subfields (as defined by the CPU immediate fields,
 299   // if the CPU splits constants across multiple instructions).
 300 
 301   return (char*) -1;
 302 }
 303 
 304 void os::initialize_thread(Thread* thr) {
 305 // Nothing to do.
 306 }
 307 
 308 address os::Bsd::ucontext_get_pc(ucontext_t * uc) {
 309   return (address)uc->context_pc;
 310 }
 311 
 312 intptr_t* os::Bsd::ucontext_get_sp(ucontext_t * uc) {
 313   return (intptr_t*)uc->context_sp;
 314 }
 315 
 316 intptr_t* os::Bsd::ucontext_get_fp(ucontext_t * uc) {
 317   return (intptr_t*)uc->context_fp;
 318 }
 319 
 320 // For Forte Analyzer AsyncGetCallTrace profiling support - thread
 321 // is currently interrupted by SIGPROF.
 322 // os::Solaris::fetch_frame_from_ucontext() tries to skip nested signal
 323 // frames. Currently we don't do that on Bsd, so it's the same as
 324 // os::fetch_frame_from_context().
 325 ExtendedPC os::Bsd::fetch_frame_from_ucontext(Thread* thread,
 326   ucontext_t* uc, intptr_t** ret_sp, intptr_t** ret_fp) {
 327 
 328   assert(thread != NULL, "just checking");
 329   assert(ret_sp != NULL, "just checking");
 330   assert(ret_fp != NULL, "just checking");
 331 
 332   return os::fetch_frame_from_context(uc, ret_sp, ret_fp);
 333 }
 334 
 335 ExtendedPC os::fetch_frame_from_context(void* ucVoid,
 336                     intptr_t** ret_sp, intptr_t** ret_fp) {
 337 
 338   ExtendedPC  epc;
 339   ucontext_t* uc = (ucontext_t*)ucVoid;
 340 
 341   if (uc != NULL) {
 342     epc = ExtendedPC(os::Bsd::ucontext_get_pc(uc));
 343     if (ret_sp) *ret_sp = os::Bsd::ucontext_get_sp(uc);
 344     if (ret_fp) *ret_fp = os::Bsd::ucontext_get_fp(uc);
 345   } else {
 346     // construct empty ExtendedPC for return value checking
 347     epc = ExtendedPC(NULL);
 348     if (ret_sp) *ret_sp = (intptr_t *)NULL;
 349     if (ret_fp) *ret_fp = (intptr_t *)NULL;
 350   }
 351 
 352   return epc;
 353 }
 354 
 355 frame os::fetch_frame_from_context(void* ucVoid) {
 356   intptr_t* sp;
 357   intptr_t* fp;
 358   ExtendedPC epc = fetch_frame_from_context(ucVoid, &sp, &fp);
 359   return frame(sp, fp, epc.pc());
 360 }
 361 
 362 // By default, gcc always save frame pointer (%ebp/%rbp) on stack. It may get
 363 // turned off by -fomit-frame-pointer,
 364 frame os::get_sender_for_C_frame(frame* fr) {
 365   return frame(fr->sender_sp(), fr->link(), fr->sender_pc());
 366 }
 367 
 368 intptr_t* _get_previous_fp() {
 369 #if defined(SPARC_WORKS) || defined(__clang__) || defined(__llvm__)
 370   register intptr_t **ebp;
 371   __asm__("mov %%"SPELL_REG_FP", %0":"=r"(ebp));
 372 #else
 373   register intptr_t **ebp __asm__ (SPELL_REG_FP);
 374 #endif
 375   return (intptr_t*) *ebp;   // we want what it points to.
 376 }
 377 
 378 
 379 frame os::current_frame() {
 380   intptr_t* fp = _get_previous_fp();
 381   frame myframe((intptr_t*)os::current_stack_pointer(),
 382                 (intptr_t*)fp,
 383                 CAST_FROM_FN_PTR(address, os::current_frame));
 384   if (os::is_first_C_frame(&myframe)) {
 385     // stack is not walkable
 386     return frame();
 387   } else {
 388     return os::get_sender_for_C_frame(&myframe);
 389   }
 390 }
 391 
 392 // Utility functions
 393 
 394 // From IA32 System Programming Guide
 395 enum {
 396   trap_page_fault = 0xE
 397 };
 398 
 399 extern "C" JNIEXPORT int
 400 JVM_handle_bsd_signal(int sig,
 401                         siginfo_t* info,
 402                         void* ucVoid,
 403                         int abort_if_unrecognized) {
 404   ucontext_t* uc = (ucontext_t*) ucVoid;
 405 
 406   Thread* t = ThreadLocalStorage::get_thread_slow();
 407 
 408   // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away
 409   // (no destructors can be run)
 410   os::WatcherThreadCrashProtection::check_crash_protection(sig, t);
 411 
 412   SignalHandlerMark shm(t);
 413 
 414   // Note: it's not uncommon that JNI code uses signal/sigset to install
 415   // then restore certain signal handler (e.g. to temporarily block SIGPIPE,
 416   // or have a SIGILL handler when detecting CPU type). When that happens,
 417   // JVM_handle_bsd_signal() might be invoked with junk info/ucVoid. To
 418   // avoid unnecessary crash when libjsig is not preloaded, try handle signals
 419   // that do not require siginfo/ucontext first.
 420 
 421   if (sig == SIGPIPE || sig == SIGXFSZ) {
 422     // allow chained handler to go first
 423     if (os::Bsd::chained_handler(sig, info, ucVoid)) {
 424       return true;
 425     } else {
 426       if (PrintMiscellaneous && (WizardMode || Verbose)) {
 427         char buf[64];
 428         warning("Ignoring %s - see bugs 4229104 or 646499219",
 429                 os::exception_name(sig, buf, sizeof(buf)));
 430       }
 431       return true;
 432     }
 433   }
 434 
 435   JavaThread* thread = NULL;
 436   VMThread* vmthread = NULL;
 437   if (os::Bsd::signal_handlers_are_installed) {
 438     if (t != NULL ){
 439       if(t->is_Java_thread()) {
 440         thread = (JavaThread*)t;
 441       }
 442       else if(t->is_VM_thread()){
 443         vmthread = (VMThread *)t;
 444       }
 445     }
 446   }
 447 /*
 448   NOTE: does not seem to work on bsd.
 449   if (info == NULL || info->si_code <= 0 || info->si_code == SI_NOINFO) {
 450     // can't decode this kind of signal
 451     info = NULL;
 452   } else {
 453     assert(sig == info->si_signo, "bad siginfo");
 454   }
 455 */
 456   // decide if this trap can be handled by a stub
 457   address stub = NULL;
 458 
 459   address pc          = NULL;
 460 
 461   //%note os_trap_1
 462   if (info != NULL && uc != NULL && thread != NULL) {
 463     pc = (address) os::Bsd::ucontext_get_pc(uc);
 464 
 465     if (StubRoutines::is_safefetch_fault(pc)) {
 466       uc->context_pc = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc));
 467       return 1;
 468     }
 469 
 470     // Handle ALL stack overflow variations here
 471     if (sig == SIGSEGV || sig == SIGBUS) {
 472       address addr = (address) info->si_addr;
 473 
 474       // check if fault address is within thread stack
 475       if (addr < thread->stack_base() &&
 476           addr >= thread->stack_base() - thread->stack_size()) {
 477         // stack overflow
 478         if (thread->in_stack_yellow_zone(addr)) {
 479           thread->disable_stack_yellow_zone();
 480           if (thread->thread_state() == _thread_in_Java) {
 481             // Throw a stack overflow exception.  Guard pages will be reenabled
 482             // while unwinding the stack.
 483             stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW);
 484           } else {
 485             // Thread was in the vm or native code.  Return and try to finish.
 486             return 1;
 487           }
 488         } else if (thread->in_stack_red_zone(addr)) {
 489           // Fatal red zone violation.  Disable the guard pages and fall through
 490           // to handle_unexpected_exception way down below.
 491           thread->disable_stack_red_zone();
 492           tty->print_raw_cr("An irrecoverable stack overflow has occurred.");
 493         }
 494       }
 495     }
 496 
 497     if ((sig == SIGSEGV || sig == SIGBUS) && VM_Version::is_cpuinfo_segv_addr(pc)) {
 498       // Verify that OS save/restore AVX registers.
 499       stub = VM_Version::cpuinfo_cont_addr();
 500     }
 501 
 502     // We test if stub is already set (by the stack overflow code
 503     // above) so it is not overwritten by the code that follows. This
 504     // check is not required on other platforms, because on other
 505     // platforms we check for SIGSEGV only or SIGBUS only, where here
 506     // we have to check for both SIGSEGV and SIGBUS.
 507     if (thread->thread_state() == _thread_in_Java && stub == NULL) {
 508       // Java thread running in Java code => find exception handler if any
 509       // a fault inside compiled code, the interpreter, or a stub
 510 
 511       if ((sig == SIGSEGV || sig == SIGBUS) && os::is_poll_address((address)info->si_addr)) {
 512         stub = SharedRuntime::get_poll_stub(pc);
 513 #if defined(__APPLE__)
 514       // 32-bit Darwin reports a SIGBUS for nearly all memory access exceptions.
 515       // 64-bit Darwin may also use a SIGBUS (seen with compressed oops).
 516       // Catching SIGBUS here prevents the implicit SIGBUS NULL check below from
 517       // being called, so only do so if the implicit NULL check is not necessary.
 518       } else if (sig == SIGBUS && MacroAssembler::needs_explicit_null_check((intptr_t)info->si_addr)) {
 519 #else
 520       } else if (sig == SIGBUS /* && info->si_code == BUS_OBJERR */) {
 521 #endif
 522         // BugId 4454115: A read from a MappedByteBuffer can fault
 523         // here if the underlying file has been truncated.
 524         // Do not crash the VM in such a case.
 525         CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
 526         nmethod* nm = (cb != NULL && cb->is_nmethod()) ? (nmethod*)cb : NULL;
 527         if (nm != NULL && nm->has_unsafe_access()) {
 528           stub = StubRoutines::handler_for_unsafe_access();
 529         }
 530       }
 531       else
 532 
 533 #ifdef AMD64
 534       if (sig == SIGFPE  &&
 535           (info->si_code == FPE_INTDIV || info->si_code == FPE_FLTDIV)) {
 536         stub =
 537           SharedRuntime::
 538           continuation_for_implicit_exception(thread,
 539                                               pc,
 540                                               SharedRuntime::
 541                                               IMPLICIT_DIVIDE_BY_ZERO);
 542 #ifdef __APPLE__
 543       } else if (sig == SIGFPE && info->si_code == FPE_NOOP) {
 544         int op = pc[0];
 545 
 546         // Skip REX
 547         if ((pc[0] & 0xf0) == 0x40) {
 548           op = pc[1];
 549         } else {
 550           op = pc[0];
 551         }
 552 
 553         // Check for IDIV
 554         if (op == 0xF7) {
 555           stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime:: IMPLICIT_DIVIDE_BY_ZERO);
 556         } else {
 557           // TODO: handle more cases if we are using other x86 instructions
 558           //   that can generate SIGFPE signal.
 559           tty->print_cr("unknown opcode 0x%X with SIGFPE.", op);
 560           fatal("please update this code.");
 561         }
 562 #endif /* __APPLE__ */
 563 
 564 #else
 565       if (sig == SIGFPE /* && info->si_code == FPE_INTDIV */) {
 566         // HACK: si_code does not work on bsd 2.2.12-20!!!
 567         int op = pc[0];
 568         if (op == 0xDB) {
 569           // FIST
 570           // TODO: The encoding of D2I in i486.ad can cause an exception
 571           // prior to the fist instruction if there was an invalid operation
 572           // pending. We want to dismiss that exception. From the win_32
 573           // side it also seems that if it really was the fist causing
 574           // the exception that we do the d2i by hand with different
 575           // rounding. Seems kind of weird.
 576           // NOTE: that we take the exception at the NEXT floating point instruction.
 577           assert(pc[0] == 0xDB, "not a FIST opcode");
 578           assert(pc[1] == 0x14, "not a FIST opcode");
 579           assert(pc[2] == 0x24, "not a FIST opcode");
 580           return true;
 581         } else if (op == 0xF7) {
 582           // IDIV
 583           stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_DIVIDE_BY_ZERO);
 584         } else {
 585           // TODO: handle more cases if we are using other x86 instructions
 586           //   that can generate SIGFPE signal on bsd.
 587           tty->print_cr("unknown opcode 0x%X with SIGFPE.", op);
 588           fatal("please update this code.");
 589         }
 590 #endif // AMD64
 591       } else if ((sig == SIGSEGV || sig == SIGBUS) &&
 592                !MacroAssembler::needs_explicit_null_check((intptr_t)info->si_addr)) {
 593           // Determination of interpreter/vtable stub/compiled code null exception
 594           stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
 595       }
 596     } else if (thread->thread_state() == _thread_in_vm &&
 597                sig == SIGBUS && /* info->si_code == BUS_OBJERR && */
 598                thread->doing_unsafe_access()) {
 599         stub = StubRoutines::handler_for_unsafe_access();
 600     }
 601 
 602     // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in
 603     // and the heap gets shrunk before the field access.
 604     if ((sig == SIGSEGV) || (sig == SIGBUS)) {
 605       address addr = JNI_FastGetField::find_slowcase_pc(pc);
 606       if (addr != (address)-1) {
 607         stub = addr;
 608       }
 609     }
 610 
 611     // Check to see if we caught the safepoint code in the
 612     // process of write protecting the memory serialization page.
 613     // It write enables the page immediately after protecting it
 614     // so we can just return to retry the write.
 615     if ((sig == SIGSEGV || sig == SIGBUS) &&
 616         os::is_memory_serialize_page(thread, (address) info->si_addr)) {
 617       // Block current thread until the memory serialize page permission restored.
 618       os::block_on_serialize_page_trap();
 619       return true;
 620     }
 621   }
 622 
 623 #ifndef AMD64
 624   // Execution protection violation
 625   //
 626   // This should be kept as the last step in the triage.  We don't
 627   // have a dedicated trap number for a no-execute fault, so be
 628   // conservative and allow other handlers the first shot.
 629   //
 630   // Note: We don't test that info->si_code == SEGV_ACCERR here.
 631   // this si_code is so generic that it is almost meaningless; and
 632   // the si_code for this condition may change in the future.
 633   // Furthermore, a false-positive should be harmless.
 634   if (UnguardOnExecutionViolation > 0 &&
 635       (sig == SIGSEGV || sig == SIGBUS) &&
 636       uc->context_trapno == trap_page_fault) {
 637     int page_size = os::vm_page_size();
 638     address addr = (address) info->si_addr;
 639     address pc = os::Bsd::ucontext_get_pc(uc);
 640     // Make sure the pc and the faulting address are sane.
 641     //
 642     // If an instruction spans a page boundary, and the page containing
 643     // the beginning of the instruction is executable but the following
 644     // page is not, the pc and the faulting address might be slightly
 645     // different - we still want to unguard the 2nd page in this case.
 646     //
 647     // 15 bytes seems to be a (very) safe value for max instruction size.
 648     bool pc_is_near_addr =
 649       (pointer_delta((void*) addr, (void*) pc, sizeof(char)) < 15);
 650     bool instr_spans_page_boundary =
 651       (align_size_down((intptr_t) pc ^ (intptr_t) addr,
 652                        (intptr_t) page_size) > 0);
 653 
 654     if (pc == addr || (pc_is_near_addr && instr_spans_page_boundary)) {
 655       static volatile address last_addr =
 656         (address) os::non_memory_address_word();
 657 
 658       // In conservative mode, don't unguard unless the address is in the VM
 659       if (addr != last_addr &&
 660           (UnguardOnExecutionViolation > 1 || os::address_is_in_vm(addr))) {
 661 
 662         // Set memory to RWX and retry
 663         address page_start =
 664           (address) align_size_down((intptr_t) addr, (intptr_t) page_size);
 665         bool res = os::protect_memory((char*) page_start, page_size,
 666                                       os::MEM_PROT_RWX);
 667 
 668         if (PrintMiscellaneous && Verbose) {
 669           char buf[256];
 670           jio_snprintf(buf, sizeof(buf), "Execution protection violation "
 671                        "at " INTPTR_FORMAT
 672                        ", unguarding " INTPTR_FORMAT ": %s, errno=%d", addr,
 673                        page_start, (res ? "success" : "failed"), errno);
 674           tty->print_raw_cr(buf);
 675         }
 676         stub = pc;
 677 
 678         // Set last_addr so if we fault again at the same address, we don't end
 679         // up in an endless loop.
 680         //
 681         // There are two potential complications here.  Two threads trapping at
 682         // the same address at the same time could cause one of the threads to
 683         // think it already unguarded, and abort the VM.  Likely very rare.
 684         //
 685         // The other race involves two threads alternately trapping at
 686         // different addresses and failing to unguard the page, resulting in
 687         // an endless loop.  This condition is probably even more unlikely than
 688         // the first.
 689         //
 690         // Although both cases could be avoided by using locks or thread local
 691         // last_addr, these solutions are unnecessary complication: this
 692         // handler is a best-effort safety net, not a complete solution.  It is
 693         // disabled by default and should only be used as a workaround in case
 694         // we missed any no-execute-unsafe VM code.
 695 
 696         last_addr = addr;
 697       }
 698     }
 699   }
 700 #endif // !AMD64
 701 
 702   if (stub != NULL) {
 703     // save all thread context in case we need to restore it
 704     if (thread != NULL) thread->set_saved_exception_pc(pc);
 705 
 706     uc->context_pc = (intptr_t)stub;
 707     return true;
 708   }
 709 
 710   // signal-chaining
 711   if (os::Bsd::chained_handler(sig, info, ucVoid)) {
 712      return true;
 713   }
 714 
 715   if (!abort_if_unrecognized) {
 716     // caller wants another chance, so give it to him
 717     return false;
 718   }
 719 
 720   if (pc == NULL && uc != NULL) {
 721     pc = os::Bsd::ucontext_get_pc(uc);
 722   }
 723 
 724   // unmask current signal
 725   sigset_t newset;
 726   sigemptyset(&newset);
 727   sigaddset(&newset, sig);
 728   sigprocmask(SIG_UNBLOCK, &newset, NULL);
 729 
 730   VMError err(t, sig, pc, info, ucVoid);
 731   err.report_and_die();
 732 
 733   ShouldNotReachHere();
 734   return false;
 735 }
 736 
 737 // From solaris_i486.s ported to bsd_i486.s
 738 extern "C" void fixcw();
 739 
 740 void os::Bsd::init_thread_fpu_state(void) {
 741 #ifndef AMD64
 742   // Set fpu to 53 bit precision. This happens too early to use a stub.
 743   fixcw();
 744 #endif // !AMD64
 745 }
 746 
 747 
 748 // Check that the bsd kernel version is 2.4 or higher since earlier
 749 // versions do not support SSE without patches.
 750 bool os::supports_sse() {
 751   return true;
 752 }
 753 
 754 bool os::is_allocatable(size_t bytes) {
 755 #ifdef AMD64
 756   // unused on amd64?
 757   return true;
 758 #else
 759 
 760   if (bytes < 2 * G) {
 761     return true;
 762   }
 763 
 764   char* addr = reserve_memory(bytes, NULL);
 765 
 766   if (addr != NULL) {
 767     release_memory(addr, bytes);
 768   }
 769 
 770   return addr != NULL;
 771 #endif // AMD64
 772 }
 773 
 774 ////////////////////////////////////////////////////////////////////////////////
 775 // thread stack
 776 
 777 #ifdef AMD64
 778 size_t os::Bsd::min_stack_allowed  = 64 * K;
 779 
 780 // amd64: pthread on amd64 is always in floating stack mode
 781 bool os::Bsd::supports_variable_stack_size() {  return true; }
 782 #else
 783 size_t os::Bsd::min_stack_allowed  =  (48 DEBUG_ONLY(+4))*K;
 784 
 785 #ifdef __GNUC__
 786 #define GET_GS() ({int gs; __asm__ volatile("movw %%gs, %w0":"=q"(gs)); gs&0xffff;})
 787 #endif
 788 
 789 bool os::Bsd::supports_variable_stack_size() { return true; }
 790 #endif // AMD64
 791 
 792 // return default stack size for thr_type
 793 size_t os::Bsd::default_stack_size(os::ThreadType thr_type) {
 794   // default stack size (compiler thread needs larger stack)
 795 #ifdef AMD64
 796   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
 797 #else
 798   size_t s = (thr_type == os::compiler_thread ? 2 * M : 512 * K);
 799 #endif // AMD64
 800   return s;
 801 }
 802 
 803 size_t os::Bsd::default_guard_size(os::ThreadType thr_type) {
 804   // Creating guard page is very expensive. Java thread has HotSpot
 805   // guard page, only enable glibc guard page for non-Java threads.
 806   return (thr_type == java_thread ? 0 : page_size());
 807 }
 808 
 809 // Java thread:
 810 //
 811 //   Low memory addresses
 812 //    +------------------------+
 813 //    |                        |\  JavaThread created by VM does not have glibc
 814 //    |    glibc guard page    | - guard, attached Java thread usually has
 815 //    |                        |/  1 page glibc guard.
 816 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
 817 //    |                        |\
 818 //    |  HotSpot Guard Pages   | - red and yellow pages
 819 //    |                        |/
 820 //    +------------------------+ JavaThread::stack_yellow_zone_base()
 821 //    |                        |\
 822 //    |      Normal Stack      | -
 823 //    |                        |/
 824 // P2 +------------------------+ Thread::stack_base()
 825 //
 826 // Non-Java thread:
 827 //
 828 //   Low memory addresses
 829 //    +------------------------+
 830 //    |                        |\
 831 //    |  glibc guard page      | - usually 1 page
 832 //    |                        |/
 833 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
 834 //    |                        |\
 835 //    |      Normal Stack      | -
 836 //    |                        |/
 837 // P2 +------------------------+ Thread::stack_base()
 838 //
 839 // ** P1 (aka bottom) and size ( P2 = P1 - size) are the address and stack size returned from
 840 //    pthread_attr_getstack()
 841 
 842 static void current_stack_region(address * bottom, size_t * size) {
 843 #ifdef __APPLE__
 844   pthread_t self = pthread_self();
 845   void *stacktop = pthread_get_stackaddr_np(self);
 846   *size = pthread_get_stacksize_np(self);
 847   // workaround for OS X 10.9.0 (Mavericks)
 848   // pthread_get_stacksize_np returns 128 pages even though the actual size is 2048 pages
 849   if (pthread_main_np() == 1) {
 850     if ((*size) < (DEFAULT_MAIN_THREAD_STACK_PAGES * (size_t)getpagesize())) {
 851       char kern_osrelease[256];
 852       size_t kern_osrelease_size = sizeof(kern_osrelease);
 853       int ret = sysctlbyname("kern.osrelease", kern_osrelease, &kern_osrelease_size, NULL, 0);
 854       if (ret == 0) {
 855         // get the major number, atoi will ignore the minor amd micro portions of the version string
 856         if (atoi(kern_osrelease) >= OS_X_10_9_0_KERNEL_MAJOR_VERSION) {
 857           *size = (DEFAULT_MAIN_THREAD_STACK_PAGES*getpagesize());
 858         }
 859       }
 860     }
 861   }
 862   *bottom = (address) stacktop - *size;
 863 #elif defined(__OpenBSD__)
 864   stack_t ss;
 865   int rslt = pthread_stackseg_np(pthread_self(), &ss);
 866 
 867   if (rslt != 0)
 868     fatal(err_msg("pthread_stackseg_np failed with err = %d", rslt));
 869 
 870   *bottom = (address)((char *)ss.ss_sp - ss.ss_size);
 871   *size   = ss.ss_size;
 872 #else
 873   pthread_attr_t attr;
 874 
 875   int rslt = pthread_attr_init(&attr);
 876 
 877   // JVM needs to know exact stack location, abort if it fails
 878   if (rslt != 0)
 879     fatal(err_msg("pthread_attr_init failed with err = %d", rslt));
 880 
 881   rslt = pthread_attr_get_np(pthread_self(), &attr);
 882 
 883   if (rslt != 0)
 884     fatal(err_msg("pthread_attr_get_np failed with err = %d", rslt));
 885 
 886   if (pthread_attr_getstackaddr(&attr, (void **)bottom) != 0 ||
 887     pthread_attr_getstacksize(&attr, size) != 0) {
 888     fatal("Can not locate current stack attributes!");
 889   }
 890 
 891   pthread_attr_destroy(&attr);
 892 #endif
 893   assert(os::current_stack_pointer() >= *bottom &&
 894          os::current_stack_pointer() < *bottom + *size, "just checking");
 895 }
 896 
 897 address os::current_stack_base() {
 898   address bottom;
 899   size_t size;
 900   current_stack_region(&bottom, &size);
 901   return (bottom + size);
 902 }
 903 
 904 size_t os::current_stack_size() {
 905   // stack size includes normal stack and HotSpot guard pages
 906   address bottom;
 907   size_t size;
 908   current_stack_region(&bottom, &size);
 909   return size;
 910 }
 911 
 912 /////////////////////////////////////////////////////////////////////////////
 913 // helper functions for fatal error handler
 914 
 915 void os::print_context(outputStream *st, void *context) {
 916   if (context == NULL) return;
 917 
 918   ucontext_t *uc = (ucontext_t*)context;
 919   st->print_cr("Registers:");
 920 #ifdef AMD64
 921   st->print(  "RAX=" INTPTR_FORMAT, uc->context_rax);
 922   st->print(", RBX=" INTPTR_FORMAT, uc->context_rbx);
 923   st->print(", RCX=" INTPTR_FORMAT, uc->context_rcx);
 924   st->print(", RDX=" INTPTR_FORMAT, uc->context_rdx);
 925   st->cr();
 926   st->print(  "RSP=" INTPTR_FORMAT, uc->context_rsp);
 927   st->print(", RBP=" INTPTR_FORMAT, uc->context_rbp);
 928   st->print(", RSI=" INTPTR_FORMAT, uc->context_rsi);
 929   st->print(", RDI=" INTPTR_FORMAT, uc->context_rdi);
 930   st->cr();
 931   st->print(  "R8 =" INTPTR_FORMAT, uc->context_r8);
 932   st->print(", R9 =" INTPTR_FORMAT, uc->context_r9);
 933   st->print(", R10=" INTPTR_FORMAT, uc->context_r10);
 934   st->print(", R11=" INTPTR_FORMAT, uc->context_r11);
 935   st->cr();
 936   st->print(  "R12=" INTPTR_FORMAT, uc->context_r12);
 937   st->print(", R13=" INTPTR_FORMAT, uc->context_r13);
 938   st->print(", R14=" INTPTR_FORMAT, uc->context_r14);
 939   st->print(", R15=" INTPTR_FORMAT, uc->context_r15);
 940   st->cr();
 941   st->print(  "RIP=" INTPTR_FORMAT, uc->context_rip);
 942   st->print(", EFLAGS=" INTPTR_FORMAT, uc->context_flags);
 943   st->print(", ERR=" INTPTR_FORMAT, uc->context_err);
 944   st->cr();
 945   st->print("  TRAPNO=" INTPTR_FORMAT, uc->context_trapno);
 946 #else
 947   st->print(  "EAX=" INTPTR_FORMAT, uc->context_eax);
 948   st->print(", EBX=" INTPTR_FORMAT, uc->context_ebx);
 949   st->print(", ECX=" INTPTR_FORMAT, uc->context_ecx);
 950   st->print(", EDX=" INTPTR_FORMAT, uc->context_edx);
 951   st->cr();
 952   st->print(  "ESP=" INTPTR_FORMAT, uc->context_esp);
 953   st->print(", EBP=" INTPTR_FORMAT, uc->context_ebp);
 954   st->print(", ESI=" INTPTR_FORMAT, uc->context_esi);
 955   st->print(", EDI=" INTPTR_FORMAT, uc->context_edi);
 956   st->cr();
 957   st->print(  "EIP=" INTPTR_FORMAT, uc->context_eip);
 958   st->print(", EFLAGS=" INTPTR_FORMAT, uc->context_eflags);
 959 #endif // AMD64
 960   st->cr();
 961   st->cr();
 962 
 963   intptr_t *sp = (intptr_t *)os::Bsd::ucontext_get_sp(uc);
 964   st->print_cr("Top of Stack: (sp=" PTR_FORMAT ")", sp);
 965   print_hex_dump(st, (address)sp, (address)(sp + 8*sizeof(intptr_t)), sizeof(intptr_t));
 966   st->cr();
 967 
 968   // Note: it may be unsafe to inspect memory near pc. For example, pc may
 969   // point to garbage if entry point in an nmethod is corrupted. Leave
 970   // this at the end, and hope for the best.
 971   address pc = os::Bsd::ucontext_get_pc(uc);
 972   st->print_cr("Instructions: (pc=" PTR_FORMAT ")", pc);
 973   print_hex_dump(st, pc - 32, pc + 32, sizeof(char));
 974 }
 975 
 976 void os::print_register_info(outputStream *st, void *context) {
 977   if (context == NULL) return;
 978 
 979   ucontext_t *uc = (ucontext_t*)context;
 980 
 981   st->print_cr("Register to memory mapping:");
 982   st->cr();
 983 
 984   // this is horrendously verbose but the layout of the registers in the
 985   // context does not match how we defined our abstract Register set, so
 986   // we can't just iterate through the gregs area
 987 
 988   // this is only for the "general purpose" registers
 989 
 990 #ifdef AMD64
 991   st->print("RAX="); print_location(st, uc->context_rax);
 992   st->print("RBX="); print_location(st, uc->context_rbx);
 993   st->print("RCX="); print_location(st, uc->context_rcx);
 994   st->print("RDX="); print_location(st, uc->context_rdx);
 995   st->print("RSP="); print_location(st, uc->context_rsp);
 996   st->print("RBP="); print_location(st, uc->context_rbp);
 997   st->print("RSI="); print_location(st, uc->context_rsi);
 998   st->print("RDI="); print_location(st, uc->context_rdi);
 999   st->print("R8 ="); print_location(st, uc->context_r8);
1000   st->print("R9 ="); print_location(st, uc->context_r9);
1001   st->print("R10="); print_location(st, uc->context_r10);
1002   st->print("R11="); print_location(st, uc->context_r11);
1003   st->print("R12="); print_location(st, uc->context_r12);
1004   st->print("R13="); print_location(st, uc->context_r13);
1005   st->print("R14="); print_location(st, uc->context_r14);
1006   st->print("R15="); print_location(st, uc->context_r15);
1007 #else
1008   st->print("EAX="); print_location(st, uc->context_eax);
1009   st->print("EBX="); print_location(st, uc->context_ebx);
1010   st->print("ECX="); print_location(st, uc->context_ecx);
1011   st->print("EDX="); print_location(st, uc->context_edx);
1012   st->print("ESP="); print_location(st, uc->context_esp);
1013   st->print("EBP="); print_location(st, uc->context_ebp);
1014   st->print("ESI="); print_location(st, uc->context_esi);
1015   st->print("EDI="); print_location(st, uc->context_edi);
1016 #endif // AMD64
1017 
1018   st->cr();
1019 }
1020 
1021 void os::setup_fpu() {
1022 #ifndef AMD64
1023   address fpu_cntrl = StubRoutines::addr_fpu_cntrl_wrd_std();
1024   __asm__ volatile (  "fldcw (%0)" :
1025                       : "r" (fpu_cntrl) : "memory");
1026 #endif // !AMD64
1027 }
1028 
1029 #ifndef PRODUCT
1030 void os::verify_stack_alignment() {
1031 }
1032 #endif
1033 
1034 int os::extra_bang_size_in_bytes() {
1035   // JDK-8050147 requires the full cache line bang for x86.
1036   return VM_Version::L1_line_size();
1037 }