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