1 /*
   2  * Copyright (c) 2003, 2013, 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 address os::current_stack_pointer() {
  63   address dummy = (address) &dummy;
  64   return dummy;
  65 }
  66 
  67 frame os::get_sender_for_C_frame(frame* fr) {
  68   ShouldNotCallThis();
  69   return frame();
  70 }
  71 
  72 frame os::current_frame() {
  73   // The only thing that calls this is the stack printing code in
  74   // VMError::report:
  75   //   - Step 110 (printing stack bounds) uses the sp in the frame
  76   //     to determine the amount of free space on the stack.  We
  77   //     set the sp to a close approximation of the real value in
  78   //     order to allow this step to complete.
  79   //   - Step 120 (printing native stack) tries to walk the stack.
  80   //     The frame we create has a NULL pc, which is ignored as an
  81   //     invalid frame.
  82   frame dummy = frame();
  83   dummy.set_sp((intptr_t *) current_stack_pointer());
  84   return dummy;
  85 }
  86 
  87 char* os::non_memory_address_word() {
  88   // Must never look like an address returned by reserve_memory,
  89   // even in its subfields (as defined by the CPU immediate fields,
  90   // if the CPU splits constants across multiple instructions).
  91 #ifdef SPARC
  92   // On SPARC, 0 != %hi(any real address), because there is no
  93   // allocation in the first 1Kb of the virtual address space.
  94   return (char *) 0;
  95 #else
  96   // This is the value for x86; works pretty well for PPC too.
  97   return (char *) -1;
  98 #endif // SPARC
  99 }
 100 
 101 void os::initialize_thread(Thread* thr) {
 102   // Nothing to do.
 103 }
 104 
 105 address os::Bsd::ucontext_get_pc(ucontext_t* uc) {
 106   ShouldNotCallThis();
 107   return NULL;
 108 }
 109 
 110 void os::Bsd::ucontext_set_pc(ucontext_t * uc, address pc) {
 111   ShouldNotCallThis();
 112 }
 113 
 114 ExtendedPC os::fetch_frame_from_context(void* ucVoid,
 115                                         intptr_t** ret_sp,
 116                                         intptr_t** ret_fp) {
 117   ShouldNotCallThis();
 118   return ExtendedPC();
 119 }
 120 
 121 frame os::fetch_frame_from_context(void* ucVoid) {
 122   ShouldNotCallThis();
 123   return frame();
 124 }
 125 
 126 extern "C" JNIEXPORT int
 127 JVM_handle_bsd_signal(int sig,
 128                         siginfo_t* info,
 129                         void* ucVoid,
 130                         int abort_if_unrecognized) {
 131   ucontext_t* uc = (ucontext_t*) ucVoid;
 132 
 133   Thread* t = ThreadLocalStorage::get_thread_slow();
 134 
 135   SignalHandlerMark shm(t);
 136 
 137   // Note: it's not uncommon that JNI code uses signal/sigset to
 138   // install then restore certain signal handler (e.g. to temporarily
 139   // block SIGPIPE, or have a SIGILL handler when detecting CPU
 140   // type). When that happens, JVM_handle_bsd_signal() might be
 141   // invoked with junk info/ucVoid. To avoid unnecessary crash when
 142   // libjsig is not preloaded, try handle signals that do not require
 143   // siginfo/ucontext first.
 144 
 145   if (sig == SIGPIPE || sig == SIGXFSZ) {
 146     // allow chained handler to go first
 147     if (os::Bsd::chained_handler(sig, info, ucVoid)) {
 148       return true;
 149     } else {
 150       if (PrintMiscellaneous && (WizardMode || Verbose)) {
 151         char buf[64];
 152         warning("Ignoring %s - see bugs 4229104 or 646499219",
 153                 os::exception_name(sig, buf, sizeof(buf)));
 154       }
 155       return true;
 156     }
 157   }
 158 
 159   JavaThread* thread = NULL;
 160   VMThread* vmthread = NULL;
 161   if (os::Bsd::signal_handlers_are_installed) {
 162     if (t != NULL ){
 163       if(t->is_Java_thread()) {
 164         thread = (JavaThread*)t;
 165       }
 166       else if(t->is_VM_thread()){
 167         vmthread = (VMThread *)t;
 168       }
 169     }
 170   }
 171 
 172   if (info != NULL && thread != NULL) {
 173     // Handle ALL stack overflow variations here
 174     if (sig == SIGSEGV || sig == SIGBUS) {
 175       address addr = (address) info->si_addr;
 176 
 177       // check if fault address is within thread stack
 178       if (addr < thread->stack_base() &&
 179           addr >= thread->stack_base() - thread->stack_size()) {
 180         // stack overflow
 181         if (thread->in_stack_yellow_zone(addr)) {
 182           thread->disable_stack_yellow_zone();
 183           ShouldNotCallThis();
 184         }
 185         else if (thread->in_stack_red_zone(addr)) {
 186           thread->disable_stack_red_zone();
 187           ShouldNotCallThis();
 188         }
 189       }
 190     }
 191 
 192     /*if (thread->thread_state() == _thread_in_Java) {
 193       ShouldNotCallThis();
 194     }
 195     else*/ if (thread->thread_state() == _thread_in_vm &&
 196                sig == SIGBUS && thread->doing_unsafe_access()) {
 197       ShouldNotCallThis();
 198     }
 199 
 200     // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC
 201     // kicks in and the heap gets shrunk before the field access.
 202     /*if (sig == SIGSEGV || sig == SIGBUS) {
 203       address addr = JNI_FastGetField::find_slowcase_pc(pc);
 204       if (addr != (address)-1) {
 205         stub = addr;
 206       }
 207     }*/
 208 
 209     // Check to see if we caught the safepoint code in the process
 210     // of write protecting the memory serialization page.  It write
 211     // enables the page immediately after protecting it so we can
 212     // just return to retry the write.
 213     if ((sig == SIGSEGV || sig == SIGBUS) &&
 214         os::is_memory_serialize_page(thread, (address) info->si_addr)) {
 215       // Block current thread until permission is restored.
 216       os::block_on_serialize_page_trap();
 217       return true;
 218     }
 219   }
 220 
 221   // signal-chaining
 222   if (os::Bsd::chained_handler(sig, info, ucVoid)) {
 223      return true;
 224   }
 225 
 226   if (!abort_if_unrecognized) {
 227     // caller wants another chance, so give it to him
 228     return false;
 229   }
 230 
 231 #ifndef PRODUCT
 232   if (sig == SIGSEGV) {
 233     fatal("\n#"
 234           "\n#    /--------------------\\"
 235           "\n#    | segmentation fault |"
 236           "\n#    \\---\\ /--------------/"
 237           "\n#        /"
 238           "\n#    [-]        |\\_/|    "
 239           "\n#    (+)=C      |o o|__  "
 240           "\n#    | |        =-*-=__\\ "
 241           "\n#    OOO        c_c_(___)");
 242   }
 243 #endif // !PRODUCT
 244 
 245   const char *fmt =
 246       "caught unhandled signal " INT32_FORMAT " at address " PTR_FORMAT;
 247   char buf[128];
 248 
 249   sprintf(buf, fmt, sig, info->si_addr);
 250   fatal(buf);
 251   return false;
 252 }
 253 
 254 void os::Bsd::init_thread_fpu_state(void) {
 255   // Nothing to do
 256 }
 257 
 258 bool os::is_allocatable(size_t bytes) {
 259 #ifdef _LP64
 260   return true;
 261 #else
 262   if (bytes < 2 * G) {
 263     return true;
 264   }
 265 
 266   char* addr = reserve_memory(bytes, NULL);
 267 
 268   if (addr != NULL) {
 269     release_memory(addr, bytes);
 270   }
 271 
 272   return addr != NULL;
 273 #endif // _LP64
 274 }
 275 
 276 ///////////////////////////////////////////////////////////////////////////////
 277 // thread stack
 278 
 279 size_t os::Bsd::min_stack_allowed = 64 * K;
 280 
 281 bool os::Bsd::supports_variable_stack_size() {
 282   return true;
 283 }
 284 
 285 size_t os::Bsd::default_stack_size(os::ThreadType thr_type) {
 286 #ifdef _LP64
 287   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
 288 #else
 289   size_t s = (thr_type == os::compiler_thread ? 2 * M : 512 * K);
 290 #endif // _LP64
 291   return s;
 292 }
 293 
 294 size_t os::Bsd::default_guard_size(os::ThreadType thr_type) {
 295   // Only enable glibc guard pages for non-Java threads
 296   // (Java threads have HotSpot guard pages)
 297   return (thr_type == java_thread ? 0 : page_size());
 298 }
 299 
 300 static void current_stack_region(address *bottom, size_t *size) {
 301   address stack_bottom;
 302   address stack_top;
 303   size_t stack_bytes;
 304 
 305 #ifdef __APPLE__
 306   pthread_t self = pthread_self();
 307   stack_top = (address) pthread_get_stackaddr_np(self);
 308   stack_bytes = pthread_get_stacksize_np(self);
 309   stack_bottom = stack_top - stack_bytes;
 310 #elif defined(__OpenBSD__)
 311   stack_t ss;
 312   int rslt = pthread_stackseg_np(pthread_self(), &ss);
 313 
 314   if (rslt != 0)
 315     fatal(err_msg("pthread_stackseg_np failed with err = " INT32_FORMAT,
 316           rslt));
 317 
 318   stack_top = (address) ss.ss_sp;
 319   stack_bytes  = ss.ss_size;
 320   stack_bottom = stack_top - stack_bytes;
 321 #else
 322   pthread_attr_t attr;
 323 
 324   int rslt = pthread_attr_init(&attr);
 325 
 326   // JVM needs to know exact stack location, abort if it fails
 327   if (rslt != 0)
 328     fatal(err_msg("pthread_attr_init failed with err = " INT32_FORMAT, rslt));
 329 
 330   rslt = pthread_attr_get_np(pthread_self(), &attr);
 331 
 332   if (rslt != 0)
 333     fatal(err_msg("pthread_attr_get_np failed with err = " INT32_FORMAT,
 334           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, void* context) {
 372   ShouldNotCallThis();
 373 }
 374 
 375 void os::print_register_info(outputStream *st, 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 }