1 /*
   2  * Copyright (c) 2003, 2011, 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(_ALLBSD_SOURCE) && !defined(__APPLE__) && !defined(__NetBSD__)
  27 # include <pthread_np.h> /* For pthread_attr_get_np */
  28 #endif
  29 
  30 // no precompiled headers
  31 #include "assembler_zero.inline.hpp"
  32 #include "classfile/classLoader.hpp"
  33 #include "classfile/systemDictionary.hpp"
  34 #include "classfile/vmSymbols.hpp"
  35 #include "code/icBuffer.hpp"
  36 #include "code/vtableStubs.hpp"
  37 #include "interpreter/interpreter.hpp"
  38 #include "jvm_bsd.h"
  39 #include "memory/allocation.inline.hpp"
  40 #include "mutex_bsd.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/timer.hpp"
  57 #include "thread_bsd.inline.hpp"
  58 #include "utilities/events.hpp"
  59 #include "utilities/vmError.hpp"
  60 #ifdef COMPILER1
  61 #include "c1/c1_Runtime1.hpp"
  62 #endif
  63 #ifdef COMPILER2
  64 #include "opto/runtime.hpp"
  65 #endif
  66 
  67 address os::current_stack_pointer() {
  68   address dummy = (address) &dummy;
  69   return dummy;
  70 }
  71 
  72 frame os::get_sender_for_C_frame(frame* fr) {
  73   ShouldNotCallThis();
  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() {
 106   // Nothing to do.
 107 }
 108 
 109 address os::Bsd::ucontext_get_pc(ucontext_t* uc) {
 110   ShouldNotCallThis();
 111 }
 112 
 113 ExtendedPC os::fetch_frame_from_context(void* ucVoid,
 114                                         intptr_t** ret_sp,
 115                                         intptr_t** ret_fp) {
 116   ShouldNotCallThis();
 117 }
 118 
 119 frame os::fetch_frame_from_context(void* ucVoid) {
 120   ShouldNotCallThis();
 121 }
 122 
 123 extern "C" JNIEXPORT int
 124 JVM_handle_bsd_signal(int sig,
 125                         siginfo_t* info,
 126                         void* ucVoid,
 127                         int abort_if_unrecognized) {
 128   ucontext_t* uc = (ucontext_t*) ucVoid;
 129 
 130   Thread* t = ThreadLocalStorage::get_thread_slow();
 131 
 132   SignalHandlerMark shm(t);
 133 
 134   // Note: it's not uncommon that JNI code uses signal/sigset to
 135   // install then restore certain signal handler (e.g. to temporarily
 136   // block SIGPIPE, or have a SIGILL handler when detecting CPU
 137   // type). When that happens, JVM_handle_bsd_signal() might be
 138   // invoked with junk info/ucVoid. To avoid unnecessary crash when
 139   // libjsig is not preloaded, try handle signals that do not require
 140   // siginfo/ucontext first.
 141 
 142   if (sig == SIGPIPE || sig == SIGXFSZ) {
 143     // allow chained handler to go first
 144     if (os::Bsd::chained_handler(sig, info, ucVoid)) {
 145       return true;
 146     } else {
 147       if (PrintMiscellaneous && (WizardMode || Verbose)) {
 148         char buf[64];
 149         warning("Ignoring %s - see bugs 4229104 or 646499219",
 150                 os::exception_name(sig, buf, sizeof(buf)));
 151       }
 152       return true;
 153     }
 154   }
 155 
 156   JavaThread* thread = NULL;
 157   VMThread* vmthread = NULL;
 158   if (os::Bsd::signal_handlers_are_installed) {
 159     if (t != NULL ){
 160       if(t->is_Java_thread()) {
 161         thread = (JavaThread*)t;
 162       }
 163       else if(t->is_VM_thread()){
 164         vmthread = (VMThread *)t;
 165       }
 166     }
 167   }
 168 
 169   if (info != NULL && thread != NULL) {
 170     // Handle ALL stack overflow variations here
 171     if (sig == SIGSEGV) {
 172       address addr = (address) info->si_addr;
 173 
 174       // check if fault address is within thread stack
 175       if (addr < thread->stack_base() &&
 176           addr >= thread->stack_base() - thread->stack_size()) {
 177         // stack overflow
 178         if (thread->in_stack_yellow_zone(addr)) {
 179           thread->disable_stack_yellow_zone();
 180           ShouldNotCallThis();
 181         }
 182         else if (thread->in_stack_red_zone(addr)) {
 183           thread->disable_stack_red_zone();
 184           ShouldNotCallThis();
 185         }
 186 #ifndef _ALLBSD_SOURCE
 187         else {
 188           // Accessing stack address below sp may cause SEGV if
 189           // current thread has MAP_GROWSDOWN stack. This should
 190           // only happen when current thread was created by user
 191           // code with MAP_GROWSDOWN flag and then attached to VM.
 192           // See notes in os_bsd.cpp.
 193           if (thread->osthread()->expanding_stack() == 0) {
 194             thread->osthread()->set_expanding_stack();
 195             if (os::Bsd::manually_expand_stack(thread, addr)) {
 196               thread->osthread()->clear_expanding_stack();
 197               return true;
 198             }
 199             thread->osthread()->clear_expanding_stack();
 200           }
 201           else {
 202             fatal("recursive segv. expanding stack.");
 203           }
 204         }
 205 #endif
 206       }
 207     }
 208 
 209     /*if (thread->thread_state() == _thread_in_Java) {
 210       ShouldNotCallThis();
 211     }
 212     else*/ if (thread->thread_state() == _thread_in_vm &&
 213                sig == SIGBUS && thread->doing_unsafe_access()) {
 214       ShouldNotCallThis();
 215     }
 216 
 217     // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC
 218     // kicks in and the heap gets shrunk before the field access.
 219     /*if (sig == SIGSEGV || sig == SIGBUS) {
 220       address addr = JNI_FastGetField::find_slowcase_pc(pc);
 221       if (addr != (address)-1) {
 222         stub = addr;
 223       }
 224     }*/
 225 
 226     // Check to see if we caught the safepoint code in the process
 227     // of write protecting the memory serialization page.  It write
 228     // enables the page immediately after protecting it so we can
 229     // just return to retry the write.
 230     if (sig == SIGSEGV &&
 231         os::is_memory_serialize_page(thread, (address) info->si_addr)) {
 232       // Block current thread until permission is restored.
 233       os::block_on_serialize_page_trap();
 234       return true;
 235     }
 236   }
 237 
 238   // signal-chaining
 239   if (os::Bsd::chained_handler(sig, info, ucVoid)) {
 240      return true;
 241   }
 242 
 243   if (!abort_if_unrecognized) {
 244     // caller wants another chance, so give it to him
 245     return false;
 246   }
 247 
 248 #ifndef PRODUCT
 249   if (sig == SIGSEGV) {
 250     fatal("\n#"
 251           "\n#    /--------------------\\"
 252           "\n#    | segmentation fault |"
 253           "\n#    \\---\\ /--------------/"
 254           "\n#        /"
 255           "\n#    [-]        |\\_/|    "
 256           "\n#    (+)=C      |o o|__  "
 257           "\n#    | |        =-*-=__\\ "
 258           "\n#    OOO        c_c_(___)");
 259   }
 260 #endif // !PRODUCT
 261 
 262   const char *fmt = "caught unhandled signal %d";
 263   char buf[64];
 264 
 265   sprintf(buf, fmt, sig);
 266   fatal(buf);
 267 }
 268 
 269 void os::Bsd::init_thread_fpu_state(void) {
 270   // Nothing to do
 271 }
 272 
 273 #ifndef _ALLBSD_SOURCE
 274 int os::Bsd::get_fpu_control_word() {
 275   ShouldNotCallThis();
 276 }
 277 
 278 void os::Bsd::set_fpu_control_word(int fpu) {
 279   ShouldNotCallThis();
 280 }
 281 #endif
 282 
 283 bool os::is_allocatable(size_t bytes) {
 284 #ifdef _LP64
 285   return true;
 286 #else
 287   if (bytes < 2 * G) {
 288     return true;
 289   }
 290 
 291   char* addr = reserve_memory(bytes, NULL);
 292 
 293   if (addr != NULL) {
 294     release_memory(addr, bytes);
 295   }
 296 
 297   return addr != NULL;
 298 #endif // _LP64
 299 }
 300 
 301 ///////////////////////////////////////////////////////////////////////////////
 302 // thread stack
 303 
 304 size_t os::Bsd::min_stack_allowed = 64 * K;
 305 
 306 bool os::Bsd::supports_variable_stack_size() {
 307   return true;
 308 }
 309 
 310 size_t os::Bsd::default_stack_size(os::ThreadType thr_type) {
 311 #ifdef _LP64
 312   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
 313 #else
 314   size_t s = (thr_type == os::compiler_thread ? 2 * M : 512 * K);
 315 #endif // _LP64
 316   return s;
 317 }
 318 
 319 size_t os::Bsd::default_guard_size(os::ThreadType thr_type) {
 320   // Only enable glibc guard pages for non-Java threads
 321   // (Java threads have HotSpot guard pages)
 322   return (thr_type == java_thread ? 0 : page_size());
 323 }
 324 
 325 static void current_stack_region(address *bottom, size_t *size) {
 326   address stack_bottom;
 327   address stack_top;
 328   size_t stack_bytes;
 329 
 330 #ifdef __APPLE__
 331   pthread_t self = pthread_self();
 332   stack_top = (address) pthread_get_stackaddr_np(self);
 333   stack_bytes = pthread_get_stacksize_np(self);
 334   stack_bottom = stack_top - stack_bytes;
 335 #elif defined(__OpenBSD__)
 336   stack_t ss;
 337   int rslt = pthread_stackseg_np(pthread_self(), &ss);
 338 
 339   if (rslt != 0)
 340     fatal(err_msg("pthread_stackseg_np failed with err = %d", rslt));
 341 
 342   stack_top = (address) ss.ss_sp;
 343   stack_bytes  = ss.ss_size;
 344   stack_bottom = stacktop - stack_bytes;
 345 #elif defined(_ALLBSD_SOURCE)
 346   pthread_attr_t attr;
 347 
 348   int rslt = pthread_attr_init(&attr);
 349 
 350   // JVM needs to know exact stack location, abort if it fails
 351   if (rslt != 0)
 352     fatal(err_msg("pthread_attr_init failed with err = %d", rslt));
 353 
 354   rslt = pthread_attr_get_np(pthread_self(), &attr);
 355 
 356   if (rslt != 0)
 357     fatal(err_msg("pthread_attr_get_np failed with err = %d", rslt));
 358 
 359   if (pthread_attr_getstackaddr(&attr, (void **) &stack_bottom) != 0 ||
 360       pthread_attr_getstacksize(&attr, &stack_bytes) != 0) {
 361     fatal("Can not locate current stack attributes!");
 362   }
 363 
 364   pthread_attr_destroy(&attr);
 365 
 366   stack_top = stack_bottom + stack_bytes;
 367 #else /* Linux */
 368   pthread_attr_t attr;
 369   int res = pthread_getattr_np(pthread_self(), &attr);
 370   if (res != 0) {
 371     if (res == ENOMEM) {
 372       vm_exit_out_of_memory(0, "pthread_getattr_np");
 373     }
 374     else {
 375       fatal(err_msg("pthread_getattr_np failed with errno = %d", res));
 376     }
 377   }
 378 
 379   res = pthread_attr_getstack(&attr, (void **) &stack_bottom, &stack_bytes);
 380   if (res != 0) {
 381     fatal(err_msg("pthread_attr_getstack failed with errno = %d", res));
 382   }
 383   stack_top = stack_bottom + stack_bytes;
 384 
 385   // The block of memory returned by pthread_attr_getstack() includes
 386   // guard pages where present.  We need to trim these off.
 387   size_t page_bytes = os::Bsd::page_size();
 388   assert(((intptr_t) stack_bottom & (page_bytes - 1)) == 0, "unaligned stack");
 389 
 390   size_t guard_bytes;
 391   res = pthread_attr_getguardsize(&attr, &guard_bytes);
 392   if (res != 0) {
 393     fatal(err_msg("pthread_attr_getguardsize failed with errno = %d", res));
 394   }
 395   int guard_pages = align_size_up(guard_bytes, page_bytes) / page_bytes;
 396   assert(guard_bytes == guard_pages * page_bytes, "unaligned guard");
 397 
 398 #ifdef IA64
 399   // IA64 has two stacks sharing the same area of memory, a normal
 400   // stack growing downwards and a register stack growing upwards.
 401   // Guard pages, if present, are in the centre.  This code splits
 402   // the stack in two even without guard pages, though in theory
 403   // there's nothing to stop us allocating more to the normal stack
 404   // or more to the register stack if one or the other were found
 405   // to grow faster.
 406   int total_pages = align_size_down(stack_bytes, page_bytes) / page_bytes;
 407   stack_bottom += (total_pages - guard_pages) / 2 * page_bytes;
 408 #endif // IA64
 409 
 410   stack_bottom += guard_bytes;
 411 
 412   pthread_attr_destroy(&attr);
 413 
 414   // The initial thread has a growable stack, and the size reported
 415   // by pthread_attr_getstack is the maximum size it could possibly
 416   // be given what currently mapped.  This can be huge, so we cap it.
 417   if (os::Bsd::is_initial_thread()) {
 418     stack_bytes = stack_top - stack_bottom;
 419 
 420     if (stack_bytes > JavaThread::stack_size_at_create())
 421       stack_bytes = JavaThread::stack_size_at_create();
 422 
 423     stack_bottom = stack_top - stack_bytes;
 424   }
 425 #endif
 426 
 427   assert(os::current_stack_pointer() >= stack_bottom, "should do");
 428   assert(os::current_stack_pointer() < stack_top, "should do");
 429 
 430   *bottom = stack_bottom;
 431   *size = stack_top - stack_bottom;
 432 }
 433 
 434 address os::current_stack_base() {
 435   address bottom;
 436   size_t size;
 437   current_stack_region(&bottom, &size);
 438   return bottom + size;
 439 }
 440 
 441 size_t os::current_stack_size() {
 442   // stack size includes normal stack and HotSpot guard pages
 443   address bottom;
 444   size_t size;
 445   current_stack_region(&bottom, &size);
 446   return size;
 447 }
 448 
 449 /////////////////////////////////////////////////////////////////////////////
 450 // helper functions for fatal error handler
 451 
 452 void os::print_context(outputStream* st, void* context) {
 453   ShouldNotCallThis();
 454 }
 455 
 456 void os::print_register_info(outputStream *st, void *context) {
 457   ShouldNotCallThis();
 458 }
 459 
 460 /////////////////////////////////////////////////////////////////////////////
 461 // Stubs for things that would be in bsd_zero.s if it existed.
 462 // You probably want to disassemble these monkeys to check they're ok.
 463 
 464 extern "C" {
 465   int SpinPause() {
 466   }
 467 
 468   int SafeFetch32(int *adr, int errValue) {
 469     int value = errValue;
 470     value = *adr;
 471     return value;
 472   }
 473   intptr_t SafeFetchN(intptr_t *adr, intptr_t errValue) {
 474     intptr_t value = errValue;
 475     value = *adr;
 476     return value;
 477   }
 478 
 479   void _Copy_conjoint_jshorts_atomic(jshort* from, jshort* to, size_t count) {
 480     if (from > to) {
 481       jshort *end = from + count;
 482       while (from < end)
 483         *(to++) = *(from++);
 484     }
 485     else if (from < to) {
 486       jshort *end = from;
 487       from += count - 1;
 488       to   += count - 1;
 489       while (from >= end)
 490         *(to--) = *(from--);
 491     }
 492   }
 493   void _Copy_conjoint_jints_atomic(jint* from, jint* to, size_t count) {
 494     if (from > to) {
 495       jint *end = from + count;
 496       while (from < end)
 497         *(to++) = *(from++);
 498     }
 499     else if (from < to) {
 500       jint *end = from;
 501       from += count - 1;
 502       to   += count - 1;
 503       while (from >= end)
 504         *(to--) = *(from--);
 505     }
 506   }
 507   void _Copy_conjoint_jlongs_atomic(jlong* from, jlong* to, size_t count) {
 508     if (from > to) {
 509       jlong *end = from + count;
 510       while (from < end)
 511         os::atomic_copy64(from++, to++);
 512     }
 513     else if (from < to) {
 514       jlong *end = from;
 515       from += count - 1;
 516       to   += count - 1;
 517       while (from >= end)
 518         os::atomic_copy64(from--, to--);
 519     }
 520   }
 521 
 522   void _Copy_arrayof_conjoint_bytes(HeapWord* from,
 523                                     HeapWord* to,
 524                                     size_t    count) {
 525     memmove(to, from, count);
 526   }
 527   void _Copy_arrayof_conjoint_jshorts(HeapWord* from,
 528                                       HeapWord* to,
 529                                       size_t    count) {
 530     memmove(to, from, count * 2);
 531   }
 532   void _Copy_arrayof_conjoint_jints(HeapWord* from,
 533                                     HeapWord* to,
 534                                     size_t    count) {
 535     memmove(to, from, count * 4);
 536   }
 537   void _Copy_arrayof_conjoint_jlongs(HeapWord* from,
 538                                      HeapWord* to,
 539                                      size_t    count) {
 540     memmove(to, from, count * 8);
 541   }
 542 };
 543 
 544 /////////////////////////////////////////////////////////////////////////////
 545 // Implementations of atomic operations not supported by processors.
 546 //  -- http://gcc.gnu.org/onlinedocs/gcc-4.2.1/gcc/Atomic-Builtins.html
 547 
 548 #ifndef _LP64
 549 extern "C" {
 550   long long unsigned int __sync_val_compare_and_swap_8(
 551     volatile void *ptr,
 552     long long unsigned int oldval,
 553     long long unsigned int newval) {
 554     ShouldNotCallThis();
 555   }
 556 };
 557 #endif // !_LP64