src/os/solaris/vm/os_solaris.cpp

Fri, 06 Jul 2018 18:50:13 +0000

author
poonam
date
Fri, 06 Jul 2018 18:50:13 +0000
changeset 9413
5aa3d728164a
parent 8420
b5c3e9670fa0
child 9417
65409bcab2ad
permissions
-rw-r--r--

8146115: Improve docker container detection and resource configuration usage
Reviewed-by: bobv, dbuck

     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  */
    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 "prims/jniFastGetField.hpp"
    41 #include "prims/jvm.h"
    42 #include "prims/jvm_misc.hpp"
    43 #include "runtime/arguments.hpp"
    44 #include "runtime/extendedPC.hpp"
    45 #include "runtime/globals.hpp"
    46 #include "runtime/interfaceSupport.hpp"
    47 #include "runtime/java.hpp"
    48 #include "runtime/javaCalls.hpp"
    49 #include "runtime/mutexLocker.hpp"
    50 #include "runtime/objectMonitor.hpp"
    51 #include "runtime/orderAccess.inline.hpp"
    52 #include "runtime/osThread.hpp"
    53 #include "runtime/perfMemory.hpp"
    54 #include "runtime/sharedRuntime.hpp"
    55 #include "runtime/statSampler.hpp"
    56 #include "runtime/stubRoutines.hpp"
    57 #include "runtime/thread.inline.hpp"
    58 #include "runtime/threadCritical.hpp"
    59 #include "runtime/timer.hpp"
    60 #include "services/attachListener.hpp"
    61 #include "services/memTracker.hpp"
    62 #include "services/runtimeService.hpp"
    63 #include "utilities/decoder.hpp"
    64 #include "utilities/defaultStream.hpp"
    65 #include "utilities/events.hpp"
    66 #include "utilities/growableArray.hpp"
    67 #include "utilities/vmError.hpp"
    69 // put OS-includes here
    70 # include <dlfcn.h>
    71 # include <errno.h>
    72 # include <exception>
    73 # include <link.h>
    74 # include <poll.h>
    75 # include <pthread.h>
    76 # include <pwd.h>
    77 # include <schedctl.h>
    78 # include <setjmp.h>
    79 # include <signal.h>
    80 # include <stdio.h>
    81 # include <alloca.h>
    82 # include <sys/filio.h>
    83 # include <sys/ipc.h>
    84 # include <sys/lwp.h>
    85 # include <sys/machelf.h>     // for elf Sym structure used by dladdr1
    86 # include <sys/mman.h>
    87 # include <sys/processor.h>
    88 # include <sys/procset.h>
    89 # include <sys/pset.h>
    90 # include <sys/resource.h>
    91 # include <sys/shm.h>
    92 # include <sys/socket.h>
    93 # include <sys/stat.h>
    94 # include <sys/systeminfo.h>
    95 # include <sys/time.h>
    96 # include <sys/times.h>
    97 # include <sys/types.h>
    98 # include <sys/wait.h>
    99 # include <sys/utsname.h>
   100 # include <thread.h>
   101 # include <unistd.h>
   102 # include <sys/priocntl.h>
   103 # include <sys/rtpriocntl.h>
   104 # include <sys/tspriocntl.h>
   105 # include <sys/iapriocntl.h>
   106 # include <sys/fxpriocntl.h>
   107 # include <sys/loadavg.h>
   108 # include <string.h>
   109 # include <stdio.h>
   111 # define _STRUCTURED_PROC 1  //  this gets us the new structured proc interfaces of 5.6 & later
   112 # include <sys/procfs.h>     //  see comment in <sys/procfs.h>
   114 #define MAX_PATH (2 * K)
   116 // for timer info max values which include all bits
   117 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
   120 // Here are some liblgrp types from sys/lgrp_user.h to be able to
   121 // compile on older systems without this header file.
   123 #ifndef MADV_ACCESS_LWP
   124 # define  MADV_ACCESS_LWP         7       /* next LWP to access heavily */
   125 #endif
   126 #ifndef MADV_ACCESS_MANY
   127 # define  MADV_ACCESS_MANY        8       /* many processes to access heavily */
   128 #endif
   130 #ifndef LGRP_RSRC_CPU
   131 # define LGRP_RSRC_CPU           0       /* CPU resources */
   132 #endif
   133 #ifndef LGRP_RSRC_MEM
   134 # define LGRP_RSRC_MEM           1       /* memory resources */
   135 #endif
   137 // see thr_setprio(3T) for the basis of these numbers
   138 #define MinimumPriority 0
   139 #define NormalPriority  64
   140 #define MaximumPriority 127
   142 // Values for ThreadPriorityPolicy == 1
   143 int prio_policy1[CriticalPriority+1] = {
   144   -99999,  0, 16,  32,  48,  64,
   145           80, 96, 112, 124, 127, 127 };
   147 // System parameters used internally
   148 static clock_t clock_tics_per_sec = 100;
   150 // Track if we have called enable_extended_FILE_stdio (on Solaris 10u4+)
   151 static bool enabled_extended_FILE_stdio = false;
   153 // For diagnostics to print a message once. see run_periodic_checks
   154 static bool check_addr0_done = false;
   155 static sigset_t check_signal_done;
   156 static bool check_signals = true;
   158 address os::Solaris::handler_start;  // start pc of thr_sighndlrinfo
   159 address os::Solaris::handler_end;    // end pc of thr_sighndlrinfo
   161 address os::Solaris::_main_stack_base = NULL;  // 4352906 workaround
   164 // "default" initializers for missing libc APIs
   165 extern "C" {
   166   static int lwp_mutex_init(mutex_t *mx, int scope, void *arg) { memset(mx, 0, sizeof(mutex_t)); return 0; }
   167   static int lwp_mutex_destroy(mutex_t *mx)                 { return 0; }
   169   static int lwp_cond_init(cond_t *cv, int scope, void *arg){ memset(cv, 0, sizeof(cond_t)); return 0; }
   170   static int lwp_cond_destroy(cond_t *cv)                   { return 0; }
   171 }
   173 // "default" initializers for pthread-based synchronization
   174 extern "C" {
   175   static int pthread_mutex_default_init(mutex_t *mx, int scope, void *arg) { memset(mx, 0, sizeof(mutex_t)); return 0; }
   176   static int pthread_cond_default_init(cond_t *cv, int scope, void *arg){ memset(cv, 0, sizeof(cond_t)); return 0; }
   177 }
   179 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time);
   181 static inline size_t adjust_stack_size(address base, size_t size) {
   182   if ((ssize_t)size < 0) {
   183     // 4759953: Compensate for ridiculous stack size.
   184     size = max_intx;
   185   }
   186   if (size > (size_t)base) {
   187     // 4812466: Make sure size doesn't allow the stack to wrap the address space.
   188     size = (size_t)base;
   189   }
   190   return size;
   191 }
   193 static inline stack_t get_stack_info() {
   194   stack_t st;
   195   int retval = thr_stksegment(&st);
   196   st.ss_size = adjust_stack_size((address)st.ss_sp, st.ss_size);
   197   assert(retval == 0, "incorrect return value from thr_stksegment");
   198   assert((address)&st < (address)st.ss_sp, "Invalid stack base returned");
   199   assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned");
   200   return st;
   201 }
   203 address os::current_stack_base() {
   204   int r = thr_main() ;
   205   guarantee (r == 0 || r == 1, "CR6501650 or CR6493689") ;
   206   bool is_primordial_thread = r;
   208   // Workaround 4352906, avoid calls to thr_stksegment by
   209   // thr_main after the first one (it looks like we trash
   210   // some data, causing the value for ss_sp to be incorrect).
   211   if (!is_primordial_thread || os::Solaris::_main_stack_base == NULL) {
   212     stack_t st = get_stack_info();
   213     if (is_primordial_thread) {
   214       // cache initial value of stack base
   215       os::Solaris::_main_stack_base = (address)st.ss_sp;
   216     }
   217     return (address)st.ss_sp;
   218   } else {
   219     guarantee(os::Solaris::_main_stack_base != NULL, "Attempt to use null cached stack base");
   220     return os::Solaris::_main_stack_base;
   221   }
   222 }
   224 size_t os::current_stack_size() {
   225   size_t size;
   227   int r = thr_main() ;
   228   guarantee (r == 0 || r == 1, "CR6501650 or CR6493689") ;
   229   if(!r) {
   230     size = get_stack_info().ss_size;
   231   } else {
   232     struct rlimit limits;
   233     getrlimit(RLIMIT_STACK, &limits);
   234     size = adjust_stack_size(os::Solaris::_main_stack_base, (size_t)limits.rlim_cur);
   235   }
   236   // base may not be page aligned
   237   address base = current_stack_base();
   238   address bottom = (address)align_size_up((intptr_t)(base - size), os::vm_page_size());;
   239   return (size_t)(base - bottom);
   240 }
   242 struct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
   243   return localtime_r(clock, res);
   244 }
   246 // interruptible infrastructure
   248 // setup_interruptible saves the thread state before going into an
   249 // interruptible system call.
   250 // The saved state is used to restore the thread to
   251 // its former state whether or not an interrupt is received.
   252 // Used by classloader os::read
   253 // os::restartable_read calls skip this layer and stay in _thread_in_native
   255 void os::Solaris::setup_interruptible(JavaThread* thread) {
   257   JavaThreadState thread_state = thread->thread_state();
   259   assert(thread_state != _thread_blocked, "Coming from the wrong thread");
   260   assert(thread_state != _thread_in_native, "Native threads skip setup_interruptible");
   261   OSThread* osthread = thread->osthread();
   262   osthread->set_saved_interrupt_thread_state(thread_state);
   263   thread->frame_anchor()->make_walkable(thread);
   264   ThreadStateTransition::transition(thread, thread_state, _thread_blocked);
   265 }
   267 // Version of setup_interruptible() for threads that are already in
   268 // _thread_blocked. Used by os_sleep().
   269 void os::Solaris::setup_interruptible_already_blocked(JavaThread* thread) {
   270   thread->frame_anchor()->make_walkable(thread);
   271 }
   273 JavaThread* os::Solaris::setup_interruptible() {
   274   JavaThread* thread = (JavaThread*)ThreadLocalStorage::thread();
   275   setup_interruptible(thread);
   276   return thread;
   277 }
   279 void os::Solaris::try_enable_extended_io() {
   280   typedef int (*enable_extended_FILE_stdio_t)(int, int);
   282   if (!UseExtendedFileIO) {
   283     return;
   284   }
   286   enable_extended_FILE_stdio_t enabler =
   287     (enable_extended_FILE_stdio_t) dlsym(RTLD_DEFAULT,
   288                                          "enable_extended_FILE_stdio");
   289   if (enabler) {
   290     enabler(-1, -1);
   291   }
   292 }
   295 #ifdef ASSERT
   297 JavaThread* os::Solaris::setup_interruptible_native() {
   298   JavaThread* thread = (JavaThread*)ThreadLocalStorage::thread();
   299   JavaThreadState thread_state = thread->thread_state();
   300   assert(thread_state == _thread_in_native, "Assumed thread_in_native");
   301   return thread;
   302 }
   304 void os::Solaris::cleanup_interruptible_native(JavaThread* thread) {
   305   JavaThreadState thread_state = thread->thread_state();
   306   assert(thread_state == _thread_in_native, "Assumed thread_in_native");
   307 }
   308 #endif
   310 // cleanup_interruptible reverses the effects of setup_interruptible
   311 // setup_interruptible_already_blocked() does not need any cleanup.
   313 void os::Solaris::cleanup_interruptible(JavaThread* thread) {
   314   OSThread* osthread = thread->osthread();
   316   ThreadStateTransition::transition(thread, _thread_blocked, osthread->saved_interrupt_thread_state());
   317 }
   319 // I/O interruption related counters called in _INTERRUPTIBLE
   321 void os::Solaris::bump_interrupted_before_count() {
   322   RuntimeService::record_interrupted_before_count();
   323 }
   325 void os::Solaris::bump_interrupted_during_count() {
   326   RuntimeService::record_interrupted_during_count();
   327 }
   329 static int _processors_online = 0;
   331          jint os::Solaris::_os_thread_limit = 0;
   332 volatile jint os::Solaris::_os_thread_count = 0;
   334 julong os::available_memory() {
   335   return Solaris::available_memory();
   336 }
   338 julong os::Solaris::available_memory() {
   339   return (julong)sysconf(_SC_AVPHYS_PAGES) * os::vm_page_size();
   340 }
   342 julong os::Solaris::_physical_memory = 0;
   344 julong os::physical_memory() {
   345    return Solaris::physical_memory();
   346 }
   348 static hrtime_t first_hrtime = 0;
   349 static const hrtime_t hrtime_hz = 1000*1000*1000;
   350 static volatile hrtime_t max_hrtime = 0;
   353 void os::Solaris::initialize_system_info() {
   354   set_processor_count(sysconf(_SC_NPROCESSORS_CONF));
   355   _processors_online = sysconf (_SC_NPROCESSORS_ONLN);
   356   _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE);
   357 }
   359 int os::active_processor_count() {
   360   // User has overridden the number of active processors
   361   if (ActiveProcessorCount > 0) {
   362     if (Verbose) {
   363       tty->print_cr("active_processor_count: "
   364                     "active processor count set by user : %d",
   365                      ActiveProcessorCount);
   366     }
   367     return ActiveProcessorCount;
   368   }
   370   int online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
   371   pid_t pid = getpid();
   372   psetid_t pset = PS_NONE;
   373   // Are we running in a processor set or is there any processor set around?
   374   if (pset_bind(PS_QUERY, P_PID, pid, &pset) == 0) {
   375     uint_t pset_cpus;
   376     // Query the number of cpus available to us.
   377     if (pset_info(pset, NULL, &pset_cpus, NULL) == 0) {
   378       assert(pset_cpus > 0 && pset_cpus <= online_cpus, "sanity check");
   379       _processors_online = pset_cpus;
   380       return pset_cpus;
   381     }
   382   }
   383   // Otherwise return number of online cpus
   384   return online_cpus;
   385 }
   387 static bool find_processors_in_pset(psetid_t        pset,
   388                                     processorid_t** id_array,
   389                                     uint_t*         id_length) {
   390   bool result = false;
   391   // Find the number of processors in the processor set.
   392   if (pset_info(pset, NULL, id_length, NULL) == 0) {
   393     // Make up an array to hold their ids.
   394     *id_array = NEW_C_HEAP_ARRAY(processorid_t, *id_length, mtInternal);
   395     // Fill in the array with their processor ids.
   396     if (pset_info(pset, NULL, id_length, *id_array) == 0) {
   397       result = true;
   398     }
   399   }
   400   return result;
   401 }
   403 // Callers of find_processors_online() must tolerate imprecise results --
   404 // the system configuration can change asynchronously because of DR
   405 // or explicit psradm operations.
   406 //
   407 // We also need to take care that the loop (below) terminates as the
   408 // number of processors online can change between the _SC_NPROCESSORS_ONLN
   409 // request and the loop that builds the list of processor ids.   Unfortunately
   410 // there's no reliable way to determine the maximum valid processor id,
   411 // so we use a manifest constant, MAX_PROCESSOR_ID, instead.  See p_online
   412 // man pages, which claim the processor id set is "sparse, but
   413 // not too sparse".  MAX_PROCESSOR_ID is used to ensure that we eventually
   414 // exit the loop.
   415 //
   416 // In the future we'll be able to use sysconf(_SC_CPUID_MAX), but that's
   417 // not available on S8.0.
   419 static bool find_processors_online(processorid_t** id_array,
   420                                    uint*           id_length) {
   421   const processorid_t MAX_PROCESSOR_ID = 100000 ;
   422   // Find the number of processors online.
   423   *id_length = sysconf(_SC_NPROCESSORS_ONLN);
   424   // Make up an array to hold their ids.
   425   *id_array = NEW_C_HEAP_ARRAY(processorid_t, *id_length, mtInternal);
   426   // Processors need not be numbered consecutively.
   427   long found = 0;
   428   processorid_t next = 0;
   429   while (found < *id_length && next < MAX_PROCESSOR_ID) {
   430     processor_info_t info;
   431     if (processor_info(next, &info) == 0) {
   432       // NB, PI_NOINTR processors are effectively online ...
   433       if (info.pi_state == P_ONLINE || info.pi_state == P_NOINTR) {
   434         (*id_array)[found] = next;
   435         found += 1;
   436       }
   437     }
   438     next += 1;
   439   }
   440   if (found < *id_length) {
   441       // The loop above didn't identify the expected number of processors.
   442       // We could always retry the operation, calling sysconf(_SC_NPROCESSORS_ONLN)
   443       // and re-running the loop, above, but there's no guarantee of progress
   444       // if the system configuration is in flux.  Instead, we just return what
   445       // we've got.  Note that in the worst case find_processors_online() could
   446       // return an empty set.  (As a fall-back in the case of the empty set we
   447       // could just return the ID of the current processor).
   448       *id_length = found ;
   449   }
   451   return true;
   452 }
   454 static bool assign_distribution(processorid_t* id_array,
   455                                 uint           id_length,
   456                                 uint*          distribution,
   457                                 uint           distribution_length) {
   458   // We assume we can assign processorid_t's to uint's.
   459   assert(sizeof(processorid_t) == sizeof(uint),
   460          "can't convert processorid_t to uint");
   461   // Quick check to see if we won't succeed.
   462   if (id_length < distribution_length) {
   463     return false;
   464   }
   465   // Assign processor ids to the distribution.
   466   // Try to shuffle processors to distribute work across boards,
   467   // assuming 4 processors per board.
   468   const uint processors_per_board = ProcessDistributionStride;
   469   // Find the maximum processor id.
   470   processorid_t max_id = 0;
   471   for (uint m = 0; m < id_length; m += 1) {
   472     max_id = MAX2(max_id, id_array[m]);
   473   }
   474   // The next id, to limit loops.
   475   const processorid_t limit_id = max_id + 1;
   476   // Make up markers for available processors.
   477   bool* available_id = NEW_C_HEAP_ARRAY(bool, limit_id, mtInternal);
   478   for (uint c = 0; c < limit_id; c += 1) {
   479     available_id[c] = false;
   480   }
   481   for (uint a = 0; a < id_length; a += 1) {
   482     available_id[id_array[a]] = true;
   483   }
   484   // Step by "boards", then by "slot", copying to "assigned".
   485   // NEEDS_CLEANUP: The assignment of processors should be stateful,
   486   //                remembering which processors have been assigned by
   487   //                previous calls, etc., so as to distribute several
   488   //                independent calls of this method.  What we'd like is
   489   //                It would be nice to have an API that let us ask
   490   //                how many processes are bound to a processor,
   491   //                but we don't have that, either.
   492   //                In the short term, "board" is static so that
   493   //                subsequent distributions don't all start at board 0.
   494   static uint board = 0;
   495   uint assigned = 0;
   496   // Until we've found enough processors ....
   497   while (assigned < distribution_length) {
   498     // ... find the next available processor in the board.
   499     for (uint slot = 0; slot < processors_per_board; slot += 1) {
   500       uint try_id = board * processors_per_board + slot;
   501       if ((try_id < limit_id) && (available_id[try_id] == true)) {
   502         distribution[assigned] = try_id;
   503         available_id[try_id] = false;
   504         assigned += 1;
   505         break;
   506       }
   507     }
   508     board += 1;
   509     if (board * processors_per_board + 0 >= limit_id) {
   510       board = 0;
   511     }
   512   }
   513   if (available_id != NULL) {
   514     FREE_C_HEAP_ARRAY(bool, available_id, mtInternal);
   515   }
   516   return true;
   517 }
   519 void os::set_native_thread_name(const char *name) {
   520   // Not yet implemented.
   521   return;
   522 }
   524 bool os::distribute_processes(uint length, uint* distribution) {
   525   bool result = false;
   526   // Find the processor id's of all the available CPUs.
   527   processorid_t* id_array  = NULL;
   528   uint           id_length = 0;
   529   // There are some races between querying information and using it,
   530   // since processor sets can change dynamically.
   531   psetid_t pset = PS_NONE;
   532   // Are we running in a processor set?
   533   if ((pset_bind(PS_QUERY, P_PID, P_MYID, &pset) == 0) && pset != PS_NONE) {
   534     result = find_processors_in_pset(pset, &id_array, &id_length);
   535   } else {
   536     result = find_processors_online(&id_array, &id_length);
   537   }
   538   if (result == true) {
   539     if (id_length >= length) {
   540       result = assign_distribution(id_array, id_length, distribution, length);
   541     } else {
   542       result = false;
   543     }
   544   }
   545   if (id_array != NULL) {
   546     FREE_C_HEAP_ARRAY(processorid_t, id_array, mtInternal);
   547   }
   548   return result;
   549 }
   551 bool os::bind_to_processor(uint processor_id) {
   552   // We assume that a processorid_t can be stored in a uint.
   553   assert(sizeof(uint) == sizeof(processorid_t),
   554          "can't convert uint to processorid_t");
   555   int bind_result =
   556     processor_bind(P_LWPID,                       // bind LWP.
   557                    P_MYID,                        // bind current LWP.
   558                    (processorid_t) processor_id,  // id.
   559                    NULL);                         // don't return old binding.
   560   return (bind_result == 0);
   561 }
   563 bool os::getenv(const char* name, char* buffer, int len) {
   564   char* val = ::getenv( name );
   565   if ( val == NULL
   566   ||   strlen(val) + 1  >  len ) {
   567     if (len > 0)  buffer[0] = 0; // return a null string
   568     return false;
   569   }
   570   strcpy( buffer, val );
   571   return true;
   572 }
   575 // Return true if user is running as root.
   577 bool os::have_special_privileges() {
   578   static bool init = false;
   579   static bool privileges = false;
   580   if (!init) {
   581     privileges = (getuid() != geteuid()) || (getgid() != getegid());
   582     init = true;
   583   }
   584   return privileges;
   585 }
   588 void os::init_system_properties_values() {
   589   // The next steps are taken in the product version:
   590   //
   591   // Obtain the JAVA_HOME value from the location of libjvm.so.
   592   // This library should be located at:
   593   // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
   594   //
   595   // If "/jre/lib/" appears at the right place in the path, then we
   596   // assume libjvm.so is installed in a JDK and we use this path.
   597   //
   598   // Otherwise exit with message: "Could not create the Java virtual machine."
   599   //
   600   // The following extra steps are taken in the debugging version:
   601   //
   602   // If "/jre/lib/" does NOT appear at the right place in the path
   603   // instead of exit check for $JAVA_HOME environment variable.
   604   //
   605   // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
   606   // then we append a fake suffix "hotspot/libjvm.so" to this path so
   607   // it looks like libjvm.so is installed there
   608   // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
   609   //
   610   // Otherwise exit.
   611   //
   612   // Important note: if the location of libjvm.so changes this
   613   // code needs to be changed accordingly.
   615 // Base path of extensions installed on the system.
   616 #define SYS_EXT_DIR     "/usr/jdk/packages"
   617 #define EXTENSIONS_DIR  "/lib/ext"
   618 #define ENDORSED_DIR    "/lib/endorsed"
   620   char cpu_arch[12];
   621   // Buffer that fits several sprintfs.
   622   // Note that the space for the colon and the trailing null are provided
   623   // by the nulls included by the sizeof operator.
   624   const size_t bufsize =
   625     MAX4((size_t)MAXPATHLEN,  // For dll_dir & friends.
   626          sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch), // invariant ld_library_path
   627          (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR), // extensions dir
   628          (size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir
   629   char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
   631   // sysclasspath, java_home, dll_dir
   632   {
   633     char *pslash;
   634     os::jvm_path(buf, bufsize);
   636     // Found the full path to libjvm.so.
   637     // Now cut the path to <java_home>/jre if we can.
   638     *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.
   639     pslash = strrchr(buf, '/');
   640     if (pslash != NULL) {
   641       *pslash = '\0';            // Get rid of /{client|server|hotspot}.
   642     }
   643     Arguments::set_dll_dir(buf);
   645     if (pslash != NULL) {
   646       pslash = strrchr(buf, '/');
   647       if (pslash != NULL) {
   648         *pslash = '\0';          // Get rid of /<arch>.
   649         pslash = strrchr(buf, '/');
   650         if (pslash != NULL) {
   651           *pslash = '\0';        // Get rid of /lib.
   652         }
   653       }
   654     }
   655     Arguments::set_java_home(buf);
   656     set_boot_path('/', ':');
   657   }
   659   // Where to look for native libraries.
   660   {
   661     // Use dlinfo() to determine the correct java.library.path.
   662     //
   663     // If we're launched by the Java launcher, and the user
   664     // does not set java.library.path explicitly on the commandline,
   665     // the Java launcher sets LD_LIBRARY_PATH for us and unsets
   666     // LD_LIBRARY_PATH_32 and LD_LIBRARY_PATH_64.  In this case
   667     // dlinfo returns LD_LIBRARY_PATH + crle settings (including
   668     // /usr/lib), which is exactly what we want.
   669     //
   670     // If the user does set java.library.path, it completely
   671     // overwrites this setting, and always has.
   672     //
   673     // If we're not launched by the Java launcher, we may
   674     // get here with any/all of the LD_LIBRARY_PATH[_32|64]
   675     // settings.  Again, dlinfo does exactly what we want.
   677     Dl_serinfo     info_sz, *info = &info_sz;
   678     Dl_serpath     *path;
   679     char           *library_path;
   680     char           *common_path = buf;
   682     // Determine search path count and required buffer size.
   683     if (dlinfo(RTLD_SELF, RTLD_DI_SERINFOSIZE, (void *)info) == -1) {
   684       FREE_C_HEAP_ARRAY(char, buf,  mtInternal);
   685       vm_exit_during_initialization("dlinfo SERINFOSIZE request", dlerror());
   686     }
   688     // Allocate new buffer and initialize.
   689     info = (Dl_serinfo*)NEW_C_HEAP_ARRAY(char, info_sz.dls_size, mtInternal);
   690     info->dls_size = info_sz.dls_size;
   691     info->dls_cnt = info_sz.dls_cnt;
   693     // Obtain search path information.
   694     if (dlinfo(RTLD_SELF, RTLD_DI_SERINFO, (void *)info) == -1) {
   695       FREE_C_HEAP_ARRAY(char, buf,  mtInternal);
   696       FREE_C_HEAP_ARRAY(char, info, mtInternal);
   697       vm_exit_during_initialization("dlinfo SERINFO request", dlerror());
   698     }
   700     path = &info->dls_serpath[0];
   702     // Note: Due to a legacy implementation, most of the library path
   703     // is set in the launcher. This was to accomodate linking restrictions
   704     // on legacy Solaris implementations (which are no longer supported).
   705     // Eventually, all the library path setting will be done here.
   706     //
   707     // However, to prevent the proliferation of improperly built native
   708     // libraries, the new path component /usr/jdk/packages is added here.
   710     // Determine the actual CPU architecture.
   711     sysinfo(SI_ARCHITECTURE, cpu_arch, sizeof(cpu_arch));
   712 #ifdef _LP64
   713     // If we are a 64-bit vm, perform the following translations:
   714     //   sparc   -> sparcv9
   715     //   i386    -> amd64
   716     if (strcmp(cpu_arch, "sparc") == 0) {
   717       strcat(cpu_arch, "v9");
   718     } else if (strcmp(cpu_arch, "i386") == 0) {
   719       strcpy(cpu_arch, "amd64");
   720     }
   721 #endif
   723     // Construct the invariant part of ld_library_path.
   724     sprintf(common_path, SYS_EXT_DIR "/lib/%s", cpu_arch);
   726     // Struct size is more than sufficient for the path components obtained
   727     // through the dlinfo() call, so only add additional space for the path
   728     // components explicitly added here.
   729     size_t library_path_size = info->dls_size + strlen(common_path);
   730     library_path = (char *)NEW_C_HEAP_ARRAY(char, library_path_size, mtInternal);
   731     library_path[0] = '\0';
   733     // Construct the desired Java library path from the linker's library
   734     // search path.
   735     //
   736     // For compatibility, it is optimal that we insert the additional path
   737     // components specific to the Java VM after those components specified
   738     // in LD_LIBRARY_PATH (if any) but before those added by the ld.so
   739     // infrastructure.
   740     if (info->dls_cnt == 0) { // Not sure this can happen, but allow for it.
   741       strcpy(library_path, common_path);
   742     } else {
   743       int inserted = 0;
   744       int i;
   745       for (i = 0; i < info->dls_cnt; i++, path++) {
   746         uint_t flags = path->dls_flags & LA_SER_MASK;
   747         if (((flags & LA_SER_LIBPATH) == 0) && !inserted) {
   748           strcat(library_path, common_path);
   749           strcat(library_path, os::path_separator());
   750           inserted = 1;
   751         }
   752         strcat(library_path, path->dls_name);
   753         strcat(library_path, os::path_separator());
   754       }
   755       // Eliminate trailing path separator.
   756       library_path[strlen(library_path)-1] = '\0';
   757     }
   759     // happens before argument parsing - can't use a trace flag
   760     // tty->print_raw("init_system_properties_values: native lib path: ");
   761     // tty->print_raw_cr(library_path);
   763     // Callee copies into its own buffer.
   764     Arguments::set_library_path(library_path);
   766     FREE_C_HEAP_ARRAY(char, library_path, mtInternal);
   767     FREE_C_HEAP_ARRAY(char, info, mtInternal);
   768   }
   770   // Extensions directories.
   771   sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());
   772   Arguments::set_ext_dirs(buf);
   774   // Endorsed standards default directory.
   775   sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
   776   Arguments::set_endorsed_dirs(buf);
   778   FREE_C_HEAP_ARRAY(char, buf, mtInternal);
   780 #undef SYS_EXT_DIR
   781 #undef EXTENSIONS_DIR
   782 #undef ENDORSED_DIR
   783 }
   785 void os::breakpoint() {
   786   BREAKPOINT;
   787 }
   789 bool os::obsolete_option(const JavaVMOption *option)
   790 {
   791   if (!strncmp(option->optionString, "-Xt", 3)) {
   792     return true;
   793   } else if (!strncmp(option->optionString, "-Xtm", 4)) {
   794     return true;
   795   } else if (!strncmp(option->optionString, "-Xverifyheap", 12)) {
   796     return true;
   797   } else if (!strncmp(option->optionString, "-Xmaxjitcodesize", 16)) {
   798     return true;
   799   }
   800   return false;
   801 }
   803 bool os::Solaris::valid_stack_address(Thread* thread, address sp) {
   804   address  stackStart  = (address)thread->stack_base();
   805   address  stackEnd    = (address)(stackStart - (address)thread->stack_size());
   806   if (sp < stackStart && sp >= stackEnd ) return true;
   807   return false;
   808 }
   810 extern "C" void breakpoint() {
   811   // use debugger to set breakpoint here
   812 }
   814 static thread_t main_thread;
   816 // Thread start routine for all new Java threads
   817 extern "C" void* java_start(void* thread_addr) {
   818   // Try to randomize the cache line index of hot stack frames.
   819   // This helps when threads of the same stack traces evict each other's
   820   // cache lines. The threads can be either from the same JVM instance, or
   821   // from different JVM instances. The benefit is especially true for
   822   // processors with hyperthreading technology.
   823   static int counter = 0;
   824   int pid = os::current_process_id();
   825   alloca(((pid ^ counter++) & 7) * 128);
   827   int prio;
   828   Thread* thread = (Thread*)thread_addr;
   829   OSThread* osthr = thread->osthread();
   831   osthr->set_lwp_id( _lwp_self() );  // Store lwp in case we are bound
   832   thread->_schedctl = (void *) schedctl_init () ;
   834   if (UseNUMA) {
   835     int lgrp_id = os::numa_get_group_id();
   836     if (lgrp_id != -1) {
   837       thread->set_lgrp_id(lgrp_id);
   838     }
   839   }
   841   // If the creator called set priority before we started,
   842   // we need to call set_native_priority now that we have an lwp.
   843   // We used to get the priority from thr_getprio (we called
   844   // thr_setprio way back in create_thread) and pass it to
   845   // set_native_priority, but Solaris scales the priority
   846   // in java_to_os_priority, so when we read it back here,
   847   // we pass trash to set_native_priority instead of what's
   848   // in java_to_os_priority. So we save the native priority
   849   // in the osThread and recall it here.
   851   if ( osthr->thread_id() != -1 ) {
   852     if ( UseThreadPriorities ) {
   853       int prio = osthr->native_priority();
   854       if (ThreadPriorityVerbose) {
   855         tty->print_cr("Starting Thread " INTPTR_FORMAT ", LWP is "
   856                       INTPTR_FORMAT ", setting priority: %d\n",
   857                       osthr->thread_id(), osthr->lwp_id(), prio);
   858       }
   859       os::set_native_priority(thread, prio);
   860     }
   861   } else if (ThreadPriorityVerbose) {
   862     warning("Can't set priority in _start routine, thread id hasn't been set\n");
   863   }
   865   assert(osthr->get_state() == RUNNABLE, "invalid os thread state");
   867   // initialize signal mask for this thread
   868   os::Solaris::hotspot_sigmask(thread);
   870   thread->run();
   872   // One less thread is executing
   873   // When the VMThread gets here, the main thread may have already exited
   874   // which frees the CodeHeap containing the Atomic::dec code
   875   if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) {
   876     Atomic::dec(&os::Solaris::_os_thread_count);
   877   }
   879   if (UseDetachedThreads) {
   880     thr_exit(NULL);
   881     ShouldNotReachHere();
   882   }
   883   return NULL;
   884 }
   886 static OSThread* create_os_thread(Thread* thread, thread_t thread_id) {
   887   // Allocate the OSThread object
   888   OSThread* osthread = new OSThread(NULL, NULL);
   889   if (osthread == NULL) return NULL;
   891   // Store info on the Solaris thread into the OSThread
   892   osthread->set_thread_id(thread_id);
   893   osthread->set_lwp_id(_lwp_self());
   894   thread->_schedctl = (void *) schedctl_init () ;
   896   if (UseNUMA) {
   897     int lgrp_id = os::numa_get_group_id();
   898     if (lgrp_id != -1) {
   899       thread->set_lgrp_id(lgrp_id);
   900     }
   901   }
   903   if ( ThreadPriorityVerbose ) {
   904     tty->print_cr("In create_os_thread, Thread " INTPTR_FORMAT ", LWP is " INTPTR_FORMAT "\n",
   905                   osthread->thread_id(), osthread->lwp_id() );
   906   }
   908   // Initial thread state is INITIALIZED, not SUSPENDED
   909   osthread->set_state(INITIALIZED);
   911   return osthread;
   912 }
   914 void os::Solaris::hotspot_sigmask(Thread* thread) {
   916   //Save caller's signal mask
   917   sigset_t sigmask;
   918   thr_sigsetmask(SIG_SETMASK, NULL, &sigmask);
   919   OSThread *osthread = thread->osthread();
   920   osthread->set_caller_sigmask(sigmask);
   922   thr_sigsetmask(SIG_UNBLOCK, os::Solaris::unblocked_signals(), NULL);
   923   if (!ReduceSignalUsage) {
   924     if (thread->is_VM_thread()) {
   925       // Only the VM thread handles BREAK_SIGNAL ...
   926       thr_sigsetmask(SIG_UNBLOCK, vm_signals(), NULL);
   927     } else {
   928       // ... all other threads block BREAK_SIGNAL
   929       assert(!sigismember(vm_signals(), SIGINT), "SIGINT should not be blocked");
   930       thr_sigsetmask(SIG_BLOCK, vm_signals(), NULL);
   931     }
   932   }
   933 }
   935 bool os::create_attached_thread(JavaThread* thread) {
   936 #ifdef ASSERT
   937   thread->verify_not_published();
   938 #endif
   939   OSThread* osthread = create_os_thread(thread, thr_self());
   940   if (osthread == NULL) {
   941      return false;
   942   }
   944   // Initial thread state is RUNNABLE
   945   osthread->set_state(RUNNABLE);
   946   thread->set_osthread(osthread);
   948   // initialize signal mask for this thread
   949   // and save the caller's signal mask
   950   os::Solaris::hotspot_sigmask(thread);
   952   return true;
   953 }
   955 bool os::create_main_thread(JavaThread* thread) {
   956 #ifdef ASSERT
   957   thread->verify_not_published();
   958 #endif
   959   if (_starting_thread == NULL) {
   960     _starting_thread = create_os_thread(thread, main_thread);
   961      if (_starting_thread == NULL) {
   962         return false;
   963      }
   964   }
   966   // The primodial thread is runnable from the start
   967   _starting_thread->set_state(RUNNABLE);
   969   thread->set_osthread(_starting_thread);
   971   // initialize signal mask for this thread
   972   // and save the caller's signal mask
   973   os::Solaris::hotspot_sigmask(thread);
   975   return true;
   976 }
   978 // _T2_libthread is true if we believe we are running with the newer
   979 // SunSoft lwp/libthread.so (2.8 patch, 2.9 default)
   980 bool os::Solaris::_T2_libthread = false;
   982 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
   983   // Allocate the OSThread object
   984   OSThread* osthread = new OSThread(NULL, NULL);
   985   if (osthread == NULL) {
   986     return false;
   987   }
   989   if ( ThreadPriorityVerbose ) {
   990     char *thrtyp;
   991     switch ( thr_type ) {
   992       case vm_thread:
   993         thrtyp = (char *)"vm";
   994         break;
   995       case cgc_thread:
   996         thrtyp = (char *)"cgc";
   997         break;
   998       case pgc_thread:
   999         thrtyp = (char *)"pgc";
  1000         break;
  1001       case java_thread:
  1002         thrtyp = (char *)"java";
  1003         break;
  1004       case compiler_thread:
  1005         thrtyp = (char *)"compiler";
  1006         break;
  1007       case watcher_thread:
  1008         thrtyp = (char *)"watcher";
  1009         break;
  1010       default:
  1011         thrtyp = (char *)"unknown";
  1012         break;
  1014     tty->print_cr("In create_thread, creating a %s thread\n", thrtyp);
  1017   // Calculate stack size if it's not specified by caller.
  1018   if (stack_size == 0) {
  1019     // The default stack size 1M (2M for LP64).
  1020     stack_size = (BytesPerWord >> 2) * K * K;
  1022     switch (thr_type) {
  1023     case os::java_thread:
  1024       // Java threads use ThreadStackSize which default value can be changed with the flag -Xss
  1025       if (JavaThread::stack_size_at_create() > 0) stack_size = JavaThread::stack_size_at_create();
  1026       break;
  1027     case os::compiler_thread:
  1028       if (CompilerThreadStackSize > 0) {
  1029         stack_size = (size_t)(CompilerThreadStackSize * K);
  1030         break;
  1031       } // else fall through:
  1032         // use VMThreadStackSize if CompilerThreadStackSize is not defined
  1033     case os::vm_thread:
  1034     case os::pgc_thread:
  1035     case os::cgc_thread:
  1036     case os::watcher_thread:
  1037       if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
  1038       break;
  1041   stack_size = MAX2(stack_size, os::Solaris::min_stack_allowed);
  1043   // Initial state is ALLOCATED but not INITIALIZED
  1044   osthread->set_state(ALLOCATED);
  1046   if (os::Solaris::_os_thread_count > os::Solaris::_os_thread_limit) {
  1047     // We got lots of threads. Check if we still have some address space left.
  1048     // Need to be at least 5Mb of unreserved address space. We do check by
  1049     // trying to reserve some.
  1050     const size_t VirtualMemoryBangSize = 20*K*K;
  1051     char* mem = os::reserve_memory(VirtualMemoryBangSize);
  1052     if (mem == NULL) {
  1053       delete osthread;
  1054       return false;
  1055     } else {
  1056       // Release the memory again
  1057       os::release_memory(mem, VirtualMemoryBangSize);
  1061   // Setup osthread because the child thread may need it.
  1062   thread->set_osthread(osthread);
  1064   // Create the Solaris thread
  1065   // explicit THR_BOUND for T2_libthread case in case
  1066   // that assumption is not accurate, but our alternate signal stack
  1067   // handling is based on it which must have bound threads
  1068   thread_t tid = 0;
  1069   long     flags = (UseDetachedThreads ? THR_DETACHED : 0) | THR_SUSPENDED
  1070                    | ((UseBoundThreads || os::Solaris::T2_libthread() ||
  1071                        (thr_type == vm_thread) ||
  1072                        (thr_type == cgc_thread) ||
  1073                        (thr_type == pgc_thread) ||
  1074                        (thr_type == compiler_thread && BackgroundCompilation)) ?
  1075                       THR_BOUND : 0);
  1076   int      status;
  1078   // 4376845 -- libthread/kernel don't provide enough LWPs to utilize all CPUs.
  1079   //
  1080   // On multiprocessors systems, libthread sometimes under-provisions our
  1081   // process with LWPs.  On a 30-way systems, for instance, we could have
  1082   // 50 user-level threads in ready state and only 2 or 3 LWPs assigned
  1083   // to our process.  This can result in under utilization of PEs.
  1084   // I suspect the problem is related to libthread's LWP
  1085   // pool management and to the kernel's SIGBLOCKING "last LWP parked"
  1086   // upcall policy.
  1087   //
  1088   // The following code is palliative -- it attempts to ensure that our
  1089   // process has sufficient LWPs to take advantage of multiple PEs.
  1090   // Proper long-term cures include using user-level threads bound to LWPs
  1091   // (THR_BOUND) or using LWP-based synchronization.  Note that there is a
  1092   // slight timing window with respect to sampling _os_thread_count, but
  1093   // the race is benign.  Also, we should periodically recompute
  1094   // _processors_online as the min of SC_NPROCESSORS_ONLN and the
  1095   // the number of PEs in our partition.  You might be tempted to use
  1096   // THR_NEW_LWP here, but I'd recommend against it as that could
  1097   // result in undesirable growth of the libthread's LWP pool.
  1098   // The fix below isn't sufficient; for instance, it doesn't take into count
  1099   // LWPs parked on IO.  It does, however, help certain CPU-bound benchmarks.
  1100   //
  1101   // Some pathologies this scheme doesn't handle:
  1102   // *  Threads can block, releasing the LWPs.  The LWPs can age out.
  1103   //    When a large number of threads become ready again there aren't
  1104   //    enough LWPs available to service them.  This can occur when the
  1105   //    number of ready threads oscillates.
  1106   // *  LWPs/Threads park on IO, thus taking the LWP out of circulation.
  1107   //
  1108   // Finally, we should call thr_setconcurrency() periodically to refresh
  1109   // the LWP pool and thwart the LWP age-out mechanism.
  1110   // The "+3" term provides a little slop -- we want to slightly overprovision.
  1112   if (AdjustConcurrency && os::Solaris::_os_thread_count < (_processors_online+3)) {
  1113     if (!(flags & THR_BOUND)) {
  1114       thr_setconcurrency (os::Solaris::_os_thread_count);       // avoid starvation
  1117   // Although this doesn't hurt, we should warn of undefined behavior
  1118   // when using unbound T1 threads with schedctl().  This should never
  1119   // happen, as the compiler and VM threads are always created bound
  1120   DEBUG_ONLY(
  1121       if ((VMThreadHintNoPreempt || CompilerThreadHintNoPreempt) &&
  1122           (!os::Solaris::T2_libthread() && (!(flags & THR_BOUND))) &&
  1123           ((thr_type == vm_thread) || (thr_type == cgc_thread) ||
  1124            (thr_type == pgc_thread) || (thr_type == compiler_thread && BackgroundCompilation))) {
  1125          warning("schedctl behavior undefined when Compiler/VM/GC Threads are Unbound");
  1127   );
  1130   // Mark that we don't have an lwp or thread id yet.
  1131   // In case we attempt to set the priority before the thread starts.
  1132   osthread->set_lwp_id(-1);
  1133   osthread->set_thread_id(-1);
  1135   status = thr_create(NULL, stack_size, java_start, thread, flags, &tid);
  1136   if (status != 0) {
  1137     if (PrintMiscellaneous && (Verbose || WizardMode)) {
  1138       perror("os::create_thread");
  1140     thread->set_osthread(NULL);
  1141     // Need to clean up stuff we've allocated so far
  1142     delete osthread;
  1143     return false;
  1146   Atomic::inc(&os::Solaris::_os_thread_count);
  1148   // Store info on the Solaris thread into the OSThread
  1149   osthread->set_thread_id(tid);
  1151   // Remember that we created this thread so we can set priority on it
  1152   osthread->set_vm_created();
  1154   // Set the default thread priority.  If using bound threads, setting
  1155   // lwp priority will be delayed until thread start.
  1156   set_native_priority(thread,
  1157                       DefaultThreadPriority == -1 ?
  1158                         java_to_os_priority[NormPriority] :
  1159                         DefaultThreadPriority);
  1161   // Initial thread state is INITIALIZED, not SUSPENDED
  1162   osthread->set_state(INITIALIZED);
  1164   // The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain
  1165   return true;
  1168 /* defined for >= Solaris 10. This allows builds on earlier versions
  1169  *  of Solaris to take advantage of the newly reserved Solaris JVM signals
  1170  *  With SIGJVM1, SIGJVM2, INTERRUPT_SIGNAL is SIGJVM1, ASYNC_SIGNAL is SIGJVM2
  1171  *  and -XX:+UseAltSigs does nothing since these should have no conflict
  1172  */
  1173 #if !defined(SIGJVM1)
  1174 #define SIGJVM1 39
  1175 #define SIGJVM2 40
  1176 #endif
  1178 debug_only(static bool signal_sets_initialized = false);
  1179 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
  1180 int os::Solaris::_SIGinterrupt = INTERRUPT_SIGNAL;
  1181 int os::Solaris::_SIGasync = ASYNC_SIGNAL;
  1183 bool os::Solaris::is_sig_ignored(int sig) {
  1184       struct sigaction oact;
  1185       sigaction(sig, (struct sigaction*)NULL, &oact);
  1186       void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oact.sa_sigaction)
  1187                                      : CAST_FROM_FN_PTR(void*,  oact.sa_handler);
  1188       if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))
  1189            return true;
  1190       else
  1191            return false;
  1194 // Note: SIGRTMIN is a macro that calls sysconf() so it will
  1195 // dynamically detect SIGRTMIN value for the system at runtime, not buildtime
  1196 static bool isJVM1available() {
  1197   return SIGJVM1 < SIGRTMIN;
  1200 void os::Solaris::signal_sets_init() {
  1201   // Should also have an assertion stating we are still single-threaded.
  1202   assert(!signal_sets_initialized, "Already initialized");
  1203   // Fill in signals that are necessarily unblocked for all threads in
  1204   // the VM. Currently, we unblock the following signals:
  1205   // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
  1206   //                         by -Xrs (=ReduceSignalUsage));
  1207   // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
  1208   // other threads. The "ReduceSignalUsage" boolean tells us not to alter
  1209   // the dispositions or masks wrt these signals.
  1210   // Programs embedding the VM that want to use the above signals for their
  1211   // own purposes must, at this time, use the "-Xrs" option to prevent
  1212   // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
  1213   // (See bug 4345157, and other related bugs).
  1214   // In reality, though, unblocking these signals is really a nop, since
  1215   // these signals are not blocked by default.
  1216   sigemptyset(&unblocked_sigs);
  1217   sigemptyset(&allowdebug_blocked_sigs);
  1218   sigaddset(&unblocked_sigs, SIGILL);
  1219   sigaddset(&unblocked_sigs, SIGSEGV);
  1220   sigaddset(&unblocked_sigs, SIGBUS);
  1221   sigaddset(&unblocked_sigs, SIGFPE);
  1223   if (isJVM1available) {
  1224     os::Solaris::set_SIGinterrupt(SIGJVM1);
  1225     os::Solaris::set_SIGasync(SIGJVM2);
  1226   } else if (UseAltSigs) {
  1227     os::Solaris::set_SIGinterrupt(ALT_INTERRUPT_SIGNAL);
  1228     os::Solaris::set_SIGasync(ALT_ASYNC_SIGNAL);
  1229   } else {
  1230     os::Solaris::set_SIGinterrupt(INTERRUPT_SIGNAL);
  1231     os::Solaris::set_SIGasync(ASYNC_SIGNAL);
  1234   sigaddset(&unblocked_sigs, os::Solaris::SIGinterrupt());
  1235   sigaddset(&unblocked_sigs, os::Solaris::SIGasync());
  1237   if (!ReduceSignalUsage) {
  1238    if (!os::Solaris::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
  1239       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
  1240       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
  1242    if (!os::Solaris::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
  1243       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
  1244       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
  1246    if (!os::Solaris::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
  1247       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
  1248       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
  1251   // Fill in signals that are blocked by all but the VM thread.
  1252   sigemptyset(&vm_sigs);
  1253   if (!ReduceSignalUsage)
  1254     sigaddset(&vm_sigs, BREAK_SIGNAL);
  1255   debug_only(signal_sets_initialized = true);
  1257   // For diagnostics only used in run_periodic_checks
  1258   sigemptyset(&check_signal_done);
  1261 // These are signals that are unblocked while a thread is running Java.
  1262 // (For some reason, they get blocked by default.)
  1263 sigset_t* os::Solaris::unblocked_signals() {
  1264   assert(signal_sets_initialized, "Not initialized");
  1265   return &unblocked_sigs;
  1268 // These are the signals that are blocked while a (non-VM) thread is
  1269 // running Java. Only the VM thread handles these signals.
  1270 sigset_t* os::Solaris::vm_signals() {
  1271   assert(signal_sets_initialized, "Not initialized");
  1272   return &vm_sigs;
  1275 // These are signals that are blocked during cond_wait to allow debugger in
  1276 sigset_t* os::Solaris::allowdebug_blocked_signals() {
  1277   assert(signal_sets_initialized, "Not initialized");
  1278   return &allowdebug_blocked_sigs;
  1282 void _handle_uncaught_cxx_exception() {
  1283   VMError err("An uncaught C++ exception");
  1284   err.report_and_die();
  1288 // First crack at OS-specific initialization, from inside the new thread.
  1289 void os::initialize_thread(Thread* thr) {
  1290   int r = thr_main() ;
  1291   guarantee (r == 0 || r == 1, "CR6501650 or CR6493689") ;
  1292   if (r) {
  1293     JavaThread* jt = (JavaThread *)thr;
  1294     assert(jt != NULL,"Sanity check");
  1295     size_t stack_size;
  1296     address base = jt->stack_base();
  1297     if (Arguments::created_by_java_launcher()) {
  1298       // Use 2MB to allow for Solaris 7 64 bit mode.
  1299       stack_size = JavaThread::stack_size_at_create() == 0
  1300         ? 2048*K : JavaThread::stack_size_at_create();
  1302       // There are rare cases when we may have already used more than
  1303       // the basic stack size allotment before this method is invoked.
  1304       // Attempt to allow for a normally sized java_stack.
  1305       size_t current_stack_offset = (size_t)(base - (address)&stack_size);
  1306       stack_size += ReservedSpace::page_align_size_down(current_stack_offset);
  1307     } else {
  1308       // 6269555: If we were not created by a Java launcher, i.e. if we are
  1309       // running embedded in a native application, treat the primordial thread
  1310       // as much like a native attached thread as possible.  This means using
  1311       // the current stack size from thr_stksegment(), unless it is too large
  1312       // to reliably setup guard pages.  A reasonable max size is 8MB.
  1313       size_t current_size = current_stack_size();
  1314       // This should never happen, but just in case....
  1315       if (current_size == 0) current_size = 2 * K * K;
  1316       stack_size = current_size > (8 * K * K) ? (8 * K * K) : current_size;
  1318     address bottom = (address)align_size_up((intptr_t)(base - stack_size), os::vm_page_size());;
  1319     stack_size = (size_t)(base - bottom);
  1321     assert(stack_size > 0, "Stack size calculation problem");
  1323     if (stack_size > jt->stack_size()) {
  1324       NOT_PRODUCT(
  1325         struct rlimit limits;
  1326         getrlimit(RLIMIT_STACK, &limits);
  1327         size_t size = adjust_stack_size(base, (size_t)limits.rlim_cur);
  1328         assert(size >= jt->stack_size(), "Stack size problem in main thread");
  1330       tty->print_cr(
  1331         "Stack size of %d Kb exceeds current limit of %d Kb.\n"
  1332         "(Stack sizes are rounded up to a multiple of the system page size.)\n"
  1333         "See limit(1) to increase the stack size limit.",
  1334         stack_size / K, jt->stack_size() / K);
  1335       vm_exit(1);
  1337     assert(jt->stack_size() >= stack_size,
  1338           "Attempt to map more stack than was allocated");
  1339     jt->set_stack_size(stack_size);
  1342    // 5/22/01: Right now alternate signal stacks do not handle
  1343    // throwing stack overflow exceptions, see bug 4463178
  1344    // Until a fix is found for this, T2 will NOT imply alternate signal
  1345    // stacks.
  1346    // If using T2 libthread threads, install an alternate signal stack.
  1347    // Because alternate stacks associate with LWPs on Solaris,
  1348    // see sigaltstack(2), if using UNBOUND threads, or if UseBoundThreads
  1349    // we prefer to explicitly stack bang.
  1350    // If not using T2 libthread, but using UseBoundThreads any threads
  1351    // (primordial thread, jni_attachCurrentThread) we do not create,
  1352    // probably are not bound, therefore they can not have an alternate
  1353    // signal stack. Since our stack banging code is generated and
  1354    // is shared across threads, all threads must be bound to allow
  1355    // using alternate signal stacks.  The alternative is to interpose
  1356    // on _lwp_create to associate an alt sig stack with each LWP,
  1357    // and this could be a problem when the JVM is embedded.
  1358    // We would prefer to use alternate signal stacks with T2
  1359    // Since there is currently no accurate way to detect T2
  1360    // we do not. Assuming T2 when running T1 causes sig 11s or assertions
  1361    // on installing alternate signal stacks
  1364    // 05/09/03: removed alternate signal stack support for Solaris
  1365    // The alternate signal stack mechanism is no longer needed to
  1366    // handle stack overflow. This is now handled by allocating
  1367    // guard pages (red zone) and stackbanging.
  1368    // Initially the alternate signal stack mechanism was removed because
  1369    // it did not work with T1 llibthread. Alternate
  1370    // signal stacks MUST have all threads bound to lwps. Applications
  1371    // can create their own threads and attach them without their being
  1372    // bound under T1. This is frequently the case for the primordial thread.
  1373    // If we were ever to reenable this mechanism we would need to
  1374    // use the dynamic check for T2 libthread.
  1376   os::Solaris::init_thread_fpu_state();
  1377   std::set_terminate(_handle_uncaught_cxx_exception);
  1382 // Free Solaris resources related to the OSThread
  1383 void os::free_thread(OSThread* osthread) {
  1384   assert(osthread != NULL, "os::free_thread but osthread not set");
  1387   // We are told to free resources of the argument thread,
  1388   // but we can only really operate on the current thread.
  1389   // The main thread must take the VMThread down synchronously
  1390   // before the main thread exits and frees up CodeHeap
  1391   guarantee((Thread::current()->osthread() == osthread
  1392      || (osthread == VMThread::vm_thread()->osthread())), "os::free_thread but not current thread");
  1393   if (Thread::current()->osthread() == osthread) {
  1394     // Restore caller's signal mask
  1395     sigset_t sigmask = osthread->caller_sigmask();
  1396     thr_sigsetmask(SIG_SETMASK, &sigmask, NULL);
  1398   delete osthread;
  1401 void os::pd_start_thread(Thread* thread) {
  1402   int status = thr_continue(thread->osthread()->thread_id());
  1403   assert_status(status == 0, status, "thr_continue failed");
  1407 intx os::current_thread_id() {
  1408   return (intx)thr_self();
  1411 static pid_t _initial_pid = 0;
  1413 int os::current_process_id() {
  1414   return (int)(_initial_pid ? _initial_pid : getpid());
  1417 // gethrtime() should be monotonic according to the documentation,
  1418 // but some virtualized platforms are known to break this guarantee.
  1419 // getTimeNanos() must be guaranteed not to move backwards, so we
  1420 // are forced to add a check here.
  1421 inline hrtime_t getTimeNanos() {
  1422   const hrtime_t now = gethrtime();
  1423   const hrtime_t prev = max_hrtime;
  1424   if (now <= prev) {
  1425     return prev;   // same or retrograde time;
  1427   const hrtime_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&max_hrtime, prev);
  1428   assert(obsv >= prev, "invariant");   // Monotonicity
  1429   // If the CAS succeeded then we're done and return "now".
  1430   // If the CAS failed and the observed value "obsv" is >= now then
  1431   // we should return "obsv".  If the CAS failed and now > obsv > prv then
  1432   // some other thread raced this thread and installed a new value, in which case
  1433   // we could either (a) retry the entire operation, (b) retry trying to install now
  1434   // or (c) just return obsv.  We use (c).   No loop is required although in some cases
  1435   // we might discard a higher "now" value in deference to a slightly lower but freshly
  1436   // installed obsv value.   That's entirely benign -- it admits no new orderings compared
  1437   // to (a) or (b) -- and greatly reduces coherence traffic.
  1438   // We might also condition (c) on the magnitude of the delta between obsv and now.
  1439   // Avoiding excessive CAS operations to hot RW locations is critical.
  1440   // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate
  1441   return (prev == obsv) ? now : obsv;
  1444 // Time since start-up in seconds to a fine granularity.
  1445 // Used by VMSelfDestructTimer and the MemProfiler.
  1446 double os::elapsedTime() {
  1447   return (double)(getTimeNanos() - first_hrtime) / (double)hrtime_hz;
  1450 jlong os::elapsed_counter() {
  1451   return (jlong)(getTimeNanos() - first_hrtime);
  1454 jlong os::elapsed_frequency() {
  1455    return hrtime_hz;
  1458 // Return the real, user, and system times in seconds from an
  1459 // arbitrary fixed point in the past.
  1460 bool os::getTimesSecs(double* process_real_time,
  1461                   double* process_user_time,
  1462                   double* process_system_time) {
  1463   struct tms ticks;
  1464   clock_t real_ticks = times(&ticks);
  1466   if (real_ticks == (clock_t) (-1)) {
  1467     return false;
  1468   } else {
  1469     double ticks_per_second = (double) clock_tics_per_sec;
  1470     *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
  1471     *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
  1472     // For consistency return the real time from getTimeNanos()
  1473     // converted to seconds.
  1474     *process_real_time = ((double) getTimeNanos()) / ((double) NANOUNITS);
  1476     return true;
  1480 bool os::supports_vtime() { return true; }
  1482 bool os::enable_vtime() {
  1483   int fd = ::open("/proc/self/ctl", O_WRONLY);
  1484   if (fd == -1)
  1485     return false;
  1487   long cmd[] = { PCSET, PR_MSACCT };
  1488   int res = ::write(fd, cmd, sizeof(long) * 2);
  1489   ::close(fd);
  1490   if (res != sizeof(long) * 2)
  1491     return false;
  1493   return true;
  1496 bool os::vtime_enabled() {
  1497   int fd = ::open("/proc/self/status", O_RDONLY);
  1498   if (fd == -1)
  1499     return false;
  1501   pstatus_t status;
  1502   int res = os::read(fd, (void*) &status, sizeof(pstatus_t));
  1503   ::close(fd);
  1504   if (res != sizeof(pstatus_t))
  1505     return false;
  1507   return status.pr_flags & PR_MSACCT;
  1510 double os::elapsedVTime() {
  1511   return (double)gethrvtime() / (double)hrtime_hz;
  1514 // Used internally for comparisons only
  1515 // getTimeMillis guaranteed to not move backwards on Solaris
  1516 jlong getTimeMillis() {
  1517   jlong nanotime = getTimeNanos();
  1518   return (jlong)(nanotime / NANOSECS_PER_MILLISEC);
  1521 // Must return millis since Jan 1 1970 for JVM_CurrentTimeMillis
  1522 jlong os::javaTimeMillis() {
  1523   timeval t;
  1524   if (gettimeofday( &t, NULL) == -1)
  1525     fatal(err_msg("os::javaTimeMillis: gettimeofday (%s)", strerror(errno)));
  1526   return jlong(t.tv_sec) * 1000  +  jlong(t.tv_usec) / 1000;
  1529 jlong os::javaTimeNanos() {
  1530   return (jlong)getTimeNanos();
  1533 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
  1534   info_ptr->max_value = ALL_64_BITS;      // gethrtime() uses all 64 bits
  1535   info_ptr->may_skip_backward = false;    // not subject to resetting or drifting
  1536   info_ptr->may_skip_forward = false;     // not subject to resetting or drifting
  1537   info_ptr->kind = JVMTI_TIMER_ELAPSED;   // elapsed not CPU time
  1540 char * os::local_time_string(char *buf, size_t buflen) {
  1541   struct tm t;
  1542   time_t long_time;
  1543   time(&long_time);
  1544   localtime_r(&long_time, &t);
  1545   jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
  1546                t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
  1547                t.tm_hour, t.tm_min, t.tm_sec);
  1548   return buf;
  1551 // Note: os::shutdown() might be called very early during initialization, or
  1552 // called from signal handler. Before adding something to os::shutdown(), make
  1553 // sure it is async-safe and can handle partially initialized VM.
  1554 void os::shutdown() {
  1556   // allow PerfMemory to attempt cleanup of any persistent resources
  1557   perfMemory_exit();
  1559   // needs to remove object in file system
  1560   AttachListener::abort();
  1562   // flush buffered output, finish log files
  1563   ostream_abort();
  1565   // Check for abort hook
  1566   abort_hook_t abort_hook = Arguments::abort_hook();
  1567   if (abort_hook != NULL) {
  1568     abort_hook();
  1572 // Note: os::abort() might be called very early during initialization, or
  1573 // called from signal handler. Before adding something to os::abort(), make
  1574 // sure it is async-safe and can handle partially initialized VM.
  1575 void os::abort(bool dump_core) {
  1576   os::shutdown();
  1577   if (dump_core) {
  1578 #ifndef PRODUCT
  1579     fdStream out(defaultStream::output_fd());
  1580     out.print_raw("Current thread is ");
  1581     char buf[16];
  1582     jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
  1583     out.print_raw_cr(buf);
  1584     out.print_raw_cr("Dumping core ...");
  1585 #endif
  1586     ::abort(); // dump core (for debugging)
  1589   ::exit(1);
  1592 // Die immediately, no exit hook, no abort hook, no cleanup.
  1593 void os::die() {
  1594   ::abort(); // dump core (for debugging)
  1597 // DLL functions
  1599 const char* os::dll_file_extension() { return ".so"; }
  1601 // This must be hard coded because it's the system's temporary
  1602 // directory not the java application's temp directory, ala java.io.tmpdir.
  1603 const char* os::get_temp_directory() { return "/tmp"; }
  1605 static bool file_exists(const char* filename) {
  1606   struct stat statbuf;
  1607   if (filename == NULL || strlen(filename) == 0) {
  1608     return false;
  1610   return os::stat(filename, &statbuf) == 0;
  1613 bool os::dll_build_name(char* buffer, size_t buflen,
  1614                         const char* pname, const char* fname) {
  1615   bool retval = false;
  1616   const size_t pnamelen = pname ? strlen(pname) : 0;
  1618   // Return error on buffer overflow.
  1619   if (pnamelen + strlen(fname) + 10 > (size_t) buflen) {
  1620     return retval;
  1623   if (pnamelen == 0) {
  1624     snprintf(buffer, buflen, "lib%s.so", fname);
  1625     retval = true;
  1626   } else if (strchr(pname, *os::path_separator()) != NULL) {
  1627     int n;
  1628     char** pelements = split_path(pname, &n);
  1629     if (pelements == NULL) {
  1630       return false;
  1632     for (int i = 0 ; i < n ; i++) {
  1633       // really shouldn't be NULL but what the heck, check can't hurt
  1634       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
  1635         continue; // skip the empty path values
  1637       snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname);
  1638       if (file_exists(buffer)) {
  1639         retval = true;
  1640         break;
  1643     // release the storage
  1644     for (int i = 0 ; i < n ; i++) {
  1645       if (pelements[i] != NULL) {
  1646         FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);
  1649     if (pelements != NULL) {
  1650       FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
  1652   } else {
  1653     snprintf(buffer, buflen, "%s/lib%s.so", pname, fname);
  1654     retval = true;
  1656   return retval;
  1659 // check if addr is inside libjvm.so
  1660 bool os::address_is_in_vm(address addr) {
  1661   static address libjvm_base_addr;
  1662   Dl_info dlinfo;
  1664   if (libjvm_base_addr == NULL) {
  1665     if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
  1666       libjvm_base_addr = (address)dlinfo.dli_fbase;
  1668     assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
  1671   if (dladdr((void *)addr, &dlinfo) != 0) {
  1672     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
  1675   return false;
  1678 typedef int (*dladdr1_func_type) (void *, Dl_info *, void **, int);
  1679 static dladdr1_func_type dladdr1_func = NULL;
  1681 bool os::dll_address_to_function_name(address addr, char *buf,
  1682                                       int buflen, int * offset) {
  1683   // buf is not optional, but offset is optional
  1684   assert(buf != NULL, "sanity check");
  1686   Dl_info dlinfo;
  1688   // dladdr1_func was initialized in os::init()
  1689   if (dladdr1_func != NULL) {
  1690     // yes, we have dladdr1
  1692     // Support for dladdr1 is checked at runtime; it may be
  1693     // available even if the vm is built on a machine that does
  1694     // not have dladdr1 support.  Make sure there is a value for
  1695     // RTLD_DL_SYMENT.
  1696     #ifndef RTLD_DL_SYMENT
  1697     #define RTLD_DL_SYMENT 1
  1698     #endif
  1699 #ifdef _LP64
  1700     Elf64_Sym * info;
  1701 #else
  1702     Elf32_Sym * info;
  1703 #endif
  1704     if (dladdr1_func((void *)addr, &dlinfo, (void **)&info,
  1705                      RTLD_DL_SYMENT) != 0) {
  1706       // see if we have a matching symbol that covers our address
  1707       if (dlinfo.dli_saddr != NULL &&
  1708           (char *)dlinfo.dli_saddr + info->st_size > (char *)addr) {
  1709         if (dlinfo.dli_sname != NULL) {
  1710           if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
  1711             jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
  1713           if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
  1714           return true;
  1717       // no matching symbol so try for just file info
  1718       if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
  1719         if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
  1720                             buf, buflen, offset, dlinfo.dli_fname)) {
  1721           return true;
  1725     buf[0] = '\0';
  1726     if (offset != NULL) *offset  = -1;
  1727     return false;
  1730   // no, only dladdr is available
  1731   if (dladdr((void *)addr, &dlinfo) != 0) {
  1732     // see if we have a matching symbol
  1733     if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
  1734       if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
  1735         jio_snprintf(buf, buflen, dlinfo.dli_sname);
  1737       if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
  1738       return true;
  1740     // no matching symbol so try for just file info
  1741     if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
  1742       if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
  1743                           buf, buflen, offset, dlinfo.dli_fname)) {
  1744         return true;
  1748   buf[0] = '\0';
  1749   if (offset != NULL) *offset  = -1;
  1750   return false;
  1753 bool os::dll_address_to_library_name(address addr, char* buf,
  1754                                      int buflen, int* offset) {
  1755   // buf is not optional, but offset is optional
  1756   assert(buf != NULL, "sanity check");
  1758   Dl_info dlinfo;
  1760   if (dladdr((void*)addr, &dlinfo) != 0) {
  1761     if (dlinfo.dli_fname != NULL) {
  1762       jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
  1764     if (dlinfo.dli_fbase != NULL && offset != NULL) {
  1765       *offset = addr - (address)dlinfo.dli_fbase;
  1767     return true;
  1770   buf[0] = '\0';
  1771   if (offset) *offset = -1;
  1772   return false;
  1775 // Prints the names and full paths of all opened dynamic libraries
  1776 // for current process
  1777 void os::print_dll_info(outputStream * st) {
  1778   Dl_info dli;
  1779   void *handle;
  1780   Link_map *map;
  1781   Link_map *p;
  1783   st->print_cr("Dynamic libraries:"); st->flush();
  1785   if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||
  1786       dli.dli_fname == NULL) {
  1787     st->print_cr("Error: Cannot print dynamic libraries.");
  1788     return;
  1790   handle = dlopen(dli.dli_fname, RTLD_LAZY);
  1791   if (handle == NULL) {
  1792     st->print_cr("Error: Cannot print dynamic libraries.");
  1793     return;
  1795   dlinfo(handle, RTLD_DI_LINKMAP, &map);
  1796   if (map == NULL) {
  1797     st->print_cr("Error: Cannot print dynamic libraries.");
  1798     return;
  1801   while (map->l_prev != NULL)
  1802     map = map->l_prev;
  1804   while (map != NULL) {
  1805     st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name);
  1806     map = map->l_next;
  1809   dlclose(handle);
  1812   // Loads .dll/.so and
  1813   // in case of error it checks if .dll/.so was built for the
  1814   // same architecture as Hotspot is running on
  1816 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
  1818   void * result= ::dlopen(filename, RTLD_LAZY);
  1819   if (result != NULL) {
  1820     // Successful loading
  1821     return result;
  1824   Elf32_Ehdr elf_head;
  1826   // Read system error message into ebuf
  1827   // It may or may not be overwritten below
  1828   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
  1829   ebuf[ebuflen-1]='\0';
  1830   int diag_msg_max_length=ebuflen-strlen(ebuf);
  1831   char* diag_msg_buf=ebuf+strlen(ebuf);
  1833   if (diag_msg_max_length==0) {
  1834     // No more space in ebuf for additional diagnostics message
  1835     return NULL;
  1839   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
  1841   if (file_descriptor < 0) {
  1842     // Can't open library, report dlerror() message
  1843     return NULL;
  1846   bool failed_to_read_elf_head=
  1847     (sizeof(elf_head)!=
  1848         (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;
  1850   ::close(file_descriptor);
  1851   if (failed_to_read_elf_head) {
  1852     // file i/o error - report dlerror() msg
  1853     return NULL;
  1856   typedef struct {
  1857     Elf32_Half  code;         // Actual value as defined in elf.h
  1858     Elf32_Half  compat_class; // Compatibility of archs at VM's sense
  1859     char        elf_class;    // 32 or 64 bit
  1860     char        endianess;    // MSB or LSB
  1861     char*       name;         // String representation
  1862   } arch_t;
  1864   static const arch_t arch_array[]={
  1865     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1866     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
  1867     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
  1868     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
  1869     {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
  1870     {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
  1871     {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
  1872     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
  1873     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
  1874     {EM_ARM,         EM_ARM,     ELFCLASS32, ELFDATA2LSB, (char*)"ARM 32"}
  1875   };
  1877   #if  (defined IA32)
  1878     static  Elf32_Half running_arch_code=EM_386;
  1879   #elif   (defined AMD64)
  1880     static  Elf32_Half running_arch_code=EM_X86_64;
  1881   #elif  (defined IA64)
  1882     static  Elf32_Half running_arch_code=EM_IA_64;
  1883   #elif  (defined __sparc) && (defined _LP64)
  1884     static  Elf32_Half running_arch_code=EM_SPARCV9;
  1885   #elif  (defined __sparc) && (!defined _LP64)
  1886     static  Elf32_Half running_arch_code=EM_SPARC;
  1887   #elif  (defined __powerpc64__)
  1888     static  Elf32_Half running_arch_code=EM_PPC64;
  1889   #elif  (defined __powerpc__)
  1890     static  Elf32_Half running_arch_code=EM_PPC;
  1891   #elif (defined ARM)
  1892     static  Elf32_Half running_arch_code=EM_ARM;
  1893   #else
  1894     #error Method os::dll_load requires that one of following is defined:\
  1895          IA32, AMD64, IA64, __sparc, __powerpc__, ARM, ARM
  1896   #endif
  1898   // Identify compatability class for VM's architecture and library's architecture
  1899   // Obtain string descriptions for architectures
  1901   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
  1902   int running_arch_index=-1;
  1904   for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
  1905     if (running_arch_code == arch_array[i].code) {
  1906       running_arch_index    = i;
  1908     if (lib_arch.code == arch_array[i].code) {
  1909       lib_arch.compat_class = arch_array[i].compat_class;
  1910       lib_arch.name         = arch_array[i].name;
  1914   assert(running_arch_index != -1,
  1915     "Didn't find running architecture code (running_arch_code) in arch_array");
  1916   if (running_arch_index == -1) {
  1917     // Even though running architecture detection failed
  1918     // we may still continue with reporting dlerror() message
  1919     return NULL;
  1922   if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
  1923     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
  1924     return NULL;
  1927   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
  1928     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
  1929     return NULL;
  1932   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
  1933     if ( lib_arch.name!=NULL ) {
  1934       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1935         " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
  1936         lib_arch.name, arch_array[running_arch_index].name);
  1937     } else {
  1938       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
  1939       " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
  1940         lib_arch.code,
  1941         arch_array[running_arch_index].name);
  1945   return NULL;
  1948 void* os::dll_lookup(void* handle, const char* name) {
  1949   return dlsym(handle, name);
  1952 void* os::get_default_process_handle() {
  1953   return (void*)::dlopen(NULL, RTLD_LAZY);
  1956 int os::stat(const char *path, struct stat *sbuf) {
  1957   char pathbuf[MAX_PATH];
  1958   if (strlen(path) > MAX_PATH - 1) {
  1959     errno = ENAMETOOLONG;
  1960     return -1;
  1962   os::native_path(strcpy(pathbuf, path));
  1963   return ::stat(pathbuf, sbuf);
  1966 static bool _print_ascii_file(const char* filename, outputStream* st) {
  1967   int fd = ::open(filename, O_RDONLY);
  1968   if (fd == -1) {
  1969      return false;
  1972   char buf[32];
  1973   int bytes;
  1974   while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
  1975     st->print_raw(buf, bytes);
  1978   ::close(fd);
  1980   return true;
  1983 void os::print_os_info_brief(outputStream* st) {
  1984   os::Solaris::print_distro_info(st);
  1986   os::Posix::print_uname_info(st);
  1988   os::Solaris::print_libversion_info(st);
  1991 void os::print_os_info(outputStream* st) {
  1992   st->print("OS:");
  1994   os::Solaris::print_distro_info(st);
  1996   os::Posix::print_uname_info(st);
  1998   os::Solaris::print_libversion_info(st);
  2000   os::Posix::print_rlimit_info(st);
  2002   os::Posix::print_load_average(st);
  2005 void os::Solaris::print_distro_info(outputStream* st) {
  2006   if (!_print_ascii_file("/etc/release", st)) {
  2007       st->print("Solaris");
  2009     st->cr();
  2012 void os::Solaris::print_libversion_info(outputStream* st) {
  2013   if (os::Solaris::T2_libthread()) {
  2014     st->print("  (T2 libthread)");
  2016   else {
  2017     st->print("  (T1 libthread)");
  2019   st->cr();
  2022 static bool check_addr0(outputStream* st) {
  2023   jboolean status = false;
  2024   int fd = ::open("/proc/self/map",O_RDONLY);
  2025   if (fd >= 0) {
  2026     prmap_t p;
  2027     while(::read(fd, &p, sizeof(p)) > 0) {
  2028       if (p.pr_vaddr == 0x0) {
  2029         st->print("Warning: Address: 0x%x, Size: %dK, ",p.pr_vaddr, p.pr_size/1024, p.pr_mapname);
  2030         st->print("Mapped file: %s, ", p.pr_mapname[0] == '\0' ? "None" : p.pr_mapname);
  2031         st->print("Access:");
  2032         st->print("%s",(p.pr_mflags & MA_READ)  ? "r" : "-");
  2033         st->print("%s",(p.pr_mflags & MA_WRITE) ? "w" : "-");
  2034         st->print("%s",(p.pr_mflags & MA_EXEC)  ? "x" : "-");
  2035         st->cr();
  2036         status = true;
  2039     ::close(fd);
  2041   return status;
  2044 void os::pd_print_cpu_info(outputStream* st) {
  2045   // Nothing to do for now.
  2048 void os::print_memory_info(outputStream* st) {
  2049   st->print("Memory:");
  2050   st->print(" %dk page", os::vm_page_size()>>10);
  2051   st->print(", physical " UINT64_FORMAT "k", os::physical_memory()>>10);
  2052   st->print("(" UINT64_FORMAT "k free)", os::available_memory() >> 10);
  2053   st->cr();
  2054   if (VMError::fatal_error_in_progress()) {
  2055      (void) check_addr0(st);
  2059 void os::print_siginfo(outputStream* st, void* siginfo) {
  2060   const siginfo_t* si = (const siginfo_t*)siginfo;
  2062   os::Posix::print_siginfo_brief(st, si);
  2064   if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
  2065       UseSharedSpaces) {
  2066     FileMapInfo* mapinfo = FileMapInfo::current_info();
  2067     if (mapinfo->is_in_shared_space(si->si_addr)) {
  2068       st->print("\n\nError accessing class data sharing archive."   \
  2069                 " Mapped file inaccessible during execution, "      \
  2070                 " possible disk/network problem.");
  2073   st->cr();
  2076 // Moved from whole group, because we need them here for diagnostic
  2077 // prints.
  2078 #define OLDMAXSIGNUM 32
  2079 static int Maxsignum = 0;
  2080 static int *ourSigFlags = NULL;
  2082 extern "C" void sigINTRHandler(int, siginfo_t*, void*);
  2084 int os::Solaris::get_our_sigflags(int sig) {
  2085   assert(ourSigFlags!=NULL, "signal data structure not initialized");
  2086   assert(sig > 0 && sig < Maxsignum, "vm signal out of expected range");
  2087   return ourSigFlags[sig];
  2090 void os::Solaris::set_our_sigflags(int sig, int flags) {
  2091   assert(ourSigFlags!=NULL, "signal data structure not initialized");
  2092   assert(sig > 0 && sig < Maxsignum, "vm signal out of expected range");
  2093   ourSigFlags[sig] = flags;
  2097 static const char* get_signal_handler_name(address handler,
  2098                                            char* buf, int buflen) {
  2099   int offset;
  2100   bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
  2101   if (found) {
  2102     // skip directory names
  2103     const char *p1, *p2;
  2104     p1 = buf;
  2105     size_t len = strlen(os::file_separator());
  2106     while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
  2107     jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
  2108   } else {
  2109     jio_snprintf(buf, buflen, PTR_FORMAT, handler);
  2111   return buf;
  2114 static void print_signal_handler(outputStream* st, int sig,
  2115                                   char* buf, size_t buflen) {
  2116   struct sigaction sa;
  2118   sigaction(sig, NULL, &sa);
  2120   st->print("%s: ", os::exception_name(sig, buf, buflen));
  2122   address handler = (sa.sa_flags & SA_SIGINFO)
  2123                   ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
  2124                   : CAST_FROM_FN_PTR(address, sa.sa_handler);
  2126   if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
  2127     st->print("SIG_DFL");
  2128   } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
  2129     st->print("SIG_IGN");
  2130   } else {
  2131     st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
  2134   st->print(", sa_mask[0]=");
  2135   os::Posix::print_signal_set_short(st, &sa.sa_mask);
  2137   address rh = VMError::get_resetted_sighandler(sig);
  2138   // May be, handler was resetted by VMError?
  2139   if(rh != NULL) {
  2140     handler = rh;
  2141     sa.sa_flags = VMError::get_resetted_sigflags(sig);
  2144   st->print(", sa_flags=");
  2145   os::Posix::print_sa_flags(st, sa.sa_flags);
  2147   // Check: is it our handler?
  2148   if(handler == CAST_FROM_FN_PTR(address, signalHandler) ||
  2149      handler == CAST_FROM_FN_PTR(address, sigINTRHandler)) {
  2150     // It is our signal handler
  2151     // check for flags
  2152     if(sa.sa_flags != os::Solaris::get_our_sigflags(sig)) {
  2153       st->print(
  2154         ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
  2155         os::Solaris::get_our_sigflags(sig));
  2158   st->cr();
  2161 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
  2162   st->print_cr("Signal Handlers:");
  2163   print_signal_handler(st, SIGSEGV, buf, buflen);
  2164   print_signal_handler(st, SIGBUS , buf, buflen);
  2165   print_signal_handler(st, SIGFPE , buf, buflen);
  2166   print_signal_handler(st, SIGPIPE, buf, buflen);
  2167   print_signal_handler(st, SIGXFSZ, buf, buflen);
  2168   print_signal_handler(st, SIGILL , buf, buflen);
  2169   print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
  2170   print_signal_handler(st, ASYNC_SIGNAL, buf, buflen);
  2171   print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
  2172   print_signal_handler(st, SHUTDOWN1_SIGNAL , buf, buflen);
  2173   print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
  2174   print_signal_handler(st, SHUTDOWN3_SIGNAL, buf, buflen);
  2175   print_signal_handler(st, os::Solaris::SIGinterrupt(), buf, buflen);
  2176   print_signal_handler(st, os::Solaris::SIGasync(), buf, buflen);
  2179 static char saved_jvm_path[MAXPATHLEN] = { 0 };
  2181 // Find the full path to the current module, libjvm.so
  2182 void os::jvm_path(char *buf, jint buflen) {
  2183   // Error checking.
  2184   if (buflen < MAXPATHLEN) {
  2185     assert(false, "must use a large-enough buffer");
  2186     buf[0] = '\0';
  2187     return;
  2189   // Lazy resolve the path to current module.
  2190   if (saved_jvm_path[0] != 0) {
  2191     strcpy(buf, saved_jvm_path);
  2192     return;
  2195   Dl_info dlinfo;
  2196   int ret = dladdr(CAST_FROM_FN_PTR(void *, os::jvm_path), &dlinfo);
  2197   assert(ret != 0, "cannot locate libjvm");
  2198   if (ret != 0 && dlinfo.dli_fname != NULL) {
  2199     realpath((char *)dlinfo.dli_fname, buf);
  2200   } else {
  2201     buf[0] = '\0';
  2202     return;
  2205   if (Arguments::created_by_gamma_launcher()) {
  2206     // Support for the gamma launcher.  Typical value for buf is
  2207     // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so".  If "/jre/lib/" appears at
  2208     // the right place in the string, then assume we are installed in a JDK and
  2209     // we're done.  Otherwise, check for a JAVA_HOME environment variable and fix
  2210     // up the path so it looks like libjvm.so is installed there (append a
  2211     // fake suffix hotspot/libjvm.so).
  2212     const char *p = buf + strlen(buf) - 1;
  2213     for (int count = 0; p > buf && count < 5; ++count) {
  2214       for (--p; p > buf && *p != '/'; --p)
  2215         /* empty */ ;
  2218     if (strncmp(p, "/jre/lib/", 9) != 0) {
  2219       // Look for JAVA_HOME in the environment.
  2220       char* java_home_var = ::getenv("JAVA_HOME");
  2221       if (java_home_var != NULL && java_home_var[0] != 0) {
  2222         char cpu_arch[12];
  2223         char* jrelib_p;
  2224         int   len;
  2225         sysinfo(SI_ARCHITECTURE, cpu_arch, sizeof(cpu_arch));
  2226 #ifdef _LP64
  2227         // If we are on sparc running a 64-bit vm, look in jre/lib/sparcv9.
  2228         if (strcmp(cpu_arch, "sparc") == 0) {
  2229           strcat(cpu_arch, "v9");
  2230         } else if (strcmp(cpu_arch, "i386") == 0) {
  2231           strcpy(cpu_arch, "amd64");
  2233 #endif
  2234         // Check the current module name "libjvm.so".
  2235         p = strrchr(buf, '/');
  2236         assert(strstr(p, "/libjvm") == p, "invalid library name");
  2238         realpath(java_home_var, buf);
  2239         // determine if this is a legacy image or modules image
  2240         // modules image doesn't have "jre" subdirectory
  2241         len = strlen(buf);
  2242         assert(len < buflen, "Ran out of buffer space");
  2243         jrelib_p = buf + len;
  2244         snprintf(jrelib_p, buflen-len, "/jre/lib/%s", cpu_arch);
  2245         if (0 != access(buf, F_OK)) {
  2246           snprintf(jrelib_p, buflen-len, "/lib/%s", cpu_arch);
  2249         if (0 == access(buf, F_OK)) {
  2250           // Use current module name "libjvm.so"
  2251           len = strlen(buf);
  2252           snprintf(buf + len, buflen-len, "/hotspot/libjvm.so");
  2253         } else {
  2254           // Go back to path of .so
  2255           realpath((char *)dlinfo.dli_fname, buf);
  2261   strncpy(saved_jvm_path, buf, MAXPATHLEN);
  2265 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
  2266   // no prefix required, not even "_"
  2270 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
  2271   // no suffix required
  2274 // This method is a copy of JDK's sysGetLastErrorString
  2275 // from src/solaris/hpi/src/system_md.c
  2277 size_t os::lasterror(char *buf, size_t len) {
  2279   if (errno == 0)  return 0;
  2281   const char *s = ::strerror(errno);
  2282   size_t n = ::strlen(s);
  2283   if (n >= len) {
  2284     n = len - 1;
  2286   ::strncpy(buf, s, n);
  2287   buf[n] = '\0';
  2288   return n;
  2292 // sun.misc.Signal
  2294 extern "C" {
  2295   static void UserHandler(int sig, void *siginfo, void *context) {
  2296     // Ctrl-C is pressed during error reporting, likely because the error
  2297     // handler fails to abort. Let VM die immediately.
  2298     if (sig == SIGINT && is_error_reported()) {
  2299        os::die();
  2302     os::signal_notify(sig);
  2303     // We do not need to reinstate the signal handler each time...
  2307 void* os::user_handler() {
  2308   return CAST_FROM_FN_PTR(void*, UserHandler);
  2311 class Semaphore : public StackObj {
  2312   public:
  2313     Semaphore();
  2314     ~Semaphore();
  2315     void signal();
  2316     void wait();
  2317     bool trywait();
  2318     bool timedwait(unsigned int sec, int nsec);
  2319   private:
  2320     sema_t _semaphore;
  2321 };
  2324 Semaphore::Semaphore() {
  2325   sema_init(&_semaphore, 0, NULL, NULL);
  2328 Semaphore::~Semaphore() {
  2329   sema_destroy(&_semaphore);
  2332 void Semaphore::signal() {
  2333   sema_post(&_semaphore);
  2336 void Semaphore::wait() {
  2337   sema_wait(&_semaphore);
  2340 bool Semaphore::trywait() {
  2341   return sema_trywait(&_semaphore) == 0;
  2344 bool Semaphore::timedwait(unsigned int sec, int nsec) {
  2345   struct timespec ts;
  2346   unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
  2348   while (1) {
  2349     int result = sema_timedwait(&_semaphore, &ts);
  2350     if (result == 0) {
  2351       return true;
  2352     } else if (errno == EINTR) {
  2353       continue;
  2354     } else if (errno == ETIME) {
  2355       return false;
  2356     } else {
  2357       return false;
  2362 extern "C" {
  2363   typedef void (*sa_handler_t)(int);
  2364   typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
  2367 void* os::signal(int signal_number, void* handler) {
  2368   struct sigaction sigAct, oldSigAct;
  2369   sigfillset(&(sigAct.sa_mask));
  2370   sigAct.sa_flags = SA_RESTART & ~SA_RESETHAND;
  2371   sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
  2373   if (sigaction(signal_number, &sigAct, &oldSigAct))
  2374     // -1 means registration failed
  2375     return (void *)-1;
  2377   return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
  2380 void os::signal_raise(int signal_number) {
  2381   raise(signal_number);
  2384 /*
  2385  * The following code is moved from os.cpp for making this
  2386  * code platform specific, which it is by its very nature.
  2387  */
  2389 // a counter for each possible signal value
  2390 static int Sigexit = 0;
  2391 static int Maxlibjsigsigs;
  2392 static jint *pending_signals = NULL;
  2393 static int *preinstalled_sigs = NULL;
  2394 static struct sigaction *chainedsigactions = NULL;
  2395 static sema_t sig_sem;
  2396 typedef int (*version_getting_t)();
  2397 version_getting_t os::Solaris::get_libjsig_version = NULL;
  2398 static int libjsigversion = NULL;
  2400 int os::sigexitnum_pd() {
  2401   assert(Sigexit > 0, "signal memory not yet initialized");
  2402   return Sigexit;
  2405 void os::Solaris::init_signal_mem() {
  2406   // Initialize signal structures
  2407   Maxsignum = SIGRTMAX;
  2408   Sigexit = Maxsignum+1;
  2409   assert(Maxsignum >0, "Unable to obtain max signal number");
  2411   Maxlibjsigsigs = Maxsignum;
  2413   // pending_signals has one int per signal
  2414   // The additional signal is for SIGEXIT - exit signal to signal_thread
  2415   pending_signals = (jint *)os::malloc(sizeof(jint) * (Sigexit+1), mtInternal);
  2416   memset(pending_signals, 0, (sizeof(jint) * (Sigexit+1)));
  2418   if (UseSignalChaining) {
  2419      chainedsigactions = (struct sigaction *)malloc(sizeof(struct sigaction)
  2420        * (Maxsignum + 1), mtInternal);
  2421      memset(chainedsigactions, 0, (sizeof(struct sigaction) * (Maxsignum + 1)));
  2422      preinstalled_sigs = (int *)os::malloc(sizeof(int) * (Maxsignum + 1), mtInternal);
  2423      memset(preinstalled_sigs, 0, (sizeof(int) * (Maxsignum + 1)));
  2425   ourSigFlags = (int*)malloc(sizeof(int) * (Maxsignum + 1 ), mtInternal);
  2426   memset(ourSigFlags, 0, sizeof(int) * (Maxsignum + 1));
  2429 void os::signal_init_pd() {
  2430   int ret;
  2432   ret = ::sema_init(&sig_sem, 0, NULL, NULL);
  2433   assert(ret == 0, "sema_init() failed");
  2436 void os::signal_notify(int signal_number) {
  2437   int ret;
  2439   Atomic::inc(&pending_signals[signal_number]);
  2440   ret = ::sema_post(&sig_sem);
  2441   assert(ret == 0, "sema_post() failed");
  2444 static int check_pending_signals(bool wait_for_signal) {
  2445   int ret;
  2446   while (true) {
  2447     for (int i = 0; i < Sigexit + 1; i++) {
  2448       jint n = pending_signals[i];
  2449       if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
  2450         return i;
  2453     if (!wait_for_signal) {
  2454       return -1;
  2456     JavaThread *thread = JavaThread::current();
  2457     ThreadBlockInVM tbivm(thread);
  2459     bool threadIsSuspended;
  2460     do {
  2461       thread->set_suspend_equivalent();
  2462       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
  2463       while((ret = ::sema_wait(&sig_sem)) == EINTR)
  2465       assert(ret == 0, "sema_wait() failed");
  2467       // were we externally suspended while we were waiting?
  2468       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
  2469       if (threadIsSuspended) {
  2470         //
  2471         // The semaphore has been incremented, but while we were waiting
  2472         // another thread suspended us. We don't want to continue running
  2473         // while suspended because that would surprise the thread that
  2474         // suspended us.
  2475         //
  2476         ret = ::sema_post(&sig_sem);
  2477         assert(ret == 0, "sema_post() failed");
  2479         thread->java_suspend_self();
  2481     } while (threadIsSuspended);
  2485 int os::signal_lookup() {
  2486   return check_pending_signals(false);
  2489 int os::signal_wait() {
  2490   return check_pending_signals(true);
  2493 ////////////////////////////////////////////////////////////////////////////////
  2494 // Virtual Memory
  2496 static int page_size = -1;
  2498 // The mmap MAP_ALIGN flag is supported on Solaris 9 and later.  init_2() will
  2499 // clear this var if support is not available.
  2500 static bool has_map_align = true;
  2502 int os::vm_page_size() {
  2503   assert(page_size != -1, "must call os::init");
  2504   return page_size;
  2507 // Solaris allocates memory by pages.
  2508 int os::vm_allocation_granularity() {
  2509   assert(page_size != -1, "must call os::init");
  2510   return page_size;
  2513 static bool recoverable_mmap_error(int err) {
  2514   // See if the error is one we can let the caller handle. This
  2515   // list of errno values comes from the Solaris mmap(2) man page.
  2516   switch (err) {
  2517   case EBADF:
  2518   case EINVAL:
  2519   case ENOTSUP:
  2520     // let the caller deal with these errors
  2521     return true;
  2523   default:
  2524     // Any remaining errors on this OS can cause our reserved mapping
  2525     // to be lost. That can cause confusion where different data
  2526     // structures think they have the same memory mapped. The worst
  2527     // scenario is if both the VM and a library think they have the
  2528     // same memory mapped.
  2529     return false;
  2533 static void warn_fail_commit_memory(char* addr, size_t bytes, bool exec,
  2534                                     int err) {
  2535   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
  2536           ", %d) failed; error='%s' (errno=%d)", addr, bytes, exec,
  2537           strerror(err), err);
  2540 static void warn_fail_commit_memory(char* addr, size_t bytes,
  2541                                     size_t alignment_hint, bool exec,
  2542                                     int err) {
  2543   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
  2544           ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", addr, bytes,
  2545           alignment_hint, exec, strerror(err), err);
  2548 int os::Solaris::commit_memory_impl(char* addr, size_t bytes, bool exec) {
  2549   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
  2550   size_t size = bytes;
  2551   char *res = Solaris::mmap_chunk(addr, size, MAP_PRIVATE|MAP_FIXED, prot);
  2552   if (res != NULL) {
  2553     if (UseNUMAInterleaving) {
  2554       numa_make_global(addr, bytes);
  2556     return 0;
  2559   int err = errno;  // save errno from mmap() call in mmap_chunk()
  2561   if (!recoverable_mmap_error(err)) {
  2562     warn_fail_commit_memory(addr, bytes, exec, err);
  2563     vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "committing reserved memory.");
  2566   return err;
  2569 bool os::pd_commit_memory(char* addr, size_t bytes, bool exec) {
  2570   return Solaris::commit_memory_impl(addr, bytes, exec) == 0;
  2573 void os::pd_commit_memory_or_exit(char* addr, size_t bytes, bool exec,
  2574                                   const char* mesg) {
  2575   assert(mesg != NULL, "mesg must be specified");
  2576   int err = os::Solaris::commit_memory_impl(addr, bytes, exec);
  2577   if (err != 0) {
  2578     // the caller wants all commit errors to exit with the specified mesg:
  2579     warn_fail_commit_memory(addr, bytes, exec, err);
  2580     vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, mesg);
  2584 size_t os::Solaris::page_size_for_alignment(size_t alignment) {
  2585   assert(is_size_aligned(alignment, (size_t) vm_page_size()),
  2586          err_msg(SIZE_FORMAT " is not aligned to " SIZE_FORMAT,
  2587                  alignment, (size_t) vm_page_size()));
  2589   for (int i = 0; _page_sizes[i] != 0; i++) {
  2590     if (is_size_aligned(alignment, _page_sizes[i])) {
  2591       return _page_sizes[i];
  2595   return (size_t) vm_page_size();
  2598 int os::Solaris::commit_memory_impl(char* addr, size_t bytes,
  2599                                     size_t alignment_hint, bool exec) {
  2600   int err = Solaris::commit_memory_impl(addr, bytes, exec);
  2601   if (err == 0 && UseLargePages && alignment_hint > 0) {
  2602     assert(is_size_aligned(bytes, alignment_hint),
  2603            err_msg(SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, alignment_hint));
  2605     // The syscall memcntl requires an exact page size (see man memcntl for details).
  2606     size_t page_size = page_size_for_alignment(alignment_hint);
  2607     if (page_size > (size_t) vm_page_size()) {
  2608       (void)Solaris::setup_large_pages(addr, bytes, page_size);
  2611   return err;
  2614 bool os::pd_commit_memory(char* addr, size_t bytes, size_t alignment_hint,
  2615                           bool exec) {
  2616   return Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec) == 0;
  2619 void os::pd_commit_memory_or_exit(char* addr, size_t bytes,
  2620                                   size_t alignment_hint, bool exec,
  2621                                   const char* mesg) {
  2622   assert(mesg != NULL, "mesg must be specified");
  2623   int err = os::Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec);
  2624   if (err != 0) {
  2625     // the caller wants all commit errors to exit with the specified mesg:
  2626     warn_fail_commit_memory(addr, bytes, alignment_hint, exec, err);
  2627     vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, mesg);
  2631 // Uncommit the pages in a specified region.
  2632 void os::pd_free_memory(char* addr, size_t bytes, size_t alignment_hint) {
  2633   if (madvise(addr, bytes, MADV_FREE) < 0) {
  2634     debug_only(warning("MADV_FREE failed."));
  2635     return;
  2639 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
  2640   return os::commit_memory(addr, size, !ExecMem);
  2643 bool os::remove_stack_guard_pages(char* addr, size_t size) {
  2644   return os::uncommit_memory(addr, size);
  2647 // Change the page size in a given range.
  2648 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
  2649   assert((intptr_t)addr % alignment_hint == 0, "Address should be aligned.");
  2650   assert((intptr_t)(addr + bytes) % alignment_hint == 0, "End should be aligned.");
  2651   if (UseLargePages) {
  2652     Solaris::setup_large_pages(addr, bytes, alignment_hint);
  2656 // Tell the OS to make the range local to the first-touching LWP
  2657 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
  2658   assert((intptr_t)addr % os::vm_page_size() == 0, "Address should be page-aligned.");
  2659   if (madvise(addr, bytes, MADV_ACCESS_LWP) < 0) {
  2660     debug_only(warning("MADV_ACCESS_LWP failed."));
  2664 // Tell the OS that this range would be accessed from different LWPs.
  2665 void os::numa_make_global(char *addr, size_t bytes) {
  2666   assert((intptr_t)addr % os::vm_page_size() == 0, "Address should be page-aligned.");
  2667   if (madvise(addr, bytes, MADV_ACCESS_MANY) < 0) {
  2668     debug_only(warning("MADV_ACCESS_MANY failed."));
  2672 // Get the number of the locality groups.
  2673 size_t os::numa_get_groups_num() {
  2674   size_t n = Solaris::lgrp_nlgrps(Solaris::lgrp_cookie());
  2675   return n != -1 ? n : 1;
  2678 // Get a list of leaf locality groups. A leaf lgroup is group that
  2679 // doesn't have any children. Typical leaf group is a CPU or a CPU/memory
  2680 // board. An LWP is assigned to one of these groups upon creation.
  2681 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
  2682    if ((ids[0] = Solaris::lgrp_root(Solaris::lgrp_cookie())) == -1) {
  2683      ids[0] = 0;
  2684      return 1;
  2686    int result_size = 0, top = 1, bottom = 0, cur = 0;
  2687    for (int k = 0; k < size; k++) {
  2688      int r = Solaris::lgrp_children(Solaris::lgrp_cookie(), ids[cur],
  2689                                     (Solaris::lgrp_id_t*)&ids[top], size - top);
  2690      if (r == -1) {
  2691        ids[0] = 0;
  2692        return 1;
  2694      if (!r) {
  2695        // That's a leaf node.
  2696        assert (bottom <= cur, "Sanity check");
  2697        // Check if the node has memory
  2698        if (Solaris::lgrp_resources(Solaris::lgrp_cookie(), ids[cur],
  2699                                    NULL, 0, LGRP_RSRC_MEM) > 0) {
  2700          ids[bottom++] = ids[cur];
  2703      top += r;
  2704      cur++;
  2706    if (bottom == 0) {
  2707      // Handle a situation, when the OS reports no memory available.
  2708      // Assume UMA architecture.
  2709      ids[0] = 0;
  2710      return 1;
  2712    return bottom;
  2715 // Detect the topology change. Typically happens during CPU plugging-unplugging.
  2716 bool os::numa_topology_changed() {
  2717   int is_stale = Solaris::lgrp_cookie_stale(Solaris::lgrp_cookie());
  2718   if (is_stale != -1 && is_stale) {
  2719     Solaris::lgrp_fini(Solaris::lgrp_cookie());
  2720     Solaris::lgrp_cookie_t c = Solaris::lgrp_init(Solaris::LGRP_VIEW_CALLER);
  2721     assert(c != 0, "Failure to initialize LGRP API");
  2722     Solaris::set_lgrp_cookie(c);
  2723     return true;
  2725   return false;
  2728 // Get the group id of the current LWP.
  2729 int os::numa_get_group_id() {
  2730   int lgrp_id = Solaris::lgrp_home(P_LWPID, P_MYID);
  2731   if (lgrp_id == -1) {
  2732     return 0;
  2734   const int size = os::numa_get_groups_num();
  2735   int *ids = (int*)alloca(size * sizeof(int));
  2737   // Get the ids of all lgroups with memory; r is the count.
  2738   int r = Solaris::lgrp_resources(Solaris::lgrp_cookie(), lgrp_id,
  2739                                   (Solaris::lgrp_id_t*)ids, size, LGRP_RSRC_MEM);
  2740   if (r <= 0) {
  2741     return 0;
  2743   return ids[os::random() % r];
  2746 // Request information about the page.
  2747 bool os::get_page_info(char *start, page_info* info) {
  2748   const uint_t info_types[] = { MEMINFO_VLGRP, MEMINFO_VPAGESIZE };
  2749   uint64_t addr = (uintptr_t)start;
  2750   uint64_t outdata[2];
  2751   uint_t validity = 0;
  2753   if (os::Solaris::meminfo(&addr, 1, info_types, 2, outdata, &validity) < 0) {
  2754     return false;
  2757   info->size = 0;
  2758   info->lgrp_id = -1;
  2760   if ((validity & 1) != 0) {
  2761     if ((validity & 2) != 0) {
  2762       info->lgrp_id = outdata[0];
  2764     if ((validity & 4) != 0) {
  2765       info->size = outdata[1];
  2767     return true;
  2769   return false;
  2772 // Scan the pages from start to end until a page different than
  2773 // the one described in the info parameter is encountered.
  2774 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
  2775   const uint_t info_types[] = { MEMINFO_VLGRP, MEMINFO_VPAGESIZE };
  2776   const size_t types = sizeof(info_types) / sizeof(info_types[0]);
  2777   uint64_t addrs[MAX_MEMINFO_CNT], outdata[types * MAX_MEMINFO_CNT + 1];
  2778   uint_t validity[MAX_MEMINFO_CNT];
  2780   size_t page_size = MAX2((size_t)os::vm_page_size(), page_expected->size);
  2781   uint64_t p = (uint64_t)start;
  2782   while (p < (uint64_t)end) {
  2783     addrs[0] = p;
  2784     size_t addrs_count = 1;
  2785     while (addrs_count < MAX_MEMINFO_CNT && addrs[addrs_count - 1] + page_size < (uint64_t)end) {
  2786       addrs[addrs_count] = addrs[addrs_count - 1] + page_size;
  2787       addrs_count++;
  2790     if (os::Solaris::meminfo(addrs, addrs_count, info_types, types, outdata, validity) < 0) {
  2791       return NULL;
  2794     size_t i = 0;
  2795     for (; i < addrs_count; i++) {
  2796       if ((validity[i] & 1) != 0) {
  2797         if ((validity[i] & 4) != 0) {
  2798           if (outdata[types * i + 1] != page_expected->size) {
  2799             break;
  2801         } else
  2802           if (page_expected->size != 0) {
  2803             break;
  2806         if ((validity[i] & 2) != 0 && page_expected->lgrp_id > 0) {
  2807           if (outdata[types * i] != page_expected->lgrp_id) {
  2808             break;
  2811       } else {
  2812         return NULL;
  2816     if (i < addrs_count) {
  2817       if ((validity[i] & 2) != 0) {
  2818         page_found->lgrp_id = outdata[types * i];
  2819       } else {
  2820         page_found->lgrp_id = -1;
  2822       if ((validity[i] & 4) != 0) {
  2823         page_found->size = outdata[types * i + 1];
  2824       } else {
  2825         page_found->size = 0;
  2827       return (char*)addrs[i];
  2830     p = addrs[addrs_count - 1] + page_size;
  2832   return end;
  2835 bool os::pd_uncommit_memory(char* addr, size_t bytes) {
  2836   size_t size = bytes;
  2837   // Map uncommitted pages PROT_NONE so we fail early if we touch an
  2838   // uncommitted page. Otherwise, the read/write might succeed if we
  2839   // have enough swap space to back the physical page.
  2840   return
  2841     NULL != Solaris::mmap_chunk(addr, size,
  2842                                 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE,
  2843                                 PROT_NONE);
  2846 char* os::Solaris::mmap_chunk(char *addr, size_t size, int flags, int prot) {
  2847   char *b = (char *)mmap(addr, size, prot, flags, os::Solaris::_dev_zero_fd, 0);
  2849   if (b == MAP_FAILED) {
  2850     return NULL;
  2852   return b;
  2855 char* os::Solaris::anon_mmap(char* requested_addr, size_t bytes, size_t alignment_hint, bool fixed) {
  2856   char* addr = requested_addr;
  2857   int flags = MAP_PRIVATE | MAP_NORESERVE;
  2859   assert(!(fixed && (alignment_hint > 0)), "alignment hint meaningless with fixed mmap");
  2861   if (fixed) {
  2862     flags |= MAP_FIXED;
  2863   } else if (has_map_align && (alignment_hint > (size_t) vm_page_size())) {
  2864     flags |= MAP_ALIGN;
  2865     addr = (char*) alignment_hint;
  2868   // Map uncommitted pages PROT_NONE so we fail early if we touch an
  2869   // uncommitted page. Otherwise, the read/write might succeed if we
  2870   // have enough swap space to back the physical page.
  2871   return mmap_chunk(addr, bytes, flags, PROT_NONE);
  2874 char* os::pd_reserve_memory(size_t bytes, char* requested_addr, size_t alignment_hint) {
  2875   char* addr = Solaris::anon_mmap(requested_addr, bytes, alignment_hint, (requested_addr != NULL));
  2877   guarantee(requested_addr == NULL || requested_addr == addr,
  2878             "OS failed to return requested mmap address.");
  2879   return addr;
  2882 // Reserve memory at an arbitrary address, only if that area is
  2883 // available (and not reserved for something else).
  2885 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
  2886   const int max_tries = 10;
  2887   char* base[max_tries];
  2888   size_t size[max_tries];
  2890   // Solaris adds a gap between mmap'ed regions.  The size of the gap
  2891   // is dependent on the requested size and the MMU.  Our initial gap
  2892   // value here is just a guess and will be corrected later.
  2893   bool had_top_overlap = false;
  2894   bool have_adjusted_gap = false;
  2895   size_t gap = 0x400000;
  2897   // Assert only that the size is a multiple of the page size, since
  2898   // that's all that mmap requires, and since that's all we really know
  2899   // about at this low abstraction level.  If we need higher alignment,
  2900   // we can either pass an alignment to this method or verify alignment
  2901   // in one of the methods further up the call chain.  See bug 5044738.
  2902   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
  2904   // Since snv_84, Solaris attempts to honor the address hint - see 5003415.
  2905   // Give it a try, if the kernel honors the hint we can return immediately.
  2906   char* addr = Solaris::anon_mmap(requested_addr, bytes, 0, false);
  2908   volatile int err = errno;
  2909   if (addr == requested_addr) {
  2910     return addr;
  2911   } else if (addr != NULL) {
  2912     pd_unmap_memory(addr, bytes);
  2915   if (PrintMiscellaneous && Verbose) {
  2916     char buf[256];
  2917     buf[0] = '\0';
  2918     if (addr == NULL) {
  2919       jio_snprintf(buf, sizeof(buf), ": %s", strerror(err));
  2921     warning("attempt_reserve_memory_at: couldn't reserve " SIZE_FORMAT " bytes at "
  2922             PTR_FORMAT ": reserve_memory_helper returned " PTR_FORMAT
  2923             "%s", bytes, requested_addr, addr, buf);
  2926   // Address hint method didn't work.  Fall back to the old method.
  2927   // In theory, once SNV becomes our oldest supported platform, this
  2928   // code will no longer be needed.
  2929   //
  2930   // Repeatedly allocate blocks until the block is allocated at the
  2931   // right spot. Give up after max_tries.
  2932   int i;
  2933   for (i = 0; i < max_tries; ++i) {
  2934     base[i] = reserve_memory(bytes);
  2936     if (base[i] != NULL) {
  2937       // Is this the block we wanted?
  2938       if (base[i] == requested_addr) {
  2939         size[i] = bytes;
  2940         break;
  2943       // check that the gap value is right
  2944       if (had_top_overlap && !have_adjusted_gap) {
  2945         size_t actual_gap = base[i-1] - base[i] - bytes;
  2946         if (gap != actual_gap) {
  2947           // adjust the gap value and retry the last 2 allocations
  2948           assert(i > 0, "gap adjustment code problem");
  2949           have_adjusted_gap = true;  // adjust the gap only once, just in case
  2950           gap = actual_gap;
  2951           if (PrintMiscellaneous && Verbose) {
  2952             warning("attempt_reserve_memory_at: adjusted gap to 0x%lx", gap);
  2954           unmap_memory(base[i], bytes);
  2955           unmap_memory(base[i-1], size[i-1]);
  2956           i-=2;
  2957           continue;
  2961       // Does this overlap the block we wanted? Give back the overlapped
  2962       // parts and try again.
  2963       //
  2964       // There is still a bug in this code: if top_overlap == bytes,
  2965       // the overlap is offset from requested region by the value of gap.
  2966       // In this case giving back the overlapped part will not work,
  2967       // because we'll give back the entire block at base[i] and
  2968       // therefore the subsequent allocation will not generate a new gap.
  2969       // This could be fixed with a new algorithm that used larger
  2970       // or variable size chunks to find the requested region -
  2971       // but such a change would introduce additional complications.
  2972       // It's rare enough that the planets align for this bug,
  2973       // so we'll just wait for a fix for 6204603/5003415 which
  2974       // will provide a mmap flag to allow us to avoid this business.
  2976       size_t top_overlap = requested_addr + (bytes + gap) - base[i];
  2977       if (top_overlap >= 0 && top_overlap < bytes) {
  2978         had_top_overlap = true;
  2979         unmap_memory(base[i], top_overlap);
  2980         base[i] += top_overlap;
  2981         size[i] = bytes - top_overlap;
  2982       } else {
  2983         size_t bottom_overlap = base[i] + bytes - requested_addr;
  2984         if (bottom_overlap >= 0 && bottom_overlap < bytes) {
  2985           if (PrintMiscellaneous && Verbose && bottom_overlap == 0) {
  2986             warning("attempt_reserve_memory_at: possible alignment bug");
  2988           unmap_memory(requested_addr, bottom_overlap);
  2989           size[i] = bytes - bottom_overlap;
  2990         } else {
  2991           size[i] = bytes;
  2997   // Give back the unused reserved pieces.
  2999   for (int j = 0; j < i; ++j) {
  3000     if (base[j] != NULL) {
  3001       unmap_memory(base[j], size[j]);
  3005   return (i < max_tries) ? requested_addr : NULL;
  3008 bool os::pd_release_memory(char* addr, size_t bytes) {
  3009   size_t size = bytes;
  3010   return munmap(addr, size) == 0;
  3013 static bool solaris_mprotect(char* addr, size_t bytes, int prot) {
  3014   assert(addr == (char*)align_size_down((uintptr_t)addr, os::vm_page_size()),
  3015          "addr must be page aligned");
  3016   int retVal = mprotect(addr, bytes, prot);
  3017   return retVal == 0;
  3020 // Protect memory (Used to pass readonly pages through
  3021 // JNI GetArray<type>Elements with empty arrays.)
  3022 // Also, used for serialization page and for compressed oops null pointer
  3023 // checking.
  3024 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
  3025                         bool is_committed) {
  3026   unsigned int p = 0;
  3027   switch (prot) {
  3028   case MEM_PROT_NONE: p = PROT_NONE; break;
  3029   case MEM_PROT_READ: p = PROT_READ; break;
  3030   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
  3031   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
  3032   default:
  3033     ShouldNotReachHere();
  3035   // is_committed is unused.
  3036   return solaris_mprotect(addr, bytes, p);
  3039 // guard_memory and unguard_memory only happens within stack guard pages.
  3040 // Since ISM pertains only to the heap, guard and unguard memory should not
  3041 /// happen with an ISM region.
  3042 bool os::guard_memory(char* addr, size_t bytes) {
  3043   return solaris_mprotect(addr, bytes, PROT_NONE);
  3046 bool os::unguard_memory(char* addr, size_t bytes) {
  3047   return solaris_mprotect(addr, bytes, PROT_READ|PROT_WRITE);
  3050 // Large page support
  3051 static size_t _large_page_size = 0;
  3053 // Insertion sort for small arrays (descending order).
  3054 static void insertion_sort_descending(size_t* array, int len) {
  3055   for (int i = 0; i < len; i++) {
  3056     size_t val = array[i];
  3057     for (size_t key = i; key > 0 && array[key - 1] < val; --key) {
  3058       size_t tmp = array[key];
  3059       array[key] = array[key - 1];
  3060       array[key - 1] = tmp;
  3065 bool os::Solaris::mpss_sanity_check(bool warn, size_t* page_size) {
  3066   const unsigned int usable_count = VM_Version::page_size_count();
  3067   if (usable_count == 1) {
  3068     return false;
  3071   // Find the right getpagesizes interface.  When solaris 11 is the minimum
  3072   // build platform, getpagesizes() (without the '2') can be called directly.
  3073   typedef int (*gps_t)(size_t[], int);
  3074   gps_t gps_func = CAST_TO_FN_PTR(gps_t, dlsym(RTLD_DEFAULT, "getpagesizes2"));
  3075   if (gps_func == NULL) {
  3076     gps_func = CAST_TO_FN_PTR(gps_t, dlsym(RTLD_DEFAULT, "getpagesizes"));
  3077     if (gps_func == NULL) {
  3078       if (warn) {
  3079         warning("MPSS is not supported by the operating system.");
  3081       return false;
  3085   // Fill the array of page sizes.
  3086   int n = (*gps_func)(_page_sizes, page_sizes_max);
  3087   assert(n > 0, "Solaris bug?");
  3089   if (n == page_sizes_max) {
  3090     // Add a sentinel value (necessary only if the array was completely filled
  3091     // since it is static (zeroed at initialization)).
  3092     _page_sizes[--n] = 0;
  3093     DEBUG_ONLY(warning("increase the size of the os::_page_sizes array.");)
  3095   assert(_page_sizes[n] == 0, "missing sentinel");
  3096   trace_page_sizes("available page sizes", _page_sizes, n);
  3098   if (n == 1) return false;     // Only one page size available.
  3100   // Skip sizes larger than 4M (or LargePageSizeInBytes if it was set) and
  3101   // select up to usable_count elements.  First sort the array, find the first
  3102   // acceptable value, then copy the usable sizes to the top of the array and
  3103   // trim the rest.  Make sure to include the default page size :-).
  3104   //
  3105   // A better policy could get rid of the 4M limit by taking the sizes of the
  3106   // important VM memory regions (java heap and possibly the code cache) into
  3107   // account.
  3108   insertion_sort_descending(_page_sizes, n);
  3109   const size_t size_limit =
  3110     FLAG_IS_DEFAULT(LargePageSizeInBytes) ? 4 * M : LargePageSizeInBytes;
  3111   int beg;
  3112   for (beg = 0; beg < n && _page_sizes[beg] > size_limit; ++beg) /* empty */ ;
  3113   const int end = MIN2((int)usable_count, n) - 1;
  3114   for (int cur = 0; cur < end; ++cur, ++beg) {
  3115     _page_sizes[cur] = _page_sizes[beg];
  3117   _page_sizes[end] = vm_page_size();
  3118   _page_sizes[end + 1] = 0;
  3120   if (_page_sizes[end] > _page_sizes[end - 1]) {
  3121     // Default page size is not the smallest; sort again.
  3122     insertion_sort_descending(_page_sizes, end + 1);
  3124   *page_size = _page_sizes[0];
  3126   trace_page_sizes("usable page sizes", _page_sizes, end + 1);
  3127   return true;
  3130 void os::large_page_init() {
  3131   if (UseLargePages) {
  3132     // print a warning if any large page related flag is specified on command line
  3133     bool warn_on_failure = !FLAG_IS_DEFAULT(UseLargePages)        ||
  3134                            !FLAG_IS_DEFAULT(LargePageSizeInBytes);
  3136     UseLargePages = Solaris::mpss_sanity_check(warn_on_failure, &_large_page_size);
  3140 bool os::Solaris::is_valid_page_size(size_t bytes) {
  3141   for (int i = 0; _page_sizes[i] != 0; i++) {
  3142     if (_page_sizes[i] == bytes) {
  3143       return true;
  3146   return false;
  3149 bool os::Solaris::setup_large_pages(caddr_t start, size_t bytes, size_t align) {
  3150   assert(is_valid_page_size(align), err_msg(SIZE_FORMAT " is not a valid page size", align));
  3151   assert(is_ptr_aligned((void*) start, align),
  3152          err_msg(PTR_FORMAT " is not aligned to " SIZE_FORMAT, p2i((void*) start), align));
  3153   assert(is_size_aligned(bytes, align),
  3154          err_msg(SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, align));
  3156   // Signal to OS that we want large pages for addresses
  3157   // from addr, addr + bytes
  3158   struct memcntl_mha mpss_struct;
  3159   mpss_struct.mha_cmd = MHA_MAPSIZE_VA;
  3160   mpss_struct.mha_pagesize = align;
  3161   mpss_struct.mha_flags = 0;
  3162   // Upon successful completion, memcntl() returns 0
  3163   if (memcntl(start, bytes, MC_HAT_ADVISE, (caddr_t) &mpss_struct, 0, 0)) {
  3164     debug_only(warning("Attempt to use MPSS failed."));
  3165     return false;
  3167   return true;
  3170 char* os::reserve_memory_special(size_t size, size_t alignment, char* addr, bool exec) {
  3171   fatal("os::reserve_memory_special should not be called on Solaris.");
  3172   return NULL;
  3175 bool os::release_memory_special(char* base, size_t bytes) {
  3176   fatal("os::release_memory_special should not be called on Solaris.");
  3177   return false;
  3180 size_t os::large_page_size() {
  3181   return _large_page_size;
  3184 // MPSS allows application to commit large page memory on demand; with ISM
  3185 // the entire memory region must be allocated as shared memory.
  3186 bool os::can_commit_large_page_memory() {
  3187   return true;
  3190 bool os::can_execute_large_page_memory() {
  3191   return true;
  3194 static int os_sleep(jlong millis, bool interruptible) {
  3195   const jlong limit = INT_MAX;
  3196   jlong prevtime;
  3197   int res;
  3199   while (millis > limit) {
  3200     if ((res = os_sleep(limit, interruptible)) != OS_OK)
  3201       return res;
  3202     millis -= limit;
  3205   // Restart interrupted polls with new parameters until the proper delay
  3206   // has been completed.
  3208   prevtime = getTimeMillis();
  3210   while (millis > 0) {
  3211     jlong newtime;
  3213     if (!interruptible) {
  3214       // Following assert fails for os::yield_all:
  3215       // assert(!thread->is_Java_thread(), "must not be java thread");
  3216       res = poll(NULL, 0, millis);
  3217     } else {
  3218       JavaThread *jt = JavaThread::current();
  3220       INTERRUPTIBLE_NORESTART_VM_ALWAYS(poll(NULL, 0, millis), res, jt,
  3221         os::Solaris::clear_interrupted);
  3224     // INTERRUPTIBLE_NORESTART_VM_ALWAYS returns res == OS_INTRPT for
  3225     // thread.Interrupt.
  3227     // See c/r 6751923. Poll can return 0 before time
  3228     // has elapsed if time is set via clock_settime (as NTP does).
  3229     // res == 0 if poll timed out (see man poll RETURN VALUES)
  3230     // using the logic below checks that we really did
  3231     // sleep at least "millis" if not we'll sleep again.
  3232     if( ( res == 0 ) || ((res == OS_ERR) && (errno == EINTR))) {
  3233       newtime = getTimeMillis();
  3234       assert(newtime >= prevtime, "time moving backwards");
  3235     /* Doing prevtime and newtime in microseconds doesn't help precision,
  3236        and trying to round up to avoid lost milliseconds can result in a
  3237        too-short delay. */
  3238       millis -= newtime - prevtime;
  3239       if(millis <= 0)
  3240         return OS_OK;
  3241       prevtime = newtime;
  3242     } else
  3243       return res;
  3246   return OS_OK;
  3249 // Read calls from inside the vm need to perform state transitions
  3250 size_t os::read(int fd, void *buf, unsigned int nBytes) {
  3251   INTERRUPTIBLE_RETURN_INT_VM(::read(fd, buf, nBytes), os::Solaris::clear_interrupted);
  3254 size_t os::restartable_read(int fd, void *buf, unsigned int nBytes) {
  3255   INTERRUPTIBLE_RETURN_INT(::read(fd, buf, nBytes), os::Solaris::clear_interrupted);
  3258 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
  3259   assert(thread == Thread::current(),  "thread consistency check");
  3261   // TODO-FIXME: this should be removed.
  3262   // On Solaris machines (especially 2.5.1) we found that sometimes the VM gets into a live lock
  3263   // situation with a JavaThread being starved out of a lwp. The kernel doesn't seem to generate
  3264   // a SIGWAITING signal which would enable the threads library to create a new lwp for the starving
  3265   // thread. We suspect that because the Watcher thread keeps waking up at periodic intervals the kernel
  3266   // is fooled into believing that the system is making progress. In the code below we block the
  3267   // the watcher thread while safepoint is in progress so that it would not appear as though the
  3268   // system is making progress.
  3269   if (!Solaris::T2_libthread() &&
  3270       thread->is_Watcher_thread() && SafepointSynchronize::is_synchronizing() && !Arguments::has_profile()) {
  3271     // We now try to acquire the threads lock. Since this lock is held by the VM thread during
  3272     // the entire safepoint, the watcher thread will  line up here during the safepoint.
  3273     Threads_lock->lock_without_safepoint_check();
  3274     Threads_lock->unlock();
  3277   if (thread->is_Java_thread()) {
  3278     // This is a JavaThread so we honor the _thread_blocked protocol
  3279     // even for sleeps of 0 milliseconds. This was originally done
  3280     // as a workaround for bug 4338139. However, now we also do it
  3281     // to honor the suspend-equivalent protocol.
  3283     JavaThread *jt = (JavaThread *) thread;
  3284     ThreadBlockInVM tbivm(jt);
  3286     jt->set_suspend_equivalent();
  3287     // cleared by handle_special_suspend_equivalent_condition() or
  3288     // java_suspend_self() via check_and_wait_while_suspended()
  3290     int ret_code;
  3291     if (millis <= 0) {
  3292       thr_yield();
  3293       ret_code = 0;
  3294     } else {
  3295       // The original sleep() implementation did not create an
  3296       // OSThreadWaitState helper for sleeps of 0 milliseconds.
  3297       // I'm preserving that decision for now.
  3298       OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
  3300       ret_code = os_sleep(millis, interruptible);
  3303     // were we externally suspended while we were waiting?
  3304     jt->check_and_wait_while_suspended();
  3306     return ret_code;
  3309   // non-JavaThread from this point on:
  3311   if (millis <= 0) {
  3312     thr_yield();
  3313     return 0;
  3316   OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
  3318   return os_sleep(millis, interruptible);
  3321 void os::naked_short_sleep(jlong ms) {
  3322   assert(ms < 1000, "Un-interruptable sleep, short time use only");
  3324   // usleep is deprecated and removed from POSIX, in favour of nanosleep, but
  3325   // Solaris requires -lrt for this.
  3326   usleep((ms * 1000));
  3328   return;
  3331 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
  3332 void os::infinite_sleep() {
  3333   while (true) {    // sleep forever ...
  3334     ::sleep(100);   // ... 100 seconds at a time
  3338 // Used to convert frequent JVM_Yield() to nops
  3339 bool os::dont_yield() {
  3340   if (DontYieldALot) {
  3341     static hrtime_t last_time = 0;
  3342     hrtime_t diff = getTimeNanos() - last_time;
  3344     if (diff < DontYieldALotInterval * 1000000)
  3345       return true;
  3347     last_time += diff;
  3349     return false;
  3351   else {
  3352     return false;
  3356 // Caveat: Solaris os::yield() causes a thread-state transition whereas
  3357 // the linux and win32 implementations do not.  This should be checked.
  3359 void os::yield() {
  3360   // Yields to all threads with same or greater priority
  3361   os::sleep(Thread::current(), 0, false);
  3364 // Note that yield semantics are defined by the scheduling class to which
  3365 // the thread currently belongs.  Typically, yield will _not yield to
  3366 // other equal or higher priority threads that reside on the dispatch queues
  3367 // of other CPUs.
  3369 os::YieldResult os::NakedYield() { thr_yield(); return os::YIELD_UNKNOWN; }
  3372 // On Solaris we found that yield_all doesn't always yield to all other threads.
  3373 // There have been cases where there is a thread ready to execute but it doesn't
  3374 // get an lwp as the VM thread continues to spin with sleeps of 1 millisecond.
  3375 // The 1 millisecond wait doesn't seem long enough for the kernel to issue a
  3376 // SIGWAITING signal which will cause a new lwp to be created. So we count the
  3377 // number of times yield_all is called in the one loop and increase the sleep
  3378 // time after 8 attempts. If this fails too we increase the concurrency level
  3379 // so that the starving thread would get an lwp
  3381 void os::yield_all(int attempts) {
  3382   // Yields to all threads, including threads with lower priorities
  3383   if (attempts == 0) {
  3384     os::sleep(Thread::current(), 1, false);
  3385   } else {
  3386     int iterations = attempts % 30;
  3387     if (iterations == 0 && !os::Solaris::T2_libthread()) {
  3388       // thr_setconcurrency and _getconcurrency make sense only under T1.
  3389       int noofLWPS = thr_getconcurrency();
  3390       if (noofLWPS < (Threads::number_of_threads() + 2)) {
  3391         thr_setconcurrency(thr_getconcurrency() + 1);
  3393     } else if (iterations < 25) {
  3394       os::sleep(Thread::current(), 1, false);
  3395     } else {
  3396       os::sleep(Thread::current(), 10, false);
  3401 // Called from the tight loops to possibly influence time-sharing heuristics
  3402 void os::loop_breaker(int attempts) {
  3403   os::yield_all(attempts);
  3407 // Interface for setting lwp priorities.  If we are using T2 libthread,
  3408 // which forces the use of BoundThreads or we manually set UseBoundThreads,
  3409 // all of our threads will be assigned to real lwp's.  Using the thr_setprio
  3410 // function is meaningless in this mode so we must adjust the real lwp's priority
  3411 // The routines below implement the getting and setting of lwp priorities.
  3412 //
  3413 // Note: There are three priority scales used on Solaris.  Java priotities
  3414 //       which range from 1 to 10, libthread "thr_setprio" scale which range
  3415 //       from 0 to 127, and the current scheduling class of the process we
  3416 //       are running in.  This is typically from -60 to +60.
  3417 //       The setting of the lwp priorities in done after a call to thr_setprio
  3418 //       so Java priorities are mapped to libthread priorities and we map from
  3419 //       the latter to lwp priorities.  We don't keep priorities stored in
  3420 //       Java priorities since some of our worker threads want to set priorities
  3421 //       higher than all Java threads.
  3422 //
  3423 // For related information:
  3424 // (1)  man -s 2 priocntl
  3425 // (2)  man -s 4 priocntl
  3426 // (3)  man dispadmin
  3427 // =    librt.so
  3428 // =    libthread/common/rtsched.c - thrp_setlwpprio().
  3429 // =    ps -cL <pid> ... to validate priority.
  3430 // =    sched_get_priority_min and _max
  3431 //              pthread_create
  3432 //              sched_setparam
  3433 //              pthread_setschedparam
  3434 //
  3435 // Assumptions:
  3436 // +    We assume that all threads in the process belong to the same
  3437 //              scheduling class.   IE. an homogenous process.
  3438 // +    Must be root or in IA group to change change "interactive" attribute.
  3439 //              Priocntl() will fail silently.  The only indication of failure is when
  3440 //              we read-back the value and notice that it hasn't changed.
  3441 // +    Interactive threads enter the runq at the head, non-interactive at the tail.
  3442 // +    For RT, change timeslice as well.  Invariant:
  3443 //              constant "priority integral"
  3444 //              Konst == TimeSlice * (60-Priority)
  3445 //              Given a priority, compute appropriate timeslice.
  3446 // +    Higher numerical values have higher priority.
  3448 // sched class attributes
  3449 typedef struct {
  3450         int   schedPolicy;              // classID
  3451         int   maxPrio;
  3452         int   minPrio;
  3453 } SchedInfo;
  3456 static SchedInfo tsLimits, iaLimits, rtLimits, fxLimits;
  3458 #ifdef ASSERT
  3459 static int  ReadBackValidate = 1;
  3460 #endif
  3461 static int  myClass     = 0;
  3462 static int  myMin       = 0;
  3463 static int  myMax       = 0;
  3464 static int  myCur       = 0;
  3465 static bool priocntl_enable = false;
  3467 static const int criticalPrio = 60; // FX/60 is critical thread class/priority on T4
  3468 static int java_MaxPriority_to_os_priority = 0; // Saved mapping
  3471 // lwp_priocntl_init
  3472 //
  3473 // Try to determine the priority scale for our process.
  3474 //
  3475 // Return errno or 0 if OK.
  3476 //
  3477 static int lwp_priocntl_init () {
  3478   int rslt;
  3479   pcinfo_t ClassInfo;
  3480   pcparms_t ParmInfo;
  3481   int i;
  3483   if (!UseThreadPriorities) return 0;
  3485   // We are using Bound threads, we need to determine our priority ranges
  3486   if (os::Solaris::T2_libthread() || UseBoundThreads) {
  3487     // If ThreadPriorityPolicy is 1, switch tables
  3488     if (ThreadPriorityPolicy == 1) {
  3489       for (i = 0 ; i < CriticalPriority+1; i++)
  3490         os::java_to_os_priority[i] = prio_policy1[i];
  3492     if (UseCriticalJavaThreadPriority) {
  3493       // MaxPriority always maps to the FX scheduling class and criticalPrio.
  3494       // See set_native_priority() and set_lwp_class_and_priority().
  3495       // Save original MaxPriority mapping in case attempt to
  3496       // use critical priority fails.
  3497       java_MaxPriority_to_os_priority = os::java_to_os_priority[MaxPriority];
  3498       // Set negative to distinguish from other priorities
  3499       os::java_to_os_priority[MaxPriority] = -criticalPrio;
  3502   // Not using Bound Threads, set to ThreadPolicy 1
  3503   else {
  3504     for ( i = 0 ; i < CriticalPriority+1; i++ ) {
  3505       os::java_to_os_priority[i] = prio_policy1[i];
  3507     return 0;
  3510   // Get IDs for a set of well-known scheduling classes.
  3511   // TODO-FIXME: GETCLINFO returns the current # of classes in the
  3512   // the system.  We should have a loop that iterates over the
  3513   // classID values, which are known to be "small" integers.
  3515   strcpy(ClassInfo.pc_clname, "TS");
  3516   ClassInfo.pc_cid = -1;
  3517   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
  3518   if (rslt < 0) return errno;
  3519   assert(ClassInfo.pc_cid != -1, "cid for TS class is -1");
  3520   tsLimits.schedPolicy = ClassInfo.pc_cid;
  3521   tsLimits.maxPrio = ((tsinfo_t*)ClassInfo.pc_clinfo)->ts_maxupri;
  3522   tsLimits.minPrio = -tsLimits.maxPrio;
  3524   strcpy(ClassInfo.pc_clname, "IA");
  3525   ClassInfo.pc_cid = -1;
  3526   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
  3527   if (rslt < 0) return errno;
  3528   assert(ClassInfo.pc_cid != -1, "cid for IA class is -1");
  3529   iaLimits.schedPolicy = ClassInfo.pc_cid;
  3530   iaLimits.maxPrio = ((iainfo_t*)ClassInfo.pc_clinfo)->ia_maxupri;
  3531   iaLimits.minPrio = -iaLimits.maxPrio;
  3533   strcpy(ClassInfo.pc_clname, "RT");
  3534   ClassInfo.pc_cid = -1;
  3535   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
  3536   if (rslt < 0) return errno;
  3537   assert(ClassInfo.pc_cid != -1, "cid for RT class is -1");
  3538   rtLimits.schedPolicy = ClassInfo.pc_cid;
  3539   rtLimits.maxPrio = ((rtinfo_t*)ClassInfo.pc_clinfo)->rt_maxpri;
  3540   rtLimits.minPrio = 0;
  3542   strcpy(ClassInfo.pc_clname, "FX");
  3543   ClassInfo.pc_cid = -1;
  3544   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
  3545   if (rslt < 0) return errno;
  3546   assert(ClassInfo.pc_cid != -1, "cid for FX class is -1");
  3547   fxLimits.schedPolicy = ClassInfo.pc_cid;
  3548   fxLimits.maxPrio = ((fxinfo_t*)ClassInfo.pc_clinfo)->fx_maxupri;
  3549   fxLimits.minPrio = 0;
  3551   // Query our "current" scheduling class.
  3552   // This will normally be IA, TS or, rarely, FX or RT.
  3553   memset(&ParmInfo, 0, sizeof(ParmInfo));
  3554   ParmInfo.pc_cid = PC_CLNULL;
  3555   rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo);
  3556   if (rslt < 0) return errno;
  3557   myClass = ParmInfo.pc_cid;
  3559   // We now know our scheduling classId, get specific information
  3560   // about the class.
  3561   ClassInfo.pc_cid = myClass;
  3562   ClassInfo.pc_clname[0] = 0;
  3563   rslt = priocntl((idtype)0, 0, PC_GETCLINFO, (caddr_t)&ClassInfo);
  3564   if (rslt < 0) return errno;
  3566   if (ThreadPriorityVerbose) {
  3567     tty->print_cr("lwp_priocntl_init: Class=%d(%s)...", myClass, ClassInfo.pc_clname);
  3570   memset(&ParmInfo, 0, sizeof(pcparms_t));
  3571   ParmInfo.pc_cid = PC_CLNULL;
  3572   rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo);
  3573   if (rslt < 0) return errno;
  3575   if (ParmInfo.pc_cid == rtLimits.schedPolicy) {
  3576     myMin = rtLimits.minPrio;
  3577     myMax = rtLimits.maxPrio;
  3578   } else if (ParmInfo.pc_cid == iaLimits.schedPolicy) {
  3579     iaparms_t *iaInfo  = (iaparms_t*)ParmInfo.pc_clparms;
  3580     myMin = iaLimits.minPrio;
  3581     myMax = iaLimits.maxPrio;
  3582     myMax = MIN2(myMax, (int)iaInfo->ia_uprilim);       // clamp - restrict
  3583   } else if (ParmInfo.pc_cid == tsLimits.schedPolicy) {
  3584     tsparms_t *tsInfo  = (tsparms_t*)ParmInfo.pc_clparms;
  3585     myMin = tsLimits.minPrio;
  3586     myMax = tsLimits.maxPrio;
  3587     myMax = MIN2(myMax, (int)tsInfo->ts_uprilim);       // clamp - restrict
  3588   } else if (ParmInfo.pc_cid == fxLimits.schedPolicy) {
  3589     fxparms_t *fxInfo = (fxparms_t*)ParmInfo.pc_clparms;
  3590     myMin = fxLimits.minPrio;
  3591     myMax = fxLimits.maxPrio;
  3592     myMax = MIN2(myMax, (int)fxInfo->fx_uprilim);       // clamp - restrict
  3593   } else {
  3594     // No clue - punt
  3595     if (ThreadPriorityVerbose)
  3596       tty->print_cr ("Unknown scheduling class: %s ... \n", ClassInfo.pc_clname);
  3597     return EINVAL;      // no clue, punt
  3600   if (ThreadPriorityVerbose) {
  3601     tty->print_cr ("Thread priority Range: [%d..%d]\n", myMin, myMax);
  3604   priocntl_enable = true;  // Enable changing priorities
  3605   return 0;
  3608 #define IAPRI(x)        ((iaparms_t *)((x).pc_clparms))
  3609 #define RTPRI(x)        ((rtparms_t *)((x).pc_clparms))
  3610 #define TSPRI(x)        ((tsparms_t *)((x).pc_clparms))
  3611 #define FXPRI(x)        ((fxparms_t *)((x).pc_clparms))
  3614 // scale_to_lwp_priority
  3615 //
  3616 // Convert from the libthread "thr_setprio" scale to our current
  3617 // lwp scheduling class scale.
  3618 //
  3619 static
  3620 int     scale_to_lwp_priority (int rMin, int rMax, int x)
  3622   int v;
  3624   if (x == 127) return rMax;            // avoid round-down
  3625     v = (((x*(rMax-rMin)))/128)+rMin;
  3626   return v;
  3630 // set_lwp_class_and_priority
  3631 //
  3632 // Set the class and priority of the lwp.  This call should only
  3633 // be made when using bound threads (T2 threads are bound by default).
  3634 //
  3635 int set_lwp_class_and_priority(int ThreadID, int lwpid,
  3636                                int newPrio, int new_class, bool scale) {
  3637   int rslt;
  3638   int Actual, Expected, prv;
  3639   pcparms_t ParmInfo;                   // for GET-SET
  3640 #ifdef ASSERT
  3641   pcparms_t ReadBack;                   // for readback
  3642 #endif
  3644   // Set priority via PC_GETPARMS, update, PC_SETPARMS
  3645   // Query current values.
  3646   // TODO: accelerate this by eliminating the PC_GETPARMS call.
  3647   // Cache "pcparms_t" in global ParmCache.
  3648   // TODO: elide set-to-same-value
  3650   // If something went wrong on init, don't change priorities.
  3651   if ( !priocntl_enable ) {
  3652     if (ThreadPriorityVerbose)
  3653       tty->print_cr("Trying to set priority but init failed, ignoring");
  3654     return EINVAL;
  3657   // If lwp hasn't started yet, just return
  3658   // the _start routine will call us again.
  3659   if ( lwpid <= 0 ) {
  3660     if (ThreadPriorityVerbose) {
  3661       tty->print_cr ("deferring the set_lwp_class_and_priority of thread "
  3662                      INTPTR_FORMAT " to %d, lwpid not set",
  3663                      ThreadID, newPrio);
  3665     return 0;
  3668   if (ThreadPriorityVerbose) {
  3669     tty->print_cr ("set_lwp_class_and_priority("
  3670                    INTPTR_FORMAT "@" INTPTR_FORMAT " %d) ",
  3671                    ThreadID, lwpid, newPrio);
  3674   memset(&ParmInfo, 0, sizeof(pcparms_t));
  3675   ParmInfo.pc_cid = PC_CLNULL;
  3676   rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ParmInfo);
  3677   if (rslt < 0) return errno;
  3679   int cur_class = ParmInfo.pc_cid;
  3680   ParmInfo.pc_cid = (id_t)new_class;
  3682   if (new_class == rtLimits.schedPolicy) {
  3683     rtparms_t *rtInfo  = (rtparms_t*)ParmInfo.pc_clparms;
  3684     rtInfo->rt_pri     = scale ? scale_to_lwp_priority(rtLimits.minPrio,
  3685                                                        rtLimits.maxPrio, newPrio)
  3686                                : newPrio;
  3687     rtInfo->rt_tqsecs  = RT_NOCHANGE;
  3688     rtInfo->rt_tqnsecs = RT_NOCHANGE;
  3689     if (ThreadPriorityVerbose) {
  3690       tty->print_cr("RT: %d->%d\n", newPrio, rtInfo->rt_pri);
  3692   } else if (new_class == iaLimits.schedPolicy) {
  3693     iaparms_t* iaInfo  = (iaparms_t*)ParmInfo.pc_clparms;
  3694     int maxClamped     = MIN2(iaLimits.maxPrio,
  3695                               cur_class == new_class
  3696                                 ? (int)iaInfo->ia_uprilim : iaLimits.maxPrio);
  3697     iaInfo->ia_upri    = scale ? scale_to_lwp_priority(iaLimits.minPrio,
  3698                                                        maxClamped, newPrio)
  3699                                : newPrio;
  3700     iaInfo->ia_uprilim = cur_class == new_class
  3701                            ? IA_NOCHANGE : (pri_t)iaLimits.maxPrio;
  3702     iaInfo->ia_mode    = IA_NOCHANGE;
  3703     if (ThreadPriorityVerbose) {
  3704       tty->print_cr("IA: [%d...%d] %d->%d\n",
  3705                     iaLimits.minPrio, maxClamped, newPrio, iaInfo->ia_upri);
  3707   } else if (new_class == tsLimits.schedPolicy) {
  3708     tsparms_t* tsInfo  = (tsparms_t*)ParmInfo.pc_clparms;
  3709     int maxClamped     = MIN2(tsLimits.maxPrio,
  3710                               cur_class == new_class
  3711                                 ? (int)tsInfo->ts_uprilim : tsLimits.maxPrio);
  3712     tsInfo->ts_upri    = scale ? scale_to_lwp_priority(tsLimits.minPrio,
  3713                                                        maxClamped, newPrio)
  3714                                : newPrio;
  3715     tsInfo->ts_uprilim = cur_class == new_class
  3716                            ? TS_NOCHANGE : (pri_t)tsLimits.maxPrio;
  3717     if (ThreadPriorityVerbose) {
  3718       tty->print_cr("TS: [%d...%d] %d->%d\n",
  3719                     tsLimits.minPrio, maxClamped, newPrio, tsInfo->ts_upri);
  3721   } else if (new_class == fxLimits.schedPolicy) {
  3722     fxparms_t* fxInfo  = (fxparms_t*)ParmInfo.pc_clparms;
  3723     int maxClamped     = MIN2(fxLimits.maxPrio,
  3724                               cur_class == new_class
  3725                                 ? (int)fxInfo->fx_uprilim : fxLimits.maxPrio);
  3726     fxInfo->fx_upri    = scale ? scale_to_lwp_priority(fxLimits.minPrio,
  3727                                                        maxClamped, newPrio)
  3728                                : newPrio;
  3729     fxInfo->fx_uprilim = cur_class == new_class
  3730                            ? FX_NOCHANGE : (pri_t)fxLimits.maxPrio;
  3731     fxInfo->fx_tqsecs  = FX_NOCHANGE;
  3732     fxInfo->fx_tqnsecs = FX_NOCHANGE;
  3733     if (ThreadPriorityVerbose) {
  3734       tty->print_cr("FX: [%d...%d] %d->%d\n",
  3735                     fxLimits.minPrio, maxClamped, newPrio, fxInfo->fx_upri);
  3737   } else {
  3738     if (ThreadPriorityVerbose) {
  3739       tty->print_cr("Unknown new scheduling class %d\n", new_class);
  3741     return EINVAL;    // no clue, punt
  3744   rslt = priocntl(P_LWPID, lwpid, PC_SETPARMS, (caddr_t)&ParmInfo);
  3745   if (ThreadPriorityVerbose && rslt) {
  3746     tty->print_cr ("PC_SETPARMS ->%d %d\n", rslt, errno);
  3748   if (rslt < 0) return errno;
  3750 #ifdef ASSERT
  3751   // Sanity check: read back what we just attempted to set.
  3752   // In theory it could have changed in the interim ...
  3753   //
  3754   // The priocntl system call is tricky.
  3755   // Sometimes it'll validate the priority value argument and
  3756   // return EINVAL if unhappy.  At other times it fails silently.
  3757   // Readbacks are prudent.
  3759   if (!ReadBackValidate) return 0;
  3761   memset(&ReadBack, 0, sizeof(pcparms_t));
  3762   ReadBack.pc_cid = PC_CLNULL;
  3763   rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ReadBack);
  3764   assert(rslt >= 0, "priocntl failed");
  3765   Actual = Expected = 0xBAD;
  3766   assert(ParmInfo.pc_cid == ReadBack.pc_cid, "cid's don't match");
  3767   if (ParmInfo.pc_cid == rtLimits.schedPolicy) {
  3768     Actual   = RTPRI(ReadBack)->rt_pri;
  3769     Expected = RTPRI(ParmInfo)->rt_pri;
  3770   } else if (ParmInfo.pc_cid == iaLimits.schedPolicy) {
  3771     Actual   = IAPRI(ReadBack)->ia_upri;
  3772     Expected = IAPRI(ParmInfo)->ia_upri;
  3773   } else if (ParmInfo.pc_cid == tsLimits.schedPolicy) {
  3774     Actual   = TSPRI(ReadBack)->ts_upri;
  3775     Expected = TSPRI(ParmInfo)->ts_upri;
  3776   } else if (ParmInfo.pc_cid == fxLimits.schedPolicy) {
  3777     Actual   = FXPRI(ReadBack)->fx_upri;
  3778     Expected = FXPRI(ParmInfo)->fx_upri;
  3779   } else {
  3780     if (ThreadPriorityVerbose) {
  3781       tty->print_cr("set_lwp_class_and_priority: unexpected class in readback: %d\n",
  3782                     ParmInfo.pc_cid);
  3786   if (Actual != Expected) {
  3787     if (ThreadPriorityVerbose) {
  3788       tty->print_cr ("set_lwp_class_and_priority(%d %d) Class=%d: actual=%d vs expected=%d\n",
  3789                      lwpid, newPrio, ReadBack.pc_cid, Actual, Expected);
  3792 #endif
  3794   return 0;
  3797 // Solaris only gives access to 128 real priorities at a time,
  3798 // so we expand Java's ten to fill this range.  This would be better
  3799 // if we dynamically adjusted relative priorities.
  3800 //
  3801 // The ThreadPriorityPolicy option allows us to select 2 different
  3802 // priority scales.
  3803 //
  3804 // ThreadPriorityPolicy=0
  3805 // Since the Solaris' default priority is MaximumPriority, we do not
  3806 // set a priority lower than Max unless a priority lower than
  3807 // NormPriority is requested.
  3808 //
  3809 // ThreadPriorityPolicy=1
  3810 // This mode causes the priority table to get filled with
  3811 // linear values.  NormPriority get's mapped to 50% of the
  3812 // Maximum priority an so on.  This will cause VM threads
  3813 // to get unfair treatment against other Solaris processes
  3814 // which do not explicitly alter their thread priorities.
  3815 //
  3817 int os::java_to_os_priority[CriticalPriority + 1] = {
  3818   -99999,         // 0 Entry should never be used
  3820   0,              // 1 MinPriority
  3821   32,             // 2
  3822   64,             // 3
  3824   96,             // 4
  3825   127,            // 5 NormPriority
  3826   127,            // 6
  3828   127,            // 7
  3829   127,            // 8
  3830   127,            // 9 NearMaxPriority
  3832   127,            // 10 MaxPriority
  3834   -criticalPrio   // 11 CriticalPriority
  3835 };
  3837 OSReturn os::set_native_priority(Thread* thread, int newpri) {
  3838   OSThread* osthread = thread->osthread();
  3840   // Save requested priority in case the thread hasn't been started
  3841   osthread->set_native_priority(newpri);
  3843   // Check for critical priority request
  3844   bool fxcritical = false;
  3845   if (newpri == -criticalPrio) {
  3846     fxcritical = true;
  3847     newpri = criticalPrio;
  3850   assert(newpri >= MinimumPriority && newpri <= MaximumPriority, "bad priority mapping");
  3851   if (!UseThreadPriorities) return OS_OK;
  3853   int status = 0;
  3855   if (!fxcritical) {
  3856     // Use thr_setprio only if we have a priority that thr_setprio understands
  3857     status = thr_setprio(thread->osthread()->thread_id(), newpri);
  3860   if (os::Solaris::T2_libthread() ||
  3861       (UseBoundThreads && osthread->is_vm_created())) {
  3862     int lwp_status =
  3863       set_lwp_class_and_priority(osthread->thread_id(),
  3864                                  osthread->lwp_id(),
  3865                                  newpri,
  3866                                  fxcritical ? fxLimits.schedPolicy : myClass,
  3867                                  !fxcritical);
  3868     if (lwp_status != 0 && fxcritical) {
  3869       // Try again, this time without changing the scheduling class
  3870       newpri = java_MaxPriority_to_os_priority;
  3871       lwp_status = set_lwp_class_and_priority(osthread->thread_id(),
  3872                                               osthread->lwp_id(),
  3873                                               newpri, myClass, false);
  3875     status |= lwp_status;
  3877   return (status == 0) ? OS_OK : OS_ERR;
  3881 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
  3882   int p;
  3883   if ( !UseThreadPriorities ) {
  3884     *priority_ptr = NormalPriority;
  3885     return OS_OK;
  3887   int status = thr_getprio(thread->osthread()->thread_id(), &p);
  3888   if (status != 0) {
  3889     return OS_ERR;
  3891   *priority_ptr = p;
  3892   return OS_OK;
  3896 // Hint to the underlying OS that a task switch would not be good.
  3897 // Void return because it's a hint and can fail.
  3898 void os::hint_no_preempt() {
  3899   schedctl_start(schedctl_init());
  3902 static void resume_clear_context(OSThread *osthread) {
  3903   osthread->set_ucontext(NULL);
  3906 static void suspend_save_context(OSThread *osthread, ucontext_t* context) {
  3907   osthread->set_ucontext(context);
  3910 static Semaphore sr_semaphore;
  3912 void os::Solaris::SR_handler(Thread* thread, ucontext_t* uc) {
  3913   // Save and restore errno to avoid confusing native code with EINTR
  3914   // after sigsuspend.
  3915   int old_errno = errno;
  3917   OSThread* osthread = thread->osthread();
  3918   assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
  3920   os::SuspendResume::State current = osthread->sr.state();
  3921   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
  3922     suspend_save_context(osthread, uc);
  3924     // attempt to switch the state, we assume we had a SUSPEND_REQUEST
  3925     os::SuspendResume::State state = osthread->sr.suspended();
  3926     if (state == os::SuspendResume::SR_SUSPENDED) {
  3927       sigset_t suspend_set;  // signals for sigsuspend()
  3929       // get current set of blocked signals and unblock resume signal
  3930       thr_sigsetmask(SIG_BLOCK, NULL, &suspend_set);
  3931       sigdelset(&suspend_set, os::Solaris::SIGasync());
  3933       sr_semaphore.signal();
  3934       // wait here until we are resumed
  3935       while (1) {
  3936         sigsuspend(&suspend_set);
  3938         os::SuspendResume::State result = osthread->sr.running();
  3939         if (result == os::SuspendResume::SR_RUNNING) {
  3940           sr_semaphore.signal();
  3941           break;
  3945     } else if (state == os::SuspendResume::SR_RUNNING) {
  3946       // request was cancelled, continue
  3947     } else {
  3948       ShouldNotReachHere();
  3951     resume_clear_context(osthread);
  3952   } else if (current == os::SuspendResume::SR_RUNNING) {
  3953     // request was cancelled, continue
  3954   } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
  3955     // ignore
  3956   } else {
  3957     // ignore
  3960   errno = old_errno;
  3964 void os::interrupt(Thread* thread) {
  3965   assert(Thread::current() == thread || Threads_lock->owned_by_self(), "possibility of dangling Thread pointer");
  3967   OSThread* osthread = thread->osthread();
  3969   int isInterrupted = osthread->interrupted();
  3970   if (!isInterrupted) {
  3971       osthread->set_interrupted(true);
  3972       OrderAccess::fence();
  3973       // os::sleep() is implemented with either poll (NULL,0,timeout) or
  3974       // by parking on _SleepEvent.  If the former, thr_kill will unwedge
  3975       // the sleeper by SIGINTR, otherwise the unpark() will wake the sleeper.
  3976       ParkEvent * const slp = thread->_SleepEvent ;
  3977       if (slp != NULL) slp->unpark() ;
  3980   // For JSR166:  unpark after setting status but before thr_kill -dl
  3981   if (thread->is_Java_thread()) {
  3982     ((JavaThread*)thread)->parker()->unpark();
  3985   // Handle interruptible wait() ...
  3986   ParkEvent * const ev = thread->_ParkEvent ;
  3987   if (ev != NULL) ev->unpark() ;
  3989   // When events are used everywhere for os::sleep, then this thr_kill
  3990   // will only be needed if UseVMInterruptibleIO is true.
  3992   if (!isInterrupted) {
  3993     int status = thr_kill(osthread->thread_id(), os::Solaris::SIGinterrupt());
  3994     assert_status(status == 0, status, "thr_kill");
  3996     // Bump thread interruption counter
  3997     RuntimeService::record_thread_interrupt_signaled_count();
  4002 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
  4003   assert(Thread::current() == thread || Threads_lock->owned_by_self(), "possibility of dangling Thread pointer");
  4005   OSThread* osthread = thread->osthread();
  4007   bool res = osthread->interrupted();
  4009   // NOTE that since there is no "lock" around these two operations,
  4010   // there is the possibility that the interrupted flag will be
  4011   // "false" but that the interrupt event will be set. This is
  4012   // intentional. The effect of this is that Object.wait() will appear
  4013   // to have a spurious wakeup, which is not harmful, and the
  4014   // possibility is so rare that it is not worth the added complexity
  4015   // to add yet another lock. It has also been recommended not to put
  4016   // the interrupted flag into the os::Solaris::Event structure,
  4017   // because it hides the issue.
  4018   if (res && clear_interrupted) {
  4019     osthread->set_interrupted(false);
  4021   return res;
  4025 void os::print_statistics() {
  4028 int os::message_box(const char* title, const char* message) {
  4029   int i;
  4030   fdStream err(defaultStream::error_fd());
  4031   for (i = 0; i < 78; i++) err.print_raw("=");
  4032   err.cr();
  4033   err.print_raw_cr(title);
  4034   for (i = 0; i < 78; i++) err.print_raw("-");
  4035   err.cr();
  4036   err.print_raw_cr(message);
  4037   for (i = 0; i < 78; i++) err.print_raw("=");
  4038   err.cr();
  4040   char buf[16];
  4041   // Prevent process from exiting upon "read error" without consuming all CPU
  4042   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
  4044   return buf[0] == 'y' || buf[0] == 'Y';
  4047 static int sr_notify(OSThread* osthread) {
  4048   int status = thr_kill(osthread->thread_id(), os::Solaris::SIGasync());
  4049   assert_status(status == 0, status, "thr_kill");
  4050   return status;
  4053 // "Randomly" selected value for how long we want to spin
  4054 // before bailing out on suspending a thread, also how often
  4055 // we send a signal to a thread we want to resume
  4056 static const int RANDOMLY_LARGE_INTEGER = 1000000;
  4057 static const int RANDOMLY_LARGE_INTEGER2 = 100;
  4059 static bool do_suspend(OSThread* osthread) {
  4060   assert(osthread->sr.is_running(), "thread should be running");
  4061   assert(!sr_semaphore.trywait(), "semaphore has invalid state");
  4063   // mark as suspended and send signal
  4064   if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
  4065     // failed to switch, state wasn't running?
  4066     ShouldNotReachHere();
  4067     return false;
  4070   if (sr_notify(osthread) != 0) {
  4071     ShouldNotReachHere();
  4074   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
  4075   while (true) {
  4076     if (sr_semaphore.timedwait(0, 2000 * NANOSECS_PER_MILLISEC)) {
  4077       break;
  4078     } else {
  4079       // timeout
  4080       os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
  4081       if (cancelled == os::SuspendResume::SR_RUNNING) {
  4082         return false;
  4083       } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
  4084         // make sure that we consume the signal on the semaphore as well
  4085         sr_semaphore.wait();
  4086         break;
  4087       } else {
  4088         ShouldNotReachHere();
  4089         return false;
  4094   guarantee(osthread->sr.is_suspended(), "Must be suspended");
  4095   return true;
  4098 static void do_resume(OSThread* osthread) {
  4099   assert(osthread->sr.is_suspended(), "thread should be suspended");
  4100   assert(!sr_semaphore.trywait(), "invalid semaphore state");
  4102   if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
  4103     // failed to switch to WAKEUP_REQUEST
  4104     ShouldNotReachHere();
  4105     return;
  4108   while (true) {
  4109     if (sr_notify(osthread) == 0) {
  4110       if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
  4111         if (osthread->sr.is_running()) {
  4112           return;
  4115     } else {
  4116       ShouldNotReachHere();
  4120   guarantee(osthread->sr.is_running(), "Must be running!");
  4123 void os::SuspendedThreadTask::internal_do_task() {
  4124   if (do_suspend(_thread->osthread())) {
  4125     SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
  4126     do_task(context);
  4127     do_resume(_thread->osthread());
  4131 class PcFetcher : public os::SuspendedThreadTask {
  4132 public:
  4133   PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
  4134   ExtendedPC result();
  4135 protected:
  4136   void do_task(const os::SuspendedThreadTaskContext& context);
  4137 private:
  4138   ExtendedPC _epc;
  4139 };
  4141 ExtendedPC PcFetcher::result() {
  4142   guarantee(is_done(), "task is not done yet.");
  4143   return _epc;
  4146 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
  4147   Thread* thread = context.thread();
  4148   OSThread* osthread = thread->osthread();
  4149   if (osthread->ucontext() != NULL) {
  4150     _epc = os::Solaris::ucontext_get_pc((ucontext_t *) context.ucontext());
  4151   } else {
  4152     // NULL context is unexpected, double-check this is the VMThread
  4153     guarantee(thread->is_VM_thread(), "can only be called for VMThread");
  4157 // A lightweight implementation that does not suspend the target thread and
  4158 // thus returns only a hint. Used for profiling only!
  4159 ExtendedPC os::get_thread_pc(Thread* thread) {
  4160   // Make sure that it is called by the watcher and the Threads lock is owned.
  4161   assert(Thread::current()->is_Watcher_thread(), "Must be watcher and own Threads_lock");
  4162   // For now, is only used to profile the VM Thread
  4163   assert(thread->is_VM_thread(), "Can only be called for VMThread");
  4164   PcFetcher fetcher(thread);
  4165   fetcher.run();
  4166   return fetcher.result();
  4170 // This does not do anything on Solaris. This is basically a hook for being
  4171 // able to use structured exception handling (thread-local exception filters) on, e.g., Win32.
  4172 void os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method, JavaCallArguments* args, Thread* thread) {
  4173   f(value, method, args, thread);
  4176 // This routine may be used by user applications as a "hook" to catch signals.
  4177 // The user-defined signal handler must pass unrecognized signals to this
  4178 // routine, and if it returns true (non-zero), then the signal handler must
  4179 // return immediately.  If the flag "abort_if_unrecognized" is true, then this
  4180 // routine will never retun false (zero), but instead will execute a VM panic
  4181 // routine kill the process.
  4182 //
  4183 // If this routine returns false, it is OK to call it again.  This allows
  4184 // the user-defined signal handler to perform checks either before or after
  4185 // the VM performs its own checks.  Naturally, the user code would be making
  4186 // a serious error if it tried to handle an exception (such as a null check
  4187 // or breakpoint) that the VM was generating for its own correct operation.
  4188 //
  4189 // This routine may recognize any of the following kinds of signals:
  4190 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, BREAK_SIGNAL, SIGPIPE, SIGXFSZ,
  4191 // os::Solaris::SIGasync
  4192 // It should be consulted by handlers for any of those signals.
  4193 // It explicitly does not recognize os::Solaris::SIGinterrupt
  4194 //
  4195 // The caller of this routine must pass in the three arguments supplied
  4196 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
  4197 // field of the structure passed to sigaction().  This routine assumes that
  4198 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
  4199 //
  4200 // Note that the VM will print warnings if it detects conflicting signal
  4201 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
  4202 //
  4203 extern "C" JNIEXPORT int
  4204 JVM_handle_solaris_signal(int signo, siginfo_t* siginfo, void* ucontext,
  4205                           int abort_if_unrecognized);
  4208 void signalHandler(int sig, siginfo_t* info, void* ucVoid) {
  4209   int orig_errno = errno;  // Preserve errno value over signal handler.
  4210   JVM_handle_solaris_signal(sig, info, ucVoid, true);
  4211   errno = orig_errno;
  4214 /* Do not delete - if guarantee is ever removed,  a signal handler (even empty)
  4215    is needed to provoke threads blocked on IO to return an EINTR
  4216    Note: this explicitly does NOT call JVM_handle_solaris_signal and
  4217    does NOT participate in signal chaining due to requirement for
  4218    NOT setting SA_RESTART to make EINTR work. */
  4219 extern "C" void sigINTRHandler(int sig, siginfo_t* info, void* ucVoid) {
  4220    if (UseSignalChaining) {
  4221       struct sigaction *actp = os::Solaris::get_chained_signal_action(sig);
  4222       if (actp && actp->sa_handler) {
  4223         vm_exit_during_initialization("Signal chaining detected for VM interrupt signal, try -XX:+UseAltSigs");
  4228 // This boolean allows users to forward their own non-matching signals
  4229 // to JVM_handle_solaris_signal, harmlessly.
  4230 bool os::Solaris::signal_handlers_are_installed = false;
  4232 // For signal-chaining
  4233 bool os::Solaris::libjsig_is_loaded = false;
  4234 typedef struct sigaction *(*get_signal_t)(int);
  4235 get_signal_t os::Solaris::get_signal_action = NULL;
  4237 struct sigaction* os::Solaris::get_chained_signal_action(int sig) {
  4238   struct sigaction *actp = NULL;
  4240   if ((libjsig_is_loaded)  && (sig <= Maxlibjsigsigs)) {
  4241     // Retrieve the old signal handler from libjsig
  4242     actp = (*get_signal_action)(sig);
  4244   if (actp == NULL) {
  4245     // Retrieve the preinstalled signal handler from jvm
  4246     actp = get_preinstalled_handler(sig);
  4249   return actp;
  4252 static bool call_chained_handler(struct sigaction *actp, int sig,
  4253                                  siginfo_t *siginfo, void *context) {
  4254   // Call the old signal handler
  4255   if (actp->sa_handler == SIG_DFL) {
  4256     // It's more reasonable to let jvm treat it as an unexpected exception
  4257     // instead of taking the default action.
  4258     return false;
  4259   } else if (actp->sa_handler != SIG_IGN) {
  4260     if ((actp->sa_flags & SA_NODEFER) == 0) {
  4261       // automaticlly block the signal
  4262       sigaddset(&(actp->sa_mask), sig);
  4265     sa_handler_t hand;
  4266     sa_sigaction_t sa;
  4267     bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
  4268     // retrieve the chained handler
  4269     if (siginfo_flag_set) {
  4270       sa = actp->sa_sigaction;
  4271     } else {
  4272       hand = actp->sa_handler;
  4275     if ((actp->sa_flags & SA_RESETHAND) != 0) {
  4276       actp->sa_handler = SIG_DFL;
  4279     // try to honor the signal mask
  4280     sigset_t oset;
  4281     thr_sigsetmask(SIG_SETMASK, &(actp->sa_mask), &oset);
  4283     // call into the chained handler
  4284     if (siginfo_flag_set) {
  4285       (*sa)(sig, siginfo, context);
  4286     } else {
  4287       (*hand)(sig);
  4290     // restore the signal mask
  4291     thr_sigsetmask(SIG_SETMASK, &oset, 0);
  4293   // Tell jvm's signal handler the signal is taken care of.
  4294   return true;
  4297 bool os::Solaris::chained_handler(int sig, siginfo_t* siginfo, void* context) {
  4298   bool chained = false;
  4299   // signal-chaining
  4300   if (UseSignalChaining) {
  4301     struct sigaction *actp = get_chained_signal_action(sig);
  4302     if (actp != NULL) {
  4303       chained = call_chained_handler(actp, sig, siginfo, context);
  4306   return chained;
  4309 struct sigaction* os::Solaris::get_preinstalled_handler(int sig) {
  4310   assert((chainedsigactions != (struct sigaction *)NULL) && (preinstalled_sigs != (int *)NULL) , "signals not yet initialized");
  4311   if (preinstalled_sigs[sig] != 0) {
  4312     return &chainedsigactions[sig];
  4314   return NULL;
  4317 void os::Solaris::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
  4319   assert(sig > 0 && sig <= Maxsignum, "vm signal out of expected range");
  4320   assert((chainedsigactions != (struct sigaction *)NULL) && (preinstalled_sigs != (int *)NULL) , "signals not yet initialized");
  4321   chainedsigactions[sig] = oldAct;
  4322   preinstalled_sigs[sig] = 1;
  4325 void os::Solaris::set_signal_handler(int sig, bool set_installed, bool oktochain) {
  4326   // Check for overwrite.
  4327   struct sigaction oldAct;
  4328   sigaction(sig, (struct sigaction*)NULL, &oldAct);
  4329   void* oldhand = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
  4330                                       : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
  4331   if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
  4332       oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
  4333       oldhand != CAST_FROM_FN_PTR(void*, signalHandler)) {
  4334     if (AllowUserSignalHandlers || !set_installed) {
  4335       // Do not overwrite; user takes responsibility to forward to us.
  4336       return;
  4337     } else if (UseSignalChaining) {
  4338       if (oktochain) {
  4339         // save the old handler in jvm
  4340         save_preinstalled_handler(sig, oldAct);
  4341       } else {
  4342         vm_exit_during_initialization("Signal chaining not allowed for VM interrupt signal, try -XX:+UseAltSigs.");
  4344       // libjsig also interposes the sigaction() call below and saves the
  4345       // old sigaction on it own.
  4346     } else {
  4347       fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
  4348                     "%#lx for signal %d.", (long)oldhand, sig));
  4352   struct sigaction sigAct;
  4353   sigfillset(&(sigAct.sa_mask));
  4354   sigAct.sa_handler = SIG_DFL;
  4356   sigAct.sa_sigaction = signalHandler;
  4357   // Handle SIGSEGV on alternate signal stack if
  4358   // not using stack banging
  4359   if (!UseStackBanging && sig == SIGSEGV) {
  4360     sigAct.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK;
  4361   // Interruptible i/o requires SA_RESTART cleared so EINTR
  4362   // is returned instead of restarting system calls
  4363   } else if (sig == os::Solaris::SIGinterrupt()) {
  4364     sigemptyset(&sigAct.sa_mask);
  4365     sigAct.sa_handler = NULL;
  4366     sigAct.sa_flags = SA_SIGINFO;
  4367     sigAct.sa_sigaction = sigINTRHandler;
  4368   } else {
  4369     sigAct.sa_flags = SA_SIGINFO | SA_RESTART;
  4371   os::Solaris::set_our_sigflags(sig, sigAct.sa_flags);
  4373   sigaction(sig, &sigAct, &oldAct);
  4375   void* oldhand2 = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
  4376                                        : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
  4377   assert(oldhand2 == oldhand, "no concurrent signal handler installation");
  4381 #define DO_SIGNAL_CHECK(sig) \
  4382   if (!sigismember(&check_signal_done, sig)) \
  4383     os::Solaris::check_signal_handler(sig)
  4385 // This method is a periodic task to check for misbehaving JNI applications
  4386 // under CheckJNI, we can add any periodic checks here
  4388 void os::run_periodic_checks() {
  4389   // A big source of grief is hijacking virt. addr 0x0 on Solaris,
  4390   // thereby preventing a NULL checks.
  4391   if(!check_addr0_done) check_addr0_done = check_addr0(tty);
  4393   if (check_signals == false) return;
  4395   // SEGV and BUS if overridden could potentially prevent
  4396   // generation of hs*.log in the event of a crash, debugging
  4397   // such a case can be very challenging, so we absolutely
  4398   // check for the following for a good measure:
  4399   DO_SIGNAL_CHECK(SIGSEGV);
  4400   DO_SIGNAL_CHECK(SIGILL);
  4401   DO_SIGNAL_CHECK(SIGFPE);
  4402   DO_SIGNAL_CHECK(SIGBUS);
  4403   DO_SIGNAL_CHECK(SIGPIPE);
  4404   DO_SIGNAL_CHECK(SIGXFSZ);
  4406   // ReduceSignalUsage allows the user to override these handlers
  4407   // see comments at the very top and jvm_solaris.h
  4408   if (!ReduceSignalUsage) {
  4409     DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
  4410     DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
  4411     DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
  4412     DO_SIGNAL_CHECK(BREAK_SIGNAL);
  4415   // See comments above for using JVM1/JVM2 and UseAltSigs
  4416   DO_SIGNAL_CHECK(os::Solaris::SIGinterrupt());
  4417   DO_SIGNAL_CHECK(os::Solaris::SIGasync());
  4421 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
  4423 static os_sigaction_t os_sigaction = NULL;
  4425 void os::Solaris::check_signal_handler(int sig) {
  4426   char buf[O_BUFLEN];
  4427   address jvmHandler = NULL;
  4429   struct sigaction act;
  4430   if (os_sigaction == NULL) {
  4431     // only trust the default sigaction, in case it has been interposed
  4432     os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
  4433     if (os_sigaction == NULL) return;
  4436   os_sigaction(sig, (struct sigaction*)NULL, &act);
  4438   address thisHandler = (act.sa_flags & SA_SIGINFO)
  4439     ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
  4440     : CAST_FROM_FN_PTR(address, act.sa_handler) ;
  4443   switch(sig) {
  4444     case SIGSEGV:
  4445     case SIGBUS:
  4446     case SIGFPE:
  4447     case SIGPIPE:
  4448     case SIGXFSZ:
  4449     case SIGILL:
  4450       jvmHandler = CAST_FROM_FN_PTR(address, signalHandler);
  4451       break;
  4453     case SHUTDOWN1_SIGNAL:
  4454     case SHUTDOWN2_SIGNAL:
  4455     case SHUTDOWN3_SIGNAL:
  4456     case BREAK_SIGNAL:
  4457       jvmHandler = (address)user_handler();
  4458       break;
  4460     default:
  4461       int intrsig = os::Solaris::SIGinterrupt();
  4462       int asynsig = os::Solaris::SIGasync();
  4464       if (sig == intrsig) {
  4465         jvmHandler = CAST_FROM_FN_PTR(address, sigINTRHandler);
  4466       } else if (sig == asynsig) {
  4467         jvmHandler = CAST_FROM_FN_PTR(address, signalHandler);
  4468       } else {
  4469         return;
  4471       break;
  4475   if (thisHandler != jvmHandler) {
  4476     tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
  4477     tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
  4478     tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
  4479     // No need to check this sig any longer
  4480     sigaddset(&check_signal_done, sig);
  4481     // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN
  4482     if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {
  4483       tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell",
  4484                     exception_name(sig, buf, O_BUFLEN));
  4486   } else if(os::Solaris::get_our_sigflags(sig) != 0 && act.sa_flags != os::Solaris::get_our_sigflags(sig)) {
  4487     tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
  4488     tty->print("expected:" PTR32_FORMAT, os::Solaris::get_our_sigflags(sig));
  4489     tty->print_cr("  found:" PTR32_FORMAT, act.sa_flags);
  4490     // No need to check this sig any longer
  4491     sigaddset(&check_signal_done, sig);
  4494   // Print all the signal handler state
  4495   if (sigismember(&check_signal_done, sig)) {
  4496     print_signal_handlers(tty, buf, O_BUFLEN);
  4501 void os::Solaris::install_signal_handlers() {
  4502   bool libjsigdone = false;
  4503   signal_handlers_are_installed = true;
  4505   // signal-chaining
  4506   typedef void (*signal_setting_t)();
  4507   signal_setting_t begin_signal_setting = NULL;
  4508   signal_setting_t end_signal_setting = NULL;
  4509   begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  4510                                         dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
  4511   if (begin_signal_setting != NULL) {
  4512     end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
  4513                                         dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
  4514     get_signal_action = CAST_TO_FN_PTR(get_signal_t,
  4515                                        dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
  4516     get_libjsig_version = CAST_TO_FN_PTR(version_getting_t,
  4517                                          dlsym(RTLD_DEFAULT, "JVM_get_libjsig_version"));
  4518     libjsig_is_loaded = true;
  4519     if (os::Solaris::get_libjsig_version != NULL) {
  4520       libjsigversion =  (*os::Solaris::get_libjsig_version)();
  4522     assert(UseSignalChaining, "should enable signal-chaining");
  4524   if (libjsig_is_loaded) {
  4525     // Tell libjsig jvm is setting signal handlers
  4526     (*begin_signal_setting)();
  4529   set_signal_handler(SIGSEGV, true, true);
  4530   set_signal_handler(SIGPIPE, true, true);
  4531   set_signal_handler(SIGXFSZ, true, true);
  4532   set_signal_handler(SIGBUS, true, true);
  4533   set_signal_handler(SIGILL, true, true);
  4534   set_signal_handler(SIGFPE, true, true);
  4537   if (os::Solaris::SIGinterrupt() > OLDMAXSIGNUM || os::Solaris::SIGasync() > OLDMAXSIGNUM) {
  4539     // Pre-1.4.1 Libjsig limited to signal chaining signals <= 32 so
  4540     // can not register overridable signals which might be > 32
  4541     if (libjsig_is_loaded && libjsigversion <= JSIG_VERSION_1_4_1) {
  4542     // Tell libjsig jvm has finished setting signal handlers
  4543       (*end_signal_setting)();
  4544       libjsigdone = true;
  4548   // Never ok to chain our SIGinterrupt
  4549   set_signal_handler(os::Solaris::SIGinterrupt(), true, false);
  4550   set_signal_handler(os::Solaris::SIGasync(), true, true);
  4552   if (libjsig_is_loaded && !libjsigdone) {
  4553     // Tell libjsig jvm finishes setting signal handlers
  4554     (*end_signal_setting)();
  4557   // We don't activate signal checker if libjsig is in place, we trust ourselves
  4558   // and if UserSignalHandler is installed all bets are off.
  4559   // Log that signal checking is off only if -verbose:jni is specified.
  4560   if (CheckJNICalls) {
  4561     if (libjsig_is_loaded) {
  4562       if (PrintJNIResolving) {
  4563         tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
  4565       check_signals = false;
  4567     if (AllowUserSignalHandlers) {
  4568       if (PrintJNIResolving) {
  4569         tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
  4571       check_signals = false;
  4577 void report_error(const char* file_name, int line_no, const char* title, const char* format, ...);
  4579 const char * signames[] = {
  4580   "SIG0",
  4581   "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP",
  4582   "SIGABRT", "SIGEMT", "SIGFPE", "SIGKILL", "SIGBUS",
  4583   "SIGSEGV", "SIGSYS", "SIGPIPE", "SIGALRM", "SIGTERM",
  4584   "SIGUSR1", "SIGUSR2", "SIGCLD", "SIGPWR", "SIGWINCH",
  4585   "SIGURG", "SIGPOLL", "SIGSTOP", "SIGTSTP", "SIGCONT",
  4586   "SIGTTIN", "SIGTTOU", "SIGVTALRM", "SIGPROF", "SIGXCPU",
  4587   "SIGXFSZ", "SIGWAITING", "SIGLWP", "SIGFREEZE", "SIGTHAW",
  4588   "SIGCANCEL", "SIGLOST"
  4589 };
  4591 const char* os::exception_name(int exception_code, char* buf, size_t size) {
  4592   if (0 < exception_code && exception_code <= SIGRTMAX) {
  4593     // signal
  4594     if (exception_code < sizeof(signames)/sizeof(const char*)) {
  4595        jio_snprintf(buf, size, "%s", signames[exception_code]);
  4596     } else {
  4597        jio_snprintf(buf, size, "SIG%d", exception_code);
  4599     return buf;
  4600   } else {
  4601     return NULL;
  4605 // (Static) wrappers for the new libthread API
  4606 int_fnP_thread_t_iP_uP_stack_tP_gregset_t os::Solaris::_thr_getstate;
  4607 int_fnP_thread_t_i_gregset_t os::Solaris::_thr_setstate;
  4608 int_fnP_thread_t_i os::Solaris::_thr_setmutator;
  4609 int_fnP_thread_t os::Solaris::_thr_suspend_mutator;
  4610 int_fnP_thread_t os::Solaris::_thr_continue_mutator;
  4612 // (Static) wrapper for getisax(2) call.
  4613 os::Solaris::getisax_func_t os::Solaris::_getisax = 0;
  4615 // (Static) wrappers for the liblgrp API
  4616 os::Solaris::lgrp_home_func_t os::Solaris::_lgrp_home;
  4617 os::Solaris::lgrp_init_func_t os::Solaris::_lgrp_init;
  4618 os::Solaris::lgrp_fini_func_t os::Solaris::_lgrp_fini;
  4619 os::Solaris::lgrp_root_func_t os::Solaris::_lgrp_root;
  4620 os::Solaris::lgrp_children_func_t os::Solaris::_lgrp_children;
  4621 os::Solaris::lgrp_resources_func_t os::Solaris::_lgrp_resources;
  4622 os::Solaris::lgrp_nlgrps_func_t os::Solaris::_lgrp_nlgrps;
  4623 os::Solaris::lgrp_cookie_stale_func_t os::Solaris::_lgrp_cookie_stale;
  4624 os::Solaris::lgrp_cookie_t os::Solaris::_lgrp_cookie = 0;
  4626 // (Static) wrapper for meminfo() call.
  4627 os::Solaris::meminfo_func_t os::Solaris::_meminfo = 0;
  4629 static address resolve_symbol_lazy(const char* name) {
  4630   address addr = (address) dlsym(RTLD_DEFAULT, name);
  4631   if(addr == NULL) {
  4632     // RTLD_DEFAULT was not defined on some early versions of 2.5.1
  4633     addr = (address) dlsym(RTLD_NEXT, name);
  4635   return addr;
  4638 static address resolve_symbol(const char* name) {
  4639   address addr = resolve_symbol_lazy(name);
  4640   if(addr == NULL) {
  4641     fatal(dlerror());
  4643   return addr;
  4648 // isT2_libthread()
  4649 //
  4650 // Routine to determine if we are currently using the new T2 libthread.
  4651 //
  4652 // We determine if we are using T2 by reading /proc/self/lstatus and
  4653 // looking for a thread with the ASLWP bit set.  If we find this status
  4654 // bit set, we must assume that we are NOT using T2.  The T2 team
  4655 // has approved this algorithm.
  4656 //
  4657 // We need to determine if we are running with the new T2 libthread
  4658 // since setting native thread priorities is handled differently
  4659 // when using this library.  All threads created using T2 are bound
  4660 // threads. Calling thr_setprio is meaningless in this case.
  4661 //
  4662 bool isT2_libthread() {
  4663   static prheader_t * lwpArray = NULL;
  4664   static int lwpSize = 0;
  4665   static int lwpFile = -1;
  4666   lwpstatus_t * that;
  4667   char lwpName [128];
  4668   bool isT2 = false;
  4670 #define ADR(x)  ((uintptr_t)(x))
  4671 #define LWPINDEX(ary,ix)   ((lwpstatus_t *)(((ary)->pr_entsize * (ix)) + (ADR((ary) + 1))))
  4673   lwpFile = ::open("/proc/self/lstatus", O_RDONLY, 0);
  4674   if (lwpFile < 0) {
  4675       if (ThreadPriorityVerbose) warning ("Couldn't open /proc/self/lstatus\n");
  4676       return false;
  4678   lwpSize = 16*1024;
  4679   for (;;) {
  4680     ::lseek64 (lwpFile, 0, SEEK_SET);
  4681     lwpArray = (prheader_t *)NEW_C_HEAP_ARRAY(char, lwpSize, mtInternal);
  4682     if (::read(lwpFile, lwpArray, lwpSize) < 0) {
  4683       if (ThreadPriorityVerbose) warning("Error reading /proc/self/lstatus\n");
  4684       break;
  4686     if ((lwpArray->pr_nent * lwpArray->pr_entsize) <= lwpSize) {
  4687        // We got a good snapshot - now iterate over the list.
  4688       int aslwpcount = 0;
  4689       for (int i = 0; i < lwpArray->pr_nent; i++ ) {
  4690         that = LWPINDEX(lwpArray,i);
  4691         if (that->pr_flags & PR_ASLWP) {
  4692           aslwpcount++;
  4695       if (aslwpcount == 0) isT2 = true;
  4696       break;
  4698     lwpSize = lwpArray->pr_nent * lwpArray->pr_entsize;
  4699     FREE_C_HEAP_ARRAY(char, lwpArray, mtInternal);  // retry.
  4702   FREE_C_HEAP_ARRAY(char, lwpArray, mtInternal);
  4703   ::close (lwpFile);
  4704   if (ThreadPriorityVerbose) {
  4705     if (isT2) tty->print_cr("We are running with a T2 libthread\n");
  4706     else tty->print_cr("We are not running with a T2 libthread\n");
  4708   return isT2;
  4712 void os::Solaris::libthread_init() {
  4713   address func = (address)dlsym(RTLD_DEFAULT, "_thr_suspend_allmutators");
  4715   // Determine if we are running with the new T2 libthread
  4716   os::Solaris::set_T2_libthread(isT2_libthread());
  4718   lwp_priocntl_init();
  4720   // RTLD_DEFAULT was not defined on some early versions of 5.5.1
  4721   if(func == NULL) {
  4722     func = (address) dlsym(RTLD_NEXT, "_thr_suspend_allmutators");
  4723     // Guarantee that this VM is running on an new enough OS (5.6 or
  4724     // later) that it will have a new enough libthread.so.
  4725     guarantee(func != NULL, "libthread.so is too old.");
  4728   // Initialize the new libthread getstate API wrappers
  4729   func = resolve_symbol("thr_getstate");
  4730   os::Solaris::set_thr_getstate(CAST_TO_FN_PTR(int_fnP_thread_t_iP_uP_stack_tP_gregset_t, func));
  4732   func = resolve_symbol("thr_setstate");
  4733   os::Solaris::set_thr_setstate(CAST_TO_FN_PTR(int_fnP_thread_t_i_gregset_t, func));
  4735   func = resolve_symbol("thr_setmutator");
  4736   os::Solaris::set_thr_setmutator(CAST_TO_FN_PTR(int_fnP_thread_t_i, func));
  4738   func = resolve_symbol("thr_suspend_mutator");
  4739   os::Solaris::set_thr_suspend_mutator(CAST_TO_FN_PTR(int_fnP_thread_t, func));
  4741   func = resolve_symbol("thr_continue_mutator");
  4742   os::Solaris::set_thr_continue_mutator(CAST_TO_FN_PTR(int_fnP_thread_t, func));
  4744   int size;
  4745   void (*handler_info_func)(address *, int *);
  4746   handler_info_func = CAST_TO_FN_PTR(void (*)(address *, int *), resolve_symbol("thr_sighndlrinfo"));
  4747   handler_info_func(&handler_start, &size);
  4748   handler_end = handler_start + size;
  4752 int_fnP_mutex_tP os::Solaris::_mutex_lock;
  4753 int_fnP_mutex_tP os::Solaris::_mutex_trylock;
  4754 int_fnP_mutex_tP os::Solaris::_mutex_unlock;
  4755 int_fnP_mutex_tP_i_vP os::Solaris::_mutex_init;
  4756 int_fnP_mutex_tP os::Solaris::_mutex_destroy;
  4757 int os::Solaris::_mutex_scope = USYNC_THREAD;
  4759 int_fnP_cond_tP_mutex_tP_timestruc_tP os::Solaris::_cond_timedwait;
  4760 int_fnP_cond_tP_mutex_tP os::Solaris::_cond_wait;
  4761 int_fnP_cond_tP os::Solaris::_cond_signal;
  4762 int_fnP_cond_tP os::Solaris::_cond_broadcast;
  4763 int_fnP_cond_tP_i_vP os::Solaris::_cond_init;
  4764 int_fnP_cond_tP os::Solaris::_cond_destroy;
  4765 int os::Solaris::_cond_scope = USYNC_THREAD;
  4767 void os::Solaris::synchronization_init() {
  4768   if(UseLWPSynchronization) {
  4769     os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_lock")));
  4770     os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_trylock")));
  4771     os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_unlock")));
  4772     os::Solaris::set_mutex_init(lwp_mutex_init);
  4773     os::Solaris::set_mutex_destroy(lwp_mutex_destroy);
  4774     os::Solaris::set_mutex_scope(USYNC_THREAD);
  4776     os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("_lwp_cond_timedwait")));
  4777     os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("_lwp_cond_wait")));
  4778     os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_signal")));
  4779     os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_broadcast")));
  4780     os::Solaris::set_cond_init(lwp_cond_init);
  4781     os::Solaris::set_cond_destroy(lwp_cond_destroy);
  4782     os::Solaris::set_cond_scope(USYNC_THREAD);
  4784   else {
  4785     os::Solaris::set_mutex_scope(USYNC_THREAD);
  4786     os::Solaris::set_cond_scope(USYNC_THREAD);
  4788     if(UsePthreads) {
  4789       os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_lock")));
  4790       os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_trylock")));
  4791       os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_unlock")));
  4792       os::Solaris::set_mutex_init(pthread_mutex_default_init);
  4793       os::Solaris::set_mutex_destroy(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_destroy")));
  4795       os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("pthread_cond_timedwait")));
  4796       os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("pthread_cond_wait")));
  4797       os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_signal")));
  4798       os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_broadcast")));
  4799       os::Solaris::set_cond_init(pthread_cond_default_init);
  4800       os::Solaris::set_cond_destroy(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_destroy")));
  4802     else {
  4803       os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_lock")));
  4804       os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_trylock")));
  4805       os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_unlock")));
  4806       os::Solaris::set_mutex_init(::mutex_init);
  4807       os::Solaris::set_mutex_destroy(::mutex_destroy);
  4809       os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("cond_timedwait")));
  4810       os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("cond_wait")));
  4811       os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_signal")));
  4812       os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_broadcast")));
  4813       os::Solaris::set_cond_init(::cond_init);
  4814       os::Solaris::set_cond_destroy(::cond_destroy);
  4819 bool os::Solaris::liblgrp_init() {
  4820   void *handle = dlopen("liblgrp.so.1", RTLD_LAZY);
  4821   if (handle != NULL) {
  4822     os::Solaris::set_lgrp_home(CAST_TO_FN_PTR(lgrp_home_func_t, dlsym(handle, "lgrp_home")));
  4823     os::Solaris::set_lgrp_init(CAST_TO_FN_PTR(lgrp_init_func_t, dlsym(handle, "lgrp_init")));
  4824     os::Solaris::set_lgrp_fini(CAST_TO_FN_PTR(lgrp_fini_func_t, dlsym(handle, "lgrp_fini")));
  4825     os::Solaris::set_lgrp_root(CAST_TO_FN_PTR(lgrp_root_func_t, dlsym(handle, "lgrp_root")));
  4826     os::Solaris::set_lgrp_children(CAST_TO_FN_PTR(lgrp_children_func_t, dlsym(handle, "lgrp_children")));
  4827     os::Solaris::set_lgrp_resources(CAST_TO_FN_PTR(lgrp_resources_func_t, dlsym(handle, "lgrp_resources")));
  4828     os::Solaris::set_lgrp_nlgrps(CAST_TO_FN_PTR(lgrp_nlgrps_func_t, dlsym(handle, "lgrp_nlgrps")));
  4829     os::Solaris::set_lgrp_cookie_stale(CAST_TO_FN_PTR(lgrp_cookie_stale_func_t,
  4830                                        dlsym(handle, "lgrp_cookie_stale")));
  4832     lgrp_cookie_t c = lgrp_init(LGRP_VIEW_CALLER);
  4833     set_lgrp_cookie(c);
  4834     return true;
  4836   return false;
  4839 void os::Solaris::misc_sym_init() {
  4840   address func;
  4842   // getisax
  4843   func = resolve_symbol_lazy("getisax");
  4844   if (func != NULL) {
  4845     os::Solaris::_getisax = CAST_TO_FN_PTR(getisax_func_t, func);
  4848   // meminfo
  4849   func = resolve_symbol_lazy("meminfo");
  4850   if (func != NULL) {
  4851     os::Solaris::set_meminfo(CAST_TO_FN_PTR(meminfo_func_t, func));
  4855 uint_t os::Solaris::getisax(uint32_t* array, uint_t n) {
  4856   assert(_getisax != NULL, "_getisax not set");
  4857   return _getisax(array, n);
  4860 // int pset_getloadavg(psetid_t pset, double loadavg[], int nelem);
  4861 typedef long (*pset_getloadavg_type)(psetid_t pset, double loadavg[], int nelem);
  4862 static pset_getloadavg_type pset_getloadavg_ptr = NULL;
  4864 void init_pset_getloadavg_ptr(void) {
  4865   pset_getloadavg_ptr =
  4866     (pset_getloadavg_type)dlsym(RTLD_DEFAULT, "pset_getloadavg");
  4867   if (PrintMiscellaneous && Verbose && pset_getloadavg_ptr == NULL) {
  4868     warning("pset_getloadavg function not found");
  4872 int os::Solaris::_dev_zero_fd = -1;
  4874 // this is called _before_ the global arguments have been parsed
  4875 void os::init(void) {
  4876   _initial_pid = getpid();
  4878   max_hrtime = first_hrtime = gethrtime();
  4880   init_random(1234567);
  4882   page_size = sysconf(_SC_PAGESIZE);
  4883   if (page_size == -1)
  4884     fatal(err_msg("os_solaris.cpp: os::init: sysconf failed (%s)",
  4885                   strerror(errno)));
  4886   init_page_sizes((size_t) page_size);
  4888   Solaris::initialize_system_info();
  4890   // Initialize misc. symbols as soon as possible, so we can use them
  4891   // if we need them.
  4892   Solaris::misc_sym_init();
  4894   int fd = ::open("/dev/zero", O_RDWR);
  4895   if (fd < 0) {
  4896     fatal(err_msg("os::init: cannot open /dev/zero (%s)", strerror(errno)));
  4897   } else {
  4898     Solaris::set_dev_zero_fd(fd);
  4900     // Close on exec, child won't inherit.
  4901     fcntl(fd, F_SETFD, FD_CLOEXEC);
  4904   clock_tics_per_sec = CLK_TCK;
  4906   // check if dladdr1() exists; dladdr1 can provide more information than
  4907   // dladdr for os::dll_address_to_function_name. It comes with SunOS 5.9
  4908   // and is available on linker patches for 5.7 and 5.8.
  4909   // libdl.so must have been loaded, this call is just an entry lookup
  4910   void * hdl = dlopen("libdl.so", RTLD_NOW);
  4911   if (hdl)
  4912     dladdr1_func = CAST_TO_FN_PTR(dladdr1_func_type, dlsym(hdl, "dladdr1"));
  4914   // (Solaris only) this switches to calls that actually do locking.
  4915   ThreadCritical::initialize();
  4917   main_thread = thr_self();
  4919   // Constant minimum stack size allowed. It must be at least
  4920   // the minimum of what the OS supports (thr_min_stack()), and
  4921   // enough to allow the thread to get to user bytecode execution.
  4922   Solaris::min_stack_allowed = MAX2(thr_min_stack(), Solaris::min_stack_allowed);
  4923   // If the pagesize of the VM is greater than 8K determine the appropriate
  4924   // number of initial guard pages.  The user can change this with the
  4925   // command line arguments, if needed.
  4926   if (vm_page_size() > 8*K) {
  4927     StackYellowPages = 1;
  4928     StackRedPages = 1;
  4929     StackShadowPages = round_to((StackShadowPages*8*K), vm_page_size()) / vm_page_size();
  4933 // To install functions for atexit system call
  4934 extern "C" {
  4935   static void perfMemory_exit_helper() {
  4936     perfMemory_exit();
  4940 // this is called _after_ the global arguments have been parsed
  4941 jint os::init_2(void) {
  4942   // try to enable extended file IO ASAP, see 6431278
  4943   os::Solaris::try_enable_extended_io();
  4945   // Allocate a single page and mark it as readable for safepoint polling.  Also
  4946   // use this first mmap call to check support for MAP_ALIGN.
  4947   address polling_page = (address)Solaris::mmap_chunk((char*)page_size,
  4948                                                       page_size,
  4949                                                       MAP_PRIVATE | MAP_ALIGN,
  4950                                                       PROT_READ);
  4951   if (polling_page == NULL) {
  4952     has_map_align = false;
  4953     polling_page = (address)Solaris::mmap_chunk(NULL, page_size, MAP_PRIVATE,
  4954                                                 PROT_READ);
  4957   os::set_polling_page(polling_page);
  4959 #ifndef PRODUCT
  4960   if( Verbose && PrintMiscellaneous )
  4961     tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
  4962 #endif
  4964   if (!UseMembar) {
  4965     address mem_serialize_page = (address)Solaris::mmap_chunk( NULL, page_size, MAP_PRIVATE, PROT_READ | PROT_WRITE );
  4966     guarantee( mem_serialize_page != NULL, "mmap Failed for memory serialize page");
  4967     os::set_memory_serialize_page( mem_serialize_page );
  4969 #ifndef PRODUCT
  4970     if(Verbose && PrintMiscellaneous)
  4971       tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
  4972 #endif
  4975   // Check minimum allowable stack size for thread creation and to initialize
  4976   // the java system classes, including StackOverflowError - depends on page
  4977   // size.  Add a page for compiler2 recursion in main thread.
  4978   // Add in 2*BytesPerWord times page size to account for VM stack during
  4979   // class initialization depending on 32 or 64 bit VM.
  4980   os::Solaris::min_stack_allowed = MAX2(os::Solaris::min_stack_allowed,
  4981             (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
  4982                     2*BytesPerWord COMPILER2_PRESENT(+1)) * page_size);
  4984   size_t threadStackSizeInBytes = ThreadStackSize * K;
  4985   if (threadStackSizeInBytes != 0 &&
  4986     threadStackSizeInBytes < os::Solaris::min_stack_allowed) {
  4987     tty->print_cr("\nThe stack size specified is too small, Specify at least %dk",
  4988                   os::Solaris::min_stack_allowed/K);
  4989     return JNI_ERR;
  4992   // For 64kbps there will be a 64kb page size, which makes
  4993   // the usable default stack size quite a bit less.  Increase the
  4994   // stack for 64kb (or any > than 8kb) pages, this increases
  4995   // virtual memory fragmentation (since we're not creating the
  4996   // stack on a power of 2 boundary.  The real fix for this
  4997   // should be to fix the guard page mechanism.
  4999   if (vm_page_size() > 8*K) {
  5000       threadStackSizeInBytes = (threadStackSizeInBytes != 0)
  5001          ? threadStackSizeInBytes +
  5002            ((StackYellowPages + StackRedPages) * vm_page_size())
  5003          : 0;
  5004       ThreadStackSize = threadStackSizeInBytes/K;
  5007   // Make the stack size a multiple of the page size so that
  5008   // the yellow/red zones can be guarded.
  5009   JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
  5010         vm_page_size()));
  5012   Solaris::libthread_init();
  5014   if (UseNUMA) {
  5015     if (!Solaris::liblgrp_init()) {
  5016       UseNUMA = false;
  5017     } else {
  5018       size_t lgrp_limit = os::numa_get_groups_num();
  5019       int *lgrp_ids = NEW_C_HEAP_ARRAY(int, lgrp_limit, mtInternal);
  5020       size_t lgrp_num = os::numa_get_leaf_groups(lgrp_ids, lgrp_limit);
  5021       FREE_C_HEAP_ARRAY(int, lgrp_ids, mtInternal);
  5022       if (lgrp_num < 2) {
  5023         // There's only one locality group, disable NUMA.
  5024         UseNUMA = false;
  5027     if (!UseNUMA && ForceNUMA) {
  5028       UseNUMA = true;
  5032   Solaris::signal_sets_init();
  5033   Solaris::init_signal_mem();
  5034   Solaris::install_signal_handlers();
  5036   if (libjsigversion < JSIG_VERSION_1_4_1) {
  5037     Maxlibjsigsigs = OLDMAXSIGNUM;
  5040   // initialize synchronization primitives to use either thread or
  5041   // lwp synchronization (controlled by UseLWPSynchronization)
  5042   Solaris::synchronization_init();
  5044   if (MaxFDLimit) {
  5045     // set the number of file descriptors to max. print out error
  5046     // if getrlimit/setrlimit fails but continue regardless.
  5047     struct rlimit nbr_files;
  5048     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
  5049     if (status != 0) {
  5050       if (PrintMiscellaneous && (Verbose || WizardMode))
  5051         perror("os::init_2 getrlimit failed");
  5052     } else {
  5053       nbr_files.rlim_cur = nbr_files.rlim_max;
  5054       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
  5055       if (status != 0) {
  5056         if (PrintMiscellaneous && (Verbose || WizardMode))
  5057           perror("os::init_2 setrlimit failed");
  5062   // Calculate theoretical max. size of Threads to guard gainst
  5063   // artifical out-of-memory situations, where all available address-
  5064   // space has been reserved by thread stacks. Default stack size is 1Mb.
  5065   size_t pre_thread_stack_size = (JavaThread::stack_size_at_create()) ?
  5066     JavaThread::stack_size_at_create() : (1*K*K);
  5067   assert(pre_thread_stack_size != 0, "Must have a stack");
  5068   // Solaris has a maximum of 4Gb of user programs. Calculate the thread limit when
  5069   // we should start doing Virtual Memory banging. Currently when the threads will
  5070   // have used all but 200Mb of space.
  5071   size_t max_address_space = ((unsigned int)4 * K * K * K) - (200 * K * K);
  5072   Solaris::_os_thread_limit = max_address_space / pre_thread_stack_size;
  5074   // at-exit methods are called in the reverse order of their registration.
  5075   // In Solaris 7 and earlier, atexit functions are called on return from
  5076   // main or as a result of a call to exit(3C). There can be only 32 of
  5077   // these functions registered and atexit() does not set errno. In Solaris
  5078   // 8 and later, there is no limit to the number of functions registered
  5079   // and atexit() sets errno. In addition, in Solaris 8 and later, atexit
  5080   // functions are called upon dlclose(3DL) in addition to return from main
  5081   // and exit(3C).
  5083   if (PerfAllowAtExitRegistration) {
  5084     // only register atexit functions if PerfAllowAtExitRegistration is set.
  5085     // atexit functions can be delayed until process exit time, which
  5086     // can be problematic for embedded VM situations. Embedded VMs should
  5087     // call DestroyJavaVM() to assure that VM resources are released.
  5089     // note: perfMemory_exit_helper atexit function may be removed in
  5090     // the future if the appropriate cleanup code can be added to the
  5091     // VM_Exit VMOperation's doit method.
  5092     if (atexit(perfMemory_exit_helper) != 0) {
  5093       warning("os::init2 atexit(perfMemory_exit_helper) failed");
  5097   // Init pset_loadavg function pointer
  5098   init_pset_getloadavg_ptr();
  5100   return JNI_OK;
  5103 // Mark the polling page as unreadable
  5104 void os::make_polling_page_unreadable(void) {
  5105   if( mprotect((char *)_polling_page, page_size, PROT_NONE) != 0 )
  5106     fatal("Could not disable polling page");
  5107 };
  5109 // Mark the polling page as readable
  5110 void os::make_polling_page_readable(void) {
  5111   if( mprotect((char *)_polling_page, page_size, PROT_READ) != 0 )
  5112     fatal("Could not enable polling page");
  5113 };
  5115 // OS interface.
  5117 bool os::check_heap(bool force) { return true; }
  5119 typedef int (*vsnprintf_t)(char* buf, size_t count, const char* fmt, va_list argptr);
  5120 static vsnprintf_t sol_vsnprintf = NULL;
  5122 int local_vsnprintf(char* buf, size_t count, const char* fmt, va_list argptr) {
  5123   if (!sol_vsnprintf) {
  5124     //search  for the named symbol in the objects that were loaded after libjvm
  5125     void* where = RTLD_NEXT;
  5126     if ((sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "__vsnprintf"))) == NULL)
  5127         sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "vsnprintf"));
  5128     if (!sol_vsnprintf){
  5129       //search  for the named symbol in the objects that were loaded before libjvm
  5130       where = RTLD_DEFAULT;
  5131       if ((sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "__vsnprintf"))) == NULL)
  5132         sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "vsnprintf"));
  5133       assert(sol_vsnprintf != NULL, "vsnprintf not found");
  5136   return (*sol_vsnprintf)(buf, count, fmt, argptr);
  5140 // Is a (classpath) directory empty?
  5141 bool os::dir_is_empty(const char* path) {
  5142   DIR *dir = NULL;
  5143   struct dirent *ptr;
  5145   dir = opendir(path);
  5146   if (dir == NULL) return true;
  5148   /* Scan the directory */
  5149   bool result = true;
  5150   char buf[sizeof(struct dirent) + MAX_PATH];
  5151   struct dirent *dbuf = (struct dirent *) buf;
  5152   while (result && (ptr = readdir(dir, dbuf)) != NULL) {
  5153     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
  5154       result = false;
  5157   closedir(dir);
  5158   return result;
  5161 // This code originates from JDK's sysOpen and open64_w
  5162 // from src/solaris/hpi/src/system_md.c
  5164 #ifndef O_DELETE
  5165 #define O_DELETE 0x10000
  5166 #endif
  5168 // Open a file. Unlink the file immediately after open returns
  5169 // if the specified oflag has the O_DELETE flag set.
  5170 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
  5172 int os::open(const char *path, int oflag, int mode) {
  5173   if (strlen(path) > MAX_PATH - 1) {
  5174     errno = ENAMETOOLONG;
  5175     return -1;
  5177   int fd;
  5178   int o_delete = (oflag & O_DELETE);
  5179   oflag = oflag & ~O_DELETE;
  5181   fd = ::open64(path, oflag, mode);
  5182   if (fd == -1) return -1;
  5184   //If the open succeeded, the file might still be a directory
  5186     struct stat64 buf64;
  5187     int ret = ::fstat64(fd, &buf64);
  5188     int st_mode = buf64.st_mode;
  5190     if (ret != -1) {
  5191       if ((st_mode & S_IFMT) == S_IFDIR) {
  5192         errno = EISDIR;
  5193         ::close(fd);
  5194         return -1;
  5196     } else {
  5197       ::close(fd);
  5198       return -1;
  5201     /*
  5202      * 32-bit Solaris systems suffer from:
  5204      * - an historical default soft limit of 256 per-process file
  5205      *   descriptors that is too low for many Java programs.
  5207      * - a design flaw where file descriptors created using stdio
  5208      *   fopen must be less than 256, _even_ when the first limit above
  5209      *   has been raised.  This can cause calls to fopen (but not calls to
  5210      *   open, for example) to fail mysteriously, perhaps in 3rd party
  5211      *   native code (although the JDK itself uses fopen).  One can hardly
  5212      *   criticize them for using this most standard of all functions.
  5214      * We attempt to make everything work anyways by:
  5216      * - raising the soft limit on per-process file descriptors beyond
  5217      *   256
  5219      * - As of Solaris 10u4, we can request that Solaris raise the 256
  5220      *   stdio fopen limit by calling function enable_extended_FILE_stdio.
  5221      *   This is done in init_2 and recorded in enabled_extended_FILE_stdio
  5223      * - If we are stuck on an old (pre 10u4) Solaris system, we can
  5224      *   workaround the bug by remapping non-stdio file descriptors below
  5225      *   256 to ones beyond 256, which is done below.
  5227      * See:
  5228      * 1085341: 32-bit stdio routines should support file descriptors >255
  5229      * 6533291: Work around 32-bit Solaris stdio limit of 256 open files
  5230      * 6431278: Netbeans crash on 32 bit Solaris: need to call
  5231      *          enable_extended_FILE_stdio() in VM initialisation
  5232      * Giri Mandalika's blog
  5233      * http://technopark02.blogspot.com/2005_05_01_archive.html
  5234      */
  5235 #ifndef  _LP64
  5236      if ((!enabled_extended_FILE_stdio) && fd < 256) {
  5237          int newfd = ::fcntl(fd, F_DUPFD, 256);
  5238          if (newfd != -1) {
  5239              ::close(fd);
  5240              fd = newfd;
  5243 #endif // 32-bit Solaris
  5244     /*
  5245      * All file descriptors that are opened in the JVM and not
  5246      * specifically destined for a subprocess should have the
  5247      * close-on-exec flag set.  If we don't set it, then careless 3rd
  5248      * party native code might fork and exec without closing all
  5249      * appropriate file descriptors (e.g. as we do in closeDescriptors in
  5250      * UNIXProcess.c), and this in turn might:
  5252      * - cause end-of-file to fail to be detected on some file
  5253      *   descriptors, resulting in mysterious hangs, or
  5255      * - might cause an fopen in the subprocess to fail on a system
  5256      *   suffering from bug 1085341.
  5258      * (Yes, the default setting of the close-on-exec flag is a Unix
  5259      * design flaw)
  5261      * See:
  5262      * 1085341: 32-bit stdio routines should support file descriptors >255
  5263      * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
  5264      * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
  5265      */
  5266 #ifdef FD_CLOEXEC
  5268         int flags = ::fcntl(fd, F_GETFD);
  5269         if (flags != -1)
  5270             ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
  5272 #endif
  5274   if (o_delete != 0) {
  5275     ::unlink(path);
  5277   return fd;
  5280 // create binary file, rewriting existing file if required
  5281 int os::create_binary_file(const char* path, bool rewrite_existing) {
  5282   int oflags = O_WRONLY | O_CREAT;
  5283   if (!rewrite_existing) {
  5284     oflags |= O_EXCL;
  5286   return ::open64(path, oflags, S_IREAD | S_IWRITE);
  5289 // return current position of file pointer
  5290 jlong os::current_file_offset(int fd) {
  5291   return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);
  5294 // move file pointer to the specified offset
  5295 jlong os::seek_to_file_offset(int fd, jlong offset) {
  5296   return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);
  5299 jlong os::lseek(int fd, jlong offset, int whence) {
  5300   return (jlong) ::lseek64(fd, offset, whence);
  5303 char * os::native_path(char *path) {
  5304   return path;
  5307 int os::ftruncate(int fd, jlong length) {
  5308   return ::ftruncate64(fd, length);
  5311 int os::fsync(int fd)  {
  5312   RESTARTABLE_RETURN_INT(::fsync(fd));
  5315 int os::available(int fd, jlong *bytes) {
  5316   jlong cur, end;
  5317   int mode;
  5318   struct stat64 buf64;
  5320   if (::fstat64(fd, &buf64) >= 0) {
  5321     mode = buf64.st_mode;
  5322     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
  5323       /*
  5324       * XXX: is the following call interruptible? If so, this might
  5325       * need to go through the INTERRUPT_IO() wrapper as for other
  5326       * blocking, interruptible calls in this file.
  5327       */
  5328       int n,ioctl_return;
  5330       INTERRUPTIBLE(::ioctl(fd, FIONREAD, &n),ioctl_return,os::Solaris::clear_interrupted);
  5331       if (ioctl_return>= 0) {
  5332           *bytes = n;
  5333         return 1;
  5337   if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {
  5338     return 0;
  5339   } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {
  5340     return 0;
  5341   } else if (::lseek64(fd, cur, SEEK_SET) == -1) {
  5342     return 0;
  5344   *bytes = end - cur;
  5345   return 1;
  5348 // Map a block of memory.
  5349 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
  5350                      char *addr, size_t bytes, bool read_only,
  5351                      bool allow_exec) {
  5352   int prot;
  5353   int flags;
  5355   if (read_only) {
  5356     prot = PROT_READ;
  5357     flags = MAP_SHARED;
  5358   } else {
  5359     prot = PROT_READ | PROT_WRITE;
  5360     flags = MAP_PRIVATE;
  5363   if (allow_exec) {
  5364     prot |= PROT_EXEC;
  5367   if (addr != NULL) {
  5368     flags |= MAP_FIXED;
  5371   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
  5372                                      fd, file_offset);
  5373   if (mapped_address == MAP_FAILED) {
  5374     return NULL;
  5376   return mapped_address;
  5380 // Remap a block of memory.
  5381 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
  5382                        char *addr, size_t bytes, bool read_only,
  5383                        bool allow_exec) {
  5384   // same as map_memory() on this OS
  5385   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
  5386                         allow_exec);
  5390 // Unmap a block of memory.
  5391 bool os::pd_unmap_memory(char* addr, size_t bytes) {
  5392   return munmap(addr, bytes) == 0;
  5395 void os::pause() {
  5396   char filename[MAX_PATH];
  5397   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
  5398     jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
  5399   } else {
  5400     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
  5403   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  5404   if (fd != -1) {
  5405     struct stat buf;
  5406     ::close(fd);
  5407     while (::stat(filename, &buf) == 0) {
  5408       (void)::poll(NULL, 0, 100);
  5410   } else {
  5411     jio_fprintf(stderr,
  5412       "Could not open pause file '%s', continuing immediately.\n", filename);
  5416 #ifndef PRODUCT
  5417 #ifdef INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS
  5418 // Turn this on if you need to trace synch operations.
  5419 // Set RECORD_SYNCH_LIMIT to a large-enough value,
  5420 // and call record_synch_enable and record_synch_disable
  5421 // around the computation of interest.
  5423 void record_synch(char* name, bool returning);  // defined below
  5425 class RecordSynch {
  5426   char* _name;
  5427  public:
  5428   RecordSynch(char* name) :_name(name)
  5429                  { record_synch(_name, false); }
  5430   ~RecordSynch() { record_synch(_name,   true);  }
  5431 };
  5433 #define CHECK_SYNCH_OP(ret, name, params, args, inner)          \
  5434 extern "C" ret name params {                                    \
  5435   typedef ret name##_t params;                                  \
  5436   static name##_t* implem = NULL;                               \
  5437   static int callcount = 0;                                     \
  5438   if (implem == NULL) {                                         \
  5439     implem = (name##_t*) dlsym(RTLD_NEXT, #name);               \
  5440     if (implem == NULL)  fatal(dlerror());                      \
  5441   }                                                             \
  5442   ++callcount;                                                  \
  5443   RecordSynch _rs(#name);                                       \
  5444   inner;                                                        \
  5445   return implem args;                                           \
  5447 // in dbx, examine callcounts this way:
  5448 // for n in $(eval whereis callcount | awk '{print $2}'); do print $n; done
  5450 #define CHECK_POINTER_OK(p) \
  5451   (!Universe::is_fully_initialized() || !Universe::is_reserved_heap((oop)(p)))
  5452 #define CHECK_MU \
  5453   if (!CHECK_POINTER_OK(mu)) fatal("Mutex must be in C heap only.");
  5454 #define CHECK_CV \
  5455   if (!CHECK_POINTER_OK(cv)) fatal("Condvar must be in C heap only.");
  5456 #define CHECK_P(p) \
  5457   if (!CHECK_POINTER_OK(p))  fatal(false,  "Pointer must be in C heap only.");
  5459 #define CHECK_MUTEX(mutex_op) \
  5460 CHECK_SYNCH_OP(int, mutex_op, (mutex_t *mu), (mu), CHECK_MU);
  5462 CHECK_MUTEX(   mutex_lock)
  5463 CHECK_MUTEX(  _mutex_lock)
  5464 CHECK_MUTEX( mutex_unlock)
  5465 CHECK_MUTEX(_mutex_unlock)
  5466 CHECK_MUTEX( mutex_trylock)
  5467 CHECK_MUTEX(_mutex_trylock)
  5469 #define CHECK_COND(cond_op) \
  5470 CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu), (cv, mu), CHECK_MU;CHECK_CV);
  5472 CHECK_COND( cond_wait);
  5473 CHECK_COND(_cond_wait);
  5474 CHECK_COND(_cond_wait_cancel);
  5476 #define CHECK_COND2(cond_op) \
  5477 CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu, timestruc_t* ts), (cv, mu, ts), CHECK_MU;CHECK_CV);
  5479 CHECK_COND2( cond_timedwait);
  5480 CHECK_COND2(_cond_timedwait);
  5481 CHECK_COND2(_cond_timedwait_cancel);
  5483 // do the _lwp_* versions too
  5484 #define mutex_t lwp_mutex_t
  5485 #define cond_t  lwp_cond_t
  5486 CHECK_MUTEX(  _lwp_mutex_lock)
  5487 CHECK_MUTEX(  _lwp_mutex_unlock)
  5488 CHECK_MUTEX(  _lwp_mutex_trylock)
  5489 CHECK_MUTEX( __lwp_mutex_lock)
  5490 CHECK_MUTEX( __lwp_mutex_unlock)
  5491 CHECK_MUTEX( __lwp_mutex_trylock)
  5492 CHECK_MUTEX(___lwp_mutex_lock)
  5493 CHECK_MUTEX(___lwp_mutex_unlock)
  5495 CHECK_COND(  _lwp_cond_wait);
  5496 CHECK_COND( __lwp_cond_wait);
  5497 CHECK_COND(___lwp_cond_wait);
  5499 CHECK_COND2(  _lwp_cond_timedwait);
  5500 CHECK_COND2( __lwp_cond_timedwait);
  5501 #undef mutex_t
  5502 #undef cond_t
  5504 CHECK_SYNCH_OP(int, _lwp_suspend2,       (int lwp, int *n), (lwp, n), 0);
  5505 CHECK_SYNCH_OP(int,__lwp_suspend2,       (int lwp, int *n), (lwp, n), 0);
  5506 CHECK_SYNCH_OP(int, _lwp_kill,           (int lwp, int n),  (lwp, n), 0);
  5507 CHECK_SYNCH_OP(int,__lwp_kill,           (int lwp, int n),  (lwp, n), 0);
  5508 CHECK_SYNCH_OP(int, _lwp_sema_wait,      (lwp_sema_t* p),   (p),  CHECK_P(p));
  5509 CHECK_SYNCH_OP(int,__lwp_sema_wait,      (lwp_sema_t* p),   (p),  CHECK_P(p));
  5510 CHECK_SYNCH_OP(int, _lwp_cond_broadcast, (lwp_cond_t* cv),  (cv), CHECK_CV);
  5511 CHECK_SYNCH_OP(int,__lwp_cond_broadcast, (lwp_cond_t* cv),  (cv), CHECK_CV);
  5514 // recording machinery:
  5516 enum { RECORD_SYNCH_LIMIT = 200 };
  5517 char* record_synch_name[RECORD_SYNCH_LIMIT];
  5518 void* record_synch_arg0ptr[RECORD_SYNCH_LIMIT];
  5519 bool record_synch_returning[RECORD_SYNCH_LIMIT];
  5520 thread_t record_synch_thread[RECORD_SYNCH_LIMIT];
  5521 int record_synch_count = 0;
  5522 bool record_synch_enabled = false;
  5524 // in dbx, examine recorded data this way:
  5525 // for n in name arg0ptr returning thread; do print record_synch_$n[0..record_synch_count-1]; done
  5527 void record_synch(char* name, bool returning) {
  5528   if (record_synch_enabled) {
  5529     if (record_synch_count < RECORD_SYNCH_LIMIT) {
  5530       record_synch_name[record_synch_count] = name;
  5531       record_synch_returning[record_synch_count] = returning;
  5532       record_synch_thread[record_synch_count] = thr_self();
  5533       record_synch_arg0ptr[record_synch_count] = &name;
  5534       record_synch_count++;
  5536     // put more checking code here:
  5537     // ...
  5541 void record_synch_enable() {
  5542   // start collecting trace data, if not already doing so
  5543   if (!record_synch_enabled)  record_synch_count = 0;
  5544   record_synch_enabled = true;
  5547 void record_synch_disable() {
  5548   // stop collecting trace data
  5549   record_synch_enabled = false;
  5552 #endif // INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS
  5553 #endif // PRODUCT
  5555 const intptr_t thr_time_off  = (intptr_t)(&((prusage_t *)(NULL))->pr_utime);
  5556 const intptr_t thr_time_size = (intptr_t)(&((prusage_t *)(NULL))->pr_ttime) -
  5557                                (intptr_t)(&((prusage_t *)(NULL))->pr_utime);
  5560 // JVMTI & JVM monitoring and management support
  5561 // The thread_cpu_time() and current_thread_cpu_time() are only
  5562 // supported if is_thread_cpu_time_supported() returns true.
  5563 // They are not supported on Solaris T1.
  5565 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
  5566 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
  5567 // of a thread.
  5568 //
  5569 // current_thread_cpu_time() and thread_cpu_time(Thread *)
  5570 // returns the fast estimate available on the platform.
  5572 // hrtime_t gethrvtime() return value includes
  5573 // user time but does not include system time
  5574 jlong os::current_thread_cpu_time() {
  5575   return (jlong) gethrvtime();
  5578 jlong os::thread_cpu_time(Thread *thread) {
  5579   // return user level CPU time only to be consistent with
  5580   // what current_thread_cpu_time returns.
  5581   // thread_cpu_time_info() must be changed if this changes
  5582   return os::thread_cpu_time(thread, false /* user time only */);
  5585 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
  5586   if (user_sys_cpu_time) {
  5587     return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
  5588   } else {
  5589     return os::current_thread_cpu_time();
  5593 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
  5594   char proc_name[64];
  5595   int count;
  5596   prusage_t prusage;
  5597   jlong lwp_time;
  5598   int fd;
  5600   sprintf(proc_name, "/proc/%d/lwp/%d/lwpusage",
  5601                      getpid(),
  5602                      thread->osthread()->lwp_id());
  5603   fd = ::open(proc_name, O_RDONLY);
  5604   if ( fd == -1 ) return -1;
  5606   do {
  5607     count = ::pread(fd,
  5608                   (void *)&prusage.pr_utime,
  5609                   thr_time_size,
  5610                   thr_time_off);
  5611   } while (count < 0 && errno == EINTR);
  5612   ::close(fd);
  5613   if ( count < 0 ) return -1;
  5615   if (user_sys_cpu_time) {
  5616     // user + system CPU time
  5617     lwp_time = (((jlong)prusage.pr_stime.tv_sec +
  5618                  (jlong)prusage.pr_utime.tv_sec) * (jlong)1000000000) +
  5619                  (jlong)prusage.pr_stime.tv_nsec +
  5620                  (jlong)prusage.pr_utime.tv_nsec;
  5621   } else {
  5622     // user level CPU time only
  5623     lwp_time = ((jlong)prusage.pr_utime.tv_sec * (jlong)1000000000) +
  5624                 (jlong)prusage.pr_utime.tv_nsec;
  5627   return(lwp_time);
  5630 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
  5631   info_ptr->max_value = ALL_64_BITS;      // will not wrap in less than 64 bits
  5632   info_ptr->may_skip_backward = false;    // elapsed time not wall time
  5633   info_ptr->may_skip_forward = false;     // elapsed time not wall time
  5634   info_ptr->kind = JVMTI_TIMER_USER_CPU;  // only user time is returned
  5637 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
  5638   info_ptr->max_value = ALL_64_BITS;      // will not wrap in less than 64 bits
  5639   info_ptr->may_skip_backward = false;    // elapsed time not wall time
  5640   info_ptr->may_skip_forward = false;     // elapsed time not wall time
  5641   info_ptr->kind = JVMTI_TIMER_USER_CPU;  // only user time is returned
  5644 bool os::is_thread_cpu_time_supported() {
  5645   if ( os::Solaris::T2_libthread() || UseBoundThreads ) {
  5646     return true;
  5647   } else {
  5648     return false;
  5652 // System loadavg support.  Returns -1 if load average cannot be obtained.
  5653 // Return the load average for our processor set if the primitive exists
  5654 // (Solaris 9 and later).  Otherwise just return system wide loadavg.
  5655 int os::loadavg(double loadavg[], int nelem) {
  5656   if (pset_getloadavg_ptr != NULL) {
  5657     return (*pset_getloadavg_ptr)(PS_MYID, loadavg, nelem);
  5658   } else {
  5659     return ::getloadavg(loadavg, nelem);
  5663 //---------------------------------------------------------------------------------
  5665 bool os::find(address addr, outputStream* st) {
  5666   Dl_info dlinfo;
  5667   memset(&dlinfo, 0, sizeof(dlinfo));
  5668   if (dladdr(addr, &dlinfo) != 0) {
  5669     st->print(PTR_FORMAT ": ", addr);
  5670     if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
  5671       st->print("%s+%#lx", dlinfo.dli_sname, addr-(intptr_t)dlinfo.dli_saddr);
  5672     } else if (dlinfo.dli_fbase != NULL)
  5673       st->print("<offset %#lx>", addr-(intptr_t)dlinfo.dli_fbase);
  5674     else
  5675       st->print("<absolute address>");
  5676     if (dlinfo.dli_fname != NULL) {
  5677       st->print(" in %s", dlinfo.dli_fname);
  5679     if (dlinfo.dli_fbase != NULL) {
  5680       st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
  5682     st->cr();
  5684     if (Verbose) {
  5685       // decode some bytes around the PC
  5686       address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
  5687       address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
  5688       address       lowest = (address) dlinfo.dli_sname;
  5689       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
  5690       if (begin < lowest)  begin = lowest;
  5691       Dl_info dlinfo2;
  5692       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
  5693           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
  5694         end = (address) dlinfo2.dli_saddr;
  5695       Disassembler::decode(begin, end, st);
  5697     return true;
  5699   return false;
  5702 // Following function has been added to support HotSparc's libjvm.so running
  5703 // under Solaris production JDK 1.2.2 / 1.3.0.  These came from
  5704 // src/solaris/hpi/native_threads in the EVM codebase.
  5705 //
  5706 // NOTE: This is no longer needed in the 1.3.1 and 1.4 production release
  5707 // libraries and should thus be removed. We will leave it behind for a while
  5708 // until we no longer want to able to run on top of 1.3.0 Solaris production
  5709 // JDK. See 4341971.
  5711 #define STACK_SLACK 0x800
  5713 extern "C" {
  5714   intptr_t sysThreadAvailableStackWithSlack() {
  5715     stack_t st;
  5716     intptr_t retval, stack_top;
  5717     retval = thr_stksegment(&st);
  5718     assert(retval == 0, "incorrect return value from thr_stksegment");
  5719     assert((address)&st < (address)st.ss_sp, "Invalid stack base returned");
  5720     assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned");
  5721     stack_top=(intptr_t)st.ss_sp-st.ss_size;
  5722     return ((intptr_t)&stack_top - stack_top - STACK_SLACK);
  5726 // ObjectMonitor park-unpark infrastructure ...
  5727 //
  5728 // We implement Solaris and Linux PlatformEvents with the
  5729 // obvious condvar-mutex-flag triple.
  5730 // Another alternative that works quite well is pipes:
  5731 // Each PlatformEvent consists of a pipe-pair.
  5732 // The thread associated with the PlatformEvent
  5733 // calls park(), which reads from the input end of the pipe.
  5734 // Unpark() writes into the other end of the pipe.
  5735 // The write-side of the pipe must be set NDELAY.
  5736 // Unfortunately pipes consume a large # of handles.
  5737 // Native solaris lwp_park() and lwp_unpark() work nicely, too.
  5738 // Using pipes for the 1st few threads might be workable, however.
  5739 //
  5740 // park() is permitted to return spuriously.
  5741 // Callers of park() should wrap the call to park() in
  5742 // an appropriate loop.  A litmus test for the correct
  5743 // usage of park is the following: if park() were modified
  5744 // to immediately return 0 your code should still work,
  5745 // albeit degenerating to a spin loop.
  5746 //
  5747 // An interesting optimization for park() is to use a trylock()
  5748 // to attempt to acquire the mutex.  If the trylock() fails
  5749 // then we know that a concurrent unpark() operation is in-progress.
  5750 // in that case the park() code could simply set _count to 0
  5751 // and return immediately.  The subsequent park() operation *might*
  5752 // return immediately.  That's harmless as the caller of park() is
  5753 // expected to loop.  By using trylock() we will have avoided a
  5754 // avoided a context switch caused by contention on the per-thread mutex.
  5755 //
  5756 // TODO-FIXME:
  5757 // 1.  Reconcile Doug's JSR166 j.u.c park-unpark with the
  5758 //     objectmonitor implementation.
  5759 // 2.  Collapse the JSR166 parker event, and the
  5760 //     objectmonitor ParkEvent into a single "Event" construct.
  5761 // 3.  In park() and unpark() add:
  5762 //     assert (Thread::current() == AssociatedWith).
  5763 // 4.  add spurious wakeup injection on a -XX:EarlyParkReturn=N switch.
  5764 //     1-out-of-N park() operations will return immediately.
  5765 //
  5766 // _Event transitions in park()
  5767 //   -1 => -1 : illegal
  5768 //    1 =>  0 : pass - return immediately
  5769 //    0 => -1 : block
  5770 //
  5771 // _Event serves as a restricted-range semaphore.
  5772 //
  5773 // Another possible encoding of _Event would be with
  5774 // explicit "PARKED" == 01b and "SIGNALED" == 10b bits.
  5775 //
  5776 // TODO-FIXME: add DTRACE probes for:
  5777 // 1.   Tx parks
  5778 // 2.   Ty unparks Tx
  5779 // 3.   Tx resumes from park
  5782 // value determined through experimentation
  5783 #define ROUNDINGFIX 11
  5785 // utility to compute the abstime argument to timedwait.
  5786 // TODO-FIXME: switch from compute_abstime() to unpackTime().
  5788 static timestruc_t* compute_abstime(timestruc_t* abstime, jlong millis) {
  5789   // millis is the relative timeout time
  5790   // abstime will be the absolute timeout time
  5791   if (millis < 0)  millis = 0;
  5792   struct timeval now;
  5793   int status = gettimeofday(&now, NULL);
  5794   assert(status == 0, "gettimeofday");
  5795   jlong seconds = millis / 1000;
  5796   jlong max_wait_period;
  5798   if (UseLWPSynchronization) {
  5799     // forward port of fix for 4275818 (not sleeping long enough)
  5800     // There was a bug in Solaris 6, 7 and pre-patch 5 of 8 where
  5801     // _lwp_cond_timedwait() used a round_down algorithm rather
  5802     // than a round_up. For millis less than our roundfactor
  5803     // it rounded down to 0 which doesn't meet the spec.
  5804     // For millis > roundfactor we may return a bit sooner, but
  5805     // since we can not accurately identify the patch level and
  5806     // this has already been fixed in Solaris 9 and 8 we will
  5807     // leave it alone rather than always rounding down.
  5809     if (millis > 0 && millis < ROUNDINGFIX) millis = ROUNDINGFIX;
  5810        // It appears that when we go directly through Solaris _lwp_cond_timedwait()
  5811            // the acceptable max time threshold is smaller than for libthread on 2.5.1 and 2.6
  5812            max_wait_period = 21000000;
  5813   } else {
  5814     max_wait_period = 50000000;
  5816   millis %= 1000;
  5817   if (seconds > max_wait_period) {      // see man cond_timedwait(3T)
  5818      seconds = max_wait_period;
  5820   abstime->tv_sec = now.tv_sec  + seconds;
  5821   long       usec = now.tv_usec + millis * 1000;
  5822   if (usec >= 1000000) {
  5823     abstime->tv_sec += 1;
  5824     usec -= 1000000;
  5826   abstime->tv_nsec = usec * 1000;
  5827   return abstime;
  5830 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
  5831 // Conceptually TryPark() should be equivalent to park(0).
  5833 int os::PlatformEvent::TryPark() {
  5834   for (;;) {
  5835     const int v = _Event ;
  5836     guarantee ((v == 0) || (v == 1), "invariant") ;
  5837     if (Atomic::cmpxchg (0, &_Event, v) == v) return v  ;
  5841 void os::PlatformEvent::park() {           // AKA: down()
  5842   // Invariant: Only the thread associated with the Event/PlatformEvent
  5843   // may call park().
  5844   int v ;
  5845   for (;;) {
  5846       v = _Event ;
  5847       if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
  5849   guarantee (v >= 0, "invariant") ;
  5850   if (v == 0) {
  5851      // Do this the hard way by blocking ...
  5852      // See http://monaco.sfbay/detail.jsf?cr=5094058.
  5853      // TODO-FIXME: for Solaris SPARC set fprs.FEF=0 prior to parking.
  5854      // Only for SPARC >= V8PlusA
  5855 #if defined(__sparc) && defined(COMPILER2)
  5856      if (ClearFPUAtPark) { _mark_fpu_nosave() ; }
  5857 #endif
  5858      int status = os::Solaris::mutex_lock(_mutex);
  5859      assert_status(status == 0, status,  "mutex_lock");
  5860      guarantee (_nParked == 0, "invariant") ;
  5861      ++ _nParked ;
  5862      while (_Event < 0) {
  5863         // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
  5864         // Treat this the same as if the wait was interrupted
  5865         // With usr/lib/lwp going to kernel, always handle ETIME
  5866         status = os::Solaris::cond_wait(_cond, _mutex);
  5867         if (status == ETIME) status = EINTR ;
  5868         assert_status(status == 0 || status == EINTR, status, "cond_wait");
  5870      -- _nParked ;
  5871      _Event = 0 ;
  5872      status = os::Solaris::mutex_unlock(_mutex);
  5873      assert_status(status == 0, status, "mutex_unlock");
  5874     // Paranoia to ensure our locked and lock-free paths interact
  5875     // correctly with each other.
  5876     OrderAccess::fence();
  5880 int os::PlatformEvent::park(jlong millis) {
  5881   guarantee (_nParked == 0, "invariant") ;
  5882   int v ;
  5883   for (;;) {
  5884       v = _Event ;
  5885       if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
  5887   guarantee (v >= 0, "invariant") ;
  5888   if (v != 0) return OS_OK ;
  5890   int ret = OS_TIMEOUT;
  5891   timestruc_t abst;
  5892   compute_abstime (&abst, millis);
  5894   // See http://monaco.sfbay/detail.jsf?cr=5094058.
  5895   // For Solaris SPARC set fprs.FEF=0 prior to parking.
  5896   // Only for SPARC >= V8PlusA
  5897 #if defined(__sparc) && defined(COMPILER2)
  5898  if (ClearFPUAtPark) { _mark_fpu_nosave() ; }
  5899 #endif
  5900   int status = os::Solaris::mutex_lock(_mutex);
  5901   assert_status(status == 0, status, "mutex_lock");
  5902   guarantee (_nParked == 0, "invariant") ;
  5903   ++ _nParked ;
  5904   while (_Event < 0) {
  5905      int status = os::Solaris::cond_timedwait(_cond, _mutex, &abst);
  5906      assert_status(status == 0 || status == EINTR ||
  5907                    status == ETIME || status == ETIMEDOUT,
  5908                    status, "cond_timedwait");
  5909      if (!FilterSpuriousWakeups) break ;                // previous semantics
  5910      if (status == ETIME || status == ETIMEDOUT) break ;
  5911      // We consume and ignore EINTR and spurious wakeups.
  5913   -- _nParked ;
  5914   if (_Event >= 0) ret = OS_OK ;
  5915   _Event = 0 ;
  5916   status = os::Solaris::mutex_unlock(_mutex);
  5917   assert_status(status == 0, status, "mutex_unlock");
  5918   // Paranoia to ensure our locked and lock-free paths interact
  5919   // correctly with each other.
  5920   OrderAccess::fence();
  5921   return ret;
  5924 void os::PlatformEvent::unpark() {
  5925   // Transitions for _Event:
  5926   //    0 :=> 1
  5927   //    1 :=> 1
  5928   //   -1 :=> either 0 or 1; must signal target thread
  5929   //          That is, we can safely transition _Event from -1 to either
  5930   //          0 or 1. Forcing 1 is slightly more efficient for back-to-back
  5931   //          unpark() calls.
  5932   // See also: "Semaphores in Plan 9" by Mullender & Cox
  5933   //
  5934   // Note: Forcing a transition from "-1" to "1" on an unpark() means
  5935   // that it will take two back-to-back park() calls for the owning
  5936   // thread to block. This has the benefit of forcing a spurious return
  5937   // from the first park() call after an unpark() call which will help
  5938   // shake out uses of park() and unpark() without condition variables.
  5940   if (Atomic::xchg(1, &_Event) >= 0) return;
  5942   // If the thread associated with the event was parked, wake it.
  5943   // Wait for the thread assoc with the PlatformEvent to vacate.
  5944   int status = os::Solaris::mutex_lock(_mutex);
  5945   assert_status(status == 0, status, "mutex_lock");
  5946   int AnyWaiters = _nParked;
  5947   status = os::Solaris::mutex_unlock(_mutex);
  5948   assert_status(status == 0, status, "mutex_unlock");
  5949   guarantee(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
  5950   if (AnyWaiters != 0) {
  5951     // We intentional signal *after* dropping the lock
  5952     // to avoid a common class of futile wakeups.
  5953     status = os::Solaris::cond_signal(_cond);
  5954     assert_status(status == 0, status, "cond_signal");
  5958 // JSR166
  5959 // -------------------------------------------------------
  5961 /*
  5962  * The solaris and linux implementations of park/unpark are fairly
  5963  * conservative for now, but can be improved. They currently use a
  5964  * mutex/condvar pair, plus _counter.
  5965  * Park decrements _counter if > 0, else does a condvar wait.  Unpark
  5966  * sets count to 1 and signals condvar.  Only one thread ever waits
  5967  * on the condvar. Contention seen when trying to park implies that someone
  5968  * is unparking you, so don't wait. And spurious returns are fine, so there
  5969  * is no need to track notifications.
  5970  */
  5972 #define MAX_SECS 100000000
  5973 /*
  5974  * This code is common to linux and solaris and will be moved to a
  5975  * common place in dolphin.
  5977  * The passed in time value is either a relative time in nanoseconds
  5978  * or an absolute time in milliseconds. Either way it has to be unpacked
  5979  * into suitable seconds and nanoseconds components and stored in the
  5980  * given timespec structure.
  5981  * Given time is a 64-bit value and the time_t used in the timespec is only
  5982  * a signed-32-bit value (except on 64-bit Linux) we have to watch for
  5983  * overflow if times way in the future are given. Further on Solaris versions
  5984  * prior to 10 there is a restriction (see cond_timedwait) that the specified
  5985  * number of seconds, in abstime, is less than current_time  + 100,000,000.
  5986  * As it will be 28 years before "now + 100000000" will overflow we can
  5987  * ignore overflow and just impose a hard-limit on seconds using the value
  5988  * of "now + 100,000,000". This places a limit on the timeout of about 3.17
  5989  * years from "now".
  5990  */
  5991 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) {
  5992   assert (time > 0, "convertTime");
  5994   struct timeval now;
  5995   int status = gettimeofday(&now, NULL);
  5996   assert(status == 0, "gettimeofday");
  5998   time_t max_secs = now.tv_sec + MAX_SECS;
  6000   if (isAbsolute) {
  6001     jlong secs = time / 1000;
  6002     if (secs > max_secs) {
  6003       absTime->tv_sec = max_secs;
  6005     else {
  6006       absTime->tv_sec = secs;
  6008     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
  6010   else {
  6011     jlong secs = time / NANOSECS_PER_SEC;
  6012     if (secs >= MAX_SECS) {
  6013       absTime->tv_sec = max_secs;
  6014       absTime->tv_nsec = 0;
  6016     else {
  6017       absTime->tv_sec = now.tv_sec + secs;
  6018       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
  6019       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
  6020         absTime->tv_nsec -= NANOSECS_PER_SEC;
  6021         ++absTime->tv_sec; // note: this must be <= max_secs
  6025   assert(absTime->tv_sec >= 0, "tv_sec < 0");
  6026   assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
  6027   assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
  6028   assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
  6031 void Parker::park(bool isAbsolute, jlong time) {
  6032   // Ideally we'd do something useful while spinning, such
  6033   // as calling unpackTime().
  6035   // Optional fast-path check:
  6036   // Return immediately if a permit is available.
  6037   // We depend on Atomic::xchg() having full barrier semantics
  6038   // since we are doing a lock-free update to _counter.
  6039   if (Atomic::xchg(0, &_counter) > 0) return;
  6041   // Optional fast-exit: Check interrupt before trying to wait
  6042   Thread* thread = Thread::current();
  6043   assert(thread->is_Java_thread(), "Must be JavaThread");
  6044   JavaThread *jt = (JavaThread *)thread;
  6045   if (Thread::is_interrupted(thread, false)) {
  6046     return;
  6049   // First, demultiplex/decode time arguments
  6050   timespec absTime;
  6051   if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
  6052     return;
  6054   if (time > 0) {
  6055     // Warning: this code might be exposed to the old Solaris time
  6056     // round-down bugs.  Grep "roundingFix" for details.
  6057     unpackTime(&absTime, isAbsolute, time);
  6060   // Enter safepoint region
  6061   // Beware of deadlocks such as 6317397.
  6062   // The per-thread Parker:: _mutex is a classic leaf-lock.
  6063   // In particular a thread must never block on the Threads_lock while
  6064   // holding the Parker:: mutex.  If safepoints are pending both the
  6065   // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
  6066   ThreadBlockInVM tbivm(jt);
  6068   // Don't wait if cannot get lock since interference arises from
  6069   // unblocking.  Also. check interrupt before trying wait
  6070   if (Thread::is_interrupted(thread, false) ||
  6071       os::Solaris::mutex_trylock(_mutex) != 0) {
  6072     return;
  6075   int status ;
  6077   if (_counter > 0)  { // no wait needed
  6078     _counter = 0;
  6079     status = os::Solaris::mutex_unlock(_mutex);
  6080     assert (status == 0, "invariant") ;
  6081     // Paranoia to ensure our locked and lock-free paths interact
  6082     // correctly with each other and Java-level accesses.
  6083     OrderAccess::fence();
  6084     return;
  6087 #ifdef ASSERT
  6088   // Don't catch signals while blocked; let the running threads have the signals.
  6089   // (This allows a debugger to break into the running thread.)
  6090   sigset_t oldsigs;
  6091   sigset_t* allowdebug_blocked = os::Solaris::allowdebug_blocked_signals();
  6092   thr_sigsetmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
  6093 #endif
  6095   OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
  6096   jt->set_suspend_equivalent();
  6097   // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
  6099   // Do this the hard way by blocking ...
  6100   // See http://monaco.sfbay/detail.jsf?cr=5094058.
  6101   // TODO-FIXME: for Solaris SPARC set fprs.FEF=0 prior to parking.
  6102   // Only for SPARC >= V8PlusA
  6103 #if defined(__sparc) && defined(COMPILER2)
  6104   if (ClearFPUAtPark) { _mark_fpu_nosave() ; }
  6105 #endif
  6107   if (time == 0) {
  6108     status = os::Solaris::cond_wait (_cond, _mutex) ;
  6109   } else {
  6110     status = os::Solaris::cond_timedwait (_cond, _mutex, &absTime);
  6112   // Note that an untimed cond_wait() can sometimes return ETIME on older
  6113   // versions of the Solaris.
  6114   assert_status(status == 0 || status == EINTR ||
  6115                 status == ETIME || status == ETIMEDOUT,
  6116                 status, "cond_timedwait");
  6118 #ifdef ASSERT
  6119   thr_sigsetmask(SIG_SETMASK, &oldsigs, NULL);
  6120 #endif
  6121   _counter = 0 ;
  6122   status = os::Solaris::mutex_unlock(_mutex);
  6123   assert_status(status == 0, status, "mutex_unlock") ;
  6124   // Paranoia to ensure our locked and lock-free paths interact
  6125   // correctly with each other and Java-level accesses.
  6126   OrderAccess::fence();
  6128   // If externally suspended while waiting, re-suspend
  6129   if (jt->handle_special_suspend_equivalent_condition()) {
  6130     jt->java_suspend_self();
  6134 void Parker::unpark() {
  6135   int s, status ;
  6136   status = os::Solaris::mutex_lock (_mutex) ;
  6137   assert (status == 0, "invariant") ;
  6138   s = _counter;
  6139   _counter = 1;
  6140   status = os::Solaris::mutex_unlock (_mutex) ;
  6141   assert (status == 0, "invariant") ;
  6143   if (s < 1) {
  6144     status = os::Solaris::cond_signal (_cond) ;
  6145     assert (status == 0, "invariant") ;
  6149 extern char** environ;
  6151 // Run the specified command in a separate process. Return its exit value,
  6152 // or -1 on failure (e.g. can't fork a new process).
  6153 // Unlike system(), this function can be called from signal handler. It
  6154 // doesn't block SIGINT et al.
  6155 int os::fork_and_exec(char* cmd) {
  6156   char * argv[4];
  6157   argv[0] = (char *)"sh";
  6158   argv[1] = (char *)"-c";
  6159   argv[2] = cmd;
  6160   argv[3] = NULL;
  6162   // fork is async-safe, fork1 is not so can't use in signal handler
  6163   pid_t pid;
  6164   Thread* t = ThreadLocalStorage::get_thread_slow();
  6165   if (t != NULL && t->is_inside_signal_handler()) {
  6166     pid = fork();
  6167   } else {
  6168     pid = fork1();
  6171   if (pid < 0) {
  6172     // fork failed
  6173     warning("fork failed: %s", strerror(errno));
  6174     return -1;
  6176   } else if (pid == 0) {
  6177     // child process
  6179     // try to be consistent with system(), which uses "/usr/bin/sh" on Solaris
  6180     execve("/usr/bin/sh", argv, environ);
  6182     // execve failed
  6183     _exit(-1);
  6185   } else  {
  6186     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
  6187     // care about the actual exit code, for now.
  6189     int status;
  6191     // Wait for the child process to exit.  This returns immediately if
  6192     // the child has already exited. */
  6193     while (waitpid(pid, &status, 0) < 0) {
  6194         switch (errno) {
  6195         case ECHILD: return 0;
  6196         case EINTR: break;
  6197         default: return -1;
  6201     if (WIFEXITED(status)) {
  6202        // The child exited normally; get its exit code.
  6203        return WEXITSTATUS(status);
  6204     } else if (WIFSIGNALED(status)) {
  6205        // The child exited because of a signal
  6206        // The best value to return is 0x80 + signal number,
  6207        // because that is what all Unix shells do, and because
  6208        // it allows callers to distinguish between process exit and
  6209        // process death by signal.
  6210        return 0x80 + WTERMSIG(status);
  6211     } else {
  6212        // Unknown exit code; pass it through
  6213        return status;
  6218 // is_headless_jre()
  6219 //
  6220 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
  6221 // in order to report if we are running in a headless jre
  6222 //
  6223 // Since JDK8 xawt/libmawt.so was moved into the same directory
  6224 // as libawt.so, and renamed libawt_xawt.so
  6225 //
  6226 bool os::is_headless_jre() {
  6227     struct stat statbuf;
  6228     char buf[MAXPATHLEN];
  6229     char libmawtpath[MAXPATHLEN];
  6230     const char *xawtstr  = "/xawt/libmawt.so";
  6231     const char *new_xawtstr = "/libawt_xawt.so";
  6232     char *p;
  6234     // Get path to libjvm.so
  6235     os::jvm_path(buf, sizeof(buf));
  6237     // Get rid of libjvm.so
  6238     p = strrchr(buf, '/');
  6239     if (p == NULL) return false;
  6240     else *p = '\0';
  6242     // Get rid of client or server
  6243     p = strrchr(buf, '/');
  6244     if (p == NULL) return false;
  6245     else *p = '\0';
  6247     // check xawt/libmawt.so
  6248     strcpy(libmawtpath, buf);
  6249     strcat(libmawtpath, xawtstr);
  6250     if (::stat(libmawtpath, &statbuf) == 0) return false;
  6252     // check libawt_xawt.so
  6253     strcpy(libmawtpath, buf);
  6254     strcat(libmawtpath, new_xawtstr);
  6255     if (::stat(libmawtpath, &statbuf) == 0) return false;
  6257     return true;
  6260 size_t os::write(int fd, const void *buf, unsigned int nBytes) {
  6261   INTERRUPTIBLE_RETURN_INT(::write(fd, buf, nBytes), os::Solaris::clear_interrupted);
  6264 int os::close(int fd) {
  6265   return ::close(fd);
  6268 int os::socket_close(int fd) {
  6269   return ::close(fd);
  6272 int os::recv(int fd, char* buf, size_t nBytes, uint flags) {
  6273   INTERRUPTIBLE_RETURN_INT((int)::recv(fd, buf, nBytes, flags), os::Solaris::clear_interrupted);
  6276 int os::send(int fd, char* buf, size_t nBytes, uint flags) {
  6277   INTERRUPTIBLE_RETURN_INT((int)::send(fd, buf, nBytes, flags), os::Solaris::clear_interrupted);
  6280 int os::raw_send(int fd, char* buf, size_t nBytes, uint flags) {
  6281   RESTARTABLE_RETURN_INT((int)::send(fd, buf, nBytes, flags));
  6284 // As both poll and select can be interrupted by signals, we have to be
  6285 // prepared to restart the system call after updating the timeout, unless
  6286 // a poll() is done with timeout == -1, in which case we repeat with this
  6287 // "wait forever" value.
  6289 int os::timeout(int fd, long timeout) {
  6290   int res;
  6291   struct timeval t;
  6292   julong prevtime, newtime;
  6293   static const char* aNull = 0;
  6294   struct pollfd pfd;
  6295   pfd.fd = fd;
  6296   pfd.events = POLLIN;
  6298   gettimeofday(&t, &aNull);
  6299   prevtime = ((julong)t.tv_sec * 1000)  +  t.tv_usec / 1000;
  6301   for(;;) {
  6302     INTERRUPTIBLE_NORESTART(::poll(&pfd, 1, timeout), res, os::Solaris::clear_interrupted);
  6303     if(res == OS_ERR && errno == EINTR) {
  6304         if(timeout != -1) {
  6305           gettimeofday(&t, &aNull);
  6306           newtime = ((julong)t.tv_sec * 1000)  +  t.tv_usec /1000;
  6307           timeout -= newtime - prevtime;
  6308           if(timeout <= 0)
  6309             return OS_OK;
  6310           prevtime = newtime;
  6312     } else return res;
  6316 int os::connect(int fd, struct sockaddr *him, socklen_t len) {
  6317   int _result;
  6318   INTERRUPTIBLE_NORESTART(::connect(fd, him, len), _result,\
  6319                           os::Solaris::clear_interrupted);
  6321   // Depending on when thread interruption is reset, _result could be
  6322   // one of two values when errno == EINTR
  6324   if (((_result == OS_INTRPT) || (_result == OS_ERR))
  6325       && (errno == EINTR)) {
  6326      /* restarting a connect() changes its errno semantics */
  6327      INTERRUPTIBLE(::connect(fd, him, len), _result,\
  6328                    os::Solaris::clear_interrupted);
  6329      /* undo these changes */
  6330      if (_result == OS_ERR) {
  6331        if (errno == EALREADY) {
  6332          errno = EINPROGRESS; /* fall through */
  6333        } else if (errno == EISCONN) {
  6334          errno = 0;
  6335          return OS_OK;
  6339    return _result;
  6342 int os::accept(int fd, struct sockaddr* him, socklen_t* len) {
  6343   if (fd < 0) {
  6344     return OS_ERR;
  6346   INTERRUPTIBLE_RETURN_INT((int)::accept(fd, him, len),\
  6347                            os::Solaris::clear_interrupted);
  6350 int os::recvfrom(int fd, char* buf, size_t nBytes, uint flags,
  6351                  sockaddr* from, socklen_t* fromlen) {
  6352   INTERRUPTIBLE_RETURN_INT((int)::recvfrom(fd, buf, nBytes, flags, from, fromlen),\
  6353                            os::Solaris::clear_interrupted);
  6356 int os::sendto(int fd, char* buf, size_t len, uint flags,
  6357                struct sockaddr* to, socklen_t tolen) {
  6358   INTERRUPTIBLE_RETURN_INT((int)::sendto(fd, buf, len, flags, to, tolen),\
  6359                            os::Solaris::clear_interrupted);
  6362 int os::socket_available(int fd, jint *pbytes) {
  6363   if (fd < 0) {
  6364     return OS_OK;
  6366   int ret;
  6367   RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
  6368   // note: ioctl can return 0 when successful, JVM_SocketAvailable
  6369   // is expected to return 0 on failure and 1 on success to the jdk.
  6370   return (ret == OS_ERR) ? 0 : 1;
  6373 int os::bind(int fd, struct sockaddr* him, socklen_t len) {
  6374    INTERRUPTIBLE_RETURN_INT_NORESTART(::bind(fd, him, len),\
  6375                                       os::Solaris::clear_interrupted);
  6378 // Get the default path to the core file
  6379 // Returns the length of the string
  6380 int os::get_core_path(char* buffer, size_t bufferSize) {
  6381   const char* p = get_current_directory(buffer, bufferSize);
  6383   if (p == NULL) {
  6384     assert(p != NULL, "failed to get current directory");
  6385     return 0;
  6388   return strlen(buffer);
  6391 #ifndef PRODUCT
  6392 void TestReserveMemorySpecial_test() {
  6393   // No tests available for this platform
  6395 #endif

mercurial