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