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