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