1 /* 2 * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 // no precompiled headers 26 #include "classfile/classLoader.hpp" 27 #include "classfile/systemDictionary.hpp" 28 #include "classfile/vmSymbols.hpp" 29 #include "code/icBuffer.hpp" 30 #include "code/vtableStubs.hpp" 31 #include "compiler/compileBroker.hpp" 32 #include "compiler/disassembler.hpp" 33 #include "interpreter/interpreter.hpp" 34 #include "jvm_linux.h" 35 #include "memory/allocation.inline.hpp" 36 #include "memory/filemap.hpp" 37 #include "mutex_linux.inline.hpp" 38 #include "oops/oop.inline.hpp" 39 #include "os_linux.inline.hpp" 40 #include "os_share_linux.hpp" 41 #include "prims/jniFastGetField.hpp" 42 #include "prims/jvm.h" 43 #include "prims/jvm_misc.hpp" 44 #include "runtime/arguments.hpp" 45 #include "runtime/atomic.inline.hpp" 46 #include "runtime/extendedPC.hpp" 47 #include "runtime/globals.hpp" 48 #include "runtime/interfaceSupport.hpp" 49 #include "runtime/init.hpp" 50 #include "runtime/java.hpp" 51 #include "runtime/javaCalls.hpp" 52 #include "runtime/mutexLocker.hpp" 53 #include "runtime/objectMonitor.hpp" 54 #include "runtime/orderAccess.inline.hpp" 55 #include "runtime/osThread.hpp" 56 #include "runtime/perfMemory.hpp" 57 #include "runtime/sharedRuntime.hpp" 58 #include "runtime/statSampler.hpp" 59 #include "runtime/stubRoutines.hpp" 60 #include "runtime/thread.inline.hpp" 61 #include "runtime/threadCritical.hpp" 62 #include "runtime/timer.hpp" 63 #include "semaphore_posix.hpp" 64 #include "services/attachListener.hpp" 65 #include "services/memTracker.hpp" 66 #include "services/runtimeService.hpp" 67 #include "utilities/decoder.hpp" 68 #include "utilities/defaultStream.hpp" 69 #include "utilities/events.hpp" 70 #include "utilities/elfFile.hpp" 71 #include "utilities/growableArray.hpp" 72 #include "utilities/macros.hpp" 73 #include "utilities/vmError.hpp" 74 75 // put OS-includes here 76 # include <sys/types.h> 77 # include <sys/mman.h> 78 # include <sys/stat.h> 79 # include <sys/select.h> 80 # include <pthread.h> 81 # include <signal.h> 82 # include <errno.h> 83 # include <dlfcn.h> 84 # include <stdio.h> 85 # include <unistd.h> 86 # include <sys/resource.h> 87 # include <pthread.h> 88 # include <sys/stat.h> 89 # include <sys/time.h> 90 # include <sys/times.h> 91 # include <sys/utsname.h> 92 # include <sys/socket.h> 93 # include <sys/wait.h> 94 # include <pwd.h> 95 # include <poll.h> 96 # include <semaphore.h> 97 # include <fcntl.h> 98 # include <string.h> 99 # include <syscall.h> 100 # include <sys/sysinfo.h> 101 # include <gnu/libc-version.h> 102 # include <sys/ipc.h> 103 # include <sys/shm.h> 104 # include <link.h> 105 # include <stdint.h> 106 # include <inttypes.h> 107 # include <sys/ioctl.h> 108 109 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC 110 111 // if RUSAGE_THREAD for getrusage() has not been defined, do it here. The code calling 112 // getrusage() is prepared to handle the associated failure. 113 #ifndef RUSAGE_THREAD 114 #define RUSAGE_THREAD (1) /* only the calling thread */ 115 #endif 116 117 #define MAX_PATH (2 * K) 118 119 #define MAX_SECS 100000000 120 121 // for timer info max values which include all bits 122 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) 123 124 #define LARGEPAGES_BIT (1 << 6) 125 //////////////////////////////////////////////////////////////////////////////// 126 // global variables 127 julong os::Linux::_physical_memory = 0; 128 129 address os::Linux::_initial_thread_stack_bottom = NULL; 130 uintptr_t os::Linux::_initial_thread_stack_size = 0; 131 132 int (*os::Linux::_clock_gettime)(clockid_t, struct timespec *) = NULL; 133 int (*os::Linux::_pthread_getcpuclockid)(pthread_t, clockid_t *) = NULL; 134 int (*os::Linux::_pthread_setname_np)(pthread_t, const char*) = NULL; 135 Mutex* os::Linux::_createThread_lock = NULL; 136 pthread_t os::Linux::_main_thread; 137 int os::Linux::_page_size = -1; 138 const int os::Linux::_vm_default_page_size = (8 * K); 139 bool os::Linux::_is_floating_stack = false; 140 bool os::Linux::_is_NPTL = false; 141 bool os::Linux::_supports_fast_thread_cpu_time = false; 142 const char * os::Linux::_glibc_version = NULL; 143 const char * os::Linux::_libpthread_version = NULL; 144 pthread_condattr_t os::Linux::_condattr[1]; 145 146 static jlong initial_time_count=0; 147 148 static int clock_tics_per_sec = 100; 149 150 // For diagnostics to print a message once. see run_periodic_checks 151 static sigset_t check_signal_done; 152 static bool check_signals = true; 153 154 static pid_t _initial_pid = 0; 155 156 // Signal number used to suspend/resume a thread 157 158 // do not use any signal number less than SIGSEGV, see 4355769 159 static int SR_signum = SIGUSR2; 160 sigset_t SR_sigset; 161 162 // Declarations 163 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time); 164 165 // utility functions 166 167 static int SR_initialize(); 168 169 julong os::available_memory() { 170 return Linux::available_memory(); 171 } 172 173 julong os::Linux::available_memory() { 174 // values in struct sysinfo are "unsigned long" 175 struct sysinfo si; 176 sysinfo(&si); 177 178 return (julong)si.freeram * si.mem_unit; 179 } 180 181 julong os::physical_memory() { 182 return Linux::physical_memory(); 183 } 184 185 // Return true if user is running as root. 186 187 bool os::have_special_privileges() { 188 static bool init = false; 189 static bool privileges = false; 190 if (!init) { 191 privileges = (getuid() != geteuid()) || (getgid() != getegid()); 192 init = true; 193 } 194 return privileges; 195 } 196 197 198 #ifndef SYS_gettid 199 // i386: 224, ia64: 1105, amd64: 186, sparc 143 200 #ifdef __ia64__ 201 #define SYS_gettid 1105 202 #else 203 #ifdef __i386__ 204 #define SYS_gettid 224 205 #else 206 #ifdef __amd64__ 207 #define SYS_gettid 186 208 #else 209 #ifdef __sparc__ 210 #define SYS_gettid 143 211 #else 212 #error define gettid for the arch 213 #endif 214 #endif 215 #endif 216 #endif 217 #endif 218 219 // Cpu architecture string 220 static char cpu_arch[] = HOTSPOT_LIB_ARCH; 221 222 223 // pid_t gettid() 224 // 225 // Returns the kernel thread id of the currently running thread. Kernel 226 // thread id is used to access /proc. 227 // 228 // (Note that getpid() on LinuxThreads returns kernel thread id too; but 229 // on NPTL, it returns the same pid for all threads, as required by POSIX.) 230 // 231 pid_t os::Linux::gettid() { 232 int rslt = syscall(SYS_gettid); 233 if (rslt == -1) { 234 // old kernel, no NPTL support 235 return getpid(); 236 } else { 237 return (pid_t)rslt; 238 } 239 } 240 241 // Most versions of linux have a bug where the number of processors are 242 // determined by looking at the /proc file system. In a chroot environment, 243 // the system call returns 1. This causes the VM to act as if it is 244 // a single processor and elide locking (see is_MP() call). 245 static bool unsafe_chroot_detected = false; 246 static const char *unstable_chroot_error = "/proc file system not found.\n" 247 "Java may be unstable running multithreaded in a chroot " 248 "environment on Linux when /proc filesystem is not mounted."; 249 250 void os::Linux::initialize_system_info() { 251 set_processor_count(sysconf(_SC_NPROCESSORS_CONF)); 252 if (processor_count() == 1) { 253 pid_t pid = os::Linux::gettid(); 254 char fname[32]; 255 jio_snprintf(fname, sizeof(fname), "/proc/%d", pid); 256 FILE *fp = fopen(fname, "r"); 257 if (fp == NULL) { 258 unsafe_chroot_detected = true; 259 } else { 260 fclose(fp); 261 } 262 } 263 _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE); 264 assert(processor_count() > 0, "linux error"); 265 } 266 267 void os::init_system_properties_values() { 268 // The next steps are taken in the product version: 269 // 270 // Obtain the JAVA_HOME value from the location of libjvm.so. 271 // This library should be located at: 272 // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so. 273 // 274 // If "/jre/lib/" appears at the right place in the path, then we 275 // assume libjvm.so is installed in a JDK and we use this path. 276 // 277 // Otherwise exit with message: "Could not create the Java virtual machine." 278 // 279 // The following extra steps are taken in the debugging version: 280 // 281 // If "/jre/lib/" does NOT appear at the right place in the path 282 // instead of exit check for $JAVA_HOME environment variable. 283 // 284 // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>, 285 // then we append a fake suffix "hotspot/libjvm.so" to this path so 286 // it looks like libjvm.so is installed there 287 // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so. 288 // 289 // Otherwise exit. 290 // 291 // Important note: if the location of libjvm.so changes this 292 // code needs to be changed accordingly. 293 294 // See ld(1): 295 // The linker uses the following search paths to locate required 296 // shared libraries: 297 // 1: ... 298 // ... 299 // 7: The default directories, normally /lib and /usr/lib. 300 #if defined(AMD64) || defined(_LP64) && (defined(SPARC) || defined(PPC) || defined(S390)) 301 #define DEFAULT_LIBPATH "/usr/lib64:/lib64:/lib:/usr/lib" 302 #else 303 #define DEFAULT_LIBPATH "/lib:/usr/lib" 304 #endif 305 306 // Base path of extensions installed on the system. 307 #define SYS_EXT_DIR "/usr/java/packages" 308 #define EXTENSIONS_DIR "/lib/ext" 309 310 // Buffer that fits several sprintfs. 311 // Note that the space for the colon and the trailing null are provided 312 // by the nulls included by the sizeof operator. 313 const size_t bufsize = 314 MAX2((size_t)MAXPATHLEN, // For dll_dir & friends. 315 (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR)); // extensions dir 316 char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal); 317 318 // sysclasspath, java_home, dll_dir 319 { 320 char *pslash; 321 os::jvm_path(buf, bufsize); 322 323 // Found the full path to libjvm.so. 324 // Now cut the path to <java_home>/jre if we can. 325 pslash = strrchr(buf, '/'); 326 if (pslash != NULL) { 327 *pslash = '\0'; // Get rid of /libjvm.so. 328 } 329 pslash = strrchr(buf, '/'); 330 if (pslash != NULL) { 331 *pslash = '\0'; // Get rid of /{client|server|hotspot}. 332 } 333 Arguments::set_dll_dir(buf); 334 335 if (pslash != NULL) { 336 pslash = strrchr(buf, '/'); 337 if (pslash != NULL) { 338 *pslash = '\0'; // Get rid of /<arch>. 339 pslash = strrchr(buf, '/'); 340 if (pslash != NULL) { 341 *pslash = '\0'; // Get rid of /lib. 342 } 343 } 344 } 345 Arguments::set_java_home(buf); 346 set_boot_path('/', ':'); 347 } 348 349 // Where to look for native libraries. 350 // 351 // Note: Due to a legacy implementation, most of the library path 352 // is set in the launcher. This was to accomodate linking restrictions 353 // on legacy Linux implementations (which are no longer supported). 354 // Eventually, all the library path setting will be done here. 355 // 356 // However, to prevent the proliferation of improperly built native 357 // libraries, the new path component /usr/java/packages is added here. 358 // Eventually, all the library path setting will be done here. 359 { 360 // Get the user setting of LD_LIBRARY_PATH, and prepended it. It 361 // should always exist (until the legacy problem cited above is 362 // addressed). 363 const char *v = ::getenv("LD_LIBRARY_PATH"); 364 const char *v_colon = ":"; 365 if (v == NULL) { v = ""; v_colon = ""; } 366 // That's +1 for the colon and +1 for the trailing '\0'. 367 char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char, 368 strlen(v) + 1 + 369 sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH) + 1, 370 mtInternal); 371 sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib/%s:" DEFAULT_LIBPATH, v, v_colon, cpu_arch); 372 Arguments::set_library_path(ld_library_path); 373 FREE_C_HEAP_ARRAY(char, ld_library_path); 374 } 375 376 // Extensions directories. 377 sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home()); 378 Arguments::set_ext_dirs(buf); 379 380 FREE_C_HEAP_ARRAY(char, buf); 381 382 #undef DEFAULT_LIBPATH 383 #undef SYS_EXT_DIR 384 #undef EXTENSIONS_DIR 385 } 386 387 //////////////////////////////////////////////////////////////////////////////// 388 // breakpoint support 389 390 void os::breakpoint() { 391 BREAKPOINT; 392 } 393 394 extern "C" void breakpoint() { 395 // use debugger to set breakpoint here 396 } 397 398 //////////////////////////////////////////////////////////////////////////////// 399 // signal support 400 401 debug_only(static bool signal_sets_initialized = false); 402 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs; 403 404 bool os::Linux::is_sig_ignored(int sig) { 405 struct sigaction oact; 406 sigaction(sig, (struct sigaction*)NULL, &oact); 407 void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction) 408 : CAST_FROM_FN_PTR(void*, oact.sa_handler); 409 if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) { 410 return true; 411 } else { 412 return false; 413 } 414 } 415 416 void os::Linux::signal_sets_init() { 417 // Should also have an assertion stating we are still single-threaded. 418 assert(!signal_sets_initialized, "Already initialized"); 419 // Fill in signals that are necessarily unblocked for all threads in 420 // the VM. Currently, we unblock the following signals: 421 // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden 422 // by -Xrs (=ReduceSignalUsage)); 423 // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all 424 // other threads. The "ReduceSignalUsage" boolean tells us not to alter 425 // the dispositions or masks wrt these signals. 426 // Programs embedding the VM that want to use the above signals for their 427 // own purposes must, at this time, use the "-Xrs" option to prevent 428 // interference with shutdown hooks and BREAK_SIGNAL thread dumping. 429 // (See bug 4345157, and other related bugs). 430 // In reality, though, unblocking these signals is really a nop, since 431 // these signals are not blocked by default. 432 sigemptyset(&unblocked_sigs); 433 sigemptyset(&allowdebug_blocked_sigs); 434 sigaddset(&unblocked_sigs, SIGILL); 435 sigaddset(&unblocked_sigs, SIGSEGV); 436 sigaddset(&unblocked_sigs, SIGBUS); 437 sigaddset(&unblocked_sigs, SIGFPE); 438 #if defined(PPC64) 439 sigaddset(&unblocked_sigs, SIGTRAP); 440 #endif 441 sigaddset(&unblocked_sigs, SR_signum); 442 443 if (!ReduceSignalUsage) { 444 if (!os::Linux::is_sig_ignored(SHUTDOWN1_SIGNAL)) { 445 sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL); 446 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL); 447 } 448 if (!os::Linux::is_sig_ignored(SHUTDOWN2_SIGNAL)) { 449 sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL); 450 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL); 451 } 452 if (!os::Linux::is_sig_ignored(SHUTDOWN3_SIGNAL)) { 453 sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL); 454 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL); 455 } 456 } 457 // Fill in signals that are blocked by all but the VM thread. 458 sigemptyset(&vm_sigs); 459 if (!ReduceSignalUsage) { 460 sigaddset(&vm_sigs, BREAK_SIGNAL); 461 } 462 debug_only(signal_sets_initialized = true); 463 464 } 465 466 // These are signals that are unblocked while a thread is running Java. 467 // (For some reason, they get blocked by default.) 468 sigset_t* os::Linux::unblocked_signals() { 469 assert(signal_sets_initialized, "Not initialized"); 470 return &unblocked_sigs; 471 } 472 473 // These are the signals that are blocked while a (non-VM) thread is 474 // running Java. Only the VM thread handles these signals. 475 sigset_t* os::Linux::vm_signals() { 476 assert(signal_sets_initialized, "Not initialized"); 477 return &vm_sigs; 478 } 479 480 // These are signals that are blocked during cond_wait to allow debugger in 481 sigset_t* os::Linux::allowdebug_blocked_signals() { 482 assert(signal_sets_initialized, "Not initialized"); 483 return &allowdebug_blocked_sigs; 484 } 485 486 void os::Linux::hotspot_sigmask(Thread* thread) { 487 488 //Save caller's signal mask before setting VM signal mask 489 sigset_t caller_sigmask; 490 pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask); 491 492 OSThread* osthread = thread->osthread(); 493 osthread->set_caller_sigmask(caller_sigmask); 494 495 pthread_sigmask(SIG_UNBLOCK, os::Linux::unblocked_signals(), NULL); 496 497 if (!ReduceSignalUsage) { 498 if (thread->is_VM_thread()) { 499 // Only the VM thread handles BREAK_SIGNAL ... 500 pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL); 501 } else { 502 // ... all other threads block BREAK_SIGNAL 503 pthread_sigmask(SIG_BLOCK, vm_signals(), NULL); 504 } 505 } 506 } 507 508 ////////////////////////////////////////////////////////////////////////////// 509 // detecting pthread library 510 511 void os::Linux::libpthread_init() { 512 // Save glibc and pthread version strings. Note that _CS_GNU_LIBC_VERSION 513 // and _CS_GNU_LIBPTHREAD_VERSION are supported in glibc >= 2.3.2. Use a 514 // generic name for earlier versions. 515 // Define macros here so we can build HotSpot on old systems. 516 #ifndef _CS_GNU_LIBC_VERSION 517 #define _CS_GNU_LIBC_VERSION 2 518 #endif 519 #ifndef _CS_GNU_LIBPTHREAD_VERSION 520 #define _CS_GNU_LIBPTHREAD_VERSION 3 521 #endif 522 523 size_t n = confstr(_CS_GNU_LIBC_VERSION, NULL, 0); 524 if (n > 0) { 525 char *str = (char *)malloc(n, mtInternal); 526 confstr(_CS_GNU_LIBC_VERSION, str, n); 527 os::Linux::set_glibc_version(str); 528 } else { 529 // _CS_GNU_LIBC_VERSION is not supported, try gnu_get_libc_version() 530 static char _gnu_libc_version[32]; 531 jio_snprintf(_gnu_libc_version, sizeof(_gnu_libc_version), 532 "glibc %s %s", gnu_get_libc_version(), gnu_get_libc_release()); 533 os::Linux::set_glibc_version(_gnu_libc_version); 534 } 535 536 n = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, 0); 537 if (n > 0) { 538 char *str = (char *)malloc(n, mtInternal); 539 confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n); 540 // Vanilla RH-9 (glibc 2.3.2) has a bug that confstr() always tells 541 // us "NPTL-0.29" even we are running with LinuxThreads. Check if this 542 // is the case. LinuxThreads has a hard limit on max number of threads. 543 // So sysconf(_SC_THREAD_THREADS_MAX) will return a positive value. 544 // On the other hand, NPTL does not have such a limit, sysconf() 545 // will return -1 and errno is not changed. Check if it is really NPTL. 546 if (strcmp(os::Linux::glibc_version(), "glibc 2.3.2") == 0 && 547 strstr(str, "NPTL") && 548 sysconf(_SC_THREAD_THREADS_MAX) > 0) { 549 free(str); 550 os::Linux::set_libpthread_version("linuxthreads"); 551 } else { 552 os::Linux::set_libpthread_version(str); 553 } 554 } else { 555 // glibc before 2.3.2 only has LinuxThreads. 556 os::Linux::set_libpthread_version("linuxthreads"); 557 } 558 559 if (strstr(libpthread_version(), "NPTL")) { 560 os::Linux::set_is_NPTL(); 561 } else { 562 os::Linux::set_is_LinuxThreads(); 563 } 564 565 // LinuxThreads have two flavors: floating-stack mode, which allows variable 566 // stack size; and fixed-stack mode. NPTL is always floating-stack. 567 if (os::Linux::is_NPTL() || os::Linux::supports_variable_stack_size()) { 568 os::Linux::set_is_floating_stack(); 569 } 570 } 571 572 ///////////////////////////////////////////////////////////////////////////// 573 // thread stack 574 575 // Force Linux kernel to expand current thread stack. If "bottom" is close 576 // to the stack guard, caller should block all signals. 577 // 578 // MAP_GROWSDOWN: 579 // A special mmap() flag that is used to implement thread stacks. It tells 580 // kernel that the memory region should extend downwards when needed. This 581 // allows early versions of LinuxThreads to only mmap the first few pages 582 // when creating a new thread. Linux kernel will automatically expand thread 583 // stack as needed (on page faults). 584 // 585 // However, because the memory region of a MAP_GROWSDOWN stack can grow on 586 // demand, if a page fault happens outside an already mapped MAP_GROWSDOWN 587 // region, it's hard to tell if the fault is due to a legitimate stack 588 // access or because of reading/writing non-exist memory (e.g. buffer 589 // overrun). As a rule, if the fault happens below current stack pointer, 590 // Linux kernel does not expand stack, instead a SIGSEGV is sent to the 591 // application (see Linux kernel fault.c). 592 // 593 // This Linux feature can cause SIGSEGV when VM bangs thread stack for 594 // stack overflow detection. 595 // 596 // Newer version of LinuxThreads (since glibc-2.2, or, RH-7.x) and NPTL do 597 // not use this flag. However, the stack of initial thread is not created 598 // by pthread, it is still MAP_GROWSDOWN. Also it's possible (though 599 // unlikely) that user code can create a thread with MAP_GROWSDOWN stack 600 // and then attach the thread to JVM. 601 // 602 // To get around the problem and allow stack banging on Linux, we need to 603 // manually expand thread stack after receiving the SIGSEGV. 604 // 605 // There are two ways to expand thread stack to address "bottom", we used 606 // both of them in JVM before 1.5: 607 // 1. adjust stack pointer first so that it is below "bottom", and then 608 // touch "bottom" 609 // 2. mmap() the page in question 610 // 611 // Now alternate signal stack is gone, it's harder to use 2. For instance, 612 // if current sp is already near the lower end of page 101, and we need to 613 // call mmap() to map page 100, it is possible that part of the mmap() frame 614 // will be placed in page 100. When page 100 is mapped, it is zero-filled. 615 // That will destroy the mmap() frame and cause VM to crash. 616 // 617 // The following code works by adjusting sp first, then accessing the "bottom" 618 // page to force a page fault. Linux kernel will then automatically expand the 619 // stack mapping. 620 // 621 // _expand_stack_to() assumes its frame size is less than page size, which 622 // should always be true if the function is not inlined. 623 624 #if __GNUC__ < 3 // gcc 2.x does not support noinline attribute 625 #define NOINLINE 626 #else 627 #define NOINLINE __attribute__ ((noinline)) 628 #endif 629 630 static void _expand_stack_to(address bottom) NOINLINE; 631 632 static void _expand_stack_to(address bottom) { 633 address sp; 634 size_t size; 635 volatile char *p; 636 637 // Adjust bottom to point to the largest address within the same page, it 638 // gives us a one-page buffer if alloca() allocates slightly more memory. 639 bottom = (address)align_size_down((uintptr_t)bottom, os::Linux::page_size()); 640 bottom += os::Linux::page_size() - 1; 641 642 // sp might be slightly above current stack pointer; if that's the case, we 643 // will alloca() a little more space than necessary, which is OK. Don't use 644 // os::current_stack_pointer(), as its result can be slightly below current 645 // stack pointer, causing us to not alloca enough to reach "bottom". 646 sp = (address)&sp; 647 648 if (sp > bottom) { 649 size = sp - bottom; 650 p = (volatile char *)alloca(size); 651 assert(p != NULL && p <= (volatile char *)bottom, "alloca problem?"); 652 p[0] = '\0'; 653 } 654 } 655 656 bool os::Linux::manually_expand_stack(JavaThread * t, address addr) { 657 assert(t!=NULL, "just checking"); 658 assert(t->osthread()->expanding_stack(), "expand should be set"); 659 assert(t->stack_base() != NULL, "stack_base was not initialized"); 660 661 if (addr < t->stack_base() && addr >= t->stack_yellow_zone_base()) { 662 sigset_t mask_all, old_sigset; 663 sigfillset(&mask_all); 664 pthread_sigmask(SIG_SETMASK, &mask_all, &old_sigset); 665 _expand_stack_to(addr); 666 pthread_sigmask(SIG_SETMASK, &old_sigset, NULL); 667 return true; 668 } 669 return false; 670 } 671 672 ////////////////////////////////////////////////////////////////////////////// 673 // create new thread 674 675 static address highest_vm_reserved_address(); 676 677 // check if it's safe to start a new thread 678 static bool _thread_safety_check(Thread* thread) { 679 if (os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack()) { 680 // Fixed stack LinuxThreads (SuSE Linux/x86, and some versions of Redhat) 681 // Heap is mmap'ed at lower end of memory space. Thread stacks are 682 // allocated (MAP_FIXED) from high address space. Every thread stack 683 // occupies a fixed size slot (usually 2Mbytes, but user can change 684 // it to other values if they rebuild LinuxThreads). 685 // 686 // Problem with MAP_FIXED is that mmap() can still succeed even part of 687 // the memory region has already been mmap'ed. That means if we have too 688 // many threads and/or very large heap, eventually thread stack will 689 // collide with heap. 690 // 691 // Here we try to prevent heap/stack collision by comparing current 692 // stack bottom with the highest address that has been mmap'ed by JVM 693 // plus a safety margin for memory maps created by native code. 694 // 695 // This feature can be disabled by setting ThreadSafetyMargin to 0 696 // 697 if (ThreadSafetyMargin > 0) { 698 address stack_bottom = os::current_stack_base() - os::current_stack_size(); 699 700 // not safe if our stack extends below the safety margin 701 return stack_bottom - ThreadSafetyMargin >= highest_vm_reserved_address(); 702 } else { 703 return true; 704 } 705 } else { 706 // Floating stack LinuxThreads or NPTL: 707 // Unlike fixed stack LinuxThreads, thread stacks are not MAP_FIXED. When 708 // there's not enough space left, pthread_create() will fail. If we come 709 // here, that means enough space has been reserved for stack. 710 return true; 711 } 712 } 713 714 // Thread start routine for all newly created threads 715 static void *java_start(Thread *thread) { 716 // Try to randomize the cache line index of hot stack frames. 717 // This helps when threads of the same stack traces evict each other's 718 // cache lines. The threads can be either from the same JVM instance, or 719 // from different JVM instances. The benefit is especially true for 720 // processors with hyperthreading technology. 721 static int counter = 0; 722 int pid = os::current_process_id(); 723 alloca(((pid ^ counter++) & 7) * 128); 724 725 ThreadLocalStorage::set_thread(thread); 726 727 OSThread* osthread = thread->osthread(); 728 Monitor* sync = osthread->startThread_lock(); 729 730 // non floating stack LinuxThreads needs extra check, see above 731 if (!_thread_safety_check(thread)) { 732 // notify parent thread 733 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); 734 osthread->set_state(ZOMBIE); 735 sync->notify_all(); 736 return NULL; 737 } 738 739 // thread_id is kernel thread id (similar to Solaris LWP id) 740 osthread->set_thread_id(os::Linux::gettid()); 741 742 if (UseNUMA) { 743 int lgrp_id = os::numa_get_group_id(); 744 if (lgrp_id != -1) { 745 thread->set_lgrp_id(lgrp_id); 746 } 747 } 748 // initialize signal mask for this thread 749 os::Linux::hotspot_sigmask(thread); 750 751 // initialize floating point control register 752 os::Linux::init_thread_fpu_state(); 753 754 // handshaking with parent thread 755 { 756 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); 757 758 // notify parent thread 759 osthread->set_state(INITIALIZED); 760 sync->notify_all(); 761 762 // wait until os::start_thread() 763 while (osthread->get_state() == INITIALIZED) { 764 sync->wait(Mutex::_no_safepoint_check_flag); 765 } 766 } 767 768 // call one more level start routine 769 thread->run(); 770 771 return 0; 772 } 773 774 bool os::create_thread(Thread* thread, ThreadType thr_type, 775 size_t stack_size) { 776 assert(thread->osthread() == NULL, "caller responsible"); 777 778 // Allocate the OSThread object 779 OSThread* osthread = new OSThread(NULL, NULL); 780 if (osthread == NULL) { 781 return false; 782 } 783 784 // set the correct thread state 785 osthread->set_thread_type(thr_type); 786 787 // Initial state is ALLOCATED but not INITIALIZED 788 osthread->set_state(ALLOCATED); 789 790 thread->set_osthread(osthread); 791 792 // init thread attributes 793 pthread_attr_t attr; 794 pthread_attr_init(&attr); 795 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 796 797 // stack size 798 if (os::Linux::supports_variable_stack_size()) { 799 // calculate stack size if it's not specified by caller 800 if (stack_size == 0) { 801 stack_size = os::Linux::default_stack_size(thr_type); 802 803 switch (thr_type) { 804 case os::java_thread: 805 // Java threads use ThreadStackSize which default value can be 806 // changed with the flag -Xss 807 assert(JavaThread::stack_size_at_create() > 0, "this should be set"); 808 stack_size = JavaThread::stack_size_at_create(); 809 break; 810 case os::compiler_thread: 811 if (CompilerThreadStackSize > 0) { 812 stack_size = (size_t)(CompilerThreadStackSize * K); 813 break; 814 } // else fall through: 815 // use VMThreadStackSize if CompilerThreadStackSize is not defined 816 case os::vm_thread: 817 case os::pgc_thread: 818 case os::cgc_thread: 819 case os::watcher_thread: 820 if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K); 821 break; 822 } 823 } 824 825 stack_size = MAX2(stack_size, os::Linux::min_stack_allowed); 826 pthread_attr_setstacksize(&attr, stack_size); 827 } else { 828 // let pthread_create() pick the default value. 829 } 830 831 // glibc guard page 832 pthread_attr_setguardsize(&attr, os::Linux::default_guard_size(thr_type)); 833 834 ThreadState state; 835 836 { 837 // Serialize thread creation if we are running with fixed stack LinuxThreads 838 bool lock = os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack(); 839 if (lock) { 840 os::Linux::createThread_lock()->lock_without_safepoint_check(); 841 } 842 843 pthread_t tid; 844 int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread); 845 846 pthread_attr_destroy(&attr); 847 848 if (ret != 0) { 849 if (PrintMiscellaneous && (Verbose || WizardMode)) { 850 perror("pthread_create()"); 851 } 852 // Need to clean up stuff we've allocated so far 853 thread->set_osthread(NULL); 854 delete osthread; 855 if (lock) os::Linux::createThread_lock()->unlock(); 856 return false; 857 } 858 859 // Store pthread info into the OSThread 860 osthread->set_pthread_id(tid); 861 862 // Wait until child thread is either initialized or aborted 863 { 864 Monitor* sync_with_child = osthread->startThread_lock(); 865 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); 866 while ((state = osthread->get_state()) == ALLOCATED) { 867 sync_with_child->wait(Mutex::_no_safepoint_check_flag); 868 } 869 } 870 871 if (lock) { 872 os::Linux::createThread_lock()->unlock(); 873 } 874 } 875 876 // Aborted due to thread limit being reached 877 if (state == ZOMBIE) { 878 thread->set_osthread(NULL); 879 delete osthread; 880 return false; 881 } 882 883 // The thread is returned suspended (in state INITIALIZED), 884 // and is started higher up in the call chain 885 assert(state == INITIALIZED, "race condition"); 886 return true; 887 } 888 889 ///////////////////////////////////////////////////////////////////////////// 890 // attach existing thread 891 892 // bootstrap the main thread 893 bool os::create_main_thread(JavaThread* thread) { 894 assert(os::Linux::_main_thread == pthread_self(), "should be called inside main thread"); 895 return create_attached_thread(thread); 896 } 897 898 bool os::create_attached_thread(JavaThread* thread) { 899 #ifdef ASSERT 900 thread->verify_not_published(); 901 #endif 902 903 // Allocate the OSThread object 904 OSThread* osthread = new OSThread(NULL, NULL); 905 906 if (osthread == NULL) { 907 return false; 908 } 909 910 // Store pthread info into the OSThread 911 osthread->set_thread_id(os::Linux::gettid()); 912 osthread->set_pthread_id(::pthread_self()); 913 914 // initialize floating point control register 915 os::Linux::init_thread_fpu_state(); 916 917 // Initial thread state is RUNNABLE 918 osthread->set_state(RUNNABLE); 919 920 thread->set_osthread(osthread); 921 922 if (UseNUMA) { 923 int lgrp_id = os::numa_get_group_id(); 924 if (lgrp_id != -1) { 925 thread->set_lgrp_id(lgrp_id); 926 } 927 } 928 929 if (os::Linux::is_initial_thread()) { 930 // If current thread is initial thread, its stack is mapped on demand, 931 // see notes about MAP_GROWSDOWN. Here we try to force kernel to map 932 // the entire stack region to avoid SEGV in stack banging. 933 // It is also useful to get around the heap-stack-gap problem on SuSE 934 // kernel (see 4821821 for details). We first expand stack to the top 935 // of yellow zone, then enable stack yellow zone (order is significant, 936 // enabling yellow zone first will crash JVM on SuSE Linux), so there 937 // is no gap between the last two virtual memory regions. 938 939 JavaThread *jt = (JavaThread *)thread; 940 address addr = jt->stack_yellow_zone_base(); 941 assert(addr != NULL, "initialization problem?"); 942 assert(jt->stack_available(addr) > 0, "stack guard should not be enabled"); 943 944 osthread->set_expanding_stack(); 945 os::Linux::manually_expand_stack(jt, addr); 946 osthread->clear_expanding_stack(); 947 } 948 949 // initialize signal mask for this thread 950 // and save the caller's signal mask 951 os::Linux::hotspot_sigmask(thread); 952 953 return true; 954 } 955 956 void os::pd_start_thread(Thread* thread) { 957 OSThread * osthread = thread->osthread(); 958 assert(osthread->get_state() != INITIALIZED, "just checking"); 959 Monitor* sync_with_child = osthread->startThread_lock(); 960 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); 961 sync_with_child->notify(); 962 } 963 964 // Free Linux resources related to the OSThread 965 void os::free_thread(OSThread* osthread) { 966 assert(osthread != NULL, "osthread not set"); 967 968 if (Thread::current()->osthread() == osthread) { 969 // Restore caller's signal mask 970 sigset_t sigmask = osthread->caller_sigmask(); 971 pthread_sigmask(SIG_SETMASK, &sigmask, NULL); 972 } 973 974 delete osthread; 975 } 976 977 ////////////////////////////////////////////////////////////////////////////// 978 // thread local storage 979 980 // Restore the thread pointer if the destructor is called. This is in case 981 // someone from JNI code sets up a destructor with pthread_key_create to run 982 // detachCurrentThread on thread death. Unless we restore the thread pointer we 983 // will hang or crash. When detachCurrentThread is called the key will be set 984 // to null and we will not be called again. If detachCurrentThread is never 985 // called we could loop forever depending on the pthread implementation. 986 static void restore_thread_pointer(void* p) { 987 Thread* thread = (Thread*) p; 988 os::thread_local_storage_at_put(ThreadLocalStorage::thread_index(), thread); 989 } 990 991 int os::allocate_thread_local_storage() { 992 pthread_key_t key; 993 int rslt = pthread_key_create(&key, restore_thread_pointer); 994 assert(rslt == 0, "cannot allocate thread local storage"); 995 return (int)key; 996 } 997 998 // Note: This is currently not used by VM, as we don't destroy TLS key 999 // on VM exit. 1000 void os::free_thread_local_storage(int index) { 1001 int rslt = pthread_key_delete((pthread_key_t)index); 1002 assert(rslt == 0, "invalid index"); 1003 } 1004 1005 void os::thread_local_storage_at_put(int index, void* value) { 1006 int rslt = pthread_setspecific((pthread_key_t)index, value); 1007 assert(rslt == 0, "pthread_setspecific failed"); 1008 } 1009 1010 extern "C" Thread* get_thread() { 1011 return ThreadLocalStorage::thread(); 1012 } 1013 1014 ////////////////////////////////////////////////////////////////////////////// 1015 // initial thread 1016 1017 // Check if current thread is the initial thread, similar to Solaris thr_main. 1018 bool os::Linux::is_initial_thread(void) { 1019 char dummy; 1020 // If called before init complete, thread stack bottom will be null. 1021 // Can be called if fatal error occurs before initialization. 1022 if (initial_thread_stack_bottom() == NULL) return false; 1023 assert(initial_thread_stack_bottom() != NULL && 1024 initial_thread_stack_size() != 0, 1025 "os::init did not locate initial thread's stack region"); 1026 if ((address)&dummy >= initial_thread_stack_bottom() && 1027 (address)&dummy < initial_thread_stack_bottom() + initial_thread_stack_size()) { 1028 return true; 1029 } else { 1030 return false; 1031 } 1032 } 1033 1034 // Find the virtual memory area that contains addr 1035 static bool find_vma(address addr, address* vma_low, address* vma_high) { 1036 FILE *fp = fopen("/proc/self/maps", "r"); 1037 if (fp) { 1038 address low, high; 1039 while (!feof(fp)) { 1040 if (fscanf(fp, "%p-%p", &low, &high) == 2) { 1041 if (low <= addr && addr < high) { 1042 if (vma_low) *vma_low = low; 1043 if (vma_high) *vma_high = high; 1044 fclose(fp); 1045 return true; 1046 } 1047 } 1048 for (;;) { 1049 int ch = fgetc(fp); 1050 if (ch == EOF || ch == (int)'\n') break; 1051 } 1052 } 1053 fclose(fp); 1054 } 1055 return false; 1056 } 1057 1058 // Locate initial thread stack. This special handling of initial thread stack 1059 // is needed because pthread_getattr_np() on most (all?) Linux distros returns 1060 // bogus value for initial thread. 1061 void os::Linux::capture_initial_stack(size_t max_size) { 1062 // stack size is the easy part, get it from RLIMIT_STACK 1063 size_t stack_size; 1064 struct rlimit rlim; 1065 getrlimit(RLIMIT_STACK, &rlim); 1066 stack_size = rlim.rlim_cur; 1067 1068 // 6308388: a bug in ld.so will relocate its own .data section to the 1069 // lower end of primordial stack; reduce ulimit -s value a little bit 1070 // so we won't install guard page on ld.so's data section. 1071 stack_size -= 2 * page_size(); 1072 1073 // 4441425: avoid crash with "unlimited" stack size on SuSE 7.1 or Redhat 1074 // 7.1, in both cases we will get 2G in return value. 1075 // 4466587: glibc 2.2.x compiled w/o "--enable-kernel=2.4.0" (RH 7.0, 1076 // SuSE 7.2, Debian) can not handle alternate signal stack correctly 1077 // for initial thread if its stack size exceeds 6M. Cap it at 2M, 1078 // in case other parts in glibc still assumes 2M max stack size. 1079 // FIXME: alt signal stack is gone, maybe we can relax this constraint? 1080 // Problem still exists RH7.2 (IA64 anyway) but 2MB is a little small 1081 if (stack_size > 2 * K * K IA64_ONLY(*2)) { 1082 stack_size = 2 * K * K IA64_ONLY(*2); 1083 } 1084 // Try to figure out where the stack base (top) is. This is harder. 1085 // 1086 // When an application is started, glibc saves the initial stack pointer in 1087 // a global variable "__libc_stack_end", which is then used by system 1088 // libraries. __libc_stack_end should be pretty close to stack top. The 1089 // variable is available since the very early days. However, because it is 1090 // a private interface, it could disappear in the future. 1091 // 1092 // Linux kernel saves start_stack information in /proc/<pid>/stat. Similar 1093 // to __libc_stack_end, it is very close to stack top, but isn't the real 1094 // stack top. Note that /proc may not exist if VM is running as a chroot 1095 // program, so reading /proc/<pid>/stat could fail. Also the contents of 1096 // /proc/<pid>/stat could change in the future (though unlikely). 1097 // 1098 // We try __libc_stack_end first. If that doesn't work, look for 1099 // /proc/<pid>/stat. If neither of them works, we use current stack pointer 1100 // as a hint, which should work well in most cases. 1101 1102 uintptr_t stack_start; 1103 1104 // try __libc_stack_end first 1105 uintptr_t *p = (uintptr_t *)dlsym(RTLD_DEFAULT, "__libc_stack_end"); 1106 if (p && *p) { 1107 stack_start = *p; 1108 } else { 1109 // see if we can get the start_stack field from /proc/self/stat 1110 FILE *fp; 1111 int pid; 1112 char state; 1113 int ppid; 1114 int pgrp; 1115 int session; 1116 int nr; 1117 int tpgrp; 1118 unsigned long flags; 1119 unsigned long minflt; 1120 unsigned long cminflt; 1121 unsigned long majflt; 1122 unsigned long cmajflt; 1123 unsigned long utime; 1124 unsigned long stime; 1125 long cutime; 1126 long cstime; 1127 long prio; 1128 long nice; 1129 long junk; 1130 long it_real; 1131 uintptr_t start; 1132 uintptr_t vsize; 1133 intptr_t rss; 1134 uintptr_t rsslim; 1135 uintptr_t scodes; 1136 uintptr_t ecode; 1137 int i; 1138 1139 // Figure what the primordial thread stack base is. Code is inspired 1140 // by email from Hans Boehm. /proc/self/stat begins with current pid, 1141 // followed by command name surrounded by parentheses, state, etc. 1142 char stat[2048]; 1143 int statlen; 1144 1145 fp = fopen("/proc/self/stat", "r"); 1146 if (fp) { 1147 statlen = fread(stat, 1, 2047, fp); 1148 stat[statlen] = '\0'; 1149 fclose(fp); 1150 1151 // Skip pid and the command string. Note that we could be dealing with 1152 // weird command names, e.g. user could decide to rename java launcher 1153 // to "java 1.4.2 :)", then the stat file would look like 1154 // 1234 (java 1.4.2 :)) R ... ... 1155 // We don't really need to know the command string, just find the last 1156 // occurrence of ")" and then start parsing from there. See bug 4726580. 1157 char * s = strrchr(stat, ')'); 1158 1159 i = 0; 1160 if (s) { 1161 // Skip blank chars 1162 do { s++; } while (s && isspace(*s)); 1163 1164 #define _UFM UINTX_FORMAT 1165 #define _DFM INTX_FORMAT 1166 1167 // 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 1168 // 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 1169 i = sscanf(s, "%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld " _UFM _UFM _DFM _UFM _UFM _UFM _UFM, 1170 &state, // 3 %c 1171 &ppid, // 4 %d 1172 &pgrp, // 5 %d 1173 &session, // 6 %d 1174 &nr, // 7 %d 1175 &tpgrp, // 8 %d 1176 &flags, // 9 %lu 1177 &minflt, // 10 %lu 1178 &cminflt, // 11 %lu 1179 &majflt, // 12 %lu 1180 &cmajflt, // 13 %lu 1181 &utime, // 14 %lu 1182 &stime, // 15 %lu 1183 &cutime, // 16 %ld 1184 &cstime, // 17 %ld 1185 &prio, // 18 %ld 1186 &nice, // 19 %ld 1187 &junk, // 20 %ld 1188 &it_real, // 21 %ld 1189 &start, // 22 UINTX_FORMAT 1190 &vsize, // 23 UINTX_FORMAT 1191 &rss, // 24 INTX_FORMAT 1192 &rsslim, // 25 UINTX_FORMAT 1193 &scodes, // 26 UINTX_FORMAT 1194 &ecode, // 27 UINTX_FORMAT 1195 &stack_start); // 28 UINTX_FORMAT 1196 } 1197 1198 #undef _UFM 1199 #undef _DFM 1200 1201 if (i != 28 - 2) { 1202 assert(false, "Bad conversion from /proc/self/stat"); 1203 // product mode - assume we are the initial thread, good luck in the 1204 // embedded case. 1205 warning("Can't detect initial thread stack location - bad conversion"); 1206 stack_start = (uintptr_t) &rlim; 1207 } 1208 } else { 1209 // For some reason we can't open /proc/self/stat (for example, running on 1210 // FreeBSD with a Linux emulator, or inside chroot), this should work for 1211 // most cases, so don't abort: 1212 warning("Can't detect initial thread stack location - no /proc/self/stat"); 1213 stack_start = (uintptr_t) &rlim; 1214 } 1215 } 1216 1217 // Now we have a pointer (stack_start) very close to the stack top, the 1218 // next thing to do is to figure out the exact location of stack top. We 1219 // can find out the virtual memory area that contains stack_start by 1220 // reading /proc/self/maps, it should be the last vma in /proc/self/maps, 1221 // and its upper limit is the real stack top. (again, this would fail if 1222 // running inside chroot, because /proc may not exist.) 1223 1224 uintptr_t stack_top; 1225 address low, high; 1226 if (find_vma((address)stack_start, &low, &high)) { 1227 // success, "high" is the true stack top. (ignore "low", because initial 1228 // thread stack grows on demand, its real bottom is high - RLIMIT_STACK.) 1229 stack_top = (uintptr_t)high; 1230 } else { 1231 // failed, likely because /proc/self/maps does not exist 1232 warning("Can't detect initial thread stack location - find_vma failed"); 1233 // best effort: stack_start is normally within a few pages below the real 1234 // stack top, use it as stack top, and reduce stack size so we won't put 1235 // guard page outside stack. 1236 stack_top = stack_start; 1237 stack_size -= 16 * page_size(); 1238 } 1239 1240 // stack_top could be partially down the page so align it 1241 stack_top = align_size_up(stack_top, page_size()); 1242 1243 if (max_size && stack_size > max_size) { 1244 _initial_thread_stack_size = max_size; 1245 } else { 1246 _initial_thread_stack_size = stack_size; 1247 } 1248 1249 _initial_thread_stack_size = align_size_down(_initial_thread_stack_size, page_size()); 1250 _initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size; 1251 } 1252 1253 //////////////////////////////////////////////////////////////////////////////// 1254 // time support 1255 1256 // Time since start-up in seconds to a fine granularity. 1257 // Used by VMSelfDestructTimer and the MemProfiler. 1258 double os::elapsedTime() { 1259 1260 return ((double)os::elapsed_counter()) / os::elapsed_frequency(); // nanosecond resolution 1261 } 1262 1263 jlong os::elapsed_counter() { 1264 return javaTimeNanos() - initial_time_count; 1265 } 1266 1267 jlong os::elapsed_frequency() { 1268 return NANOSECS_PER_SEC; // nanosecond resolution 1269 } 1270 1271 bool os::supports_vtime() { return true; } 1272 bool os::enable_vtime() { return false; } 1273 bool os::vtime_enabled() { return false; } 1274 1275 double os::elapsedVTime() { 1276 struct rusage usage; 1277 int retval = getrusage(RUSAGE_THREAD, &usage); 1278 if (retval == 0) { 1279 return (double) (usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) + (double) (usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) / (1000 * 1000); 1280 } else { 1281 // better than nothing, but not much 1282 return elapsedTime(); 1283 } 1284 } 1285 1286 jlong os::javaTimeMillis() { 1287 timeval time; 1288 int status = gettimeofday(&time, NULL); 1289 assert(status != -1, "linux error"); 1290 return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000); 1291 } 1292 1293 void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) { 1294 timeval time; 1295 int status = gettimeofday(&time, NULL); 1296 assert(status != -1, "linux error"); 1297 seconds = jlong(time.tv_sec); 1298 nanos = jlong(time.tv_usec) * 1000; 1299 } 1300 1301 1302 #ifndef CLOCK_MONOTONIC 1303 #define CLOCK_MONOTONIC (1) 1304 #endif 1305 1306 void os::Linux::clock_init() { 1307 // we do dlopen's in this particular order due to bug in linux 1308 // dynamical loader (see 6348968) leading to crash on exit 1309 void* handle = dlopen("librt.so.1", RTLD_LAZY); 1310 if (handle == NULL) { 1311 handle = dlopen("librt.so", RTLD_LAZY); 1312 } 1313 1314 if (handle) { 1315 int (*clock_getres_func)(clockid_t, struct timespec*) = 1316 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres"); 1317 int (*clock_gettime_func)(clockid_t, struct timespec*) = 1318 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime"); 1319 if (clock_getres_func && clock_gettime_func) { 1320 // See if monotonic clock is supported by the kernel. Note that some 1321 // early implementations simply return kernel jiffies (updated every 1322 // 1/100 or 1/1000 second). It would be bad to use such a low res clock 1323 // for nano time (though the monotonic property is still nice to have). 1324 // It's fixed in newer kernels, however clock_getres() still returns 1325 // 1/HZ. We check if clock_getres() works, but will ignore its reported 1326 // resolution for now. Hopefully as people move to new kernels, this 1327 // won't be a problem. 1328 struct timespec res; 1329 struct timespec tp; 1330 if (clock_getres_func (CLOCK_MONOTONIC, &res) == 0 && 1331 clock_gettime_func(CLOCK_MONOTONIC, &tp) == 0) { 1332 // yes, monotonic clock is supported 1333 _clock_gettime = clock_gettime_func; 1334 return; 1335 } else { 1336 // close librt if there is no monotonic clock 1337 dlclose(handle); 1338 } 1339 } 1340 } 1341 warning("No monotonic clock was available - timed services may " \ 1342 "be adversely affected if the time-of-day clock changes"); 1343 } 1344 1345 #ifndef SYS_clock_getres 1346 #if defined(IA32) || defined(AMD64) 1347 #define SYS_clock_getres IA32_ONLY(266) AMD64_ONLY(229) 1348 #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y) 1349 #else 1350 #warning "SYS_clock_getres not defined for this platform, disabling fast_thread_cpu_time" 1351 #define sys_clock_getres(x,y) -1 1352 #endif 1353 #else 1354 #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y) 1355 #endif 1356 1357 void os::Linux::fast_thread_clock_init() { 1358 if (!UseLinuxPosixThreadCPUClocks) { 1359 return; 1360 } 1361 clockid_t clockid; 1362 struct timespec tp; 1363 int (*pthread_getcpuclockid_func)(pthread_t, clockid_t *) = 1364 (int(*)(pthread_t, clockid_t *)) dlsym(RTLD_DEFAULT, "pthread_getcpuclockid"); 1365 1366 // Switch to using fast clocks for thread cpu time if 1367 // the sys_clock_getres() returns 0 error code. 1368 // Note, that some kernels may support the current thread 1369 // clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks 1370 // returned by the pthread_getcpuclockid(). 1371 // If the fast Posix clocks are supported then the sys_clock_getres() 1372 // must return at least tp.tv_sec == 0 which means a resolution 1373 // better than 1 sec. This is extra check for reliability. 1374 1375 if (pthread_getcpuclockid_func && 1376 pthread_getcpuclockid_func(_main_thread, &clockid) == 0 && 1377 sys_clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) { 1378 _supports_fast_thread_cpu_time = true; 1379 _pthread_getcpuclockid = pthread_getcpuclockid_func; 1380 } 1381 } 1382 1383 jlong os::javaTimeNanos() { 1384 if (os::supports_monotonic_clock()) { 1385 struct timespec tp; 1386 int status = Linux::clock_gettime(CLOCK_MONOTONIC, &tp); 1387 assert(status == 0, "gettime error"); 1388 jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec); 1389 return result; 1390 } else { 1391 timeval time; 1392 int status = gettimeofday(&time, NULL); 1393 assert(status != -1, "linux error"); 1394 jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec); 1395 return 1000 * usecs; 1396 } 1397 } 1398 1399 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { 1400 if (os::supports_monotonic_clock()) { 1401 info_ptr->max_value = ALL_64_BITS; 1402 1403 // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past 1404 info_ptr->may_skip_backward = false; // not subject to resetting or drifting 1405 info_ptr->may_skip_forward = false; // not subject to resetting or drifting 1406 } else { 1407 // gettimeofday - based on time in seconds since the Epoch thus does not wrap 1408 info_ptr->max_value = ALL_64_BITS; 1409 1410 // gettimeofday is a real time clock so it skips 1411 info_ptr->may_skip_backward = true; 1412 info_ptr->may_skip_forward = true; 1413 } 1414 1415 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time 1416 } 1417 1418 // Return the real, user, and system times in seconds from an 1419 // arbitrary fixed point in the past. 1420 bool os::getTimesSecs(double* process_real_time, 1421 double* process_user_time, 1422 double* process_system_time) { 1423 struct tms ticks; 1424 clock_t real_ticks = times(&ticks); 1425 1426 if (real_ticks == (clock_t) (-1)) { 1427 return false; 1428 } else { 1429 double ticks_per_second = (double) clock_tics_per_sec; 1430 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second; 1431 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second; 1432 *process_real_time = ((double) real_ticks) / ticks_per_second; 1433 1434 return true; 1435 } 1436 } 1437 1438 1439 char * os::local_time_string(char *buf, size_t buflen) { 1440 struct tm t; 1441 time_t long_time; 1442 time(&long_time); 1443 localtime_r(&long_time, &t); 1444 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d", 1445 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, 1446 t.tm_hour, t.tm_min, t.tm_sec); 1447 return buf; 1448 } 1449 1450 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) { 1451 return localtime_r(clock, res); 1452 } 1453 1454 //////////////////////////////////////////////////////////////////////////////// 1455 // runtime exit support 1456 1457 // Note: os::shutdown() might be called very early during initialization, or 1458 // called from signal handler. Before adding something to os::shutdown(), make 1459 // sure it is async-safe and can handle partially initialized VM. 1460 void os::shutdown() { 1461 1462 // allow PerfMemory to attempt cleanup of any persistent resources 1463 perfMemory_exit(); 1464 1465 // needs to remove object in file system 1466 AttachListener::abort(); 1467 1468 // flush buffered output, finish log files 1469 ostream_abort(); 1470 1471 // Check for abort hook 1472 abort_hook_t abort_hook = Arguments::abort_hook(); 1473 if (abort_hook != NULL) { 1474 abort_hook(); 1475 } 1476 1477 } 1478 1479 // Note: os::abort() might be called very early during initialization, or 1480 // called from signal handler. Before adding something to os::abort(), make 1481 // sure it is async-safe and can handle partially initialized VM. 1482 void os::abort(bool dump_core) { 1483 abort(dump_core, NULL, NULL); 1484 } 1485 1486 void os::abort(bool dump_core, void* siginfo, void* context) { 1487 os::shutdown(); 1488 if (dump_core) { 1489 #ifndef PRODUCT 1490 fdStream out(defaultStream::output_fd()); 1491 out.print_raw("Current thread is "); 1492 char buf[16]; 1493 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id()); 1494 out.print_raw_cr(buf); 1495 out.print_raw_cr("Dumping core ..."); 1496 #endif 1497 ::abort(); // dump core 1498 } 1499 1500 ::exit(1); 1501 } 1502 1503 // Die immediately, no exit hook, no abort hook, no cleanup. 1504 void os::die() { 1505 // _exit() on LinuxThreads only kills current thread 1506 ::abort(); 1507 } 1508 1509 1510 // This method is a copy of JDK's sysGetLastErrorString 1511 // from src/solaris/hpi/src/system_md.c 1512 1513 size_t os::lasterror(char *buf, size_t len) { 1514 if (errno == 0) return 0; 1515 1516 const char *s = ::strerror(errno); 1517 size_t n = ::strlen(s); 1518 if (n >= len) { 1519 n = len - 1; 1520 } 1521 ::strncpy(buf, s, n); 1522 buf[n] = '\0'; 1523 return n; 1524 } 1525 1526 intx os::current_thread_id() { return (intx)pthread_self(); } 1527 int os::current_process_id() { 1528 1529 // Under the old linux thread library, linux gives each thread 1530 // its own process id. Because of this each thread will return 1531 // a different pid if this method were to return the result 1532 // of getpid(2). Linux provides no api that returns the pid 1533 // of the launcher thread for the vm. This implementation 1534 // returns a unique pid, the pid of the launcher thread 1535 // that starts the vm 'process'. 1536 1537 // Under the NPTL, getpid() returns the same pid as the 1538 // launcher thread rather than a unique pid per thread. 1539 // Use gettid() if you want the old pre NPTL behaviour. 1540 1541 // if you are looking for the result of a call to getpid() that 1542 // returns a unique pid for the calling thread, then look at the 1543 // OSThread::thread_id() method in osThread_linux.hpp file 1544 1545 return (int)(_initial_pid ? _initial_pid : getpid()); 1546 } 1547 1548 // DLL functions 1549 1550 const char* os::dll_file_extension() { return ".so"; } 1551 1552 // This must be hard coded because it's the system's temporary 1553 // directory not the java application's temp directory, ala java.io.tmpdir. 1554 const char* os::get_temp_directory() { return "/tmp"; } 1555 1556 static bool file_exists(const char* filename) { 1557 struct stat statbuf; 1558 if (filename == NULL || strlen(filename) == 0) { 1559 return false; 1560 } 1561 return os::stat(filename, &statbuf) == 0; 1562 } 1563 1564 bool os::dll_build_name(char* buffer, size_t buflen, 1565 const char* pname, const char* fname) { 1566 bool retval = false; 1567 // Copied from libhpi 1568 const size_t pnamelen = pname ? strlen(pname) : 0; 1569 1570 // Return error on buffer overflow. 1571 if (pnamelen + strlen(fname) + 10 > (size_t) buflen) { 1572 return retval; 1573 } 1574 1575 if (pnamelen == 0) { 1576 snprintf(buffer, buflen, "lib%s.so", fname); 1577 retval = true; 1578 } else if (strchr(pname, *os::path_separator()) != NULL) { 1579 int n; 1580 char** pelements = split_path(pname, &n); 1581 if (pelements == NULL) { 1582 return false; 1583 } 1584 for (int i = 0; i < n; i++) { 1585 // Really shouldn't be NULL, but check can't hurt 1586 if (pelements[i] == NULL || strlen(pelements[i]) == 0) { 1587 continue; // skip the empty path values 1588 } 1589 snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname); 1590 if (file_exists(buffer)) { 1591 retval = true; 1592 break; 1593 } 1594 } 1595 // release the storage 1596 for (int i = 0; i < n; i++) { 1597 if (pelements[i] != NULL) { 1598 FREE_C_HEAP_ARRAY(char, pelements[i]); 1599 } 1600 } 1601 if (pelements != NULL) { 1602 FREE_C_HEAP_ARRAY(char*, pelements); 1603 } 1604 } else { 1605 snprintf(buffer, buflen, "%s/lib%s.so", pname, fname); 1606 retval = true; 1607 } 1608 return retval; 1609 } 1610 1611 // check if addr is inside libjvm.so 1612 bool os::address_is_in_vm(address addr) { 1613 static address libjvm_base_addr; 1614 Dl_info dlinfo; 1615 1616 if (libjvm_base_addr == NULL) { 1617 if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) { 1618 libjvm_base_addr = (address)dlinfo.dli_fbase; 1619 } 1620 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm"); 1621 } 1622 1623 if (dladdr((void *)addr, &dlinfo) != 0) { 1624 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true; 1625 } 1626 1627 return false; 1628 } 1629 1630 bool os::dll_address_to_function_name(address addr, char *buf, 1631 int buflen, int *offset) { 1632 // buf is not optional, but offset is optional 1633 assert(buf != NULL, "sanity check"); 1634 1635 Dl_info dlinfo; 1636 1637 if (dladdr((void*)addr, &dlinfo) != 0) { 1638 // see if we have a matching symbol 1639 if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) { 1640 if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) { 1641 jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname); 1642 } 1643 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; 1644 return true; 1645 } 1646 // no matching symbol so try for just file info 1647 if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) { 1648 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), 1649 buf, buflen, offset, dlinfo.dli_fname)) { 1650 return true; 1651 } 1652 } 1653 } 1654 1655 buf[0] = '\0'; 1656 if (offset != NULL) *offset = -1; 1657 return false; 1658 } 1659 1660 struct _address_to_library_name { 1661 address addr; // input : memory address 1662 size_t buflen; // size of fname 1663 char* fname; // output: library name 1664 address base; // library base addr 1665 }; 1666 1667 static int address_to_library_name_callback(struct dl_phdr_info *info, 1668 size_t size, void *data) { 1669 int i; 1670 bool found = false; 1671 address libbase = NULL; 1672 struct _address_to_library_name * d = (struct _address_to_library_name *)data; 1673 1674 // iterate through all loadable segments 1675 for (i = 0; i < info->dlpi_phnum; i++) { 1676 address segbase = (address)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr); 1677 if (info->dlpi_phdr[i].p_type == PT_LOAD) { 1678 // base address of a library is the lowest address of its loaded 1679 // segments. 1680 if (libbase == NULL || libbase > segbase) { 1681 libbase = segbase; 1682 } 1683 // see if 'addr' is within current segment 1684 if (segbase <= d->addr && 1685 d->addr < segbase + info->dlpi_phdr[i].p_memsz) { 1686 found = true; 1687 } 1688 } 1689 } 1690 1691 // dlpi_name is NULL or empty if the ELF file is executable, return 0 1692 // so dll_address_to_library_name() can fall through to use dladdr() which 1693 // can figure out executable name from argv[0]. 1694 if (found && info->dlpi_name && info->dlpi_name[0]) { 1695 d->base = libbase; 1696 if (d->fname) { 1697 jio_snprintf(d->fname, d->buflen, "%s", info->dlpi_name); 1698 } 1699 return 1; 1700 } 1701 return 0; 1702 } 1703 1704 bool os::dll_address_to_library_name(address addr, char* buf, 1705 int buflen, int* offset) { 1706 // buf is not optional, but offset is optional 1707 assert(buf != NULL, "sanity check"); 1708 1709 Dl_info dlinfo; 1710 struct _address_to_library_name data; 1711 1712 // There is a bug in old glibc dladdr() implementation that it could resolve 1713 // to wrong library name if the .so file has a base address != NULL. Here 1714 // we iterate through the program headers of all loaded libraries to find 1715 // out which library 'addr' really belongs to. This workaround can be 1716 // removed once the minimum requirement for glibc is moved to 2.3.x. 1717 data.addr = addr; 1718 data.fname = buf; 1719 data.buflen = buflen; 1720 data.base = NULL; 1721 int rslt = dl_iterate_phdr(address_to_library_name_callback, (void *)&data); 1722 1723 if (rslt) { 1724 // buf already contains library name 1725 if (offset) *offset = addr - data.base; 1726 return true; 1727 } 1728 if (dladdr((void*)addr, &dlinfo) != 0) { 1729 if (dlinfo.dli_fname != NULL) { 1730 jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); 1731 } 1732 if (dlinfo.dli_fbase != NULL && offset != NULL) { 1733 *offset = addr - (address)dlinfo.dli_fbase; 1734 } 1735 return true; 1736 } 1737 1738 buf[0] = '\0'; 1739 if (offset) *offset = -1; 1740 return false; 1741 } 1742 1743 // Loads .dll/.so and 1744 // in case of error it checks if .dll/.so was built for the 1745 // same architecture as Hotspot is running on 1746 1747 1748 // Remember the stack's state. The Linux dynamic linker will change 1749 // the stack to 'executable' at most once, so we must safepoint only once. 1750 bool os::Linux::_stack_is_executable = false; 1751 1752 // VM operation that loads a library. This is necessary if stack protection 1753 // of the Java stacks can be lost during loading the library. If we 1754 // do not stop the Java threads, they can stack overflow before the stacks 1755 // are protected again. 1756 class VM_LinuxDllLoad: public VM_Operation { 1757 private: 1758 const char *_filename; 1759 char *_ebuf; 1760 int _ebuflen; 1761 void *_lib; 1762 public: 1763 VM_LinuxDllLoad(const char *fn, char *ebuf, int ebuflen) : 1764 _filename(fn), _ebuf(ebuf), _ebuflen(ebuflen), _lib(NULL) {} 1765 VMOp_Type type() const { return VMOp_LinuxDllLoad; } 1766 void doit() { 1767 _lib = os::Linux::dll_load_in_vmthread(_filename, _ebuf, _ebuflen); 1768 os::Linux::_stack_is_executable = true; 1769 } 1770 void* loaded_library() { return _lib; } 1771 }; 1772 1773 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) { 1774 void * result = NULL; 1775 bool load_attempted = false; 1776 1777 // Check whether the library to load might change execution rights 1778 // of the stack. If they are changed, the protection of the stack 1779 // guard pages will be lost. We need a safepoint to fix this. 1780 // 1781 // See Linux man page execstack(8) for more info. 1782 if (os::uses_stack_guard_pages() && !os::Linux::_stack_is_executable) { 1783 ElfFile ef(filename); 1784 if (!ef.specifies_noexecstack()) { 1785 if (!is_init_completed()) { 1786 os::Linux::_stack_is_executable = true; 1787 // This is OK - No Java threads have been created yet, and hence no 1788 // stack guard pages to fix. 1789 // 1790 // This should happen only when you are building JDK7 using a very 1791 // old version of JDK6 (e.g., with JPRT) and running test_gamma. 1792 // 1793 // Dynamic loader will make all stacks executable after 1794 // this function returns, and will not do that again. 1795 assert(Threads::first() == NULL, "no Java threads should exist yet."); 1796 } else { 1797 warning("You have loaded library %s which might have disabled stack guard. " 1798 "The VM will try to fix the stack guard now.\n" 1799 "It's highly recommended that you fix the library with " 1800 "'execstack -c <libfile>', or link it with '-z noexecstack'.", 1801 filename); 1802 1803 assert(Thread::current()->is_Java_thread(), "must be Java thread"); 1804 JavaThread *jt = JavaThread::current(); 1805 if (jt->thread_state() != _thread_in_native) { 1806 // This happens when a compiler thread tries to load a hsdis-<arch>.so file 1807 // that requires ExecStack. Cannot enter safe point. Let's give up. 1808 warning("Unable to fix stack guard. Giving up."); 1809 } else { 1810 if (!LoadExecStackDllInVMThread) { 1811 // This is for the case where the DLL has an static 1812 // constructor function that executes JNI code. We cannot 1813 // load such DLLs in the VMThread. 1814 result = os::Linux::dlopen_helper(filename, ebuf, ebuflen); 1815 } 1816 1817 ThreadInVMfromNative tiv(jt); 1818 debug_only(VMNativeEntryWrapper vew;) 1819 1820 VM_LinuxDllLoad op(filename, ebuf, ebuflen); 1821 VMThread::execute(&op); 1822 if (LoadExecStackDllInVMThread) { 1823 result = op.loaded_library(); 1824 } 1825 load_attempted = true; 1826 } 1827 } 1828 } 1829 } 1830 1831 if (!load_attempted) { 1832 result = os::Linux::dlopen_helper(filename, ebuf, ebuflen); 1833 } 1834 1835 if (result != NULL) { 1836 // Successful loading 1837 return result; 1838 } 1839 1840 Elf32_Ehdr elf_head; 1841 int diag_msg_max_length=ebuflen-strlen(ebuf); 1842 char* diag_msg_buf=ebuf+strlen(ebuf); 1843 1844 if (diag_msg_max_length==0) { 1845 // No more space in ebuf for additional diagnostics message 1846 return NULL; 1847 } 1848 1849 1850 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK); 1851 1852 if (file_descriptor < 0) { 1853 // Can't open library, report dlerror() message 1854 return NULL; 1855 } 1856 1857 bool failed_to_read_elf_head= 1858 (sizeof(elf_head)!= 1859 (::read(file_descriptor, &elf_head,sizeof(elf_head)))); 1860 1861 ::close(file_descriptor); 1862 if (failed_to_read_elf_head) { 1863 // file i/o error - report dlerror() msg 1864 return NULL; 1865 } 1866 1867 typedef struct { 1868 Elf32_Half code; // Actual value as defined in elf.h 1869 Elf32_Half compat_class; // Compatibility of archs at VM's sense 1870 char elf_class; // 32 or 64 bit 1871 char endianess; // MSB or LSB 1872 char* name; // String representation 1873 } arch_t; 1874 1875 #ifndef EM_486 1876 #define EM_486 6 /* Intel 80486 */ 1877 #endif 1878 #ifndef EM_AARCH64 1879 #define EM_AARCH64 183 /* ARM AARCH64 */ 1880 #endif 1881 1882 static const arch_t arch_array[]={ 1883 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 1884 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 1885 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"}, 1886 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"}, 1887 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 1888 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 1889 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"}, 1890 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"}, 1891 #if defined(VM_LITTLE_ENDIAN) 1892 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2LSB, (char*)"Power PC 64"}, 1893 #else 1894 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"}, 1895 #endif 1896 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"}, 1897 {EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"}, 1898 {EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"}, 1899 {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"}, 1900 {EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"}, 1901 {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"}, 1902 {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}, 1903 {EM_AARCH64, EM_AARCH64, ELFCLASS64, ELFDATA2LSB, (char*)"AARCH64"}, 1904 }; 1905 1906 #if (defined IA32) 1907 static Elf32_Half running_arch_code=EM_386; 1908 #elif (defined AMD64) 1909 static Elf32_Half running_arch_code=EM_X86_64; 1910 #elif (defined IA64) 1911 static Elf32_Half running_arch_code=EM_IA_64; 1912 #elif (defined __sparc) && (defined _LP64) 1913 static Elf32_Half running_arch_code=EM_SPARCV9; 1914 #elif (defined __sparc) && (!defined _LP64) 1915 static Elf32_Half running_arch_code=EM_SPARC; 1916 #elif (defined __powerpc64__) 1917 static Elf32_Half running_arch_code=EM_PPC64; 1918 #elif (defined __powerpc__) 1919 static Elf32_Half running_arch_code=EM_PPC; 1920 #elif (defined ARM) 1921 static Elf32_Half running_arch_code=EM_ARM; 1922 #elif (defined S390) 1923 static Elf32_Half running_arch_code=EM_S390; 1924 #elif (defined ALPHA) 1925 static Elf32_Half running_arch_code=EM_ALPHA; 1926 #elif (defined MIPSEL) 1927 static Elf32_Half running_arch_code=EM_MIPS_RS3_LE; 1928 #elif (defined PARISC) 1929 static Elf32_Half running_arch_code=EM_PARISC; 1930 #elif (defined MIPS) 1931 static Elf32_Half running_arch_code=EM_MIPS; 1932 #elif (defined M68K) 1933 static Elf32_Half running_arch_code=EM_68K; 1934 #elif (defined AARCH64) 1935 static Elf32_Half running_arch_code=EM_AARCH64; 1936 #else 1937 #error Method os::dll_load requires that one of following is defined:\ 1938 IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K, AARCH64 1939 #endif 1940 1941 // Identify compatability class for VM's architecture and library's architecture 1942 // Obtain string descriptions for architectures 1943 1944 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL}; 1945 int running_arch_index=-1; 1946 1947 for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) { 1948 if (running_arch_code == arch_array[i].code) { 1949 running_arch_index = i; 1950 } 1951 if (lib_arch.code == arch_array[i].code) { 1952 lib_arch.compat_class = arch_array[i].compat_class; 1953 lib_arch.name = arch_array[i].name; 1954 } 1955 } 1956 1957 assert(running_arch_index != -1, 1958 "Didn't find running architecture code (running_arch_code) in arch_array"); 1959 if (running_arch_index == -1) { 1960 // Even though running architecture detection failed 1961 // we may still continue with reporting dlerror() message 1962 return NULL; 1963 } 1964 1965 if (lib_arch.endianess != arch_array[running_arch_index].endianess) { 1966 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)"); 1967 return NULL; 1968 } 1969 1970 #ifndef S390 1971 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) { 1972 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)"); 1973 return NULL; 1974 } 1975 #endif // !S390 1976 1977 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) { 1978 if (lib_arch.name!=NULL) { 1979 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 1980 " (Possible cause: can't load %s-bit .so on a %s-bit platform)", 1981 lib_arch.name, arch_array[running_arch_index].name); 1982 } else { 1983 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 1984 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)", 1985 lib_arch.code, 1986 arch_array[running_arch_index].name); 1987 } 1988 } 1989 1990 return NULL; 1991 } 1992 1993 void * os::Linux::dlopen_helper(const char *filename, char *ebuf, 1994 int ebuflen) { 1995 void * result = ::dlopen(filename, RTLD_LAZY); 1996 if (result == NULL) { 1997 ::strncpy(ebuf, ::dlerror(), ebuflen - 1); 1998 ebuf[ebuflen-1] = '\0'; 1999 } 2000 return result; 2001 } 2002 2003 void * os::Linux::dll_load_in_vmthread(const char *filename, char *ebuf, 2004 int ebuflen) { 2005 void * result = NULL; 2006 if (LoadExecStackDllInVMThread) { 2007 result = dlopen_helper(filename, ebuf, ebuflen); 2008 } 2009 2010 // Since 7019808, libjvm.so is linked with -noexecstack. If the VM loads a 2011 // library that requires an executable stack, or which does not have this 2012 // stack attribute set, dlopen changes the stack attribute to executable. The 2013 // read protection of the guard pages gets lost. 2014 // 2015 // Need to check _stack_is_executable again as multiple VM_LinuxDllLoad 2016 // may have been queued at the same time. 2017 2018 if (!_stack_is_executable) { 2019 JavaThread *jt = Threads::first(); 2020 2021 while (jt) { 2022 if (!jt->stack_guard_zone_unused() && // Stack not yet fully initialized 2023 jt->stack_yellow_zone_enabled()) { // No pending stack overflow exceptions 2024 if (!os::guard_memory((char *) jt->stack_red_zone_base() - jt->stack_red_zone_size(), 2025 jt->stack_yellow_zone_size() + jt->stack_red_zone_size())) { 2026 warning("Attempt to reguard stack yellow zone failed."); 2027 } 2028 } 2029 jt = jt->next(); 2030 } 2031 } 2032 2033 return result; 2034 } 2035 2036 void* os::dll_lookup(void* handle, const char* name) { 2037 void* res = dlsym(handle, name); 2038 return res; 2039 } 2040 2041 void* os::get_default_process_handle() { 2042 return (void*)::dlopen(NULL, RTLD_LAZY); 2043 } 2044 2045 static bool _print_ascii_file(const char* filename, outputStream* st) { 2046 int fd = ::open(filename, O_RDONLY); 2047 if (fd == -1) { 2048 return false; 2049 } 2050 2051 char buf[32]; 2052 int bytes; 2053 while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) { 2054 st->print_raw(buf, bytes); 2055 } 2056 2057 ::close(fd); 2058 2059 return true; 2060 } 2061 2062 void os::print_dll_info(outputStream *st) { 2063 st->print_cr("Dynamic libraries:"); 2064 2065 char fname[32]; 2066 pid_t pid = os::Linux::gettid(); 2067 2068 jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid); 2069 2070 if (!_print_ascii_file(fname, st)) { 2071 st->print("Can not get library information for pid = %d\n", pid); 2072 } 2073 } 2074 2075 int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) { 2076 FILE *procmapsFile = NULL; 2077 2078 // Open the procfs maps file for the current process 2079 if ((procmapsFile = fopen("/proc/self/maps", "r")) != NULL) { 2080 // Allocate PATH_MAX for file name plus a reasonable size for other fields. 2081 char line[PATH_MAX + 100]; 2082 2083 // Read line by line from 'file' 2084 while (fgets(line, sizeof(line), procmapsFile) != NULL) { 2085 u8 base, top, offset, inode; 2086 char permissions[5]; 2087 char device[6]; 2088 char name[PATH_MAX + 1]; 2089 2090 // Parse fields from line 2091 sscanf(line, "%lx-%lx %4s %lx %5s %ld %s", &base, &top, permissions, &offset, device, &inode, name); 2092 2093 // Filter by device id '00:00' so that we only get file system mapped files. 2094 if (strcmp(device, "00:00") != 0) { 2095 2096 // Call callback with the fields of interest 2097 if(callback(name, (address)base, (address)top, param)) { 2098 // Oops abort, callback aborted 2099 fclose(procmapsFile); 2100 return 1; 2101 } 2102 } 2103 } 2104 fclose(procmapsFile); 2105 } 2106 return 0; 2107 } 2108 2109 void os::print_os_info_brief(outputStream* st) { 2110 os::Linux::print_distro_info(st); 2111 2112 os::Posix::print_uname_info(st); 2113 2114 os::Linux::print_libversion_info(st); 2115 2116 } 2117 2118 void os::print_os_info(outputStream* st) { 2119 st->print("OS:"); 2120 2121 os::Linux::print_distro_info(st); 2122 2123 os::Posix::print_uname_info(st); 2124 2125 // Print warning if unsafe chroot environment detected 2126 if (unsafe_chroot_detected) { 2127 st->print("WARNING!! "); 2128 st->print_cr("%s", unstable_chroot_error); 2129 } 2130 2131 os::Linux::print_libversion_info(st); 2132 2133 os::Posix::print_rlimit_info(st); 2134 2135 os::Posix::print_load_average(st); 2136 2137 os::Linux::print_full_memory_info(st); 2138 } 2139 2140 // Try to identify popular distros. 2141 // Most Linux distributions have a /etc/XXX-release file, which contains 2142 // the OS version string. Newer Linux distributions have a /etc/lsb-release 2143 // file that also contains the OS version string. Some have more than one 2144 // /etc/XXX-release file (e.g. Mandrake has both /etc/mandrake-release and 2145 // /etc/redhat-release.), so the order is important. 2146 // Any Linux that is based on Redhat (i.e. Oracle, Mandrake, Sun JDS...) have 2147 // their own specific XXX-release file as well as a redhat-release file. 2148 // Because of this the XXX-release file needs to be searched for before the 2149 // redhat-release file. 2150 // Since Red Hat has a lsb-release file that is not very descriptive the 2151 // search for redhat-release needs to be before lsb-release. 2152 // Since the lsb-release file is the new standard it needs to be searched 2153 // before the older style release files. 2154 // Searching system-release (Red Hat) and os-release (other Linuxes) are a 2155 // next to last resort. The os-release file is a new standard that contains 2156 // distribution information and the system-release file seems to be an old 2157 // standard that has been replaced by the lsb-release and os-release files. 2158 // Searching for the debian_version file is the last resort. It contains 2159 // an informative string like "6.0.6" or "wheezy/sid". Because of this 2160 // "Debian " is printed before the contents of the debian_version file. 2161 void os::Linux::print_distro_info(outputStream* st) { 2162 if (!_print_ascii_file("/etc/oracle-release", st) && 2163 !_print_ascii_file("/etc/mandriva-release", st) && 2164 !_print_ascii_file("/etc/mandrake-release", st) && 2165 !_print_ascii_file("/etc/sun-release", st) && 2166 !_print_ascii_file("/etc/redhat-release", st) && 2167 !_print_ascii_file("/etc/lsb-release", st) && 2168 !_print_ascii_file("/etc/SuSE-release", st) && 2169 !_print_ascii_file("/etc/turbolinux-release", st) && 2170 !_print_ascii_file("/etc/gentoo-release", st) && 2171 !_print_ascii_file("/etc/ltib-release", st) && 2172 !_print_ascii_file("/etc/angstrom-version", st) && 2173 !_print_ascii_file("/etc/system-release", st) && 2174 !_print_ascii_file("/etc/os-release", st)) { 2175 2176 if (file_exists("/etc/debian_version")) { 2177 st->print("Debian "); 2178 _print_ascii_file("/etc/debian_version", st); 2179 } else { 2180 st->print("Linux"); 2181 } 2182 } 2183 st->cr(); 2184 } 2185 2186 void os::Linux::print_libversion_info(outputStream* st) { 2187 // libc, pthread 2188 st->print("libc:"); 2189 st->print("%s ", os::Linux::glibc_version()); 2190 st->print("%s ", os::Linux::libpthread_version()); 2191 if (os::Linux::is_LinuxThreads()) { 2192 st->print("(%s stack)", os::Linux::is_floating_stack() ? "floating" : "fixed"); 2193 } 2194 st->cr(); 2195 } 2196 2197 void os::Linux::print_full_memory_info(outputStream* st) { 2198 st->print("\n/proc/meminfo:\n"); 2199 _print_ascii_file("/proc/meminfo", st); 2200 st->cr(); 2201 } 2202 2203 void os::print_memory_info(outputStream* st) { 2204 2205 st->print("Memory:"); 2206 st->print(" %dk page", os::vm_page_size()>>10); 2207 2208 // values in struct sysinfo are "unsigned long" 2209 struct sysinfo si; 2210 sysinfo(&si); 2211 2212 st->print(", physical " UINT64_FORMAT "k", 2213 os::physical_memory() >> 10); 2214 st->print("(" UINT64_FORMAT "k free)", 2215 os::available_memory() >> 10); 2216 st->print(", swap " UINT64_FORMAT "k", 2217 ((jlong)si.totalswap * si.mem_unit) >> 10); 2218 st->print("(" UINT64_FORMAT "k free)", 2219 ((jlong)si.freeswap * si.mem_unit) >> 10); 2220 st->cr(); 2221 } 2222 2223 void os::pd_print_cpu_info(outputStream* st) { 2224 st->print("\n/proc/cpuinfo:\n"); 2225 if (!_print_ascii_file("/proc/cpuinfo", st)) { 2226 st->print(" <Not Available>"); 2227 } 2228 st->cr(); 2229 } 2230 2231 void os::print_siginfo(outputStream* st, void* siginfo) { 2232 const siginfo_t* si = (const siginfo_t*)siginfo; 2233 2234 os::Posix::print_siginfo_brief(st, si); 2235 #if INCLUDE_CDS 2236 if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) && 2237 UseSharedSpaces) { 2238 FileMapInfo* mapinfo = FileMapInfo::current_info(); 2239 if (mapinfo->is_in_shared_space(si->si_addr)) { 2240 st->print("\n\nError accessing class data sharing archive." \ 2241 " Mapped file inaccessible during execution, " \ 2242 " possible disk/network problem."); 2243 } 2244 } 2245 #endif 2246 st->cr(); 2247 } 2248 2249 2250 static void print_signal_handler(outputStream* st, int sig, 2251 char* buf, size_t buflen); 2252 2253 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) { 2254 st->print_cr("Signal Handlers:"); 2255 print_signal_handler(st, SIGSEGV, buf, buflen); 2256 print_signal_handler(st, SIGBUS , buf, buflen); 2257 print_signal_handler(st, SIGFPE , buf, buflen); 2258 print_signal_handler(st, SIGPIPE, buf, buflen); 2259 print_signal_handler(st, SIGXFSZ, buf, buflen); 2260 print_signal_handler(st, SIGILL , buf, buflen); 2261 print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen); 2262 print_signal_handler(st, SR_signum, buf, buflen); 2263 print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen); 2264 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen); 2265 print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen); 2266 print_signal_handler(st, BREAK_SIGNAL, buf, buflen); 2267 #if defined(PPC64) 2268 print_signal_handler(st, SIGTRAP, buf, buflen); 2269 #endif 2270 } 2271 2272 static char saved_jvm_path[MAXPATHLEN] = {0}; 2273 2274 // Find the full path to the current module, libjvm.so 2275 void os::jvm_path(char *buf, jint buflen) { 2276 // Error checking. 2277 if (buflen < MAXPATHLEN) { 2278 assert(false, "must use a large-enough buffer"); 2279 buf[0] = '\0'; 2280 return; 2281 } 2282 // Lazy resolve the path to current module. 2283 if (saved_jvm_path[0] != 0) { 2284 strcpy(buf, saved_jvm_path); 2285 return; 2286 } 2287 2288 char dli_fname[MAXPATHLEN]; 2289 bool ret = dll_address_to_library_name( 2290 CAST_FROM_FN_PTR(address, os::jvm_path), 2291 dli_fname, sizeof(dli_fname), NULL); 2292 assert(ret, "cannot locate libjvm"); 2293 char *rp = NULL; 2294 if (ret && dli_fname[0] != '\0') { 2295 rp = realpath(dli_fname, buf); 2296 } 2297 if (rp == NULL) { 2298 return; 2299 } 2300 2301 if (Arguments::sun_java_launcher_is_altjvm()) { 2302 // Support for the java launcher's '-XXaltjvm=<path>' option. Typical 2303 // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so". 2304 // If "/jre/lib/" appears at the right place in the string, then 2305 // assume we are installed in a JDK and we're done. Otherwise, check 2306 // for a JAVA_HOME environment variable and fix up the path so it 2307 // looks like libjvm.so is installed there (append a fake suffix 2308 // hotspot/libjvm.so). 2309 const char *p = buf + strlen(buf) - 1; 2310 for (int count = 0; p > buf && count < 5; ++count) { 2311 for (--p; p > buf && *p != '/'; --p) 2312 /* empty */ ; 2313 } 2314 2315 if (strncmp(p, "/jre/lib/", 9) != 0) { 2316 // Look for JAVA_HOME in the environment. 2317 char* java_home_var = ::getenv("JAVA_HOME"); 2318 if (java_home_var != NULL && java_home_var[0] != 0) { 2319 char* jrelib_p; 2320 int len; 2321 2322 // Check the current module name "libjvm.so". 2323 p = strrchr(buf, '/'); 2324 if (p == NULL) { 2325 return; 2326 } 2327 assert(strstr(p, "/libjvm") == p, "invalid library name"); 2328 2329 rp = realpath(java_home_var, buf); 2330 if (rp == NULL) { 2331 return; 2332 } 2333 2334 // determine if this is a legacy image or modules image 2335 // modules image doesn't have "jre" subdirectory 2336 len = strlen(buf); 2337 assert(len < buflen, "Ran out of buffer room"); 2338 jrelib_p = buf + len; 2339 snprintf(jrelib_p, buflen-len, "/jre/lib/%s", cpu_arch); 2340 if (0 != access(buf, F_OK)) { 2341 snprintf(jrelib_p, buflen-len, "/lib/%s", cpu_arch); 2342 } 2343 2344 if (0 == access(buf, F_OK)) { 2345 // Use current module name "libjvm.so" 2346 len = strlen(buf); 2347 snprintf(buf + len, buflen-len, "/hotspot/libjvm.so"); 2348 } else { 2349 // Go back to path of .so 2350 rp = realpath(dli_fname, buf); 2351 if (rp == NULL) { 2352 return; 2353 } 2354 } 2355 } 2356 } 2357 } 2358 2359 strncpy(saved_jvm_path, buf, MAXPATHLEN); 2360 saved_jvm_path[MAXPATHLEN - 1] = '\0'; 2361 } 2362 2363 void os::print_jni_name_prefix_on(outputStream* st, int args_size) { 2364 // no prefix required, not even "_" 2365 } 2366 2367 void os::print_jni_name_suffix_on(outputStream* st, int args_size) { 2368 // no suffix required 2369 } 2370 2371 //////////////////////////////////////////////////////////////////////////////// 2372 // sun.misc.Signal support 2373 2374 static volatile jint sigint_count = 0; 2375 2376 static void UserHandler(int sig, void *siginfo, void *context) { 2377 // 4511530 - sem_post is serialized and handled by the manager thread. When 2378 // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We 2379 // don't want to flood the manager thread with sem_post requests. 2380 if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1) { 2381 return; 2382 } 2383 2384 // Ctrl-C is pressed during error reporting, likely because the error 2385 // handler fails to abort. Let VM die immediately. 2386 if (sig == SIGINT && is_error_reported()) { 2387 os::die(); 2388 } 2389 2390 os::signal_notify(sig); 2391 } 2392 2393 void* os::user_handler() { 2394 return CAST_FROM_FN_PTR(void*, UserHandler); 2395 } 2396 2397 struct timespec PosixSemaphore::create_timespec(unsigned int sec, int nsec) { 2398 struct timespec ts; 2399 // Semaphore's are always associated with CLOCK_REALTIME 2400 os::Linux::clock_gettime(CLOCK_REALTIME, &ts); 2401 // see unpackTime for discussion on overflow checking 2402 if (sec >= MAX_SECS) { 2403 ts.tv_sec += MAX_SECS; 2404 ts.tv_nsec = 0; 2405 } else { 2406 ts.tv_sec += sec; 2407 ts.tv_nsec += nsec; 2408 if (ts.tv_nsec >= NANOSECS_PER_SEC) { 2409 ts.tv_nsec -= NANOSECS_PER_SEC; 2410 ++ts.tv_sec; // note: this must be <= max_secs 2411 } 2412 } 2413 2414 return ts; 2415 } 2416 2417 extern "C" { 2418 typedef void (*sa_handler_t)(int); 2419 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *); 2420 } 2421 2422 void* os::signal(int signal_number, void* handler) { 2423 struct sigaction sigAct, oldSigAct; 2424 2425 sigfillset(&(sigAct.sa_mask)); 2426 sigAct.sa_flags = SA_RESTART|SA_SIGINFO; 2427 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler); 2428 2429 if (sigaction(signal_number, &sigAct, &oldSigAct)) { 2430 // -1 means registration failed 2431 return (void *)-1; 2432 } 2433 2434 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler); 2435 } 2436 2437 void os::signal_raise(int signal_number) { 2438 ::raise(signal_number); 2439 } 2440 2441 // The following code is moved from os.cpp for making this 2442 // code platform specific, which it is by its very nature. 2443 2444 // Will be modified when max signal is changed to be dynamic 2445 int os::sigexitnum_pd() { 2446 return NSIG; 2447 } 2448 2449 // a counter for each possible signal value 2450 static volatile jint pending_signals[NSIG+1] = { 0 }; 2451 2452 // Linux(POSIX) specific hand shaking semaphore. 2453 static sem_t sig_sem; 2454 static PosixSemaphore sr_semaphore; 2455 2456 void os::signal_init_pd() { 2457 // Initialize signal structures 2458 ::memset((void*)pending_signals, 0, sizeof(pending_signals)); 2459 2460 // Initialize signal semaphore 2461 ::sem_init(&sig_sem, 0, 0); 2462 } 2463 2464 void os::signal_notify(int sig) { 2465 Atomic::inc(&pending_signals[sig]); 2466 ::sem_post(&sig_sem); 2467 } 2468 2469 static int check_pending_signals(bool wait) { 2470 Atomic::store(0, &sigint_count); 2471 for (;;) { 2472 for (int i = 0; i < NSIG + 1; i++) { 2473 jint n = pending_signals[i]; 2474 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) { 2475 return i; 2476 } 2477 } 2478 if (!wait) { 2479 return -1; 2480 } 2481 JavaThread *thread = JavaThread::current(); 2482 ThreadBlockInVM tbivm(thread); 2483 2484 bool threadIsSuspended; 2485 do { 2486 thread->set_suspend_equivalent(); 2487 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 2488 ::sem_wait(&sig_sem); 2489 2490 // were we externally suspended while we were waiting? 2491 threadIsSuspended = thread->handle_special_suspend_equivalent_condition(); 2492 if (threadIsSuspended) { 2493 // The semaphore has been incremented, but while we were waiting 2494 // another thread suspended us. We don't want to continue running 2495 // while suspended because that would surprise the thread that 2496 // suspended us. 2497 ::sem_post(&sig_sem); 2498 2499 thread->java_suspend_self(); 2500 } 2501 } while (threadIsSuspended); 2502 } 2503 } 2504 2505 int os::signal_lookup() { 2506 return check_pending_signals(false); 2507 } 2508 2509 int os::signal_wait() { 2510 return check_pending_signals(true); 2511 } 2512 2513 //////////////////////////////////////////////////////////////////////////////// 2514 // Virtual Memory 2515 2516 int os::vm_page_size() { 2517 // Seems redundant as all get out 2518 assert(os::Linux::page_size() != -1, "must call os::init"); 2519 return os::Linux::page_size(); 2520 } 2521 2522 // Solaris allocates memory by pages. 2523 int os::vm_allocation_granularity() { 2524 assert(os::Linux::page_size() != -1, "must call os::init"); 2525 return os::Linux::page_size(); 2526 } 2527 2528 // Rationale behind this function: 2529 // current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable 2530 // mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get 2531 // samples for JITted code. Here we create private executable mapping over the code cache 2532 // and then we can use standard (well, almost, as mapping can change) way to provide 2533 // info for the reporting script by storing timestamp and location of symbol 2534 void linux_wrap_code(char* base, size_t size) { 2535 static volatile jint cnt = 0; 2536 2537 if (!UseOprofile) { 2538 return; 2539 } 2540 2541 char buf[PATH_MAX+1]; 2542 int num = Atomic::add(1, &cnt); 2543 2544 snprintf(buf, sizeof(buf), "%s/hs-vm-%d-%d", 2545 os::get_temp_directory(), os::current_process_id(), num); 2546 unlink(buf); 2547 2548 int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU); 2549 2550 if (fd != -1) { 2551 off_t rv = ::lseek(fd, size-2, SEEK_SET); 2552 if (rv != (off_t)-1) { 2553 if (::write(fd, "", 1) == 1) { 2554 mmap(base, size, 2555 PROT_READ|PROT_WRITE|PROT_EXEC, 2556 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0); 2557 } 2558 } 2559 ::close(fd); 2560 unlink(buf); 2561 } 2562 } 2563 2564 static bool recoverable_mmap_error(int err) { 2565 // See if the error is one we can let the caller handle. This 2566 // list of errno values comes from JBS-6843484. I can't find a 2567 // Linux man page that documents this specific set of errno 2568 // values so while this list currently matches Solaris, it may 2569 // change as we gain experience with this failure mode. 2570 switch (err) { 2571 case EBADF: 2572 case EINVAL: 2573 case ENOTSUP: 2574 // let the caller deal with these errors 2575 return true; 2576 2577 default: 2578 // Any remaining errors on this OS can cause our reserved mapping 2579 // to be lost. That can cause confusion where different data 2580 // structures think they have the same memory mapped. The worst 2581 // scenario is if both the VM and a library think they have the 2582 // same memory mapped. 2583 return false; 2584 } 2585 } 2586 2587 static void warn_fail_commit_memory(char* addr, size_t size, bool exec, 2588 int err) { 2589 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT 2590 ", %d) failed; error='%s' (errno=%d)", addr, size, exec, 2591 strerror(err), err); 2592 } 2593 2594 static void warn_fail_commit_memory(char* addr, size_t size, 2595 size_t alignment_hint, bool exec, 2596 int err) { 2597 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT 2598 ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", addr, size, 2599 alignment_hint, exec, strerror(err), err); 2600 } 2601 2602 // NOTE: Linux kernel does not really reserve the pages for us. 2603 // All it does is to check if there are enough free pages 2604 // left at the time of mmap(). This could be a potential 2605 // problem. 2606 int os::Linux::commit_memory_impl(char* addr, size_t size, bool exec) { 2607 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; 2608 uintptr_t res = (uintptr_t) ::mmap(addr, size, prot, 2609 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0); 2610 if (res != (uintptr_t) MAP_FAILED) { 2611 if (UseNUMAInterleaving) { 2612 numa_make_global(addr, size); 2613 } 2614 return 0; 2615 } 2616 2617 int err = errno; // save errno from mmap() call above 2618 2619 if (!recoverable_mmap_error(err)) { 2620 warn_fail_commit_memory(addr, size, exec, err); 2621 vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "committing reserved memory."); 2622 } 2623 2624 return err; 2625 } 2626 2627 bool os::pd_commit_memory(char* addr, size_t size, bool exec) { 2628 return os::Linux::commit_memory_impl(addr, size, exec) == 0; 2629 } 2630 2631 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec, 2632 const char* mesg) { 2633 assert(mesg != NULL, "mesg must be specified"); 2634 int err = os::Linux::commit_memory_impl(addr, size, exec); 2635 if (err != 0) { 2636 // the caller wants all commit errors to exit with the specified mesg: 2637 warn_fail_commit_memory(addr, size, exec, err); 2638 vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg); 2639 } 2640 } 2641 2642 // Define MAP_HUGETLB here so we can build HotSpot on old systems. 2643 #ifndef MAP_HUGETLB 2644 #define MAP_HUGETLB 0x40000 2645 #endif 2646 2647 // Define MADV_HUGEPAGE here so we can build HotSpot on old systems. 2648 #ifndef MADV_HUGEPAGE 2649 #define MADV_HUGEPAGE 14 2650 #endif 2651 2652 int os::Linux::commit_memory_impl(char* addr, size_t size, 2653 size_t alignment_hint, bool exec) { 2654 int err = os::Linux::commit_memory_impl(addr, size, exec); 2655 if (err == 0) { 2656 realign_memory(addr, size, alignment_hint); 2657 } 2658 return err; 2659 } 2660 2661 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint, 2662 bool exec) { 2663 return os::Linux::commit_memory_impl(addr, size, alignment_hint, exec) == 0; 2664 } 2665 2666 void os::pd_commit_memory_or_exit(char* addr, size_t size, 2667 size_t alignment_hint, bool exec, 2668 const char* mesg) { 2669 assert(mesg != NULL, "mesg must be specified"); 2670 int err = os::Linux::commit_memory_impl(addr, size, alignment_hint, exec); 2671 if (err != 0) { 2672 // the caller wants all commit errors to exit with the specified mesg: 2673 warn_fail_commit_memory(addr, size, alignment_hint, exec, err); 2674 vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg); 2675 } 2676 } 2677 2678 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) { 2679 if (UseTransparentHugePages && alignment_hint > (size_t)vm_page_size()) { 2680 // We don't check the return value: madvise(MADV_HUGEPAGE) may not 2681 // be supported or the memory may already be backed by huge pages. 2682 ::madvise(addr, bytes, MADV_HUGEPAGE); 2683 } 2684 } 2685 2686 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) { 2687 // This method works by doing an mmap over an existing mmaping and effectively discarding 2688 // the existing pages. However it won't work for SHM-based large pages that cannot be 2689 // uncommitted at all. We don't do anything in this case to avoid creating a segment with 2690 // small pages on top of the SHM segment. This method always works for small pages, so we 2691 // allow that in any case. 2692 if (alignment_hint <= (size_t)os::vm_page_size() || can_commit_large_page_memory()) { 2693 commit_memory(addr, bytes, alignment_hint, !ExecMem); 2694 } 2695 } 2696 2697 void os::numa_make_global(char *addr, size_t bytes) { 2698 Linux::numa_interleave_memory(addr, bytes); 2699 } 2700 2701 // Define for numa_set_bind_policy(int). Setting the argument to 0 will set the 2702 // bind policy to MPOL_PREFERRED for the current thread. 2703 #define USE_MPOL_PREFERRED 0 2704 2705 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { 2706 // To make NUMA and large pages more robust when both enabled, we need to ease 2707 // the requirements on where the memory should be allocated. MPOL_BIND is the 2708 // default policy and it will force memory to be allocated on the specified 2709 // node. Changing this to MPOL_PREFERRED will prefer to allocate the memory on 2710 // the specified node, but will not force it. Using this policy will prevent 2711 // getting SIGBUS when trying to allocate large pages on NUMA nodes with no 2712 // free large pages. 2713 Linux::numa_set_bind_policy(USE_MPOL_PREFERRED); 2714 Linux::numa_tonode_memory(addr, bytes, lgrp_hint); 2715 } 2716 2717 bool os::numa_topology_changed() { return false; } 2718 2719 size_t os::numa_get_groups_num() { 2720 int max_node = Linux::numa_max_node(); 2721 return max_node > 0 ? max_node + 1 : 1; 2722 } 2723 2724 int os::numa_get_group_id() { 2725 int cpu_id = Linux::sched_getcpu(); 2726 if (cpu_id != -1) { 2727 int lgrp_id = Linux::get_node_by_cpu(cpu_id); 2728 if (lgrp_id != -1) { 2729 return lgrp_id; 2730 } 2731 } 2732 return 0; 2733 } 2734 2735 size_t os::numa_get_leaf_groups(int *ids, size_t size) { 2736 for (size_t i = 0; i < size; i++) { 2737 ids[i] = i; 2738 } 2739 return size; 2740 } 2741 2742 bool os::get_page_info(char *start, page_info* info) { 2743 return false; 2744 } 2745 2746 char *os::scan_pages(char *start, char* end, page_info* page_expected, 2747 page_info* page_found) { 2748 return end; 2749 } 2750 2751 2752 int os::Linux::sched_getcpu_syscall(void) { 2753 unsigned int cpu; 2754 int retval = -1; 2755 2756 #if defined(IA32) 2757 #ifndef SYS_getcpu 2758 #define SYS_getcpu 318 2759 #endif 2760 retval = syscall(SYS_getcpu, &cpu, NULL, NULL); 2761 #elif defined(AMD64) 2762 // Unfortunately we have to bring all these macros here from vsyscall.h 2763 // to be able to compile on old linuxes. 2764 #define __NR_vgetcpu 2 2765 #define VSYSCALL_START (-10UL << 20) 2766 #define VSYSCALL_SIZE 1024 2767 #define VSYSCALL_ADDR(vsyscall_nr) (VSYSCALL_START+VSYSCALL_SIZE*(vsyscall_nr)) 2768 typedef long (*vgetcpu_t)(unsigned int *cpu, unsigned int *node, unsigned long *tcache); 2769 vgetcpu_t vgetcpu = (vgetcpu_t)VSYSCALL_ADDR(__NR_vgetcpu); 2770 retval = vgetcpu(&cpu, NULL, NULL); 2771 #endif 2772 2773 return (retval == -1) ? retval : cpu; 2774 } 2775 2776 // Something to do with the numa-aware allocator needs these symbols 2777 extern "C" JNIEXPORT void numa_warn(int number, char *where, ...) { } 2778 extern "C" JNIEXPORT void numa_error(char *where) { } 2779 extern "C" JNIEXPORT int fork1() { return fork(); } 2780 2781 2782 // If we are running with libnuma version > 2, then we should 2783 // be trying to use symbols with versions 1.1 2784 // If we are running with earlier version, which did not have symbol versions, 2785 // we should use the base version. 2786 void* os::Linux::libnuma_dlsym(void* handle, const char *name) { 2787 void *f = dlvsym(handle, name, "libnuma_1.1"); 2788 if (f == NULL) { 2789 f = dlsym(handle, name); 2790 } 2791 return f; 2792 } 2793 2794 bool os::Linux::libnuma_init() { 2795 // sched_getcpu() should be in libc. 2796 set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t, 2797 dlsym(RTLD_DEFAULT, "sched_getcpu"))); 2798 2799 // If it's not, try a direct syscall. 2800 if (sched_getcpu() == -1) { 2801 set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t, 2802 (void*)&sched_getcpu_syscall)); 2803 } 2804 2805 if (sched_getcpu() != -1) { // Does it work? 2806 void *handle = dlopen("libnuma.so.1", RTLD_LAZY); 2807 if (handle != NULL) { 2808 set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t, 2809 libnuma_dlsym(handle, "numa_node_to_cpus"))); 2810 set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t, 2811 libnuma_dlsym(handle, "numa_max_node"))); 2812 set_numa_available(CAST_TO_FN_PTR(numa_available_func_t, 2813 libnuma_dlsym(handle, "numa_available"))); 2814 set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t, 2815 libnuma_dlsym(handle, "numa_tonode_memory"))); 2816 set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t, 2817 libnuma_dlsym(handle, "numa_interleave_memory"))); 2818 set_numa_set_bind_policy(CAST_TO_FN_PTR(numa_set_bind_policy_func_t, 2819 libnuma_dlsym(handle, "numa_set_bind_policy"))); 2820 2821 2822 if (numa_available() != -1) { 2823 set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes")); 2824 // Create a cpu -> node mapping 2825 _cpu_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, true); 2826 rebuild_cpu_to_node_map(); 2827 return true; 2828 } 2829 } 2830 } 2831 return false; 2832 } 2833 2834 // rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id. 2835 // The table is later used in get_node_by_cpu(). 2836 void os::Linux::rebuild_cpu_to_node_map() { 2837 const size_t NCPUS = 32768; // Since the buffer size computation is very obscure 2838 // in libnuma (possible values are starting from 16, 2839 // and continuing up with every other power of 2, but less 2840 // than the maximum number of CPUs supported by kernel), and 2841 // is a subject to change (in libnuma version 2 the requirements 2842 // are more reasonable) we'll just hardcode the number they use 2843 // in the library. 2844 const size_t BitsPerCLong = sizeof(long) * CHAR_BIT; 2845 2846 size_t cpu_num = os::active_processor_count(); 2847 size_t cpu_map_size = NCPUS / BitsPerCLong; 2848 size_t cpu_map_valid_size = 2849 MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size); 2850 2851 cpu_to_node()->clear(); 2852 cpu_to_node()->at_grow(cpu_num - 1); 2853 size_t node_num = numa_get_groups_num(); 2854 2855 unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size, mtInternal); 2856 for (size_t i = 0; i < node_num; i++) { 2857 if (numa_node_to_cpus(i, cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) { 2858 for (size_t j = 0; j < cpu_map_valid_size; j++) { 2859 if (cpu_map[j] != 0) { 2860 for (size_t k = 0; k < BitsPerCLong; k++) { 2861 if (cpu_map[j] & (1UL << k)) { 2862 cpu_to_node()->at_put(j * BitsPerCLong + k, i); 2863 } 2864 } 2865 } 2866 } 2867 } 2868 } 2869 FREE_C_HEAP_ARRAY(unsigned long, cpu_map); 2870 } 2871 2872 int os::Linux::get_node_by_cpu(int cpu_id) { 2873 if (cpu_to_node() != NULL && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) { 2874 return cpu_to_node()->at(cpu_id); 2875 } 2876 return -1; 2877 } 2878 2879 GrowableArray<int>* os::Linux::_cpu_to_node; 2880 os::Linux::sched_getcpu_func_t os::Linux::_sched_getcpu; 2881 os::Linux::numa_node_to_cpus_func_t os::Linux::_numa_node_to_cpus; 2882 os::Linux::numa_max_node_func_t os::Linux::_numa_max_node; 2883 os::Linux::numa_available_func_t os::Linux::_numa_available; 2884 os::Linux::numa_tonode_memory_func_t os::Linux::_numa_tonode_memory; 2885 os::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory; 2886 os::Linux::numa_set_bind_policy_func_t os::Linux::_numa_set_bind_policy; 2887 unsigned long* os::Linux::_numa_all_nodes; 2888 2889 bool os::pd_uncommit_memory(char* addr, size_t size) { 2890 uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE, 2891 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0); 2892 return res != (uintptr_t) MAP_FAILED; 2893 } 2894 2895 static address get_stack_commited_bottom(address bottom, size_t size) { 2896 address nbot = bottom; 2897 address ntop = bottom + size; 2898 2899 size_t page_sz = os::vm_page_size(); 2900 unsigned pages = size / page_sz; 2901 2902 unsigned char vec[1]; 2903 unsigned imin = 1, imax = pages + 1, imid; 2904 int mincore_return_value = 0; 2905 2906 assert(imin <= imax, "Unexpected page size"); 2907 2908 while (imin < imax) { 2909 imid = (imax + imin) / 2; 2910 nbot = ntop - (imid * page_sz); 2911 2912 // Use a trick with mincore to check whether the page is mapped or not. 2913 // mincore sets vec to 1 if page resides in memory and to 0 if page 2914 // is swapped output but if page we are asking for is unmapped 2915 // it returns -1,ENOMEM 2916 mincore_return_value = mincore(nbot, page_sz, vec); 2917 2918 if (mincore_return_value == -1) { 2919 // Page is not mapped go up 2920 // to find first mapped page 2921 if (errno != EAGAIN) { 2922 assert(errno == ENOMEM, "Unexpected mincore errno"); 2923 imax = imid; 2924 } 2925 } else { 2926 // Page is mapped go down 2927 // to find first not mapped page 2928 imin = imid + 1; 2929 } 2930 } 2931 2932 nbot = nbot + page_sz; 2933 2934 // Adjust stack bottom one page up if last checked page is not mapped 2935 if (mincore_return_value == -1) { 2936 nbot = nbot + page_sz; 2937 } 2938 2939 return nbot; 2940 } 2941 2942 2943 // Linux uses a growable mapping for the stack, and if the mapping for 2944 // the stack guard pages is not removed when we detach a thread the 2945 // stack cannot grow beyond the pages where the stack guard was 2946 // mapped. If at some point later in the process the stack expands to 2947 // that point, the Linux kernel cannot expand the stack any further 2948 // because the guard pages are in the way, and a segfault occurs. 2949 // 2950 // However, it's essential not to split the stack region by unmapping 2951 // a region (leaving a hole) that's already part of the stack mapping, 2952 // so if the stack mapping has already grown beyond the guard pages at 2953 // the time we create them, we have to truncate the stack mapping. 2954 // So, we need to know the extent of the stack mapping when 2955 // create_stack_guard_pages() is called. 2956 2957 // We only need this for stacks that are growable: at the time of 2958 // writing thread stacks don't use growable mappings (i.e. those 2959 // creeated with MAP_GROWSDOWN), and aren't marked "[stack]", so this 2960 // only applies to the main thread. 2961 2962 // If the (growable) stack mapping already extends beyond the point 2963 // where we're going to put our guard pages, truncate the mapping at 2964 // that point by munmap()ping it. This ensures that when we later 2965 // munmap() the guard pages we don't leave a hole in the stack 2966 // mapping. This only affects the main/initial thread 2967 2968 bool os::pd_create_stack_guard_pages(char* addr, size_t size) { 2969 if (os::Linux::is_initial_thread()) { 2970 // As we manually grow stack up to bottom inside create_attached_thread(), 2971 // it's likely that os::Linux::initial_thread_stack_bottom is mapped and 2972 // we don't need to do anything special. 2973 // Check it first, before calling heavy function. 2974 uintptr_t stack_extent = (uintptr_t) os::Linux::initial_thread_stack_bottom(); 2975 unsigned char vec[1]; 2976 2977 if (mincore((address)stack_extent, os::vm_page_size(), vec) == -1) { 2978 // Fallback to slow path on all errors, including EAGAIN 2979 stack_extent = (uintptr_t) get_stack_commited_bottom( 2980 os::Linux::initial_thread_stack_bottom(), 2981 (size_t)addr - stack_extent); 2982 } 2983 2984 if (stack_extent < (uintptr_t)addr) { 2985 ::munmap((void*)stack_extent, (uintptr_t)(addr - stack_extent)); 2986 } 2987 } 2988 2989 return os::commit_memory(addr, size, !ExecMem); 2990 } 2991 2992 // If this is a growable mapping, remove the guard pages entirely by 2993 // munmap()ping them. If not, just call uncommit_memory(). This only 2994 // affects the main/initial thread, but guard against future OS changes 2995 // It's safe to always unmap guard pages for initial thread because we 2996 // always place it right after end of the mapped region 2997 2998 bool os::remove_stack_guard_pages(char* addr, size_t size) { 2999 uintptr_t stack_extent, stack_base; 3000 3001 if (os::Linux::is_initial_thread()) { 3002 return ::munmap(addr, size) == 0; 3003 } 3004 3005 return os::uncommit_memory(addr, size); 3006 } 3007 3008 static address _highest_vm_reserved_address = NULL; 3009 3010 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory 3011 // at 'requested_addr'. If there are existing memory mappings at the same 3012 // location, however, they will be overwritten. If 'fixed' is false, 3013 // 'requested_addr' is only treated as a hint, the return value may or 3014 // may not start from the requested address. Unlike Linux mmap(), this 3015 // function returns NULL to indicate failure. 3016 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) { 3017 char * addr; 3018 int flags; 3019 3020 flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS; 3021 if (fixed) { 3022 assert((uintptr_t)requested_addr % os::Linux::page_size() == 0, "unaligned address"); 3023 flags |= MAP_FIXED; 3024 } 3025 3026 // Map reserved/uncommitted pages PROT_NONE so we fail early if we 3027 // touch an uncommitted page. Otherwise, the read/write might 3028 // succeed if we have enough swap space to back the physical page. 3029 addr = (char*)::mmap(requested_addr, bytes, PROT_NONE, 3030 flags, -1, 0); 3031 3032 if (addr != MAP_FAILED) { 3033 // anon_mmap() should only get called during VM initialization, 3034 // don't need lock (actually we can skip locking even it can be called 3035 // from multiple threads, because _highest_vm_reserved_address is just a 3036 // hint about the upper limit of non-stack memory regions.) 3037 if ((address)addr + bytes > _highest_vm_reserved_address) { 3038 _highest_vm_reserved_address = (address)addr + bytes; 3039 } 3040 } 3041 3042 return addr == MAP_FAILED ? NULL : addr; 3043 } 3044 3045 // Don't update _highest_vm_reserved_address, because there might be memory 3046 // regions above addr + size. If so, releasing a memory region only creates 3047 // a hole in the address space, it doesn't help prevent heap-stack collision. 3048 // 3049 static int anon_munmap(char * addr, size_t size) { 3050 return ::munmap(addr, size) == 0; 3051 } 3052 3053 char* os::pd_reserve_memory(size_t bytes, char* requested_addr, 3054 size_t alignment_hint) { 3055 return anon_mmap(requested_addr, bytes, (requested_addr != NULL)); 3056 } 3057 3058 bool os::pd_release_memory(char* addr, size_t size) { 3059 return anon_munmap(addr, size); 3060 } 3061 3062 static address highest_vm_reserved_address() { 3063 return _highest_vm_reserved_address; 3064 } 3065 3066 static bool linux_mprotect(char* addr, size_t size, int prot) { 3067 // Linux wants the mprotect address argument to be page aligned. 3068 char* bottom = (char*)align_size_down((intptr_t)addr, os::Linux::page_size()); 3069 3070 // According to SUSv3, mprotect() should only be used with mappings 3071 // established by mmap(), and mmap() always maps whole pages. Unaligned 3072 // 'addr' likely indicates problem in the VM (e.g. trying to change 3073 // protection of malloc'ed or statically allocated memory). Check the 3074 // caller if you hit this assert. 3075 assert(addr == bottom, "sanity check"); 3076 3077 size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Linux::page_size()); 3078 return ::mprotect(bottom, size, prot) == 0; 3079 } 3080 3081 // Set protections specified 3082 bool os::protect_memory(char* addr, size_t bytes, ProtType prot, 3083 bool is_committed) { 3084 unsigned int p = 0; 3085 switch (prot) { 3086 case MEM_PROT_NONE: p = PROT_NONE; break; 3087 case MEM_PROT_READ: p = PROT_READ; break; 3088 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break; 3089 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break; 3090 default: 3091 ShouldNotReachHere(); 3092 } 3093 // is_committed is unused. 3094 return linux_mprotect(addr, bytes, p); 3095 } 3096 3097 bool os::guard_memory(char* addr, size_t size) { 3098 return linux_mprotect(addr, size, PROT_NONE); 3099 } 3100 3101 bool os::unguard_memory(char* addr, size_t size) { 3102 return linux_mprotect(addr, size, PROT_READ|PROT_WRITE); 3103 } 3104 3105 bool os::Linux::transparent_huge_pages_sanity_check(bool warn, 3106 size_t page_size) { 3107 bool result = false; 3108 void *p = mmap(NULL, page_size * 2, PROT_READ|PROT_WRITE, 3109 MAP_ANONYMOUS|MAP_PRIVATE, 3110 -1, 0); 3111 if (p != MAP_FAILED) { 3112 void *aligned_p = align_ptr_up(p, page_size); 3113 3114 result = madvise(aligned_p, page_size, MADV_HUGEPAGE) == 0; 3115 3116 munmap(p, page_size * 2); 3117 } 3118 3119 if (warn && !result) { 3120 warning("TransparentHugePages is not supported by the operating system."); 3121 } 3122 3123 return result; 3124 } 3125 3126 bool os::Linux::hugetlbfs_sanity_check(bool warn, size_t page_size) { 3127 bool result = false; 3128 void *p = mmap(NULL, page_size, PROT_READ|PROT_WRITE, 3129 MAP_ANONYMOUS|MAP_PRIVATE|MAP_HUGETLB, 3130 -1, 0); 3131 3132 if (p != MAP_FAILED) { 3133 // We don't know if this really is a huge page or not. 3134 FILE *fp = fopen("/proc/self/maps", "r"); 3135 if (fp) { 3136 while (!feof(fp)) { 3137 char chars[257]; 3138 long x = 0; 3139 if (fgets(chars, sizeof(chars), fp)) { 3140 if (sscanf(chars, "%lx-%*x", &x) == 1 3141 && x == (long)p) { 3142 if (strstr (chars, "hugepage")) { 3143 result = true; 3144 break; 3145 } 3146 } 3147 } 3148 } 3149 fclose(fp); 3150 } 3151 munmap(p, page_size); 3152 } 3153 3154 if (warn && !result) { 3155 warning("HugeTLBFS is not supported by the operating system."); 3156 } 3157 3158 return result; 3159 } 3160 3161 // Set the coredump_filter bits to include largepages in core dump (bit 6) 3162 // 3163 // From the coredump_filter documentation: 3164 // 3165 // - (bit 0) anonymous private memory 3166 // - (bit 1) anonymous shared memory 3167 // - (bit 2) file-backed private memory 3168 // - (bit 3) file-backed shared memory 3169 // - (bit 4) ELF header pages in file-backed private memory areas (it is 3170 // effective only if the bit 2 is cleared) 3171 // - (bit 5) hugetlb private memory 3172 // - (bit 6) hugetlb shared memory 3173 // 3174 static void set_coredump_filter(void) { 3175 FILE *f; 3176 long cdm; 3177 3178 if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) { 3179 return; 3180 } 3181 3182 if (fscanf(f, "%lx", &cdm) != 1) { 3183 fclose(f); 3184 return; 3185 } 3186 3187 rewind(f); 3188 3189 if ((cdm & LARGEPAGES_BIT) == 0) { 3190 cdm |= LARGEPAGES_BIT; 3191 fprintf(f, "%#lx", cdm); 3192 } 3193 3194 fclose(f); 3195 } 3196 3197 // Large page support 3198 3199 static size_t _large_page_size = 0; 3200 3201 size_t os::Linux::find_large_page_size() { 3202 size_t large_page_size = 0; 3203 3204 // large_page_size on Linux is used to round up heap size. x86 uses either 3205 // 2M or 4M page, depending on whether PAE (Physical Address Extensions) 3206 // mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. IA64 can use 3207 // page as large as 256M. 3208 // 3209 // Here we try to figure out page size by parsing /proc/meminfo and looking 3210 // for a line with the following format: 3211 // Hugepagesize: 2048 kB 3212 // 3213 // If we can't determine the value (e.g. /proc is not mounted, or the text 3214 // format has been changed), we'll use the largest page size supported by 3215 // the processor. 3216 3217 #ifndef ZERO 3218 large_page_size = IA32_ONLY(4 * M) AMD64_ONLY(2 * M) IA64_ONLY(256 * M) SPARC_ONLY(4 * M) 3219 ARM32_ONLY(2 * M) PPC_ONLY(4 * M) AARCH64_ONLY(2 * M); 3220 #endif // ZERO 3221 3222 FILE *fp = fopen("/proc/meminfo", "r"); 3223 if (fp) { 3224 while (!feof(fp)) { 3225 int x = 0; 3226 char buf[16]; 3227 if (fscanf(fp, "Hugepagesize: %d", &x) == 1) { 3228 if (x && fgets(buf, sizeof(buf), fp) && strcmp(buf, " kB\n") == 0) { 3229 large_page_size = x * K; 3230 break; 3231 } 3232 } else { 3233 // skip to next line 3234 for (;;) { 3235 int ch = fgetc(fp); 3236 if (ch == EOF || ch == (int)'\n') break; 3237 } 3238 } 3239 } 3240 fclose(fp); 3241 } 3242 3243 if (!FLAG_IS_DEFAULT(LargePageSizeInBytes) && LargePageSizeInBytes != large_page_size) { 3244 warning("Setting LargePageSizeInBytes has no effect on this OS. Large page size is " 3245 SIZE_FORMAT "%s.", byte_size_in_proper_unit(large_page_size), 3246 proper_unit_for_byte_size(large_page_size)); 3247 } 3248 3249 return large_page_size; 3250 } 3251 3252 size_t os::Linux::setup_large_page_size() { 3253 _large_page_size = Linux::find_large_page_size(); 3254 const size_t default_page_size = (size_t)Linux::page_size(); 3255 if (_large_page_size > default_page_size) { 3256 _page_sizes[0] = _large_page_size; 3257 _page_sizes[1] = default_page_size; 3258 _page_sizes[2] = 0; 3259 } 3260 3261 return _large_page_size; 3262 } 3263 3264 bool os::Linux::setup_large_page_type(size_t page_size) { 3265 if (FLAG_IS_DEFAULT(UseHugeTLBFS) && 3266 FLAG_IS_DEFAULT(UseSHM) && 3267 FLAG_IS_DEFAULT(UseTransparentHugePages)) { 3268 3269 // The type of large pages has not been specified by the user. 3270 3271 // Try UseHugeTLBFS and then UseSHM. 3272 UseHugeTLBFS = UseSHM = true; 3273 3274 // Don't try UseTransparentHugePages since there are known 3275 // performance issues with it turned on. This might change in the future. 3276 UseTransparentHugePages = false; 3277 } 3278 3279 if (UseTransparentHugePages) { 3280 bool warn_on_failure = !FLAG_IS_DEFAULT(UseTransparentHugePages); 3281 if (transparent_huge_pages_sanity_check(warn_on_failure, page_size)) { 3282 UseHugeTLBFS = false; 3283 UseSHM = false; 3284 return true; 3285 } 3286 UseTransparentHugePages = false; 3287 } 3288 3289 if (UseHugeTLBFS) { 3290 bool warn_on_failure = !FLAG_IS_DEFAULT(UseHugeTLBFS); 3291 if (hugetlbfs_sanity_check(warn_on_failure, page_size)) { 3292 UseSHM = false; 3293 return true; 3294 } 3295 UseHugeTLBFS = false; 3296 } 3297 3298 return UseSHM; 3299 } 3300 3301 void os::large_page_init() { 3302 if (!UseLargePages && 3303 !UseTransparentHugePages && 3304 !UseHugeTLBFS && 3305 !UseSHM) { 3306 // Not using large pages. 3307 return; 3308 } 3309 3310 if (!FLAG_IS_DEFAULT(UseLargePages) && !UseLargePages) { 3311 // The user explicitly turned off large pages. 3312 // Ignore the rest of the large pages flags. 3313 UseTransparentHugePages = false; 3314 UseHugeTLBFS = false; 3315 UseSHM = false; 3316 return; 3317 } 3318 3319 size_t large_page_size = Linux::setup_large_page_size(); 3320 UseLargePages = Linux::setup_large_page_type(large_page_size); 3321 3322 set_coredump_filter(); 3323 } 3324 3325 #ifndef SHM_HUGETLB 3326 #define SHM_HUGETLB 04000 3327 #endif 3328 3329 char* os::Linux::reserve_memory_special_shm(size_t bytes, size_t alignment, 3330 char* req_addr, bool exec) { 3331 // "exec" is passed in but not used. Creating the shared image for 3332 // the code cache doesn't have an SHM_X executable permission to check. 3333 assert(UseLargePages && UseSHM, "only for SHM large pages"); 3334 assert(is_ptr_aligned(req_addr, os::large_page_size()), "Unaligned address"); 3335 3336 if (!is_size_aligned(bytes, os::large_page_size()) || alignment > os::large_page_size()) { 3337 return NULL; // Fallback to small pages. 3338 } 3339 3340 key_t key = IPC_PRIVATE; 3341 char *addr; 3342 3343 bool warn_on_failure = UseLargePages && 3344 (!FLAG_IS_DEFAULT(UseLargePages) || 3345 !FLAG_IS_DEFAULT(UseSHM) || 3346 !FLAG_IS_DEFAULT(LargePageSizeInBytes)); 3347 char msg[128]; 3348 3349 // Create a large shared memory region to attach to based on size. 3350 // Currently, size is the total size of the heap 3351 int shmid = shmget(key, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W); 3352 if (shmid == -1) { 3353 // Possible reasons for shmget failure: 3354 // 1. shmmax is too small for Java heap. 3355 // > check shmmax value: cat /proc/sys/kernel/shmmax 3356 // > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax 3357 // 2. not enough large page memory. 3358 // > check available large pages: cat /proc/meminfo 3359 // > increase amount of large pages: 3360 // echo new_value > /proc/sys/vm/nr_hugepages 3361 // Note 1: different Linux may use different name for this property, 3362 // e.g. on Redhat AS-3 it is "hugetlb_pool". 3363 // Note 2: it's possible there's enough physical memory available but 3364 // they are so fragmented after a long run that they can't 3365 // coalesce into large pages. Try to reserve large pages when 3366 // the system is still "fresh". 3367 if (warn_on_failure) { 3368 jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno); 3369 warning("%s", msg); 3370 } 3371 return NULL; 3372 } 3373 3374 // attach to the region 3375 addr = (char*)shmat(shmid, req_addr, 0); 3376 int err = errno; 3377 3378 // Remove shmid. If shmat() is successful, the actual shared memory segment 3379 // will be deleted when it's detached by shmdt() or when the process 3380 // terminates. If shmat() is not successful this will remove the shared 3381 // segment immediately. 3382 shmctl(shmid, IPC_RMID, NULL); 3383 3384 if ((intptr_t)addr == -1) { 3385 if (warn_on_failure) { 3386 jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err); 3387 warning("%s", msg); 3388 } 3389 return NULL; 3390 } 3391 3392 return addr; 3393 } 3394 3395 static void warn_on_large_pages_failure(char* req_addr, size_t bytes, 3396 int error) { 3397 assert(error == ENOMEM, "Only expect to fail if no memory is available"); 3398 3399 bool warn_on_failure = UseLargePages && 3400 (!FLAG_IS_DEFAULT(UseLargePages) || 3401 !FLAG_IS_DEFAULT(UseHugeTLBFS) || 3402 !FLAG_IS_DEFAULT(LargePageSizeInBytes)); 3403 3404 if (warn_on_failure) { 3405 char msg[128]; 3406 jio_snprintf(msg, sizeof(msg), "Failed to reserve large pages memory req_addr: " 3407 PTR_FORMAT " bytes: " SIZE_FORMAT " (errno = %d).", req_addr, bytes, error); 3408 warning("%s", msg); 3409 } 3410 } 3411 3412 char* os::Linux::reserve_memory_special_huge_tlbfs_only(size_t bytes, 3413 char* req_addr, 3414 bool exec) { 3415 assert(UseLargePages && UseHugeTLBFS, "only for Huge TLBFS large pages"); 3416 assert(is_size_aligned(bytes, os::large_page_size()), "Unaligned size"); 3417 assert(is_ptr_aligned(req_addr, os::large_page_size()), "Unaligned address"); 3418 3419 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; 3420 char* addr = (char*)::mmap(req_addr, bytes, prot, 3421 MAP_PRIVATE|MAP_ANONYMOUS|MAP_HUGETLB, 3422 -1, 0); 3423 3424 if (addr == MAP_FAILED) { 3425 warn_on_large_pages_failure(req_addr, bytes, errno); 3426 return NULL; 3427 } 3428 3429 assert(is_ptr_aligned(addr, os::large_page_size()), "Must be"); 3430 3431 return addr; 3432 } 3433 3434 // Helper for os::Linux::reserve_memory_special_huge_tlbfs_mixed(). 3435 // Allocate (using mmap, NO_RESERVE, with small pages) at either a given request address 3436 // (req_addr != NULL) or with a given alignment. 3437 // - bytes shall be a multiple of alignment. 3438 // - req_addr can be NULL. If not NULL, it must be a multiple of alignment. 3439 // - alignment sets the alignment at which memory shall be allocated. 3440 // It must be a multiple of allocation granularity. 3441 // Returns address of memory or NULL. If req_addr was not NULL, will only return 3442 // req_addr or NULL. 3443 static char* anon_mmap_aligned(size_t bytes, size_t alignment, char* req_addr) { 3444 3445 size_t extra_size = bytes; 3446 if (req_addr == NULL && alignment > 0) { 3447 extra_size += alignment; 3448 } 3449 3450 char* start = (char*) ::mmap(req_addr, extra_size, PROT_NONE, 3451 MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE, 3452 -1, 0); 3453 if (start == MAP_FAILED) { 3454 start = NULL; 3455 } else { 3456 if (req_addr != NULL) { 3457 if (start != req_addr) { 3458 ::munmap(start, extra_size); 3459 start = NULL; 3460 } 3461 } else { 3462 char* const start_aligned = (char*) align_ptr_up(start, alignment); 3463 char* const end_aligned = start_aligned + bytes; 3464 char* const end = start + extra_size; 3465 if (start_aligned > start) { 3466 ::munmap(start, start_aligned - start); 3467 } 3468 if (end_aligned < end) { 3469 ::munmap(end_aligned, end - end_aligned); 3470 } 3471 start = start_aligned; 3472 } 3473 } 3474 return start; 3475 3476 } 3477 3478 // Reserve memory using mmap(MAP_HUGETLB). 3479 // - bytes shall be a multiple of alignment. 3480 // - req_addr can be NULL. If not NULL, it must be a multiple of alignment. 3481 // - alignment sets the alignment at which memory shall be allocated. 3482 // It must be a multiple of allocation granularity. 3483 // Returns address of memory or NULL. If req_addr was not NULL, will only return 3484 // req_addr or NULL. 3485 char* os::Linux::reserve_memory_special_huge_tlbfs_mixed(size_t bytes, 3486 size_t alignment, 3487 char* req_addr, 3488 bool exec) { 3489 size_t large_page_size = os::large_page_size(); 3490 assert(bytes >= large_page_size, "Shouldn't allocate large pages for small sizes"); 3491 3492 assert(is_ptr_aligned(req_addr, alignment), "Must be"); 3493 assert(is_size_aligned(bytes, alignment), "Must be"); 3494 3495 // First reserve - but not commit - the address range in small pages. 3496 char* const start = anon_mmap_aligned(bytes, alignment, req_addr); 3497 3498 if (start == NULL) { 3499 return NULL; 3500 } 3501 3502 assert(is_ptr_aligned(start, alignment), "Must be"); 3503 3504 char* end = start + bytes; 3505 3506 // Find the regions of the allocated chunk that can be promoted to large pages. 3507 char* lp_start = (char*)align_ptr_up(start, large_page_size); 3508 char* lp_end = (char*)align_ptr_down(end, large_page_size); 3509 3510 size_t lp_bytes = lp_end - lp_start; 3511 3512 assert(is_size_aligned(lp_bytes, large_page_size), "Must be"); 3513 3514 if (lp_bytes == 0) { 3515 // The mapped region doesn't even span the start and the end of a large page. 3516 // Fall back to allocate a non-special area. 3517 ::munmap(start, end - start); 3518 return NULL; 3519 } 3520 3521 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; 3522 3523 void* result; 3524 3525 // Commit small-paged leading area. 3526 if (start != lp_start) { 3527 result = ::mmap(start, lp_start - start, prot, 3528 MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, 3529 -1, 0); 3530 if (result == MAP_FAILED) { 3531 ::munmap(lp_start, end - lp_start); 3532 return NULL; 3533 } 3534 } 3535 3536 // Commit large-paged area. 3537 result = ::mmap(lp_start, lp_bytes, prot, 3538 MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED|MAP_HUGETLB, 3539 -1, 0); 3540 if (result == MAP_FAILED) { 3541 warn_on_large_pages_failure(lp_start, lp_bytes, errno); 3542 // If the mmap above fails, the large pages region will be unmapped and we 3543 // have regions before and after with small pages. Release these regions. 3544 // 3545 // | mapped | unmapped | mapped | 3546 // ^ ^ ^ ^ 3547 // start lp_start lp_end end 3548 // 3549 ::munmap(start, lp_start - start); 3550 ::munmap(lp_end, end - lp_end); 3551 return NULL; 3552 } 3553 3554 // Commit small-paged trailing area. 3555 if (lp_end != end) { 3556 result = ::mmap(lp_end, end - lp_end, prot, 3557 MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, 3558 -1, 0); 3559 if (result == MAP_FAILED) { 3560 ::munmap(start, lp_end - start); 3561 return NULL; 3562 } 3563 } 3564 3565 return start; 3566 } 3567 3568 char* os::Linux::reserve_memory_special_huge_tlbfs(size_t bytes, 3569 size_t alignment, 3570 char* req_addr, 3571 bool exec) { 3572 assert(UseLargePages && UseHugeTLBFS, "only for Huge TLBFS large pages"); 3573 assert(is_ptr_aligned(req_addr, alignment), "Must be"); 3574 assert(is_size_aligned(alignment, os::vm_allocation_granularity()), "Must be"); 3575 assert(is_power_of_2(os::large_page_size()), "Must be"); 3576 assert(bytes >= os::large_page_size(), "Shouldn't allocate large pages for small sizes"); 3577 3578 if (is_size_aligned(bytes, os::large_page_size()) && alignment <= os::large_page_size()) { 3579 return reserve_memory_special_huge_tlbfs_only(bytes, req_addr, exec); 3580 } else { 3581 return reserve_memory_special_huge_tlbfs_mixed(bytes, alignment, req_addr, exec); 3582 } 3583 } 3584 3585 char* os::reserve_memory_special(size_t bytes, size_t alignment, 3586 char* req_addr, bool exec) { 3587 assert(UseLargePages, "only for large pages"); 3588 3589 char* addr; 3590 if (UseSHM) { 3591 addr = os::Linux::reserve_memory_special_shm(bytes, alignment, req_addr, exec); 3592 } else { 3593 assert(UseHugeTLBFS, "must be"); 3594 addr = os::Linux::reserve_memory_special_huge_tlbfs(bytes, alignment, req_addr, exec); 3595 } 3596 3597 if (addr != NULL) { 3598 if (UseNUMAInterleaving) { 3599 numa_make_global(addr, bytes); 3600 } 3601 3602 // The memory is committed 3603 MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, CALLER_PC); 3604 } 3605 3606 return addr; 3607 } 3608 3609 bool os::Linux::release_memory_special_shm(char* base, size_t bytes) { 3610 // detaching the SHM segment will also delete it, see reserve_memory_special_shm() 3611 return shmdt(base) == 0; 3612 } 3613 3614 bool os::Linux::release_memory_special_huge_tlbfs(char* base, size_t bytes) { 3615 return pd_release_memory(base, bytes); 3616 } 3617 3618 bool os::release_memory_special(char* base, size_t bytes) { 3619 bool res; 3620 if (MemTracker::tracking_level() > NMT_minimal) { 3621 Tracker tkr = MemTracker::get_virtual_memory_release_tracker(); 3622 res = os::Linux::release_memory_special_impl(base, bytes); 3623 if (res) { 3624 tkr.record((address)base, bytes); 3625 } 3626 3627 } else { 3628 res = os::Linux::release_memory_special_impl(base, bytes); 3629 } 3630 return res; 3631 } 3632 3633 bool os::Linux::release_memory_special_impl(char* base, size_t bytes) { 3634 assert(UseLargePages, "only for large pages"); 3635 bool res; 3636 3637 if (UseSHM) { 3638 res = os::Linux::release_memory_special_shm(base, bytes); 3639 } else { 3640 assert(UseHugeTLBFS, "must be"); 3641 res = os::Linux::release_memory_special_huge_tlbfs(base, bytes); 3642 } 3643 return res; 3644 } 3645 3646 size_t os::large_page_size() { 3647 return _large_page_size; 3648 } 3649 3650 // With SysV SHM the entire memory region must be allocated as shared 3651 // memory. 3652 // HugeTLBFS allows application to commit large page memory on demand. 3653 // However, when committing memory with HugeTLBFS fails, the region 3654 // that was supposed to be committed will lose the old reservation 3655 // and allow other threads to steal that memory region. Because of this 3656 // behavior we can't commit HugeTLBFS memory. 3657 bool os::can_commit_large_page_memory() { 3658 return UseTransparentHugePages; 3659 } 3660 3661 bool os::can_execute_large_page_memory() { 3662 return UseTransparentHugePages || UseHugeTLBFS; 3663 } 3664 3665 // Reserve memory at an arbitrary address, only if that area is 3666 // available (and not reserved for something else). 3667 3668 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) { 3669 const int max_tries = 10; 3670 char* base[max_tries]; 3671 size_t size[max_tries]; 3672 const size_t gap = 0x000000; 3673 3674 // Assert only that the size is a multiple of the page size, since 3675 // that's all that mmap requires, and since that's all we really know 3676 // about at this low abstraction level. If we need higher alignment, 3677 // we can either pass an alignment to this method or verify alignment 3678 // in one of the methods further up the call chain. See bug 5044738. 3679 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block"); 3680 3681 // Repeatedly allocate blocks until the block is allocated at the 3682 // right spot. Give up after max_tries. Note that reserve_memory() will 3683 // automatically update _highest_vm_reserved_address if the call is 3684 // successful. The variable tracks the highest memory address every reserved 3685 // by JVM. It is used to detect heap-stack collision if running with 3686 // fixed-stack LinuxThreads. Because here we may attempt to reserve more 3687 // space than needed, it could confuse the collision detecting code. To 3688 // solve the problem, save current _highest_vm_reserved_address and 3689 // calculate the correct value before return. 3690 address old_highest = _highest_vm_reserved_address; 3691 3692 // Linux mmap allows caller to pass an address as hint; give it a try first, 3693 // if kernel honors the hint then we can return immediately. 3694 char * addr = anon_mmap(requested_addr, bytes, false); 3695 if (addr == requested_addr) { 3696 return requested_addr; 3697 } 3698 3699 if (addr != NULL) { 3700 // mmap() is successful but it fails to reserve at the requested address 3701 anon_munmap(addr, bytes); 3702 } 3703 3704 int i; 3705 for (i = 0; i < max_tries; ++i) { 3706 base[i] = reserve_memory(bytes); 3707 3708 if (base[i] != NULL) { 3709 // Is this the block we wanted? 3710 if (base[i] == requested_addr) { 3711 size[i] = bytes; 3712 break; 3713 } 3714 3715 // Does this overlap the block we wanted? Give back the overlapped 3716 // parts and try again. 3717 3718 ptrdiff_t top_overlap = requested_addr + (bytes + gap) - base[i]; 3719 if (top_overlap >= 0 && (size_t)top_overlap < bytes) { 3720 unmap_memory(base[i], top_overlap); 3721 base[i] += top_overlap; 3722 size[i] = bytes - top_overlap; 3723 } else { 3724 ptrdiff_t bottom_overlap = base[i] + bytes - requested_addr; 3725 if (bottom_overlap >= 0 && (size_t)bottom_overlap < bytes) { 3726 unmap_memory(requested_addr, bottom_overlap); 3727 size[i] = bytes - bottom_overlap; 3728 } else { 3729 size[i] = bytes; 3730 } 3731 } 3732 } 3733 } 3734 3735 // Give back the unused reserved pieces. 3736 3737 for (int j = 0; j < i; ++j) { 3738 if (base[j] != NULL) { 3739 unmap_memory(base[j], size[j]); 3740 } 3741 } 3742 3743 if (i < max_tries) { 3744 _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes); 3745 return requested_addr; 3746 } else { 3747 _highest_vm_reserved_address = old_highest; 3748 return NULL; 3749 } 3750 } 3751 3752 size_t os::read(int fd, void *buf, unsigned int nBytes) { 3753 return ::read(fd, buf, nBytes); 3754 } 3755 3756 size_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) { 3757 return ::pread(fd, buf, nBytes, offset); 3758 } 3759 3760 // Short sleep, direct OS call. 3761 // 3762 // Note: certain versions of Linux CFS scheduler (since 2.6.23) do not guarantee 3763 // sched_yield(2) will actually give up the CPU: 3764 // 3765 // * Alone on this pariticular CPU, keeps running. 3766 // * Before the introduction of "skip_buddy" with "compat_yield" disabled 3767 // (pre 2.6.39). 3768 // 3769 // So calling this with 0 is an alternative. 3770 // 3771 void os::naked_short_sleep(jlong ms) { 3772 struct timespec req; 3773 3774 assert(ms < 1000, "Un-interruptable sleep, short time use only"); 3775 req.tv_sec = 0; 3776 if (ms > 0) { 3777 req.tv_nsec = (ms % 1000) * 1000000; 3778 } else { 3779 req.tv_nsec = 1; 3780 } 3781 3782 nanosleep(&req, NULL); 3783 3784 return; 3785 } 3786 3787 // Sleep forever; naked call to OS-specific sleep; use with CAUTION 3788 void os::infinite_sleep() { 3789 while (true) { // sleep forever ... 3790 ::sleep(100); // ... 100 seconds at a time 3791 } 3792 } 3793 3794 // Used to convert frequent JVM_Yield() to nops 3795 bool os::dont_yield() { 3796 return DontYieldALot; 3797 } 3798 3799 void os::naked_yield() { 3800 sched_yield(); 3801 } 3802 3803 //////////////////////////////////////////////////////////////////////////////// 3804 // thread priority support 3805 3806 // Note: Normal Linux applications are run with SCHED_OTHER policy. SCHED_OTHER 3807 // only supports dynamic priority, static priority must be zero. For real-time 3808 // applications, Linux supports SCHED_RR which allows static priority (1-99). 3809 // However, for large multi-threaded applications, SCHED_RR is not only slower 3810 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out 3811 // of 5 runs - Sep 2005). 3812 // 3813 // The following code actually changes the niceness of kernel-thread/LWP. It 3814 // has an assumption that setpriority() only modifies one kernel-thread/LWP, 3815 // not the entire user process, and user level threads are 1:1 mapped to kernel 3816 // threads. It has always been the case, but could change in the future. For 3817 // this reason, the code should not be used as default (ThreadPriorityPolicy=0). 3818 // It is only used when ThreadPriorityPolicy=1 and requires root privilege. 3819 3820 int os::java_to_os_priority[CriticalPriority + 1] = { 3821 19, // 0 Entry should never be used 3822 3823 4, // 1 MinPriority 3824 3, // 2 3825 2, // 3 3826 3827 1, // 4 3828 0, // 5 NormPriority 3829 -1, // 6 3830 3831 -2, // 7 3832 -3, // 8 3833 -4, // 9 NearMaxPriority 3834 3835 -5, // 10 MaxPriority 3836 3837 -5 // 11 CriticalPriority 3838 }; 3839 3840 static int prio_init() { 3841 if (ThreadPriorityPolicy == 1) { 3842 // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1 3843 // if effective uid is not root. Perhaps, a more elegant way of doing 3844 // this is to test CAP_SYS_NICE capability, but that will require libcap.so 3845 if (geteuid() != 0) { 3846 if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) { 3847 warning("-XX:ThreadPriorityPolicy requires root privilege on Linux"); 3848 } 3849 ThreadPriorityPolicy = 0; 3850 } 3851 } 3852 if (UseCriticalJavaThreadPriority) { 3853 os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority]; 3854 } 3855 return 0; 3856 } 3857 3858 OSReturn os::set_native_priority(Thread* thread, int newpri) { 3859 if (!UseThreadPriorities || ThreadPriorityPolicy == 0) return OS_OK; 3860 3861 int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri); 3862 return (ret == 0) ? OS_OK : OS_ERR; 3863 } 3864 3865 OSReturn os::get_native_priority(const Thread* const thread, 3866 int *priority_ptr) { 3867 if (!UseThreadPriorities || ThreadPriorityPolicy == 0) { 3868 *priority_ptr = java_to_os_priority[NormPriority]; 3869 return OS_OK; 3870 } 3871 3872 errno = 0; 3873 *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id()); 3874 return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR); 3875 } 3876 3877 // Hint to the underlying OS that a task switch would not be good. 3878 // Void return because it's a hint and can fail. 3879 void os::hint_no_preempt() {} 3880 3881 //////////////////////////////////////////////////////////////////////////////// 3882 // suspend/resume support 3883 3884 // the low-level signal-based suspend/resume support is a remnant from the 3885 // old VM-suspension that used to be for java-suspension, safepoints etc, 3886 // within hotspot. Now there is a single use-case for this: 3887 // - calling get_thread_pc() on the VMThread by the flat-profiler task 3888 // that runs in the watcher thread. 3889 // The remaining code is greatly simplified from the more general suspension 3890 // code that used to be used. 3891 // 3892 // The protocol is quite simple: 3893 // - suspend: 3894 // - sends a signal to the target thread 3895 // - polls the suspend state of the osthread using a yield loop 3896 // - target thread signal handler (SR_handler) sets suspend state 3897 // and blocks in sigsuspend until continued 3898 // - resume: 3899 // - sets target osthread state to continue 3900 // - sends signal to end the sigsuspend loop in the SR_handler 3901 // 3902 // Note that the SR_lock plays no role in this suspend/resume protocol. 3903 3904 static void resume_clear_context(OSThread *osthread) { 3905 osthread->set_ucontext(NULL); 3906 osthread->set_siginfo(NULL); 3907 } 3908 3909 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, 3910 ucontext_t* context) { 3911 osthread->set_ucontext(context); 3912 osthread->set_siginfo(siginfo); 3913 } 3914 3915 // Handler function invoked when a thread's execution is suspended or 3916 // resumed. We have to be careful that only async-safe functions are 3917 // called here (Note: most pthread functions are not async safe and 3918 // should be avoided.) 3919 // 3920 // Note: sigwait() is a more natural fit than sigsuspend() from an 3921 // interface point of view, but sigwait() prevents the signal hander 3922 // from being run. libpthread would get very confused by not having 3923 // its signal handlers run and prevents sigwait()'s use with the 3924 // mutex granting granting signal. 3925 // 3926 // Currently only ever called on the VMThread and JavaThreads (PC sampling) 3927 // 3928 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) { 3929 // Save and restore errno to avoid confusing native code with EINTR 3930 // after sigsuspend. 3931 int old_errno = errno; 3932 3933 Thread* thread = Thread::current(); 3934 OSThread* osthread = thread->osthread(); 3935 assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread"); 3936 3937 os::SuspendResume::State current = osthread->sr.state(); 3938 if (current == os::SuspendResume::SR_SUSPEND_REQUEST) { 3939 suspend_save_context(osthread, siginfo, context); 3940 3941 // attempt to switch the state, we assume we had a SUSPEND_REQUEST 3942 os::SuspendResume::State state = osthread->sr.suspended(); 3943 if (state == os::SuspendResume::SR_SUSPENDED) { 3944 sigset_t suspend_set; // signals for sigsuspend() 3945 3946 // get current set of blocked signals and unblock resume signal 3947 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set); 3948 sigdelset(&suspend_set, SR_signum); 3949 3950 sr_semaphore.signal(); 3951 // wait here until we are resumed 3952 while (1) { 3953 sigsuspend(&suspend_set); 3954 3955 os::SuspendResume::State result = osthread->sr.running(); 3956 if (result == os::SuspendResume::SR_RUNNING) { 3957 sr_semaphore.signal(); 3958 break; 3959 } 3960 } 3961 3962 } else if (state == os::SuspendResume::SR_RUNNING) { 3963 // request was cancelled, continue 3964 } else { 3965 ShouldNotReachHere(); 3966 } 3967 3968 resume_clear_context(osthread); 3969 } else if (current == os::SuspendResume::SR_RUNNING) { 3970 // request was cancelled, continue 3971 } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) { 3972 // ignore 3973 } else { 3974 // ignore 3975 } 3976 3977 errno = old_errno; 3978 } 3979 3980 3981 static int SR_initialize() { 3982 struct sigaction act; 3983 char *s; 3984 // Get signal number to use for suspend/resume 3985 if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) { 3986 int sig = ::strtol(s, 0, 10); 3987 if (sig > 0 || sig < _NSIG) { 3988 SR_signum = sig; 3989 } 3990 } 3991 3992 assert(SR_signum > SIGSEGV && SR_signum > SIGBUS, 3993 "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769"); 3994 3995 sigemptyset(&SR_sigset); 3996 sigaddset(&SR_sigset, SR_signum); 3997 3998 // Set up signal handler for suspend/resume 3999 act.sa_flags = SA_RESTART|SA_SIGINFO; 4000 act.sa_handler = (void (*)(int)) SR_handler; 4001 4002 // SR_signum is blocked by default. 4003 // 4528190 - We also need to block pthread restart signal (32 on all 4004 // supported Linux platforms). Note that LinuxThreads need to block 4005 // this signal for all threads to work properly. So we don't have 4006 // to use hard-coded signal number when setting up the mask. 4007 pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask); 4008 4009 if (sigaction(SR_signum, &act, 0) == -1) { 4010 return -1; 4011 } 4012 4013 // Save signal flag 4014 os::Linux::set_our_sigflags(SR_signum, act.sa_flags); 4015 return 0; 4016 } 4017 4018 static int sr_notify(OSThread* osthread) { 4019 int status = pthread_kill(osthread->pthread_id(), SR_signum); 4020 assert_status(status == 0, status, "pthread_kill"); 4021 return status; 4022 } 4023 4024 // "Randomly" selected value for how long we want to spin 4025 // before bailing out on suspending a thread, also how often 4026 // we send a signal to a thread we want to resume 4027 static const int RANDOMLY_LARGE_INTEGER = 1000000; 4028 static const int RANDOMLY_LARGE_INTEGER2 = 100; 4029 4030 // returns true on success and false on error - really an error is fatal 4031 // but this seems the normal response to library errors 4032 static bool do_suspend(OSThread* osthread) { 4033 assert(osthread->sr.is_running(), "thread should be running"); 4034 assert(!sr_semaphore.trywait(), "semaphore has invalid state"); 4035 4036 // mark as suspended and send signal 4037 if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) { 4038 // failed to switch, state wasn't running? 4039 ShouldNotReachHere(); 4040 return false; 4041 } 4042 4043 if (sr_notify(osthread) != 0) { 4044 ShouldNotReachHere(); 4045 } 4046 4047 // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED 4048 while (true) { 4049 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) { 4050 break; 4051 } else { 4052 // timeout 4053 os::SuspendResume::State cancelled = osthread->sr.cancel_suspend(); 4054 if (cancelled == os::SuspendResume::SR_RUNNING) { 4055 return false; 4056 } else if (cancelled == os::SuspendResume::SR_SUSPENDED) { 4057 // make sure that we consume the signal on the semaphore as well 4058 sr_semaphore.wait(); 4059 break; 4060 } else { 4061 ShouldNotReachHere(); 4062 return false; 4063 } 4064 } 4065 } 4066 4067 guarantee(osthread->sr.is_suspended(), "Must be suspended"); 4068 return true; 4069 } 4070 4071 static void do_resume(OSThread* osthread) { 4072 assert(osthread->sr.is_suspended(), "thread should be suspended"); 4073 assert(!sr_semaphore.trywait(), "invalid semaphore state"); 4074 4075 if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) { 4076 // failed to switch to WAKEUP_REQUEST 4077 ShouldNotReachHere(); 4078 return; 4079 } 4080 4081 while (true) { 4082 if (sr_notify(osthread) == 0) { 4083 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) { 4084 if (osthread->sr.is_running()) { 4085 return; 4086 } 4087 } 4088 } else { 4089 ShouldNotReachHere(); 4090 } 4091 } 4092 4093 guarantee(osthread->sr.is_running(), "Must be running!"); 4094 } 4095 4096 /////////////////////////////////////////////////////////////////////////////////// 4097 // signal handling (except suspend/resume) 4098 4099 // This routine may be used by user applications as a "hook" to catch signals. 4100 // The user-defined signal handler must pass unrecognized signals to this 4101 // routine, and if it returns true (non-zero), then the signal handler must 4102 // return immediately. If the flag "abort_if_unrecognized" is true, then this 4103 // routine will never retun false (zero), but instead will execute a VM panic 4104 // routine kill the process. 4105 // 4106 // If this routine returns false, it is OK to call it again. This allows 4107 // the user-defined signal handler to perform checks either before or after 4108 // the VM performs its own checks. Naturally, the user code would be making 4109 // a serious error if it tried to handle an exception (such as a null check 4110 // or breakpoint) that the VM was generating for its own correct operation. 4111 // 4112 // This routine may recognize any of the following kinds of signals: 4113 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1. 4114 // It should be consulted by handlers for any of those signals. 4115 // 4116 // The caller of this routine must pass in the three arguments supplied 4117 // to the function referred to in the "sa_sigaction" (not the "sa_handler") 4118 // field of the structure passed to sigaction(). This routine assumes that 4119 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART. 4120 // 4121 // Note that the VM will print warnings if it detects conflicting signal 4122 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers". 4123 // 4124 extern "C" JNIEXPORT int JVM_handle_linux_signal(int signo, 4125 siginfo_t* siginfo, 4126 void* ucontext, 4127 int abort_if_unrecognized); 4128 4129 void signalHandler(int sig, siginfo_t* info, void* uc) { 4130 assert(info != NULL && uc != NULL, "it must be old kernel"); 4131 int orig_errno = errno; // Preserve errno value over signal handler. 4132 JVM_handle_linux_signal(sig, info, uc, true); 4133 errno = orig_errno; 4134 } 4135 4136 4137 // This boolean allows users to forward their own non-matching signals 4138 // to JVM_handle_linux_signal, harmlessly. 4139 bool os::Linux::signal_handlers_are_installed = false; 4140 4141 // For signal-chaining 4142 struct sigaction os::Linux::sigact[MAXSIGNUM]; 4143 unsigned int os::Linux::sigs = 0; 4144 bool os::Linux::libjsig_is_loaded = false; 4145 typedef struct sigaction *(*get_signal_t)(int); 4146 get_signal_t os::Linux::get_signal_action = NULL; 4147 4148 struct sigaction* os::Linux::get_chained_signal_action(int sig) { 4149 struct sigaction *actp = NULL; 4150 4151 if (libjsig_is_loaded) { 4152 // Retrieve the old signal handler from libjsig 4153 actp = (*get_signal_action)(sig); 4154 } 4155 if (actp == NULL) { 4156 // Retrieve the preinstalled signal handler from jvm 4157 actp = get_preinstalled_handler(sig); 4158 } 4159 4160 return actp; 4161 } 4162 4163 static bool call_chained_handler(struct sigaction *actp, int sig, 4164 siginfo_t *siginfo, void *context) { 4165 // Call the old signal handler 4166 if (actp->sa_handler == SIG_DFL) { 4167 // It's more reasonable to let jvm treat it as an unexpected exception 4168 // instead of taking the default action. 4169 return false; 4170 } else if (actp->sa_handler != SIG_IGN) { 4171 if ((actp->sa_flags & SA_NODEFER) == 0) { 4172 // automaticlly block the signal 4173 sigaddset(&(actp->sa_mask), sig); 4174 } 4175 4176 sa_handler_t hand; 4177 sa_sigaction_t sa; 4178 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0; 4179 // retrieve the chained handler 4180 if (siginfo_flag_set) { 4181 sa = actp->sa_sigaction; 4182 } else { 4183 hand = actp->sa_handler; 4184 } 4185 4186 if ((actp->sa_flags & SA_RESETHAND) != 0) { 4187 actp->sa_handler = SIG_DFL; 4188 } 4189 4190 // try to honor the signal mask 4191 sigset_t oset; 4192 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset); 4193 4194 // call into the chained handler 4195 if (siginfo_flag_set) { 4196 (*sa)(sig, siginfo, context); 4197 } else { 4198 (*hand)(sig); 4199 } 4200 4201 // restore the signal mask 4202 pthread_sigmask(SIG_SETMASK, &oset, 0); 4203 } 4204 // Tell jvm's signal handler the signal is taken care of. 4205 return true; 4206 } 4207 4208 bool os::Linux::chained_handler(int sig, siginfo_t* siginfo, void* context) { 4209 bool chained = false; 4210 // signal-chaining 4211 if (UseSignalChaining) { 4212 struct sigaction *actp = get_chained_signal_action(sig); 4213 if (actp != NULL) { 4214 chained = call_chained_handler(actp, sig, siginfo, context); 4215 } 4216 } 4217 return chained; 4218 } 4219 4220 struct sigaction* os::Linux::get_preinstalled_handler(int sig) { 4221 if ((((unsigned int)1 << sig) & sigs) != 0) { 4222 return &sigact[sig]; 4223 } 4224 return NULL; 4225 } 4226 4227 void os::Linux::save_preinstalled_handler(int sig, struct sigaction& oldAct) { 4228 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 4229 sigact[sig] = oldAct; 4230 sigs |= (unsigned int)1 << sig; 4231 } 4232 4233 // for diagnostic 4234 int os::Linux::sigflags[MAXSIGNUM]; 4235 4236 int os::Linux::get_our_sigflags(int sig) { 4237 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 4238 return sigflags[sig]; 4239 } 4240 4241 void os::Linux::set_our_sigflags(int sig, int flags) { 4242 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 4243 sigflags[sig] = flags; 4244 } 4245 4246 void os::Linux::set_signal_handler(int sig, bool set_installed) { 4247 // Check for overwrite. 4248 struct sigaction oldAct; 4249 sigaction(sig, (struct sigaction*)NULL, &oldAct); 4250 4251 void* oldhand = oldAct.sa_sigaction 4252 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 4253 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 4254 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) && 4255 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) && 4256 oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) { 4257 if (AllowUserSignalHandlers || !set_installed) { 4258 // Do not overwrite; user takes responsibility to forward to us. 4259 return; 4260 } else if (UseSignalChaining) { 4261 // save the old handler in jvm 4262 save_preinstalled_handler(sig, oldAct); 4263 // libjsig also interposes the sigaction() call below and saves the 4264 // old sigaction on it own. 4265 } else { 4266 fatal(err_msg("Encountered unexpected pre-existing sigaction handler " 4267 "%#lx for signal %d.", (long)oldhand, sig)); 4268 } 4269 } 4270 4271 struct sigaction sigAct; 4272 sigfillset(&(sigAct.sa_mask)); 4273 sigAct.sa_handler = SIG_DFL; 4274 if (!set_installed) { 4275 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; 4276 } else { 4277 sigAct.sa_sigaction = signalHandler; 4278 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; 4279 } 4280 // Save flags, which are set by ours 4281 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 4282 sigflags[sig] = sigAct.sa_flags; 4283 4284 int ret = sigaction(sig, &sigAct, &oldAct); 4285 assert(ret == 0, "check"); 4286 4287 void* oldhand2 = oldAct.sa_sigaction 4288 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 4289 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 4290 assert(oldhand2 == oldhand, "no concurrent signal handler installation"); 4291 } 4292 4293 // install signal handlers for signals that HotSpot needs to 4294 // handle in order to support Java-level exception handling. 4295 4296 void os::Linux::install_signal_handlers() { 4297 if (!signal_handlers_are_installed) { 4298 signal_handlers_are_installed = true; 4299 4300 // signal-chaining 4301 typedef void (*signal_setting_t)(); 4302 signal_setting_t begin_signal_setting = NULL; 4303 signal_setting_t end_signal_setting = NULL; 4304 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 4305 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting")); 4306 if (begin_signal_setting != NULL) { 4307 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 4308 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting")); 4309 get_signal_action = CAST_TO_FN_PTR(get_signal_t, 4310 dlsym(RTLD_DEFAULT, "JVM_get_signal_action")); 4311 libjsig_is_loaded = true; 4312 assert(UseSignalChaining, "should enable signal-chaining"); 4313 } 4314 if (libjsig_is_loaded) { 4315 // Tell libjsig jvm is setting signal handlers 4316 (*begin_signal_setting)(); 4317 } 4318 4319 set_signal_handler(SIGSEGV, true); 4320 set_signal_handler(SIGPIPE, true); 4321 set_signal_handler(SIGBUS, true); 4322 set_signal_handler(SIGILL, true); 4323 set_signal_handler(SIGFPE, true); 4324 #if defined(PPC64) 4325 set_signal_handler(SIGTRAP, true); 4326 #endif 4327 set_signal_handler(SIGXFSZ, true); 4328 4329 if (libjsig_is_loaded) { 4330 // Tell libjsig jvm finishes setting signal handlers 4331 (*end_signal_setting)(); 4332 } 4333 4334 // We don't activate signal checker if libjsig is in place, we trust ourselves 4335 // and if UserSignalHandler is installed all bets are off. 4336 // Log that signal checking is off only if -verbose:jni is specified. 4337 if (CheckJNICalls) { 4338 if (libjsig_is_loaded) { 4339 if (PrintJNIResolving) { 4340 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled"); 4341 } 4342 check_signals = false; 4343 } 4344 if (AllowUserSignalHandlers) { 4345 if (PrintJNIResolving) { 4346 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled"); 4347 } 4348 check_signals = false; 4349 } 4350 } 4351 } 4352 } 4353 4354 // This is the fastest way to get thread cpu time on Linux. 4355 // Returns cpu time (user+sys) for any thread, not only for current. 4356 // POSIX compliant clocks are implemented in the kernels 2.6.16+. 4357 // It might work on 2.6.10+ with a special kernel/glibc patch. 4358 // For reference, please, see IEEE Std 1003.1-2004: 4359 // http://www.unix.org/single_unix_specification 4360 4361 jlong os::Linux::fast_thread_cpu_time(clockid_t clockid) { 4362 struct timespec tp; 4363 int rc = os::Linux::clock_gettime(clockid, &tp); 4364 assert(rc == 0, "clock_gettime is expected to return 0 code"); 4365 4366 return (tp.tv_sec * NANOSECS_PER_SEC) + tp.tv_nsec; 4367 } 4368 4369 ///// 4370 // glibc on Linux platform uses non-documented flag 4371 // to indicate, that some special sort of signal 4372 // trampoline is used. 4373 // We will never set this flag, and we should 4374 // ignore this flag in our diagnostic 4375 #ifdef SIGNIFICANT_SIGNAL_MASK 4376 #undef SIGNIFICANT_SIGNAL_MASK 4377 #endif 4378 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000) 4379 4380 static const char* get_signal_handler_name(address handler, 4381 char* buf, int buflen) { 4382 int offset; 4383 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset); 4384 if (found) { 4385 // skip directory names 4386 const char *p1, *p2; 4387 p1 = buf; 4388 size_t len = strlen(os::file_separator()); 4389 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len; 4390 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset); 4391 } else { 4392 jio_snprintf(buf, buflen, PTR_FORMAT, handler); 4393 } 4394 return buf; 4395 } 4396 4397 static void print_signal_handler(outputStream* st, int sig, 4398 char* buf, size_t buflen) { 4399 struct sigaction sa; 4400 4401 sigaction(sig, NULL, &sa); 4402 4403 // See comment for SIGNIFICANT_SIGNAL_MASK define 4404 sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK; 4405 4406 st->print("%s: ", os::exception_name(sig, buf, buflen)); 4407 4408 address handler = (sa.sa_flags & SA_SIGINFO) 4409 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction) 4410 : CAST_FROM_FN_PTR(address, sa.sa_handler); 4411 4412 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) { 4413 st->print("SIG_DFL"); 4414 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) { 4415 st->print("SIG_IGN"); 4416 } else { 4417 st->print("[%s]", get_signal_handler_name(handler, buf, buflen)); 4418 } 4419 4420 st->print(", sa_mask[0]="); 4421 os::Posix::print_signal_set_short(st, &sa.sa_mask); 4422 4423 address rh = VMError::get_resetted_sighandler(sig); 4424 // May be, handler was resetted by VMError? 4425 if (rh != NULL) { 4426 handler = rh; 4427 sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK; 4428 } 4429 4430 st->print(", sa_flags="); 4431 os::Posix::print_sa_flags(st, sa.sa_flags); 4432 4433 // Check: is it our handler? 4434 if (handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) || 4435 handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) { 4436 // It is our signal handler 4437 // check for flags, reset system-used one! 4438 if ((int)sa.sa_flags != os::Linux::get_our_sigflags(sig)) { 4439 st->print( 4440 ", flags was changed from " PTR32_FORMAT ", consider using jsig library", 4441 os::Linux::get_our_sigflags(sig)); 4442 } 4443 } 4444 st->cr(); 4445 } 4446 4447 4448 #define DO_SIGNAL_CHECK(sig) \ 4449 do { \ 4450 if (!sigismember(&check_signal_done, sig)) { \ 4451 os::Linux::check_signal_handler(sig); \ 4452 } \ 4453 } while (0) 4454 4455 // This method is a periodic task to check for misbehaving JNI applications 4456 // under CheckJNI, we can add any periodic checks here 4457 4458 void os::run_periodic_checks() { 4459 if (check_signals == false) return; 4460 4461 // SEGV and BUS if overridden could potentially prevent 4462 // generation of hs*.log in the event of a crash, debugging 4463 // such a case can be very challenging, so we absolutely 4464 // check the following for a good measure: 4465 DO_SIGNAL_CHECK(SIGSEGV); 4466 DO_SIGNAL_CHECK(SIGILL); 4467 DO_SIGNAL_CHECK(SIGFPE); 4468 DO_SIGNAL_CHECK(SIGBUS); 4469 DO_SIGNAL_CHECK(SIGPIPE); 4470 DO_SIGNAL_CHECK(SIGXFSZ); 4471 #if defined(PPC64) 4472 DO_SIGNAL_CHECK(SIGTRAP); 4473 #endif 4474 4475 // ReduceSignalUsage allows the user to override these handlers 4476 // see comments at the very top and jvm_solaris.h 4477 if (!ReduceSignalUsage) { 4478 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL); 4479 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL); 4480 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL); 4481 DO_SIGNAL_CHECK(BREAK_SIGNAL); 4482 } 4483 4484 DO_SIGNAL_CHECK(SR_signum); 4485 DO_SIGNAL_CHECK(INTERRUPT_SIGNAL); 4486 } 4487 4488 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *); 4489 4490 static os_sigaction_t os_sigaction = NULL; 4491 4492 void os::Linux::check_signal_handler(int sig) { 4493 char buf[O_BUFLEN]; 4494 address jvmHandler = NULL; 4495 4496 4497 struct sigaction act; 4498 if (os_sigaction == NULL) { 4499 // only trust the default sigaction, in case it has been interposed 4500 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction"); 4501 if (os_sigaction == NULL) return; 4502 } 4503 4504 os_sigaction(sig, (struct sigaction*)NULL, &act); 4505 4506 4507 act.sa_flags &= SIGNIFICANT_SIGNAL_MASK; 4508 4509 address thisHandler = (act.sa_flags & SA_SIGINFO) 4510 ? CAST_FROM_FN_PTR(address, act.sa_sigaction) 4511 : CAST_FROM_FN_PTR(address, act.sa_handler); 4512 4513 4514 switch (sig) { 4515 case SIGSEGV: 4516 case SIGBUS: 4517 case SIGFPE: 4518 case SIGPIPE: 4519 case SIGILL: 4520 case SIGXFSZ: 4521 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler); 4522 break; 4523 4524 case SHUTDOWN1_SIGNAL: 4525 case SHUTDOWN2_SIGNAL: 4526 case SHUTDOWN3_SIGNAL: 4527 case BREAK_SIGNAL: 4528 jvmHandler = (address)user_handler(); 4529 break; 4530 4531 case INTERRUPT_SIGNAL: 4532 jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL); 4533 break; 4534 4535 default: 4536 if (sig == SR_signum) { 4537 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler); 4538 } else { 4539 return; 4540 } 4541 break; 4542 } 4543 4544 if (thisHandler != jvmHandler) { 4545 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN)); 4546 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN)); 4547 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN)); 4548 // No need to check this sig any longer 4549 sigaddset(&check_signal_done, sig); 4550 // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN 4551 if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) { 4552 tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell", 4553 exception_name(sig, buf, O_BUFLEN)); 4554 } 4555 } else if(os::Linux::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Linux::get_our_sigflags(sig)) { 4556 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN)); 4557 tty->print("expected:" PTR32_FORMAT, os::Linux::get_our_sigflags(sig)); 4558 tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags); 4559 // No need to check this sig any longer 4560 sigaddset(&check_signal_done, sig); 4561 } 4562 4563 // Dump all the signal 4564 if (sigismember(&check_signal_done, sig)) { 4565 print_signal_handlers(tty, buf, O_BUFLEN); 4566 } 4567 } 4568 4569 extern void report_error(char* file_name, int line_no, char* title, 4570 char* format, ...); 4571 4572 extern bool signal_name(int signo, char* buf, size_t len); 4573 4574 const char* os::exception_name(int exception_code, char* buf, size_t size) { 4575 if (0 < exception_code && exception_code <= SIGRTMAX) { 4576 // signal 4577 if (!signal_name(exception_code, buf, size)) { 4578 jio_snprintf(buf, size, "SIG%d", exception_code); 4579 } 4580 return buf; 4581 } else { 4582 return NULL; 4583 } 4584 } 4585 4586 // this is called _before_ the most of global arguments have been parsed 4587 void os::init(void) { 4588 char dummy; // used to get a guess on initial stack address 4589 // first_hrtime = gethrtime(); 4590 4591 // With LinuxThreads the JavaMain thread pid (primordial thread) 4592 // is different than the pid of the java launcher thread. 4593 // So, on Linux, the launcher thread pid is passed to the VM 4594 // via the sun.java.launcher.pid property. 4595 // Use this property instead of getpid() if it was correctly passed. 4596 // See bug 6351349. 4597 pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid(); 4598 4599 _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid(); 4600 4601 clock_tics_per_sec = sysconf(_SC_CLK_TCK); 4602 4603 init_random(1234567); 4604 4605 ThreadCritical::initialize(); 4606 4607 Linux::set_page_size(sysconf(_SC_PAGESIZE)); 4608 if (Linux::page_size() == -1) { 4609 fatal(err_msg("os_linux.cpp: os::init: sysconf failed (%s)", 4610 strerror(errno))); 4611 } 4612 init_page_sizes((size_t) Linux::page_size()); 4613 4614 Linux::initialize_system_info(); 4615 4616 // main_thread points to the aboriginal thread 4617 Linux::_main_thread = pthread_self(); 4618 4619 Linux::clock_init(); 4620 initial_time_count = javaTimeNanos(); 4621 4622 // pthread_condattr initialization for monotonic clock 4623 int status; 4624 pthread_condattr_t* _condattr = os::Linux::condAttr(); 4625 if ((status = pthread_condattr_init(_condattr)) != 0) { 4626 fatal(err_msg("pthread_condattr_init: %s", strerror(status))); 4627 } 4628 // Only set the clock if CLOCK_MONOTONIC is available 4629 if (os::supports_monotonic_clock()) { 4630 if ((status = pthread_condattr_setclock(_condattr, CLOCK_MONOTONIC)) != 0) { 4631 if (status == EINVAL) { 4632 warning("Unable to use monotonic clock with relative timed-waits" \ 4633 " - changes to the time-of-day clock may have adverse affects"); 4634 } else { 4635 fatal(err_msg("pthread_condattr_setclock: %s", strerror(status))); 4636 } 4637 } 4638 } 4639 // else it defaults to CLOCK_REALTIME 4640 4641 // If the pagesize of the VM is greater than 8K determine the appropriate 4642 // number of initial guard pages. The user can change this with the 4643 // command line arguments, if needed. 4644 if (vm_page_size() > (int)Linux::vm_default_page_size()) { 4645 StackYellowPages = 1; 4646 StackRedPages = 1; 4647 StackShadowPages = round_to((StackShadowPages*Linux::vm_default_page_size()), vm_page_size()) / vm_page_size(); 4648 } 4649 4650 // retrieve entry point for pthread_setname_np 4651 Linux::_pthread_setname_np = 4652 (int(*)(pthread_t, const char*))dlsym(RTLD_DEFAULT, "pthread_setname_np"); 4653 4654 } 4655 4656 // To install functions for atexit system call 4657 extern "C" { 4658 static void perfMemory_exit_helper() { 4659 perfMemory_exit(); 4660 } 4661 } 4662 4663 // this is called _after_ the global arguments have been parsed 4664 jint os::init_2(void) { 4665 Linux::fast_thread_clock_init(); 4666 4667 // Allocate a single page and mark it as readable for safepoint polling 4668 address polling_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 4669 guarantee(polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page"); 4670 4671 os::set_polling_page(polling_page); 4672 4673 #ifndef PRODUCT 4674 if (Verbose && PrintMiscellaneous) { 4675 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", 4676 (intptr_t)polling_page); 4677 } 4678 #endif 4679 4680 if (!UseMembar) { 4681 address mem_serialize_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 4682 guarantee(mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page"); 4683 os::set_memory_serialize_page(mem_serialize_page); 4684 4685 #ifndef PRODUCT 4686 if (Verbose && PrintMiscellaneous) { 4687 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", 4688 (intptr_t)mem_serialize_page); 4689 } 4690 #endif 4691 } 4692 4693 // initialize suspend/resume support - must do this before signal_sets_init() 4694 if (SR_initialize() != 0) { 4695 perror("SR_initialize failed"); 4696 return JNI_ERR; 4697 } 4698 4699 Linux::signal_sets_init(); 4700 Linux::install_signal_handlers(); 4701 4702 // Check minimum allowable stack size for thread creation and to initialize 4703 // the java system classes, including StackOverflowError - depends on page 4704 // size. Add a page for compiler2 recursion in main thread. 4705 // Add in 2*BytesPerWord times page size to account for VM stack during 4706 // class initialization depending on 32 or 64 bit VM. 4707 os::Linux::min_stack_allowed = MAX2(os::Linux::min_stack_allowed, 4708 (size_t)(StackYellowPages+StackRedPages+StackShadowPages) * Linux::page_size() + 4709 (2*BytesPerWord COMPILER2_PRESENT(+1)) * Linux::vm_default_page_size()); 4710 4711 size_t threadStackSizeInBytes = ThreadStackSize * K; 4712 if (threadStackSizeInBytes != 0 && 4713 threadStackSizeInBytes < os::Linux::min_stack_allowed) { 4714 tty->print_cr("\nThe stack size specified is too small, " 4715 "Specify at least %dk", 4716 os::Linux::min_stack_allowed/ K); 4717 return JNI_ERR; 4718 } 4719 4720 // Make the stack size a multiple of the page size so that 4721 // the yellow/red zones can be guarded. 4722 JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes, 4723 vm_page_size())); 4724 4725 Linux::capture_initial_stack(JavaThread::stack_size_at_create()); 4726 4727 #if defined(IA32) 4728 workaround_expand_exec_shield_cs_limit(); 4729 #endif 4730 4731 Linux::libpthread_init(); 4732 if (PrintMiscellaneous && (Verbose || WizardMode)) { 4733 tty->print_cr("[HotSpot is running with %s, %s(%s)]\n", 4734 Linux::glibc_version(), Linux::libpthread_version(), 4735 Linux::is_floating_stack() ? "floating stack" : "fixed stack"); 4736 } 4737 4738 if (UseNUMA) { 4739 if (!Linux::libnuma_init()) { 4740 UseNUMA = false; 4741 } else { 4742 if ((Linux::numa_max_node() < 1)) { 4743 // There's only one node(they start from 0), disable NUMA. 4744 UseNUMA = false; 4745 } 4746 } 4747 // With SHM and HugeTLBFS large pages we cannot uncommit a page, so there's no way 4748 // we can make the adaptive lgrp chunk resizing work. If the user specified 4749 // both UseNUMA and UseLargePages (or UseSHM/UseHugeTLBFS) on the command line - warn and 4750 // disable adaptive resizing. 4751 if (UseNUMA && UseLargePages && !can_commit_large_page_memory()) { 4752 if (FLAG_IS_DEFAULT(UseNUMA)) { 4753 UseNUMA = false; 4754 } else { 4755 if (FLAG_IS_DEFAULT(UseLargePages) && 4756 FLAG_IS_DEFAULT(UseSHM) && 4757 FLAG_IS_DEFAULT(UseHugeTLBFS)) { 4758 UseLargePages = false; 4759 } else if (UseAdaptiveSizePolicy || UseAdaptiveNUMAChunkSizing) { 4760 warning("UseNUMA is not fully compatible with SHM/HugeTLBFS large pages, disabling adaptive resizing (-XX:-UseAdaptiveSizePolicy -XX:-UseAdaptiveNUMAChunkSizing)"); 4761 UseAdaptiveSizePolicy = false; 4762 UseAdaptiveNUMAChunkSizing = false; 4763 } 4764 } 4765 } 4766 if (!UseNUMA && ForceNUMA) { 4767 UseNUMA = true; 4768 } 4769 } 4770 4771 if (MaxFDLimit) { 4772 // set the number of file descriptors to max. print out error 4773 // if getrlimit/setrlimit fails but continue regardless. 4774 struct rlimit nbr_files; 4775 int status = getrlimit(RLIMIT_NOFILE, &nbr_files); 4776 if (status != 0) { 4777 if (PrintMiscellaneous && (Verbose || WizardMode)) { 4778 perror("os::init_2 getrlimit failed"); 4779 } 4780 } else { 4781 nbr_files.rlim_cur = nbr_files.rlim_max; 4782 status = setrlimit(RLIMIT_NOFILE, &nbr_files); 4783 if (status != 0) { 4784 if (PrintMiscellaneous && (Verbose || WizardMode)) { 4785 perror("os::init_2 setrlimit failed"); 4786 } 4787 } 4788 } 4789 } 4790 4791 // Initialize lock used to serialize thread creation (see os::create_thread) 4792 Linux::set_createThread_lock(new Mutex(Mutex::leaf, "createThread_lock", false)); 4793 4794 // at-exit methods are called in the reverse order of their registration. 4795 // atexit functions are called on return from main or as a result of a 4796 // call to exit(3C). There can be only 32 of these functions registered 4797 // and atexit() does not set errno. 4798 4799 if (PerfAllowAtExitRegistration) { 4800 // only register atexit functions if PerfAllowAtExitRegistration is set. 4801 // atexit functions can be delayed until process exit time, which 4802 // can be problematic for embedded VM situations. Embedded VMs should 4803 // call DestroyJavaVM() to assure that VM resources are released. 4804 4805 // note: perfMemory_exit_helper atexit function may be removed in 4806 // the future if the appropriate cleanup code can be added to the 4807 // VM_Exit VMOperation's doit method. 4808 if (atexit(perfMemory_exit_helper) != 0) { 4809 warning("os::init_2 atexit(perfMemory_exit_helper) failed"); 4810 } 4811 } 4812 4813 // initialize thread priority policy 4814 prio_init(); 4815 4816 return JNI_OK; 4817 } 4818 4819 // Mark the polling page as unreadable 4820 void os::make_polling_page_unreadable(void) { 4821 if (!guard_memory((char*)_polling_page, Linux::page_size())) { 4822 fatal("Could not disable polling page"); 4823 } 4824 } 4825 4826 // Mark the polling page as readable 4827 void os::make_polling_page_readable(void) { 4828 if (!linux_mprotect((char *)_polling_page, Linux::page_size(), PROT_READ)) { 4829 fatal("Could not enable polling page"); 4830 } 4831 } 4832 4833 int os::active_processor_count() { 4834 // Linux doesn't yet have a (official) notion of processor sets, 4835 // so just return the number of online processors. 4836 int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN); 4837 assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check"); 4838 return online_cpus; 4839 } 4840 4841 void os::set_native_thread_name(const char *name) { 4842 if (Linux::_pthread_setname_np) { 4843 char buf [16]; // according to glibc manpage, 16 chars incl. '/0' 4844 snprintf(buf, sizeof(buf), "%s", name); 4845 buf[sizeof(buf) - 1] = '\0'; 4846 const int rc = Linux::_pthread_setname_np(pthread_self(), buf); 4847 // ERANGE should not happen; all other errors should just be ignored. 4848 assert(rc != ERANGE, "pthread_setname_np failed"); 4849 } 4850 } 4851 4852 bool os::distribute_processes(uint length, uint* distribution) { 4853 // Not yet implemented. 4854 return false; 4855 } 4856 4857 bool os::bind_to_processor(uint processor_id) { 4858 // Not yet implemented. 4859 return false; 4860 } 4861 4862 /// 4863 4864 void os::SuspendedThreadTask::internal_do_task() { 4865 if (do_suspend(_thread->osthread())) { 4866 SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext()); 4867 do_task(context); 4868 do_resume(_thread->osthread()); 4869 } 4870 } 4871 4872 class PcFetcher : public os::SuspendedThreadTask { 4873 public: 4874 PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {} 4875 ExtendedPC result(); 4876 protected: 4877 void do_task(const os::SuspendedThreadTaskContext& context); 4878 private: 4879 ExtendedPC _epc; 4880 }; 4881 4882 ExtendedPC PcFetcher::result() { 4883 guarantee(is_done(), "task is not done yet."); 4884 return _epc; 4885 } 4886 4887 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) { 4888 Thread* thread = context.thread(); 4889 OSThread* osthread = thread->osthread(); 4890 if (osthread->ucontext() != NULL) { 4891 _epc = os::Linux::ucontext_get_pc((ucontext_t *) context.ucontext()); 4892 } else { 4893 // NULL context is unexpected, double-check this is the VMThread 4894 guarantee(thread->is_VM_thread(), "can only be called for VMThread"); 4895 } 4896 } 4897 4898 // Suspends the target using the signal mechanism and then grabs the PC before 4899 // resuming the target. Used by the flat-profiler only 4900 ExtendedPC os::get_thread_pc(Thread* thread) { 4901 // Make sure that it is called by the watcher for the VMThread 4902 assert(Thread::current()->is_Watcher_thread(), "Must be watcher"); 4903 assert(thread->is_VM_thread(), "Can only be called for VMThread"); 4904 4905 PcFetcher fetcher(thread); 4906 fetcher.run(); 4907 return fetcher.result(); 4908 } 4909 4910 int os::Linux::safe_cond_timedwait(pthread_cond_t *_cond, 4911 pthread_mutex_t *_mutex, 4912 const struct timespec *_abstime) { 4913 if (is_NPTL()) { 4914 return pthread_cond_timedwait(_cond, _mutex, _abstime); 4915 } else { 4916 // 6292965: LinuxThreads pthread_cond_timedwait() resets FPU control 4917 // word back to default 64bit precision if condvar is signaled. Java 4918 // wants 53bit precision. Save and restore current value. 4919 int fpu = get_fpu_control_word(); 4920 int status = pthread_cond_timedwait(_cond, _mutex, _abstime); 4921 set_fpu_control_word(fpu); 4922 return status; 4923 } 4924 } 4925 4926 //////////////////////////////////////////////////////////////////////////////// 4927 // debug support 4928 4929 bool os::find(address addr, outputStream* st) { 4930 Dl_info dlinfo; 4931 memset(&dlinfo, 0, sizeof(dlinfo)); 4932 if (dladdr(addr, &dlinfo) != 0) { 4933 st->print(PTR_FORMAT ": ", addr); 4934 if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) { 4935 st->print("%s+%#x", dlinfo.dli_sname, 4936 addr - (intptr_t)dlinfo.dli_saddr); 4937 } else if (dlinfo.dli_fbase != NULL) { 4938 st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase); 4939 } else { 4940 st->print("<absolute address>"); 4941 } 4942 if (dlinfo.dli_fname != NULL) { 4943 st->print(" in %s", dlinfo.dli_fname); 4944 } 4945 if (dlinfo.dli_fbase != NULL) { 4946 st->print(" at " PTR_FORMAT, dlinfo.dli_fbase); 4947 } 4948 st->cr(); 4949 4950 if (Verbose) { 4951 // decode some bytes around the PC 4952 address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size()); 4953 address end = clamp_address_in_page(addr+40, addr, os::vm_page_size()); 4954 address lowest = (address) dlinfo.dli_sname; 4955 if (!lowest) lowest = (address) dlinfo.dli_fbase; 4956 if (begin < lowest) begin = lowest; 4957 Dl_info dlinfo2; 4958 if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr 4959 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) { 4960 end = (address) dlinfo2.dli_saddr; 4961 } 4962 Disassembler::decode(begin, end, st); 4963 } 4964 return true; 4965 } 4966 return false; 4967 } 4968 4969 //////////////////////////////////////////////////////////////////////////////// 4970 // misc 4971 4972 // This does not do anything on Linux. This is basically a hook for being 4973 // able to use structured exception handling (thread-local exception filters) 4974 // on, e.g., Win32. 4975 void 4976 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method, 4977 JavaCallArguments* args, Thread* thread) { 4978 f(value, method, args, thread); 4979 } 4980 4981 void os::print_statistics() { 4982 } 4983 4984 int os::message_box(const char* title, const char* message) { 4985 int i; 4986 fdStream err(defaultStream::error_fd()); 4987 for (i = 0; i < 78; i++) err.print_raw("="); 4988 err.cr(); 4989 err.print_raw_cr(title); 4990 for (i = 0; i < 78; i++) err.print_raw("-"); 4991 err.cr(); 4992 err.print_raw_cr(message); 4993 for (i = 0; i < 78; i++) err.print_raw("="); 4994 err.cr(); 4995 4996 char buf[16]; 4997 // Prevent process from exiting upon "read error" without consuming all CPU 4998 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); } 4999 5000 return buf[0] == 'y' || buf[0] == 'Y'; 5001 } 5002 5003 int os::stat(const char *path, struct stat *sbuf) { 5004 char pathbuf[MAX_PATH]; 5005 if (strlen(path) > MAX_PATH - 1) { 5006 errno = ENAMETOOLONG; 5007 return -1; 5008 } 5009 os::native_path(strcpy(pathbuf, path)); 5010 return ::stat(pathbuf, sbuf); 5011 } 5012 5013 bool os::check_heap(bool force) { 5014 return true; 5015 } 5016 5017 // Is a (classpath) directory empty? 5018 bool os::dir_is_empty(const char* path) { 5019 DIR *dir = NULL; 5020 struct dirent *ptr; 5021 5022 dir = opendir(path); 5023 if (dir == NULL) return true; 5024 5025 // Scan the directory 5026 bool result = true; 5027 char buf[sizeof(struct dirent) + MAX_PATH]; 5028 while (result && (ptr = ::readdir(dir)) != NULL) { 5029 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { 5030 result = false; 5031 } 5032 } 5033 closedir(dir); 5034 return result; 5035 } 5036 5037 // This code originates from JDK's sysOpen and open64_w 5038 // from src/solaris/hpi/src/system_md.c 5039 5040 int os::open(const char *path, int oflag, int mode) { 5041 if (strlen(path) > MAX_PATH - 1) { 5042 errno = ENAMETOOLONG; 5043 return -1; 5044 } 5045 5046 // All file descriptors that are opened in the Java process and not 5047 // specifically destined for a subprocess should have the close-on-exec 5048 // flag set. If we don't set it, then careless 3rd party native code 5049 // might fork and exec without closing all appropriate file descriptors 5050 // (e.g. as we do in closeDescriptors in UNIXProcess.c), and this in 5051 // turn might: 5052 // 5053 // - cause end-of-file to fail to be detected on some file 5054 // descriptors, resulting in mysterious hangs, or 5055 // 5056 // - might cause an fopen in the subprocess to fail on a system 5057 // suffering from bug 1085341. 5058 // 5059 // (Yes, the default setting of the close-on-exec flag is a Unix 5060 // design flaw) 5061 // 5062 // See: 5063 // 1085341: 32-bit stdio routines should support file descriptors >255 5064 // 4843136: (process) pipe file descriptor from Runtime.exec not being closed 5065 // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9 5066 // 5067 // Modern Linux kernels (after 2.6.23 2007) support O_CLOEXEC with open(). 5068 // O_CLOEXEC is preferable to using FD_CLOEXEC on an open file descriptor 5069 // because it saves a system call and removes a small window where the flag 5070 // is unset. On ancient Linux kernels the O_CLOEXEC flag will be ignored 5071 // and we fall back to using FD_CLOEXEC (see below). 5072 #ifdef O_CLOEXEC 5073 oflag |= O_CLOEXEC; 5074 #endif 5075 5076 int fd = ::open64(path, oflag, mode); 5077 if (fd == -1) return -1; 5078 5079 //If the open succeeded, the file might still be a directory 5080 { 5081 struct stat64 buf64; 5082 int ret = ::fstat64(fd, &buf64); 5083 int st_mode = buf64.st_mode; 5084 5085 if (ret != -1) { 5086 if ((st_mode & S_IFMT) == S_IFDIR) { 5087 errno = EISDIR; 5088 ::close(fd); 5089 return -1; 5090 } 5091 } else { 5092 ::close(fd); 5093 return -1; 5094 } 5095 } 5096 5097 #ifdef FD_CLOEXEC 5098 // Validate that the use of the O_CLOEXEC flag on open above worked. 5099 // With recent kernels, we will perform this check exactly once. 5100 static sig_atomic_t O_CLOEXEC_is_known_to_work = 0; 5101 if (!O_CLOEXEC_is_known_to_work) { 5102 int flags = ::fcntl(fd, F_GETFD); 5103 if (flags != -1) { 5104 if ((flags & FD_CLOEXEC) != 0) 5105 O_CLOEXEC_is_known_to_work = 1; 5106 else 5107 ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC); 5108 } 5109 } 5110 #endif 5111 5112 return fd; 5113 } 5114 5115 5116 // create binary file, rewriting existing file if required 5117 int os::create_binary_file(const char* path, bool rewrite_existing) { 5118 int oflags = O_WRONLY | O_CREAT; 5119 if (!rewrite_existing) { 5120 oflags |= O_EXCL; 5121 } 5122 return ::open64(path, oflags, S_IREAD | S_IWRITE); 5123 } 5124 5125 // return current position of file pointer 5126 jlong os::current_file_offset(int fd) { 5127 return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR); 5128 } 5129 5130 // move file pointer to the specified offset 5131 jlong os::seek_to_file_offset(int fd, jlong offset) { 5132 return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET); 5133 } 5134 5135 // This code originates from JDK's sysAvailable 5136 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c 5137 5138 int os::available(int fd, jlong *bytes) { 5139 jlong cur, end; 5140 int mode; 5141 struct stat64 buf64; 5142 5143 if (::fstat64(fd, &buf64) >= 0) { 5144 mode = buf64.st_mode; 5145 if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) { 5146 // XXX: is the following call interruptible? If so, this might 5147 // need to go through the INTERRUPT_IO() wrapper as for other 5148 // blocking, interruptible calls in this file. 5149 int n; 5150 if (::ioctl(fd, FIONREAD, &n) >= 0) { 5151 *bytes = n; 5152 return 1; 5153 } 5154 } 5155 } 5156 if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) { 5157 return 0; 5158 } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) { 5159 return 0; 5160 } else if (::lseek64(fd, cur, SEEK_SET) == -1) { 5161 return 0; 5162 } 5163 *bytes = end - cur; 5164 return 1; 5165 } 5166 5167 // Map a block of memory. 5168 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset, 5169 char *addr, size_t bytes, bool read_only, 5170 bool allow_exec) { 5171 int prot; 5172 int flags = MAP_PRIVATE; 5173 5174 if (read_only) { 5175 prot = PROT_READ; 5176 } else { 5177 prot = PROT_READ | PROT_WRITE; 5178 } 5179 5180 if (allow_exec) { 5181 prot |= PROT_EXEC; 5182 } 5183 5184 if (addr != NULL) { 5185 flags |= MAP_FIXED; 5186 } 5187 5188 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags, 5189 fd, file_offset); 5190 if (mapped_address == MAP_FAILED) { 5191 return NULL; 5192 } 5193 return mapped_address; 5194 } 5195 5196 5197 // Remap a block of memory. 5198 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset, 5199 char *addr, size_t bytes, bool read_only, 5200 bool allow_exec) { 5201 // same as map_memory() on this OS 5202 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only, 5203 allow_exec); 5204 } 5205 5206 5207 // Unmap a block of memory. 5208 bool os::pd_unmap_memory(char* addr, size_t bytes) { 5209 return munmap(addr, bytes) == 0; 5210 } 5211 5212 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time); 5213 5214 static clockid_t thread_cpu_clockid(Thread* thread) { 5215 pthread_t tid = thread->osthread()->pthread_id(); 5216 clockid_t clockid; 5217 5218 // Get thread clockid 5219 int rc = os::Linux::pthread_getcpuclockid(tid, &clockid); 5220 assert(rc == 0, "pthread_getcpuclockid is expected to return 0 code"); 5221 return clockid; 5222 } 5223 5224 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool) 5225 // are used by JVM M&M and JVMTI to get user+sys or user CPU time 5226 // of a thread. 5227 // 5228 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns 5229 // the fast estimate available on the platform. 5230 5231 jlong os::current_thread_cpu_time() { 5232 if (os::Linux::supports_fast_thread_cpu_time()) { 5233 return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID); 5234 } else { 5235 // return user + sys since the cost is the same 5236 return slow_thread_cpu_time(Thread::current(), true /* user + sys */); 5237 } 5238 } 5239 5240 jlong os::thread_cpu_time(Thread* thread) { 5241 // consistent with what current_thread_cpu_time() returns 5242 if (os::Linux::supports_fast_thread_cpu_time()) { 5243 return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread)); 5244 } else { 5245 return slow_thread_cpu_time(thread, true /* user + sys */); 5246 } 5247 } 5248 5249 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) { 5250 if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) { 5251 return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID); 5252 } else { 5253 return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time); 5254 } 5255 } 5256 5257 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { 5258 if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) { 5259 return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread)); 5260 } else { 5261 return slow_thread_cpu_time(thread, user_sys_cpu_time); 5262 } 5263 } 5264 5265 // -1 on error. 5266 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { 5267 pid_t tid = thread->osthread()->thread_id(); 5268 char *s; 5269 char stat[2048]; 5270 int statlen; 5271 char proc_name[64]; 5272 int count; 5273 long sys_time, user_time; 5274 char cdummy; 5275 int idummy; 5276 long ldummy; 5277 FILE *fp; 5278 5279 snprintf(proc_name, 64, "/proc/self/task/%d/stat", tid); 5280 fp = fopen(proc_name, "r"); 5281 if (fp == NULL) return -1; 5282 statlen = fread(stat, 1, 2047, fp); 5283 stat[statlen] = '\0'; 5284 fclose(fp); 5285 5286 // Skip pid and the command string. Note that we could be dealing with 5287 // weird command names, e.g. user could decide to rename java launcher 5288 // to "java 1.4.2 :)", then the stat file would look like 5289 // 1234 (java 1.4.2 :)) R ... ... 5290 // We don't really need to know the command string, just find the last 5291 // occurrence of ")" and then start parsing from there. See bug 4726580. 5292 s = strrchr(stat, ')'); 5293 if (s == NULL) return -1; 5294 5295 // Skip blank chars 5296 do { s++; } while (s && isspace(*s)); 5297 5298 count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu", 5299 &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy, 5300 &ldummy, &ldummy, &ldummy, &ldummy, &ldummy, 5301 &user_time, &sys_time); 5302 if (count != 13) return -1; 5303 if (user_sys_cpu_time) { 5304 return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec); 5305 } else { 5306 return (jlong)user_time * (1000000000 / clock_tics_per_sec); 5307 } 5308 } 5309 5310 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 5311 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 5312 info_ptr->may_skip_backward = false; // elapsed time not wall time 5313 info_ptr->may_skip_forward = false; // elapsed time not wall time 5314 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 5315 } 5316 5317 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 5318 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 5319 info_ptr->may_skip_backward = false; // elapsed time not wall time 5320 info_ptr->may_skip_forward = false; // elapsed time not wall time 5321 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 5322 } 5323 5324 bool os::is_thread_cpu_time_supported() { 5325 return true; 5326 } 5327 5328 // System loadavg support. Returns -1 if load average cannot be obtained. 5329 // Linux doesn't yet have a (official) notion of processor sets, 5330 // so just return the system wide load average. 5331 int os::loadavg(double loadavg[], int nelem) { 5332 return ::getloadavg(loadavg, nelem); 5333 } 5334 5335 void os::pause() { 5336 char filename[MAX_PATH]; 5337 if (PauseAtStartupFile && PauseAtStartupFile[0]) { 5338 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile); 5339 } else { 5340 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id()); 5341 } 5342 5343 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); 5344 if (fd != -1) { 5345 struct stat buf; 5346 ::close(fd); 5347 while (::stat(filename, &buf) == 0) { 5348 (void)::poll(NULL, 0, 100); 5349 } 5350 } else { 5351 jio_fprintf(stderr, 5352 "Could not open pause file '%s', continuing immediately.\n", filename); 5353 } 5354 } 5355 5356 5357 // Refer to the comments in os_solaris.cpp park-unpark. The next two 5358 // comment paragraphs are worth repeating here: 5359 // 5360 // Assumption: 5361 // Only one parker can exist on an event, which is why we allocate 5362 // them per-thread. Multiple unparkers can coexist. 5363 // 5364 // _Event serves as a restricted-range semaphore. 5365 // -1 : thread is blocked, i.e. there is a waiter 5366 // 0 : neutral: thread is running or ready, 5367 // could have been signaled after a wait started 5368 // 1 : signaled - thread is running or ready 5369 // 5370 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can 5371 // hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable. 5372 // For specifics regarding the bug see GLIBC BUGID 261237 : 5373 // http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html. 5374 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future 5375 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar 5376 // is used. (The simple C test-case provided in the GLIBC bug report manifests the 5377 // hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos() 5378 // and monitorenter when we're using 1-0 locking. All those operations may result in 5379 // calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version 5380 // of libpthread avoids the problem, but isn't practical. 5381 // 5382 // Possible remedies: 5383 // 5384 // 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work. 5385 // This is palliative and probabilistic, however. If the thread is preempted 5386 // between the call to compute_abstime() and pthread_cond_timedwait(), more 5387 // than the minimum period may have passed, and the abstime may be stale (in the 5388 // past) resultin in a hang. Using this technique reduces the odds of a hang 5389 // but the JVM is still vulnerable, particularly on heavily loaded systems. 5390 // 5391 // 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead 5392 // of the usual flag-condvar-mutex idiom. The write side of the pipe is set 5393 // NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo) 5394 // reduces to poll()+read(). This works well, but consumes 2 FDs per extant 5395 // thread. 5396 // 5397 // 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread 5398 // that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing 5399 // a timeout request to the chron thread and then blocking via pthread_cond_wait(). 5400 // This also works well. In fact it avoids kernel-level scalability impediments 5401 // on certain platforms that don't handle lots of active pthread_cond_timedwait() 5402 // timers in a graceful fashion. 5403 // 5404 // 4. When the abstime value is in the past it appears that control returns 5405 // correctly from pthread_cond_timedwait(), but the condvar is left corrupt. 5406 // Subsequent timedwait/wait calls may hang indefinitely. Given that, we 5407 // can avoid the problem by reinitializing the condvar -- by cond_destroy() 5408 // followed by cond_init() -- after all calls to pthread_cond_timedwait(). 5409 // It may be possible to avoid reinitialization by checking the return 5410 // value from pthread_cond_timedwait(). In addition to reinitializing the 5411 // condvar we must establish the invariant that cond_signal() is only called 5412 // within critical sections protected by the adjunct mutex. This prevents 5413 // cond_signal() from "seeing" a condvar that's in the midst of being 5414 // reinitialized or that is corrupt. Sadly, this invariant obviates the 5415 // desirable signal-after-unlock optimization that avoids futile context switching. 5416 // 5417 // I'm also concerned that some versions of NTPL might allocate an auxilliary 5418 // structure when a condvar is used or initialized. cond_destroy() would 5419 // release the helper structure. Our reinitialize-after-timedwait fix 5420 // put excessive stress on malloc/free and locks protecting the c-heap. 5421 // 5422 // We currently use (4). See the WorkAroundNTPLTimedWaitHang flag. 5423 // It may be possible to refine (4) by checking the kernel and NTPL verisons 5424 // and only enabling the work-around for vulnerable environments. 5425 5426 // utility to compute the abstime argument to timedwait: 5427 // millis is the relative timeout time 5428 // abstime will be the absolute timeout time 5429 // TODO: replace compute_abstime() with unpackTime() 5430 5431 static struct timespec* compute_abstime(timespec* abstime, jlong millis) { 5432 if (millis < 0) millis = 0; 5433 5434 jlong seconds = millis / 1000; 5435 millis %= 1000; 5436 if (seconds > 50000000) { // see man cond_timedwait(3T) 5437 seconds = 50000000; 5438 } 5439 5440 if (os::supports_monotonic_clock()) { 5441 struct timespec now; 5442 int status = os::Linux::clock_gettime(CLOCK_MONOTONIC, &now); 5443 assert_status(status == 0, status, "clock_gettime"); 5444 abstime->tv_sec = now.tv_sec + seconds; 5445 long nanos = now.tv_nsec + millis * NANOSECS_PER_MILLISEC; 5446 if (nanos >= NANOSECS_PER_SEC) { 5447 abstime->tv_sec += 1; 5448 nanos -= NANOSECS_PER_SEC; 5449 } 5450 abstime->tv_nsec = nanos; 5451 } else { 5452 struct timeval now; 5453 int status = gettimeofday(&now, NULL); 5454 assert(status == 0, "gettimeofday"); 5455 abstime->tv_sec = now.tv_sec + seconds; 5456 long usec = now.tv_usec + millis * 1000; 5457 if (usec >= 1000000) { 5458 abstime->tv_sec += 1; 5459 usec -= 1000000; 5460 } 5461 abstime->tv_nsec = usec * 1000; 5462 } 5463 return abstime; 5464 } 5465 5466 void os::PlatformEvent::park() { // AKA "down()" 5467 // Transitions for _Event: 5468 // -1 => -1 : illegal 5469 // 1 => 0 : pass - return immediately 5470 // 0 => -1 : block; then set _Event to 0 before returning 5471 5472 // Invariant: Only the thread associated with the Event/PlatformEvent 5473 // may call park(). 5474 // TODO: assert that _Assoc != NULL or _Assoc == Self 5475 assert(_nParked == 0, "invariant"); 5476 5477 int v; 5478 for (;;) { 5479 v = _Event; 5480 if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; 5481 } 5482 guarantee(v >= 0, "invariant"); 5483 if (v == 0) { 5484 // Do this the hard way by blocking ... 5485 int status = pthread_mutex_lock(_mutex); 5486 assert_status(status == 0, status, "mutex_lock"); 5487 guarantee(_nParked == 0, "invariant"); 5488 ++_nParked; 5489 while (_Event < 0) { 5490 status = pthread_cond_wait(_cond, _mutex); 5491 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ... 5492 // Treat this the same as if the wait was interrupted 5493 if (status == ETIME) { status = EINTR; } 5494 assert_status(status == 0 || status == EINTR, status, "cond_wait"); 5495 } 5496 --_nParked; 5497 5498 _Event = 0; 5499 status = pthread_mutex_unlock(_mutex); 5500 assert_status(status == 0, status, "mutex_unlock"); 5501 // Paranoia to ensure our locked and lock-free paths interact 5502 // correctly with each other. 5503 OrderAccess::fence(); 5504 } 5505 guarantee(_Event >= 0, "invariant"); 5506 } 5507 5508 int os::PlatformEvent::park(jlong millis) { 5509 // Transitions for _Event: 5510 // -1 => -1 : illegal 5511 // 1 => 0 : pass - return immediately 5512 // 0 => -1 : block; then set _Event to 0 before returning 5513 5514 guarantee(_nParked == 0, "invariant"); 5515 5516 int v; 5517 for (;;) { 5518 v = _Event; 5519 if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; 5520 } 5521 guarantee(v >= 0, "invariant"); 5522 if (v != 0) return OS_OK; 5523 5524 // We do this the hard way, by blocking the thread. 5525 // Consider enforcing a minimum timeout value. 5526 struct timespec abst; 5527 compute_abstime(&abst, millis); 5528 5529 int ret = OS_TIMEOUT; 5530 int status = pthread_mutex_lock(_mutex); 5531 assert_status(status == 0, status, "mutex_lock"); 5532 guarantee(_nParked == 0, "invariant"); 5533 ++_nParked; 5534 5535 // Object.wait(timo) will return because of 5536 // (a) notification 5537 // (b) timeout 5538 // (c) thread.interrupt 5539 // 5540 // Thread.interrupt and object.notify{All} both call Event::set. 5541 // That is, we treat thread.interrupt as a special case of notification. 5542 // We ignore spurious OS wakeups unless FilterSpuriousWakeups is false. 5543 // We assume all ETIME returns are valid. 5544 // 5545 // TODO: properly differentiate simultaneous notify+interrupt. 5546 // In that case, we should propagate the notify to another waiter. 5547 5548 while (_Event < 0) { 5549 status = os::Linux::safe_cond_timedwait(_cond, _mutex, &abst); 5550 if (status != 0 && WorkAroundNPTLTimedWaitHang) { 5551 pthread_cond_destroy(_cond); 5552 pthread_cond_init(_cond, os::Linux::condAttr()); 5553 } 5554 assert_status(status == 0 || status == EINTR || 5555 status == ETIME || status == ETIMEDOUT, 5556 status, "cond_timedwait"); 5557 if (!FilterSpuriousWakeups) break; // previous semantics 5558 if (status == ETIME || status == ETIMEDOUT) break; 5559 // We consume and ignore EINTR and spurious wakeups. 5560 } 5561 --_nParked; 5562 if (_Event >= 0) { 5563 ret = OS_OK; 5564 } 5565 _Event = 0; 5566 status = pthread_mutex_unlock(_mutex); 5567 assert_status(status == 0, status, "mutex_unlock"); 5568 assert(_nParked == 0, "invariant"); 5569 // Paranoia to ensure our locked and lock-free paths interact 5570 // correctly with each other. 5571 OrderAccess::fence(); 5572 return ret; 5573 } 5574 5575 void os::PlatformEvent::unpark() { 5576 // Transitions for _Event: 5577 // 0 => 1 : just return 5578 // 1 => 1 : just return 5579 // -1 => either 0 or 1; must signal target thread 5580 // That is, we can safely transition _Event from -1 to either 5581 // 0 or 1. 5582 // See also: "Semaphores in Plan 9" by Mullender & Cox 5583 // 5584 // Note: Forcing a transition from "-1" to "1" on an unpark() means 5585 // that it will take two back-to-back park() calls for the owning 5586 // thread to block. This has the benefit of forcing a spurious return 5587 // from the first park() call after an unpark() call which will help 5588 // shake out uses of park() and unpark() without condition variables. 5589 5590 if (Atomic::xchg(1, &_Event) >= 0) return; 5591 5592 // Wait for the thread associated with the event to vacate 5593 int status = pthread_mutex_lock(_mutex); 5594 assert_status(status == 0, status, "mutex_lock"); 5595 int AnyWaiters = _nParked; 5596 assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant"); 5597 if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) { 5598 AnyWaiters = 0; 5599 pthread_cond_signal(_cond); 5600 } 5601 status = pthread_mutex_unlock(_mutex); 5602 assert_status(status == 0, status, "mutex_unlock"); 5603 if (AnyWaiters != 0) { 5604 // Note that we signal() *after* dropping the lock for "immortal" Events. 5605 // This is safe and avoids a common class of futile wakeups. In rare 5606 // circumstances this can cause a thread to return prematurely from 5607 // cond_{timed}wait() but the spurious wakeup is benign and the victim 5608 // will simply re-test the condition and re-park itself. 5609 // This provides particular benefit if the underlying platform does not 5610 // provide wait morphing. 5611 status = pthread_cond_signal(_cond); 5612 assert_status(status == 0, status, "cond_signal"); 5613 } 5614 } 5615 5616 5617 // JSR166 5618 // ------------------------------------------------------- 5619 5620 // The solaris and linux implementations of park/unpark are fairly 5621 // conservative for now, but can be improved. They currently use a 5622 // mutex/condvar pair, plus a a count. 5623 // Park decrements count if > 0, else does a condvar wait. Unpark 5624 // sets count to 1 and signals condvar. Only one thread ever waits 5625 // on the condvar. Contention seen when trying to park implies that someone 5626 // is unparking you, so don't wait. And spurious returns are fine, so there 5627 // is no need to track notifications. 5628 5629 // This code is common to linux and solaris and will be moved to a 5630 // common place in dolphin. 5631 // 5632 // The passed in time value is either a relative time in nanoseconds 5633 // or an absolute time in milliseconds. Either way it has to be unpacked 5634 // into suitable seconds and nanoseconds components and stored in the 5635 // given timespec structure. 5636 // Given time is a 64-bit value and the time_t used in the timespec is only 5637 // a signed-32-bit value (except on 64-bit Linux) we have to watch for 5638 // overflow if times way in the future are given. Further on Solaris versions 5639 // prior to 10 there is a restriction (see cond_timedwait) that the specified 5640 // number of seconds, in abstime, is less than current_time + 100,000,000. 5641 // As it will be 28 years before "now + 100000000" will overflow we can 5642 // ignore overflow and just impose a hard-limit on seconds using the value 5643 // of "now + 100,000,000". This places a limit on the timeout of about 3.17 5644 // years from "now". 5645 5646 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) { 5647 assert(time > 0, "convertTime"); 5648 time_t max_secs = 0; 5649 5650 if (!os::supports_monotonic_clock() || isAbsolute) { 5651 struct timeval now; 5652 int status = gettimeofday(&now, NULL); 5653 assert(status == 0, "gettimeofday"); 5654 5655 max_secs = now.tv_sec + MAX_SECS; 5656 5657 if (isAbsolute) { 5658 jlong secs = time / 1000; 5659 if (secs > max_secs) { 5660 absTime->tv_sec = max_secs; 5661 } else { 5662 absTime->tv_sec = secs; 5663 } 5664 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC; 5665 } else { 5666 jlong secs = time / NANOSECS_PER_SEC; 5667 if (secs >= MAX_SECS) { 5668 absTime->tv_sec = max_secs; 5669 absTime->tv_nsec = 0; 5670 } else { 5671 absTime->tv_sec = now.tv_sec + secs; 5672 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000; 5673 if (absTime->tv_nsec >= NANOSECS_PER_SEC) { 5674 absTime->tv_nsec -= NANOSECS_PER_SEC; 5675 ++absTime->tv_sec; // note: this must be <= max_secs 5676 } 5677 } 5678 } 5679 } else { 5680 // must be relative using monotonic clock 5681 struct timespec now; 5682 int status = os::Linux::clock_gettime(CLOCK_MONOTONIC, &now); 5683 assert_status(status == 0, status, "clock_gettime"); 5684 max_secs = now.tv_sec + MAX_SECS; 5685 jlong secs = time / NANOSECS_PER_SEC; 5686 if (secs >= MAX_SECS) { 5687 absTime->tv_sec = max_secs; 5688 absTime->tv_nsec = 0; 5689 } else { 5690 absTime->tv_sec = now.tv_sec + secs; 5691 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_nsec; 5692 if (absTime->tv_nsec >= NANOSECS_PER_SEC) { 5693 absTime->tv_nsec -= NANOSECS_PER_SEC; 5694 ++absTime->tv_sec; // note: this must be <= max_secs 5695 } 5696 } 5697 } 5698 assert(absTime->tv_sec >= 0, "tv_sec < 0"); 5699 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs"); 5700 assert(absTime->tv_nsec >= 0, "tv_nsec < 0"); 5701 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec"); 5702 } 5703 5704 void Parker::park(bool isAbsolute, jlong time) { 5705 // Ideally we'd do something useful while spinning, such 5706 // as calling unpackTime(). 5707 5708 // Optional fast-path check: 5709 // Return immediately if a permit is available. 5710 // We depend on Atomic::xchg() having full barrier semantics 5711 // since we are doing a lock-free update to _counter. 5712 if (Atomic::xchg(0, &_counter) > 0) return; 5713 5714 Thread* thread = Thread::current(); 5715 assert(thread->is_Java_thread(), "Must be JavaThread"); 5716 JavaThread *jt = (JavaThread *)thread; 5717 5718 // Optional optimization -- avoid state transitions if there's an interrupt pending. 5719 // Check interrupt before trying to wait 5720 if (Thread::is_interrupted(thread, false)) { 5721 return; 5722 } 5723 5724 // Next, demultiplex/decode time arguments 5725 timespec absTime; 5726 if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all 5727 return; 5728 } 5729 if (time > 0) { 5730 unpackTime(&absTime, isAbsolute, time); 5731 } 5732 5733 5734 // Enter safepoint region 5735 // Beware of deadlocks such as 6317397. 5736 // The per-thread Parker:: mutex is a classic leaf-lock. 5737 // In particular a thread must never block on the Threads_lock while 5738 // holding the Parker:: mutex. If safepoints are pending both the 5739 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock. 5740 ThreadBlockInVM tbivm(jt); 5741 5742 // Don't wait if cannot get lock since interference arises from 5743 // unblocking. Also. check interrupt before trying wait 5744 if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) { 5745 return; 5746 } 5747 5748 int status; 5749 if (_counter > 0) { // no wait needed 5750 _counter = 0; 5751 status = pthread_mutex_unlock(_mutex); 5752 assert(status == 0, "invariant"); 5753 // Paranoia to ensure our locked and lock-free paths interact 5754 // correctly with each other and Java-level accesses. 5755 OrderAccess::fence(); 5756 return; 5757 } 5758 5759 #ifdef ASSERT 5760 // Don't catch signals while blocked; let the running threads have the signals. 5761 // (This allows a debugger to break into the running thread.) 5762 sigset_t oldsigs; 5763 sigset_t* allowdebug_blocked = os::Linux::allowdebug_blocked_signals(); 5764 pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs); 5765 #endif 5766 5767 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 5768 jt->set_suspend_equivalent(); 5769 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 5770 5771 assert(_cur_index == -1, "invariant"); 5772 if (time == 0) { 5773 _cur_index = REL_INDEX; // arbitrary choice when not timed 5774 status = pthread_cond_wait(&_cond[_cur_index], _mutex); 5775 } else { 5776 _cur_index = isAbsolute ? ABS_INDEX : REL_INDEX; 5777 status = os::Linux::safe_cond_timedwait(&_cond[_cur_index], _mutex, &absTime); 5778 if (status != 0 && WorkAroundNPTLTimedWaitHang) { 5779 pthread_cond_destroy(&_cond[_cur_index]); 5780 pthread_cond_init(&_cond[_cur_index], isAbsolute ? NULL : os::Linux::condAttr()); 5781 } 5782 } 5783 _cur_index = -1; 5784 assert_status(status == 0 || status == EINTR || 5785 status == ETIME || status == ETIMEDOUT, 5786 status, "cond_timedwait"); 5787 5788 #ifdef ASSERT 5789 pthread_sigmask(SIG_SETMASK, &oldsigs, NULL); 5790 #endif 5791 5792 _counter = 0; 5793 status = pthread_mutex_unlock(_mutex); 5794 assert_status(status == 0, status, "invariant"); 5795 // Paranoia to ensure our locked and lock-free paths interact 5796 // correctly with each other and Java-level accesses. 5797 OrderAccess::fence(); 5798 5799 // If externally suspended while waiting, re-suspend 5800 if (jt->handle_special_suspend_equivalent_condition()) { 5801 jt->java_suspend_self(); 5802 } 5803 } 5804 5805 void Parker::unpark() { 5806 int status = pthread_mutex_lock(_mutex); 5807 assert(status == 0, "invariant"); 5808 const int s = _counter; 5809 _counter = 1; 5810 if (s < 1) { 5811 // thread might be parked 5812 if (_cur_index != -1) { 5813 // thread is definitely parked 5814 if (WorkAroundNPTLTimedWaitHang) { 5815 status = pthread_cond_signal(&_cond[_cur_index]); 5816 assert(status == 0, "invariant"); 5817 status = pthread_mutex_unlock(_mutex); 5818 assert(status == 0, "invariant"); 5819 } else { 5820 status = pthread_mutex_unlock(_mutex); 5821 assert(status == 0, "invariant"); 5822 status = pthread_cond_signal(&_cond[_cur_index]); 5823 assert(status == 0, "invariant"); 5824 } 5825 } else { 5826 pthread_mutex_unlock(_mutex); 5827 assert(status == 0, "invariant"); 5828 } 5829 } else { 5830 pthread_mutex_unlock(_mutex); 5831 assert(status == 0, "invariant"); 5832 } 5833 } 5834 5835 5836 extern char** environ; 5837 5838 // Run the specified command in a separate process. Return its exit value, 5839 // or -1 on failure (e.g. can't fork a new process). 5840 // Unlike system(), this function can be called from signal handler. It 5841 // doesn't block SIGINT et al. 5842 int os::fork_and_exec(char* cmd) { 5843 const char * argv[4] = {"sh", "-c", cmd, NULL}; 5844 5845 pid_t pid = fork(); 5846 5847 if (pid < 0) { 5848 // fork failed 5849 return -1; 5850 5851 } else if (pid == 0) { 5852 // child process 5853 5854 execve("/bin/sh", (char* const*)argv, environ); 5855 5856 // execve failed 5857 _exit(-1); 5858 5859 } else { 5860 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't 5861 // care about the actual exit code, for now. 5862 5863 int status; 5864 5865 // Wait for the child process to exit. This returns immediately if 5866 // the child has already exited. */ 5867 while (waitpid(pid, &status, 0) < 0) { 5868 switch (errno) { 5869 case ECHILD: return 0; 5870 case EINTR: break; 5871 default: return -1; 5872 } 5873 } 5874 5875 if (WIFEXITED(status)) { 5876 // The child exited normally; get its exit code. 5877 return WEXITSTATUS(status); 5878 } else if (WIFSIGNALED(status)) { 5879 // The child exited because of a signal 5880 // The best value to return is 0x80 + signal number, 5881 // because that is what all Unix shells do, and because 5882 // it allows callers to distinguish between process exit and 5883 // process death by signal. 5884 return 0x80 + WTERMSIG(status); 5885 } else { 5886 // Unknown exit code; pass it through 5887 return status; 5888 } 5889 } 5890 } 5891 5892 // is_headless_jre() 5893 // 5894 // Test for the existence of xawt/libmawt.so or libawt_xawt.so 5895 // in order to report if we are running in a headless jre 5896 // 5897 // Since JDK8 xawt/libmawt.so was moved into the same directory 5898 // as libawt.so, and renamed libawt_xawt.so 5899 // 5900 bool os::is_headless_jre() { 5901 struct stat statbuf; 5902 char buf[MAXPATHLEN]; 5903 char libmawtpath[MAXPATHLEN]; 5904 const char *xawtstr = "/xawt/libmawt.so"; 5905 const char *new_xawtstr = "/libawt_xawt.so"; 5906 char *p; 5907 5908 // Get path to libjvm.so 5909 os::jvm_path(buf, sizeof(buf)); 5910 5911 // Get rid of libjvm.so 5912 p = strrchr(buf, '/'); 5913 if (p == NULL) { 5914 return false; 5915 } else { 5916 *p = '\0'; 5917 } 5918 5919 // Get rid of client or server 5920 p = strrchr(buf, '/'); 5921 if (p == NULL) { 5922 return false; 5923 } else { 5924 *p = '\0'; 5925 } 5926 5927 // check xawt/libmawt.so 5928 strcpy(libmawtpath, buf); 5929 strcat(libmawtpath, xawtstr); 5930 if (::stat(libmawtpath, &statbuf) == 0) return false; 5931 5932 // check libawt_xawt.so 5933 strcpy(libmawtpath, buf); 5934 strcat(libmawtpath, new_xawtstr); 5935 if (::stat(libmawtpath, &statbuf) == 0) return false; 5936 5937 return true; 5938 } 5939 5940 // Get the default path to the core file 5941 // Returns the length of the string 5942 int os::get_core_path(char* buffer, size_t bufferSize) { 5943 /* 5944 * Max length of /proc/sys/kernel/core_pattern is 128 characters. 5945 * See https://www.kernel.org/doc/Documentation/sysctl/kernel.txt 5946 */ 5947 const int core_pattern_len = 129; 5948 char core_pattern[core_pattern_len] = {0}; 5949 5950 int core_pattern_file = ::open("/proc/sys/kernel/core_pattern", O_RDONLY); 5951 if (core_pattern_file != -1) { 5952 ssize_t ret = ::read(core_pattern_file, core_pattern, core_pattern_len); 5953 ::close(core_pattern_file); 5954 5955 if (ret > 0) { 5956 char *last_char = core_pattern + strlen(core_pattern) - 1; 5957 5958 if (*last_char == '\n') { 5959 *last_char = '\0'; 5960 } 5961 } 5962 } 5963 5964 if (strlen(core_pattern) == 0) { 5965 return -1; 5966 } 5967 5968 char *pid_pos = strstr(core_pattern, "%p"); 5969 int written; 5970 5971 if (core_pattern[0] == '/') { 5972 written = jio_snprintf(buffer, bufferSize, core_pattern); 5973 } else { 5974 char cwd[PATH_MAX]; 5975 5976 const char* p = get_current_directory(cwd, PATH_MAX); 5977 if (p == NULL) { 5978 return -1; 5979 } 5980 5981 if (core_pattern[0] == '|') { 5982 written = jio_snprintf(buffer, bufferSize, 5983 "\"%s\" (or dumping to %s/core.%d)", 5984 &core_pattern[1], p, current_process_id()); 5985 } else { 5986 written = jio_snprintf(buffer, bufferSize, "%s/%s", p, core_pattern); 5987 } 5988 } 5989 5990 if (written < 0) { 5991 return -1; 5992 } 5993 5994 if (((size_t)written < bufferSize) && (pid_pos == NULL) && (core_pattern[0] != '|')) { 5995 int core_uses_pid_file = ::open("/proc/sys/kernel/core_uses_pid", O_RDONLY); 5996 5997 if (core_uses_pid_file != -1) { 5998 char core_uses_pid = 0; 5999 ssize_t ret = ::read(core_uses_pid_file, &core_uses_pid, 1); 6000 ::close(core_uses_pid_file); 6001 6002 if (core_uses_pid == '1') { 6003 jio_snprintf(buffer + written, bufferSize - written, 6004 ".%d", current_process_id()); 6005 } 6006 } 6007 } 6008 6009 return strlen(buffer); 6010 } 6011 6012 /////////////// Unit tests /////////////// 6013 6014 #ifndef PRODUCT 6015 6016 #define test_log(...) \ 6017 do { \ 6018 if (VerboseInternalVMTests) { \ 6019 tty->print_cr(__VA_ARGS__); \ 6020 tty->flush(); \ 6021 } \ 6022 } while (false) 6023 6024 class TestReserveMemorySpecial : AllStatic { 6025 public: 6026 static void small_page_write(void* addr, size_t size) { 6027 size_t page_size = os::vm_page_size(); 6028 6029 char* end = (char*)addr + size; 6030 for (char* p = (char*)addr; p < end; p += page_size) { 6031 *p = 1; 6032 } 6033 } 6034 6035 static void test_reserve_memory_special_huge_tlbfs_only(size_t size) { 6036 if (!UseHugeTLBFS) { 6037 return; 6038 } 6039 6040 test_log("test_reserve_memory_special_huge_tlbfs_only(" SIZE_FORMAT ")", size); 6041 6042 char* addr = os::Linux::reserve_memory_special_huge_tlbfs_only(size, NULL, false); 6043 6044 if (addr != NULL) { 6045 small_page_write(addr, size); 6046 6047 os::Linux::release_memory_special_huge_tlbfs(addr, size); 6048 } 6049 } 6050 6051 static void test_reserve_memory_special_huge_tlbfs_only() { 6052 if (!UseHugeTLBFS) { 6053 return; 6054 } 6055 6056 size_t lp = os::large_page_size(); 6057 6058 for (size_t size = lp; size <= lp * 10; size += lp) { 6059 test_reserve_memory_special_huge_tlbfs_only(size); 6060 } 6061 } 6062 6063 static void test_reserve_memory_special_huge_tlbfs_mixed() { 6064 size_t lp = os::large_page_size(); 6065 size_t ag = os::vm_allocation_granularity(); 6066 6067 // sizes to test 6068 const size_t sizes[] = { 6069 lp, lp + ag, lp + lp / 2, lp * 2, 6070 lp * 2 + ag, lp * 2 - ag, lp * 2 + lp / 2, 6071 lp * 10, lp * 10 + lp / 2 6072 }; 6073 const int num_sizes = sizeof(sizes) / sizeof(size_t); 6074 6075 // For each size/alignment combination, we test three scenarios: 6076 // 1) with req_addr == NULL 6077 // 2) with a non-null req_addr at which we expect to successfully allocate 6078 // 3) with a non-null req_addr which contains a pre-existing mapping, at which we 6079 // expect the allocation to either fail or to ignore req_addr 6080 6081 // Pre-allocate two areas; they shall be as large as the largest allocation 6082 // and aligned to the largest alignment we will be testing. 6083 const size_t mapping_size = sizes[num_sizes - 1] * 2; 6084 char* const mapping1 = (char*) ::mmap(NULL, mapping_size, 6085 PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE, 6086 -1, 0); 6087 assert(mapping1 != MAP_FAILED, "should work"); 6088 6089 char* const mapping2 = (char*) ::mmap(NULL, mapping_size, 6090 PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE, 6091 -1, 0); 6092 assert(mapping2 != MAP_FAILED, "should work"); 6093 6094 // Unmap the first mapping, but leave the second mapping intact: the first 6095 // mapping will serve as a value for a "good" req_addr (case 2). The second 6096 // mapping, still intact, as "bad" req_addr (case 3). 6097 ::munmap(mapping1, mapping_size); 6098 6099 // Case 1 6100 test_log("%s, req_addr NULL:", __FUNCTION__); 6101 test_log("size align result"); 6102 6103 for (int i = 0; i < num_sizes; i++) { 6104 const size_t size = sizes[i]; 6105 for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) { 6106 char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, NULL, false); 6107 test_log(SIZE_FORMAT_HEX " " SIZE_FORMAT_HEX " -> " PTR_FORMAT " %s", 6108 size, alignment, p, (p != NULL ? "" : "(failed)")); 6109 if (p != NULL) { 6110 assert(is_ptr_aligned(p, alignment), "must be"); 6111 small_page_write(p, size); 6112 os::Linux::release_memory_special_huge_tlbfs(p, size); 6113 } 6114 } 6115 } 6116 6117 // Case 2 6118 test_log("%s, req_addr non-NULL:", __FUNCTION__); 6119 test_log("size align req_addr result"); 6120 6121 for (int i = 0; i < num_sizes; i++) { 6122 const size_t size = sizes[i]; 6123 for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) { 6124 char* const req_addr = (char*) align_ptr_up(mapping1, alignment); 6125 char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, req_addr, false); 6126 test_log(SIZE_FORMAT_HEX " " SIZE_FORMAT_HEX " " PTR_FORMAT " -> " PTR_FORMAT " %s", 6127 size, alignment, req_addr, p, 6128 ((p != NULL ? (p == req_addr ? "(exact match)" : "") : "(failed)"))); 6129 if (p != NULL) { 6130 assert(p == req_addr, "must be"); 6131 small_page_write(p, size); 6132 os::Linux::release_memory_special_huge_tlbfs(p, size); 6133 } 6134 } 6135 } 6136 6137 // Case 3 6138 test_log("%s, req_addr non-NULL with preexisting mapping:", __FUNCTION__); 6139 test_log("size align req_addr result"); 6140 6141 for (int i = 0; i < num_sizes; i++) { 6142 const size_t size = sizes[i]; 6143 for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) { 6144 char* const req_addr = (char*) align_ptr_up(mapping2, alignment); 6145 char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, req_addr, false); 6146 test_log(SIZE_FORMAT_HEX " " SIZE_FORMAT_HEX " " PTR_FORMAT " -> " PTR_FORMAT " %s", 6147 size, alignment, req_addr, p, 6148 ((p != NULL ? "" : "(failed)"))); 6149 // as the area around req_addr contains already existing mappings, the API should always 6150 // return NULL (as per contract, it cannot return another address) 6151 assert(p == NULL, "must be"); 6152 } 6153 } 6154 6155 ::munmap(mapping2, mapping_size); 6156 6157 } 6158 6159 static void test_reserve_memory_special_huge_tlbfs() { 6160 if (!UseHugeTLBFS) { 6161 return; 6162 } 6163 6164 test_reserve_memory_special_huge_tlbfs_only(); 6165 test_reserve_memory_special_huge_tlbfs_mixed(); 6166 } 6167 6168 static void test_reserve_memory_special_shm(size_t size, size_t alignment) { 6169 if (!UseSHM) { 6170 return; 6171 } 6172 6173 test_log("test_reserve_memory_special_shm(" SIZE_FORMAT ", " SIZE_FORMAT ")", size, alignment); 6174 6175 char* addr = os::Linux::reserve_memory_special_shm(size, alignment, NULL, false); 6176 6177 if (addr != NULL) { 6178 assert(is_ptr_aligned(addr, alignment), "Check"); 6179 assert(is_ptr_aligned(addr, os::large_page_size()), "Check"); 6180 6181 small_page_write(addr, size); 6182 6183 os::Linux::release_memory_special_shm(addr, size); 6184 } 6185 } 6186 6187 static void test_reserve_memory_special_shm() { 6188 size_t lp = os::large_page_size(); 6189 size_t ag = os::vm_allocation_granularity(); 6190 6191 for (size_t size = ag; size < lp * 3; size += ag) { 6192 for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) { 6193 test_reserve_memory_special_shm(size, alignment); 6194 } 6195 } 6196 } 6197 6198 static void test() { 6199 test_reserve_memory_special_huge_tlbfs(); 6200 test_reserve_memory_special_shm(); 6201 } 6202 }; 6203 6204 void TestReserveMemorySpecial_test() { 6205 TestReserveMemorySpecial::test(); 6206 } 6207 6208 #endif