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