1 /*
   2  * Copyright (c) 1999, 2011, 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 "assembler_x86.inline.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_solaris.h"
  34 #include "memory/allocation.inline.hpp"
  35 #include "mutex_solaris.inline.hpp"
  36 #include "nativeInst_x86.hpp"
  37 #include "os_share_solaris.hpp"
  38 #include "prims/jniFastGetField.hpp"
  39 #include "prims/jvm.h"
  40 #include "prims/jvm_misc.hpp"
  41 #include "runtime/arguments.hpp"
  42 #include "runtime/extendedPC.hpp"
  43 #include "runtime/frame.inline.hpp"
  44 #include "runtime/interfaceSupport.hpp"
  45 #include "runtime/java.hpp"
  46 #include "runtime/javaCalls.hpp"
  47 #include "runtime/mutexLocker.hpp"
  48 #include "runtime/osThread.hpp"
  49 #include "runtime/sharedRuntime.hpp"
  50 #include "runtime/stubRoutines.hpp"
  51 #include "runtime/timer.hpp"
  52 #include "thread_solaris.inline.hpp"
  53 #include "utilities/events.hpp"
  54 #include "utilities/vmError.hpp"
  55 #ifdef COMPILER1
  56 #include "c1/c1_Runtime1.hpp"
  57 #endif
  58 #ifdef COMPILER2
  59 #include "opto/runtime.hpp"
  60 #endif
  61 
  62 // put OS-includes here
  63 # include <sys/types.h>
  64 # include <sys/mman.h>
  65 # include <pthread.h>
  66 # include <signal.h>
  67 # include <setjmp.h>
  68 # include <errno.h>
  69 # include <dlfcn.h>
  70 # include <stdio.h>
  71 # include <unistd.h>
  72 # include <sys/resource.h>
  73 # include <thread.h>
  74 # include <sys/stat.h>
  75 # include <sys/time.h>
  76 # include <sys/filio.h>
  77 # include <sys/utsname.h>
  78 # include <sys/systeminfo.h>
  79 # include <sys/socket.h>
  80 # include <sys/trap.h>
  81 # include <sys/lwp.h>
  82 # include <pwd.h>
  83 # include <poll.h>
  84 # include <sys/lwp.h>
  85 # include <procfs.h>     //  see comment in <sys/procfs.h>
  86 
  87 #ifndef AMD64
  88 // QQQ seems useless at this point
  89 # define _STRUCTURED_PROC 1  //  this gets us the new structured proc interfaces of 5.6 & later
  90 #endif // AMD64
  91 # include <sys/procfs.h>     //  see comment in <sys/procfs.h>
  92 
  93 
  94 #define MAX_PATH (2 * K)
  95 
  96 // Minimum stack size for the VM.  It's easier to document a constant value
  97 // but it's different for x86 and sparc because the page sizes are different.
  98 #ifdef AMD64
  99 size_t os::Solaris::min_stack_allowed = 224*K;
 100 #define REG_SP REG_RSP
 101 #define REG_PC REG_RIP
 102 #define REG_FP REG_RBP
 103 #else
 104 size_t os::Solaris::min_stack_allowed = 64*K;
 105 #define REG_SP UESP
 106 #define REG_PC EIP
 107 #define REG_FP EBP
 108 // 4900493 counter to prevent runaway LDTR refresh attempt
 109 
 110 static volatile int ldtr_refresh = 0;
 111 // the libthread instruction that faults because of the stale LDTR
 112 
 113 static const unsigned char movlfs[] = { 0x8e, 0xe0    // movl %eax,%fs
 114                        };
 115 #endif // AMD64
 116 
 117 char* os::non_memory_address_word() {
 118   // Must never look like an address returned by reserve_memory,
 119   // even in its subfields (as defined by the CPU immediate fields,
 120   // if the CPU splits constants across multiple instructions).
 121   return (char*) -1;
 122 }
 123 
 124 //
 125 // Validate a ucontext retrieved from walking a uc_link of a ucontext.
 126 // There are issues with libthread giving out uc_links for different threads
 127 // on the same uc_link chain and bad or circular links.
 128 //
 129 bool os::Solaris::valid_ucontext(Thread* thread, ucontext_t* valid, ucontext_t* suspect) {
 130   if (valid >= suspect ||
 131       valid->uc_stack.ss_flags != suspect->uc_stack.ss_flags ||
 132       valid->uc_stack.ss_sp    != suspect->uc_stack.ss_sp    ||
 133       valid->uc_stack.ss_size  != suspect->uc_stack.ss_size) {
 134     DEBUG_ONLY(tty->print_cr("valid_ucontext: failed test 1");)
 135     return false;
 136   }
 137 
 138   if (thread->is_Java_thread()) {
 139     if (!valid_stack_address(thread, (address)suspect)) {
 140       DEBUG_ONLY(tty->print_cr("valid_ucontext: uc_link not in thread stack");)
 141       return false;
 142     }
 143     if (!valid_stack_address(thread,  (address) suspect->uc_mcontext.gregs[REG_SP])) {
 144       DEBUG_ONLY(tty->print_cr("valid_ucontext: stackpointer not in thread stack");)
 145       return false;
 146     }
 147   }
 148   return true;
 149 }
 150 
 151 // We will only follow one level of uc_link since there are libthread
 152 // issues with ucontext linking and it is better to be safe and just
 153 // let caller retry later.
 154 ucontext_t* os::Solaris::get_valid_uc_in_signal_handler(Thread *thread,
 155   ucontext_t *uc) {
 156 
 157   ucontext_t *retuc = NULL;
 158 
 159   if (uc != NULL) {
 160     if (uc->uc_link == NULL) {
 161       // cannot validate without uc_link so accept current ucontext
 162       retuc = uc;
 163     } else if (os::Solaris::valid_ucontext(thread, uc, uc->uc_link)) {
 164       // first ucontext is valid so try the next one
 165       uc = uc->uc_link;
 166       if (uc->uc_link == NULL) {
 167         // cannot validate without uc_link so accept current ucontext
 168         retuc = uc;
 169       } else if (os::Solaris::valid_ucontext(thread, uc, uc->uc_link)) {
 170         // the ucontext one level down is also valid so return it
 171         retuc = uc;
 172       }
 173     }
 174   }
 175   return retuc;
 176 }
 177 
 178 // Assumes ucontext is valid
 179 ExtendedPC os::Solaris::ucontext_get_ExtendedPC(ucontext_t *uc) {
 180   return ExtendedPC((address)uc->uc_mcontext.gregs[REG_PC]);
 181 }
 182 
 183 // Assumes ucontext is valid
 184 intptr_t* os::Solaris::ucontext_get_sp(ucontext_t *uc) {
 185   return (intptr_t*)uc->uc_mcontext.gregs[REG_SP];
 186 }
 187 
 188 // Assumes ucontext is valid
 189 intptr_t* os::Solaris::ucontext_get_fp(ucontext_t *uc) {
 190   return (intptr_t*)uc->uc_mcontext.gregs[REG_FP];
 191 }
 192 
 193 // For Forte Analyzer AsyncGetCallTrace profiling support - thread
 194 // is currently interrupted by SIGPROF.
 195 //
 196 // The difference between this and os::fetch_frame_from_context() is that
 197 // here we try to skip nested signal frames.
 198 ExtendedPC os::Solaris::fetch_frame_from_ucontext(Thread* thread,
 199   ucontext_t* uc, intptr_t** ret_sp, intptr_t** ret_fp) {
 200 
 201   assert(thread != NULL, "just checking");
 202   assert(ret_sp != NULL, "just checking");
 203   assert(ret_fp != NULL, "just checking");
 204 
 205   ucontext_t *luc = os::Solaris::get_valid_uc_in_signal_handler(thread, uc);
 206   return os::fetch_frame_from_context(luc, ret_sp, ret_fp);
 207 }
 208 
 209 ExtendedPC os::fetch_frame_from_context(void* ucVoid,
 210                     intptr_t** ret_sp, intptr_t** ret_fp) {
 211 
 212   ExtendedPC  epc;
 213   ucontext_t *uc = (ucontext_t*)ucVoid;
 214 
 215   if (uc != NULL) {
 216     epc = os::Solaris::ucontext_get_ExtendedPC(uc);
 217     if (ret_sp) *ret_sp = os::Solaris::ucontext_get_sp(uc);
 218     if (ret_fp) *ret_fp = os::Solaris::ucontext_get_fp(uc);
 219   } else {
 220     // construct empty ExtendedPC for return value checking
 221     epc = ExtendedPC(NULL);
 222     if (ret_sp) *ret_sp = (intptr_t *)NULL;
 223     if (ret_fp) *ret_fp = (intptr_t *)NULL;
 224   }
 225 
 226   return epc;
 227 }
 228 
 229 frame os::fetch_frame_from_context(void* ucVoid) {
 230   intptr_t* sp;
 231   intptr_t* fp;
 232   ExtendedPC epc = fetch_frame_from_context(ucVoid, &sp, &fp);
 233   return frame(sp, fp, epc.pc());
 234 }
 235 
 236 frame os::get_sender_for_C_frame(frame* fr) {
 237   return frame(fr->sender_sp(), fr->link(), fr->sender_pc());
 238 }
 239 
 240 extern "C" intptr_t *_get_current_sp();  // in .il file
 241 
 242 address os::current_stack_pointer() {
 243   return (address)_get_current_sp();
 244 }
 245 
 246 extern "C" intptr_t *_get_current_fp();  // in .il file
 247 
 248 frame os::current_frame() {
 249   intptr_t* fp = _get_current_fp();  // it's inlined so want current fp
 250   frame myframe((intptr_t*)os::current_stack_pointer(),
 251                 (intptr_t*)fp,
 252                 CAST_FROM_FN_PTR(address, os::current_frame));
 253   if (os::is_first_C_frame(&myframe)) {
 254     // stack is not walkable
 255     frame ret; // This will be a null useless frame
 256     return ret;
 257   } else {
 258     return os::get_sender_for_C_frame(&myframe);
 259   }
 260 }
 261 
 262 // This is a simple callback that just fetches a PC for an interrupted thread.
 263 // The thread need not be suspended and the fetched PC is just a hint.
 264 // This one is currently used for profiling the VMThread ONLY!
 265 
 266 // Must be synchronous
 267 void GetThreadPC_Callback::execute(OSThread::InterruptArguments *args) {
 268   Thread*     thread = args->thread();
 269   ucontext_t* uc     = args->ucontext();
 270   intptr_t* sp;
 271 
 272   assert(ProfileVM && thread->is_VM_thread(), "just checking");
 273 
 274   ExtendedPC new_addr((address)uc->uc_mcontext.gregs[REG_PC]);
 275   _addr = new_addr;
 276 }
 277 
 278 static int threadgetstate(thread_t tid, int *flags, lwpid_t *lwp, stack_t *ss, gregset_t rs, lwpstatus_t *lwpstatus) {
 279   char lwpstatusfile[PROCFILE_LENGTH];
 280   int lwpfd, err;
 281 
 282   if (err = os::Solaris::thr_getstate(tid, flags, lwp, ss, rs))
 283     return (err);
 284   if (*flags == TRS_LWPID) {
 285     sprintf(lwpstatusfile, "/proc/%d/lwp/%d/lwpstatus", getpid(),
 286             *lwp);
 287     if ((lwpfd = open(lwpstatusfile, O_RDONLY)) < 0) {
 288       perror("thr_mutator_status: open lwpstatus");
 289       return (EINVAL);
 290     }
 291     if (pread(lwpfd, lwpstatus, sizeof (lwpstatus_t), (off_t)0) !=
 292         sizeof (lwpstatus_t)) {
 293       perror("thr_mutator_status: read lwpstatus");
 294       (void) close(lwpfd);
 295       return (EINVAL);
 296     }
 297     (void) close(lwpfd);
 298   }
 299   return (0);
 300 }
 301 
 302 #ifndef AMD64
 303 
 304 // Detecting SSE support by OS
 305 // From solaris_i486.s
 306 extern "C" bool sse_check();
 307 extern "C" bool sse_unavailable();
 308 
 309 enum { SSE_UNKNOWN, SSE_NOT_SUPPORTED, SSE_SUPPORTED};
 310 static int sse_status = SSE_UNKNOWN;
 311 
 312 
 313 static void  check_for_sse_support() {
 314   if (!VM_Version::supports_sse()) {
 315     sse_status = SSE_NOT_SUPPORTED;
 316     return;
 317   }
 318   // looking for _sse_hw in libc.so, if it does not exist or
 319   // the value (int) is 0, OS has no support for SSE
 320   int *sse_hwp;
 321   void *h;
 322 
 323   if ((h=dlopen("/usr/lib/libc.so", RTLD_LAZY)) == NULL) {
 324     //open failed, presume no support for SSE
 325     sse_status = SSE_NOT_SUPPORTED;
 326     return;
 327   }
 328   if ((sse_hwp = (int *)dlsym(h, "_sse_hw")) == NULL) {
 329     sse_status = SSE_NOT_SUPPORTED;
 330   } else if (*sse_hwp == 0) {
 331     sse_status = SSE_NOT_SUPPORTED;
 332   }
 333   dlclose(h);
 334 
 335   if (sse_status == SSE_UNKNOWN) {
 336     bool (*try_sse)() = (bool (*)())sse_check;
 337     sse_status = (*try_sse)() ? SSE_SUPPORTED : SSE_NOT_SUPPORTED;
 338   }
 339 
 340 }
 341 
 342 #endif // AMD64
 343 
 344 bool os::supports_sse() {
 345 #ifdef AMD64
 346   return true;
 347 #else
 348   if (sse_status == SSE_UNKNOWN)
 349     check_for_sse_support();
 350   return sse_status == SSE_SUPPORTED;
 351 #endif // AMD64
 352 }
 353 
 354 bool os::is_allocatable(size_t bytes) {
 355 #ifdef AMD64
 356   return true;
 357 #else
 358 
 359   if (bytes < 2 * G) {
 360     return true;
 361   }
 362 
 363   char* addr = reserve_memory(bytes, NULL);
 364 
 365   if (addr != NULL) {
 366     release_memory(addr, bytes);
 367   }
 368 
 369   return addr != NULL;
 370 #endif // AMD64
 371 
 372 }
 373 
 374 extern "C" void Fetch32PFI () ;
 375 extern "C" void Fetch32Resume () ;
 376 #ifdef AMD64
 377 extern "C" void FetchNPFI () ;
 378 extern "C" void FetchNResume () ;
 379 #endif // AMD64
 380 
 381 extern "C" JNIEXPORT int
 382 JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid,
 383                           int abort_if_unrecognized) {
 384   ucontext_t* uc = (ucontext_t*) ucVoid;
 385 
 386 #ifndef AMD64
 387   if (sig == SIGILL && info->si_addr == (caddr_t)sse_check) {
 388     // the SSE instruction faulted. supports_sse() need return false.
 389     uc->uc_mcontext.gregs[EIP] = (greg_t)sse_unavailable;
 390     return true;
 391   }
 392 #endif // !AMD64
 393 
 394   Thread* t = ThreadLocalStorage::get_thread_slow();  // slow & steady
 395 
 396   SignalHandlerMark shm(t);
 397 
 398   if(sig == SIGPIPE || sig == SIGXFSZ) {
 399     if (os::Solaris::chained_handler(sig, info, ucVoid)) {
 400       return true;
 401     } else {
 402       if (PrintMiscellaneous && (WizardMode || Verbose)) {
 403         char buf[64];
 404         warning("Ignoring %s - see 4229104 or 6499219",
 405                 os::exception_name(sig, buf, sizeof(buf)));
 406 
 407       }
 408       return true;
 409     }
 410   }
 411 
 412   JavaThread* thread = NULL;
 413   VMThread* vmthread = NULL;
 414 
 415   if (os::Solaris::signal_handlers_are_installed) {
 416     if (t != NULL ){
 417       if(t->is_Java_thread()) {
 418         thread = (JavaThread*)t;
 419       }
 420       else if(t->is_VM_thread()){
 421         vmthread = (VMThread *)t;
 422       }
 423     }
 424   }
 425 
 426   guarantee(sig != os::Solaris::SIGinterrupt(), "Can not chain VM interrupt signal, try -XX:+UseAltSigs");
 427 
 428   if (sig == os::Solaris::SIGasync()) {
 429     if(thread){
 430       OSThread::InterruptArguments args(thread, uc);
 431       thread->osthread()->do_interrupt_callbacks_at_interrupt(&args);
 432       return true;
 433     }
 434     else if(vmthread){
 435       OSThread::InterruptArguments args(vmthread, uc);
 436       vmthread->osthread()->do_interrupt_callbacks_at_interrupt(&args);
 437       return true;
 438     } else if (os::Solaris::chained_handler(sig, info, ucVoid)) {
 439       return true;
 440     } else {
 441       // If os::Solaris::SIGasync not chained, and this is a non-vm and
 442       // non-java thread
 443       return true;
 444     }
 445   }
 446 
 447   if (info == NULL || info->si_code <= 0 || info->si_code == SI_NOINFO) {
 448     // can't decode this kind of signal
 449     info = NULL;
 450   } else {
 451     assert(sig == info->si_signo, "bad siginfo");
 452   }
 453 
 454   // decide if this trap can be handled by a stub
 455   address stub = NULL;
 456 
 457   address pc          = NULL;
 458 
 459   //%note os_trap_1
 460   if (info != NULL && uc != NULL && thread != NULL) {
 461     // factor me: getPCfromContext
 462     pc = (address) uc->uc_mcontext.gregs[REG_PC];
 463 
 464     // SafeFetch32() support
 465     if (pc == (address) Fetch32PFI) {
 466       uc->uc_mcontext.gregs[REG_PC] = intptr_t(Fetch32Resume) ;
 467       return true ;
 468     }
 469 #ifdef AMD64
 470     if (pc == (address) FetchNPFI) {
 471        uc->uc_mcontext.gregs [REG_PC] = intptr_t(FetchNResume) ;
 472        return true ;
 473     }
 474 #endif // AMD64
 475 
 476     // Handle ALL stack overflow variations here
 477     if (sig == SIGSEGV && info->si_code == SEGV_ACCERR) {
 478       address addr = (address) info->si_addr;
 479       if (thread->in_stack_yellow_zone(addr)) {
 480         thread->disable_stack_yellow_zone();
 481         if (thread->thread_state() == _thread_in_Java) {
 482           // Throw a stack overflow exception.  Guard pages will be reenabled
 483           // while unwinding the stack.
 484           stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW);
 485         } else {
 486           // Thread was in the vm or native code.  Return and try to finish.
 487           return true;
 488         }
 489       } else if (thread->in_stack_red_zone(addr)) {
 490         // Fatal red zone violation.  Disable the guard pages and fall through
 491         // to handle_unexpected_exception way down below.
 492         thread->disable_stack_red_zone();
 493         tty->print_raw_cr("An irrecoverable stack overflow has occurred.");
 494       }
 495     }
 496 
 497     if (thread->thread_state() == _thread_in_vm) {
 498       if (sig == SIGBUS && info->si_code == BUS_OBJERR && thread->doing_unsafe_access()) {
 499         stub = StubRoutines::handler_for_unsafe_access();
 500       }
 501     }
 502 
 503     if (thread->thread_state() == _thread_in_Java) {
 504       // Support Safepoint Polling
 505       if ( sig == SIGSEGV && os::is_poll_address((address)info->si_addr)) {
 506         stub = SharedRuntime::get_poll_stub(pc);
 507       }
 508       else if (sig == SIGBUS && info->si_code == BUS_OBJERR) {
 509         // BugId 4454115: A read from a MappedByteBuffer can fault
 510         // here if the underlying file has been truncated.
 511         // Do not crash the VM in such a case.
 512         CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
 513         nmethod* nm = cb->is_nmethod() ? (nmethod*)cb : NULL;
 514         if (nm != NULL && nm->has_unsafe_access()) {
 515           stub = StubRoutines::handler_for_unsafe_access();
 516         }
 517       }
 518       else
 519       if (sig == SIGFPE && info->si_code == FPE_INTDIV) {
 520         // integer divide by zero
 521         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_DIVIDE_BY_ZERO);
 522       }
 523 #ifndef AMD64
 524       else if (sig == SIGFPE && info->si_code == FPE_FLTDIV) {
 525         // floating-point divide by zero
 526         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_DIVIDE_BY_ZERO);
 527       }
 528       else if (sig == SIGFPE && info->si_code == FPE_FLTINV) {
 529         // The encoding of D2I in i486.ad can cause an exception prior
 530         // to the fist instruction if there was an invalid operation
 531         // pending. We want to dismiss that exception. From the win_32
 532         // side it also seems that if it really was the fist causing
 533         // the exception that we do the d2i by hand with different
 534         // rounding. Seems kind of weird. QQQ TODO
 535         // Note that we take the exception at the NEXT floating point instruction.
 536         if (pc[0] == 0xDB) {
 537             assert(pc[0] == 0xDB, "not a FIST opcode");
 538             assert(pc[1] == 0x14, "not a FIST opcode");
 539             assert(pc[2] == 0x24, "not a FIST opcode");
 540             return true;
 541         } else {
 542             assert(pc[-3] == 0xDB, "not an flt invalid opcode");
 543             assert(pc[-2] == 0x14, "not an flt invalid opcode");
 544             assert(pc[-1] == 0x24, "not an flt invalid opcode");
 545         }
 546       }
 547       else if (sig == SIGFPE ) {
 548         tty->print_cr("caught SIGFPE, info 0x%x.", info->si_code);
 549       }
 550 #endif // !AMD64
 551 
 552         // QQQ It doesn't seem that we need to do this on x86 because we should be able
 553         // to return properly from the handler without this extra stuff on the back side.
 554 
 555       else if (sig == SIGSEGV && info->si_code > 0 && !MacroAssembler::needs_explicit_null_check((intptr_t)info->si_addr)) {
 556         // Determination of interpreter/vtable stub/compiled code null exception
 557         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
 558       }
 559     }
 560 
 561     // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in
 562     // and the heap gets shrunk before the field access.
 563     if ((sig == SIGSEGV) || (sig == SIGBUS)) {
 564       address addr = JNI_FastGetField::find_slowcase_pc(pc);
 565       if (addr != (address)-1) {
 566         stub = addr;
 567       }
 568     }
 569 
 570     // Check to see if we caught the safepoint code in the
 571     // process of write protecting the memory serialization page.
 572     // It write enables the page immediately after protecting it
 573     // so we can just return to retry the write.
 574     if ((sig == SIGSEGV) &&
 575         os::is_memory_serialize_page(thread, (address)info->si_addr)) {
 576       // Block current thread until the memory serialize page permission restored.
 577       os::block_on_serialize_page_trap();
 578       return true;
 579     }
 580   }
 581 
 582   // Execution protection violation
 583   //
 584   // Preventative code for future versions of Solaris which may
 585   // enable execution protection when running the 32-bit VM on AMD64.
 586   //
 587   // This should be kept as the last step in the triage.  We don't
 588   // have a dedicated trap number for a no-execute fault, so be
 589   // conservative and allow other handlers the first shot.
 590   //
 591   // Note: We don't test that info->si_code == SEGV_ACCERR here.
 592   // this si_code is so generic that it is almost meaningless; and
 593   // the si_code for this condition may change in the future.
 594   // Furthermore, a false-positive should be harmless.
 595   if (UnguardOnExecutionViolation > 0 &&
 596       (sig == SIGSEGV || sig == SIGBUS) &&
 597       uc->uc_mcontext.gregs[TRAPNO] == T_PGFLT) {  // page fault
 598     int page_size = os::vm_page_size();
 599     address addr = (address) info->si_addr;
 600     address pc = (address) uc->uc_mcontext.gregs[REG_PC];
 601     // Make sure the pc and the faulting address are sane.
 602     //
 603     // If an instruction spans a page boundary, and the page containing
 604     // the beginning of the instruction is executable but the following
 605     // page is not, the pc and the faulting address might be slightly
 606     // different - we still want to unguard the 2nd page in this case.
 607     //
 608     // 15 bytes seems to be a (very) safe value for max instruction size.
 609     bool pc_is_near_addr =
 610       (pointer_delta((void*) addr, (void*) pc, sizeof(char)) < 15);
 611     bool instr_spans_page_boundary =
 612       (align_size_down((intptr_t) pc ^ (intptr_t) addr,
 613                        (intptr_t) page_size) > 0);
 614 
 615     if (pc == addr || (pc_is_near_addr && instr_spans_page_boundary)) {
 616       static volatile address last_addr =
 617         (address) os::non_memory_address_word();
 618 
 619       // In conservative mode, don't unguard unless the address is in the VM
 620       if (addr != last_addr &&
 621           (UnguardOnExecutionViolation > 1 || os::address_is_in_vm(addr))) {
 622 
 623         // Make memory rwx and retry
 624         address page_start =
 625           (address) align_size_down((intptr_t) addr, (intptr_t) page_size);
 626         bool res = os::protect_memory((char*) page_start, page_size,
 627                                       os::MEM_PROT_RWX);
 628 
 629         if (PrintMiscellaneous && Verbose) {
 630           char buf[256];
 631           jio_snprintf(buf, sizeof(buf), "Execution protection violation "
 632                        "at " INTPTR_FORMAT
 633                        ", unguarding " INTPTR_FORMAT ": %s, errno=%d", addr,
 634                        page_start, (res ? "success" : "failed"), errno);
 635           tty->print_raw_cr(buf);
 636         }
 637         stub = pc;
 638 
 639         // Set last_addr so if we fault again at the same address, we don't end
 640         // up in an endless loop.
 641         //
 642         // There are two potential complications here.  Two threads trapping at
 643         // the same address at the same time could cause one of the threads to
 644         // think it already unguarded, and abort the VM.  Likely very rare.
 645         //
 646         // The other race involves two threads alternately trapping at
 647         // different addresses and failing to unguard the page, resulting in
 648         // an endless loop.  This condition is probably even more unlikely than
 649         // the first.
 650         //
 651         // Although both cases could be avoided by using locks or thread local
 652         // last_addr, these solutions are unnecessary complication: this
 653         // handler is a best-effort safety net, not a complete solution.  It is
 654         // disabled by default and should only be used as a workaround in case
 655         // we missed any no-execute-unsafe VM code.
 656 
 657         last_addr = addr;
 658       }
 659     }
 660   }
 661 
 662   if (stub != NULL) {
 663     // save all thread context in case we need to restore it
 664 
 665     if (thread != NULL) thread->set_saved_exception_pc(pc);
 666     // 12/02/99: On Sparc it appears that the full context is also saved
 667     // but as yet, no one looks at or restores that saved context
 668     // factor me: setPC
 669     uc->uc_mcontext.gregs[REG_PC] = (greg_t)stub;
 670     return true;
 671   }
 672 
 673   // signal-chaining
 674   if (os::Solaris::chained_handler(sig, info, ucVoid)) {
 675     return true;
 676   }
 677 
 678 #ifndef AMD64
 679   // Workaround (bug 4900493) for Solaris kernel bug 4966651.
 680   // Handle an undefined selector caused by an attempt to assign
 681   // fs in libthread getipriptr(). With the current libthread design every 512
 682   // thread creations the LDT for a private thread data structure is extended
 683   // and thre is a hazard that and another thread attempting a thread creation
 684   // will use a stale LDTR that doesn't reflect the structure's growth,
 685   // causing a GP fault.
 686   // Enforce the probable limit of passes through here to guard against an
 687   // infinite loop if some other move to fs caused the GP fault. Note that
 688   // this loop counter is ultimately a heuristic as it is possible for
 689   // more than one thread to generate this fault at a time in an MP system.
 690   // In the case of the loop count being exceeded or if the poll fails
 691   // just fall through to a fatal error.
 692   // If there is some other source of T_GPFLT traps and the text at EIP is
 693   // unreadable this code will loop infinitely until the stack is exausted.
 694   // The key to diagnosis in this case is to look for the bottom signal handler
 695   // frame.
 696 
 697   if(! IgnoreLibthreadGPFault) {
 698     if (sig == SIGSEGV && uc->uc_mcontext.gregs[TRAPNO] == T_GPFLT) {
 699       const unsigned char *p =
 700                         (unsigned const char *) uc->uc_mcontext.gregs[EIP];
 701 
 702       // Expected instruction?
 703 
 704       if(p[0] == movlfs[0] && p[1] == movlfs[1]) {
 705 
 706         Atomic::inc(&ldtr_refresh);
 707 
 708         // Infinite loop?
 709 
 710         if(ldtr_refresh < ((2 << 16) / PAGESIZE)) {
 711 
 712           // No, force scheduling to get a fresh view of the LDTR
 713 
 714           if(poll(NULL, 0, 10) == 0) {
 715 
 716             // Retry the move
 717 
 718             return false;
 719           }
 720         }
 721       }
 722     }
 723   }
 724 #endif // !AMD64
 725 
 726   if (!abort_if_unrecognized) {
 727     // caller wants another chance, so give it to him
 728     return false;
 729   }
 730 
 731   if (!os::Solaris::libjsig_is_loaded) {
 732     struct sigaction oldAct;
 733     sigaction(sig, (struct sigaction *)0, &oldAct);
 734     if (oldAct.sa_sigaction != signalHandler) {
 735       void* sighand = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
 736                                           : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
 737       warning("Unexpected Signal %d occurred under user-defined signal handler %#lx", sig, (long)sighand);
 738     }
 739   }
 740 
 741   if (pc == NULL && uc != NULL) {
 742     pc = (address) uc->uc_mcontext.gregs[REG_PC];
 743   }
 744 
 745   // unmask current signal
 746   sigset_t newset;
 747   sigemptyset(&newset);
 748   sigaddset(&newset, sig);
 749   sigprocmask(SIG_UNBLOCK, &newset, NULL);
 750 
 751   // Determine which sort of error to throw.  Out of swap may signal
 752   // on the thread stack, which could get a mapping error when touched.
 753   address addr = (address) info->si_addr;
 754   if (sig == SIGBUS && info->si_code == BUS_OBJERR && info->si_errno == ENOMEM) {
 755     vm_exit_out_of_memory(0, "Out of swap space to map in thread stack.");
 756   }
 757 
 758   VMError err(t, sig, pc, info, ucVoid);
 759   err.report_and_die();
 760 
 761   ShouldNotReachHere();
 762 }
 763 
 764 void os::print_context(outputStream *st, void *context) {
 765   if (context == NULL) return;
 766 
 767   ucontext_t *uc = (ucontext_t*)context;
 768   st->print_cr("Registers:");
 769 #ifdef AMD64
 770   st->print(  "RAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RAX]);
 771   st->print(", RBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RBX]);
 772   st->print(", RCX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RCX]);
 773   st->print(", RDX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RDX]);
 774   st->cr();
 775   st->print(  "RSP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RSP]);
 776   st->print(", RBP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RBP]);
 777   st->print(", RSI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RSI]);
 778   st->print(", RDI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RDI]);
 779   st->cr();
 780   st->print(  "R8 =" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R8]);
 781   st->print(", R9 =" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R9]);
 782   st->print(", R10=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R10]);
 783   st->print(", R11=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R11]);
 784   st->cr();
 785   st->print(  "R12=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R12]);
 786   st->print(", R13=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R13]);
 787   st->print(", R14=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R14]);
 788   st->print(", R15=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R15]);
 789   st->cr();
 790   st->print(  "RIP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RIP]);
 791   st->print(", RFLAGS=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RFL]);
 792 #else
 793   st->print(  "EAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EAX]);
 794   st->print(", EBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EBX]);
 795   st->print(", ECX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[ECX]);
 796   st->print(", EDX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EDX]);
 797   st->cr();
 798   st->print(  "ESP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[UESP]);
 799   st->print(", EBP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EBP]);
 800   st->print(", ESI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[ESI]);
 801   st->print(", EDI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EDI]);
 802   st->cr();
 803   st->print(  "EIP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EIP]);
 804   st->print(", EFLAGS=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EFL]);
 805 #endif // AMD64
 806   st->cr();
 807   st->cr();
 808 
 809   intptr_t *sp = (intptr_t *)os::Solaris::ucontext_get_sp(uc);
 810   st->print_cr("Top of Stack: (sp=" PTR_FORMAT ")", sp);
 811   print_hex_dump(st, (address)sp, (address)(sp + 8*sizeof(intptr_t)), sizeof(intptr_t));
 812   st->cr();
 813 
 814   // Note: it may be unsafe to inspect memory near pc. For example, pc may
 815   // point to garbage if entry point in an nmethod is corrupted. Leave
 816   // this at the end, and hope for the best.
 817   ExtendedPC epc = os::Solaris::ucontext_get_ExtendedPC(uc);
 818   address pc = epc.pc();
 819   st->print_cr("Instructions: (pc=" PTR_FORMAT ")", pc);
 820   print_hex_dump(st, pc - 32, pc + 32, sizeof(char));
 821 }
 822 
 823 void os::print_register_info(outputStream *st, void *context) {
 824   if (context == NULL) return;
 825 
 826   ucontext_t *uc = (ucontext_t*)context;
 827 
 828   st->print_cr("Register to memory mapping:");
 829   st->cr();
 830 
 831   // this is horrendously verbose but the layout of the registers in the
 832   // context does not match how we defined our abstract Register set, so
 833   // we can't just iterate through the gregs area
 834 
 835   // this is only for the "general purpose" registers
 836 
 837 #ifdef AMD64
 838   st->print("RAX="); print_location(st, uc->uc_mcontext.gregs[REG_RAX]);
 839   st->print("RBX="); print_location(st, uc->uc_mcontext.gregs[REG_RBX]);
 840   st->print("RCX="); print_location(st, uc->uc_mcontext.gregs[REG_RCX]);
 841   st->print("RDX="); print_location(st, uc->uc_mcontext.gregs[REG_RDX]);
 842   st->print("RSP="); print_location(st, uc->uc_mcontext.gregs[REG_RSP]);
 843   st->print("RBP="); print_location(st, uc->uc_mcontext.gregs[REG_RBP]);
 844   st->print("RSI="); print_location(st, uc->uc_mcontext.gregs[REG_RSI]);
 845   st->print("RDI="); print_location(st, uc->uc_mcontext.gregs[REG_RDI]);
 846   st->print("R8 ="); print_location(st, uc->uc_mcontext.gregs[REG_R8]);
 847   st->print("R9 ="); print_location(st, uc->uc_mcontext.gregs[REG_R9]);
 848   st->print("R10="); print_location(st, uc->uc_mcontext.gregs[REG_R10]);
 849   st->print("R11="); print_location(st, uc->uc_mcontext.gregs[REG_R11]);
 850   st->print("R12="); print_location(st, uc->uc_mcontext.gregs[REG_R12]);
 851   st->print("R13="); print_location(st, uc->uc_mcontext.gregs[REG_R13]);
 852   st->print("R14="); print_location(st, uc->uc_mcontext.gregs[REG_R14]);
 853   st->print("R15="); print_location(st, uc->uc_mcontext.gregs[REG_R15]);
 854 #else
 855   st->print("EAX="); print_location(st, uc->uc_mcontext.gregs[EAX]);
 856   st->print("EBX="); print_location(st, uc->uc_mcontext.gregs[EBX]);
 857   st->print("ECX="); print_location(st, uc->uc_mcontext.gregs[ECX]);
 858   st->print("EDX="); print_location(st, uc->uc_mcontext.gregs[EDX]);
 859   st->print("ESP="); print_location(st, uc->uc_mcontext.gregs[UESP]);
 860   st->print("EBP="); print_location(st, uc->uc_mcontext.gregs[EBP]);
 861   st->print("ESI="); print_location(st, uc->uc_mcontext.gregs[ESI]);
 862   st->print("EDI="); print_location(st, uc->uc_mcontext.gregs[EDI]);
 863 #endif
 864 
 865   st->cr();
 866 }
 867 
 868 
 869 #ifdef AMD64
 870 void os::Solaris::init_thread_fpu_state(void) {
 871   // Nothing to do
 872 }
 873 #else
 874 // From solaris_i486.s
 875 extern "C" void fixcw();
 876 
 877 void os::Solaris::init_thread_fpu_state(void) {
 878   // Set fpu to 53 bit precision. This happens too early to use a stub.
 879   fixcw();
 880 }
 881 
 882 // These routines are the initial value of atomic_xchg_entry(),
 883 // atomic_cmpxchg_entry(), atomic_inc_entry() and fence_entry()
 884 // until initialization is complete.
 885 // TODO - replace with .il implementation when compiler supports it.
 886 
 887 typedef jint  xchg_func_t        (jint,  volatile jint*);
 888 typedef jint  cmpxchg_func_t     (jint,  volatile jint*,  jint);
 889 typedef jlong cmpxchg_long_func_t(jlong, volatile jlong*, jlong);
 890 typedef jint  add_func_t         (jint,  volatile jint*);
 891 
 892 jint os::atomic_xchg_bootstrap(jint exchange_value, volatile jint* dest) {
 893   // try to use the stub:
 894   xchg_func_t* func = CAST_TO_FN_PTR(xchg_func_t*, StubRoutines::atomic_xchg_entry());
 895 
 896   if (func != NULL) {
 897     os::atomic_xchg_func = func;
 898     return (*func)(exchange_value, dest);
 899   }
 900   assert(Threads::number_of_threads() == 0, "for bootstrap only");
 901 
 902   jint old_value = *dest;
 903   *dest = exchange_value;
 904   return old_value;
 905 }
 906 
 907 jint os::atomic_cmpxchg_bootstrap(jint exchange_value, volatile jint* dest, jint compare_value) {
 908   // try to use the stub:
 909   cmpxchg_func_t* func = CAST_TO_FN_PTR(cmpxchg_func_t*, StubRoutines::atomic_cmpxchg_entry());
 910 
 911   if (func != NULL) {
 912     os::atomic_cmpxchg_func = func;
 913     return (*func)(exchange_value, dest, compare_value);
 914   }
 915   assert(Threads::number_of_threads() == 0, "for bootstrap only");
 916 
 917   jint old_value = *dest;
 918   if (old_value == compare_value)
 919     *dest = exchange_value;
 920   return old_value;
 921 }
 922 
 923 jlong os::atomic_cmpxchg_long_bootstrap(jlong exchange_value, volatile jlong* dest, jlong compare_value) {
 924   // try to use the stub:
 925   cmpxchg_long_func_t* func = CAST_TO_FN_PTR(cmpxchg_long_func_t*, StubRoutines::atomic_cmpxchg_long_entry());
 926 
 927   if (func != NULL) {
 928     os::atomic_cmpxchg_long_func = func;
 929     return (*func)(exchange_value, dest, compare_value);
 930   }
 931   assert(Threads::number_of_threads() == 0, "for bootstrap only");
 932 
 933   jlong old_value = *dest;
 934   if (old_value == compare_value)
 935     *dest = exchange_value;
 936   return old_value;
 937 }
 938 
 939 jint os::atomic_add_bootstrap(jint add_value, volatile jint* dest) {
 940   // try to use the stub:
 941   add_func_t* func = CAST_TO_FN_PTR(add_func_t*, StubRoutines::atomic_add_entry());
 942 
 943   if (func != NULL) {
 944     os::atomic_add_func = func;
 945     return (*func)(add_value, dest);
 946   }
 947   assert(Threads::number_of_threads() == 0, "for bootstrap only");
 948 
 949   return (*dest) += add_value;
 950 }
 951 
 952 xchg_func_t*         os::atomic_xchg_func         = os::atomic_xchg_bootstrap;
 953 cmpxchg_func_t*      os::atomic_cmpxchg_func      = os::atomic_cmpxchg_bootstrap;
 954 cmpxchg_long_func_t* os::atomic_cmpxchg_long_func = os::atomic_cmpxchg_long_bootstrap;
 955 add_func_t*          os::atomic_add_func          = os::atomic_add_bootstrap;
 956 
 957 extern "C" void _solaris_raw_setup_fpu(address ptr);
 958 void os::setup_fpu() {
 959   address fpu_cntrl = StubRoutines::addr_fpu_cntrl_wrd_std();
 960   _solaris_raw_setup_fpu(fpu_cntrl);
 961 }
 962 #endif // AMD64
 963 
 964 #ifndef PRODUCT
 965 void os::verify_stack_alignment() {
 966 #ifdef AMD64
 967   assert(((intptr_t)os::current_stack_pointer() & (StackAlignmentInBytes-1)) == 0, "incorrect stack alignment");
 968 #endif
 969 }
 970 #endif