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