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