1 /*
   2  * Copyright (c) 1997, 2017, 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_solaris.h"
  35 #include "logging/log.hpp"
  36 #include "memory/allocation.inline.hpp"
  37 #include "memory/filemap.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "os_share_solaris.hpp"
  40 #include "os_solaris.inline.hpp"
  41 #include "prims/jniFastGetField.hpp"
  42 #include "prims/jvm.h"
  43 #include "prims/jvm_misc.hpp"
  44 #include "runtime/arguments.hpp"
  45 #include "runtime/atomic.hpp"
  46 #include "runtime/extendedPC.hpp"
  47 #include "runtime/globals.hpp"
  48 #include "runtime/interfaceSupport.hpp"
  49 #include "runtime/java.hpp"
  50 #include "runtime/javaCalls.hpp"
  51 #include "runtime/mutexLocker.hpp"
  52 #include "runtime/objectMonitor.hpp"
  53 #include "runtime/orderAccess.inline.hpp"
  54 #include "runtime/osThread.hpp"
  55 #include "runtime/perfMemory.hpp"
  56 #include "runtime/sharedRuntime.hpp"
  57 #include "runtime/statSampler.hpp"
  58 #include "runtime/stubRoutines.hpp"
  59 #include "runtime/thread.inline.hpp"
  60 #include "runtime/threadCritical.hpp"
  61 #include "runtime/timer.hpp"
  62 #include "runtime/vm_version.hpp"
  63 #include "semaphore_posix.hpp"
  64 #include "services/attachListener.hpp"
  65 #include "services/memTracker.hpp"
  66 #include "services/runtimeService.hpp"
  67 #include "utilities/decoder.hpp"
  68 #include "utilities/defaultStream.hpp"
  69 #include "utilities/events.hpp"
  70 #include "utilities/growableArray.hpp"
  71 #include "utilities/macros.hpp"
  72 #include "utilities/vmError.hpp"
  73 
  74 // put OS-includes here
  75 # include <dlfcn.h>
  76 # include <errno.h>
  77 # include <exception>
  78 # include <link.h>
  79 # include <poll.h>
  80 # include <pthread.h>
  81 # include <schedctl.h>
  82 # include <setjmp.h>
  83 # include <signal.h>
  84 # include <stdio.h>
  85 # include <alloca.h>
  86 # include <sys/filio.h>
  87 # include <sys/ipc.h>
  88 # include <sys/lwp.h>
  89 # include <sys/machelf.h>     // for elf Sym structure used by dladdr1
  90 # include <sys/mman.h>
  91 # include <sys/processor.h>
  92 # include <sys/procset.h>
  93 # include <sys/pset.h>
  94 # include <sys/resource.h>
  95 # include <sys/shm.h>
  96 # include <sys/socket.h>
  97 # include <sys/stat.h>
  98 # include <sys/systeminfo.h>
  99 # include <sys/time.h>
 100 # include <sys/times.h>
 101 # include <sys/types.h>
 102 # include <sys/wait.h>
 103 # include <sys/utsname.h>
 104 # include <thread.h>
 105 # include <unistd.h>
 106 # include <sys/priocntl.h>
 107 # include <sys/rtpriocntl.h>
 108 # include <sys/tspriocntl.h>
 109 # include <sys/iapriocntl.h>
 110 # include <sys/fxpriocntl.h>
 111 # include <sys/loadavg.h>
 112 # include <string.h>
 113 # include <stdio.h>
 114 
 115 # define _STRUCTURED_PROC 1  //  this gets us the new structured proc interfaces of 5.6 & later
 116 # include <sys/procfs.h>     //  see comment in <sys/procfs.h>
 117 
 118 #define MAX_PATH (2 * K)
 119 
 120 // for timer info max values which include all bits
 121 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
 122 
 123 
 124 // Here are some liblgrp types from sys/lgrp_user.h to be able to
 125 // compile on older systems without this header file.
 126 
 127 #ifndef MADV_ACCESS_LWP
 128   #define  MADV_ACCESS_LWP   7       /* next LWP to access heavily */
 129 #endif
 130 #ifndef MADV_ACCESS_MANY
 131   #define  MADV_ACCESS_MANY  8       /* many processes to access heavily */
 132 #endif
 133 
 134 #ifndef LGRP_RSRC_CPU
 135   #define LGRP_RSRC_CPU      0       /* CPU resources */
 136 #endif
 137 #ifndef LGRP_RSRC_MEM
 138   #define LGRP_RSRC_MEM      1       /* memory resources */
 139 #endif
 140 
 141 // Values for ThreadPriorityPolicy == 1
 142 int prio_policy1[CriticalPriority+1] = {
 143   -99999,  0, 16,  32,  48,  64,
 144           80, 96, 112, 124, 127, 127 };
 145 
 146 // System parameters used internally
 147 static clock_t clock_tics_per_sec = 100;
 148 
 149 // Track if we have called enable_extended_FILE_stdio (on Solaris 10u4+)
 150 static bool enabled_extended_FILE_stdio = false;
 151 
 152 // For diagnostics to print a message once. see run_periodic_checks
 153 static bool check_addr0_done = false;
 154 static sigset_t check_signal_done;
 155 static bool check_signals = true;
 156 
 157 address os::Solaris::handler_start;  // start pc of thr_sighndlrinfo
 158 address os::Solaris::handler_end;    // end pc of thr_sighndlrinfo
 159 
 160 address os::Solaris::_main_stack_base = NULL;  // 4352906 workaround
 161 
 162 os::Solaris::pthread_setname_np_func_t os::Solaris::_pthread_setname_np = NULL;
 163 
 164 // "default" initializers for missing libc APIs
 165 extern "C" {
 166   static int lwp_mutex_init(mutex_t *mx, int scope, void *arg) { memset(mx, 0, sizeof(mutex_t)); return 0; }
 167   static int lwp_mutex_destroy(mutex_t *mx)                 { return 0; }
 168 
 169   static int lwp_cond_init(cond_t *cv, int scope, void *arg){ memset(cv, 0, sizeof(cond_t)); return 0; }
 170   static int lwp_cond_destroy(cond_t *cv)                   { return 0; }
 171 }
 172 
 173 // "default" initializers for pthread-based synchronization
 174 extern "C" {
 175   static int pthread_mutex_default_init(mutex_t *mx, int scope, void *arg) { memset(mx, 0, sizeof(mutex_t)); return 0; }
 176   static int pthread_cond_default_init(cond_t *cv, int scope, void *arg){ memset(cv, 0, sizeof(cond_t)); return 0; }
 177 }
 178 
 179 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time);
 180 
 181 static inline size_t adjust_stack_size(address base, size_t size) {
 182   if ((ssize_t)size < 0) {
 183     // 4759953: Compensate for ridiculous stack size.
 184     size = max_intx;
 185   }
 186   if (size > (size_t)base) {
 187     // 4812466: Make sure size doesn't allow the stack to wrap the address space.
 188     size = (size_t)base;
 189   }
 190   return size;
 191 }
 192 
 193 static inline stack_t get_stack_info() {
 194   stack_t st;
 195   int retval = thr_stksegment(&st);
 196   st.ss_size = adjust_stack_size((address)st.ss_sp, st.ss_size);
 197   assert(retval == 0, "incorrect return value from thr_stksegment");
 198   assert((address)&st < (address)st.ss_sp, "Invalid stack base returned");
 199   assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned");
 200   return st;
 201 }
 202 
 203 address os::current_stack_base() {
 204   int r = thr_main();
 205   guarantee(r == 0 || r == 1, "CR6501650 or CR6493689");
 206   bool is_primordial_thread = r;
 207 
 208   // Workaround 4352906, avoid calls to thr_stksegment by
 209   // thr_main after the first one (it looks like we trash
 210   // some data, causing the value for ss_sp to be incorrect).
 211   if (!is_primordial_thread || os::Solaris::_main_stack_base == NULL) {
 212     stack_t st = get_stack_info();
 213     if (is_primordial_thread) {
 214       // cache initial value of stack base
 215       os::Solaris::_main_stack_base = (address)st.ss_sp;
 216     }
 217     return (address)st.ss_sp;
 218   } else {
 219     guarantee(os::Solaris::_main_stack_base != NULL, "Attempt to use null cached stack base");
 220     return os::Solaris::_main_stack_base;
 221   }
 222 }
 223 
 224 size_t os::current_stack_size() {
 225   size_t size;
 226 
 227   int r = thr_main();
 228   guarantee(r == 0 || r == 1, "CR6501650 or CR6493689");
 229   if (!r) {
 230     size = get_stack_info().ss_size;
 231   } else {
 232     struct rlimit limits;
 233     getrlimit(RLIMIT_STACK, &limits);
 234     size = adjust_stack_size(os::Solaris::_main_stack_base, (size_t)limits.rlim_cur);
 235   }
 236   // base may not be page aligned
 237   address base = current_stack_base();
 238   address bottom = (address)align_size_up((intptr_t)(base - size), os::vm_page_size());;
 239   return (size_t)(base - bottom);
 240 }
 241 
 242 struct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
 243   return localtime_r(clock, res);
 244 }
 245 
 246 void os::Solaris::try_enable_extended_io() {
 247   typedef int (*enable_extended_FILE_stdio_t)(int, int);
 248 
 249   if (!UseExtendedFileIO) {
 250     return;
 251   }
 252 
 253   enable_extended_FILE_stdio_t enabler =
 254     (enable_extended_FILE_stdio_t) dlsym(RTLD_DEFAULT,
 255                                          "enable_extended_FILE_stdio");
 256   if (enabler) {
 257     enabler(-1, -1);
 258   }
 259 }
 260 
 261 static int _processors_online = 0;
 262 
 263 jint os::Solaris::_os_thread_limit = 0;
 264 volatile jint os::Solaris::_os_thread_count = 0;
 265 
 266 julong os::available_memory() {
 267   return Solaris::available_memory();
 268 }
 269 
 270 julong os::Solaris::available_memory() {
 271   return (julong)sysconf(_SC_AVPHYS_PAGES) * os::vm_page_size();
 272 }
 273 
 274 julong os::Solaris::_physical_memory = 0;
 275 
 276 julong os::physical_memory() {
 277   return Solaris::physical_memory();
 278 }
 279 
 280 static hrtime_t first_hrtime = 0;
 281 static const hrtime_t hrtime_hz = 1000*1000*1000;
 282 static volatile hrtime_t max_hrtime = 0;
 283 
 284 
 285 void os::Solaris::initialize_system_info() {
 286   set_processor_count(sysconf(_SC_NPROCESSORS_CONF));
 287   _processors_online = sysconf(_SC_NPROCESSORS_ONLN);
 288   _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) *
 289                                      (julong)sysconf(_SC_PAGESIZE);
 290 }
 291 
 292 int os::active_processor_count() {
 293   int online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
 294   pid_t pid = getpid();
 295   psetid_t pset = PS_NONE;
 296   // Are we running in a processor set or is there any processor set around?
 297   if (pset_bind(PS_QUERY, P_PID, pid, &pset) == 0) {
 298     uint_t pset_cpus;
 299     // Query the number of cpus available to us.
 300     if (pset_info(pset, NULL, &pset_cpus, NULL) == 0) {
 301       assert(pset_cpus > 0 && pset_cpus <= online_cpus, "sanity check");
 302       _processors_online = pset_cpus;
 303       return pset_cpus;
 304     }
 305   }
 306   // Otherwise return number of online cpus
 307   return online_cpus;
 308 }
 309 
 310 static bool find_processors_in_pset(psetid_t        pset,
 311                                     processorid_t** id_array,
 312                                     uint_t*         id_length) {
 313   bool result = false;
 314   // Find the number of processors in the processor set.
 315   if (pset_info(pset, NULL, id_length, NULL) == 0) {
 316     // Make up an array to hold their ids.
 317     *id_array = NEW_C_HEAP_ARRAY(processorid_t, *id_length, mtInternal);
 318     // Fill in the array with their processor ids.
 319     if (pset_info(pset, NULL, id_length, *id_array) == 0) {
 320       result = true;
 321     }
 322   }
 323   return result;
 324 }
 325 
 326 // Callers of find_processors_online() must tolerate imprecise results --
 327 // the system configuration can change asynchronously because of DR
 328 // or explicit psradm operations.
 329 //
 330 // We also need to take care that the loop (below) terminates as the
 331 // number of processors online can change between the _SC_NPROCESSORS_ONLN
 332 // request and the loop that builds the list of processor ids.   Unfortunately
 333 // there's no reliable way to determine the maximum valid processor id,
 334 // so we use a manifest constant, MAX_PROCESSOR_ID, instead.  See p_online
 335 // man pages, which claim the processor id set is "sparse, but
 336 // not too sparse".  MAX_PROCESSOR_ID is used to ensure that we eventually
 337 // exit the loop.
 338 //
 339 // In the future we'll be able to use sysconf(_SC_CPUID_MAX), but that's
 340 // not available on S8.0.
 341 
 342 static bool find_processors_online(processorid_t** id_array,
 343                                    uint*           id_length) {
 344   const processorid_t MAX_PROCESSOR_ID = 100000;
 345   // Find the number of processors online.
 346   *id_length = sysconf(_SC_NPROCESSORS_ONLN);
 347   // Make up an array to hold their ids.
 348   *id_array = NEW_C_HEAP_ARRAY(processorid_t, *id_length, mtInternal);
 349   // Processors need not be numbered consecutively.
 350   long found = 0;
 351   processorid_t next = 0;
 352   while (found < *id_length && next < MAX_PROCESSOR_ID) {
 353     processor_info_t info;
 354     if (processor_info(next, &info) == 0) {
 355       // NB, PI_NOINTR processors are effectively online ...
 356       if (info.pi_state == P_ONLINE || info.pi_state == P_NOINTR) {
 357         (*id_array)[found] = next;
 358         found += 1;
 359       }
 360     }
 361     next += 1;
 362   }
 363   if (found < *id_length) {
 364     // The loop above didn't identify the expected number of processors.
 365     // We could always retry the operation, calling sysconf(_SC_NPROCESSORS_ONLN)
 366     // and re-running the loop, above, but there's no guarantee of progress
 367     // if the system configuration is in flux.  Instead, we just return what
 368     // we've got.  Note that in the worst case find_processors_online() could
 369     // return an empty set.  (As a fall-back in the case of the empty set we
 370     // could just return the ID of the current processor).
 371     *id_length = found;
 372   }
 373 
 374   return true;
 375 }
 376 
 377 static bool assign_distribution(processorid_t* id_array,
 378                                 uint           id_length,
 379                                 uint*          distribution,
 380                                 uint           distribution_length) {
 381   // We assume we can assign processorid_t's to uint's.
 382   assert(sizeof(processorid_t) == sizeof(uint),
 383          "can't convert processorid_t to uint");
 384   // Quick check to see if we won't succeed.
 385   if (id_length < distribution_length) {
 386     return false;
 387   }
 388   // Assign processor ids to the distribution.
 389   // Try to shuffle processors to distribute work across boards,
 390   // assuming 4 processors per board.
 391   const uint processors_per_board = ProcessDistributionStride;
 392   // Find the maximum processor id.
 393   processorid_t max_id = 0;
 394   for (uint m = 0; m < id_length; m += 1) {
 395     max_id = MAX2(max_id, id_array[m]);
 396   }
 397   // The next id, to limit loops.
 398   const processorid_t limit_id = max_id + 1;
 399   // Make up markers for available processors.
 400   bool* available_id = NEW_C_HEAP_ARRAY(bool, limit_id, mtInternal);
 401   for (uint c = 0; c < limit_id; c += 1) {
 402     available_id[c] = false;
 403   }
 404   for (uint a = 0; a < id_length; a += 1) {
 405     available_id[id_array[a]] = true;
 406   }
 407   // Step by "boards", then by "slot", copying to "assigned".
 408   // NEEDS_CLEANUP: The assignment of processors should be stateful,
 409   //                remembering which processors have been assigned by
 410   //                previous calls, etc., so as to distribute several
 411   //                independent calls of this method.  What we'd like is
 412   //                It would be nice to have an API that let us ask
 413   //                how many processes are bound to a processor,
 414   //                but we don't have that, either.
 415   //                In the short term, "board" is static so that
 416   //                subsequent distributions don't all start at board 0.
 417   static uint board = 0;
 418   uint assigned = 0;
 419   // Until we've found enough processors ....
 420   while (assigned < distribution_length) {
 421     // ... find the next available processor in the board.
 422     for (uint slot = 0; slot < processors_per_board; slot += 1) {
 423       uint try_id = board * processors_per_board + slot;
 424       if ((try_id < limit_id) && (available_id[try_id] == true)) {
 425         distribution[assigned] = try_id;
 426         available_id[try_id] = false;
 427         assigned += 1;
 428         break;
 429       }
 430     }
 431     board += 1;
 432     if (board * processors_per_board + 0 >= limit_id) {
 433       board = 0;
 434     }
 435   }
 436   if (available_id != NULL) {
 437     FREE_C_HEAP_ARRAY(bool, available_id);
 438   }
 439   return true;
 440 }
 441 
 442 void os::set_native_thread_name(const char *name) {
 443   if (Solaris::_pthread_setname_np != NULL) {
 444     // Only the first 31 bytes of 'name' are processed by pthread_setname_np
 445     // but we explicitly copy into a size-limited buffer to avoid any
 446     // possible overflow.
 447     char buf[32];
 448     snprintf(buf, sizeof(buf), "%s", name);
 449     buf[sizeof(buf) - 1] = '\0';
 450     Solaris::_pthread_setname_np(pthread_self(), buf);
 451   }
 452 }
 453 
 454 bool os::distribute_processes(uint length, uint* distribution) {
 455   bool result = false;
 456   // Find the processor id's of all the available CPUs.
 457   processorid_t* id_array  = NULL;
 458   uint           id_length = 0;
 459   // There are some races between querying information and using it,
 460   // since processor sets can change dynamically.
 461   psetid_t pset = PS_NONE;
 462   // Are we running in a processor set?
 463   if ((pset_bind(PS_QUERY, P_PID, P_MYID, &pset) == 0) && pset != PS_NONE) {
 464     result = find_processors_in_pset(pset, &id_array, &id_length);
 465   } else {
 466     result = find_processors_online(&id_array, &id_length);
 467   }
 468   if (result == true) {
 469     if (id_length >= length) {
 470       result = assign_distribution(id_array, id_length, distribution, length);
 471     } else {
 472       result = false;
 473     }
 474   }
 475   if (id_array != NULL) {
 476     FREE_C_HEAP_ARRAY(processorid_t, id_array);
 477   }
 478   return result;
 479 }
 480 
 481 bool os::bind_to_processor(uint processor_id) {
 482   // We assume that a processorid_t can be stored in a uint.
 483   assert(sizeof(uint) == sizeof(processorid_t),
 484          "can't convert uint to processorid_t");
 485   int bind_result =
 486     processor_bind(P_LWPID,                       // bind LWP.
 487                    P_MYID,                        // bind current LWP.
 488                    (processorid_t) processor_id,  // id.
 489                    NULL);                         // don't return old binding.
 490   return (bind_result == 0);
 491 }
 492 
 493 // Return true if user is running as root.
 494 
 495 bool os::have_special_privileges() {
 496   static bool init = false;
 497   static bool privileges = false;
 498   if (!init) {
 499     privileges = (getuid() != geteuid()) || (getgid() != getegid());
 500     init = true;
 501   }
 502   return privileges;
 503 }
 504 
 505 
 506 void os::init_system_properties_values() {
 507   // The next steps are taken in the product version:
 508   //
 509   // Obtain the JAVA_HOME value from the location of libjvm.so.
 510   // This library should be located at:
 511   // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
 512   //
 513   // If "/jre/lib/" appears at the right place in the path, then we
 514   // assume libjvm.so is installed in a JDK and we use this path.
 515   //
 516   // Otherwise exit with message: "Could not create the Java virtual machine."
 517   //
 518   // The following extra steps are taken in the debugging version:
 519   //
 520   // If "/jre/lib/" does NOT appear at the right place in the path
 521   // instead of exit check for $JAVA_HOME environment variable.
 522   //
 523   // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
 524   // then we append a fake suffix "hotspot/libjvm.so" to this path so
 525   // it looks like libjvm.so is installed there
 526   // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
 527   //
 528   // Otherwise exit.
 529   //
 530   // Important note: if the location of libjvm.so changes this
 531   // code needs to be changed accordingly.
 532 
 533 // Base path of extensions installed on the system.
 534 #define SYS_EXT_DIR     "/usr/jdk/packages"
 535 #define EXTENSIONS_DIR  "/lib/ext"
 536 
 537   // Buffer that fits several sprintfs.
 538   // Note that the space for the colon and the trailing null are provided
 539   // by the nulls included by the sizeof operator.
 540   const size_t bufsize =
 541     MAX3((size_t)MAXPATHLEN,  // For dll_dir & friends.
 542          sizeof(SYS_EXT_DIR) + sizeof("/lib/"), // invariant ld_library_path
 543          (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR)); // extensions dir
 544   char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
 545 
 546   // sysclasspath, java_home, dll_dir
 547   {
 548     char *pslash;
 549     os::jvm_path(buf, bufsize);
 550 
 551     // Found the full path to libjvm.so.
 552     // Now cut the path to <java_home>/jre if we can.
 553     *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.
 554     pslash = strrchr(buf, '/');
 555     if (pslash != NULL) {
 556       *pslash = '\0';            // Get rid of /{client|server|hotspot}.
 557     }
 558     Arguments::set_dll_dir(buf);
 559 
 560     if (pslash != NULL) {
 561       pslash = strrchr(buf, '/');
 562       if (pslash != NULL) {
 563         *pslash = '\0';        // Get rid of /lib.
 564       }
 565     }
 566     Arguments::set_java_home(buf);
 567     set_boot_path('/', ':');
 568   }
 569 
 570   // Where to look for native libraries.
 571   {
 572     // Use dlinfo() to determine the correct java.library.path.
 573     //
 574     // If we're launched by the Java launcher, and the user
 575     // does not set java.library.path explicitly on the commandline,
 576     // the Java launcher sets LD_LIBRARY_PATH for us and unsets
 577     // LD_LIBRARY_PATH_32 and LD_LIBRARY_PATH_64.  In this case
 578     // dlinfo returns LD_LIBRARY_PATH + crle settings (including
 579     // /usr/lib), which is exactly what we want.
 580     //
 581     // If the user does set java.library.path, it completely
 582     // overwrites this setting, and always has.
 583     //
 584     // If we're not launched by the Java launcher, we may
 585     // get here with any/all of the LD_LIBRARY_PATH[_32|64]
 586     // settings.  Again, dlinfo does exactly what we want.
 587 
 588     Dl_serinfo     info_sz, *info = &info_sz;
 589     Dl_serpath     *path;
 590     char           *library_path;
 591     char           *common_path = buf;
 592 
 593     // Determine search path count and required buffer size.
 594     if (dlinfo(RTLD_SELF, RTLD_DI_SERINFOSIZE, (void *)info) == -1) {
 595       FREE_C_HEAP_ARRAY(char, buf);
 596       vm_exit_during_initialization("dlinfo SERINFOSIZE request", dlerror());
 597     }
 598 
 599     // Allocate new buffer and initialize.
 600     info = (Dl_serinfo*)NEW_C_HEAP_ARRAY(char, info_sz.dls_size, mtInternal);
 601     info->dls_size = info_sz.dls_size;
 602     info->dls_cnt = info_sz.dls_cnt;
 603 
 604     // Obtain search path information.
 605     if (dlinfo(RTLD_SELF, RTLD_DI_SERINFO, (void *)info) == -1) {
 606       FREE_C_HEAP_ARRAY(char, buf);
 607       FREE_C_HEAP_ARRAY(char, info);
 608       vm_exit_during_initialization("dlinfo SERINFO request", dlerror());
 609     }
 610 
 611     path = &info->dls_serpath[0];
 612 
 613     // Note: Due to a legacy implementation, most of the library path
 614     // is set in the launcher. This was to accomodate linking restrictions
 615     // on legacy Solaris implementations (which are no longer supported).
 616     // Eventually, all the library path setting will be done here.
 617     //
 618     // However, to prevent the proliferation of improperly built native
 619     // libraries, the new path component /usr/jdk/packages is added here.
 620 
 621     // Construct the invariant part of ld_library_path.
 622     sprintf(common_path, SYS_EXT_DIR "/lib");
 623 
 624     // Struct size is more than sufficient for the path components obtained
 625     // through the dlinfo() call, so only add additional space for the path
 626     // components explicitly added here.
 627     size_t library_path_size = info->dls_size + strlen(common_path);
 628     library_path = (char *)NEW_C_HEAP_ARRAY(char, library_path_size, mtInternal);
 629     library_path[0] = '\0';
 630 
 631     // Construct the desired Java library path from the linker's library
 632     // search path.
 633     //
 634     // For compatibility, it is optimal that we insert the additional path
 635     // components specific to the Java VM after those components specified
 636     // in LD_LIBRARY_PATH (if any) but before those added by the ld.so
 637     // infrastructure.
 638     if (info->dls_cnt == 0) { // Not sure this can happen, but allow for it.
 639       strcpy(library_path, common_path);
 640     } else {
 641       int inserted = 0;
 642       int i;
 643       for (i = 0; i < info->dls_cnt; i++, path++) {
 644         uint_t flags = path->dls_flags & LA_SER_MASK;
 645         if (((flags & LA_SER_LIBPATH) == 0) && !inserted) {
 646           strcat(library_path, common_path);
 647           strcat(library_path, os::path_separator());
 648           inserted = 1;
 649         }
 650         strcat(library_path, path->dls_name);
 651         strcat(library_path, os::path_separator());
 652       }
 653       // Eliminate trailing path separator.
 654       library_path[strlen(library_path)-1] = '\0';
 655     }
 656 
 657     // happens before argument parsing - can't use a trace flag
 658     // tty->print_raw("init_system_properties_values: native lib path: ");
 659     // tty->print_raw_cr(library_path);
 660 
 661     // Callee copies into its own buffer.
 662     Arguments::set_library_path(library_path);
 663 
 664     FREE_C_HEAP_ARRAY(char, library_path);
 665     FREE_C_HEAP_ARRAY(char, info);
 666   }
 667 
 668   // Extensions directories.
 669   sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());
 670   Arguments::set_ext_dirs(buf);
 671 
 672   FREE_C_HEAP_ARRAY(char, buf);
 673 
 674 #undef SYS_EXT_DIR
 675 #undef EXTENSIONS_DIR
 676 }
 677 
 678 void os::breakpoint() {
 679   BREAKPOINT;
 680 }
 681 
 682 bool os::obsolete_option(const JavaVMOption *option) {
 683   if (!strncmp(option->optionString, "-Xt", 3)) {
 684     return true;
 685   } else if (!strncmp(option->optionString, "-Xtm", 4)) {
 686     return true;
 687   } else if (!strncmp(option->optionString, "-Xverifyheap", 12)) {
 688     return true;
 689   } else if (!strncmp(option->optionString, "-Xmaxjitcodesize", 16)) {
 690     return true;
 691   }
 692   return false;
 693 }
 694 
 695 bool os::Solaris::valid_stack_address(Thread* thread, address sp) {
 696   address  stackStart  = (address)thread->stack_base();
 697   address  stackEnd    = (address)(stackStart - (address)thread->stack_size());
 698   if (sp < stackStart && sp >= stackEnd) return true;
 699   return false;
 700 }
 701 
 702 extern "C" void breakpoint() {
 703   // use debugger to set breakpoint here
 704 }
 705 
 706 static thread_t main_thread;
 707 
 708 // Thread start routine for all newly created threads
 709 extern "C" void* thread_native_entry(void* thread_addr) {
 710   // Try to randomize the cache line index of hot stack frames.
 711   // This helps when threads of the same stack traces evict each other's
 712   // cache lines. The threads can be either from the same JVM instance, or
 713   // from different JVM instances. The benefit is especially true for
 714   // processors with hyperthreading technology.
 715   static int counter = 0;
 716   int pid = os::current_process_id();
 717   alloca(((pid ^ counter++) & 7) * 128);
 718 
 719   int prio;
 720   Thread* thread = (Thread*)thread_addr;
 721 
 722   thread->initialize_thread_current();
 723 
 724   OSThread* osthr = thread->osthread();
 725 
 726   osthr->set_lwp_id(_lwp_self());  // Store lwp in case we are bound
 727   thread->_schedctl = (void *) schedctl_init();
 728 
 729   log_info(os, thread)("Thread is alive (tid: " UINTX_FORMAT ").",
 730     os::current_thread_id());
 731 
 732   if (UseNUMA) {
 733     int lgrp_id = os::numa_get_group_id();
 734     if (lgrp_id != -1) {
 735       thread->set_lgrp_id(lgrp_id);
 736     }
 737   }
 738 
 739   // Our priority was set when we were created, and stored in the
 740   // osthread, but couldn't be passed through to our LWP until now.
 741   // So read back the priority and set it again.
 742 
 743   if (osthr->thread_id() != -1) {
 744     if (UseThreadPriorities) {
 745       int prio = osthr->native_priority();
 746       if (ThreadPriorityVerbose) {
 747         tty->print_cr("Starting Thread " INTPTR_FORMAT ", LWP is "
 748                       INTPTR_FORMAT ", setting priority: %d\n",
 749                       osthr->thread_id(), osthr->lwp_id(), prio);
 750       }
 751       os::set_native_priority(thread, prio);
 752     }
 753   } else if (ThreadPriorityVerbose) {
 754     warning("Can't set priority in _start routine, thread id hasn't been set\n");
 755   }
 756 
 757   assert(osthr->get_state() == RUNNABLE, "invalid os thread state");
 758 
 759   // initialize signal mask for this thread
 760   os::Solaris::hotspot_sigmask(thread);
 761 
 762   thread->run();
 763 
 764   // One less thread is executing
 765   // When the VMThread gets here, the main thread may have already exited
 766   // which frees the CodeHeap containing the Atomic::dec code
 767   if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) {
 768     Atomic::dec(&os::Solaris::_os_thread_count);
 769   }
 770 
 771   log_info(os, thread)("Thread finished (tid: " UINTX_FORMAT ").", os::current_thread_id());
 772 
 773   // If a thread has not deleted itself ("delete this") as part of its
 774   // termination sequence, we have to ensure thread-local-storage is
 775   // cleared before we actually terminate. No threads should ever be
 776   // deleted asynchronously with respect to their termination.
 777   if (Thread::current_or_null_safe() != NULL) {
 778     assert(Thread::current_or_null_safe() == thread, "current thread is wrong");
 779     thread->clear_thread_current();
 780   }
 781 
 782   if (UseDetachedThreads) {
 783     thr_exit(NULL);
 784     ShouldNotReachHere();
 785   }
 786   return NULL;
 787 }
 788 
 789 static OSThread* create_os_thread(Thread* thread, thread_t thread_id) {
 790   // Allocate the OSThread object
 791   OSThread* osthread = new OSThread(NULL, NULL);
 792   if (osthread == NULL) return NULL;
 793 
 794   // Store info on the Solaris thread into the OSThread
 795   osthread->set_thread_id(thread_id);
 796   osthread->set_lwp_id(_lwp_self());
 797   thread->_schedctl = (void *) schedctl_init();
 798 
 799   if (UseNUMA) {
 800     int lgrp_id = os::numa_get_group_id();
 801     if (lgrp_id != -1) {
 802       thread->set_lgrp_id(lgrp_id);
 803     }
 804   }
 805 
 806   if (ThreadPriorityVerbose) {
 807     tty->print_cr("In create_os_thread, Thread " INTPTR_FORMAT ", LWP is " INTPTR_FORMAT "\n",
 808                   osthread->thread_id(), osthread->lwp_id());
 809   }
 810 
 811   // Initial thread state is INITIALIZED, not SUSPENDED
 812   osthread->set_state(INITIALIZED);
 813 
 814   return osthread;
 815 }
 816 
 817 void os::Solaris::hotspot_sigmask(Thread* thread) {
 818   //Save caller's signal mask
 819   sigset_t sigmask;
 820   pthread_sigmask(SIG_SETMASK, NULL, &sigmask);
 821   OSThread *osthread = thread->osthread();
 822   osthread->set_caller_sigmask(sigmask);
 823 
 824   pthread_sigmask(SIG_UNBLOCK, os::Solaris::unblocked_signals(), NULL);
 825   if (!ReduceSignalUsage) {
 826     if (thread->is_VM_thread()) {
 827       // Only the VM thread handles BREAK_SIGNAL ...
 828       pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
 829     } else {
 830       // ... all other threads block BREAK_SIGNAL
 831       assert(!sigismember(vm_signals(), SIGINT), "SIGINT should not be blocked");
 832       pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
 833     }
 834   }
 835 }
 836 
 837 bool os::create_attached_thread(JavaThread* thread) {
 838 #ifdef ASSERT
 839   thread->verify_not_published();
 840 #endif
 841   OSThread* osthread = create_os_thread(thread, thr_self());
 842   if (osthread == NULL) {
 843     return false;
 844   }
 845 
 846   // Initial thread state is RUNNABLE
 847   osthread->set_state(RUNNABLE);
 848   thread->set_osthread(osthread);
 849 
 850   // initialize signal mask for this thread
 851   // and save the caller's signal mask
 852   os::Solaris::hotspot_sigmask(thread);
 853 
 854   log_info(os, thread)("Thread attached (tid: " UINTX_FORMAT ").",
 855     os::current_thread_id());
 856 
 857   return true;
 858 }
 859 
 860 bool os::create_main_thread(JavaThread* thread) {
 861 #ifdef ASSERT
 862   thread->verify_not_published();
 863 #endif
 864   if (_starting_thread == NULL) {
 865     _starting_thread = create_os_thread(thread, main_thread);
 866     if (_starting_thread == NULL) {
 867       return false;
 868     }
 869   }
 870 
 871   // The primodial thread is runnable from the start
 872   _starting_thread->set_state(RUNNABLE);
 873 
 874   thread->set_osthread(_starting_thread);
 875 
 876   // initialize signal mask for this thread
 877   // and save the caller's signal mask
 878   os::Solaris::hotspot_sigmask(thread);
 879 
 880   return true;
 881 }
 882 
 883 // Helper function to trace thread attributes, similar to os::Posix::describe_pthread_attr()
 884 static char* describe_thr_create_attributes(char* buf, size_t buflen,
 885                                             size_t stacksize, long flags) {
 886   stringStream ss(buf, buflen);
 887   ss.print("stacksize: " SIZE_FORMAT "k, ", stacksize / 1024);
 888   ss.print("flags: ");
 889   #define PRINT_FLAG(f) if (flags & f) ss.print( #f " ");
 890   #define ALL(X) \
 891     X(THR_SUSPENDED) \
 892     X(THR_DETACHED) \
 893     X(THR_BOUND) \
 894     X(THR_NEW_LWP) \
 895     X(THR_DAEMON)
 896   ALL(PRINT_FLAG)
 897   #undef ALL
 898   #undef PRINT_FLAG
 899   return buf;
 900 }
 901 
 902 // return default stack size for thr_type
 903 size_t os::Posix::default_stack_size(os::ThreadType thr_type) {
 904   // default stack size when not specified by caller is 1M (2M for LP64)
 905   size_t s = (BytesPerWord >> 2) * K * K;
 906   return s;
 907 }
 908 
 909 bool os::create_thread(Thread* thread, ThreadType thr_type,
 910                        size_t req_stack_size) {
 911   // Allocate the OSThread object
 912   OSThread* osthread = new OSThread(NULL, NULL);
 913   if (osthread == NULL) {
 914     return false;
 915   }
 916 
 917   if (ThreadPriorityVerbose) {
 918     char *thrtyp;
 919     switch (thr_type) {
 920     case vm_thread:
 921       thrtyp = (char *)"vm";
 922       break;
 923     case cgc_thread:
 924       thrtyp = (char *)"cgc";
 925       break;
 926     case pgc_thread:
 927       thrtyp = (char *)"pgc";
 928       break;
 929     case java_thread:
 930       thrtyp = (char *)"java";
 931       break;
 932     case compiler_thread:
 933       thrtyp = (char *)"compiler";
 934       break;
 935     case watcher_thread:
 936       thrtyp = (char *)"watcher";
 937       break;
 938     default:
 939       thrtyp = (char *)"unknown";
 940       break;
 941     }
 942     tty->print_cr("In create_thread, creating a %s thread\n", thrtyp);
 943   }
 944 
 945   // calculate stack size if it's not specified by caller
 946   size_t stack_size = os::Posix::get_initial_stack_size(thr_type, req_stack_size);
 947 
 948   // Initial state is ALLOCATED but not INITIALIZED
 949   osthread->set_state(ALLOCATED);
 950 
 951   if (os::Solaris::_os_thread_count > os::Solaris::_os_thread_limit) {
 952     // We got lots of threads. Check if we still have some address space left.
 953     // Need to be at least 5Mb of unreserved address space. We do check by
 954     // trying to reserve some.
 955     const size_t VirtualMemoryBangSize = 20*K*K;
 956     char* mem = os::reserve_memory(VirtualMemoryBangSize);
 957     if (mem == NULL) {
 958       delete osthread;
 959       return false;
 960     } else {
 961       // Release the memory again
 962       os::release_memory(mem, VirtualMemoryBangSize);
 963     }
 964   }
 965 
 966   // Setup osthread because the child thread may need it.
 967   thread->set_osthread(osthread);
 968 
 969   // Create the Solaris thread
 970   thread_t tid = 0;
 971   long     flags = (UseDetachedThreads ? THR_DETACHED : 0) | THR_SUSPENDED;
 972   int      status;
 973 
 974   // Mark that we don't have an lwp or thread id yet.
 975   // In case we attempt to set the priority before the thread starts.
 976   osthread->set_lwp_id(-1);
 977   osthread->set_thread_id(-1);
 978 
 979   status = thr_create(NULL, stack_size, thread_native_entry, thread, flags, &tid);
 980 
 981   char buf[64];
 982   if (status == 0) {
 983     log_info(os, thread)("Thread started (tid: " UINTX_FORMAT ", attributes: %s). ",
 984       (uintx) tid, describe_thr_create_attributes(buf, sizeof(buf), stack_size, flags));
 985   } else {
 986     log_warning(os, thread)("Failed to start thread - thr_create failed (%s) for attributes: %s.",
 987       os::errno_name(status), describe_thr_create_attributes(buf, sizeof(buf), stack_size, flags));
 988   }
 989 
 990   if (status != 0) {
 991     thread->set_osthread(NULL);
 992     // Need to clean up stuff we've allocated so far
 993     delete osthread;
 994     return false;
 995   }
 996 
 997   Atomic::inc(&os::Solaris::_os_thread_count);
 998 
 999   // Store info on the Solaris thread into the OSThread
1000   osthread->set_thread_id(tid);
1001 
1002   // Remember that we created this thread so we can set priority on it
1003   osthread->set_vm_created();
1004 
1005   // Most thread types will set an explicit priority before starting the thread,
1006   // but for those that don't we need a valid value to read back in thread_native_entry.
1007   osthread->set_native_priority(NormPriority);
1008 
1009   // Initial thread state is INITIALIZED, not SUSPENDED
1010   osthread->set_state(INITIALIZED);
1011 
1012   // The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain
1013   return true;
1014 }
1015 
1016 // defined for >= Solaris 10. This allows builds on earlier versions
1017 // of Solaris to take advantage of the newly reserved Solaris JVM signals.
1018 // With SIGJVM1, SIGJVM2, ASYNC_SIGNAL is SIGJVM2. Previously INTERRUPT_SIGNAL
1019 // was SIGJVM1.
1020 //
1021 #if !defined(SIGJVM1)
1022   #define SIGJVM1 39
1023   #define SIGJVM2 40
1024 #endif
1025 
1026 debug_only(static bool signal_sets_initialized = false);
1027 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
1028 
1029 int os::Solaris::_SIGasync = ASYNC_SIGNAL;
1030 
1031 bool os::Solaris::is_sig_ignored(int sig) {
1032   struct sigaction oact;
1033   sigaction(sig, (struct sigaction*)NULL, &oact);
1034   void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oact.sa_sigaction)
1035                                  : CAST_FROM_FN_PTR(void*,  oact.sa_handler);
1036   if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) {
1037     return true;
1038   } else {
1039     return false;
1040   }
1041 }
1042 
1043 // Note: SIGRTMIN is a macro that calls sysconf() so it will
1044 // dynamically detect SIGRTMIN value for the system at runtime, not buildtime
1045 static bool isJVM1available() {
1046   return SIGJVM1 < SIGRTMIN;
1047 }
1048 
1049 void os::Solaris::signal_sets_init() {
1050   // Should also have an assertion stating we are still single-threaded.
1051   assert(!signal_sets_initialized, "Already initialized");
1052   // Fill in signals that are necessarily unblocked for all threads in
1053   // the VM. Currently, we unblock the following signals:
1054   // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
1055   //                         by -Xrs (=ReduceSignalUsage));
1056   // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
1057   // other threads. The "ReduceSignalUsage" boolean tells us not to alter
1058   // the dispositions or masks wrt these signals.
1059   // Programs embedding the VM that want to use the above signals for their
1060   // own purposes must, at this time, use the "-Xrs" option to prevent
1061   // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
1062   // (See bug 4345157, and other related bugs).
1063   // In reality, though, unblocking these signals is really a nop, since
1064   // these signals are not blocked by default.
1065   sigemptyset(&unblocked_sigs);
1066   sigemptyset(&allowdebug_blocked_sigs);
1067   sigaddset(&unblocked_sigs, SIGILL);
1068   sigaddset(&unblocked_sigs, SIGSEGV);
1069   sigaddset(&unblocked_sigs, SIGBUS);
1070   sigaddset(&unblocked_sigs, SIGFPE);
1071 
1072   // Always true on Solaris 10+
1073   guarantee(isJVM1available(), "SIGJVM1/2 missing!");
1074   os::Solaris::set_SIGasync(SIGJVM2);
1075 
1076   sigaddset(&unblocked_sigs, os::Solaris::SIGasync());
1077 
1078   if (!ReduceSignalUsage) {
1079     if (!os::Solaris::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
1080       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
1081       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
1082     }
1083     if (!os::Solaris::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
1084       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
1085       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
1086     }
1087     if (!os::Solaris::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
1088       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
1089       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
1090     }
1091   }
1092   // Fill in signals that are blocked by all but the VM thread.
1093   sigemptyset(&vm_sigs);
1094   if (!ReduceSignalUsage) {
1095     sigaddset(&vm_sigs, BREAK_SIGNAL);
1096   }
1097   debug_only(signal_sets_initialized = true);
1098 
1099   // For diagnostics only used in run_periodic_checks
1100   sigemptyset(&check_signal_done);
1101 }
1102 
1103 // These are signals that are unblocked while a thread is running Java.
1104 // (For some reason, they get blocked by default.)
1105 sigset_t* os::Solaris::unblocked_signals() {
1106   assert(signal_sets_initialized, "Not initialized");
1107   return &unblocked_sigs;
1108 }
1109 
1110 // These are the signals that are blocked while a (non-VM) thread is
1111 // running Java. Only the VM thread handles these signals.
1112 sigset_t* os::Solaris::vm_signals() {
1113   assert(signal_sets_initialized, "Not initialized");
1114   return &vm_sigs;
1115 }
1116 
1117 // These are signals that are blocked during cond_wait to allow debugger in
1118 sigset_t* os::Solaris::allowdebug_blocked_signals() {
1119   assert(signal_sets_initialized, "Not initialized");
1120   return &allowdebug_blocked_sigs;
1121 }
1122 
1123 
1124 void _handle_uncaught_cxx_exception() {
1125   VMError::report_and_die("An uncaught C++ exception");
1126 }
1127 
1128 
1129 // First crack at OS-specific initialization, from inside the new thread.
1130 void os::initialize_thread(Thread* thr) {
1131   int r = thr_main();
1132   guarantee(r == 0 || r == 1, "CR6501650 or CR6493689");
1133   if (r) {
1134     JavaThread* jt = (JavaThread *)thr;
1135     assert(jt != NULL, "Sanity check");
1136     size_t stack_size;
1137     address base = jt->stack_base();
1138     if (Arguments::created_by_java_launcher()) {
1139       // Use 2MB to allow for Solaris 7 64 bit mode.
1140       stack_size = JavaThread::stack_size_at_create() == 0
1141         ? 2048*K : JavaThread::stack_size_at_create();
1142 
1143       // There are rare cases when we may have already used more than
1144       // the basic stack size allotment before this method is invoked.
1145       // Attempt to allow for a normally sized java_stack.
1146       size_t current_stack_offset = (size_t)(base - (address)&stack_size);
1147       stack_size += ReservedSpace::page_align_size_down(current_stack_offset);
1148     } else {
1149       // 6269555: If we were not created by a Java launcher, i.e. if we are
1150       // running embedded in a native application, treat the primordial thread
1151       // as much like a native attached thread as possible.  This means using
1152       // the current stack size from thr_stksegment(), unless it is too large
1153       // to reliably setup guard pages.  A reasonable max size is 8MB.
1154       size_t current_size = current_stack_size();
1155       // This should never happen, but just in case....
1156       if (current_size == 0) current_size = 2 * K * K;
1157       stack_size = current_size > (8 * K * K) ? (8 * K * K) : current_size;
1158     }
1159     address bottom = (address)align_size_up((intptr_t)(base - stack_size), os::vm_page_size());;
1160     stack_size = (size_t)(base - bottom);
1161 
1162     assert(stack_size > 0, "Stack size calculation problem");
1163 
1164     if (stack_size > jt->stack_size()) {
1165 #ifndef PRODUCT
1166       struct rlimit limits;
1167       getrlimit(RLIMIT_STACK, &limits);
1168       size_t size = adjust_stack_size(base, (size_t)limits.rlim_cur);
1169       assert(size >= jt->stack_size(), "Stack size problem in main thread");
1170 #endif
1171       tty->print_cr("Stack size of %d Kb exceeds current limit of %d Kb.\n"
1172                     "(Stack sizes are rounded up to a multiple of the system page size.)\n"
1173                     "See limit(1) to increase the stack size limit.",
1174                     stack_size / K, jt->stack_size() / K);
1175       vm_exit(1);
1176     }
1177     assert(jt->stack_size() >= stack_size,
1178            "Attempt to map more stack than was allocated");
1179     jt->set_stack_size(stack_size);
1180   }
1181 
1182   // With the T2 libthread (T1 is no longer supported) threads are always bound
1183   // and we use stackbanging in all cases.
1184 
1185   os::Solaris::init_thread_fpu_state();
1186   std::set_terminate(_handle_uncaught_cxx_exception);
1187 }
1188 
1189 
1190 
1191 // Free Solaris resources related to the OSThread
1192 void os::free_thread(OSThread* osthread) {
1193   assert(osthread != NULL, "os::free_thread but osthread not set");
1194 
1195   // We are told to free resources of the argument thread,
1196   // but we can only really operate on the current thread.
1197   assert(Thread::current()->osthread() == osthread,
1198          "os::free_thread but not current thread");
1199 
1200   // Restore caller's signal mask
1201   sigset_t sigmask = osthread->caller_sigmask();
1202   pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
1203 
1204   delete osthread;
1205 }
1206 
1207 void os::pd_start_thread(Thread* thread) {
1208   int status = thr_continue(thread->osthread()->thread_id());
1209   assert_status(status == 0, status, "thr_continue failed");
1210 }
1211 
1212 
1213 intx os::current_thread_id() {
1214   return (intx)thr_self();
1215 }
1216 
1217 static pid_t _initial_pid = 0;
1218 
1219 int os::current_process_id() {
1220   return (int)(_initial_pid ? _initial_pid : getpid());
1221 }
1222 
1223 // gethrtime() should be monotonic according to the documentation,
1224 // but some virtualized platforms are known to break this guarantee.
1225 // getTimeNanos() must be guaranteed not to move backwards, so we
1226 // are forced to add a check here.
1227 inline hrtime_t getTimeNanos() {
1228   const hrtime_t now = gethrtime();
1229   const hrtime_t prev = max_hrtime;
1230   if (now <= prev) {
1231     return prev;   // same or retrograde time;
1232   }
1233   const hrtime_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&max_hrtime, prev);
1234   assert(obsv >= prev, "invariant");   // Monotonicity
1235   // If the CAS succeeded then we're done and return "now".
1236   // If the CAS failed and the observed value "obsv" is >= now then
1237   // we should return "obsv".  If the CAS failed and now > obsv > prv then
1238   // some other thread raced this thread and installed a new value, in which case
1239   // we could either (a) retry the entire operation, (b) retry trying to install now
1240   // or (c) just return obsv.  We use (c).   No loop is required although in some cases
1241   // we might discard a higher "now" value in deference to a slightly lower but freshly
1242   // installed obsv value.   That's entirely benign -- it admits no new orderings compared
1243   // to (a) or (b) -- and greatly reduces coherence traffic.
1244   // We might also condition (c) on the magnitude of the delta between obsv and now.
1245   // Avoiding excessive CAS operations to hot RW locations is critical.
1246   // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate
1247   return (prev == obsv) ? now : obsv;
1248 }
1249 
1250 // Time since start-up in seconds to a fine granularity.
1251 // Used by VMSelfDestructTimer and the MemProfiler.
1252 double os::elapsedTime() {
1253   return (double)(getTimeNanos() - first_hrtime) / (double)hrtime_hz;
1254 }
1255 
1256 jlong os::elapsed_counter() {
1257   return (jlong)(getTimeNanos() - first_hrtime);
1258 }
1259 
1260 jlong os::elapsed_frequency() {
1261   return hrtime_hz;
1262 }
1263 
1264 // Return the real, user, and system times in seconds from an
1265 // arbitrary fixed point in the past.
1266 bool os::getTimesSecs(double* process_real_time,
1267                       double* process_user_time,
1268                       double* process_system_time) {
1269   struct tms ticks;
1270   clock_t real_ticks = times(&ticks);
1271 
1272   if (real_ticks == (clock_t) (-1)) {
1273     return false;
1274   } else {
1275     double ticks_per_second = (double) clock_tics_per_sec;
1276     *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
1277     *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
1278     // For consistency return the real time from getTimeNanos()
1279     // converted to seconds.
1280     *process_real_time = ((double) getTimeNanos()) / ((double) NANOUNITS);
1281 
1282     return true;
1283   }
1284 }
1285 
1286 bool os::supports_vtime() { return true; }
1287 bool os::enable_vtime() { return false; }
1288 bool os::vtime_enabled() { return false; }
1289 
1290 double os::elapsedVTime() {
1291   return (double)gethrvtime() / (double)hrtime_hz;
1292 }
1293 
1294 // Must return millis since Jan 1 1970 for JVM_CurrentTimeMillis
1295 jlong os::javaTimeMillis() {
1296   timeval t;
1297   if (gettimeofday(&t, NULL) == -1) {
1298     fatal("os::javaTimeMillis: gettimeofday (%s)", os::strerror(errno));
1299   }
1300   return jlong(t.tv_sec) * 1000  +  jlong(t.tv_usec) / 1000;
1301 }
1302 
1303 // Must return seconds+nanos since Jan 1 1970. This must use the same
1304 // time source as javaTimeMillis and can't use get_nsec_fromepoch as
1305 // we need better than 1ms accuracy
1306 void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) {
1307   timeval t;
1308   if (gettimeofday(&t, NULL) == -1) {
1309     fatal("os::javaTimeSystemUTC: gettimeofday (%s)", os::strerror(errno));
1310   }
1311   seconds = jlong(t.tv_sec);
1312   nanos = jlong(t.tv_usec) * 1000;
1313 }
1314 
1315 
1316 jlong os::javaTimeNanos() {
1317   return (jlong)getTimeNanos();
1318 }
1319 
1320 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
1321   info_ptr->max_value = ALL_64_BITS;      // gethrtime() uses all 64 bits
1322   info_ptr->may_skip_backward = false;    // not subject to resetting or drifting
1323   info_ptr->may_skip_forward = false;     // not subject to resetting or drifting
1324   info_ptr->kind = JVMTI_TIMER_ELAPSED;   // elapsed not CPU time
1325 }
1326 
1327 char * os::local_time_string(char *buf, size_t buflen) {
1328   struct tm t;
1329   time_t long_time;
1330   time(&long_time);
1331   localtime_r(&long_time, &t);
1332   jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
1333                t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
1334                t.tm_hour, t.tm_min, t.tm_sec);
1335   return buf;
1336 }
1337 
1338 // Note: os::shutdown() might be called very early during initialization, or
1339 // called from signal handler. Before adding something to os::shutdown(), make
1340 // sure it is async-safe and can handle partially initialized VM.
1341 void os::shutdown() {
1342 
1343   // allow PerfMemory to attempt cleanup of any persistent resources
1344   perfMemory_exit();
1345 
1346   // needs to remove object in file system
1347   AttachListener::abort();
1348 
1349   // flush buffered output, finish log files
1350   ostream_abort();
1351 
1352   // Check for abort hook
1353   abort_hook_t abort_hook = Arguments::abort_hook();
1354   if (abort_hook != NULL) {
1355     abort_hook();
1356   }
1357 }
1358 
1359 // Note: os::abort() might be called very early during initialization, or
1360 // called from signal handler. Before adding something to os::abort(), make
1361 // sure it is async-safe and can handle partially initialized VM.
1362 void os::abort(bool dump_core, void* siginfo, const void* context) {
1363   os::shutdown();
1364   if (dump_core) {
1365 #ifndef PRODUCT
1366     fdStream out(defaultStream::output_fd());
1367     out.print_raw("Current thread is ");
1368     char buf[16];
1369     jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
1370     out.print_raw_cr(buf);
1371     out.print_raw_cr("Dumping core ...");
1372 #endif
1373     ::abort(); // dump core (for debugging)
1374   }
1375 
1376   ::exit(1);
1377 }
1378 
1379 // Die immediately, no exit hook, no abort hook, no cleanup.
1380 void os::die() {
1381   ::abort(); // dump core (for debugging)
1382 }
1383 
1384 // DLL functions
1385 
1386 const char* os::dll_file_extension() { return ".so"; }
1387 
1388 // This must be hard coded because it's the system's temporary
1389 // directory not the java application's temp directory, ala java.io.tmpdir.
1390 const char* os::get_temp_directory() { return "/tmp"; }
1391 
1392 static bool file_exists(const char* filename) {
1393   struct stat statbuf;
1394   if (filename == NULL || strlen(filename) == 0) {
1395     return false;
1396   }
1397   return os::stat(filename, &statbuf) == 0;
1398 }
1399 
1400 bool os::dll_build_name(char* buffer, size_t buflen,
1401                         const char* pname, const char* fname) {
1402   bool retval = false;
1403   const size_t pnamelen = pname ? strlen(pname) : 0;
1404 
1405   // Return error on buffer overflow.
1406   if (pnamelen + strlen(fname) + 10 > (size_t) buflen) {
1407     return retval;
1408   }
1409 
1410   if (pnamelen == 0) {
1411     snprintf(buffer, buflen, "lib%s.so", fname);
1412     retval = true;
1413   } else if (strchr(pname, *os::path_separator()) != NULL) {
1414     int n;
1415     char** pelements = split_path(pname, &n);
1416     if (pelements == NULL) {
1417       return false;
1418     }
1419     for (int i = 0; i < n; i++) {
1420       // really shouldn't be NULL but what the heck, check can't hurt
1421       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
1422         continue; // skip the empty path values
1423       }
1424       snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname);
1425       if (file_exists(buffer)) {
1426         retval = true;
1427         break;
1428       }
1429     }
1430     // release the storage
1431     for (int i = 0; i < n; i++) {
1432       if (pelements[i] != NULL) {
1433         FREE_C_HEAP_ARRAY(char, pelements[i]);
1434       }
1435     }
1436     if (pelements != NULL) {
1437       FREE_C_HEAP_ARRAY(char*, pelements);
1438     }
1439   } else {
1440     snprintf(buffer, buflen, "%s/lib%s.so", pname, fname);
1441     retval = true;
1442   }
1443   return retval;
1444 }
1445 
1446 // check if addr is inside libjvm.so
1447 bool os::address_is_in_vm(address addr) {
1448   static address libjvm_base_addr;
1449   Dl_info dlinfo;
1450 
1451   if (libjvm_base_addr == NULL) {
1452     if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
1453       libjvm_base_addr = (address)dlinfo.dli_fbase;
1454     }
1455     assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1456   }
1457 
1458   if (dladdr((void *)addr, &dlinfo) != 0) {
1459     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1460   }
1461 
1462   return false;
1463 }
1464 
1465 typedef int (*dladdr1_func_type)(void *, Dl_info *, void **, int);
1466 static dladdr1_func_type dladdr1_func = NULL;
1467 
1468 bool os::dll_address_to_function_name(address addr, char *buf,
1469                                       int buflen, int * offset,
1470                                       bool demangle) {
1471   // buf is not optional, but offset is optional
1472   assert(buf != NULL, "sanity check");
1473 
1474   Dl_info dlinfo;
1475 
1476   // dladdr1_func was initialized in os::init()
1477   if (dladdr1_func != NULL) {
1478     // yes, we have dladdr1
1479 
1480     // Support for dladdr1 is checked at runtime; it may be
1481     // available even if the vm is built on a machine that does
1482     // not have dladdr1 support.  Make sure there is a value for
1483     // RTLD_DL_SYMENT.
1484 #ifndef RTLD_DL_SYMENT
1485   #define RTLD_DL_SYMENT 1
1486 #endif
1487 #ifdef _LP64
1488     Elf64_Sym * info;
1489 #else
1490     Elf32_Sym * info;
1491 #endif
1492     if (dladdr1_func((void *)addr, &dlinfo, (void **)&info,
1493                      RTLD_DL_SYMENT) != 0) {
1494       // see if we have a matching symbol that covers our address
1495       if (dlinfo.dli_saddr != NULL &&
1496           (char *)dlinfo.dli_saddr + info->st_size > (char *)addr) {
1497         if (dlinfo.dli_sname != NULL) {
1498           if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) {
1499             jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1500           }
1501           if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1502           return true;
1503         }
1504       }
1505       // no matching symbol so try for just file info
1506       if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1507         if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1508                             buf, buflen, offset, dlinfo.dli_fname, demangle)) {
1509           return true;
1510         }
1511       }
1512     }
1513     buf[0] = '\0';
1514     if (offset != NULL) *offset  = -1;
1515     return false;
1516   }
1517 
1518   // no, only dladdr is available
1519   if (dladdr((void *)addr, &dlinfo) != 0) {
1520     // see if we have a matching symbol
1521     if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
1522       if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) {
1523         jio_snprintf(buf, buflen, dlinfo.dli_sname);
1524       }
1525       if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1526       return true;
1527     }
1528     // no matching symbol so try for just file info
1529     if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1530       if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1531                           buf, buflen, offset, dlinfo.dli_fname, demangle)) {
1532         return true;
1533       }
1534     }
1535   }
1536   buf[0] = '\0';
1537   if (offset != NULL) *offset  = -1;
1538   return false;
1539 }
1540 
1541 bool os::dll_address_to_library_name(address addr, char* buf,
1542                                      int buflen, int* offset) {
1543   // buf is not optional, but offset is optional
1544   assert(buf != NULL, "sanity check");
1545 
1546   Dl_info dlinfo;
1547 
1548   if (dladdr((void*)addr, &dlinfo) != 0) {
1549     if (dlinfo.dli_fname != NULL) {
1550       jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1551     }
1552     if (dlinfo.dli_fbase != NULL && offset != NULL) {
1553       *offset = addr - (address)dlinfo.dli_fbase;
1554     }
1555     return true;
1556   }
1557 
1558   buf[0] = '\0';
1559   if (offset) *offset = -1;
1560   return false;
1561 }
1562 
1563 int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) {
1564   Dl_info dli;
1565   // Sanity check?
1566   if (dladdr(CAST_FROM_FN_PTR(void *, os::get_loaded_modules_info), &dli) == 0 ||
1567       dli.dli_fname == NULL) {
1568     return 1;
1569   }
1570 
1571   void * handle = dlopen(dli.dli_fname, RTLD_LAZY);
1572   if (handle == NULL) {
1573     return 1;
1574   }
1575 
1576   Link_map *map;
1577   dlinfo(handle, RTLD_DI_LINKMAP, &map);
1578   if (map == NULL) {
1579     dlclose(handle);
1580     return 1;
1581   }
1582 
1583   while (map->l_prev != NULL) {
1584     map = map->l_prev;
1585   }
1586 
1587   while (map != NULL) {
1588     // Iterate through all map entries and call callback with fields of interest
1589     if(callback(map->l_name, (address)map->l_addr, (address)0, param)) {
1590       dlclose(handle);
1591       return 1;
1592     }
1593     map = map->l_next;
1594   }
1595 
1596   dlclose(handle);
1597   return 0;
1598 }
1599 
1600 int _print_dll_info_cb(const char * name, address base_address, address top_address, void * param) {
1601   outputStream * out = (outputStream *) param;
1602   out->print_cr(PTR_FORMAT " \t%s", base_address, name);
1603   return 0;
1604 }
1605 
1606 void os::print_dll_info(outputStream * st) {
1607   st->print_cr("Dynamic libraries:"); st->flush();
1608   if (get_loaded_modules_info(_print_dll_info_cb, (void *)st)) {
1609     st->print_cr("Error: Cannot print dynamic libraries.");
1610   }
1611 }
1612 
1613 // Loads .dll/.so and
1614 // in case of error it checks if .dll/.so was built for the
1615 // same architecture as Hotspot is running on
1616 
1617 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1618   void * result= ::dlopen(filename, RTLD_LAZY);
1619   if (result != NULL) {
1620     // Successful loading
1621     return result;
1622   }
1623 
1624   Elf32_Ehdr elf_head;
1625 
1626   // Read system error message into ebuf
1627   // It may or may not be overwritten below
1628   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
1629   ebuf[ebuflen-1]='\0';
1630   int diag_msg_max_length=ebuflen-strlen(ebuf);
1631   char* diag_msg_buf=ebuf+strlen(ebuf);
1632 
1633   if (diag_msg_max_length==0) {
1634     // No more space in ebuf for additional diagnostics message
1635     return NULL;
1636   }
1637 
1638 
1639   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1640 
1641   if (file_descriptor < 0) {
1642     // Can't open library, report dlerror() message
1643     return NULL;
1644   }
1645 
1646   bool failed_to_read_elf_head=
1647     (sizeof(elf_head)!=
1648      (::read(file_descriptor, &elf_head,sizeof(elf_head))));
1649 
1650   ::close(file_descriptor);
1651   if (failed_to_read_elf_head) {
1652     // file i/o error - report dlerror() msg
1653     return NULL;
1654   }
1655 
1656   typedef struct {
1657     Elf32_Half  code;         // Actual value as defined in elf.h
1658     Elf32_Half  compat_class; // Compatibility of archs at VM's sense
1659     char        elf_class;    // 32 or 64 bit
1660     char        endianess;    // MSB or LSB
1661     char*       name;         // String representation
1662   } arch_t;
1663 
1664   static const arch_t arch_array[]={
1665     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1666     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1667     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1668     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1669     {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1670     {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1671     {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
1672     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1673     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1674     {EM_ARM,         EM_ARM,     ELFCLASS32, ELFDATA2LSB, (char*)"ARM 32"}
1675   };
1676 
1677 #if  (defined IA32)
1678   static  Elf32_Half running_arch_code=EM_386;
1679 #elif   (defined AMD64)
1680   static  Elf32_Half running_arch_code=EM_X86_64;
1681 #elif  (defined IA64)
1682   static  Elf32_Half running_arch_code=EM_IA_64;
1683 #elif  (defined __sparc) && (defined _LP64)
1684   static  Elf32_Half running_arch_code=EM_SPARCV9;
1685 #elif  (defined __sparc) && (!defined _LP64)
1686   static  Elf32_Half running_arch_code=EM_SPARC;
1687 #elif  (defined __powerpc64__)
1688   static  Elf32_Half running_arch_code=EM_PPC64;
1689 #elif  (defined __powerpc__)
1690   static  Elf32_Half running_arch_code=EM_PPC;
1691 #elif (defined ARM)
1692   static  Elf32_Half running_arch_code=EM_ARM;
1693 #else
1694   #error Method os::dll_load requires that one of following is defined:\
1695        IA32, AMD64, IA64, __sparc, __powerpc__, ARM, ARM
1696 #endif
1697 
1698   // Identify compatability class for VM's architecture and library's architecture
1699   // Obtain string descriptions for architectures
1700 
1701   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
1702   int running_arch_index=-1;
1703 
1704   for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) {
1705     if (running_arch_code == arch_array[i].code) {
1706       running_arch_index    = i;
1707     }
1708     if (lib_arch.code == arch_array[i].code) {
1709       lib_arch.compat_class = arch_array[i].compat_class;
1710       lib_arch.name         = arch_array[i].name;
1711     }
1712   }
1713 
1714   assert(running_arch_index != -1,
1715          "Didn't find running architecture code (running_arch_code) in arch_array");
1716   if (running_arch_index == -1) {
1717     // Even though running architecture detection failed
1718     // we may still continue with reporting dlerror() message
1719     return NULL;
1720   }
1721 
1722   if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
1723     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
1724     return NULL;
1725   }
1726 
1727   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
1728     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
1729     return NULL;
1730   }
1731 
1732   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
1733     if (lib_arch.name!=NULL) {
1734       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1735                  " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
1736                  lib_arch.name, arch_array[running_arch_index].name);
1737     } else {
1738       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1739                  " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
1740                  lib_arch.code,
1741                  arch_array[running_arch_index].name);
1742     }
1743   }
1744 
1745   return NULL;
1746 }
1747 
1748 void* os::dll_lookup(void* handle, const char* name) {
1749   return dlsym(handle, name);
1750 }
1751 
1752 void* os::get_default_process_handle() {
1753   return (void*)::dlopen(NULL, RTLD_LAZY);
1754 }
1755 
1756 int os::stat(const char *path, struct stat *sbuf) {
1757   char pathbuf[MAX_PATH];
1758   if (strlen(path) > MAX_PATH - 1) {
1759     errno = ENAMETOOLONG;
1760     return -1;
1761   }
1762   os::native_path(strcpy(pathbuf, path));
1763   return ::stat(pathbuf, sbuf);
1764 }
1765 
1766 static inline time_t get_mtime(const char* filename) {
1767   struct stat st;
1768   int ret = os::stat(filename, &st);
1769   assert(ret == 0, "failed to stat() file '%s': %s", filename, strerror(errno));
1770   return st.st_mtime;
1771 }
1772 
1773 int os::compare_file_modified_times(const char* file1, const char* file2) {
1774   time_t t1 = get_mtime(file1);
1775   time_t t2 = get_mtime(file2);
1776   return t1 - t2;
1777 }
1778 
1779 static bool _print_ascii_file(const char* filename, outputStream* st) {
1780   int fd = ::open(filename, O_RDONLY);
1781   if (fd == -1) {
1782     return false;
1783   }
1784 
1785   char buf[32];
1786   int bytes;
1787   while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
1788     st->print_raw(buf, bytes);
1789   }
1790 
1791   ::close(fd);
1792 
1793   return true;
1794 }
1795 
1796 void os::print_os_info_brief(outputStream* st) {
1797   os::Solaris::print_distro_info(st);
1798 
1799   os::Posix::print_uname_info(st);
1800 
1801   os::Solaris::print_libversion_info(st);
1802 }
1803 
1804 void os::print_os_info(outputStream* st) {
1805   st->print("OS:");
1806 
1807   os::Solaris::print_distro_info(st);
1808 
1809   os::Posix::print_uname_info(st);
1810 
1811   os::Solaris::print_libversion_info(st);
1812 
1813   os::Posix::print_rlimit_info(st);
1814 
1815   os::Posix::print_load_average(st);
1816 }
1817 
1818 void os::Solaris::print_distro_info(outputStream* st) {
1819   if (!_print_ascii_file("/etc/release", st)) {
1820     st->print("Solaris");
1821   }
1822   st->cr();
1823 }
1824 
1825 void os::get_summary_os_info(char* buf, size_t buflen) {
1826   strncpy(buf, "Solaris", buflen);  // default to plain solaris
1827   FILE* fp = fopen("/etc/release", "r");
1828   if (fp != NULL) {
1829     char tmp[256];
1830     // Only get the first line and chop out everything but the os name.
1831     if (fgets(tmp, sizeof(tmp), fp)) {
1832       char* ptr = tmp;
1833       // skip past whitespace characters
1834       while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t' || *ptr == '\n')) ptr++;
1835       if (*ptr != '\0') {
1836         char* nl = strchr(ptr, '\n');
1837         if (nl != NULL) *nl = '\0';
1838         strncpy(buf, ptr, buflen);
1839       }
1840     }
1841     fclose(fp);
1842   }
1843 }
1844 
1845 void os::Solaris::print_libversion_info(outputStream* st) {
1846   st->print("  (T2 libthread)");
1847   st->cr();
1848 }
1849 
1850 static bool check_addr0(outputStream* st) {
1851   jboolean status = false;
1852   const int read_chunk = 200;
1853   int ret = 0;
1854   int nmap = 0;
1855   int fd = ::open("/proc/self/map",O_RDONLY);
1856   if (fd >= 0) {
1857     prmap_t *p = NULL;
1858     char *mbuff = (char *) calloc(read_chunk, sizeof(prmap_t));
1859     if (NULL == mbuff) {
1860       ::close(fd);
1861       return status;
1862     }
1863     while ((ret = ::read(fd, mbuff, read_chunk*sizeof(prmap_t))) > 0) {
1864       //check if read() has not read partial data
1865       if( 0 != ret % sizeof(prmap_t)){
1866         break;
1867       }
1868       nmap = ret / sizeof(prmap_t);
1869       p = (prmap_t *)mbuff;
1870       for(int i = 0; i < nmap; i++){
1871         if (p->pr_vaddr == 0x0) {
1872           st->print("Warning: Address: " PTR_FORMAT ", Size: " SIZE_FORMAT "K, ",p->pr_vaddr, p->pr_size/1024);
1873           st->print("Mapped file: %s, ", p->pr_mapname[0] == '\0' ? "None" : p->pr_mapname);
1874           st->print("Access: ");
1875           st->print("%s",(p->pr_mflags & MA_READ)  ? "r" : "-");
1876           st->print("%s",(p->pr_mflags & MA_WRITE) ? "w" : "-");
1877           st->print("%s",(p->pr_mflags & MA_EXEC)  ? "x" : "-");
1878           st->cr();
1879           status = true;
1880         }
1881         p++;
1882       }
1883     }
1884     free(mbuff);
1885     ::close(fd);
1886   }
1887   return status;
1888 }
1889 
1890 void os::get_summary_cpu_info(char* buf, size_t buflen) {
1891   // Get MHz with system call. We don't seem to already have this.
1892   processor_info_t stats;
1893   processorid_t id = getcpuid();
1894   int clock = 0;
1895   if (processor_info(id, &stats) != -1) {
1896     clock = stats.pi_clock;  // pi_processor_type isn't more informative than below
1897   }
1898 #ifdef AMD64
1899   snprintf(buf, buflen, "x86 64 bit %d MHz", clock);
1900 #else
1901   // must be sparc
1902   snprintf(buf, buflen, "Sparcv9 64 bit %d MHz", clock);
1903 #endif
1904 }
1905 
1906 void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {
1907   // Nothing to do for now.
1908 }
1909 
1910 void os::print_memory_info(outputStream* st) {
1911   st->print("Memory:");
1912   st->print(" %dk page", os::vm_page_size()>>10);
1913   st->print(", physical " UINT64_FORMAT "k", os::physical_memory()>>10);
1914   st->print("(" UINT64_FORMAT "k free)", os::available_memory() >> 10);
1915   st->cr();
1916   (void) check_addr0(st);
1917 }
1918 
1919 // Moved from whole group, because we need them here for diagnostic
1920 // prints.
1921 #define OLDMAXSIGNUM 32
1922 static int Maxsignum = 0;
1923 static int *ourSigFlags = NULL;
1924 
1925 int os::Solaris::get_our_sigflags(int sig) {
1926   assert(ourSigFlags!=NULL, "signal data structure not initialized");
1927   assert(sig > 0 && sig < Maxsignum, "vm signal out of expected range");
1928   return ourSigFlags[sig];
1929 }
1930 
1931 void os::Solaris::set_our_sigflags(int sig, int flags) {
1932   assert(ourSigFlags!=NULL, "signal data structure not initialized");
1933   assert(sig > 0 && sig < Maxsignum, "vm signal out of expected range");
1934   ourSigFlags[sig] = flags;
1935 }
1936 
1937 
1938 static const char* get_signal_handler_name(address handler,
1939                                            char* buf, int buflen) {
1940   int offset;
1941   bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
1942   if (found) {
1943     // skip directory names
1944     const char *p1, *p2;
1945     p1 = buf;
1946     size_t len = strlen(os::file_separator());
1947     while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
1948     jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
1949   } else {
1950     jio_snprintf(buf, buflen, PTR_FORMAT, handler);
1951   }
1952   return buf;
1953 }
1954 
1955 static void print_signal_handler(outputStream* st, int sig,
1956                                  char* buf, size_t buflen) {
1957   struct sigaction sa;
1958 
1959   sigaction(sig, NULL, &sa);
1960 
1961   st->print("%s: ", os::exception_name(sig, buf, buflen));
1962 
1963   address handler = (sa.sa_flags & SA_SIGINFO)
1964                   ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
1965                   : CAST_FROM_FN_PTR(address, sa.sa_handler);
1966 
1967   if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
1968     st->print("SIG_DFL");
1969   } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
1970     st->print("SIG_IGN");
1971   } else {
1972     st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
1973   }
1974 
1975   st->print(", sa_mask[0]=");
1976   os::Posix::print_signal_set_short(st, &sa.sa_mask);
1977 
1978   address rh = VMError::get_resetted_sighandler(sig);
1979   // May be, handler was resetted by VMError?
1980   if (rh != NULL) {
1981     handler = rh;
1982     sa.sa_flags = VMError::get_resetted_sigflags(sig);
1983   }
1984 
1985   st->print(", sa_flags=");
1986   os::Posix::print_sa_flags(st, sa.sa_flags);
1987 
1988   // Check: is it our handler?
1989   if (handler == CAST_FROM_FN_PTR(address, signalHandler)) {
1990     // It is our signal handler
1991     // check for flags
1992     if (sa.sa_flags != os::Solaris::get_our_sigflags(sig)) {
1993       st->print(
1994                 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
1995                 os::Solaris::get_our_sigflags(sig));
1996     }
1997   }
1998   st->cr();
1999 }
2000 
2001 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
2002   st->print_cr("Signal Handlers:");
2003   print_signal_handler(st, SIGSEGV, buf, buflen);
2004   print_signal_handler(st, SIGBUS , buf, buflen);
2005   print_signal_handler(st, SIGFPE , buf, buflen);
2006   print_signal_handler(st, SIGPIPE, buf, buflen);
2007   print_signal_handler(st, SIGXFSZ, buf, buflen);
2008   print_signal_handler(st, SIGILL , buf, buflen);
2009   print_signal_handler(st, ASYNC_SIGNAL, buf, buflen);
2010   print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
2011   print_signal_handler(st, SHUTDOWN1_SIGNAL , buf, buflen);
2012   print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
2013   print_signal_handler(st, SHUTDOWN3_SIGNAL, buf, buflen);
2014   print_signal_handler(st, os::Solaris::SIGasync(), buf, buflen);
2015 }
2016 
2017 static char saved_jvm_path[MAXPATHLEN] = { 0 };
2018 
2019 // Find the full path to the current module, libjvm.so
2020 void os::jvm_path(char *buf, jint buflen) {
2021   // Error checking.
2022   if (buflen < MAXPATHLEN) {
2023     assert(false, "must use a large-enough buffer");
2024     buf[0] = '\0';
2025     return;
2026   }
2027   // Lazy resolve the path to current module.
2028   if (saved_jvm_path[0] != 0) {
2029     strcpy(buf, saved_jvm_path);
2030     return;
2031   }
2032 
2033   Dl_info dlinfo;
2034   int ret = dladdr(CAST_FROM_FN_PTR(void *, os::jvm_path), &dlinfo);
2035   assert(ret != 0, "cannot locate libjvm");
2036   if (ret != 0 && dlinfo.dli_fname != NULL) {
2037     if (os::Posix::realpath((char *)dlinfo.dli_fname, buf, buflen) == NULL) {
2038       return;
2039     }
2040   } else {
2041     buf[0] = '\0';
2042     return;
2043   }
2044 
2045   if (Arguments::sun_java_launcher_is_altjvm()) {
2046     // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
2047     // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so".
2048     // If "/jre/lib/" appears at the right place in the string, then
2049     // assume we are installed in a JDK and we're done.  Otherwise, check
2050     // for a JAVA_HOME environment variable and fix up the path so it
2051     // looks like libjvm.so is installed there (append a fake suffix
2052     // hotspot/libjvm.so).
2053     const char *p = buf + strlen(buf) - 1;
2054     for (int count = 0; p > buf && count < 5; ++count) {
2055       for (--p; p > buf && *p != '/'; --p)
2056         /* empty */ ;
2057     }
2058 
2059     if (strncmp(p, "/jre/lib/", 9) != 0) {
2060       // Look for JAVA_HOME in the environment.
2061       char* java_home_var = ::getenv("JAVA_HOME");
2062       if (java_home_var != NULL && java_home_var[0] != 0) {
2063         char* jrelib_p;
2064         int   len;
2065 
2066         // Check the current module name "libjvm.so".
2067         p = strrchr(buf, '/');
2068         assert(strstr(p, "/libjvm") == p, "invalid library name");
2069 
2070         if (os::Posix::realpath(java_home_var, buf, buflen) == NULL) {
2071           return;
2072         }
2073         // determine if this is a legacy image or modules image
2074         // modules image doesn't have "jre" subdirectory
2075         len = strlen(buf);
2076         assert(len < buflen, "Ran out of buffer space");
2077         jrelib_p = buf + len;
2078         snprintf(jrelib_p, buflen-len, "/jre/lib");
2079         if (0 != access(buf, F_OK)) {
2080           snprintf(jrelib_p, buflen-len, "/lib");
2081         }
2082 
2083         if (0 == access(buf, F_OK)) {
2084           // Use current module name "libjvm.so"
2085           len = strlen(buf);
2086           snprintf(buf + len, buflen-len, "/hotspot/libjvm.so");
2087         } else {
2088           // Go back to path of .so
2089           if (os::Posix::realpath((char *)dlinfo.dli_fname, buf, buflen) == NULL) {
2090             return;
2091           }
2092         }
2093       }
2094     }
2095   }
2096 
2097   strncpy(saved_jvm_path, buf, MAXPATHLEN);
2098   saved_jvm_path[MAXPATHLEN - 1] = '\0';
2099 }
2100 
2101 
2102 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
2103   // no prefix required, not even "_"
2104 }
2105 
2106 
2107 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
2108   // no suffix required
2109 }
2110 
2111 // This method is a copy of JDK's sysGetLastErrorString
2112 // from src/solaris/hpi/src/system_md.c
2113 
2114 size_t os::lasterror(char *buf, size_t len) {
2115   if (errno == 0)  return 0;
2116 
2117   const char *s = os::strerror(errno);
2118   size_t n = ::strlen(s);
2119   if (n >= len) {
2120     n = len - 1;
2121   }
2122   ::strncpy(buf, s, n);
2123   buf[n] = '\0';
2124   return n;
2125 }
2126 
2127 
2128 // sun.misc.Signal
2129 
2130 extern "C" {
2131   static void UserHandler(int sig, void *siginfo, void *context) {
2132     // Ctrl-C is pressed during error reporting, likely because the error
2133     // handler fails to abort. Let VM die immediately.
2134     if (sig == SIGINT && is_error_reported()) {
2135       os::die();
2136     }
2137 
2138     os::signal_notify(sig);
2139     // We do not need to reinstate the signal handler each time...
2140   }
2141 }
2142 
2143 void* os::user_handler() {
2144   return CAST_FROM_FN_PTR(void*, UserHandler);
2145 }
2146 
2147 struct timespec PosixSemaphore::create_timespec(unsigned int sec, int nsec) {
2148   struct timespec ts;
2149   unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
2150 
2151   return ts;
2152 }
2153 
2154 extern "C" {
2155   typedef void (*sa_handler_t)(int);
2156   typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
2157 }
2158 
2159 void* os::signal(int signal_number, void* handler) {
2160   struct sigaction sigAct, oldSigAct;
2161   sigfillset(&(sigAct.sa_mask));
2162   sigAct.sa_flags = SA_RESTART & ~SA_RESETHAND;
2163   sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
2164 
2165   if (sigaction(signal_number, &sigAct, &oldSigAct)) {
2166     // -1 means registration failed
2167     return (void *)-1;
2168   }
2169 
2170   return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
2171 }
2172 
2173 void os::signal_raise(int signal_number) {
2174   raise(signal_number);
2175 }
2176 
2177 // The following code is moved from os.cpp for making this
2178 // code platform specific, which it is by its very nature.
2179 
2180 // a counter for each possible signal value
2181 static int Sigexit = 0;
2182 static int Maxlibjsigsigs;
2183 static jint *pending_signals = NULL;
2184 static int *preinstalled_sigs = NULL;
2185 static struct sigaction *chainedsigactions = NULL;
2186 static sema_t sig_sem;
2187 typedef int (*version_getting_t)();
2188 version_getting_t os::Solaris::get_libjsig_version = NULL;
2189 static int libjsigversion = NULL;
2190 
2191 int os::sigexitnum_pd() {
2192   assert(Sigexit > 0, "signal memory not yet initialized");
2193   return Sigexit;
2194 }
2195 
2196 void os::Solaris::init_signal_mem() {
2197   // Initialize signal structures
2198   Maxsignum = SIGRTMAX;
2199   Sigexit = Maxsignum+1;
2200   assert(Maxsignum >0, "Unable to obtain max signal number");
2201 
2202   Maxlibjsigsigs = Maxsignum;
2203 
2204   // pending_signals has one int per signal
2205   // The additional signal is for SIGEXIT - exit signal to signal_thread
2206   pending_signals = (jint *)os::malloc(sizeof(jint) * (Sigexit+1), mtInternal);
2207   memset(pending_signals, 0, (sizeof(jint) * (Sigexit+1)));
2208 
2209   if (UseSignalChaining) {
2210     chainedsigactions = (struct sigaction *)malloc(sizeof(struct sigaction)
2211                                                    * (Maxsignum + 1), mtInternal);
2212     memset(chainedsigactions, 0, (sizeof(struct sigaction) * (Maxsignum + 1)));
2213     preinstalled_sigs = (int *)os::malloc(sizeof(int) * (Maxsignum + 1), mtInternal);
2214     memset(preinstalled_sigs, 0, (sizeof(int) * (Maxsignum + 1)));
2215   }
2216   ourSigFlags = (int*)malloc(sizeof(int) * (Maxsignum + 1), mtInternal);
2217   memset(ourSigFlags, 0, sizeof(int) * (Maxsignum + 1));
2218 }
2219 
2220 void os::signal_init_pd() {
2221   int ret;
2222 
2223   ret = ::sema_init(&sig_sem, 0, NULL, NULL);
2224   assert(ret == 0, "sema_init() failed");
2225 }
2226 
2227 void os::signal_notify(int signal_number) {
2228   int ret;
2229 
2230   Atomic::inc(&pending_signals[signal_number]);
2231   ret = ::sema_post(&sig_sem);
2232   assert(ret == 0, "sema_post() failed");
2233 }
2234 
2235 static int check_pending_signals(bool wait_for_signal) {
2236   int ret;
2237   while (true) {
2238     for (int i = 0; i < Sigexit + 1; i++) {
2239       jint n = pending_signals[i];
2240       if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
2241         return i;
2242       }
2243     }
2244     if (!wait_for_signal) {
2245       return -1;
2246     }
2247     JavaThread *thread = JavaThread::current();
2248     ThreadBlockInVM tbivm(thread);
2249 
2250     bool threadIsSuspended;
2251     do {
2252       thread->set_suspend_equivalent();
2253       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
2254       while ((ret = ::sema_wait(&sig_sem)) == EINTR)
2255         ;
2256       assert(ret == 0, "sema_wait() failed");
2257 
2258       // were we externally suspended while we were waiting?
2259       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
2260       if (threadIsSuspended) {
2261         // The semaphore has been incremented, but while we were waiting
2262         // another thread suspended us. We don't want to continue running
2263         // while suspended because that would surprise the thread that
2264         // suspended us.
2265         ret = ::sema_post(&sig_sem);
2266         assert(ret == 0, "sema_post() failed");
2267 
2268         thread->java_suspend_self();
2269       }
2270     } while (threadIsSuspended);
2271   }
2272 }
2273 
2274 int os::signal_lookup() {
2275   return check_pending_signals(false);
2276 }
2277 
2278 int os::signal_wait() {
2279   return check_pending_signals(true);
2280 }
2281 
2282 ////////////////////////////////////////////////////////////////////////////////
2283 // Virtual Memory
2284 
2285 static int page_size = -1;
2286 
2287 // The mmap MAP_ALIGN flag is supported on Solaris 9 and later.  init_2() will
2288 // clear this var if support is not available.
2289 static bool has_map_align = true;
2290 
2291 int os::vm_page_size() {
2292   assert(page_size != -1, "must call os::init");
2293   return page_size;
2294 }
2295 
2296 // Solaris allocates memory by pages.
2297 int os::vm_allocation_granularity() {
2298   assert(page_size != -1, "must call os::init");
2299   return page_size;
2300 }
2301 
2302 static bool recoverable_mmap_error(int err) {
2303   // See if the error is one we can let the caller handle. This
2304   // list of errno values comes from the Solaris mmap(2) man page.
2305   switch (err) {
2306   case EBADF:
2307   case EINVAL:
2308   case ENOTSUP:
2309     // let the caller deal with these errors
2310     return true;
2311 
2312   default:
2313     // Any remaining errors on this OS can cause our reserved mapping
2314     // to be lost. That can cause confusion where different data
2315     // structures think they have the same memory mapped. The worst
2316     // scenario is if both the VM and a library think they have the
2317     // same memory mapped.
2318     return false;
2319   }
2320 }
2321 
2322 static void warn_fail_commit_memory(char* addr, size_t bytes, bool exec,
2323                                     int err) {
2324   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2325           ", %d) failed; error='%s' (errno=%d)", addr, bytes, exec,
2326           os::strerror(err), err);
2327 }
2328 
2329 static void warn_fail_commit_memory(char* addr, size_t bytes,
2330                                     size_t alignment_hint, bool exec,
2331                                     int err) {
2332   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2333           ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", addr, bytes,
2334           alignment_hint, exec, os::strerror(err), err);
2335 }
2336 
2337 int os::Solaris::commit_memory_impl(char* addr, size_t bytes, bool exec) {
2338   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2339   size_t size = bytes;
2340   char *res = Solaris::mmap_chunk(addr, size, MAP_PRIVATE|MAP_FIXED, prot);
2341   if (res != NULL) {
2342     if (UseNUMAInterleaving) {
2343       numa_make_global(addr, bytes);
2344     }
2345     return 0;
2346   }
2347 
2348   int err = errno;  // save errno from mmap() call in mmap_chunk()
2349 
2350   if (!recoverable_mmap_error(err)) {
2351     warn_fail_commit_memory(addr, bytes, exec, err);
2352     vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "committing reserved memory.");
2353   }
2354 
2355   return err;
2356 }
2357 
2358 bool os::pd_commit_memory(char* addr, size_t bytes, bool exec) {
2359   return Solaris::commit_memory_impl(addr, bytes, exec) == 0;
2360 }
2361 
2362 void os::pd_commit_memory_or_exit(char* addr, size_t bytes, bool exec,
2363                                   const char* mesg) {
2364   assert(mesg != NULL, "mesg must be specified");
2365   int err = os::Solaris::commit_memory_impl(addr, bytes, exec);
2366   if (err != 0) {
2367     // the caller wants all commit errors to exit with the specified mesg:
2368     warn_fail_commit_memory(addr, bytes, exec, err);
2369     vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "%s", mesg);
2370   }
2371 }
2372 
2373 size_t os::Solaris::page_size_for_alignment(size_t alignment) {
2374   assert(is_size_aligned(alignment, (size_t) vm_page_size()),
2375          SIZE_FORMAT " is not aligned to " SIZE_FORMAT,
2376          alignment, (size_t) vm_page_size());
2377 
2378   for (int i = 0; _page_sizes[i] != 0; i++) {
2379     if (is_size_aligned(alignment, _page_sizes[i])) {
2380       return _page_sizes[i];
2381     }
2382   }
2383 
2384   return (size_t) vm_page_size();
2385 }
2386 
2387 int os::Solaris::commit_memory_impl(char* addr, size_t bytes,
2388                                     size_t alignment_hint, bool exec) {
2389   int err = Solaris::commit_memory_impl(addr, bytes, exec);
2390   if (err == 0 && UseLargePages && alignment_hint > 0) {
2391     assert(is_size_aligned(bytes, alignment_hint),
2392            SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, alignment_hint);
2393 
2394     // The syscall memcntl requires an exact page size (see man memcntl for details).
2395     size_t page_size = page_size_for_alignment(alignment_hint);
2396     if (page_size > (size_t) vm_page_size()) {
2397       (void)Solaris::setup_large_pages(addr, bytes, page_size);
2398     }
2399   }
2400   return err;
2401 }
2402 
2403 bool os::pd_commit_memory(char* addr, size_t bytes, size_t alignment_hint,
2404                           bool exec) {
2405   return Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec) == 0;
2406 }
2407 
2408 void os::pd_commit_memory_or_exit(char* addr, size_t bytes,
2409                                   size_t alignment_hint, bool exec,
2410                                   const char* mesg) {
2411   assert(mesg != NULL, "mesg must be specified");
2412   int err = os::Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec);
2413   if (err != 0) {
2414     // the caller wants all commit errors to exit with the specified mesg:
2415     warn_fail_commit_memory(addr, bytes, alignment_hint, exec, err);
2416     vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "%s", mesg);
2417   }
2418 }
2419 
2420 // Uncommit the pages in a specified region.
2421 void os::pd_free_memory(char* addr, size_t bytes, size_t alignment_hint) {
2422   if (madvise(addr, bytes, MADV_FREE) < 0) {
2423     debug_only(warning("MADV_FREE failed."));
2424     return;
2425   }
2426 }
2427 
2428 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
2429   return os::commit_memory(addr, size, !ExecMem);
2430 }
2431 
2432 bool os::remove_stack_guard_pages(char* addr, size_t size) {
2433   return os::uncommit_memory(addr, size);
2434 }
2435 
2436 // Change the page size in a given range.
2437 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2438   assert((intptr_t)addr % alignment_hint == 0, "Address should be aligned.");
2439   assert((intptr_t)(addr + bytes) % alignment_hint == 0, "End should be aligned.");
2440   if (UseLargePages) {
2441     size_t page_size = Solaris::page_size_for_alignment(alignment_hint);
2442     if (page_size > (size_t) vm_page_size()) {
2443       Solaris::setup_large_pages(addr, bytes, page_size);
2444     }
2445   }
2446 }
2447 
2448 // Tell the OS to make the range local to the first-touching LWP
2449 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2450   assert((intptr_t)addr % os::vm_page_size() == 0, "Address should be page-aligned.");
2451   if (madvise(addr, bytes, MADV_ACCESS_LWP) < 0) {
2452     debug_only(warning("MADV_ACCESS_LWP failed."));
2453   }
2454 }
2455 
2456 // Tell the OS that this range would be accessed from different LWPs.
2457 void os::numa_make_global(char *addr, size_t bytes) {
2458   assert((intptr_t)addr % os::vm_page_size() == 0, "Address should be page-aligned.");
2459   if (madvise(addr, bytes, MADV_ACCESS_MANY) < 0) {
2460     debug_only(warning("MADV_ACCESS_MANY failed."));
2461   }
2462 }
2463 
2464 // Get the number of the locality groups.
2465 size_t os::numa_get_groups_num() {
2466   size_t n = Solaris::lgrp_nlgrps(Solaris::lgrp_cookie());
2467   return n != -1 ? n : 1;
2468 }
2469 
2470 // Get a list of leaf locality groups. A leaf lgroup is group that
2471 // doesn't have any children. Typical leaf group is a CPU or a CPU/memory
2472 // board. An LWP is assigned to one of these groups upon creation.
2473 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2474   if ((ids[0] = Solaris::lgrp_root(Solaris::lgrp_cookie())) == -1) {
2475     ids[0] = 0;
2476     return 1;
2477   }
2478   int result_size = 0, top = 1, bottom = 0, cur = 0;
2479   for (int k = 0; k < size; k++) {
2480     int r = Solaris::lgrp_children(Solaris::lgrp_cookie(), ids[cur],
2481                                    (Solaris::lgrp_id_t*)&ids[top], size - top);
2482     if (r == -1) {
2483       ids[0] = 0;
2484       return 1;
2485     }
2486     if (!r) {
2487       // That's a leaf node.
2488       assert(bottom <= cur, "Sanity check");
2489       // Check if the node has memory
2490       if (Solaris::lgrp_resources(Solaris::lgrp_cookie(), ids[cur],
2491                                   NULL, 0, LGRP_RSRC_MEM) > 0) {
2492         ids[bottom++] = ids[cur];
2493       }
2494     }
2495     top += r;
2496     cur++;
2497   }
2498   if (bottom == 0) {
2499     // Handle a situation, when the OS reports no memory available.
2500     // Assume UMA architecture.
2501     ids[0] = 0;
2502     return 1;
2503   }
2504   return bottom;
2505 }
2506 
2507 // Detect the topology change. Typically happens during CPU plugging-unplugging.
2508 bool os::numa_topology_changed() {
2509   int is_stale = Solaris::lgrp_cookie_stale(Solaris::lgrp_cookie());
2510   if (is_stale != -1 && is_stale) {
2511     Solaris::lgrp_fini(Solaris::lgrp_cookie());
2512     Solaris::lgrp_cookie_t c = Solaris::lgrp_init(Solaris::LGRP_VIEW_CALLER);
2513     assert(c != 0, "Failure to initialize LGRP API");
2514     Solaris::set_lgrp_cookie(c);
2515     return true;
2516   }
2517   return false;
2518 }
2519 
2520 // Get the group id of the current LWP.
2521 int os::numa_get_group_id() {
2522   int lgrp_id = Solaris::lgrp_home(P_LWPID, P_MYID);
2523   if (lgrp_id == -1) {
2524     return 0;
2525   }
2526   const int size = os::numa_get_groups_num();
2527   int *ids = (int*)alloca(size * sizeof(int));
2528 
2529   // Get the ids of all lgroups with memory; r is the count.
2530   int r = Solaris::lgrp_resources(Solaris::lgrp_cookie(), lgrp_id,
2531                                   (Solaris::lgrp_id_t*)ids, size, LGRP_RSRC_MEM);
2532   if (r <= 0) {
2533     return 0;
2534   }
2535   return ids[os::random() % r];
2536 }
2537 
2538 // Request information about the page.
2539 bool os::get_page_info(char *start, page_info* info) {
2540   const uint_t info_types[] = { MEMINFO_VLGRP, MEMINFO_VPAGESIZE };
2541   uint64_t addr = (uintptr_t)start;
2542   uint64_t outdata[2];
2543   uint_t validity = 0;
2544 
2545   if (meminfo(&addr, 1, info_types, 2, outdata, &validity) < 0) {
2546     return false;
2547   }
2548 
2549   info->size = 0;
2550   info->lgrp_id = -1;
2551 
2552   if ((validity & 1) != 0) {
2553     if ((validity & 2) != 0) {
2554       info->lgrp_id = outdata[0];
2555     }
2556     if ((validity & 4) != 0) {
2557       info->size = outdata[1];
2558     }
2559     return true;
2560   }
2561   return false;
2562 }
2563 
2564 // Scan the pages from start to end until a page different than
2565 // the one described in the info parameter is encountered.
2566 char *os::scan_pages(char *start, char* end, page_info* page_expected,
2567                      page_info* page_found) {
2568   const uint_t info_types[] = { MEMINFO_VLGRP, MEMINFO_VPAGESIZE };
2569   const size_t types = sizeof(info_types) / sizeof(info_types[0]);
2570   uint64_t addrs[MAX_MEMINFO_CNT], outdata[types * MAX_MEMINFO_CNT + 1];
2571   uint_t validity[MAX_MEMINFO_CNT];
2572 
2573   size_t page_size = MAX2((size_t)os::vm_page_size(), page_expected->size);
2574   uint64_t p = (uint64_t)start;
2575   while (p < (uint64_t)end) {
2576     addrs[0] = p;
2577     size_t addrs_count = 1;
2578     while (addrs_count < MAX_MEMINFO_CNT && addrs[addrs_count - 1] + page_size < (uint64_t)end) {
2579       addrs[addrs_count] = addrs[addrs_count - 1] + page_size;
2580       addrs_count++;
2581     }
2582 
2583     if (meminfo(addrs, addrs_count, info_types, types, outdata, validity) < 0) {
2584       return NULL;
2585     }
2586 
2587     size_t i = 0;
2588     for (; i < addrs_count; i++) {
2589       if ((validity[i] & 1) != 0) {
2590         if ((validity[i] & 4) != 0) {
2591           if (outdata[types * i + 1] != page_expected->size) {
2592             break;
2593           }
2594         } else if (page_expected->size != 0) {
2595           break;
2596         }
2597 
2598         if ((validity[i] & 2) != 0 && page_expected->lgrp_id > 0) {
2599           if (outdata[types * i] != page_expected->lgrp_id) {
2600             break;
2601           }
2602         }
2603       } else {
2604         return NULL;
2605       }
2606     }
2607 
2608     if (i < addrs_count) {
2609       if ((validity[i] & 2) != 0) {
2610         page_found->lgrp_id = outdata[types * i];
2611       } else {
2612         page_found->lgrp_id = -1;
2613       }
2614       if ((validity[i] & 4) != 0) {
2615         page_found->size = outdata[types * i + 1];
2616       } else {
2617         page_found->size = 0;
2618       }
2619       return (char*)addrs[i];
2620     }
2621 
2622     p = addrs[addrs_count - 1] + page_size;
2623   }
2624   return end;
2625 }
2626 
2627 bool os::pd_uncommit_memory(char* addr, size_t bytes) {
2628   size_t size = bytes;
2629   // Map uncommitted pages PROT_NONE so we fail early if we touch an
2630   // uncommitted page. Otherwise, the read/write might succeed if we
2631   // have enough swap space to back the physical page.
2632   return
2633     NULL != Solaris::mmap_chunk(addr, size,
2634                                 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE,
2635                                 PROT_NONE);
2636 }
2637 
2638 char* os::Solaris::mmap_chunk(char *addr, size_t size, int flags, int prot) {
2639   char *b = (char *)mmap(addr, size, prot, flags, os::Solaris::_dev_zero_fd, 0);
2640 
2641   if (b == MAP_FAILED) {
2642     return NULL;
2643   }
2644   return b;
2645 }
2646 
2647 char* os::Solaris::anon_mmap(char* requested_addr, size_t bytes,
2648                              size_t alignment_hint, bool fixed) {
2649   char* addr = requested_addr;
2650   int flags = MAP_PRIVATE | MAP_NORESERVE;
2651 
2652   assert(!(fixed && (alignment_hint > 0)),
2653          "alignment hint meaningless with fixed mmap");
2654 
2655   if (fixed) {
2656     flags |= MAP_FIXED;
2657   } else if (has_map_align && (alignment_hint > (size_t) vm_page_size())) {
2658     flags |= MAP_ALIGN;
2659     addr = (char*) alignment_hint;
2660   }
2661 
2662   // Map uncommitted pages PROT_NONE so we fail early if we touch an
2663   // uncommitted page. Otherwise, the read/write might succeed if we
2664   // have enough swap space to back the physical page.
2665   return mmap_chunk(addr, bytes, flags, PROT_NONE);
2666 }
2667 
2668 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
2669                             size_t alignment_hint) {
2670   char* addr = Solaris::anon_mmap(requested_addr, bytes, alignment_hint,
2671                                   (requested_addr != NULL));
2672 
2673   guarantee(requested_addr == NULL || requested_addr == addr,
2674             "OS failed to return requested mmap address.");
2675   return addr;
2676 }
2677 
2678 // Reserve memory at an arbitrary address, only if that area is
2679 // available (and not reserved for something else).
2680 
2681 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
2682   const int max_tries = 10;
2683   char* base[max_tries];
2684   size_t size[max_tries];
2685 
2686   // Solaris adds a gap between mmap'ed regions.  The size of the gap
2687   // is dependent on the requested size and the MMU.  Our initial gap
2688   // value here is just a guess and will be corrected later.
2689   bool had_top_overlap = false;
2690   bool have_adjusted_gap = false;
2691   size_t gap = 0x400000;
2692 
2693   // Assert only that the size is a multiple of the page size, since
2694   // that's all that mmap requires, and since that's all we really know
2695   // about at this low abstraction level.  If we need higher alignment,
2696   // we can either pass an alignment to this method or verify alignment
2697   // in one of the methods further up the call chain.  See bug 5044738.
2698   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
2699 
2700   // Since snv_84, Solaris attempts to honor the address hint - see 5003415.
2701   // Give it a try, if the kernel honors the hint we can return immediately.
2702   char* addr = Solaris::anon_mmap(requested_addr, bytes, 0, false);
2703 
2704   volatile int err = errno;
2705   if (addr == requested_addr) {
2706     return addr;
2707   } else if (addr != NULL) {
2708     pd_unmap_memory(addr, bytes);
2709   }
2710 
2711   if (log_is_enabled(Warning, os)) {
2712     char buf[256];
2713     buf[0] = '\0';
2714     if (addr == NULL) {
2715       jio_snprintf(buf, sizeof(buf), ": %s", os::strerror(err));
2716     }
2717     log_info(os)("attempt_reserve_memory_at: couldn't reserve " SIZE_FORMAT " bytes at "
2718             PTR_FORMAT ": reserve_memory_helper returned " PTR_FORMAT
2719             "%s", bytes, requested_addr, addr, buf);
2720   }
2721 
2722   // Address hint method didn't work.  Fall back to the old method.
2723   // In theory, once SNV becomes our oldest supported platform, this
2724   // code will no longer be needed.
2725   //
2726   // Repeatedly allocate blocks until the block is allocated at the
2727   // right spot. Give up after max_tries.
2728   int i;
2729   for (i = 0; i < max_tries; ++i) {
2730     base[i] = reserve_memory(bytes);
2731 
2732     if (base[i] != NULL) {
2733       // Is this the block we wanted?
2734       if (base[i] == requested_addr) {
2735         size[i] = bytes;
2736         break;
2737       }
2738 
2739       // check that the gap value is right
2740       if (had_top_overlap && !have_adjusted_gap) {
2741         size_t actual_gap = base[i-1] - base[i] - bytes;
2742         if (gap != actual_gap) {
2743           // adjust the gap value and retry the last 2 allocations
2744           assert(i > 0, "gap adjustment code problem");
2745           have_adjusted_gap = true;  // adjust the gap only once, just in case
2746           gap = actual_gap;
2747           log_info(os)("attempt_reserve_memory_at: adjusted gap to 0x%lx", gap);
2748           unmap_memory(base[i], bytes);
2749           unmap_memory(base[i-1], size[i-1]);
2750           i-=2;
2751           continue;
2752         }
2753       }
2754 
2755       // Does this overlap the block we wanted? Give back the overlapped
2756       // parts and try again.
2757       //
2758       // There is still a bug in this code: if top_overlap == bytes,
2759       // the overlap is offset from requested region by the value of gap.
2760       // In this case giving back the overlapped part will not work,
2761       // because we'll give back the entire block at base[i] and
2762       // therefore the subsequent allocation will not generate a new gap.
2763       // This could be fixed with a new algorithm that used larger
2764       // or variable size chunks to find the requested region -
2765       // but such a change would introduce additional complications.
2766       // It's rare enough that the planets align for this bug,
2767       // so we'll just wait for a fix for 6204603/5003415 which
2768       // will provide a mmap flag to allow us to avoid this business.
2769 
2770       size_t top_overlap = requested_addr + (bytes + gap) - base[i];
2771       if (top_overlap >= 0 && top_overlap < bytes) {
2772         had_top_overlap = true;
2773         unmap_memory(base[i], top_overlap);
2774         base[i] += top_overlap;
2775         size[i] = bytes - top_overlap;
2776       } else {
2777         size_t bottom_overlap = base[i] + bytes - requested_addr;
2778         if (bottom_overlap >= 0 && bottom_overlap < bytes) {
2779           if (bottom_overlap == 0) {
2780             log_info(os)("attempt_reserve_memory_at: possible alignment bug");
2781           }
2782           unmap_memory(requested_addr, bottom_overlap);
2783           size[i] = bytes - bottom_overlap;
2784         } else {
2785           size[i] = bytes;
2786         }
2787       }
2788     }
2789   }
2790 
2791   // Give back the unused reserved pieces.
2792 
2793   for (int j = 0; j < i; ++j) {
2794     if (base[j] != NULL) {
2795       unmap_memory(base[j], size[j]);
2796     }
2797   }
2798 
2799   return (i < max_tries) ? requested_addr : NULL;
2800 }
2801 
2802 bool os::pd_release_memory(char* addr, size_t bytes) {
2803   size_t size = bytes;
2804   return munmap(addr, size) == 0;
2805 }
2806 
2807 static bool solaris_mprotect(char* addr, size_t bytes, int prot) {
2808   assert(addr == (char*)align_size_down((uintptr_t)addr, os::vm_page_size()),
2809          "addr must be page aligned");
2810   int retVal = mprotect(addr, bytes, prot);
2811   return retVal == 0;
2812 }
2813 
2814 // Protect memory (Used to pass readonly pages through
2815 // JNI GetArray<type>Elements with empty arrays.)
2816 // Also, used for serialization page and for compressed oops null pointer
2817 // checking.
2818 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
2819                         bool is_committed) {
2820   unsigned int p = 0;
2821   switch (prot) {
2822   case MEM_PROT_NONE: p = PROT_NONE; break;
2823   case MEM_PROT_READ: p = PROT_READ; break;
2824   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
2825   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
2826   default:
2827     ShouldNotReachHere();
2828   }
2829   // is_committed is unused.
2830   return solaris_mprotect(addr, bytes, p);
2831 }
2832 
2833 // guard_memory and unguard_memory only happens within stack guard pages.
2834 // Since ISM pertains only to the heap, guard and unguard memory should not
2835 /// happen with an ISM region.
2836 bool os::guard_memory(char* addr, size_t bytes) {
2837   return solaris_mprotect(addr, bytes, PROT_NONE);
2838 }
2839 
2840 bool os::unguard_memory(char* addr, size_t bytes) {
2841   return solaris_mprotect(addr, bytes, PROT_READ|PROT_WRITE);
2842 }
2843 
2844 // Large page support
2845 static size_t _large_page_size = 0;
2846 
2847 // Insertion sort for small arrays (descending order).
2848 static void insertion_sort_descending(size_t* array, int len) {
2849   for (int i = 0; i < len; i++) {
2850     size_t val = array[i];
2851     for (size_t key = i; key > 0 && array[key - 1] < val; --key) {
2852       size_t tmp = array[key];
2853       array[key] = array[key - 1];
2854       array[key - 1] = tmp;
2855     }
2856   }
2857 }
2858 
2859 bool os::Solaris::mpss_sanity_check(bool warn, size_t* page_size) {
2860   const unsigned int usable_count = VM_Version::page_size_count();
2861   if (usable_count == 1) {
2862     return false;
2863   }
2864 
2865   // Find the right getpagesizes interface.  When solaris 11 is the minimum
2866   // build platform, getpagesizes() (without the '2') can be called directly.
2867   typedef int (*gps_t)(size_t[], int);
2868   gps_t gps_func = CAST_TO_FN_PTR(gps_t, dlsym(RTLD_DEFAULT, "getpagesizes2"));
2869   if (gps_func == NULL) {
2870     gps_func = CAST_TO_FN_PTR(gps_t, dlsym(RTLD_DEFAULT, "getpagesizes"));
2871     if (gps_func == NULL) {
2872       if (warn) {
2873         warning("MPSS is not supported by the operating system.");
2874       }
2875       return false;
2876     }
2877   }
2878 
2879   // Fill the array of page sizes.
2880   int n = (*gps_func)(_page_sizes, page_sizes_max);
2881   assert(n > 0, "Solaris bug?");
2882 
2883   if (n == page_sizes_max) {
2884     // Add a sentinel value (necessary only if the array was completely filled
2885     // since it is static (zeroed at initialization)).
2886     _page_sizes[--n] = 0;
2887     DEBUG_ONLY(warning("increase the size of the os::_page_sizes array.");)
2888   }
2889   assert(_page_sizes[n] == 0, "missing sentinel");
2890   trace_page_sizes("available page sizes", _page_sizes, n);
2891 
2892   if (n == 1) return false;     // Only one page size available.
2893 
2894   // Skip sizes larger than 4M (or LargePageSizeInBytes if it was set) and
2895   // select up to usable_count elements.  First sort the array, find the first
2896   // acceptable value, then copy the usable sizes to the top of the array and
2897   // trim the rest.  Make sure to include the default page size :-).
2898   //
2899   // A better policy could get rid of the 4M limit by taking the sizes of the
2900   // important VM memory regions (java heap and possibly the code cache) into
2901   // account.
2902   insertion_sort_descending(_page_sizes, n);
2903   const size_t size_limit =
2904     FLAG_IS_DEFAULT(LargePageSizeInBytes) ? 4 * M : LargePageSizeInBytes;
2905   int beg;
2906   for (beg = 0; beg < n && _page_sizes[beg] > size_limit; ++beg) /* empty */;
2907   const int end = MIN2((int)usable_count, n) - 1;
2908   for (int cur = 0; cur < end; ++cur, ++beg) {
2909     _page_sizes[cur] = _page_sizes[beg];
2910   }
2911   _page_sizes[end] = vm_page_size();
2912   _page_sizes[end + 1] = 0;
2913 
2914   if (_page_sizes[end] > _page_sizes[end - 1]) {
2915     // Default page size is not the smallest; sort again.
2916     insertion_sort_descending(_page_sizes, end + 1);
2917   }
2918   *page_size = _page_sizes[0];
2919 
2920   trace_page_sizes("usable page sizes", _page_sizes, end + 1);
2921   return true;
2922 }
2923 
2924 void os::large_page_init() {
2925   if (UseLargePages) {
2926     // print a warning if any large page related flag is specified on command line
2927     bool warn_on_failure = !FLAG_IS_DEFAULT(UseLargePages)        ||
2928                            !FLAG_IS_DEFAULT(LargePageSizeInBytes);
2929 
2930     UseLargePages = Solaris::mpss_sanity_check(warn_on_failure, &_large_page_size);
2931   }
2932 }
2933 
2934 bool os::Solaris::is_valid_page_size(size_t bytes) {
2935   for (int i = 0; _page_sizes[i] != 0; i++) {
2936     if (_page_sizes[i] == bytes) {
2937       return true;
2938     }
2939   }
2940   return false;
2941 }
2942 
2943 bool os::Solaris::setup_large_pages(caddr_t start, size_t bytes, size_t align) {
2944   assert(is_valid_page_size(align), SIZE_FORMAT " is not a valid page size", align);
2945   assert(is_ptr_aligned((void*) start, align),
2946          PTR_FORMAT " is not aligned to " SIZE_FORMAT, p2i((void*) start), align);
2947   assert(is_size_aligned(bytes, align),
2948          SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, align);
2949 
2950   // Signal to OS that we want large pages for addresses
2951   // from addr, addr + bytes
2952   struct memcntl_mha mpss_struct;
2953   mpss_struct.mha_cmd = MHA_MAPSIZE_VA;
2954   mpss_struct.mha_pagesize = align;
2955   mpss_struct.mha_flags = 0;
2956   // Upon successful completion, memcntl() returns 0
2957   if (memcntl(start, bytes, MC_HAT_ADVISE, (caddr_t) &mpss_struct, 0, 0)) {
2958     debug_only(warning("Attempt to use MPSS failed."));
2959     return false;
2960   }
2961   return true;
2962 }
2963 
2964 char* os::reserve_memory_special(size_t size, size_t alignment, char* addr, bool exec) {
2965   fatal("os::reserve_memory_special should not be called on Solaris.");
2966   return NULL;
2967 }
2968 
2969 bool os::release_memory_special(char* base, size_t bytes) {
2970   fatal("os::release_memory_special should not be called on Solaris.");
2971   return false;
2972 }
2973 
2974 size_t os::large_page_size() {
2975   return _large_page_size;
2976 }
2977 
2978 // MPSS allows application to commit large page memory on demand; with ISM
2979 // the entire memory region must be allocated as shared memory.
2980 bool os::can_commit_large_page_memory() {
2981   return true;
2982 }
2983 
2984 bool os::can_execute_large_page_memory() {
2985   return true;
2986 }
2987 
2988 // Read calls from inside the vm need to perform state transitions
2989 size_t os::read(int fd, void *buf, unsigned int nBytes) {
2990   size_t res;
2991   JavaThread* thread = (JavaThread*)Thread::current();
2992   assert(thread->thread_state() == _thread_in_vm, "Assumed _thread_in_vm");
2993   ThreadBlockInVM tbiv(thread);
2994   RESTARTABLE(::read(fd, buf, (size_t) nBytes), res);
2995   return res;
2996 }
2997 
2998 size_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) {
2999   size_t res;
3000   JavaThread* thread = (JavaThread*)Thread::current();
3001   assert(thread->thread_state() == _thread_in_vm, "Assumed _thread_in_vm");
3002   ThreadBlockInVM tbiv(thread);
3003   RESTARTABLE(::pread(fd, buf, (size_t) nBytes, offset), res);
3004   return res;
3005 }
3006 
3007 size_t os::restartable_read(int fd, void *buf, unsigned int nBytes) {
3008   size_t res;
3009   assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
3010          "Assumed _thread_in_native");
3011   RESTARTABLE(::read(fd, buf, (size_t) nBytes), res);
3012   return res;
3013 }
3014 
3015 void os::naked_short_sleep(jlong ms) {
3016   assert(ms < 1000, "Un-interruptable sleep, short time use only");
3017 
3018   // usleep is deprecated and removed from POSIX, in favour of nanosleep, but
3019   // Solaris requires -lrt for this.
3020   usleep((ms * 1000));
3021 
3022   return;
3023 }
3024 
3025 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
3026 void os::infinite_sleep() {
3027   while (true) {    // sleep forever ...
3028     ::sleep(100);   // ... 100 seconds at a time
3029   }
3030 }
3031 
3032 // Used to convert frequent JVM_Yield() to nops
3033 bool os::dont_yield() {
3034   if (DontYieldALot) {
3035     static hrtime_t last_time = 0;
3036     hrtime_t diff = getTimeNanos() - last_time;
3037 
3038     if (diff < DontYieldALotInterval * 1000000) {
3039       return true;
3040     }
3041 
3042     last_time += diff;
3043 
3044     return false;
3045   } else {
3046     return false;
3047   }
3048 }
3049 
3050 // Note that yield semantics are defined by the scheduling class to which
3051 // the thread currently belongs.  Typically, yield will _not yield to
3052 // other equal or higher priority threads that reside on the dispatch queues
3053 // of other CPUs.
3054 
3055 void os::naked_yield() {
3056   thr_yield();
3057 }
3058 
3059 // Interface for setting lwp priorities.  We are using T2 libthread,
3060 // which forces the use of bound threads, so all of our threads will
3061 // be assigned to real lwp's.  Using the thr_setprio function is
3062 // meaningless in this mode so we must adjust the real lwp's priority.
3063 // The routines below implement the getting and setting of lwp priorities.
3064 //
3065 // Note: There are three priority scales used on Solaris.  Java priotities
3066 //       which range from 1 to 10, libthread "thr_setprio" scale which range
3067 //       from 0 to 127, and the current scheduling class of the process we
3068 //       are running in.  This is typically from -60 to +60.
3069 //       The setting of the lwp priorities in done after a call to thr_setprio
3070 //       so Java priorities are mapped to libthread priorities and we map from
3071 //       the latter to lwp priorities.  We don't keep priorities stored in
3072 //       Java priorities since some of our worker threads want to set priorities
3073 //       higher than all Java threads.
3074 //
3075 // For related information:
3076 // (1)  man -s 2 priocntl
3077 // (2)  man -s 4 priocntl
3078 // (3)  man dispadmin
3079 // =    librt.so
3080 // =    libthread/common/rtsched.c - thrp_setlwpprio().
3081 // =    ps -cL <pid> ... to validate priority.
3082 // =    sched_get_priority_min and _max
3083 //              pthread_create
3084 //              sched_setparam
3085 //              pthread_setschedparam
3086 //
3087 // Assumptions:
3088 // +    We assume that all threads in the process belong to the same
3089 //              scheduling class.   IE. an homogenous process.
3090 // +    Must be root or in IA group to change change "interactive" attribute.
3091 //              Priocntl() will fail silently.  The only indication of failure is when
3092 //              we read-back the value and notice that it hasn't changed.
3093 // +    Interactive threads enter the runq at the head, non-interactive at the tail.
3094 // +    For RT, change timeslice as well.  Invariant:
3095 //              constant "priority integral"
3096 //              Konst == TimeSlice * (60-Priority)
3097 //              Given a priority, compute appropriate timeslice.
3098 // +    Higher numerical values have higher priority.
3099 
3100 // sched class attributes
3101 typedef struct {
3102   int   schedPolicy;              // classID
3103   int   maxPrio;
3104   int   minPrio;
3105 } SchedInfo;
3106 
3107 
3108 static SchedInfo tsLimits, iaLimits, rtLimits, fxLimits;
3109 
3110 #ifdef ASSERT
3111 static int  ReadBackValidate = 1;
3112 #endif
3113 static int  myClass     = 0;
3114 static int  myMin       = 0;
3115 static int  myMax       = 0;
3116 static int  myCur       = 0;
3117 static bool priocntl_enable = false;
3118 
3119 static const int criticalPrio = FXCriticalPriority;
3120 static int java_MaxPriority_to_os_priority = 0; // Saved mapping
3121 
3122 
3123 // lwp_priocntl_init
3124 //
3125 // Try to determine the priority scale for our process.
3126 //
3127 // Return errno or 0 if OK.
3128 //
3129 static int lwp_priocntl_init() {
3130   int rslt;
3131   pcinfo_t ClassInfo;
3132   pcparms_t ParmInfo;
3133   int i;
3134 
3135   if (!UseThreadPriorities) return 0;
3136 
3137   // If ThreadPriorityPolicy is 1, switch tables
3138   if (ThreadPriorityPolicy == 1) {
3139     for (i = 0; i < CriticalPriority+1; i++)
3140       os::java_to_os_priority[i] = prio_policy1[i];
3141   }
3142   if (UseCriticalJavaThreadPriority) {
3143     // MaxPriority always maps to the FX scheduling class and criticalPrio.
3144     // See set_native_priority() and set_lwp_class_and_priority().
3145     // Save original MaxPriority mapping in case attempt to
3146     // use critical priority fails.
3147     java_MaxPriority_to_os_priority = os::java_to_os_priority[MaxPriority];
3148     // Set negative to distinguish from other priorities
3149     os::java_to_os_priority[MaxPriority] = -criticalPrio;
3150   }
3151 
3152   // Get IDs for a set of well-known scheduling classes.
3153   // TODO-FIXME: GETCLINFO returns the current # of classes in the
3154   // the system.  We should have a loop that iterates over the
3155   // classID values, which are known to be "small" integers.
3156 
3157   strcpy(ClassInfo.pc_clname, "TS");
3158   ClassInfo.pc_cid = -1;
3159   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3160   if (rslt < 0) return errno;
3161   assert(ClassInfo.pc_cid != -1, "cid for TS class is -1");
3162   tsLimits.schedPolicy = ClassInfo.pc_cid;
3163   tsLimits.maxPrio = ((tsinfo_t*)ClassInfo.pc_clinfo)->ts_maxupri;
3164   tsLimits.minPrio = -tsLimits.maxPrio;
3165 
3166   strcpy(ClassInfo.pc_clname, "IA");
3167   ClassInfo.pc_cid = -1;
3168   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3169   if (rslt < 0) return errno;
3170   assert(ClassInfo.pc_cid != -1, "cid for IA class is -1");
3171   iaLimits.schedPolicy = ClassInfo.pc_cid;
3172   iaLimits.maxPrio = ((iainfo_t*)ClassInfo.pc_clinfo)->ia_maxupri;
3173   iaLimits.minPrio = -iaLimits.maxPrio;
3174 
3175   strcpy(ClassInfo.pc_clname, "RT");
3176   ClassInfo.pc_cid = -1;
3177   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3178   if (rslt < 0) return errno;
3179   assert(ClassInfo.pc_cid != -1, "cid for RT class is -1");
3180   rtLimits.schedPolicy = ClassInfo.pc_cid;
3181   rtLimits.maxPrio = ((rtinfo_t*)ClassInfo.pc_clinfo)->rt_maxpri;
3182   rtLimits.minPrio = 0;
3183 
3184   strcpy(ClassInfo.pc_clname, "FX");
3185   ClassInfo.pc_cid = -1;
3186   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3187   if (rslt < 0) return errno;
3188   assert(ClassInfo.pc_cid != -1, "cid for FX class is -1");
3189   fxLimits.schedPolicy = ClassInfo.pc_cid;
3190   fxLimits.maxPrio = ((fxinfo_t*)ClassInfo.pc_clinfo)->fx_maxupri;
3191   fxLimits.minPrio = 0;
3192 
3193   // Query our "current" scheduling class.
3194   // This will normally be IA, TS or, rarely, FX or RT.
3195   memset(&ParmInfo, 0, sizeof(ParmInfo));
3196   ParmInfo.pc_cid = PC_CLNULL;
3197   rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo);
3198   if (rslt < 0) return errno;
3199   myClass = ParmInfo.pc_cid;
3200 
3201   // We now know our scheduling classId, get specific information
3202   // about the class.
3203   ClassInfo.pc_cid = myClass;
3204   ClassInfo.pc_clname[0] = 0;
3205   rslt = priocntl((idtype)0, 0, PC_GETCLINFO, (caddr_t)&ClassInfo);
3206   if (rslt < 0) return errno;
3207 
3208   if (ThreadPriorityVerbose) {
3209     tty->print_cr("lwp_priocntl_init: Class=%d(%s)...", myClass, ClassInfo.pc_clname);
3210   }
3211 
3212   memset(&ParmInfo, 0, sizeof(pcparms_t));
3213   ParmInfo.pc_cid = PC_CLNULL;
3214   rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo);
3215   if (rslt < 0) return errno;
3216 
3217   if (ParmInfo.pc_cid == rtLimits.schedPolicy) {
3218     myMin = rtLimits.minPrio;
3219     myMax = rtLimits.maxPrio;
3220   } else if (ParmInfo.pc_cid == iaLimits.schedPolicy) {
3221     iaparms_t *iaInfo  = (iaparms_t*)ParmInfo.pc_clparms;
3222     myMin = iaLimits.minPrio;
3223     myMax = iaLimits.maxPrio;
3224     myMax = MIN2(myMax, (int)iaInfo->ia_uprilim);       // clamp - restrict
3225   } else if (ParmInfo.pc_cid == tsLimits.schedPolicy) {
3226     tsparms_t *tsInfo  = (tsparms_t*)ParmInfo.pc_clparms;
3227     myMin = tsLimits.minPrio;
3228     myMax = tsLimits.maxPrio;
3229     myMax = MIN2(myMax, (int)tsInfo->ts_uprilim);       // clamp - restrict
3230   } else if (ParmInfo.pc_cid == fxLimits.schedPolicy) {
3231     fxparms_t *fxInfo = (fxparms_t*)ParmInfo.pc_clparms;
3232     myMin = fxLimits.minPrio;
3233     myMax = fxLimits.maxPrio;
3234     myMax = MIN2(myMax, (int)fxInfo->fx_uprilim);       // clamp - restrict
3235   } else {
3236     // No clue - punt
3237     if (ThreadPriorityVerbose) {
3238       tty->print_cr("Unknown scheduling class: %s ... \n",
3239                     ClassInfo.pc_clname);
3240     }
3241     return EINVAL;      // no clue, punt
3242   }
3243 
3244   if (ThreadPriorityVerbose) {
3245     tty->print_cr("Thread priority Range: [%d..%d]\n", myMin, myMax);
3246   }
3247 
3248   priocntl_enable = true;  // Enable changing priorities
3249   return 0;
3250 }
3251 
3252 #define IAPRI(x)        ((iaparms_t *)((x).pc_clparms))
3253 #define RTPRI(x)        ((rtparms_t *)((x).pc_clparms))
3254 #define TSPRI(x)        ((tsparms_t *)((x).pc_clparms))
3255 #define FXPRI(x)        ((fxparms_t *)((x).pc_clparms))
3256 
3257 
3258 // scale_to_lwp_priority
3259 //
3260 // Convert from the libthread "thr_setprio" scale to our current
3261 // lwp scheduling class scale.
3262 //
3263 static int scale_to_lwp_priority(int rMin, int rMax, int x) {
3264   int v;
3265 
3266   if (x == 127) return rMax;            // avoid round-down
3267   v = (((x*(rMax-rMin)))/128)+rMin;
3268   return v;
3269 }
3270 
3271 
3272 // set_lwp_class_and_priority
3273 int set_lwp_class_and_priority(int ThreadID, int lwpid,
3274                                int newPrio, int new_class, bool scale) {
3275   int rslt;
3276   int Actual, Expected, prv;
3277   pcparms_t ParmInfo;                   // for GET-SET
3278 #ifdef ASSERT
3279   pcparms_t ReadBack;                   // for readback
3280 #endif
3281 
3282   // Set priority via PC_GETPARMS, update, PC_SETPARMS
3283   // Query current values.
3284   // TODO: accelerate this by eliminating the PC_GETPARMS call.
3285   // Cache "pcparms_t" in global ParmCache.
3286   // TODO: elide set-to-same-value
3287 
3288   // If something went wrong on init, don't change priorities.
3289   if (!priocntl_enable) {
3290     if (ThreadPriorityVerbose) {
3291       tty->print_cr("Trying to set priority but init failed, ignoring");
3292     }
3293     return EINVAL;
3294   }
3295 
3296   // If lwp hasn't started yet, just return
3297   // the _start routine will call us again.
3298   if (lwpid <= 0) {
3299     if (ThreadPriorityVerbose) {
3300       tty->print_cr("deferring the set_lwp_class_and_priority of thread "
3301                     INTPTR_FORMAT " to %d, lwpid not set",
3302                     ThreadID, newPrio);
3303     }
3304     return 0;
3305   }
3306 
3307   if (ThreadPriorityVerbose) {
3308     tty->print_cr ("set_lwp_class_and_priority("
3309                    INTPTR_FORMAT "@" INTPTR_FORMAT " %d) ",
3310                    ThreadID, lwpid, newPrio);
3311   }
3312 
3313   memset(&ParmInfo, 0, sizeof(pcparms_t));
3314   ParmInfo.pc_cid = PC_CLNULL;
3315   rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ParmInfo);
3316   if (rslt < 0) return errno;
3317 
3318   int cur_class = ParmInfo.pc_cid;
3319   ParmInfo.pc_cid = (id_t)new_class;
3320 
3321   if (new_class == rtLimits.schedPolicy) {
3322     rtparms_t *rtInfo  = (rtparms_t*)ParmInfo.pc_clparms;
3323     rtInfo->rt_pri     = scale ? scale_to_lwp_priority(rtLimits.minPrio,
3324                                                        rtLimits.maxPrio, newPrio)
3325                                : newPrio;
3326     rtInfo->rt_tqsecs  = RT_NOCHANGE;
3327     rtInfo->rt_tqnsecs = RT_NOCHANGE;
3328     if (ThreadPriorityVerbose) {
3329       tty->print_cr("RT: %d->%d\n", newPrio, rtInfo->rt_pri);
3330     }
3331   } else if (new_class == iaLimits.schedPolicy) {
3332     iaparms_t* iaInfo  = (iaparms_t*)ParmInfo.pc_clparms;
3333     int maxClamped     = MIN2(iaLimits.maxPrio,
3334                               cur_class == new_class
3335                               ? (int)iaInfo->ia_uprilim : iaLimits.maxPrio);
3336     iaInfo->ia_upri    = scale ? scale_to_lwp_priority(iaLimits.minPrio,
3337                                                        maxClamped, newPrio)
3338                                : newPrio;
3339     iaInfo->ia_uprilim = cur_class == new_class
3340                            ? IA_NOCHANGE : (pri_t)iaLimits.maxPrio;
3341     iaInfo->ia_mode    = IA_NOCHANGE;
3342     if (ThreadPriorityVerbose) {
3343       tty->print_cr("IA: [%d...%d] %d->%d\n",
3344                     iaLimits.minPrio, maxClamped, newPrio, iaInfo->ia_upri);
3345     }
3346   } else if (new_class == tsLimits.schedPolicy) {
3347     tsparms_t* tsInfo  = (tsparms_t*)ParmInfo.pc_clparms;
3348     int maxClamped     = MIN2(tsLimits.maxPrio,
3349                               cur_class == new_class
3350                               ? (int)tsInfo->ts_uprilim : tsLimits.maxPrio);
3351     tsInfo->ts_upri    = scale ? scale_to_lwp_priority(tsLimits.minPrio,
3352                                                        maxClamped, newPrio)
3353                                : newPrio;
3354     tsInfo->ts_uprilim = cur_class == new_class
3355                            ? TS_NOCHANGE : (pri_t)tsLimits.maxPrio;
3356     if (ThreadPriorityVerbose) {
3357       tty->print_cr("TS: [%d...%d] %d->%d\n",
3358                     tsLimits.minPrio, maxClamped, newPrio, tsInfo->ts_upri);
3359     }
3360   } else if (new_class == fxLimits.schedPolicy) {
3361     fxparms_t* fxInfo  = (fxparms_t*)ParmInfo.pc_clparms;
3362     int maxClamped     = MIN2(fxLimits.maxPrio,
3363                               cur_class == new_class
3364                               ? (int)fxInfo->fx_uprilim : fxLimits.maxPrio);
3365     fxInfo->fx_upri    = scale ? scale_to_lwp_priority(fxLimits.minPrio,
3366                                                        maxClamped, newPrio)
3367                                : newPrio;
3368     fxInfo->fx_uprilim = cur_class == new_class
3369                            ? FX_NOCHANGE : (pri_t)fxLimits.maxPrio;
3370     fxInfo->fx_tqsecs  = FX_NOCHANGE;
3371     fxInfo->fx_tqnsecs = FX_NOCHANGE;
3372     if (ThreadPriorityVerbose) {
3373       tty->print_cr("FX: [%d...%d] %d->%d\n",
3374                     fxLimits.minPrio, maxClamped, newPrio, fxInfo->fx_upri);
3375     }
3376   } else {
3377     if (ThreadPriorityVerbose) {
3378       tty->print_cr("Unknown new scheduling class %d\n", new_class);
3379     }
3380     return EINVAL;    // no clue, punt
3381   }
3382 
3383   rslt = priocntl(P_LWPID, lwpid, PC_SETPARMS, (caddr_t)&ParmInfo);
3384   if (ThreadPriorityVerbose && rslt) {
3385     tty->print_cr ("PC_SETPARMS ->%d %d\n", rslt, errno);
3386   }
3387   if (rslt < 0) return errno;
3388 
3389 #ifdef ASSERT
3390   // Sanity check: read back what we just attempted to set.
3391   // In theory it could have changed in the interim ...
3392   //
3393   // The priocntl system call is tricky.
3394   // Sometimes it'll validate the priority value argument and
3395   // return EINVAL if unhappy.  At other times it fails silently.
3396   // Readbacks are prudent.
3397 
3398   if (!ReadBackValidate) return 0;
3399 
3400   memset(&ReadBack, 0, sizeof(pcparms_t));
3401   ReadBack.pc_cid = PC_CLNULL;
3402   rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ReadBack);
3403   assert(rslt >= 0, "priocntl failed");
3404   Actual = Expected = 0xBAD;
3405   assert(ParmInfo.pc_cid == ReadBack.pc_cid, "cid's don't match");
3406   if (ParmInfo.pc_cid == rtLimits.schedPolicy) {
3407     Actual   = RTPRI(ReadBack)->rt_pri;
3408     Expected = RTPRI(ParmInfo)->rt_pri;
3409   } else if (ParmInfo.pc_cid == iaLimits.schedPolicy) {
3410     Actual   = IAPRI(ReadBack)->ia_upri;
3411     Expected = IAPRI(ParmInfo)->ia_upri;
3412   } else if (ParmInfo.pc_cid == tsLimits.schedPolicy) {
3413     Actual   = TSPRI(ReadBack)->ts_upri;
3414     Expected = TSPRI(ParmInfo)->ts_upri;
3415   } else if (ParmInfo.pc_cid == fxLimits.schedPolicy) {
3416     Actual   = FXPRI(ReadBack)->fx_upri;
3417     Expected = FXPRI(ParmInfo)->fx_upri;
3418   } else {
3419     if (ThreadPriorityVerbose) {
3420       tty->print_cr("set_lwp_class_and_priority: unexpected class in readback: %d\n",
3421                     ParmInfo.pc_cid);
3422     }
3423   }
3424 
3425   if (Actual != Expected) {
3426     if (ThreadPriorityVerbose) {
3427       tty->print_cr ("set_lwp_class_and_priority(%d %d) Class=%d: actual=%d vs expected=%d\n",
3428                      lwpid, newPrio, ReadBack.pc_cid, Actual, Expected);
3429     }
3430   }
3431 #endif
3432 
3433   return 0;
3434 }
3435 
3436 // Solaris only gives access to 128 real priorities at a time,
3437 // so we expand Java's ten to fill this range.  This would be better
3438 // if we dynamically adjusted relative priorities.
3439 //
3440 // The ThreadPriorityPolicy option allows us to select 2 different
3441 // priority scales.
3442 //
3443 // ThreadPriorityPolicy=0
3444 // Since the Solaris' default priority is MaximumPriority, we do not
3445 // set a priority lower than Max unless a priority lower than
3446 // NormPriority is requested.
3447 //
3448 // ThreadPriorityPolicy=1
3449 // This mode causes the priority table to get filled with
3450 // linear values.  NormPriority get's mapped to 50% of the
3451 // Maximum priority an so on.  This will cause VM threads
3452 // to get unfair treatment against other Solaris processes
3453 // which do not explicitly alter their thread priorities.
3454 
3455 int os::java_to_os_priority[CriticalPriority + 1] = {
3456   -99999,         // 0 Entry should never be used
3457 
3458   0,              // 1 MinPriority
3459   32,             // 2
3460   64,             // 3
3461 
3462   96,             // 4
3463   127,            // 5 NormPriority
3464   127,            // 6
3465 
3466   127,            // 7
3467   127,            // 8
3468   127,            // 9 NearMaxPriority
3469 
3470   127,            // 10 MaxPriority
3471 
3472   -criticalPrio   // 11 CriticalPriority
3473 };
3474 
3475 OSReturn os::set_native_priority(Thread* thread, int newpri) {
3476   OSThread* osthread = thread->osthread();
3477 
3478   // Save requested priority in case the thread hasn't been started
3479   osthread->set_native_priority(newpri);
3480 
3481   // Check for critical priority request
3482   bool fxcritical = false;
3483   if (newpri == -criticalPrio) {
3484     fxcritical = true;
3485     newpri = criticalPrio;
3486   }
3487 
3488   assert(newpri >= MinimumPriority && newpri <= MaximumPriority, "bad priority mapping");
3489   if (!UseThreadPriorities) return OS_OK;
3490 
3491   int status = 0;
3492 
3493   if (!fxcritical) {
3494     // Use thr_setprio only if we have a priority that thr_setprio understands
3495     status = thr_setprio(thread->osthread()->thread_id(), newpri);
3496   }
3497 
3498   int lwp_status =
3499           set_lwp_class_and_priority(osthread->thread_id(),
3500                                      osthread->lwp_id(),
3501                                      newpri,
3502                                      fxcritical ? fxLimits.schedPolicy : myClass,
3503                                      !fxcritical);
3504   if (lwp_status != 0 && fxcritical) {
3505     // Try again, this time without changing the scheduling class
3506     newpri = java_MaxPriority_to_os_priority;
3507     lwp_status = set_lwp_class_and_priority(osthread->thread_id(),
3508                                             osthread->lwp_id(),
3509                                             newpri, myClass, false);
3510   }
3511   status |= lwp_status;
3512   return (status == 0) ? OS_OK : OS_ERR;
3513 }
3514 
3515 
3516 OSReturn os::get_native_priority(const Thread* const thread,
3517                                  int *priority_ptr) {
3518   int p;
3519   if (!UseThreadPriorities) {
3520     *priority_ptr = NormalPriority;
3521     return OS_OK;
3522   }
3523   int status = thr_getprio(thread->osthread()->thread_id(), &p);
3524   if (status != 0) {
3525     return OS_ERR;
3526   }
3527   *priority_ptr = p;
3528   return OS_OK;
3529 }
3530 
3531 
3532 // Hint to the underlying OS that a task switch would not be good.
3533 // Void return because it's a hint and can fail.
3534 void os::hint_no_preempt() {
3535   schedctl_start(schedctl_init());
3536 }
3537 
3538 static void resume_clear_context(OSThread *osthread) {
3539   osthread->set_ucontext(NULL);
3540 }
3541 
3542 static void suspend_save_context(OSThread *osthread, ucontext_t* context) {
3543   osthread->set_ucontext(context);
3544 }
3545 
3546 static PosixSemaphore sr_semaphore;
3547 
3548 void os::Solaris::SR_handler(Thread* thread, ucontext_t* uc) {
3549   // Save and restore errno to avoid confusing native code with EINTR
3550   // after sigsuspend.
3551   int old_errno = errno;
3552 
3553   OSThread* osthread = thread->osthread();
3554   assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
3555 
3556   os::SuspendResume::State current = osthread->sr.state();
3557   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
3558     suspend_save_context(osthread, uc);
3559 
3560     // attempt to switch the state, we assume we had a SUSPEND_REQUEST
3561     os::SuspendResume::State state = osthread->sr.suspended();
3562     if (state == os::SuspendResume::SR_SUSPENDED) {
3563       sigset_t suspend_set;  // signals for sigsuspend()
3564 
3565       // get current set of blocked signals and unblock resume signal
3566       pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
3567       sigdelset(&suspend_set, os::Solaris::SIGasync());
3568 
3569       sr_semaphore.signal();
3570       // wait here until we are resumed
3571       while (1) {
3572         sigsuspend(&suspend_set);
3573 
3574         os::SuspendResume::State result = osthread->sr.running();
3575         if (result == os::SuspendResume::SR_RUNNING) {
3576           sr_semaphore.signal();
3577           break;
3578         }
3579       }
3580 
3581     } else if (state == os::SuspendResume::SR_RUNNING) {
3582       // request was cancelled, continue
3583     } else {
3584       ShouldNotReachHere();
3585     }
3586 
3587     resume_clear_context(osthread);
3588   } else if (current == os::SuspendResume::SR_RUNNING) {
3589     // request was cancelled, continue
3590   } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
3591     // ignore
3592   } else {
3593     // ignore
3594   }
3595 
3596   errno = old_errno;
3597 }
3598 
3599 void os::print_statistics() {
3600 }
3601 
3602 bool os::message_box(const char* title, const char* message) {
3603   int i;
3604   fdStream err(defaultStream::error_fd());
3605   for (i = 0; i < 78; i++) err.print_raw("=");
3606   err.cr();
3607   err.print_raw_cr(title);
3608   for (i = 0; i < 78; i++) err.print_raw("-");
3609   err.cr();
3610   err.print_raw_cr(message);
3611   for (i = 0; i < 78; i++) err.print_raw("=");
3612   err.cr();
3613 
3614   char buf[16];
3615   // Prevent process from exiting upon "read error" without consuming all CPU
3616   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
3617 
3618   return buf[0] == 'y' || buf[0] == 'Y';
3619 }
3620 
3621 static int sr_notify(OSThread* osthread) {
3622   int status = thr_kill(osthread->thread_id(), os::Solaris::SIGasync());
3623   assert_status(status == 0, status, "thr_kill");
3624   return status;
3625 }
3626 
3627 // "Randomly" selected value for how long we want to spin
3628 // before bailing out on suspending a thread, also how often
3629 // we send a signal to a thread we want to resume
3630 static const int RANDOMLY_LARGE_INTEGER = 1000000;
3631 static const int RANDOMLY_LARGE_INTEGER2 = 100;
3632 
3633 static bool do_suspend(OSThread* osthread) {
3634   assert(osthread->sr.is_running(), "thread should be running");
3635   assert(!sr_semaphore.trywait(), "semaphore has invalid state");
3636 
3637   // mark as suspended and send signal
3638   if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
3639     // failed to switch, state wasn't running?
3640     ShouldNotReachHere();
3641     return false;
3642   }
3643 
3644   if (sr_notify(osthread) != 0) {
3645     ShouldNotReachHere();
3646   }
3647 
3648   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
3649   while (true) {
3650     if (sr_semaphore.timedwait(0, 2000 * NANOSECS_PER_MILLISEC)) {
3651       break;
3652     } else {
3653       // timeout
3654       os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
3655       if (cancelled == os::SuspendResume::SR_RUNNING) {
3656         return false;
3657       } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
3658         // make sure that we consume the signal on the semaphore as well
3659         sr_semaphore.wait();
3660         break;
3661       } else {
3662         ShouldNotReachHere();
3663         return false;
3664       }
3665     }
3666   }
3667 
3668   guarantee(osthread->sr.is_suspended(), "Must be suspended");
3669   return true;
3670 }
3671 
3672 static void do_resume(OSThread* osthread) {
3673   assert(osthread->sr.is_suspended(), "thread should be suspended");
3674   assert(!sr_semaphore.trywait(), "invalid semaphore state");
3675 
3676   if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
3677     // failed to switch to WAKEUP_REQUEST
3678     ShouldNotReachHere();
3679     return;
3680   }
3681 
3682   while (true) {
3683     if (sr_notify(osthread) == 0) {
3684       if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
3685         if (osthread->sr.is_running()) {
3686           return;
3687         }
3688       }
3689     } else {
3690       ShouldNotReachHere();
3691     }
3692   }
3693 
3694   guarantee(osthread->sr.is_running(), "Must be running!");
3695 }
3696 
3697 void os::SuspendedThreadTask::internal_do_task() {
3698   if (do_suspend(_thread->osthread())) {
3699     SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
3700     do_task(context);
3701     do_resume(_thread->osthread());
3702   }
3703 }
3704 
3705 class PcFetcher : public os::SuspendedThreadTask {
3706  public:
3707   PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
3708   ExtendedPC result();
3709  protected:
3710   void do_task(const os::SuspendedThreadTaskContext& context);
3711  private:
3712   ExtendedPC _epc;
3713 };
3714 
3715 ExtendedPC PcFetcher::result() {
3716   guarantee(is_done(), "task is not done yet.");
3717   return _epc;
3718 }
3719 
3720 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
3721   Thread* thread = context.thread();
3722   OSThread* osthread = thread->osthread();
3723   if (osthread->ucontext() != NULL) {
3724     _epc = os::Solaris::ucontext_get_pc((const ucontext_t *) context.ucontext());
3725   } else {
3726     // NULL context is unexpected, double-check this is the VMThread
3727     guarantee(thread->is_VM_thread(), "can only be called for VMThread");
3728   }
3729 }
3730 
3731 // A lightweight implementation that does not suspend the target thread and
3732 // thus returns only a hint. Used for profiling only!
3733 ExtendedPC os::get_thread_pc(Thread* thread) {
3734   // Make sure that it is called by the watcher and the Threads lock is owned.
3735   assert(Thread::current()->is_Watcher_thread(), "Must be watcher and own Threads_lock");
3736   // For now, is only used to profile the VM Thread
3737   assert(thread->is_VM_thread(), "Can only be called for VMThread");
3738   PcFetcher fetcher(thread);
3739   fetcher.run();
3740   return fetcher.result();
3741 }
3742 
3743 
3744 // This does not do anything on Solaris. This is basically a hook for being
3745 // able to use structured exception handling (thread-local exception filters) on, e.g., Win32.
3746 void os::os_exception_wrapper(java_call_t f, JavaValue* value,
3747                               const methodHandle& method, JavaCallArguments* args,
3748                               Thread* thread) {
3749   f(value, method, args, thread);
3750 }
3751 
3752 // This routine may be used by user applications as a "hook" to catch signals.
3753 // The user-defined signal handler must pass unrecognized signals to this
3754 // routine, and if it returns true (non-zero), then the signal handler must
3755 // return immediately.  If the flag "abort_if_unrecognized" is true, then this
3756 // routine will never retun false (zero), but instead will execute a VM panic
3757 // routine kill the process.
3758 //
3759 // If this routine returns false, it is OK to call it again.  This allows
3760 // the user-defined signal handler to perform checks either before or after
3761 // the VM performs its own checks.  Naturally, the user code would be making
3762 // a serious error if it tried to handle an exception (such as a null check
3763 // or breakpoint) that the VM was generating for its own correct operation.
3764 //
3765 // This routine may recognize any of the following kinds of signals:
3766 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, BREAK_SIGNAL, SIGPIPE, SIGXFSZ,
3767 // os::Solaris::SIGasync
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 JVM_handle_solaris_signal(int signo,
3779                                                    siginfo_t* siginfo,
3780                                                    void* ucontext,
3781                                                    int abort_if_unrecognized);
3782 
3783 
3784 void signalHandler(int sig, siginfo_t* info, void* ucVoid) {
3785   int orig_errno = errno;  // Preserve errno value over signal handler.
3786   JVM_handle_solaris_signal(sig, info, ucVoid, true);
3787   errno = orig_errno;
3788 }
3789 
3790 // This boolean allows users to forward their own non-matching signals
3791 // to JVM_handle_solaris_signal, harmlessly.
3792 bool os::Solaris::signal_handlers_are_installed = false;
3793 
3794 // For signal-chaining
3795 bool os::Solaris::libjsig_is_loaded = false;
3796 typedef struct sigaction *(*get_signal_t)(int);
3797 get_signal_t os::Solaris::get_signal_action = NULL;
3798 
3799 struct sigaction* os::Solaris::get_chained_signal_action(int sig) {
3800   struct sigaction *actp = NULL;
3801 
3802   if ((libjsig_is_loaded)  && (sig <= Maxlibjsigsigs)) {
3803     // Retrieve the old signal handler from libjsig
3804     actp = (*get_signal_action)(sig);
3805   }
3806   if (actp == NULL) {
3807     // Retrieve the preinstalled signal handler from jvm
3808     actp = get_preinstalled_handler(sig);
3809   }
3810 
3811   return actp;
3812 }
3813 
3814 static bool call_chained_handler(struct sigaction *actp, int sig,
3815                                  siginfo_t *siginfo, void *context) {
3816   // Call the old signal handler
3817   if (actp->sa_handler == SIG_DFL) {
3818     // It's more reasonable to let jvm treat it as an unexpected exception
3819     // instead of taking the default action.
3820     return false;
3821   } else if (actp->sa_handler != SIG_IGN) {
3822     if ((actp->sa_flags & SA_NODEFER) == 0) {
3823       // automaticlly block the signal
3824       sigaddset(&(actp->sa_mask), sig);
3825     }
3826 
3827     sa_handler_t hand;
3828     sa_sigaction_t sa;
3829     bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
3830     // retrieve the chained handler
3831     if (siginfo_flag_set) {
3832       sa = actp->sa_sigaction;
3833     } else {
3834       hand = actp->sa_handler;
3835     }
3836 
3837     if ((actp->sa_flags & SA_RESETHAND) != 0) {
3838       actp->sa_handler = SIG_DFL;
3839     }
3840 
3841     // try to honor the signal mask
3842     sigset_t oset;
3843     pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
3844 
3845     // call into the chained handler
3846     if (siginfo_flag_set) {
3847       (*sa)(sig, siginfo, context);
3848     } else {
3849       (*hand)(sig);
3850     }
3851 
3852     // restore the signal mask
3853     pthread_sigmask(SIG_SETMASK, &oset, 0);
3854   }
3855   // Tell jvm's signal handler the signal is taken care of.
3856   return true;
3857 }
3858 
3859 bool os::Solaris::chained_handler(int sig, siginfo_t* siginfo, void* context) {
3860   bool chained = false;
3861   // signal-chaining
3862   if (UseSignalChaining) {
3863     struct sigaction *actp = get_chained_signal_action(sig);
3864     if (actp != NULL) {
3865       chained = call_chained_handler(actp, sig, siginfo, context);
3866     }
3867   }
3868   return chained;
3869 }
3870 
3871 struct sigaction* os::Solaris::get_preinstalled_handler(int sig) {
3872   assert((chainedsigactions != (struct sigaction *)NULL) &&
3873          (preinstalled_sigs != (int *)NULL), "signals not yet initialized");
3874   if (preinstalled_sigs[sig] != 0) {
3875     return &chainedsigactions[sig];
3876   }
3877   return NULL;
3878 }
3879 
3880 void os::Solaris::save_preinstalled_handler(int sig,
3881                                             struct sigaction& oldAct) {
3882   assert(sig > 0 && sig <= Maxsignum, "vm signal out of expected range");
3883   assert((chainedsigactions != (struct sigaction *)NULL) &&
3884          (preinstalled_sigs != (int *)NULL), "signals not yet initialized");
3885   chainedsigactions[sig] = oldAct;
3886   preinstalled_sigs[sig] = 1;
3887 }
3888 
3889 void os::Solaris::set_signal_handler(int sig, bool set_installed,
3890                                      bool oktochain) {
3891   // Check for overwrite.
3892   struct sigaction oldAct;
3893   sigaction(sig, (struct sigaction*)NULL, &oldAct);
3894   void* oldhand =
3895       oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
3896                           : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
3897   if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
3898       oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
3899       oldhand != CAST_FROM_FN_PTR(void*, signalHandler)) {
3900     if (AllowUserSignalHandlers || !set_installed) {
3901       // Do not overwrite; user takes responsibility to forward to us.
3902       return;
3903     } else if (UseSignalChaining) {
3904       if (oktochain) {
3905         // save the old handler in jvm
3906         save_preinstalled_handler(sig, oldAct);
3907       } else {
3908         vm_exit_during_initialization("Signal chaining not allowed for VM interrupt signal.");
3909       }
3910       // libjsig also interposes the sigaction() call below and saves the
3911       // old sigaction on it own.
3912     } else {
3913       fatal("Encountered unexpected pre-existing sigaction handler "
3914             "%#lx for signal %d.", (long)oldhand, sig);
3915     }
3916   }
3917 
3918   struct sigaction sigAct;
3919   sigfillset(&(sigAct.sa_mask));
3920   sigAct.sa_handler = SIG_DFL;
3921 
3922   sigAct.sa_sigaction = signalHandler;
3923   // Handle SIGSEGV on alternate signal stack if
3924   // not using stack banging
3925   if (!UseStackBanging && sig == SIGSEGV) {
3926     sigAct.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK;
3927   } else {
3928     sigAct.sa_flags = SA_SIGINFO | SA_RESTART;
3929   }
3930   os::Solaris::set_our_sigflags(sig, sigAct.sa_flags);
3931 
3932   sigaction(sig, &sigAct, &oldAct);
3933 
3934   void* oldhand2 = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
3935                                        : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
3936   assert(oldhand2 == oldhand, "no concurrent signal handler installation");
3937 }
3938 
3939 
3940 #define DO_SIGNAL_CHECK(sig)                      \
3941   do {                                            \
3942     if (!sigismember(&check_signal_done, sig)) {  \
3943       os::Solaris::check_signal_handler(sig);     \
3944     }                                             \
3945   } while (0)
3946 
3947 // This method is a periodic task to check for misbehaving JNI applications
3948 // under CheckJNI, we can add any periodic checks here
3949 
3950 void os::run_periodic_checks() {
3951   // A big source of grief is hijacking virt. addr 0x0 on Solaris,
3952   // thereby preventing a NULL checks.
3953   if (!check_addr0_done) check_addr0_done = check_addr0(tty);
3954 
3955   if (check_signals == false) return;
3956 
3957   // SEGV and BUS if overridden could potentially prevent
3958   // generation of hs*.log in the event of a crash, debugging
3959   // such a case can be very challenging, so we absolutely
3960   // check for the following for a good measure:
3961   DO_SIGNAL_CHECK(SIGSEGV);
3962   DO_SIGNAL_CHECK(SIGILL);
3963   DO_SIGNAL_CHECK(SIGFPE);
3964   DO_SIGNAL_CHECK(SIGBUS);
3965   DO_SIGNAL_CHECK(SIGPIPE);
3966   DO_SIGNAL_CHECK(SIGXFSZ);
3967 
3968   // ReduceSignalUsage allows the user to override these handlers
3969   // see comments at the very top and jvm_solaris.h
3970   if (!ReduceSignalUsage) {
3971     DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
3972     DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
3973     DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
3974     DO_SIGNAL_CHECK(BREAK_SIGNAL);
3975   }
3976 
3977   // See comments above for using JVM1/JVM2
3978   DO_SIGNAL_CHECK(os::Solaris::SIGasync());
3979 
3980 }
3981 
3982 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
3983 
3984 static os_sigaction_t os_sigaction = NULL;
3985 
3986 void os::Solaris::check_signal_handler(int sig) {
3987   char buf[O_BUFLEN];
3988   address jvmHandler = NULL;
3989 
3990   struct sigaction act;
3991   if (os_sigaction == NULL) {
3992     // only trust the default sigaction, in case it has been interposed
3993     os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
3994     if (os_sigaction == NULL) return;
3995   }
3996 
3997   os_sigaction(sig, (struct sigaction*)NULL, &act);
3998 
3999   address thisHandler = (act.sa_flags & SA_SIGINFO)
4000     ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
4001     : CAST_FROM_FN_PTR(address, act.sa_handler);
4002 
4003 
4004   switch (sig) {
4005   case SIGSEGV:
4006   case SIGBUS:
4007   case SIGFPE:
4008   case SIGPIPE:
4009   case SIGXFSZ:
4010   case SIGILL:
4011     jvmHandler = CAST_FROM_FN_PTR(address, signalHandler);
4012     break;
4013 
4014   case SHUTDOWN1_SIGNAL:
4015   case SHUTDOWN2_SIGNAL:
4016   case SHUTDOWN3_SIGNAL:
4017   case BREAK_SIGNAL:
4018     jvmHandler = (address)user_handler();
4019     break;
4020 
4021   default:
4022     int asynsig = os::Solaris::SIGasync();
4023 
4024     if (sig == asynsig) {
4025       jvmHandler = CAST_FROM_FN_PTR(address, signalHandler);
4026     } else {
4027       return;
4028     }
4029     break;
4030   }
4031 
4032 
4033   if (thisHandler != jvmHandler) {
4034     tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
4035     tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
4036     tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
4037     // No need to check this sig any longer
4038     sigaddset(&check_signal_done, sig);
4039     // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN
4040     if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {
4041       tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell",
4042                     exception_name(sig, buf, O_BUFLEN));
4043     }
4044   } else if(os::Solaris::get_our_sigflags(sig) != 0 && act.sa_flags != os::Solaris::get_our_sigflags(sig)) {
4045     tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
4046     tty->print("expected:");
4047     os::Posix::print_sa_flags(tty, os::Solaris::get_our_sigflags(sig));
4048     tty->cr();
4049     tty->print("  found:");
4050     os::Posix::print_sa_flags(tty, act.sa_flags);
4051     tty->cr();
4052     // No need to check this sig any longer
4053     sigaddset(&check_signal_done, sig);
4054   }
4055 
4056   // Print all the signal handler state
4057   if (sigismember(&check_signal_done, sig)) {
4058     print_signal_handlers(tty, buf, O_BUFLEN);
4059   }
4060 
4061 }
4062 
4063 void os::Solaris::install_signal_handlers() {
4064   bool libjsigdone = false;
4065   signal_handlers_are_installed = true;
4066 
4067   // signal-chaining
4068   typedef void (*signal_setting_t)();
4069   signal_setting_t begin_signal_setting = NULL;
4070   signal_setting_t end_signal_setting = NULL;
4071   begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4072                                         dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
4073   if (begin_signal_setting != NULL) {
4074     end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4075                                         dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
4076     get_signal_action = CAST_TO_FN_PTR(get_signal_t,
4077                                        dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
4078     get_libjsig_version = CAST_TO_FN_PTR(version_getting_t,
4079                                          dlsym(RTLD_DEFAULT, "JVM_get_libjsig_version"));
4080     libjsig_is_loaded = true;
4081     if (os::Solaris::get_libjsig_version != NULL) {
4082       libjsigversion =  (*os::Solaris::get_libjsig_version)();
4083     }
4084     assert(UseSignalChaining, "should enable signal-chaining");
4085   }
4086   if (libjsig_is_loaded) {
4087     // Tell libjsig jvm is setting signal handlers
4088     (*begin_signal_setting)();
4089   }
4090 
4091   set_signal_handler(SIGSEGV, true, true);
4092   set_signal_handler(SIGPIPE, true, true);
4093   set_signal_handler(SIGXFSZ, true, true);
4094   set_signal_handler(SIGBUS, true, true);
4095   set_signal_handler(SIGILL, true, true);
4096   set_signal_handler(SIGFPE, true, true);
4097 
4098 
4099   if (os::Solaris::SIGasync() > OLDMAXSIGNUM) {
4100     // Pre-1.4.1 Libjsig limited to signal chaining signals <= 32 so
4101     // can not register overridable signals which might be > 32
4102     if (libjsig_is_loaded && libjsigversion <= JSIG_VERSION_1_4_1) {
4103       // Tell libjsig jvm has finished setting signal handlers
4104       (*end_signal_setting)();
4105       libjsigdone = true;
4106     }
4107   }
4108 
4109   set_signal_handler(os::Solaris::SIGasync(), true, true);
4110 
4111   if (libjsig_is_loaded && !libjsigdone) {
4112     // Tell libjsig jvm finishes setting signal handlers
4113     (*end_signal_setting)();
4114   }
4115 
4116   // We don't activate signal checker if libjsig is in place, we trust ourselves
4117   // and if UserSignalHandler is installed all bets are off.
4118   // Log that signal checking is off only if -verbose:jni is specified.
4119   if (CheckJNICalls) {
4120     if (libjsig_is_loaded) {
4121       if (PrintJNIResolving) {
4122         tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
4123       }
4124       check_signals = false;
4125     }
4126     if (AllowUserSignalHandlers) {
4127       if (PrintJNIResolving) {
4128         tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
4129       }
4130       check_signals = false;
4131     }
4132   }
4133 }
4134 
4135 
4136 void report_error(const char* file_name, int line_no, const char* title,
4137                   const char* format, ...);
4138 
4139 // (Static) wrappers for the liblgrp API
4140 os::Solaris::lgrp_home_func_t os::Solaris::_lgrp_home;
4141 os::Solaris::lgrp_init_func_t os::Solaris::_lgrp_init;
4142 os::Solaris::lgrp_fini_func_t os::Solaris::_lgrp_fini;
4143 os::Solaris::lgrp_root_func_t os::Solaris::_lgrp_root;
4144 os::Solaris::lgrp_children_func_t os::Solaris::_lgrp_children;
4145 os::Solaris::lgrp_resources_func_t os::Solaris::_lgrp_resources;
4146 os::Solaris::lgrp_nlgrps_func_t os::Solaris::_lgrp_nlgrps;
4147 os::Solaris::lgrp_cookie_stale_func_t os::Solaris::_lgrp_cookie_stale;
4148 os::Solaris::lgrp_cookie_t os::Solaris::_lgrp_cookie = 0;
4149 
4150 static address resolve_symbol_lazy(const char* name) {
4151   address addr = (address) dlsym(RTLD_DEFAULT, name);
4152   if (addr == NULL) {
4153     // RTLD_DEFAULT was not defined on some early versions of 2.5.1
4154     addr = (address) dlsym(RTLD_NEXT, name);
4155   }
4156   return addr;
4157 }
4158 
4159 static address resolve_symbol(const char* name) {
4160   address addr = resolve_symbol_lazy(name);
4161   if (addr == NULL) {
4162     fatal(dlerror());
4163   }
4164   return addr;
4165 }
4166 
4167 void os::Solaris::libthread_init() {
4168   address func = (address)dlsym(RTLD_DEFAULT, "_thr_suspend_allmutators");
4169 
4170   lwp_priocntl_init();
4171 
4172   // RTLD_DEFAULT was not defined on some early versions of 5.5.1
4173   if (func == NULL) {
4174     func = (address) dlsym(RTLD_NEXT, "_thr_suspend_allmutators");
4175     // Guarantee that this VM is running on an new enough OS (5.6 or
4176     // later) that it will have a new enough libthread.so.
4177     guarantee(func != NULL, "libthread.so is too old.");
4178   }
4179 
4180   int size;
4181   void (*handler_info_func)(address *, int *);
4182   handler_info_func = CAST_TO_FN_PTR(void (*)(address *, int *), resolve_symbol("thr_sighndlrinfo"));
4183   handler_info_func(&handler_start, &size);
4184   handler_end = handler_start + size;
4185 }
4186 
4187 
4188 int_fnP_mutex_tP os::Solaris::_mutex_lock;
4189 int_fnP_mutex_tP os::Solaris::_mutex_trylock;
4190 int_fnP_mutex_tP os::Solaris::_mutex_unlock;
4191 int_fnP_mutex_tP_i_vP os::Solaris::_mutex_init;
4192 int_fnP_mutex_tP os::Solaris::_mutex_destroy;
4193 int os::Solaris::_mutex_scope = USYNC_THREAD;
4194 
4195 int_fnP_cond_tP_mutex_tP_timestruc_tP os::Solaris::_cond_timedwait;
4196 int_fnP_cond_tP_mutex_tP os::Solaris::_cond_wait;
4197 int_fnP_cond_tP os::Solaris::_cond_signal;
4198 int_fnP_cond_tP os::Solaris::_cond_broadcast;
4199 int_fnP_cond_tP_i_vP os::Solaris::_cond_init;
4200 int_fnP_cond_tP os::Solaris::_cond_destroy;
4201 int os::Solaris::_cond_scope = USYNC_THREAD;
4202 
4203 void os::Solaris::synchronization_init() {
4204   if (UseLWPSynchronization) {
4205     os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_lock")));
4206     os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_trylock")));
4207     os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_unlock")));
4208     os::Solaris::set_mutex_init(lwp_mutex_init);
4209     os::Solaris::set_mutex_destroy(lwp_mutex_destroy);
4210     os::Solaris::set_mutex_scope(USYNC_THREAD);
4211 
4212     os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("_lwp_cond_timedwait")));
4213     os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("_lwp_cond_wait")));
4214     os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_signal")));
4215     os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_broadcast")));
4216     os::Solaris::set_cond_init(lwp_cond_init);
4217     os::Solaris::set_cond_destroy(lwp_cond_destroy);
4218     os::Solaris::set_cond_scope(USYNC_THREAD);
4219   } else {
4220     os::Solaris::set_mutex_scope(USYNC_THREAD);
4221     os::Solaris::set_cond_scope(USYNC_THREAD);
4222 
4223     if (UsePthreads) {
4224       os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_lock")));
4225       os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_trylock")));
4226       os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_unlock")));
4227       os::Solaris::set_mutex_init(pthread_mutex_default_init);
4228       os::Solaris::set_mutex_destroy(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_destroy")));
4229 
4230       os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("pthread_cond_timedwait")));
4231       os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("pthread_cond_wait")));
4232       os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_signal")));
4233       os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_broadcast")));
4234       os::Solaris::set_cond_init(pthread_cond_default_init);
4235       os::Solaris::set_cond_destroy(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_destroy")));
4236     } else {
4237       os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_lock")));
4238       os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_trylock")));
4239       os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_unlock")));
4240       os::Solaris::set_mutex_init(::mutex_init);
4241       os::Solaris::set_mutex_destroy(::mutex_destroy);
4242 
4243       os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("cond_timedwait")));
4244       os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("cond_wait")));
4245       os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_signal")));
4246       os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_broadcast")));
4247       os::Solaris::set_cond_init(::cond_init);
4248       os::Solaris::set_cond_destroy(::cond_destroy);
4249     }
4250   }
4251 }
4252 
4253 bool os::Solaris::liblgrp_init() {
4254   void *handle = dlopen("liblgrp.so.1", RTLD_LAZY);
4255   if (handle != NULL) {
4256     os::Solaris::set_lgrp_home(CAST_TO_FN_PTR(lgrp_home_func_t, dlsym(handle, "lgrp_home")));
4257     os::Solaris::set_lgrp_init(CAST_TO_FN_PTR(lgrp_init_func_t, dlsym(handle, "lgrp_init")));
4258     os::Solaris::set_lgrp_fini(CAST_TO_FN_PTR(lgrp_fini_func_t, dlsym(handle, "lgrp_fini")));
4259     os::Solaris::set_lgrp_root(CAST_TO_FN_PTR(lgrp_root_func_t, dlsym(handle, "lgrp_root")));
4260     os::Solaris::set_lgrp_children(CAST_TO_FN_PTR(lgrp_children_func_t, dlsym(handle, "lgrp_children")));
4261     os::Solaris::set_lgrp_resources(CAST_TO_FN_PTR(lgrp_resources_func_t, dlsym(handle, "lgrp_resources")));
4262     os::Solaris::set_lgrp_nlgrps(CAST_TO_FN_PTR(lgrp_nlgrps_func_t, dlsym(handle, "lgrp_nlgrps")));
4263     os::Solaris::set_lgrp_cookie_stale(CAST_TO_FN_PTR(lgrp_cookie_stale_func_t,
4264                                                       dlsym(handle, "lgrp_cookie_stale")));
4265 
4266     lgrp_cookie_t c = lgrp_init(LGRP_VIEW_CALLER);
4267     set_lgrp_cookie(c);
4268     return true;
4269   }
4270   return false;
4271 }
4272 
4273 // int pset_getloadavg(psetid_t pset, double loadavg[], int nelem);
4274 typedef long (*pset_getloadavg_type)(psetid_t pset, double loadavg[], int nelem);
4275 static pset_getloadavg_type pset_getloadavg_ptr = NULL;
4276 
4277 void init_pset_getloadavg_ptr(void) {
4278   pset_getloadavg_ptr =
4279     (pset_getloadavg_type)dlsym(RTLD_DEFAULT, "pset_getloadavg");
4280   if (pset_getloadavg_ptr == NULL) {
4281     log_warning(os)("pset_getloadavg function not found");
4282   }
4283 }
4284 
4285 int os::Solaris::_dev_zero_fd = -1;
4286 
4287 // this is called _before_ the global arguments have been parsed
4288 void os::init(void) {
4289   _initial_pid = getpid();
4290 
4291   max_hrtime = first_hrtime = gethrtime();
4292 
4293   init_random(1234567);
4294 
4295   page_size = sysconf(_SC_PAGESIZE);
4296   if (page_size == -1) {
4297     fatal("os_solaris.cpp: os::init: sysconf failed (%s)", os::strerror(errno));
4298   }
4299   init_page_sizes((size_t) page_size);
4300 
4301   Solaris::initialize_system_info();
4302 
4303   int fd = ::open("/dev/zero", O_RDWR);
4304   if (fd < 0) {
4305     fatal("os::init: cannot open /dev/zero (%s)", os::strerror(errno));
4306   } else {
4307     Solaris::set_dev_zero_fd(fd);
4308 
4309     // Close on exec, child won't inherit.
4310     fcntl(fd, F_SETFD, FD_CLOEXEC);
4311   }
4312 
4313   clock_tics_per_sec = CLK_TCK;
4314 
4315   // check if dladdr1() exists; dladdr1 can provide more information than
4316   // dladdr for os::dll_address_to_function_name. It comes with SunOS 5.9
4317   // and is available on linker patches for 5.7 and 5.8.
4318   // libdl.so must have been loaded, this call is just an entry lookup
4319   void * hdl = dlopen("libdl.so", RTLD_NOW);
4320   if (hdl) {
4321     dladdr1_func = CAST_TO_FN_PTR(dladdr1_func_type, dlsym(hdl, "dladdr1"));
4322   }
4323 
4324   // (Solaris only) this switches to calls that actually do locking.
4325   ThreadCritical::initialize();
4326 
4327   main_thread = thr_self();
4328 
4329   // Constant minimum stack size allowed. It must be at least
4330   // the minimum of what the OS supports (thr_min_stack()), and
4331   // enough to allow the thread to get to user bytecode execution.
4332   Posix::_compiler_thread_min_stack_allowed = MAX2(thr_min_stack(),
4333                                                    Posix::_compiler_thread_min_stack_allowed);
4334   Posix::_java_thread_min_stack_allowed = MAX2(thr_min_stack(),
4335                                                Posix::_java_thread_min_stack_allowed);
4336   Posix::_vm_internal_thread_min_stack_allowed = MAX2(thr_min_stack(),
4337                                                       Posix::_vm_internal_thread_min_stack_allowed);
4338 
4339   // dynamic lookup of functions that may not be available in our lowest
4340   // supported Solaris release
4341   void * handle = dlopen("libc.so.1", RTLD_LAZY);
4342   if (handle != NULL) {
4343     Solaris::_pthread_setname_np =  // from 11.3
4344         (Solaris::pthread_setname_np_func_t)dlsym(handle, "pthread_setname_np");
4345   }
4346 }
4347 
4348 // To install functions for atexit system call
4349 extern "C" {
4350   static void perfMemory_exit_helper() {
4351     perfMemory_exit();
4352   }
4353 }
4354 
4355 // this is called _after_ the global arguments have been parsed
4356 jint os::init_2(void) {
4357   // try to enable extended file IO ASAP, see 6431278
4358   os::Solaris::try_enable_extended_io();
4359 
4360   // Allocate a single page and mark it as readable for safepoint polling.  Also
4361   // use this first mmap call to check support for MAP_ALIGN.
4362   address polling_page = (address)Solaris::mmap_chunk((char*)page_size,
4363                                                       page_size,
4364                                                       MAP_PRIVATE | MAP_ALIGN,
4365                                                       PROT_READ);
4366   if (polling_page == NULL) {
4367     has_map_align = false;
4368     polling_page = (address)Solaris::mmap_chunk(NULL, page_size, MAP_PRIVATE,
4369                                                 PROT_READ);
4370   }
4371 
4372   os::set_polling_page(polling_page);
4373   log_info(os)("SafePoint Polling address: " INTPTR_FORMAT, p2i(polling_page));
4374 
4375   if (!UseMembar) {
4376     address mem_serialize_page = (address)Solaris::mmap_chunk(NULL, page_size, MAP_PRIVATE, PROT_READ | PROT_WRITE);
4377     guarantee(mem_serialize_page != NULL, "mmap Failed for memory serialize page");
4378     os::set_memory_serialize_page(mem_serialize_page);
4379     log_info(os)("Memory Serialize Page address: " INTPTR_FORMAT, p2i(mem_serialize_page));
4380   }
4381 
4382   // Check and sets minimum stack sizes against command line options
4383   if (Posix::set_minimum_stack_sizes() == JNI_ERR) {
4384     return JNI_ERR;
4385   }
4386 
4387   Solaris::libthread_init();
4388 
4389   if (UseNUMA) {
4390     if (!Solaris::liblgrp_init()) {
4391       UseNUMA = false;
4392     } else {
4393       size_t lgrp_limit = os::numa_get_groups_num();
4394       int *lgrp_ids = NEW_C_HEAP_ARRAY(int, lgrp_limit, mtInternal);
4395       size_t lgrp_num = os::numa_get_leaf_groups(lgrp_ids, lgrp_limit);
4396       FREE_C_HEAP_ARRAY(int, lgrp_ids);
4397       if (lgrp_num < 2) {
4398         // There's only one locality group, disable NUMA.
4399         UseNUMA = false;
4400       }
4401     }
4402     if (!UseNUMA && ForceNUMA) {
4403       UseNUMA = true;
4404     }
4405   }
4406 
4407   Solaris::signal_sets_init();
4408   Solaris::init_signal_mem();
4409   Solaris::install_signal_handlers();
4410 
4411   if (libjsigversion < JSIG_VERSION_1_4_1) {
4412     Maxlibjsigsigs = OLDMAXSIGNUM;
4413   }
4414 
4415   // initialize synchronization primitives to use either thread or
4416   // lwp synchronization (controlled by UseLWPSynchronization)
4417   Solaris::synchronization_init();
4418 
4419   if (MaxFDLimit) {
4420     // set the number of file descriptors to max. print out error
4421     // if getrlimit/setrlimit fails but continue regardless.
4422     struct rlimit nbr_files;
4423     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
4424     if (status != 0) {
4425       log_info(os)("os::init_2 getrlimit failed: %s", os::strerror(errno));
4426     } else {
4427       nbr_files.rlim_cur = nbr_files.rlim_max;
4428       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
4429       if (status != 0) {
4430         log_info(os)("os::init_2 setrlimit failed: %s", os::strerror(errno));
4431       }
4432     }
4433   }
4434 
4435   // Calculate theoretical max. size of Threads to guard gainst
4436   // artifical out-of-memory situations, where all available address-
4437   // space has been reserved by thread stacks. Default stack size is 1Mb.
4438   size_t pre_thread_stack_size = (JavaThread::stack_size_at_create()) ?
4439     JavaThread::stack_size_at_create() : (1*K*K);
4440   assert(pre_thread_stack_size != 0, "Must have a stack");
4441   // Solaris has a maximum of 4Gb of user programs. Calculate the thread limit when
4442   // we should start doing Virtual Memory banging. Currently when the threads will
4443   // have used all but 200Mb of space.
4444   size_t max_address_space = ((unsigned int)4 * K * K * K) - (200 * K * K);
4445   Solaris::_os_thread_limit = max_address_space / pre_thread_stack_size;
4446 
4447   // at-exit methods are called in the reverse order of their registration.
4448   // In Solaris 7 and earlier, atexit functions are called on return from
4449   // main or as a result of a call to exit(3C). There can be only 32 of
4450   // these functions registered and atexit() does not set errno. In Solaris
4451   // 8 and later, there is no limit to the number of functions registered
4452   // and atexit() sets errno. In addition, in Solaris 8 and later, atexit
4453   // functions are called upon dlclose(3DL) in addition to return from main
4454   // and exit(3C).
4455 
4456   if (PerfAllowAtExitRegistration) {
4457     // only register atexit functions if PerfAllowAtExitRegistration is set.
4458     // atexit functions can be delayed until process exit time, which
4459     // can be problematic for embedded VM situations. Embedded VMs should
4460     // call DestroyJavaVM() to assure that VM resources are released.
4461 
4462     // note: perfMemory_exit_helper atexit function may be removed in
4463     // the future if the appropriate cleanup code can be added to the
4464     // VM_Exit VMOperation's doit method.
4465     if (atexit(perfMemory_exit_helper) != 0) {
4466       warning("os::init2 atexit(perfMemory_exit_helper) failed");
4467     }
4468   }
4469 
4470   // Init pset_loadavg function pointer
4471   init_pset_getloadavg_ptr();
4472 
4473   return JNI_OK;
4474 }
4475 
4476 // Mark the polling page as unreadable
4477 void os::make_polling_page_unreadable(void) {
4478   if (mprotect((char *)_polling_page, page_size, PROT_NONE) != 0) {
4479     fatal("Could not disable polling page");
4480   }
4481 }
4482 
4483 // Mark the polling page as readable
4484 void os::make_polling_page_readable(void) {
4485   if (mprotect((char *)_polling_page, page_size, PROT_READ) != 0) {
4486     fatal("Could not enable polling page");
4487   }
4488 }
4489 
4490 // Is a (classpath) directory empty?
4491 bool os::dir_is_empty(const char* path) {
4492   DIR *dir = NULL;
4493   struct dirent *ptr;
4494 
4495   dir = opendir(path);
4496   if (dir == NULL) return true;
4497 
4498   // Scan the directory
4499   bool result = true;
4500   char buf[sizeof(struct dirent) + MAX_PATH];
4501   struct dirent *dbuf = (struct dirent *) buf;
4502   while (result && (ptr = readdir(dir, dbuf)) != NULL) {
4503     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
4504       result = false;
4505     }
4506   }
4507   closedir(dir);
4508   return result;
4509 }
4510 
4511 // This code originates from JDK's sysOpen and open64_w
4512 // from src/solaris/hpi/src/system_md.c
4513 
4514 int os::open(const char *path, int oflag, int mode) {
4515   if (strlen(path) > MAX_PATH - 1) {
4516     errno = ENAMETOOLONG;
4517     return -1;
4518   }
4519   int fd;
4520 
4521   fd = ::open64(path, oflag, mode);
4522   if (fd == -1) return -1;
4523 
4524   // If the open succeeded, the file might still be a directory
4525   {
4526     struct stat64 buf64;
4527     int ret = ::fstat64(fd, &buf64);
4528     int st_mode = buf64.st_mode;
4529 
4530     if (ret != -1) {
4531       if ((st_mode & S_IFMT) == S_IFDIR) {
4532         errno = EISDIR;
4533         ::close(fd);
4534         return -1;
4535       }
4536     } else {
4537       ::close(fd);
4538       return -1;
4539     }
4540   }
4541 
4542   // 32-bit Solaris systems suffer from:
4543   //
4544   // - an historical default soft limit of 256 per-process file
4545   //   descriptors that is too low for many Java programs.
4546   //
4547   // - a design flaw where file descriptors created using stdio
4548   //   fopen must be less than 256, _even_ when the first limit above
4549   //   has been raised.  This can cause calls to fopen (but not calls to
4550   //   open, for example) to fail mysteriously, perhaps in 3rd party
4551   //   native code (although the JDK itself uses fopen).  One can hardly
4552   //   criticize them for using this most standard of all functions.
4553   //
4554   // We attempt to make everything work anyways by:
4555   //
4556   // - raising the soft limit on per-process file descriptors beyond
4557   //   256
4558   //
4559   // - As of Solaris 10u4, we can request that Solaris raise the 256
4560   //   stdio fopen limit by calling function enable_extended_FILE_stdio.
4561   //   This is done in init_2 and recorded in enabled_extended_FILE_stdio
4562   //
4563   // - If we are stuck on an old (pre 10u4) Solaris system, we can
4564   //   workaround the bug by remapping non-stdio file descriptors below
4565   //   256 to ones beyond 256, which is done below.
4566   //
4567   // See:
4568   // 1085341: 32-bit stdio routines should support file descriptors >255
4569   // 6533291: Work around 32-bit Solaris stdio limit of 256 open files
4570   // 6431278: Netbeans crash on 32 bit Solaris: need to call
4571   //          enable_extended_FILE_stdio() in VM initialisation
4572   // Giri Mandalika's blog
4573   // http://technopark02.blogspot.com/2005_05_01_archive.html
4574   //
4575 #ifndef  _LP64
4576   if ((!enabled_extended_FILE_stdio) && fd < 256) {
4577     int newfd = ::fcntl(fd, F_DUPFD, 256);
4578     if (newfd != -1) {
4579       ::close(fd);
4580       fd = newfd;
4581     }
4582   }
4583 #endif // 32-bit Solaris
4584 
4585   // All file descriptors that are opened in the JVM and not
4586   // specifically destined for a subprocess should have the
4587   // close-on-exec flag set.  If we don't set it, then careless 3rd
4588   // party native code might fork and exec without closing all
4589   // appropriate file descriptors (e.g. as we do in closeDescriptors in
4590   // UNIXProcess.c), and this in turn might:
4591   //
4592   // - cause end-of-file to fail to be detected on some file
4593   //   descriptors, resulting in mysterious hangs, or
4594   //
4595   // - might cause an fopen in the subprocess to fail on a system
4596   //   suffering from bug 1085341.
4597   //
4598   // (Yes, the default setting of the close-on-exec flag is a Unix
4599   // design flaw)
4600   //
4601   // See:
4602   // 1085341: 32-bit stdio routines should support file descriptors >255
4603   // 4843136: (process) pipe file descriptor from Runtime.exec not being closed
4604   // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
4605   //
4606 #ifdef FD_CLOEXEC
4607   {
4608     int flags = ::fcntl(fd, F_GETFD);
4609     if (flags != -1) {
4610       ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4611     }
4612   }
4613 #endif
4614 
4615   return fd;
4616 }
4617 
4618 // create binary file, rewriting existing file if required
4619 int os::create_binary_file(const char* path, bool rewrite_existing) {
4620   int oflags = O_WRONLY | O_CREAT;
4621   if (!rewrite_existing) {
4622     oflags |= O_EXCL;
4623   }
4624   return ::open64(path, oflags, S_IREAD | S_IWRITE);
4625 }
4626 
4627 // return current position of file pointer
4628 jlong os::current_file_offset(int fd) {
4629   return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);
4630 }
4631 
4632 // move file pointer to the specified offset
4633 jlong os::seek_to_file_offset(int fd, jlong offset) {
4634   return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);
4635 }
4636 
4637 jlong os::lseek(int fd, jlong offset, int whence) {
4638   return (jlong) ::lseek64(fd, offset, whence);
4639 }
4640 
4641 char * os::native_path(char *path) {
4642   return path;
4643 }
4644 
4645 int os::ftruncate(int fd, jlong length) {
4646   return ::ftruncate64(fd, length);
4647 }
4648 
4649 int os::fsync(int fd)  {
4650   RESTARTABLE_RETURN_INT(::fsync(fd));
4651 }
4652 
4653 int os::available(int fd, jlong *bytes) {
4654   assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
4655          "Assumed _thread_in_native");
4656   jlong cur, end;
4657   int mode;
4658   struct stat64 buf64;
4659 
4660   if (::fstat64(fd, &buf64) >= 0) {
4661     mode = buf64.st_mode;
4662     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
4663       int n,ioctl_return;
4664 
4665       RESTARTABLE(::ioctl(fd, FIONREAD, &n), ioctl_return);
4666       if (ioctl_return>= 0) {
4667         *bytes = n;
4668         return 1;
4669       }
4670     }
4671   }
4672   if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {
4673     return 0;
4674   } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {
4675     return 0;
4676   } else if (::lseek64(fd, cur, SEEK_SET) == -1) {
4677     return 0;
4678   }
4679   *bytes = end - cur;
4680   return 1;
4681 }
4682 
4683 // Map a block of memory.
4684 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
4685                         char *addr, size_t bytes, bool read_only,
4686                         bool allow_exec) {
4687   int prot;
4688   int flags;
4689 
4690   if (read_only) {
4691     prot = PROT_READ;
4692     flags = MAP_SHARED;
4693   } else {
4694     prot = PROT_READ | PROT_WRITE;
4695     flags = MAP_PRIVATE;
4696   }
4697 
4698   if (allow_exec) {
4699     prot |= PROT_EXEC;
4700   }
4701 
4702   if (addr != NULL) {
4703     flags |= MAP_FIXED;
4704   }
4705 
4706   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
4707                                      fd, file_offset);
4708   if (mapped_address == MAP_FAILED) {
4709     return NULL;
4710   }
4711   return mapped_address;
4712 }
4713 
4714 
4715 // Remap a block of memory.
4716 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
4717                           char *addr, size_t bytes, bool read_only,
4718                           bool allow_exec) {
4719   // same as map_memory() on this OS
4720   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
4721                         allow_exec);
4722 }
4723 
4724 
4725 // Unmap a block of memory.
4726 bool os::pd_unmap_memory(char* addr, size_t bytes) {
4727   return munmap(addr, bytes) == 0;
4728 }
4729 
4730 void os::pause() {
4731   char filename[MAX_PATH];
4732   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
4733     jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
4734   } else {
4735     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
4736   }
4737 
4738   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
4739   if (fd != -1) {
4740     struct stat buf;
4741     ::close(fd);
4742     while (::stat(filename, &buf) == 0) {
4743       (void)::poll(NULL, 0, 100);
4744     }
4745   } else {
4746     jio_fprintf(stderr,
4747                 "Could not open pause file '%s', continuing immediately.\n", filename);
4748   }
4749 }
4750 
4751 #ifndef PRODUCT
4752 #ifdef INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS
4753 // Turn this on if you need to trace synch operations.
4754 // Set RECORD_SYNCH_LIMIT to a large-enough value,
4755 // and call record_synch_enable and record_synch_disable
4756 // around the computation of interest.
4757 
4758 void record_synch(char* name, bool returning);  // defined below
4759 
4760 class RecordSynch {
4761   char* _name;
4762  public:
4763   RecordSynch(char* name) :_name(name) { record_synch(_name, false); }
4764   ~RecordSynch()                       { record_synch(_name, true); }
4765 };
4766 
4767 #define CHECK_SYNCH_OP(ret, name, params, args, inner)          \
4768 extern "C" ret name params {                                    \
4769   typedef ret name##_t params;                                  \
4770   static name##_t* implem = NULL;                               \
4771   static int callcount = 0;                                     \
4772   if (implem == NULL) {                                         \
4773     implem = (name##_t*) dlsym(RTLD_NEXT, #name);               \
4774     if (implem == NULL)  fatal(dlerror());                      \
4775   }                                                             \
4776   ++callcount;                                                  \
4777   RecordSynch _rs(#name);                                       \
4778   inner;                                                        \
4779   return implem args;                                           \
4780 }
4781 // in dbx, examine callcounts this way:
4782 // for n in $(eval whereis callcount | awk '{print $2}'); do print $n; done
4783 
4784 #define CHECK_POINTER_OK(p) \
4785   (!Universe::is_fully_initialized() || !Universe::is_reserved_heap((oop)(p)))
4786 #define CHECK_MU \
4787   if (!CHECK_POINTER_OK(mu)) fatal("Mutex must be in C heap only.");
4788 #define CHECK_CV \
4789   if (!CHECK_POINTER_OK(cv)) fatal("Condvar must be in C heap only.");
4790 #define CHECK_P(p) \
4791   if (!CHECK_POINTER_OK(p))  fatal(false,  "Pointer must be in C heap only.");
4792 
4793 #define CHECK_MUTEX(mutex_op) \
4794   CHECK_SYNCH_OP(int, mutex_op, (mutex_t *mu), (mu), CHECK_MU);
4795 
4796 CHECK_MUTEX(   mutex_lock)
4797 CHECK_MUTEX(  _mutex_lock)
4798 CHECK_MUTEX( mutex_unlock)
4799 CHECK_MUTEX(_mutex_unlock)
4800 CHECK_MUTEX( mutex_trylock)
4801 CHECK_MUTEX(_mutex_trylock)
4802 
4803 #define CHECK_COND(cond_op) \
4804   CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu), (cv, mu), CHECK_MU; CHECK_CV);
4805 
4806 CHECK_COND( cond_wait);
4807 CHECK_COND(_cond_wait);
4808 CHECK_COND(_cond_wait_cancel);
4809 
4810 #define CHECK_COND2(cond_op) \
4811   CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu, timestruc_t* ts), (cv, mu, ts), CHECK_MU; CHECK_CV);
4812 
4813 CHECK_COND2( cond_timedwait);
4814 CHECK_COND2(_cond_timedwait);
4815 CHECK_COND2(_cond_timedwait_cancel);
4816 
4817 // do the _lwp_* versions too
4818 #define mutex_t lwp_mutex_t
4819 #define cond_t  lwp_cond_t
4820 CHECK_MUTEX(  _lwp_mutex_lock)
4821 CHECK_MUTEX(  _lwp_mutex_unlock)
4822 CHECK_MUTEX(  _lwp_mutex_trylock)
4823 CHECK_MUTEX( __lwp_mutex_lock)
4824 CHECK_MUTEX( __lwp_mutex_unlock)
4825 CHECK_MUTEX( __lwp_mutex_trylock)
4826 CHECK_MUTEX(___lwp_mutex_lock)
4827 CHECK_MUTEX(___lwp_mutex_unlock)
4828 
4829 CHECK_COND(  _lwp_cond_wait);
4830 CHECK_COND( __lwp_cond_wait);
4831 CHECK_COND(___lwp_cond_wait);
4832 
4833 CHECK_COND2(  _lwp_cond_timedwait);
4834 CHECK_COND2( __lwp_cond_timedwait);
4835 #undef mutex_t
4836 #undef cond_t
4837 
4838 CHECK_SYNCH_OP(int, _lwp_suspend2,       (int lwp, int *n), (lwp, n), 0);
4839 CHECK_SYNCH_OP(int,__lwp_suspend2,       (int lwp, int *n), (lwp, n), 0);
4840 CHECK_SYNCH_OP(int, _lwp_kill,           (int lwp, int n),  (lwp, n), 0);
4841 CHECK_SYNCH_OP(int,__lwp_kill,           (int lwp, int n),  (lwp, n), 0);
4842 CHECK_SYNCH_OP(int, _lwp_sema_wait,      (lwp_sema_t* p),   (p),  CHECK_P(p));
4843 CHECK_SYNCH_OP(int,__lwp_sema_wait,      (lwp_sema_t* p),   (p),  CHECK_P(p));
4844 CHECK_SYNCH_OP(int, _lwp_cond_broadcast, (lwp_cond_t* cv),  (cv), CHECK_CV);
4845 CHECK_SYNCH_OP(int,__lwp_cond_broadcast, (lwp_cond_t* cv),  (cv), CHECK_CV);
4846 
4847 
4848 // recording machinery:
4849 
4850 enum { RECORD_SYNCH_LIMIT = 200 };
4851 char* record_synch_name[RECORD_SYNCH_LIMIT];
4852 void* record_synch_arg0ptr[RECORD_SYNCH_LIMIT];
4853 bool record_synch_returning[RECORD_SYNCH_LIMIT];
4854 thread_t record_synch_thread[RECORD_SYNCH_LIMIT];
4855 int record_synch_count = 0;
4856 bool record_synch_enabled = false;
4857 
4858 // in dbx, examine recorded data this way:
4859 // for n in name arg0ptr returning thread; do print record_synch_$n[0..record_synch_count-1]; done
4860 
4861 void record_synch(char* name, bool returning) {
4862   if (record_synch_enabled) {
4863     if (record_synch_count < RECORD_SYNCH_LIMIT) {
4864       record_synch_name[record_synch_count] = name;
4865       record_synch_returning[record_synch_count] = returning;
4866       record_synch_thread[record_synch_count] = thr_self();
4867       record_synch_arg0ptr[record_synch_count] = &name;
4868       record_synch_count++;
4869     }
4870     // put more checking code here:
4871     // ...
4872   }
4873 }
4874 
4875 void record_synch_enable() {
4876   // start collecting trace data, if not already doing so
4877   if (!record_synch_enabled)  record_synch_count = 0;
4878   record_synch_enabled = true;
4879 }
4880 
4881 void record_synch_disable() {
4882   // stop collecting trace data
4883   record_synch_enabled = false;
4884 }
4885 
4886 #endif // INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS
4887 #endif // PRODUCT
4888 
4889 const intptr_t thr_time_off  = (intptr_t)(&((prusage_t *)(NULL))->pr_utime);
4890 const intptr_t thr_time_size = (intptr_t)(&((prusage_t *)(NULL))->pr_ttime) -
4891                                (intptr_t)(&((prusage_t *)(NULL))->pr_utime);
4892 
4893 
4894 // JVMTI & JVM monitoring and management support
4895 // The thread_cpu_time() and current_thread_cpu_time() are only
4896 // supported if is_thread_cpu_time_supported() returns true.
4897 // They are not supported on Solaris T1.
4898 
4899 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
4900 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
4901 // of a thread.
4902 //
4903 // current_thread_cpu_time() and thread_cpu_time(Thread *)
4904 // returns the fast estimate available on the platform.
4905 
4906 // hrtime_t gethrvtime() return value includes
4907 // user time but does not include system time
4908 jlong os::current_thread_cpu_time() {
4909   return (jlong) gethrvtime();
4910 }
4911 
4912 jlong os::thread_cpu_time(Thread *thread) {
4913   // return user level CPU time only to be consistent with
4914   // what current_thread_cpu_time returns.
4915   // thread_cpu_time_info() must be changed if this changes
4916   return os::thread_cpu_time(thread, false /* user time only */);
4917 }
4918 
4919 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
4920   if (user_sys_cpu_time) {
4921     return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
4922   } else {
4923     return os::current_thread_cpu_time();
4924   }
4925 }
4926 
4927 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
4928   char proc_name[64];
4929   int count;
4930   prusage_t prusage;
4931   jlong lwp_time;
4932   int fd;
4933 
4934   sprintf(proc_name, "/proc/%d/lwp/%d/lwpusage",
4935           getpid(),
4936           thread->osthread()->lwp_id());
4937   fd = ::open(proc_name, O_RDONLY);
4938   if (fd == -1) return -1;
4939 
4940   do {
4941     count = ::pread(fd,
4942                     (void *)&prusage.pr_utime,
4943                     thr_time_size,
4944                     thr_time_off);
4945   } while (count < 0 && errno == EINTR);
4946   ::close(fd);
4947   if (count < 0) return -1;
4948 
4949   if (user_sys_cpu_time) {
4950     // user + system CPU time
4951     lwp_time = (((jlong)prusage.pr_stime.tv_sec +
4952                  (jlong)prusage.pr_utime.tv_sec) * (jlong)1000000000) +
4953                  (jlong)prusage.pr_stime.tv_nsec +
4954                  (jlong)prusage.pr_utime.tv_nsec;
4955   } else {
4956     // user level CPU time only
4957     lwp_time = ((jlong)prusage.pr_utime.tv_sec * (jlong)1000000000) +
4958                 (jlong)prusage.pr_utime.tv_nsec;
4959   }
4960 
4961   return (lwp_time);
4962 }
4963 
4964 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
4965   info_ptr->max_value = ALL_64_BITS;      // will not wrap in less than 64 bits
4966   info_ptr->may_skip_backward = false;    // elapsed time not wall time
4967   info_ptr->may_skip_forward = false;     // elapsed time not wall time
4968   info_ptr->kind = JVMTI_TIMER_USER_CPU;  // only user time is returned
4969 }
4970 
4971 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
4972   info_ptr->max_value = ALL_64_BITS;      // will not wrap in less than 64 bits
4973   info_ptr->may_skip_backward = false;    // elapsed time not wall time
4974   info_ptr->may_skip_forward = false;     // elapsed time not wall time
4975   info_ptr->kind = JVMTI_TIMER_USER_CPU;  // only user time is returned
4976 }
4977 
4978 bool os::is_thread_cpu_time_supported() {
4979   return true;
4980 }
4981 
4982 // System loadavg support.  Returns -1 if load average cannot be obtained.
4983 // Return the load average for our processor set if the primitive exists
4984 // (Solaris 9 and later).  Otherwise just return system wide loadavg.
4985 int os::loadavg(double loadavg[], int nelem) {
4986   if (pset_getloadavg_ptr != NULL) {
4987     return (*pset_getloadavg_ptr)(PS_MYID, loadavg, nelem);
4988   } else {
4989     return ::getloadavg(loadavg, nelem);
4990   }
4991 }
4992 
4993 //---------------------------------------------------------------------------------
4994 
4995 bool os::find(address addr, outputStream* st) {
4996   Dl_info dlinfo;
4997   memset(&dlinfo, 0, sizeof(dlinfo));
4998   if (dladdr(addr, &dlinfo) != 0) {
4999     st->print(PTR_FORMAT ": ", addr);
5000     if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
5001       st->print("%s+%#lx", dlinfo.dli_sname, addr-(intptr_t)dlinfo.dli_saddr);
5002     } else if (dlinfo.dli_fbase != NULL) {
5003       st->print("<offset %#lx>", addr-(intptr_t)dlinfo.dli_fbase);
5004     } else {
5005       st->print("<absolute address>");
5006     }
5007     if (dlinfo.dli_fname != NULL) {
5008       st->print(" in %s", dlinfo.dli_fname);
5009     }
5010     if (dlinfo.dli_fbase != NULL) {
5011       st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
5012     }
5013     st->cr();
5014 
5015     if (Verbose) {
5016       // decode some bytes around the PC
5017       address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
5018       address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
5019       address       lowest = (address) dlinfo.dli_sname;
5020       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
5021       if (begin < lowest)  begin = lowest;
5022       Dl_info dlinfo2;
5023       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
5024           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) {
5025         end = (address) dlinfo2.dli_saddr;
5026       }
5027       Disassembler::decode(begin, end, st);
5028     }
5029     return true;
5030   }
5031   return false;
5032 }
5033 
5034 // Following function has been added to support HotSparc's libjvm.so running
5035 // under Solaris production JDK 1.2.2 / 1.3.0.  These came from
5036 // src/solaris/hpi/native_threads in the EVM codebase.
5037 //
5038 // NOTE: This is no longer needed in the 1.3.1 and 1.4 production release
5039 // libraries and should thus be removed. We will leave it behind for a while
5040 // until we no longer want to able to run on top of 1.3.0 Solaris production
5041 // JDK. See 4341971.
5042 
5043 #define STACK_SLACK 0x800
5044 
5045 extern "C" {
5046   intptr_t sysThreadAvailableStackWithSlack() {
5047     stack_t st;
5048     intptr_t retval, stack_top;
5049     retval = thr_stksegment(&st);
5050     assert(retval == 0, "incorrect return value from thr_stksegment");
5051     assert((address)&st < (address)st.ss_sp, "Invalid stack base returned");
5052     assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned");
5053     stack_top=(intptr_t)st.ss_sp-st.ss_size;
5054     return ((intptr_t)&stack_top - stack_top - STACK_SLACK);
5055   }
5056 }
5057 
5058 // ObjectMonitor park-unpark infrastructure ...
5059 //
5060 // We implement Solaris and Linux PlatformEvents with the
5061 // obvious condvar-mutex-flag triple.
5062 // Another alternative that works quite well is pipes:
5063 // Each PlatformEvent consists of a pipe-pair.
5064 // The thread associated with the PlatformEvent
5065 // calls park(), which reads from the input end of the pipe.
5066 // Unpark() writes into the other end of the pipe.
5067 // The write-side of the pipe must be set NDELAY.
5068 // Unfortunately pipes consume a large # of handles.
5069 // Native solaris lwp_park() and lwp_unpark() work nicely, too.
5070 // Using pipes for the 1st few threads might be workable, however.
5071 //
5072 // park() is permitted to return spuriously.
5073 // Callers of park() should wrap the call to park() in
5074 // an appropriate loop.  A litmus test for the correct
5075 // usage of park is the following: if park() were modified
5076 // to immediately return 0 your code should still work,
5077 // albeit degenerating to a spin loop.
5078 //
5079 // In a sense, park()-unpark() just provides more polite spinning
5080 // and polling with the key difference over naive spinning being
5081 // that a parked thread needs to be explicitly unparked() in order
5082 // to wake up and to poll the underlying condition.
5083 //
5084 // Assumption:
5085 //    Only one parker can exist on an event, which is why we allocate
5086 //    them per-thread. Multiple unparkers can coexist.
5087 //
5088 // _Event transitions in park()
5089 //   -1 => -1 : illegal
5090 //    1 =>  0 : pass - return immediately
5091 //    0 => -1 : block; then set _Event to 0 before returning
5092 //
5093 // _Event transitions in unpark()
5094 //    0 => 1 : just return
5095 //    1 => 1 : just return
5096 //   -1 => either 0 or 1; must signal target thread
5097 //         That is, we can safely transition _Event from -1 to either
5098 //         0 or 1.
5099 //
5100 // _Event serves as a restricted-range semaphore.
5101 //   -1 : thread is blocked, i.e. there is a waiter
5102 //    0 : neutral: thread is running or ready,
5103 //        could have been signaled after a wait started
5104 //    1 : signaled - thread is running or ready
5105 //
5106 // Another possible encoding of _Event would be with
5107 // explicit "PARKED" == 01b and "SIGNALED" == 10b bits.
5108 //
5109 // TODO-FIXME: add DTRACE probes for:
5110 // 1.   Tx parks
5111 // 2.   Ty unparks Tx
5112 // 3.   Tx resumes from park
5113 
5114 
5115 // value determined through experimentation
5116 #define ROUNDINGFIX 11
5117 
5118 // utility to compute the abstime argument to timedwait.
5119 // TODO-FIXME: switch from compute_abstime() to unpackTime().
5120 
5121 static timestruc_t* compute_abstime(timestruc_t* abstime, jlong millis) {
5122   // millis is the relative timeout time
5123   // abstime will be the absolute timeout time
5124   if (millis < 0)  millis = 0;
5125   struct timeval now;
5126   int status = gettimeofday(&now, NULL);
5127   assert(status == 0, "gettimeofday");
5128   jlong seconds = millis / 1000;
5129   jlong max_wait_period;
5130 
5131   if (UseLWPSynchronization) {
5132     // forward port of fix for 4275818 (not sleeping long enough)
5133     // There was a bug in Solaris 6, 7 and pre-patch 5 of 8 where
5134     // _lwp_cond_timedwait() used a round_down algorithm rather
5135     // than a round_up. For millis less than our roundfactor
5136     // it rounded down to 0 which doesn't meet the spec.
5137     // For millis > roundfactor we may return a bit sooner, but
5138     // since we can not accurately identify the patch level and
5139     // this has already been fixed in Solaris 9 and 8 we will
5140     // leave it alone rather than always rounding down.
5141 
5142     if (millis > 0 && millis < ROUNDINGFIX) millis = ROUNDINGFIX;
5143     // It appears that when we go directly through Solaris _lwp_cond_timedwait()
5144     // the acceptable max time threshold is smaller than for libthread on 2.5.1 and 2.6
5145     max_wait_period = 21000000;
5146   } else {
5147     max_wait_period = 50000000;
5148   }
5149   millis %= 1000;
5150   if (seconds > max_wait_period) {      // see man cond_timedwait(3T)
5151     seconds = max_wait_period;
5152   }
5153   abstime->tv_sec = now.tv_sec  + seconds;
5154   long       usec = now.tv_usec + millis * 1000;
5155   if (usec >= 1000000) {
5156     abstime->tv_sec += 1;
5157     usec -= 1000000;
5158   }
5159   abstime->tv_nsec = usec * 1000;
5160   return abstime;
5161 }
5162 
5163 void os::PlatformEvent::park() {           // AKA: down()
5164   // Transitions for _Event:
5165   //   -1 => -1 : illegal
5166   //    1 =>  0 : pass - return immediately
5167   //    0 => -1 : block; then set _Event to 0 before returning
5168 
5169   // Invariant: Only the thread associated with the Event/PlatformEvent
5170   // may call park().
5171   assert(_nParked == 0, "invariant");
5172 
5173   int v;
5174   for (;;) {
5175     v = _Event;
5176     if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
5177   }
5178   guarantee(v >= 0, "invariant");
5179   if (v == 0) {
5180     // Do this the hard way by blocking ...
5181     // See http://monaco.sfbay/detail.jsf?cr=5094058.
5182     // TODO-FIXME: for Solaris SPARC set fprs.FEF=0 prior to parking.
5183     // Only for SPARC >= V8PlusA
5184 #if defined(__sparc) && defined(COMPILER2)
5185     if (ClearFPUAtPark) { _mark_fpu_nosave(); }
5186 #endif
5187     int status = os::Solaris::mutex_lock(_mutex);
5188     assert_status(status == 0, status, "mutex_lock");
5189     guarantee(_nParked == 0, "invariant");
5190     ++_nParked;
5191     while (_Event < 0) {
5192       // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
5193       // Treat this the same as if the wait was interrupted
5194       // With usr/lib/lwp going to kernel, always handle ETIME
5195       status = os::Solaris::cond_wait(_cond, _mutex);
5196       if (status == ETIME) status = EINTR;
5197       assert_status(status == 0 || status == EINTR, status, "cond_wait");
5198     }
5199     --_nParked;
5200     _Event = 0;
5201     status = os::Solaris::mutex_unlock(_mutex);
5202     assert_status(status == 0, status, "mutex_unlock");
5203     // Paranoia to ensure our locked and lock-free paths interact
5204     // correctly with each other.
5205     OrderAccess::fence();
5206   }
5207 }
5208 
5209 int os::PlatformEvent::park(jlong millis) {
5210   // Transitions for _Event:
5211   //   -1 => -1 : illegal
5212   //    1 =>  0 : pass - return immediately
5213   //    0 => -1 : block; then set _Event to 0 before returning
5214 
5215   guarantee(_nParked == 0, "invariant");
5216   int v;
5217   for (;;) {
5218     v = _Event;
5219     if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
5220   }
5221   guarantee(v >= 0, "invariant");
5222   if (v != 0) return OS_OK;
5223 
5224   int ret = OS_TIMEOUT;
5225   timestruc_t abst;
5226   compute_abstime(&abst, millis);
5227 
5228   // See http://monaco.sfbay/detail.jsf?cr=5094058.
5229   // For Solaris SPARC set fprs.FEF=0 prior to parking.
5230   // Only for SPARC >= V8PlusA
5231 #if defined(__sparc) && defined(COMPILER2)
5232   if (ClearFPUAtPark) { _mark_fpu_nosave(); }
5233 #endif
5234   int status = os::Solaris::mutex_lock(_mutex);
5235   assert_status(status == 0, status, "mutex_lock");
5236   guarantee(_nParked == 0, "invariant");
5237   ++_nParked;
5238   while (_Event < 0) {
5239     int status = os::Solaris::cond_timedwait(_cond, _mutex, &abst);
5240     assert_status(status == 0 || status == EINTR ||
5241                   status == ETIME || status == ETIMEDOUT,
5242                   status, "cond_timedwait");
5243     if (!FilterSpuriousWakeups) break;                // previous semantics
5244     if (status == ETIME || status == ETIMEDOUT) break;
5245     // We consume and ignore EINTR and spurious wakeups.
5246   }
5247   --_nParked;
5248   if (_Event >= 0) ret = OS_OK;
5249   _Event = 0;
5250   status = os::Solaris::mutex_unlock(_mutex);
5251   assert_status(status == 0, status, "mutex_unlock");
5252   // Paranoia to ensure our locked and lock-free paths interact
5253   // correctly with each other.
5254   OrderAccess::fence();
5255   return ret;
5256 }
5257 
5258 void os::PlatformEvent::unpark() {
5259   // Transitions for _Event:
5260   //    0 => 1 : just return
5261   //    1 => 1 : just return
5262   //   -1 => either 0 or 1; must signal target thread
5263   //         That is, we can safely transition _Event from -1 to either
5264   //         0 or 1.
5265   // See also: "Semaphores in Plan 9" by Mullender & Cox
5266   //
5267   // Note: Forcing a transition from "-1" to "1" on an unpark() means
5268   // that it will take two back-to-back park() calls for the owning
5269   // thread to block. This has the benefit of forcing a spurious return
5270   // from the first park() call after an unpark() call which will help
5271   // shake out uses of park() and unpark() without condition variables.
5272 
5273   if (Atomic::xchg(1, &_Event) >= 0) return;
5274 
5275   // If the thread associated with the event was parked, wake it.
5276   // Wait for the thread assoc with the PlatformEvent to vacate.
5277   int status = os::Solaris::mutex_lock(_mutex);
5278   assert_status(status == 0, status, "mutex_lock");
5279   int AnyWaiters = _nParked;
5280   status = os::Solaris::mutex_unlock(_mutex);
5281   assert_status(status == 0, status, "mutex_unlock");
5282   guarantee(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
5283   if (AnyWaiters != 0) {
5284     // Note that we signal() *after* dropping the lock for "immortal" Events.
5285     // This is safe and avoids a common class of  futile wakeups.  In rare
5286     // circumstances this can cause a thread to return prematurely from
5287     // cond_{timed}wait() but the spurious wakeup is benign and the victim
5288     // will simply re-test the condition and re-park itself.
5289     // This provides particular benefit if the underlying platform does not
5290     // provide wait morphing.
5291     status = os::Solaris::cond_signal(_cond);
5292     assert_status(status == 0, status, "cond_signal");
5293   }
5294 }
5295 
5296 // JSR166
5297 // -------------------------------------------------------
5298 
5299 // The solaris and linux implementations of park/unpark are fairly
5300 // conservative for now, but can be improved. They currently use a
5301 // mutex/condvar pair, plus _counter.
5302 // Park decrements _counter if > 0, else does a condvar wait.  Unpark
5303 // sets count to 1 and signals condvar.  Only one thread ever waits
5304 // on the condvar. Contention seen when trying to park implies that someone
5305 // is unparking you, so don't wait. And spurious returns are fine, so there
5306 // is no need to track notifications.
5307 
5308 #define MAX_SECS 100000000
5309 
5310 // This code is common to linux and solaris and will be moved to a
5311 // common place in dolphin.
5312 //
5313 // The passed in time value is either a relative time in nanoseconds
5314 // or an absolute time in milliseconds. Either way it has to be unpacked
5315 // into suitable seconds and nanoseconds components and stored in the
5316 // given timespec structure.
5317 // Given time is a 64-bit value and the time_t used in the timespec is only
5318 // a signed-32-bit value (except on 64-bit Linux) we have to watch for
5319 // overflow if times way in the future are given. Further on Solaris versions
5320 // prior to 10 there is a restriction (see cond_timedwait) that the specified
5321 // number of seconds, in abstime, is less than current_time  + 100,000,000.
5322 // As it will be 28 years before "now + 100000000" will overflow we can
5323 // ignore overflow and just impose a hard-limit on seconds using the value
5324 // of "now + 100,000,000". This places a limit on the timeout of about 3.17
5325 // years from "now".
5326 //
5327 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) {
5328   assert(time > 0, "convertTime");
5329 
5330   struct timeval now;
5331   int status = gettimeofday(&now, NULL);
5332   assert(status == 0, "gettimeofday");
5333 
5334   time_t max_secs = now.tv_sec + MAX_SECS;
5335 
5336   if (isAbsolute) {
5337     jlong secs = time / 1000;
5338     if (secs > max_secs) {
5339       absTime->tv_sec = max_secs;
5340     } else {
5341       absTime->tv_sec = secs;
5342     }
5343     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
5344   } else {
5345     jlong secs = time / NANOSECS_PER_SEC;
5346     if (secs >= MAX_SECS) {
5347       absTime->tv_sec = max_secs;
5348       absTime->tv_nsec = 0;
5349     } else {
5350       absTime->tv_sec = now.tv_sec + secs;
5351       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
5352       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
5353         absTime->tv_nsec -= NANOSECS_PER_SEC;
5354         ++absTime->tv_sec; // note: this must be <= max_secs
5355       }
5356     }
5357   }
5358   assert(absTime->tv_sec >= 0, "tv_sec < 0");
5359   assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
5360   assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
5361   assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
5362 }
5363 
5364 void Parker::park(bool isAbsolute, jlong time) {
5365   // Ideally we'd do something useful while spinning, such
5366   // as calling unpackTime().
5367 
5368   // Optional fast-path check:
5369   // Return immediately if a permit is available.
5370   // We depend on Atomic::xchg() having full barrier semantics
5371   // since we are doing a lock-free update to _counter.
5372   if (Atomic::xchg(0, &_counter) > 0) return;
5373 
5374   // Optional fast-exit: Check interrupt before trying to wait
5375   Thread* thread = Thread::current();
5376   assert(thread->is_Java_thread(), "Must be JavaThread");
5377   JavaThread *jt = (JavaThread *)thread;
5378   if (Thread::is_interrupted(thread, false)) {
5379     return;
5380   }
5381 
5382   // First, demultiplex/decode time arguments
5383   timespec absTime;
5384   if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all
5385     return;
5386   }
5387   if (time > 0) {
5388     // Warning: this code might be exposed to the old Solaris time
5389     // round-down bugs.  Grep "roundingFix" for details.
5390     unpackTime(&absTime, isAbsolute, time);
5391   }
5392 
5393   // Enter safepoint region
5394   // Beware of deadlocks such as 6317397.
5395   // The per-thread Parker:: _mutex is a classic leaf-lock.
5396   // In particular a thread must never block on the Threads_lock while
5397   // holding the Parker:: mutex.  If safepoints are pending both the
5398   // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
5399   ThreadBlockInVM tbivm(jt);
5400 
5401   // Don't wait if cannot get lock since interference arises from
5402   // unblocking.  Also. check interrupt before trying wait
5403   if (Thread::is_interrupted(thread, false) ||
5404       os::Solaris::mutex_trylock(_mutex) != 0) {
5405     return;
5406   }
5407 
5408   int status;
5409 
5410   if (_counter > 0)  { // no wait needed
5411     _counter = 0;
5412     status = os::Solaris::mutex_unlock(_mutex);
5413     assert(status == 0, "invariant");
5414     // Paranoia to ensure our locked and lock-free paths interact
5415     // correctly with each other and Java-level accesses.
5416     OrderAccess::fence();
5417     return;
5418   }
5419 
5420 #ifdef ASSERT
5421   // Don't catch signals while blocked; let the running threads have the signals.
5422   // (This allows a debugger to break into the running thread.)
5423   sigset_t oldsigs;
5424   sigset_t* allowdebug_blocked = os::Solaris::allowdebug_blocked_signals();
5425   pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
5426 #endif
5427 
5428   OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
5429   jt->set_suspend_equivalent();
5430   // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
5431 
5432   // Do this the hard way by blocking ...
5433   // See http://monaco.sfbay/detail.jsf?cr=5094058.
5434   // TODO-FIXME: for Solaris SPARC set fprs.FEF=0 prior to parking.
5435   // Only for SPARC >= V8PlusA
5436 #if defined(__sparc) && defined(COMPILER2)
5437   if (ClearFPUAtPark) { _mark_fpu_nosave(); }
5438 #endif
5439 
5440   if (time == 0) {
5441     status = os::Solaris::cond_wait(_cond, _mutex);
5442   } else {
5443     status = os::Solaris::cond_timedwait (_cond, _mutex, &absTime);
5444   }
5445   // Note that an untimed cond_wait() can sometimes return ETIME on older
5446   // versions of the Solaris.
5447   assert_status(status == 0 || status == EINTR ||
5448                 status == ETIME || status == ETIMEDOUT,
5449                 status, "cond_timedwait");
5450 
5451 #ifdef ASSERT
5452   pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
5453 #endif
5454   _counter = 0;
5455   status = os::Solaris::mutex_unlock(_mutex);
5456   assert_status(status == 0, status, "mutex_unlock");
5457   // Paranoia to ensure our locked and lock-free paths interact
5458   // correctly with each other and Java-level accesses.
5459   OrderAccess::fence();
5460 
5461   // If externally suspended while waiting, re-suspend
5462   if (jt->handle_special_suspend_equivalent_condition()) {
5463     jt->java_suspend_self();
5464   }
5465 }
5466 
5467 void Parker::unpark() {
5468   int status = os::Solaris::mutex_lock(_mutex);
5469   assert(status == 0, "invariant");
5470   const int s = _counter;
5471   _counter = 1;
5472   status = os::Solaris::mutex_unlock(_mutex);
5473   assert(status == 0, "invariant");
5474 
5475   if (s < 1) {
5476     status = os::Solaris::cond_signal(_cond);
5477     assert(status == 0, "invariant");
5478   }
5479 }
5480 
5481 extern char** environ;
5482 
5483 // Run the specified command in a separate process. Return its exit value,
5484 // or -1 on failure (e.g. can't fork a new process).
5485 // Unlike system(), this function can be called from signal handler. It
5486 // doesn't block SIGINT et al.
5487 int os::fork_and_exec(char* cmd) {
5488   char * argv[4];
5489   argv[0] = (char *)"sh";
5490   argv[1] = (char *)"-c";
5491   argv[2] = cmd;
5492   argv[3] = NULL;
5493 
5494   // fork is async-safe, fork1 is not so can't use in signal handler
5495   pid_t pid;
5496   Thread* t = Thread::current_or_null_safe();
5497   if (t != NULL && t->is_inside_signal_handler()) {
5498     pid = fork();
5499   } else {
5500     pid = fork1();
5501   }
5502 
5503   if (pid < 0) {
5504     // fork failed
5505     warning("fork failed: %s", os::strerror(errno));
5506     return -1;
5507 
5508   } else if (pid == 0) {
5509     // child process
5510 
5511     // try to be consistent with system(), which uses "/usr/bin/sh" on Solaris
5512     execve("/usr/bin/sh", argv, environ);
5513 
5514     // execve failed
5515     _exit(-1);
5516 
5517   } else  {
5518     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
5519     // care about the actual exit code, for now.
5520 
5521     int status;
5522 
5523     // Wait for the child process to exit.  This returns immediately if
5524     // the child has already exited. */
5525     while (waitpid(pid, &status, 0) < 0) {
5526       switch (errno) {
5527       case ECHILD: return 0;
5528       case EINTR: break;
5529       default: return -1;
5530       }
5531     }
5532 
5533     if (WIFEXITED(status)) {
5534       // The child exited normally; get its exit code.
5535       return WEXITSTATUS(status);
5536     } else if (WIFSIGNALED(status)) {
5537       // The child exited because of a signal
5538       // The best value to return is 0x80 + signal number,
5539       // because that is what all Unix shells do, and because
5540       // it allows callers to distinguish between process exit and
5541       // process death by signal.
5542       return 0x80 + WTERMSIG(status);
5543     } else {
5544       // Unknown exit code; pass it through
5545       return status;
5546     }
5547   }
5548 }
5549 
5550 // is_headless_jre()
5551 //
5552 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
5553 // in order to report if we are running in a headless jre
5554 //
5555 // Since JDK8 xawt/libmawt.so was moved into the same directory
5556 // as libawt.so, and renamed libawt_xawt.so
5557 //
5558 bool os::is_headless_jre() {
5559   struct stat statbuf;
5560   char buf[MAXPATHLEN];
5561   char libmawtpath[MAXPATHLEN];
5562   const char *xawtstr  = "/xawt/libmawt.so";
5563   const char *new_xawtstr = "/libawt_xawt.so";
5564   char *p;
5565 
5566   // Get path to libjvm.so
5567   os::jvm_path(buf, sizeof(buf));
5568 
5569   // Get rid of libjvm.so
5570   p = strrchr(buf, '/');
5571   if (p == NULL) {
5572     return false;
5573   } else {
5574     *p = '\0';
5575   }
5576 
5577   // Get rid of client or server
5578   p = strrchr(buf, '/');
5579   if (p == NULL) {
5580     return false;
5581   } else {
5582     *p = '\0';
5583   }
5584 
5585   // check xawt/libmawt.so
5586   strcpy(libmawtpath, buf);
5587   strcat(libmawtpath, xawtstr);
5588   if (::stat(libmawtpath, &statbuf) == 0) return false;
5589 
5590   // check libawt_xawt.so
5591   strcpy(libmawtpath, buf);
5592   strcat(libmawtpath, new_xawtstr);
5593   if (::stat(libmawtpath, &statbuf) == 0) return false;
5594 
5595   return true;
5596 }
5597 
5598 size_t os::write(int fd, const void *buf, unsigned int nBytes) {
5599   size_t res;
5600   RESTARTABLE((size_t) ::write(fd, buf, (size_t) nBytes), res);
5601   return res;
5602 }
5603 
5604 int os::close(int fd) {
5605   return ::close(fd);
5606 }
5607 
5608 int os::socket_close(int fd) {
5609   return ::close(fd);
5610 }
5611 
5612 int os::recv(int fd, char* buf, size_t nBytes, uint flags) {
5613   assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5614          "Assumed _thread_in_native");
5615   RESTARTABLE_RETURN_INT((int)::recv(fd, buf, nBytes, flags));
5616 }
5617 
5618 int os::send(int fd, char* buf, size_t nBytes, uint flags) {
5619   assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5620          "Assumed _thread_in_native");
5621   RESTARTABLE_RETURN_INT((int)::send(fd, buf, nBytes, flags));
5622 }
5623 
5624 int os::raw_send(int fd, char* buf, size_t nBytes, uint flags) {
5625   RESTARTABLE_RETURN_INT((int)::send(fd, buf, nBytes, flags));
5626 }
5627 
5628 // As both poll and select can be interrupted by signals, we have to be
5629 // prepared to restart the system call after updating the timeout, unless
5630 // a poll() is done with timeout == -1, in which case we repeat with this
5631 // "wait forever" value.
5632 
5633 int os::connect(int fd, struct sockaddr *him, socklen_t len) {
5634   int _result;
5635   _result = ::connect(fd, him, len);
5636 
5637   // On Solaris, when a connect() call is interrupted, the connection
5638   // can be established asynchronously (see 6343810). Subsequent calls
5639   // to connect() must check the errno value which has the semantic
5640   // described below (copied from the connect() man page). Handling
5641   // of asynchronously established connections is required for both
5642   // blocking and non-blocking sockets.
5643   //     EINTR            The  connection  attempt  was   interrupted
5644   //                      before  any data arrived by the delivery of
5645   //                      a signal. The connection, however, will  be
5646   //                      established asynchronously.
5647   //
5648   //     EINPROGRESS      The socket is non-blocking, and the connec-
5649   //                      tion  cannot  be completed immediately.
5650   //
5651   //     EALREADY         The socket is non-blocking,  and a previous
5652   //                      connection  attempt  has  not yet been com-
5653   //                      pleted.
5654   //
5655   //     EISCONN          The socket is already connected.
5656   if (_result == OS_ERR && errno == EINTR) {
5657     // restarting a connect() changes its errno semantics
5658     RESTARTABLE(::connect(fd, him, len), _result);
5659     // undo these changes
5660     if (_result == OS_ERR) {
5661       if (errno == EALREADY) {
5662         errno = EINPROGRESS; // fall through
5663       } else if (errno == EISCONN) {
5664         errno = 0;
5665         return OS_OK;
5666       }
5667     }
5668   }
5669   return _result;
5670 }
5671 
5672 // Get the default path to the core file
5673 // Returns the length of the string
5674 int os::get_core_path(char* buffer, size_t bufferSize) {
5675   const char* p = get_current_directory(buffer, bufferSize);
5676 
5677   if (p == NULL) {
5678     assert(p != NULL, "failed to get current directory");
5679     return 0;
5680   }
5681 
5682   jio_snprintf(buffer, bufferSize, "%s/core or core.%d",
5683                                               p, current_process_id());
5684 
5685   return strlen(buffer);
5686 }
5687 
5688 #ifndef PRODUCT
5689 void TestReserveMemorySpecial_test() {
5690   // No tests available for this platform
5691 }
5692 #endif
5693 
5694 bool os::start_debugging(char *buf, int buflen) {
5695   int len = (int)strlen(buf);
5696   char *p = &buf[len];
5697 
5698   jio_snprintf(p, buflen-len,
5699                "\n\n"
5700                "Do you want to debug the problem?\n\n"
5701                "To debug, run 'dbx - %d'; then switch to thread " INTX_FORMAT "\n"
5702                "Enter 'yes' to launch dbx automatically (PATH must include dbx)\n"
5703                "Otherwise, press RETURN to abort...",
5704                os::current_process_id(), os::current_thread_id());
5705 
5706   bool yes = os::message_box("Unexpected Error", buf);
5707 
5708   if (yes) {
5709     // yes, user asked VM to launch debugger
5710     jio_snprintf(buf, sizeof(buf), "dbx - %d", os::current_process_id());
5711 
5712     os::fork_and_exec(buf);
5713     yes = false;
5714   }
5715   return yes;
5716 }