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