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_linux.h"
  34 #include "memory/allocation.inline.hpp"
  35 #include "mutex_linux.inline.hpp"
  36 #include "nativeInst_x86.hpp"
  37 #include "os_share_linux.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_linux.inline.hpp"
  53 #include "utilities/events.hpp"
  54 #include "utilities/vmError.hpp"
  55 
  56 // put OS-includes here
  57 # include <sys/types.h>
  58 # include <sys/mman.h>
  59 # include <pthread.h>
  60 # include <signal.h>
  61 # include <errno.h>
  62 # include <dlfcn.h>
  63 # include <stdlib.h>
  64 # include <stdio.h>
  65 # include <unistd.h>
  66 # include <sys/resource.h>
  67 # include <pthread.h>
  68 # include <sys/stat.h>
  69 # include <sys/time.h>
  70 # include <sys/utsname.h>
  71 # include <sys/socket.h>
  72 # include <sys/wait.h>
  73 # include <pwd.h>
  74 # include <poll.h>
  75 # include <ucontext.h>
  76 # include <fpu_control.h>
  77 
  78 #ifdef AMD64
  79 #define REG_SP REG_RSP
  80 #define REG_PC REG_RIP
  81 #define REG_FP REG_RBP
  82 #define SPELL_REG_SP "rsp"
  83 #define SPELL_REG_FP "rbp"
  84 #else
  85 #define REG_SP REG_UESP
  86 #define REG_PC REG_EIP
  87 #define REG_FP REG_EBP
  88 #define SPELL_REG_SP "esp"
  89 #define SPELL_REG_FP "ebp"
  90 #endif // AMD64
  91 
  92 address os::current_stack_pointer() {
  93 #ifdef SPARC_WORKS
  94   register void *esp;
  95   __asm__("mov %%"SPELL_REG_SP", %0":"=r"(esp));
  96   return (address) ((char*)esp + sizeof(long)*2);
  97 #else
  98   register void *esp __asm__ (SPELL_REG_SP);
  99   return (address) esp;
 100 #endif
 101 }
 102 
 103 char* os::non_memory_address_word() {
 104   // Must never look like an address returned by reserve_memory,
 105   // even in its subfields (as defined by the CPU immediate fields,
 106   // if the CPU splits constants across multiple instructions).
 107 
 108   return (char*) -1;
 109 }
 110 
 111 void os::initialize_thread(Thread* thr) {
 112 // Nothing to do.
 113 }
 114 
 115 address os::Linux::ucontext_get_pc(ucontext_t * uc) {
 116   return (address)uc->uc_mcontext.gregs[REG_PC];
 117 }
 118 
 119 intptr_t* os::Linux::ucontext_get_sp(ucontext_t * uc) {
 120   return (intptr_t*)uc->uc_mcontext.gregs[REG_SP];
 121 }
 122 
 123 intptr_t* os::Linux::ucontext_get_fp(ucontext_t * uc) {
 124   return (intptr_t*)uc->uc_mcontext.gregs[REG_FP];
 125 }
 126 
 127 // For Forte Analyzer AsyncGetCallTrace profiling support - thread
 128 // is currently interrupted by SIGPROF.
 129 // os::Solaris::fetch_frame_from_ucontext() tries to skip nested signal
 130 // frames. Currently we don't do that on Linux, so it's the same as
 131 // os::fetch_frame_from_context().
 132 ExtendedPC os::Linux::fetch_frame_from_ucontext(Thread* thread,
 133   ucontext_t* uc, intptr_t** ret_sp, intptr_t** ret_fp) {
 134 
 135   assert(thread != NULL, "just checking");
 136   assert(ret_sp != NULL, "just checking");
 137   assert(ret_fp != NULL, "just checking");
 138 
 139   return os::fetch_frame_from_context(uc, ret_sp, ret_fp);
 140 }
 141 
 142 ExtendedPC os::fetch_frame_from_context(void* ucVoid,
 143                     intptr_t** ret_sp, intptr_t** ret_fp) {
 144 
 145   ExtendedPC  epc;
 146   ucontext_t* uc = (ucontext_t*)ucVoid;
 147 
 148   if (uc != NULL) {
 149     epc = ExtendedPC(os::Linux::ucontext_get_pc(uc));
 150     if (ret_sp) *ret_sp = os::Linux::ucontext_get_sp(uc);
 151     if (ret_fp) *ret_fp = os::Linux::ucontext_get_fp(uc);
 152   } else {
 153     // construct empty ExtendedPC for return value checking
 154     epc = ExtendedPC(NULL);
 155     if (ret_sp) *ret_sp = (intptr_t *)NULL;
 156     if (ret_fp) *ret_fp = (intptr_t *)NULL;
 157   }
 158 
 159   return epc;
 160 }
 161 
 162 frame os::fetch_frame_from_context(void* ucVoid) {
 163   intptr_t* sp;
 164   intptr_t* fp;
 165   ExtendedPC epc = fetch_frame_from_context(ucVoid, &sp, &fp);
 166   return frame(sp, fp, epc.pc());
 167 }
 168 
 169 // By default, gcc always save frame pointer (%ebp/%rbp) on stack. It may get
 170 // turned off by -fomit-frame-pointer,
 171 frame os::get_sender_for_C_frame(frame* fr) {
 172   return frame(fr->sender_sp(), fr->link(), fr->sender_pc());
 173 }
 174 
 175 intptr_t* _get_previous_fp() {
 176 #ifdef SPARC_WORKS
 177   register intptr_t **ebp;
 178   __asm__("mov %%"SPELL_REG_FP", %0":"=r"(ebp));
 179 #else
 180   register intptr_t **ebp __asm__ (SPELL_REG_FP);
 181 #endif
 182   return (intptr_t*) *ebp;   // we want what it points to.
 183 }
 184 
 185 
 186 frame os::current_frame() {
 187   intptr_t* fp = _get_previous_fp();
 188   frame myframe((intptr_t*)os::current_stack_pointer(),
 189                 (intptr_t*)fp,
 190                 CAST_FROM_FN_PTR(address, os::current_frame));
 191   if (os::is_first_C_frame(&myframe)) {
 192     // stack is not walkable
 193     return frame(NULL, NULL, NULL);
 194   } else {
 195     return os::get_sender_for_C_frame(&myframe);
 196   }
 197 }
 198 
 199 // Utility functions
 200 
 201 // From IA32 System Programming Guide
 202 enum {
 203   trap_page_fault = 0xE
 204 };
 205 
 206 extern "C" void Fetch32PFI () ;
 207 extern "C" void Fetch32Resume () ;
 208 #ifdef AMD64
 209 extern "C" void FetchNPFI () ;
 210 extern "C" void FetchNResume () ;
 211 #endif // AMD64
 212 
 213 extern "C" JNIEXPORT int
 214 JVM_handle_linux_signal(int sig,
 215                         siginfo_t* info,
 216                         void* ucVoid,
 217                         int abort_if_unrecognized) {
 218   ucontext_t* uc = (ucontext_t*) ucVoid;
 219 
 220   Thread* t = ThreadLocalStorage::get_thread_slow();
 221 
 222   SignalHandlerMark shm(t);
 223 
 224   // Note: it's not uncommon that JNI code uses signal/sigset to install
 225   // then restore certain signal handler (e.g. to temporarily block SIGPIPE,
 226   // or have a SIGILL handler when detecting CPU type). When that happens,
 227   // JVM_handle_linux_signal() might be invoked with junk info/ucVoid. To
 228   // avoid unnecessary crash when libjsig is not preloaded, try handle signals
 229   // that do not require siginfo/ucontext first.
 230 
 231   if (sig == SIGPIPE || sig == SIGXFSZ) {
 232     // allow chained handler to go first
 233     if (os::Linux::chained_handler(sig, info, ucVoid)) {
 234       return true;
 235     } else {
 236       if (PrintMiscellaneous && (WizardMode || Verbose)) {
 237         char buf[64];
 238         warning("Ignoring %s - see bugs 4229104 or 646499219",
 239                 os::exception_name(sig, buf, sizeof(buf)));
 240       }
 241       return true;
 242     }
 243   }
 244 
 245   JavaThread* thread = NULL;
 246   VMThread* vmthread = NULL;
 247   if (os::Linux::signal_handlers_are_installed) {
 248     if (t != NULL ){
 249       if(t->is_Java_thread()) {
 250         thread = (JavaThread*)t;
 251       }
 252       else if(t->is_VM_thread()){
 253         vmthread = (VMThread *)t;
 254       }
 255     }
 256   }
 257 /*
 258   NOTE: does not seem to work on linux.
 259   if (info == NULL || info->si_code <= 0 || info->si_code == SI_NOINFO) {
 260     // can't decode this kind of signal
 261     info = NULL;
 262   } else {
 263     assert(sig == info->si_signo, "bad siginfo");
 264   }
 265 */
 266   // decide if this trap can be handled by a stub
 267   address stub = NULL;
 268 
 269   address pc          = NULL;
 270 
 271   //%note os_trap_1
 272   if (info != NULL && uc != NULL && thread != NULL) {
 273     pc = (address) os::Linux::ucontext_get_pc(uc);
 274 
 275     if (pc == (address) Fetch32PFI) {
 276        uc->uc_mcontext.gregs[REG_PC] = intptr_t(Fetch32Resume) ;
 277        return 1 ;
 278     }
 279 #ifdef AMD64
 280     if (pc == (address) FetchNPFI) {
 281        uc->uc_mcontext.gregs[REG_PC] = intptr_t (FetchNResume) ;
 282        return 1 ;
 283     }
 284 #endif // AMD64
 285 
 286     // Handle ALL stack overflow variations here
 287     if (sig == SIGSEGV) {
 288       address addr = (address) info->si_addr;
 289 
 290       // check if fault address is within thread stack
 291       if (addr < thread->stack_base() &&
 292           addr >= thread->stack_base() - thread->stack_size()) {
 293         // stack overflow
 294         if (thread->in_stack_yellow_zone(addr)) {
 295           thread->disable_stack_yellow_zone();
 296           if (thread->thread_state() == _thread_in_Java) {
 297             // Throw a stack overflow exception.  Guard pages will be reenabled
 298             // while unwinding the stack.
 299             stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW);
 300           } else {
 301             // Thread was in the vm or native code.  Return and try to finish.
 302             return 1;
 303           }
 304         } else if (thread->in_stack_red_zone(addr)) {
 305           // Fatal red zone violation.  Disable the guard pages and fall through
 306           // to handle_unexpected_exception way down below.
 307           thread->disable_stack_red_zone();
 308           tty->print_raw_cr("An irrecoverable stack overflow has occurred.");
 309         } else {
 310           // Accessing stack address below sp may cause SEGV if current
 311           // thread has MAP_GROWSDOWN stack. This should only happen when
 312           // current thread was created by user code with MAP_GROWSDOWN flag
 313           // and then attached to VM. See notes in os_linux.cpp.
 314           if (thread->osthread()->expanding_stack() == 0) {
 315              thread->osthread()->set_expanding_stack();
 316              if (os::Linux::manually_expand_stack(thread, addr)) {
 317                thread->osthread()->clear_expanding_stack();
 318                return 1;
 319              }
 320              thread->osthread()->clear_expanding_stack();
 321           } else {
 322              fatal("recursive segv. expanding stack.");
 323           }
 324         }
 325       }
 326     }
 327 
 328     if (thread->thread_state() == _thread_in_Java) {
 329       // Java thread running in Java code => find exception handler if any
 330       // a fault inside compiled code, the interpreter, or a stub
 331 
 332       if (sig == SIGSEGV && os::is_poll_address((address)info->si_addr)) {
 333         stub = SharedRuntime::get_poll_stub(pc);
 334       } else if (sig == SIGBUS /* && info->si_code == BUS_OBJERR */) {
 335         // BugId 4454115: A read from a MappedByteBuffer can fault
 336         // here if the underlying file has been truncated.
 337         // Do not crash the VM in such a case.
 338         CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
 339         nmethod* nm = cb->is_nmethod() ? (nmethod*)cb : NULL;
 340         if (nm != NULL && nm->has_unsafe_access()) {
 341           stub = StubRoutines::handler_for_unsafe_access();
 342         }
 343       }
 344       else
 345 
 346 #ifdef AMD64
 347       if (sig == SIGFPE  &&
 348           (info->si_code == FPE_INTDIV || info->si_code == FPE_FLTDIV)) {
 349         stub =
 350           SharedRuntime::
 351           continuation_for_implicit_exception(thread,
 352                                               pc,
 353                                               SharedRuntime::
 354                                               IMPLICIT_DIVIDE_BY_ZERO);
 355 #else
 356       if (sig == SIGFPE /* && info->si_code == FPE_INTDIV */) {
 357         // HACK: si_code does not work on linux 2.2.12-20!!!
 358         int op = pc[0];
 359         if (op == 0xDB) {
 360           // FIST
 361           // TODO: The encoding of D2I in i486.ad can cause an exception
 362           // prior to the fist instruction if there was an invalid operation
 363           // pending. We want to dismiss that exception. From the win_32
 364           // side it also seems that if it really was the fist causing
 365           // the exception that we do the d2i by hand with different
 366           // rounding. Seems kind of weird.
 367           // NOTE: that we take the exception at the NEXT floating point instruction.
 368           assert(pc[0] == 0xDB, "not a FIST opcode");
 369           assert(pc[1] == 0x14, "not a FIST opcode");
 370           assert(pc[2] == 0x24, "not a FIST opcode");
 371           return true;
 372         } else if (op == 0xF7) {
 373           // IDIV
 374           stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_DIVIDE_BY_ZERO);
 375         } else {
 376           // TODO: handle more cases if we are using other x86 instructions
 377           //   that can generate SIGFPE signal on linux.
 378           tty->print_cr("unknown opcode 0x%X with SIGFPE.", op);
 379           fatal("please update this code.");
 380         }
 381 #endif // AMD64
 382       } else if (sig == SIGSEGV &&
 383                !MacroAssembler::needs_explicit_null_check((intptr_t)info->si_addr)) {
 384           // Determination of interpreter/vtable stub/compiled code null exception
 385           stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
 386       }
 387     } else if (thread->thread_state() == _thread_in_vm &&
 388                sig == SIGBUS && /* info->si_code == BUS_OBJERR && */
 389                thread->doing_unsafe_access()) {
 390         stub = StubRoutines::handler_for_unsafe_access();
 391     }
 392 
 393     // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in
 394     // and the heap gets shrunk before the field access.
 395     if ((sig == SIGSEGV) || (sig == SIGBUS)) {
 396       address addr = JNI_FastGetField::find_slowcase_pc(pc);
 397       if (addr != (address)-1) {
 398         stub = addr;
 399       }
 400     }
 401 
 402     // Check to see if we caught the safepoint code in the
 403     // process of write protecting the memory serialization page.
 404     // It write enables the page immediately after protecting it
 405     // so we can just return to retry the write.
 406     if ((sig == SIGSEGV) &&
 407         os::is_memory_serialize_page(thread, (address) info->si_addr)) {
 408       // Block current thread until the memory serialize page permission restored.
 409       os::block_on_serialize_page_trap();
 410       return true;
 411     }
 412   }
 413 
 414 #ifndef AMD64
 415   // Execution protection violation
 416   //
 417   // This should be kept as the last step in the triage.  We don't
 418   // have a dedicated trap number for a no-execute fault, so be
 419   // conservative and allow other handlers the first shot.
 420   //
 421   // Note: We don't test that info->si_code == SEGV_ACCERR here.
 422   // this si_code is so generic that it is almost meaningless; and
 423   // the si_code for this condition may change in the future.
 424   // Furthermore, a false-positive should be harmless.
 425   if (UnguardOnExecutionViolation > 0 &&
 426       (sig == SIGSEGV || sig == SIGBUS) &&
 427       uc->uc_mcontext.gregs[REG_TRAPNO] == trap_page_fault) {
 428     int page_size = os::vm_page_size();
 429     address addr = (address) info->si_addr;
 430     address pc = os::Linux::ucontext_get_pc(uc);
 431     // Make sure the pc and the faulting address are sane.
 432     //
 433     // If an instruction spans a page boundary, and the page containing
 434     // the beginning of the instruction is executable but the following
 435     // page is not, the pc and the faulting address might be slightly
 436     // different - we still want to unguard the 2nd page in this case.
 437     //
 438     // 15 bytes seems to be a (very) safe value for max instruction size.
 439     bool pc_is_near_addr =
 440       (pointer_delta((void*) addr, (void*) pc, sizeof(char)) < 15);
 441     bool instr_spans_page_boundary =
 442       (align_size_down((intptr_t) pc ^ (intptr_t) addr,
 443                        (intptr_t) page_size) > 0);
 444 
 445     if (pc == addr || (pc_is_near_addr && instr_spans_page_boundary)) {
 446       static volatile address last_addr =
 447         (address) os::non_memory_address_word();
 448 
 449       // In conservative mode, don't unguard unless the address is in the VM
 450       if (addr != last_addr &&
 451           (UnguardOnExecutionViolation > 1 || os::address_is_in_vm(addr))) {
 452 
 453         // Set memory to RWX and retry
 454         address page_start =
 455           (address) align_size_down((intptr_t) addr, (intptr_t) page_size);
 456         bool res = os::protect_memory((char*) page_start, page_size,
 457                                       os::MEM_PROT_RWX);
 458 
 459         if (PrintMiscellaneous && Verbose) {
 460           char buf[256];
 461           jio_snprintf(buf, sizeof(buf), "Execution protection violation "
 462                        "at " INTPTR_FORMAT
 463                        ", unguarding " INTPTR_FORMAT ": %s, errno=%d", addr,
 464                        page_start, (res ? "success" : "failed"), errno);
 465           tty->print_raw_cr(buf);
 466         }
 467         stub = pc;
 468 
 469         // Set last_addr so if we fault again at the same address, we don't end
 470         // up in an endless loop.
 471         //
 472         // There are two potential complications here.  Two threads trapping at
 473         // the same address at the same time could cause one of the threads to
 474         // think it already unguarded, and abort the VM.  Likely very rare.
 475         //
 476         // The other race involves two threads alternately trapping at
 477         // different addresses and failing to unguard the page, resulting in
 478         // an endless loop.  This condition is probably even more unlikely than
 479         // the first.
 480         //
 481         // Although both cases could be avoided by using locks or thread local
 482         // last_addr, these solutions are unnecessary complication: this
 483         // handler is a best-effort safety net, not a complete solution.  It is
 484         // disabled by default and should only be used as a workaround in case
 485         // we missed any no-execute-unsafe VM code.
 486 
 487         last_addr = addr;
 488       }
 489     }
 490   }
 491 #endif // !AMD64
 492 
 493   if (stub != NULL) {
 494     // save all thread context in case we need to restore it
 495     if (thread != NULL) thread->set_saved_exception_pc(pc);
 496 
 497     uc->uc_mcontext.gregs[REG_PC] = (greg_t)stub;
 498     return true;
 499   }
 500 
 501   // signal-chaining
 502   if (os::Linux::chained_handler(sig, info, ucVoid)) {
 503      return true;
 504   }
 505 
 506   if (!abort_if_unrecognized) {
 507     // caller wants another chance, so give it to him
 508     return false;
 509   }
 510 
 511   if (pc == NULL && uc != NULL) {
 512     pc = os::Linux::ucontext_get_pc(uc);
 513   }
 514 
 515   // unmask current signal
 516   sigset_t newset;
 517   sigemptyset(&newset);
 518   sigaddset(&newset, sig);
 519   sigprocmask(SIG_UNBLOCK, &newset, NULL);
 520 
 521   VMError err(t, sig, pc, info, ucVoid);
 522   err.report_and_die();
 523 
 524   ShouldNotReachHere();
 525 }
 526 
 527 void os::Linux::init_thread_fpu_state(void) {
 528 #ifndef AMD64
 529   // set fpu to 53 bit precision
 530   set_fpu_control_word(0x27f);
 531 #endif // !AMD64
 532 }
 533 
 534 int os::Linux::get_fpu_control_word(void) {
 535 #ifdef AMD64
 536   return 0;
 537 #else
 538   int fpu_control;
 539   _FPU_GETCW(fpu_control);
 540   return fpu_control & 0xffff;
 541 #endif // AMD64
 542 }
 543 
 544 void os::Linux::set_fpu_control_word(int fpu_control) {
 545 #ifndef AMD64
 546   _FPU_SETCW(fpu_control);
 547 #endif // !AMD64
 548 }
 549 
 550 // Check that the linux kernel version is 2.4 or higher since earlier
 551 // versions do not support SSE without patches.
 552 bool os::supports_sse() {
 553 #ifdef AMD64
 554   return true;
 555 #else
 556   struct utsname uts;
 557   if( uname(&uts) != 0 ) return false; // uname fails?
 558   char *minor_string;
 559   int major = strtol(uts.release,&minor_string,10);
 560   int minor = strtol(minor_string+1,NULL,10);
 561   bool result = (major > 2 || (major==2 && minor >= 4));
 562 #ifndef PRODUCT
 563   if (PrintMiscellaneous && Verbose) {
 564     tty->print("OS version is %d.%d, which %s support SSE/SSE2\n",
 565                major,minor, result ? "DOES" : "does NOT");
 566   }
 567 #endif
 568   return result;
 569 #endif // AMD64
 570 }
 571 
 572 bool os::is_allocatable(size_t bytes) {
 573 #ifdef AMD64
 574   // unused on amd64?
 575   return true;
 576 #else
 577 
 578   if (bytes < 2 * G) {
 579     return true;
 580   }
 581 
 582   char* addr = reserve_memory(bytes, NULL);
 583 
 584   if (addr != NULL) {
 585     release_memory(addr, bytes);
 586   }
 587 
 588   return addr != NULL;
 589 #endif // AMD64
 590 }
 591 
 592 ////////////////////////////////////////////////////////////////////////////////
 593 // thread stack
 594 
 595 #ifdef AMD64
 596 size_t os::Linux::min_stack_allowed  = 64 * K;
 597 
 598 // amd64: pthread on amd64 is always in floating stack mode
 599 bool os::Linux::supports_variable_stack_size() {  return true; }
 600 #else
 601 size_t os::Linux::min_stack_allowed  =  (48 DEBUG_ONLY(+4))*K;
 602 
 603 #ifdef __GNUC__
 604 #define GET_GS() ({int gs; __asm__ volatile("movw %%gs, %w0":"=q"(gs)); gs&0xffff;})
 605 #endif
 606 
 607 // Test if pthread library can support variable thread stack size. LinuxThreads
 608 // in fixed stack mode allocates 2M fixed slot for each thread. LinuxThreads
 609 // in floating stack mode and NPTL support variable stack size.
 610 bool os::Linux::supports_variable_stack_size() {
 611   if (os::Linux::is_NPTL()) {
 612      // NPTL, yes
 613      return true;
 614 
 615   } else {
 616     // Note: We can't control default stack size when creating a thread.
 617     // If we use non-default stack size (pthread_attr_setstacksize), both
 618     // floating stack and non-floating stack LinuxThreads will return the
 619     // same value. This makes it impossible to implement this function by
 620     // detecting thread stack size directly.
 621     //
 622     // An alternative approach is to check %gs. Fixed-stack LinuxThreads
 623     // do not use %gs, so its value is 0. Floating-stack LinuxThreads use
 624     // %gs (either as LDT selector or GDT selector, depending on kernel)
 625     // to access thread specific data.
 626     //
 627     // Note that %gs is a reserved glibc register since early 2001, so
 628     // applications are not allowed to change its value (Ulrich Drepper from
 629     // Redhat confirmed that all known offenders have been modified to use
 630     // either %fs or TSD). In the worst case scenario, when VM is embedded in
 631     // a native application that plays with %gs, we might see non-zero %gs
 632     // even LinuxThreads is running in fixed stack mode. As the result, we'll
 633     // return true and skip _thread_safety_check(), so we may not be able to
 634     // detect stack-heap collisions. But otherwise it's harmless.
 635     //
 636 #ifdef __GNUC__
 637     return (GET_GS() != 0);
 638 #else
 639     return false;
 640 #endif
 641   }
 642 }
 643 #endif // AMD64
 644 
 645 // return default stack size for thr_type
 646 size_t os::Linux::default_stack_size(os::ThreadType thr_type) {
 647   // default stack size (compiler thread needs larger stack)
 648 #ifdef AMD64
 649   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
 650 #else
 651   size_t s = (thr_type == os::compiler_thread ? 2 * M : 512 * K);
 652 #endif // AMD64
 653   return s;
 654 }
 655 
 656 size_t os::Linux::default_guard_size(os::ThreadType thr_type) {
 657   // Creating guard page is very expensive. Java thread has HotSpot
 658   // guard page, only enable glibc guard page for non-Java threads.
 659   return (thr_type == java_thread ? 0 : page_size());
 660 }
 661 
 662 // Java thread:
 663 //
 664 //   Low memory addresses
 665 //    +------------------------+
 666 //    |                        |\  JavaThread created by VM does not have glibc
 667 //    |    glibc guard page    | - guard, attached Java thread usually has
 668 //    |                        |/  1 page glibc guard.
 669 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
 670 //    |                        |\
 671 //    |  HotSpot Guard Pages   | - red and yellow pages
 672 //    |                        |/
 673 //    +------------------------+ JavaThread::stack_yellow_zone_base()
 674 //    |                        |\
 675 //    |      Normal Stack      | -
 676 //    |                        |/
 677 // P2 +------------------------+ Thread::stack_base()
 678 //
 679 // Non-Java thread:
 680 //
 681 //   Low memory addresses
 682 //    +------------------------+
 683 //    |                        |\
 684 //    |  glibc guard page      | - usually 1 page
 685 //    |                        |/
 686 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
 687 //    |                        |\
 688 //    |      Normal Stack      | -
 689 //    |                        |/
 690 // P2 +------------------------+ Thread::stack_base()
 691 //
 692 // ** P1 (aka bottom) and size ( P2 = P1 - size) are the address and stack size returned from
 693 //    pthread_attr_getstack()
 694 
 695 static void current_stack_region(address * bottom, size_t * size) {
 696   if (os::Linux::is_initial_thread()) {
 697      // initial thread needs special handling because pthread_getattr_np()
 698      // may return bogus value.
 699      *bottom = os::Linux::initial_thread_stack_bottom();
 700      *size   = os::Linux::initial_thread_stack_size();
 701   } else {
 702      pthread_attr_t attr;
 703 
 704      int rslt = pthread_getattr_np(pthread_self(), &attr);
 705 
 706      // JVM needs to know exact stack location, abort if it fails
 707      if (rslt != 0) {
 708        if (rslt == ENOMEM) {
 709          vm_exit_out_of_memory(0, "pthread_getattr_np");
 710        } else {
 711          fatal(err_msg("pthread_getattr_np failed with errno = %d", rslt));
 712        }
 713      }
 714 
 715      if (pthread_attr_getstack(&attr, (void **)bottom, size) != 0) {
 716          fatal("Can not locate current stack attributes!");
 717      }
 718 
 719      pthread_attr_destroy(&attr);
 720 
 721   }
 722   assert(os::current_stack_pointer() >= *bottom &&
 723          os::current_stack_pointer() < *bottom + *size, "just checking");
 724 }
 725 
 726 address os::current_stack_base() {
 727   address bottom;
 728   size_t size;
 729   current_stack_region(&bottom, &size);
 730   return (bottom + size);
 731 }
 732 
 733 size_t os::current_stack_size() {
 734   // stack size includes normal stack and HotSpot guard pages
 735   address bottom;
 736   size_t size;
 737   current_stack_region(&bottom, &size);
 738   return size;
 739 }
 740 
 741 /////////////////////////////////////////////////////////////////////////////
 742 // helper functions for fatal error handler
 743 
 744 void os::print_context(outputStream *st, void *context) {
 745   if (context == NULL) return;
 746 
 747   ucontext_t *uc = (ucontext_t*)context;
 748   st->print_cr("Registers:");
 749 #ifdef AMD64
 750   st->print(  "RAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RAX]);
 751   st->print(", RBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RBX]);
 752   st->print(", RCX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RCX]);
 753   st->print(", RDX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RDX]);
 754   st->cr();
 755   st->print(  "RSP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RSP]);
 756   st->print(", RBP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RBP]);
 757   st->print(", RSI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RSI]);
 758   st->print(", RDI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RDI]);
 759   st->cr();
 760   st->print(  "R8 =" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R8]);
 761   st->print(", R9 =" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R9]);
 762   st->print(", R10=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R10]);
 763   st->print(", R11=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R11]);
 764   st->cr();
 765   st->print(  "R12=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R12]);
 766   st->print(", R13=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R13]);
 767   st->print(", R14=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R14]);
 768   st->print(", R15=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R15]);
 769   st->cr();
 770   st->print(  "RIP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RIP]);
 771   st->print(", EFLAGS=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EFL]);
 772   st->print(", CSGSFS=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_CSGSFS]);
 773   st->print(", ERR=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_ERR]);
 774   st->cr();
 775   st->print("  TRAPNO=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_TRAPNO]);
 776 #else
 777   st->print(  "EAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EAX]);
 778   st->print(", EBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EBX]);
 779   st->print(", ECX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_ECX]);
 780   st->print(", EDX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EDX]);
 781   st->cr();
 782   st->print(  "ESP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_UESP]);
 783   st->print(", EBP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EBP]);
 784   st->print(", ESI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_ESI]);
 785   st->print(", EDI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EDI]);
 786   st->cr();
 787   st->print(  "EIP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EIP]);
 788   st->print(", EFLAGS=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EFL]);
 789   st->print(", CR2=" INTPTR_FORMAT, uc->uc_mcontext.cr2);
 790 #endif // AMD64
 791   st->cr();
 792   st->cr();
 793 
 794   intptr_t *sp = (intptr_t *)os::Linux::ucontext_get_sp(uc);
 795   st->print_cr("Top of Stack: (sp=" PTR_FORMAT ")", sp);
 796   print_hex_dump(st, (address)sp, (address)(sp + 8*sizeof(intptr_t)), sizeof(intptr_t));
 797   st->cr();
 798 
 799   // Note: it may be unsafe to inspect memory near pc. For example, pc may
 800   // point to garbage if entry point in an nmethod is corrupted. Leave
 801   // this at the end, and hope for the best.
 802   address pc = os::Linux::ucontext_get_pc(uc);
 803   st->print_cr("Instructions: (pc=" PTR_FORMAT ")", pc);
 804   print_hex_dump(st, pc - 32, pc + 32, sizeof(char));
 805 }
 806 
 807 void os::print_register_info(outputStream *st, void *context) {
 808   if (context == NULL) return;
 809 
 810   ucontext_t *uc = (ucontext_t*)context;
 811 
 812   st->print_cr("Register to memory mapping:");
 813   st->cr();
 814 
 815   // this is horrendously verbose but the layout of the registers in the
 816   // context does not match how we defined our abstract Register set, so
 817   // we can't just iterate through the gregs area
 818 
 819   // this is only for the "general purpose" registers
 820 
 821 #ifdef AMD64
 822   st->print("RAX="); print_location(st, uc->uc_mcontext.gregs[REG_RAX]);
 823   st->print("RBX="); print_location(st, uc->uc_mcontext.gregs[REG_RBX]);
 824   st->print("RCX="); print_location(st, uc->uc_mcontext.gregs[REG_RCX]);
 825   st->print("RDX="); print_location(st, uc->uc_mcontext.gregs[REG_RDX]);
 826   st->print("RSP="); print_location(st, uc->uc_mcontext.gregs[REG_RSP]);
 827   st->print("RBP="); print_location(st, uc->uc_mcontext.gregs[REG_RBP]);
 828   st->print("RSI="); print_location(st, uc->uc_mcontext.gregs[REG_RSI]);
 829   st->print("RDI="); print_location(st, uc->uc_mcontext.gregs[REG_RDI]);
 830   st->print("R8 ="); print_location(st, uc->uc_mcontext.gregs[REG_R8]);
 831   st->print("R9 ="); print_location(st, uc->uc_mcontext.gregs[REG_R9]);
 832   st->print("R10="); print_location(st, uc->uc_mcontext.gregs[REG_R10]);
 833   st->print("R11="); print_location(st, uc->uc_mcontext.gregs[REG_R11]);
 834   st->print("R12="); print_location(st, uc->uc_mcontext.gregs[REG_R12]);
 835   st->print("R13="); print_location(st, uc->uc_mcontext.gregs[REG_R13]);
 836   st->print("R14="); print_location(st, uc->uc_mcontext.gregs[REG_R14]);
 837   st->print("R15="); print_location(st, uc->uc_mcontext.gregs[REG_R15]);
 838 #else
 839   st->print("EAX="); print_location(st, uc->uc_mcontext.gregs[REG_EAX]);
 840   st->print("EBX="); print_location(st, uc->uc_mcontext.gregs[REG_EBX]);
 841   st->print("ECX="); print_location(st, uc->uc_mcontext.gregs[REG_ECX]);
 842   st->print("EDX="); print_location(st, uc->uc_mcontext.gregs[REG_EDX]);
 843   st->print("ESP="); print_location(st, uc->uc_mcontext.gregs[REG_ESP]);
 844   st->print("EBP="); print_location(st, uc->uc_mcontext.gregs[REG_EBP]);
 845   st->print("ESI="); print_location(st, uc->uc_mcontext.gregs[REG_ESI]);
 846   st->print("EDI="); print_location(st, uc->uc_mcontext.gregs[REG_EDI]);
 847 #endif // AMD64
 848 
 849   st->cr();
 850 }
 851 
 852 void os::setup_fpu() {
 853 #ifndef AMD64
 854   address fpu_cntrl = StubRoutines::addr_fpu_cntrl_wrd_std();
 855   __asm__ volatile (  "fldcw (%0)" :
 856                       : "r" (fpu_cntrl) : "memory");
 857 #endif // !AMD64
 858 }
 859 
 860 #ifndef PRODUCT
 861 void os::verify_stack_alignment() {
 862 #ifdef AMD64
 863   assert(((intptr_t)os::current_stack_pointer() & (StackAlignmentInBytes-1)) == 0, "incorrect stack alignment");
 864 #endif
 865 }
 866 #endif