1 /*
   2  * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright 2007, 2008, 2009, 2010 Red Hat, Inc.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #if !defined(__APPLE__) && !defined(__NetBSD__)
  27 #include <pthread.h>
  28 # include <pthread_np.h> /* For pthread_attr_get_np */
  29 #endif
  30 
  31 // no precompiled headers
  32 #include "assembler_zero.inline.hpp"
  33 #include "classfile/classLoader.hpp"
  34 #include "classfile/systemDictionary.hpp"
  35 #include "classfile/vmSymbols.hpp"
  36 #include "code/icBuffer.hpp"
  37 #include "code/vtableStubs.hpp"
  38 #include "interpreter/interpreter.hpp"
  39 #include "jvm_bsd.h"
  40 #include "memory/allocation.inline.hpp"
  41 #include "mutex_bsd.inline.hpp"
  42 #include "nativeInst_zero.hpp"
  43 #include "os_share_bsd.hpp"
  44 #include "prims/jniFastGetField.hpp"
  45 #include "prims/jvm.h"
  46 #include "prims/jvm_misc.hpp"
  47 #include "runtime/arguments.hpp"
  48 #include "runtime/extendedPC.hpp"
  49 #include "runtime/frame.inline.hpp"
  50 #include "runtime/interfaceSupport.hpp"
  51 #include "runtime/java.hpp"
  52 #include "runtime/javaCalls.hpp"
  53 #include "runtime/mutexLocker.hpp"
  54 #include "runtime/osThread.hpp"
  55 #include "runtime/sharedRuntime.hpp"
  56 #include "runtime/stubRoutines.hpp"
  57 #include "runtime/thread.inline.hpp"
  58 #include "runtime/timer.hpp"
  59 #include "utilities/events.hpp"
  60 #include "utilities/vmError.hpp"
  61 
  62 // See stubGenerator_zero.cpp
  63 #include <setjmp.h>
  64 extern sigjmp_buf* get_jmp_buf_for_continuation();
  65 
  66 address os::current_stack_pointer() {
  67   address dummy = (address) &dummy;
  68   return dummy;
  69 }
  70 
  71 frame os::get_sender_for_C_frame(frame* fr) {
  72   ShouldNotCallThis();
  73   return frame();
  74 }
  75 
  76 frame os::current_frame() {
  77   // The only thing that calls this is the stack printing code in
  78   // VMError::report:
  79   //   - Step 110 (printing stack bounds) uses the sp in the frame
  80   //     to determine the amount of free space on the stack.  We
  81   //     set the sp to a close approximation of the real value in
  82   //     order to allow this step to complete.
  83   //   - Step 120 (printing native stack) tries to walk the stack.
  84   //     The frame we create has a NULL pc, which is ignored as an
  85   //     invalid frame.
  86   frame dummy = frame();
  87   dummy.set_sp((intptr_t *) current_stack_pointer());
  88   return dummy;
  89 }
  90 
  91 char* os::non_memory_address_word() {
  92   // Must never look like an address returned by reserve_memory,
  93   // even in its subfields (as defined by the CPU immediate fields,
  94   // if the CPU splits constants across multiple instructions).
  95 #ifdef SPARC
  96   // On SPARC, 0 != %hi(any real address), because there is no
  97   // allocation in the first 1Kb of the virtual address space.
  98   return (char *) 0;
  99 #else
 100   // This is the value for x86; works pretty well for PPC too.
 101   return (char *) -1;
 102 #endif // SPARC
 103 }
 104 
 105 void os::initialize_thread(Thread* thr) {
 106   // Nothing to do.
 107 }
 108 
 109 address os::Bsd::ucontext_get_pc(const ucontext_t* uc) {
 110   ShouldNotCallThis();
 111   return NULL;
 112 }
 113 
 114 void os::Bsd::ucontext_set_pc(ucontext_t * uc, address pc) {
 115   ShouldNotCallThis();
 116 }
 117 
 118 ExtendedPC os::fetch_frame_from_context(const void* ucVoid,
 119                                         intptr_t** ret_sp,
 120                                         intptr_t** ret_fp) {
 121   ShouldNotCallThis();
 122   return ExtendedPC();
 123 }
 124 
 125 frame os::fetch_frame_from_context(const void* ucVoid) {
 126   ShouldNotCallThis();
 127   return frame();
 128 }
 129 
 130 extern "C" JNIEXPORT int
 131 JVM_handle_bsd_signal(int sig,
 132                         siginfo_t* info,
 133                         void* ucVoid,
 134                         int abort_if_unrecognized) {
 135   ucontext_t* uc = (ucontext_t*) ucVoid;
 136 
 137   Thread* t = Thread::current_or_null_safe();
 138 
 139   SignalHandlerMark shm(t);
 140 
 141   // handle SafeFetch faults
 142   if (sig == SIGSEGV || sig == SIGBUS) {
 143     sigjmp_buf* const pjb = get_jmp_buf_for_continuation();
 144     if (pjb) {
 145       siglongjmp(*pjb, 1);
 146     }
 147   }
 148 
 149   // Note: it's not uncommon that JNI code uses signal/sigset to
 150   // install then restore certain signal handler (e.g. to temporarily
 151   // block SIGPIPE, or have a SIGILL handler when detecting CPU
 152   // type). When that happens, JVM_handle_bsd_signal() might be
 153   // invoked with junk info/ucVoid. To avoid unnecessary crash when
 154   // libjsig is not preloaded, try handle signals that do not require
 155   // siginfo/ucontext first.
 156 
 157   if (sig == SIGPIPE || sig == SIGXFSZ) {
 158     // allow chained handler to go first
 159     if (os::Bsd::chained_handler(sig, info, ucVoid)) {
 160       return true;
 161     } else {
 162       // Ignoring SIGPIPE/SIGXFSZ - see bugs 4229104 or 6499219
 163       return true;
 164     }
 165   }
 166 
 167   JavaThread* thread = NULL;
 168   VMThread* vmthread = NULL;
 169   if (os::Bsd::signal_handlers_are_installed) {
 170     if (t != NULL ){
 171       if(t->is_Java_thread()) {
 172         thread = (JavaThread*)t;
 173       }
 174       else if(t->is_VM_thread()){
 175         vmthread = (VMThread *)t;
 176       }
 177     }
 178   }
 179 
 180   if (info != NULL && thread != NULL) {
 181     // Handle ALL stack overflow variations here
 182     if (sig == SIGSEGV || sig == SIGBUS) {
 183       address addr = (address) info->si_addr;
 184 
 185       // check if fault address is within thread stack
 186       if (thread->on_local_stack(addr)) {
 187         // stack overflow
 188         if (thread->in_stack_yellow_reserved_zone(addr)) {
 189           thread->disable_stack_yellow_reserved_zone();
 190           ShouldNotCallThis();
 191         }
 192         else if (thread->in_stack_red_zone(addr)) {
 193           thread->disable_stack_red_zone();
 194           ShouldNotCallThis();
 195         }
 196       }
 197     }
 198 
 199     /*if (thread->thread_state() == _thread_in_Java) {
 200       ShouldNotCallThis();
 201     }
 202     else*/ if (thread->thread_state() == _thread_in_vm &&
 203                sig == SIGBUS && thread->doing_unsafe_access()) {
 204       ShouldNotCallThis();
 205     }
 206 
 207     // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC
 208     // kicks in and the heap gets shrunk before the field access.
 209     /*if (sig == SIGSEGV || sig == SIGBUS) {
 210       address addr = JNI_FastGetField::find_slowcase_pc(pc);
 211       if (addr != (address)-1) {
 212         stub = addr;
 213       }
 214     }*/
 215 
 216     // Check to see if we caught the safepoint code in the process
 217     // of write protecting the memory serialization page.  It write
 218     // enables the page immediately after protecting it so we can
 219     // just return to retry the write.
 220     if ((sig == SIGSEGV || sig == SIGBUS) &&
 221         os::is_memory_serialize_page(thread, (address) info->si_addr)) {
 222       // Block current thread until permission is restored.
 223       os::block_on_serialize_page_trap();
 224       return true;
 225     }
 226   }
 227 
 228   // signal-chaining
 229   if (os::Bsd::chained_handler(sig, info, ucVoid)) {
 230      return true;
 231   }
 232 
 233   if (!abort_if_unrecognized) {
 234     // caller wants another chance, so give it to him
 235     return false;
 236   }
 237 
 238 #ifndef PRODUCT
 239   if (sig == SIGSEGV) {
 240     fatal("\n#"
 241           "\n#    /--------------------\\"
 242           "\n#    | segmentation fault |"
 243           "\n#    \\---\\ /--------------/"
 244           "\n#        /"
 245           "\n#    [-]        |\\_/|    "
 246           "\n#    (+)=C      |o o|__  "
 247           "\n#    | |        =-*-=__\\ "
 248           "\n#    OOO        c_c_(___)");
 249   }
 250 #endif // !PRODUCT
 251 
 252   const char *fmt =
 253       "caught unhandled signal " INT32_FORMAT " at address " PTR_FORMAT;
 254   char buf[128];
 255 
 256   sprintf(buf, fmt, sig, info->si_addr);
 257   fatal(buf);
 258   return false;
 259 }
 260 
 261 void os::Bsd::init_thread_fpu_state(void) {
 262   // Nothing to do
 263 }
 264 
 265 bool os::is_allocatable(size_t bytes) {
 266 #ifdef _LP64
 267   return true;
 268 #else
 269   if (bytes < 2 * G) {
 270     return true;
 271   }
 272 
 273   char* addr = reserve_memory(bytes, NULL);
 274 
 275   if (addr != NULL) {
 276     release_memory(addr, bytes);
 277   }
 278 
 279   return addr != NULL;
 280 #endif // _LP64
 281 }
 282 
 283 ///////////////////////////////////////////////////////////////////////////////
 284 // thread stack
 285 
 286 size_t os::Bsd::min_stack_allowed = 64 * K;
 287 
 288 size_t os::Bsd::default_stack_size(os::ThreadType thr_type) {
 289 #ifdef _LP64
 290   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
 291 #else
 292   size_t s = (thr_type == os::compiler_thread ? 2 * M : 512 * K);
 293 #endif // _LP64
 294   return s;
 295 }
 296 
 297 size_t os::Bsd::default_guard_size(os::ThreadType thr_type) {
 298   // Only enable glibc guard pages for non-Java threads
 299   // (Java threads have HotSpot guard pages)
 300   return (thr_type == java_thread ? 0 : page_size());
 301 }
 302 
 303 static void current_stack_region(address *bottom, size_t *size) {
 304   address stack_bottom;
 305   address stack_top;
 306   size_t stack_bytes;
 307 
 308 #ifdef __APPLE__
 309   pthread_t self = pthread_self();
 310   stack_top = (address) pthread_get_stackaddr_np(self);
 311   stack_bytes = pthread_get_stacksize_np(self);
 312   stack_bottom = stack_top - stack_bytes;
 313 #elif defined(__OpenBSD__)
 314   stack_t ss;
 315   int rslt = pthread_stackseg_np(pthread_self(), &ss);
 316 
 317   if (rslt != 0)
 318     fatal("pthread_stackseg_np failed with err = " INT32_FORMAT, rslt);
 319 
 320   stack_top = (address) ss.ss_sp;
 321   stack_bytes  = ss.ss_size;
 322   stack_bottom = stack_top - stack_bytes;
 323 #else
 324   pthread_attr_t attr;
 325 
 326   int rslt = pthread_attr_init(&attr);
 327 
 328   // JVM needs to know exact stack location, abort if it fails
 329   if (rslt != 0)
 330     fatal("pthread_attr_init failed with err = " INT32_FORMAT, rslt);
 331 
 332   rslt = pthread_attr_get_np(pthread_self(), &attr);
 333 
 334   if (rslt != 0)
 335     fatal("pthread_attr_get_np failed with err = " INT32_FORMAT, rslt);
 336 
 337   if (pthread_attr_getstackaddr(&attr, (void **) &stack_bottom) != 0 ||
 338       pthread_attr_getstacksize(&attr, &stack_bytes) != 0) {
 339     fatal("Can not locate current stack attributes!");
 340   }
 341 
 342   pthread_attr_destroy(&attr);
 343 
 344   stack_top = stack_bottom + stack_bytes;
 345 #endif
 346 
 347   assert(os::current_stack_pointer() >= stack_bottom, "should do");
 348   assert(os::current_stack_pointer() < stack_top, "should do");
 349 
 350   *bottom = stack_bottom;
 351   *size = stack_top - stack_bottom;
 352 }
 353 
 354 address os::current_stack_base() {
 355   address bottom;
 356   size_t size;
 357   current_stack_region(&bottom, &size);
 358   return bottom + size;
 359 }
 360 
 361 size_t os::current_stack_size() {
 362   // stack size includes normal stack and HotSpot guard pages
 363   address bottom;
 364   size_t size;
 365   current_stack_region(&bottom, &size);
 366   return size;
 367 }
 368 
 369 /////////////////////////////////////////////////////////////////////////////
 370 // helper functions for fatal error handler
 371 
 372 void os::print_context(outputStream* st, const void* context) {
 373   ShouldNotCallThis();
 374 }
 375 
 376 void os::print_register_info(outputStream *st, const void *context) {
 377   ShouldNotCallThis();
 378 }
 379 
 380 /////////////////////////////////////////////////////////////////////////////
 381 // Stubs for things that would be in bsd_zero.s if it existed.
 382 // You probably want to disassemble these monkeys to check they're ok.
 383 
 384 extern "C" {
 385   int SpinPause() {
 386     return 1;
 387   }
 388 
 389   void _Copy_conjoint_jshorts_atomic(jshort* from, jshort* to, size_t count) {
 390     if (from > to) {
 391       jshort *end = from + count;
 392       while (from < end)
 393         *(to++) = *(from++);
 394     }
 395     else if (from < to) {
 396       jshort *end = from;
 397       from += count - 1;
 398       to   += count - 1;
 399       while (from >= end)
 400         *(to--) = *(from--);
 401     }
 402   }
 403   void _Copy_conjoint_jints_atomic(jint* from, jint* to, size_t count) {
 404     if (from > to) {
 405       jint *end = from + count;
 406       while (from < end)
 407         *(to++) = *(from++);
 408     }
 409     else if (from < to) {
 410       jint *end = from;
 411       from += count - 1;
 412       to   += count - 1;
 413       while (from >= end)
 414         *(to--) = *(from--);
 415     }
 416   }
 417   void _Copy_conjoint_jlongs_atomic(jlong* from, jlong* to, size_t count) {
 418     if (from > to) {
 419       jlong *end = from + count;
 420       while (from < end)
 421         os::atomic_copy64(from++, to++);
 422     }
 423     else if (from < to) {
 424       jlong *end = from;
 425       from += count - 1;
 426       to   += count - 1;
 427       while (from >= end)
 428         os::atomic_copy64(from--, to--);
 429     }
 430   }
 431 
 432   void _Copy_arrayof_conjoint_bytes(HeapWord* from,
 433                                     HeapWord* to,
 434                                     size_t    count) {
 435     memmove(to, from, count);
 436   }
 437   void _Copy_arrayof_conjoint_jshorts(HeapWord* from,
 438                                       HeapWord* to,
 439                                       size_t    count) {
 440     memmove(to, from, count * 2);
 441   }
 442   void _Copy_arrayof_conjoint_jints(HeapWord* from,
 443                                     HeapWord* to,
 444                                     size_t    count) {
 445     memmove(to, from, count * 4);
 446   }
 447   void _Copy_arrayof_conjoint_jlongs(HeapWord* from,
 448                                      HeapWord* to,
 449                                      size_t    count) {
 450     memmove(to, from, count * 8);
 451   }
 452 };
 453 
 454 /////////////////////////////////////////////////////////////////////////////
 455 // Implementations of atomic operations not supported by processors.
 456 //  -- http://gcc.gnu.org/onlinedocs/gcc-4.2.1/gcc/Atomic-Builtins.html
 457 
 458 #ifndef _LP64
 459 extern "C" {
 460   long long unsigned int __sync_val_compare_and_swap_8(
 461     volatile void *ptr,
 462     long long unsigned int oldval,
 463     long long unsigned int newval) {
 464     ShouldNotCallThis();
 465   }
 466 };
 467 #endif // !_LP64
 468 
 469 #ifndef PRODUCT
 470 void os::verify_stack_alignment() {
 471 }
 472 #endif
 473 
 474 int os::extra_bang_size_in_bytes() {
 475   // Zero does not require an additional stack bang.
 476   return 0;
 477 }