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