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