os.cpp revision 2721:f08d439fab8c
1/*
2 * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25#include "precompiled.hpp"
26#include "classfile/classLoader.hpp"
27#include "classfile/javaClasses.hpp"
28#include "classfile/systemDictionary.hpp"
29#include "classfile/vmSymbols.hpp"
30#include "code/icBuffer.hpp"
31#include "code/vtableStubs.hpp"
32#include "gc_implementation/shared/vmGCOperations.hpp"
33#include "interpreter/interpreter.hpp"
34#include "memory/allocation.inline.hpp"
35#include "oops/oop.inline.hpp"
36#include "prims/jvm.h"
37#include "prims/jvm_misc.hpp"
38#include "prims/privilegedStack.hpp"
39#include "runtime/arguments.hpp"
40#include "runtime/frame.inline.hpp"
41#include "runtime/interfaceSupport.hpp"
42#include "runtime/java.hpp"
43#include "runtime/javaCalls.hpp"
44#include "runtime/mutexLocker.hpp"
45#include "runtime/os.hpp"
46#include "runtime/stubRoutines.hpp"
47#include "services/attachListener.hpp"
48#include "services/threadService.hpp"
49#include "utilities/defaultStream.hpp"
50#include "utilities/events.hpp"
51#ifdef TARGET_OS_FAMILY_linux
52# include "os_linux.inline.hpp"
53# include "thread_linux.inline.hpp"
54#endif
55#ifdef TARGET_OS_FAMILY_solaris
56# include "os_solaris.inline.hpp"
57# include "thread_solaris.inline.hpp"
58#endif
59#ifdef TARGET_OS_FAMILY_windows
60# include "os_windows.inline.hpp"
61# include "thread_windows.inline.hpp"
62#endif
63#ifdef TARGET_OS_FAMILY_bsd
64# include "os_bsd.inline.hpp"
65# include "thread_bsd.inline.hpp"
66#endif
67
68# include <signal.h>
69
70OSThread*         os::_starting_thread    = NULL;
71address           os::_polling_page       = NULL;
72volatile int32_t* os::_mem_serialize_page = NULL;
73uintptr_t         os::_serialize_page_mask = 0;
74long              os::_rand_seed          = 1;
75int               os::_processor_count    = 0;
76size_t            os::_page_sizes[os::page_sizes_max];
77
78#ifndef PRODUCT
79julong os::num_mallocs = 0;         // # of calls to malloc/realloc
80julong os::alloc_bytes = 0;         // # of bytes allocated
81julong os::num_frees = 0;           // # of calls to free
82julong os::free_bytes = 0;          // # of bytes freed
83#endif
84
85// Fill in buffer with current local time as an ISO-8601 string.
86// E.g., yyyy-mm-ddThh:mm:ss-zzzz.
87// Returns buffer, or NULL if it failed.
88// This would mostly be a call to
89//     strftime(...., "%Y-%m-%d" "T" "%H:%M:%S" "%z", ....)
90// except that on Windows the %z behaves badly, so we do it ourselves.
91// Also, people wanted milliseconds on there,
92// and strftime doesn't do milliseconds.
93char* os::iso8601_time(char* buffer, size_t buffer_length) {
94  // Output will be of the form "YYYY-MM-DDThh:mm:ss.mmm+zzzz\0"
95  //                                      1         2
96  //                             12345678901234567890123456789
97  static const char* iso8601_format =
98    "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d";
99  static const size_t needed_buffer = 29;
100
101  // Sanity check the arguments
102  if (buffer == NULL) {
103    assert(false, "NULL buffer");
104    return NULL;
105  }
106  if (buffer_length < needed_buffer) {
107    assert(false, "buffer_length too small");
108    return NULL;
109  }
110  // Get the current time
111  jlong milliseconds_since_19700101 = javaTimeMillis();
112  const int milliseconds_per_microsecond = 1000;
113  const time_t seconds_since_19700101 =
114    milliseconds_since_19700101 / milliseconds_per_microsecond;
115  const int milliseconds_after_second =
116    milliseconds_since_19700101 % milliseconds_per_microsecond;
117  // Convert the time value to a tm and timezone variable
118  struct tm time_struct;
119  if (localtime_pd(&seconds_since_19700101, &time_struct) == NULL) {
120    assert(false, "Failed localtime_pd");
121    return NULL;
122  }
123#if defined(_ALLBSD_SOURCE)
124  const time_t zone = (time_t) time_struct.tm_gmtoff;
125#else
126  const time_t zone = timezone;
127#endif
128
129  // If daylight savings time is in effect,
130  // we are 1 hour East of our time zone
131  const time_t seconds_per_minute = 60;
132  const time_t minutes_per_hour = 60;
133  const time_t seconds_per_hour = seconds_per_minute * minutes_per_hour;
134  time_t UTC_to_local = zone;
135  if (time_struct.tm_isdst > 0) {
136    UTC_to_local = UTC_to_local - seconds_per_hour;
137  }
138  // Compute the time zone offset.
139  //    localtime_pd() sets timezone to the difference (in seconds)
140  //    between UTC and and local time.
141  //    ISO 8601 says we need the difference between local time and UTC,
142  //    we change the sign of the localtime_pd() result.
143  const time_t local_to_UTC = -(UTC_to_local);
144  // Then we have to figure out if if we are ahead (+) or behind (-) UTC.
145  char sign_local_to_UTC = '+';
146  time_t abs_local_to_UTC = local_to_UTC;
147  if (local_to_UTC < 0) {
148    sign_local_to_UTC = '-';
149    abs_local_to_UTC = -(abs_local_to_UTC);
150  }
151  // Convert time zone offset seconds to hours and minutes.
152  const time_t zone_hours = (abs_local_to_UTC / seconds_per_hour);
153  const time_t zone_min =
154    ((abs_local_to_UTC % seconds_per_hour) / seconds_per_minute);
155
156  // Print an ISO 8601 date and time stamp into the buffer
157  const int year = 1900 + time_struct.tm_year;
158  const int month = 1 + time_struct.tm_mon;
159  const int printed = jio_snprintf(buffer, buffer_length, iso8601_format,
160                                   year,
161                                   month,
162                                   time_struct.tm_mday,
163                                   time_struct.tm_hour,
164                                   time_struct.tm_min,
165                                   time_struct.tm_sec,
166                                   milliseconds_after_second,
167                                   sign_local_to_UTC,
168                                   zone_hours,
169                                   zone_min);
170  if (printed == 0) {
171    assert(false, "Failed jio_printf");
172    return NULL;
173  }
174  return buffer;
175}
176
177OSReturn os::set_priority(Thread* thread, ThreadPriority p) {
178#ifdef ASSERT
179  if (!(!thread->is_Java_thread() ||
180         Thread::current() == thread  ||
181         Threads_lock->owned_by_self()
182         || thread->is_Compiler_thread()
183        )) {
184    assert(false, "possibility of dangling Thread pointer");
185  }
186#endif
187
188  if (p >= MinPriority && p <= MaxPriority) {
189    int priority = java_to_os_priority[p];
190    return set_native_priority(thread, priority);
191  } else {
192    assert(false, "Should not happen");
193    return OS_ERR;
194  }
195}
196
197
198OSReturn os::get_priority(const Thread* const thread, ThreadPriority& priority) {
199  int p;
200  int os_prio;
201  OSReturn ret = get_native_priority(thread, &os_prio);
202  if (ret != OS_OK) return ret;
203
204  for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] > os_prio; p--) ;
205  priority = (ThreadPriority)p;
206  return OS_OK;
207}
208
209
210// --------------------- sun.misc.Signal (optional) ---------------------
211
212
213// SIGBREAK is sent by the keyboard to query the VM state
214#ifndef SIGBREAK
215#define SIGBREAK SIGQUIT
216#endif
217
218// sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread.
219
220
221static void signal_thread_entry(JavaThread* thread, TRAPS) {
222  os::set_priority(thread, NearMaxPriority);
223  while (true) {
224    int sig;
225    {
226      // FIXME : Currently we have not decieded what should be the status
227      //         for this java thread blocked here. Once we decide about
228      //         that we should fix this.
229      sig = os::signal_wait();
230    }
231    if (sig == os::sigexitnum_pd()) {
232       // Terminate the signal thread
233       return;
234    }
235
236    switch (sig) {
237      case SIGBREAK: {
238        // Check if the signal is a trigger to start the Attach Listener - in that
239        // case don't print stack traces.
240        if (!DisableAttachMechanism && AttachListener::is_init_trigger()) {
241          continue;
242        }
243        // Print stack traces
244        // Any SIGBREAK operations added here should make sure to flush
245        // the output stream (e.g. tty->flush()) after output.  See 4803766.
246        // Each module also prints an extra carriage return after its output.
247        VM_PrintThreads op;
248        VMThread::execute(&op);
249        VM_PrintJNI jni_op;
250        VMThread::execute(&jni_op);
251        VM_FindDeadlocks op1(tty);
252        VMThread::execute(&op1);
253        Universe::print_heap_at_SIGBREAK();
254        if (PrintClassHistogram) {
255          VM_GC_HeapInspection op1(gclog_or_tty, true /* force full GC before heap inspection */,
256                                   true /* need_prologue */);
257          VMThread::execute(&op1);
258        }
259        if (JvmtiExport::should_post_data_dump()) {
260          JvmtiExport::post_data_dump();
261        }
262        break;
263      }
264      default: {
265        // Dispatch the signal to java
266        HandleMark hm(THREAD);
267        klassOop k = SystemDictionary::resolve_or_null(vmSymbols::sun_misc_Signal(), THREAD);
268        KlassHandle klass (THREAD, k);
269        if (klass.not_null()) {
270          JavaValue result(T_VOID);
271          JavaCallArguments args;
272          args.push_int(sig);
273          JavaCalls::call_static(
274            &result,
275            klass,
276            vmSymbols::dispatch_name(),
277            vmSymbols::int_void_signature(),
278            &args,
279            THREAD
280          );
281        }
282        if (HAS_PENDING_EXCEPTION) {
283          // tty is initialized early so we don't expect it to be null, but
284          // if it is we can't risk doing an initialization that might
285          // trigger additional out-of-memory conditions
286          if (tty != NULL) {
287            char klass_name[256];
288            char tmp_sig_name[16];
289            const char* sig_name = "UNKNOWN";
290            instanceKlass::cast(PENDING_EXCEPTION->klass())->
291              name()->as_klass_external_name(klass_name, 256);
292            if (os::exception_name(sig, tmp_sig_name, 16) != NULL)
293              sig_name = tmp_sig_name;
294            warning("Exception %s occurred dispatching signal %s to handler"
295                    "- the VM may need to be forcibly terminated",
296                    klass_name, sig_name );
297          }
298          CLEAR_PENDING_EXCEPTION;
299        }
300      }
301    }
302  }
303}
304
305
306void os::signal_init() {
307  if (!ReduceSignalUsage) {
308    // Setup JavaThread for processing signals
309    EXCEPTION_MARK;
310    klassOop k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
311    instanceKlassHandle klass (THREAD, k);
312    instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
313
314    const char thread_name[] = "Signal Dispatcher";
315    Handle string = java_lang_String::create_from_str(thread_name, CHECK);
316
317    // Initialize thread_oop to put it into the system threadGroup
318    Handle thread_group (THREAD, Universe::system_thread_group());
319    JavaValue result(T_VOID);
320    JavaCalls::call_special(&result, thread_oop,
321                           klass,
322                           vmSymbols::object_initializer_name(),
323                           vmSymbols::threadgroup_string_void_signature(),
324                           thread_group,
325                           string,
326                           CHECK);
327
328    KlassHandle group(THREAD, SystemDictionary::ThreadGroup_klass());
329    JavaCalls::call_special(&result,
330                            thread_group,
331                            group,
332                            vmSymbols::add_method_name(),
333                            vmSymbols::thread_void_signature(),
334                            thread_oop,         // ARG 1
335                            CHECK);
336
337    os::signal_init_pd();
338
339    { MutexLocker mu(Threads_lock);
340      JavaThread* signal_thread = new JavaThread(&signal_thread_entry);
341
342      // At this point it may be possible that no osthread was created for the
343      // JavaThread due to lack of memory. We would have to throw an exception
344      // in that case. However, since this must work and we do not allow
345      // exceptions anyway, check and abort if this fails.
346      if (signal_thread == NULL || signal_thread->osthread() == NULL) {
347        vm_exit_during_initialization("java.lang.OutOfMemoryError",
348                                      "unable to create new native thread");
349      }
350
351      java_lang_Thread::set_thread(thread_oop(), signal_thread);
352      java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
353      java_lang_Thread::set_daemon(thread_oop());
354
355      signal_thread->set_threadObj(thread_oop());
356      Threads::add(signal_thread);
357      Thread::start(signal_thread);
358    }
359    // Handle ^BREAK
360    os::signal(SIGBREAK, os::user_handler());
361  }
362}
363
364
365void os::terminate_signal_thread() {
366  if (!ReduceSignalUsage)
367    signal_notify(sigexitnum_pd());
368}
369
370
371// --------------------- loading libraries ---------------------
372
373typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
374extern struct JavaVM_ main_vm;
375
376static void* _native_java_library = NULL;
377
378void* os::native_java_library() {
379  if (_native_java_library == NULL) {
380    char buffer[JVM_MAXPATHLEN];
381    char ebuf[1024];
382
383    // Try to load verify dll first. In 1.3 java dll depends on it and is not
384    // always able to find it when the loading executable is outside the JDK.
385    // In order to keep working with 1.2 we ignore any loading errors.
386    dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), "verify");
387    dll_load(buffer, ebuf, sizeof(ebuf));
388
389    // Load java dll
390    dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), "java");
391    _native_java_library = dll_load(buffer, ebuf, sizeof(ebuf));
392    if (_native_java_library == NULL) {
393      vm_exit_during_initialization("Unable to load native library", ebuf);
394    }
395
396#if defined(__OpenBSD__)
397    // Work-around OpenBSD's lack of $ORIGIN support by pre-loading libnet.so
398    // ignore errors
399    dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), "net");
400    dll_load(buffer, ebuf, sizeof(ebuf));
401#endif
402  }
403  static jboolean onLoaded = JNI_FALSE;
404  if (onLoaded) {
405    // We may have to wait to fire OnLoad until TLS is initialized.
406    if (ThreadLocalStorage::is_initialized()) {
407      // The JNI_OnLoad handling is normally done by method load in
408      // java.lang.ClassLoader$NativeLibrary, but the VM loads the base library
409      // explicitly so we have to check for JNI_OnLoad as well
410      const char *onLoadSymbols[] = JNI_ONLOAD_SYMBOLS;
411      JNI_OnLoad_t JNI_OnLoad = CAST_TO_FN_PTR(
412          JNI_OnLoad_t, dll_lookup(_native_java_library, onLoadSymbols[0]));
413      if (JNI_OnLoad != NULL) {
414        JavaThread* thread = JavaThread::current();
415        ThreadToNativeFromVM ttn(thread);
416        HandleMark hm(thread);
417        jint ver = (*JNI_OnLoad)(&main_vm, NULL);
418        onLoaded = JNI_TRUE;
419        if (!Threads::is_supported_jni_version_including_1_1(ver)) {
420          vm_exit_during_initialization("Unsupported JNI version");
421        }
422      }
423    }
424  }
425  return _native_java_library;
426}
427
428// --------------------- heap allocation utilities ---------------------
429
430char *os::strdup(const char *str) {
431  size_t size = strlen(str);
432  char *dup_str = (char *)malloc(size + 1);
433  if (dup_str == NULL) return NULL;
434  strcpy(dup_str, str);
435  return dup_str;
436}
437
438
439
440#ifdef ASSERT
441#define space_before             (MallocCushion + sizeof(double))
442#define space_after              MallocCushion
443#define size_addr_from_base(p)   (size_t*)(p + space_before - sizeof(size_t))
444#define size_addr_from_obj(p)    ((size_t*)p - 1)
445// MallocCushion: size of extra cushion allocated around objects with +UseMallocOnly
446// NB: cannot be debug variable, because these aren't set from the command line until
447// *after* the first few allocs already happened
448#define MallocCushion            16
449#else
450#define space_before             0
451#define space_after              0
452#define size_addr_from_base(p)   should not use w/o ASSERT
453#define size_addr_from_obj(p)    should not use w/o ASSERT
454#define MallocCushion            0
455#endif
456#define paranoid                 0  /* only set to 1 if you suspect checking code has bug */
457
458#ifdef ASSERT
459inline size_t get_size(void* obj) {
460  size_t size = *size_addr_from_obj(obj);
461  if (size < 0) {
462    fatal(err_msg("free: size field of object #" PTR_FORMAT " was overwritten ("
463                  SIZE_FORMAT ")", obj, size));
464  }
465  return size;
466}
467
468u_char* find_cushion_backwards(u_char* start) {
469  u_char* p = start;
470  while (p[ 0] != badResourceValue || p[-1] != badResourceValue ||
471         p[-2] != badResourceValue || p[-3] != badResourceValue) p--;
472  // ok, we have four consecutive marker bytes; find start
473  u_char* q = p - 4;
474  while (*q == badResourceValue) q--;
475  return q + 1;
476}
477
478u_char* find_cushion_forwards(u_char* start) {
479  u_char* p = start;
480  while (p[0] != badResourceValue || p[1] != badResourceValue ||
481         p[2] != badResourceValue || p[3] != badResourceValue) p++;
482  // ok, we have four consecutive marker bytes; find end of cushion
483  u_char* q = p + 4;
484  while (*q == badResourceValue) q++;
485  return q - MallocCushion;
486}
487
488void print_neighbor_blocks(void* ptr) {
489  // find block allocated before ptr (not entirely crash-proof)
490  if (MallocCushion < 4) {
491    tty->print_cr("### cannot find previous block (MallocCushion < 4)");
492    return;
493  }
494  u_char* start_of_this_block = (u_char*)ptr - space_before;
495  u_char* end_of_prev_block_data = start_of_this_block - space_after -1;
496  // look for cushion in front of prev. block
497  u_char* start_of_prev_block = find_cushion_backwards(end_of_prev_block_data);
498  ptrdiff_t size = *size_addr_from_base(start_of_prev_block);
499  u_char* obj = start_of_prev_block + space_before;
500  if (size <= 0 ) {
501    // start is bad; mayhave been confused by OS data inbetween objects
502    // search one more backwards
503    start_of_prev_block = find_cushion_backwards(start_of_prev_block);
504    size = *size_addr_from_base(start_of_prev_block);
505    obj = start_of_prev_block + space_before;
506  }
507
508  if (start_of_prev_block + space_before + size + space_after == start_of_this_block) {
509    tty->print_cr("### previous object: " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", obj, size);
510  } else {
511    tty->print_cr("### previous object (not sure if correct): " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", obj, size);
512  }
513
514  // now find successor block
515  u_char* start_of_next_block = (u_char*)ptr + *size_addr_from_obj(ptr) + space_after;
516  start_of_next_block = find_cushion_forwards(start_of_next_block);
517  u_char* next_obj = start_of_next_block + space_before;
518  ptrdiff_t next_size = *size_addr_from_base(start_of_next_block);
519  if (start_of_next_block[0] == badResourceValue &&
520      start_of_next_block[1] == badResourceValue &&
521      start_of_next_block[2] == badResourceValue &&
522      start_of_next_block[3] == badResourceValue) {
523    tty->print_cr("### next object: " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", next_obj, next_size);
524  } else {
525    tty->print_cr("### next object (not sure if correct): " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", next_obj, next_size);
526  }
527}
528
529
530void report_heap_error(void* memblock, void* bad, const char* where) {
531  tty->print_cr("## nof_mallocs = " UINT64_FORMAT ", nof_frees = " UINT64_FORMAT, os::num_mallocs, os::num_frees);
532  tty->print_cr("## memory stomp: byte at " PTR_FORMAT " %s object " PTR_FORMAT, bad, where, memblock);
533  print_neighbor_blocks(memblock);
534  fatal("memory stomping error");
535}
536
537void verify_block(void* memblock) {
538  size_t size = get_size(memblock);
539  if (MallocCushion) {
540    u_char* ptr = (u_char*)memblock - space_before;
541    for (int i = 0; i < MallocCushion; i++) {
542      if (ptr[i] != badResourceValue) {
543        report_heap_error(memblock, ptr+i, "in front of");
544      }
545    }
546    u_char* end = (u_char*)memblock + size + space_after;
547    for (int j = -MallocCushion; j < 0; j++) {
548      if (end[j] != badResourceValue) {
549        report_heap_error(memblock, end+j, "after");
550      }
551    }
552  }
553}
554#endif
555
556void* os::malloc(size_t size) {
557  NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
558  NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
559
560  if (size == 0) {
561    // return a valid pointer if size is zero
562    // if NULL is returned the calling functions assume out of memory.
563    size = 1;
564  }
565
566  NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
567  u_char* ptr = (u_char*)::malloc(size + space_before + space_after);
568#ifdef ASSERT
569  if (ptr == NULL) return NULL;
570  if (MallocCushion) {
571    for (u_char* p = ptr; p < ptr + MallocCushion; p++) *p = (u_char)badResourceValue;
572    u_char* end = ptr + space_before + size;
573    for (u_char* pq = ptr+MallocCushion; pq < end; pq++) *pq = (u_char)uninitBlockPad;
574    for (u_char* q = end; q < end + MallocCushion; q++) *q = (u_char)badResourceValue;
575  }
576  // put size just before data
577  *size_addr_from_base(ptr) = size;
578#endif
579  u_char* memblock = ptr + space_before;
580  if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
581    tty->print_cr("os::malloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, memblock);
582    breakpoint();
583  }
584  debug_only(if (paranoid) verify_block(memblock));
585  if (PrintMalloc && tty != NULL) tty->print_cr("os::malloc " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, memblock);
586  return memblock;
587}
588
589
590void* os::realloc(void *memblock, size_t size) {
591#ifndef ASSERT
592  NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
593  NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
594  return ::realloc(memblock, size);
595#else
596  if (memblock == NULL) {
597    return malloc(size);
598  }
599  if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
600    tty->print_cr("os::realloc caught " PTR_FORMAT, memblock);
601    breakpoint();
602  }
603  verify_block(memblock);
604  NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
605  if (size == 0) return NULL;
606  // always move the block
607  void* ptr = malloc(size);
608  if (PrintMalloc) tty->print_cr("os::remalloc " SIZE_FORMAT " bytes, " PTR_FORMAT " --> " PTR_FORMAT, size, memblock, ptr);
609  // Copy to new memory if malloc didn't fail
610  if ( ptr != NULL ) {
611    memcpy(ptr, memblock, MIN2(size, get_size(memblock)));
612    if (paranoid) verify_block(ptr);
613    if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
614      tty->print_cr("os::realloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr);
615      breakpoint();
616    }
617    free(memblock);
618  }
619  return ptr;
620#endif
621}
622
623
624void  os::free(void *memblock) {
625  NOT_PRODUCT(inc_stat_counter(&num_frees, 1));
626#ifdef ASSERT
627  if (memblock == NULL) return;
628  if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
629    if (tty != NULL) tty->print_cr("os::free caught " PTR_FORMAT, memblock);
630    breakpoint();
631  }
632  verify_block(memblock);
633  NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
634  // Added by detlefs.
635  if (MallocCushion) {
636    u_char* ptr = (u_char*)memblock - space_before;
637    for (u_char* p = ptr; p < ptr + MallocCushion; p++) {
638      guarantee(*p == badResourceValue,
639                "Thing freed should be malloc result.");
640      *p = (u_char)freeBlockPad;
641    }
642    size_t size = get_size(memblock);
643    inc_stat_counter(&free_bytes, size);
644    u_char* end = ptr + space_before + size;
645    for (u_char* q = end; q < end + MallocCushion; q++) {
646      guarantee(*q == badResourceValue,
647                "Thing freed should be malloc result.");
648      *q = (u_char)freeBlockPad;
649    }
650    if (PrintMalloc && tty != NULL)
651      fprintf(stderr, "os::free " SIZE_FORMAT " bytes --> " PTR_FORMAT "\n", size, (uintptr_t)memblock);
652  } else if (PrintMalloc && tty != NULL) {
653    // tty->print_cr("os::free %p", memblock);
654    fprintf(stderr, "os::free " PTR_FORMAT "\n", (uintptr_t)memblock);
655  }
656#endif
657  ::free((char*)memblock - space_before);
658}
659
660void os::init_random(long initval) {
661  _rand_seed = initval;
662}
663
664
665long os::random() {
666  /* standard, well-known linear congruential random generator with
667   * next_rand = (16807*seed) mod (2**31-1)
668   * see
669   * (1) "Random Number Generators: Good Ones Are Hard to Find",
670   *      S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988),
671   * (2) "Two Fast Implementations of the 'Minimal Standard' Random
672   *     Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88.
673  */
674  const long a = 16807;
675  const unsigned long m = 2147483647;
676  const long q = m / a;        assert(q == 127773, "weird math");
677  const long r = m % a;        assert(r == 2836, "weird math");
678
679  // compute az=2^31p+q
680  unsigned long lo = a * (long)(_rand_seed & 0xFFFF);
681  unsigned long hi = a * (long)((unsigned long)_rand_seed >> 16);
682  lo += (hi & 0x7FFF) << 16;
683
684  // if q overflowed, ignore the overflow and increment q
685  if (lo > m) {
686    lo &= m;
687    ++lo;
688  }
689  lo += hi >> 15;
690
691  // if (p+q) overflowed, ignore the overflow and increment (p+q)
692  if (lo > m) {
693    lo &= m;
694    ++lo;
695  }
696  return (_rand_seed = lo);
697}
698
699// The INITIALIZED state is distinguished from the SUSPENDED state because the
700// conditions in which a thread is first started are different from those in which
701// a suspension is resumed.  These differences make it hard for us to apply the
702// tougher checks when starting threads that we want to do when resuming them.
703// However, when start_thread is called as a result of Thread.start, on a Java
704// thread, the operation is synchronized on the Java Thread object.  So there
705// cannot be a race to start the thread and hence for the thread to exit while
706// we are working on it.  Non-Java threads that start Java threads either have
707// to do so in a context in which races are impossible, or should do appropriate
708// locking.
709
710void os::start_thread(Thread* thread) {
711  // guard suspend/resume
712  MutexLockerEx ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag);
713  OSThread* osthread = thread->osthread();
714  osthread->set_state(RUNNABLE);
715  pd_start_thread(thread);
716}
717
718//---------------------------------------------------------------------------
719// Helper functions for fatal error handler
720
721void os::print_hex_dump(outputStream* st, address start, address end, int unitsize) {
722  assert(unitsize == 1 || unitsize == 2 || unitsize == 4 || unitsize == 8, "just checking");
723
724  int cols = 0;
725  int cols_per_line = 0;
726  switch (unitsize) {
727    case 1: cols_per_line = 16; break;
728    case 2: cols_per_line = 8;  break;
729    case 4: cols_per_line = 4;  break;
730    case 8: cols_per_line = 2;  break;
731    default: return;
732  }
733
734  address p = start;
735  st->print(PTR_FORMAT ":   ", start);
736  while (p < end) {
737    switch (unitsize) {
738      case 1: st->print("%02x", *(u1*)p); break;
739      case 2: st->print("%04x", *(u2*)p); break;
740      case 4: st->print("%08x", *(u4*)p); break;
741      case 8: st->print("%016" FORMAT64_MODIFIER "x", *(u8*)p); break;
742    }
743    p += unitsize;
744    cols++;
745    if (cols >= cols_per_line && p < end) {
746       cols = 0;
747       st->cr();
748       st->print(PTR_FORMAT ":   ", p);
749    } else {
750       st->print(" ");
751    }
752  }
753  st->cr();
754}
755
756void os::print_environment_variables(outputStream* st, const char** env_list,
757                                     char* buffer, int len) {
758  if (env_list) {
759    st->print_cr("Environment Variables:");
760
761    for (int i = 0; env_list[i] != NULL; i++) {
762      if (getenv(env_list[i], buffer, len)) {
763        st->print(env_list[i]);
764        st->print("=");
765        st->print_cr(buffer);
766      }
767    }
768  }
769}
770
771void os::print_cpu_info(outputStream* st) {
772  // cpu
773  st->print("CPU:");
774  st->print("total %d", os::processor_count());
775  // It's not safe to query number of active processors after crash
776  // st->print("(active %d)", os::active_processor_count());
777  st->print(" %s", VM_Version::cpu_features());
778  st->cr();
779  pd_print_cpu_info(st);
780}
781
782void os::print_date_and_time(outputStream *st) {
783  time_t tloc;
784  (void)time(&tloc);
785  st->print("time: %s", ctime(&tloc));  // ctime adds newline.
786
787  double t = os::elapsedTime();
788  // NOTE: It tends to crash after a SEGV if we want to printf("%f",...) in
789  //       Linux. Must be a bug in glibc ? Workaround is to round "t" to int
790  //       before printf. We lost some precision, but who cares?
791  st->print_cr("elapsed time: %d seconds", (int)t);
792}
793
794// moved from debug.cpp (used to be find()) but still called from there
795// The verbose parameter is only set by the debug code in one case
796void os::print_location(outputStream* st, intptr_t x, bool verbose) {
797  address addr = (address)x;
798  CodeBlob* b = CodeCache::find_blob_unsafe(addr);
799  if (b != NULL) {
800    if (b->is_buffer_blob()) {
801      // the interpreter is generated into a buffer blob
802      InterpreterCodelet* i = Interpreter::codelet_containing(addr);
803      if (i != NULL) {
804        st->print_cr(INTPTR_FORMAT " is an Interpreter codelet", addr);
805        i->print_on(st);
806        return;
807      }
808      if (Interpreter::contains(addr)) {
809        st->print_cr(INTPTR_FORMAT " is pointing into interpreter code"
810                     " (not bytecode specific)", addr);
811        return;
812      }
813      //
814      if (AdapterHandlerLibrary::contains(b)) {
815        st->print_cr(INTPTR_FORMAT " is an AdapterHandler", addr);
816        AdapterHandlerLibrary::print_handler_on(st, b);
817      }
818      // the stubroutines are generated into a buffer blob
819      StubCodeDesc* d = StubCodeDesc::desc_for(addr);
820      if (d != NULL) {
821        d->print_on(st);
822        if (verbose) st->cr();
823        return;
824      }
825      if (StubRoutines::contains(addr)) {
826        st->print_cr(INTPTR_FORMAT " is pointing to an (unnamed) "
827                     "stub routine", addr);
828        return;
829      }
830      // the InlineCacheBuffer is using stubs generated into a buffer blob
831      if (InlineCacheBuffer::contains(addr)) {
832        st->print_cr(INTPTR_FORMAT " is pointing into InlineCacheBuffer", addr);
833        return;
834      }
835      VtableStub* v = VtableStubs::stub_containing(addr);
836      if (v != NULL) {
837        v->print_on(st);
838        return;
839      }
840    }
841    if (verbose && b->is_nmethod()) {
842      ResourceMark rm;
843      st->print("%#p: Compiled ", addr);
844      ((nmethod*)b)->method()->print_value_on(st);
845      st->print("  = (CodeBlob*)" INTPTR_FORMAT, b);
846      st->cr();
847      return;
848    }
849    st->print(INTPTR_FORMAT " ", b);
850    if ( b->is_nmethod()) {
851      if (b->is_zombie()) {
852        st->print_cr("is zombie nmethod");
853      } else if (b->is_not_entrant()) {
854        st->print_cr("is non-entrant nmethod");
855      }
856    }
857    b->print_on(st);
858    return;
859  }
860
861  if (Universe::heap()->is_in(addr)) {
862    HeapWord* p = Universe::heap()->block_start(addr);
863    bool print = false;
864    // If we couldn't find it it just may mean that heap wasn't parseable
865    // See if we were just given an oop directly
866    if (p != NULL && Universe::heap()->block_is_obj(p)) {
867      print = true;
868    } else if (p == NULL && ((oopDesc*)addr)->is_oop()) {
869      p = (HeapWord*) addr;
870      print = true;
871    }
872    if (print) {
873      st->print_cr(INTPTR_FORMAT " is an oop", addr);
874      oop(p)->print_on(st);
875      if (p != (HeapWord*)x && oop(p)->is_constMethod() &&
876          constMethodOop(p)->contains(addr)) {
877        Thread *thread = Thread::current();
878        HandleMark hm(thread);
879        methodHandle mh (thread, constMethodOop(p)->method());
880        if (!mh->is_native()) {
881          st->print_cr("bci_from(%p) = %d; print_codes():",
882                        addr, mh->bci_from(address(x)));
883          mh->print_codes_on(st);
884        }
885      }
886      return;
887    }
888  } else {
889    if (Universe::heap()->is_in_reserved(addr)) {
890      st->print_cr(INTPTR_FORMAT " is an unallocated location "
891                   "in the heap", addr);
892      return;
893    }
894  }
895  if (JNIHandles::is_global_handle((jobject) addr)) {
896    st->print_cr(INTPTR_FORMAT " is a global jni handle", addr);
897    return;
898  }
899  if (JNIHandles::is_weak_global_handle((jobject) addr)) {
900    st->print_cr(INTPTR_FORMAT " is a weak global jni handle", addr);
901    return;
902  }
903#ifndef PRODUCT
904  // we don't keep the block list in product mode
905  if (JNIHandleBlock::any_contains((jobject) addr)) {
906    st->print_cr(INTPTR_FORMAT " is a local jni handle", addr);
907    return;
908  }
909#endif
910
911  for(JavaThread *thread = Threads::first(); thread; thread = thread->next()) {
912    // Check for privilege stack
913    if (thread->privileged_stack_top() != NULL &&
914        thread->privileged_stack_top()->contains(addr)) {
915      st->print_cr(INTPTR_FORMAT " is pointing into the privilege stack "
916                   "for thread: " INTPTR_FORMAT, addr, thread);
917      if (verbose) thread->print_on(st);
918      return;
919    }
920    // If the addr is a java thread print information about that.
921    if (addr == (address)thread) {
922      if (verbose) {
923        thread->print_on(st);
924      } else {
925        st->print_cr(INTPTR_FORMAT " is a thread", addr);
926      }
927      return;
928    }
929    // If the addr is in the stack region for this thread then report that
930    // and print thread info
931    if (thread->stack_base() >= addr &&
932        addr > (thread->stack_base() - thread->stack_size())) {
933      st->print_cr(INTPTR_FORMAT " is pointing into the stack for thread: "
934                   INTPTR_FORMAT, addr, thread);
935      if (verbose) thread->print_on(st);
936      return;
937    }
938
939  }
940  // Try an OS specific find
941  if (os::find(addr, st)) {
942    return;
943  }
944
945  st->print_cr(INTPTR_FORMAT " is an unknown value", addr);
946}
947
948// Looks like all platforms except IA64 can use the same function to check
949// if C stack is walkable beyond current frame. The check for fp() is not
950// necessary on Sparc, but it's harmless.
951bool os::is_first_C_frame(frame* fr) {
952#ifdef IA64
953  // In order to walk native frames on Itanium, we need to access the unwind
954  // table, which is inside ELF. We don't want to parse ELF after fatal error,
955  // so return true for IA64. If we need to support C stack walking on IA64,
956  // this function needs to be moved to CPU specific files, as fp() on IA64
957  // is register stack, which grows towards higher memory address.
958  return true;
959#endif
960
961  // Load up sp, fp, sender sp and sender fp, check for reasonable values.
962  // Check usp first, because if that's bad the other accessors may fault
963  // on some architectures.  Ditto ufp second, etc.
964  uintptr_t fp_align_mask = (uintptr_t)(sizeof(address)-1);
965  // sp on amd can be 32 bit aligned.
966  uintptr_t sp_align_mask = (uintptr_t)(sizeof(int)-1);
967
968  uintptr_t usp    = (uintptr_t)fr->sp();
969  if ((usp & sp_align_mask) != 0) return true;
970
971  uintptr_t ufp    = (uintptr_t)fr->fp();
972  if ((ufp & fp_align_mask) != 0) return true;
973
974  uintptr_t old_sp = (uintptr_t)fr->sender_sp();
975  if ((old_sp & sp_align_mask) != 0) return true;
976  if (old_sp == 0 || old_sp == (uintptr_t)-1) return true;
977
978  uintptr_t old_fp = (uintptr_t)fr->link();
979  if ((old_fp & fp_align_mask) != 0) return true;
980  if (old_fp == 0 || old_fp == (uintptr_t)-1 || old_fp == ufp) return true;
981
982  // stack grows downwards; if old_fp is below current fp or if the stack
983  // frame is too large, either the stack is corrupted or fp is not saved
984  // on stack (i.e. on x86, ebp may be used as general register). The stack
985  // is not walkable beyond current frame.
986  if (old_fp < ufp) return true;
987  if (old_fp - ufp > 64 * K) return true;
988
989  return false;
990}
991
992#ifdef ASSERT
993extern "C" void test_random() {
994  const double m = 2147483647;
995  double mean = 0.0, variance = 0.0, t;
996  long reps = 10000;
997  unsigned long seed = 1;
998
999  tty->print_cr("seed %ld for %ld repeats...", seed, reps);
1000  os::init_random(seed);
1001  long num;
1002  for (int k = 0; k < reps; k++) {
1003    num = os::random();
1004    double u = (double)num / m;
1005    assert(u >= 0.0 && u <= 1.0, "bad random number!");
1006
1007    // calculate mean and variance of the random sequence
1008    mean += u;
1009    variance += (u*u);
1010  }
1011  mean /= reps;
1012  variance /= (reps - 1);
1013
1014  assert(num == 1043618065, "bad seed");
1015  tty->print_cr("mean of the 1st 10000 numbers: %f", mean);
1016  tty->print_cr("variance of the 1st 10000 numbers: %f", variance);
1017  const double eps = 0.0001;
1018  t = fabsd(mean - 0.5018);
1019  assert(t < eps, "bad mean");
1020  t = (variance - 0.3355) < 0.0 ? -(variance - 0.3355) : variance - 0.3355;
1021  assert(t < eps, "bad variance");
1022}
1023#endif
1024
1025
1026// Set up the boot classpath.
1027
1028char* os::format_boot_path(const char* format_string,
1029                           const char* home,
1030                           int home_len,
1031                           char fileSep,
1032                           char pathSep) {
1033    assert((fileSep == '/' && pathSep == ':') ||
1034           (fileSep == '\\' && pathSep == ';'), "unexpected seperator chars");
1035
1036    // Scan the format string to determine the length of the actual
1037    // boot classpath, and handle platform dependencies as well.
1038    int formatted_path_len = 0;
1039    const char* p;
1040    for (p = format_string; *p != 0; ++p) {
1041        if (*p == '%') formatted_path_len += home_len - 1;
1042        ++formatted_path_len;
1043    }
1044
1045    char* formatted_path = NEW_C_HEAP_ARRAY(char, formatted_path_len + 1);
1046    if (formatted_path == NULL) {
1047        return NULL;
1048    }
1049
1050    // Create boot classpath from format, substituting separator chars and
1051    // java home directory.
1052    char* q = formatted_path;
1053    for (p = format_string; *p != 0; ++p) {
1054        switch (*p) {
1055        case '%':
1056            strcpy(q, home);
1057            q += home_len;
1058            break;
1059        case '/':
1060            *q++ = fileSep;
1061            break;
1062        case ':':
1063            *q++ = pathSep;
1064            break;
1065        default:
1066            *q++ = *p;
1067        }
1068    }
1069    *q = '\0';
1070
1071    assert((q - formatted_path) == formatted_path_len, "formatted_path size botched");
1072    return formatted_path;
1073}
1074
1075
1076bool os::set_boot_path(char fileSep, char pathSep) {
1077    const char* home = Arguments::get_java_home();
1078    int home_len = (int)strlen(home);
1079
1080    static const char* meta_index_dir_format = "%/lib/";
1081    static const char* meta_index_format = "%/lib/meta-index";
1082    char* meta_index = format_boot_path(meta_index_format, home, home_len, fileSep, pathSep);
1083    if (meta_index == NULL) return false;
1084    char* meta_index_dir = format_boot_path(meta_index_dir_format, home, home_len, fileSep, pathSep);
1085    if (meta_index_dir == NULL) return false;
1086    Arguments::set_meta_index_path(meta_index, meta_index_dir);
1087
1088    // Any modification to the JAR-file list, for the boot classpath must be
1089    // aligned with install/install/make/common/Pack.gmk. Note: boot class
1090    // path class JARs, are stripped for StackMapTable to reduce download size.
1091    static const char classpath_format[] =
1092        "%/lib/resources.jar:"
1093        "%/lib/rt.jar:"
1094        "%/lib/sunrsasign.jar:"
1095        "%/lib/jsse.jar:"
1096        "%/lib/jce.jar:"
1097        "%/lib/charsets.jar:"
1098        "%/classes";
1099    char* sysclasspath = format_boot_path(classpath_format, home, home_len, fileSep, pathSep);
1100    if (sysclasspath == NULL) return false;
1101    Arguments::set_sysclasspath(sysclasspath);
1102
1103    return true;
1104}
1105
1106/*
1107 * Splits a path, based on its separator, the number of
1108 * elements is returned back in n.
1109 * It is the callers responsibility to:
1110 *   a> check the value of n, and n may be 0.
1111 *   b> ignore any empty path elements
1112 *   c> free up the data.
1113 */
1114char** os::split_path(const char* path, int* n) {
1115  *n = 0;
1116  if (path == NULL || strlen(path) == 0) {
1117    return NULL;
1118  }
1119  const char psepchar = *os::path_separator();
1120  char* inpath = (char*)NEW_C_HEAP_ARRAY(char, strlen(path) + 1);
1121  if (inpath == NULL) {
1122    return NULL;
1123  }
1124  strncpy(inpath, path, strlen(path));
1125  int count = 1;
1126  char* p = strchr(inpath, psepchar);
1127  // Get a count of elements to allocate memory
1128  while (p != NULL) {
1129    count++;
1130    p++;
1131    p = strchr(p, psepchar);
1132  }
1133  char** opath = (char**) NEW_C_HEAP_ARRAY(char*, count);
1134  if (opath == NULL) {
1135    return NULL;
1136  }
1137
1138  // do the actual splitting
1139  p = inpath;
1140  for (int i = 0 ; i < count ; i++) {
1141    size_t len = strcspn(p, os::path_separator());
1142    if (len > JVM_MAXPATHLEN) {
1143      return NULL;
1144    }
1145    // allocate the string and add terminator storage
1146    char* s  = (char*)NEW_C_HEAP_ARRAY(char, len + 1);
1147    if (s == NULL) {
1148      return NULL;
1149    }
1150    strncpy(s, p, len);
1151    s[len] = '\0';
1152    opath[i] = s;
1153    p += len + 1;
1154  }
1155  FREE_C_HEAP_ARRAY(char, inpath);
1156  *n = count;
1157  return opath;
1158}
1159
1160void os::set_memory_serialize_page(address page) {
1161  int count = log2_intptr(sizeof(class JavaThread)) - log2_intptr(64);
1162  _mem_serialize_page = (volatile int32_t *)page;
1163  // We initialize the serialization page shift count here
1164  // We assume a cache line size of 64 bytes
1165  assert(SerializePageShiftCount == count,
1166         "thread size changed, fix SerializePageShiftCount constant");
1167  set_serialize_page_mask((uintptr_t)(vm_page_size() - sizeof(int32_t)));
1168}
1169
1170static volatile intptr_t SerializePageLock = 0;
1171
1172// This method is called from signal handler when SIGSEGV occurs while the current
1173// thread tries to store to the "read-only" memory serialize page during state
1174// transition.
1175void os::block_on_serialize_page_trap() {
1176  if (TraceSafepoint) {
1177    tty->print_cr("Block until the serialize page permission restored");
1178  }
1179  // When VMThread is holding the SerializePageLock during modifying the
1180  // access permission of the memory serialize page, the following call
1181  // will block until the permission of that page is restored to rw.
1182  // Generally, it is unsafe to manipulate locks in signal handlers, but in
1183  // this case, it's OK as the signal is synchronous and we know precisely when
1184  // it can occur.
1185  Thread::muxAcquire(&SerializePageLock, "set_memory_serialize_page");
1186  Thread::muxRelease(&SerializePageLock);
1187}
1188
1189// Serialize all thread state variables
1190void os::serialize_thread_states() {
1191  // On some platforms such as Solaris & Linux, the time duration of the page
1192  // permission restoration is observed to be much longer than expected  due to
1193  // scheduler starvation problem etc. To avoid the long synchronization
1194  // time and expensive page trap spinning, 'SerializePageLock' is used to block
1195  // the mutator thread if such case is encountered. See bug 6546278 for details.
1196  Thread::muxAcquire(&SerializePageLock, "serialize_thread_states");
1197  os::protect_memory((char *)os::get_memory_serialize_page(),
1198                     os::vm_page_size(), MEM_PROT_READ);
1199  os::protect_memory((char *)os::get_memory_serialize_page(),
1200                     os::vm_page_size(), MEM_PROT_RW);
1201  Thread::muxRelease(&SerializePageLock);
1202}
1203
1204// Returns true if the current stack pointer is above the stack shadow
1205// pages, false otherwise.
1206
1207bool os::stack_shadow_pages_available(Thread *thread, methodHandle method) {
1208  assert(StackRedPages > 0 && StackYellowPages > 0,"Sanity check");
1209  address sp = current_stack_pointer();
1210  // Check if we have StackShadowPages above the yellow zone.  This parameter
1211  // is dependent on the depth of the maximum VM call stack possible from
1212  // the handler for stack overflow.  'instanceof' in the stack overflow
1213  // handler or a println uses at least 8k stack of VM and native code
1214  // respectively.
1215  const int framesize_in_bytes =
1216    Interpreter::size_top_interpreter_activation(method()) * wordSize;
1217  int reserved_area = ((StackShadowPages + StackRedPages + StackYellowPages)
1218                      * vm_page_size()) + framesize_in_bytes;
1219  // The very lower end of the stack
1220  address stack_limit = thread->stack_base() - thread->stack_size();
1221  return (sp > (stack_limit + reserved_area));
1222}
1223
1224size_t os::page_size_for_region(size_t region_min_size, size_t region_max_size,
1225                                uint min_pages)
1226{
1227  assert(min_pages > 0, "sanity");
1228  if (UseLargePages) {
1229    const size_t max_page_size = region_max_size / min_pages;
1230
1231    for (unsigned int i = 0; _page_sizes[i] != 0; ++i) {
1232      const size_t sz = _page_sizes[i];
1233      const size_t mask = sz - 1;
1234      if ((region_min_size & mask) == 0 && (region_max_size & mask) == 0) {
1235        // The largest page size with no fragmentation.
1236        return sz;
1237      }
1238
1239      if (sz <= max_page_size) {
1240        // The largest page size that satisfies the min_pages requirement.
1241        return sz;
1242      }
1243    }
1244  }
1245
1246  return vm_page_size();
1247}
1248
1249#ifndef PRODUCT
1250void os::trace_page_sizes(const char* str, const size_t* page_sizes, int count)
1251{
1252  if (TracePageSizes) {
1253    tty->print("%s: ", str);
1254    for (int i = 0; i < count; ++i) {
1255      tty->print(" " SIZE_FORMAT, page_sizes[i]);
1256    }
1257    tty->cr();
1258  }
1259}
1260
1261void os::trace_page_sizes(const char* str, const size_t region_min_size,
1262                          const size_t region_max_size, const size_t page_size,
1263                          const char* base, const size_t size)
1264{
1265  if (TracePageSizes) {
1266    tty->print_cr("%s:  min=" SIZE_FORMAT " max=" SIZE_FORMAT
1267                  " pg_sz=" SIZE_FORMAT " base=" PTR_FORMAT
1268                  " size=" SIZE_FORMAT,
1269                  str, region_min_size, region_max_size,
1270                  page_size, base, size);
1271  }
1272}
1273#endif  // #ifndef PRODUCT
1274
1275// This is the working definition of a server class machine:
1276// >= 2 physical CPU's and >=2GB of memory, with some fuzz
1277// because the graphics memory (?) sometimes masks physical memory.
1278// If you want to change the definition of a server class machine
1279// on some OS or platform, e.g., >=4GB on Windohs platforms,
1280// then you'll have to parameterize this method based on that state,
1281// as was done for logical processors here, or replicate and
1282// specialize this method for each platform.  (Or fix os to have
1283// some inheritance structure and use subclassing.  Sigh.)
1284// If you want some platform to always or never behave as a server
1285// class machine, change the setting of AlwaysActAsServerClassMachine
1286// and NeverActAsServerClassMachine in globals*.hpp.
1287bool os::is_server_class_machine() {
1288  // First check for the early returns
1289  if (NeverActAsServerClassMachine) {
1290    return false;
1291  }
1292  if (AlwaysActAsServerClassMachine) {
1293    return true;
1294  }
1295  // Then actually look at the machine
1296  bool         result            = false;
1297  const unsigned int    server_processors = 2;
1298  const julong server_memory     = 2UL * G;
1299  // We seem not to get our full complement of memory.
1300  //     We allow some part (1/8?) of the memory to be "missing",
1301  //     based on the sizes of DIMMs, and maybe graphics cards.
1302  const julong missing_memory   = 256UL * M;
1303
1304  /* Is this a server class machine? */
1305  if ((os::active_processor_count() >= (int)server_processors) &&
1306      (os::physical_memory() >= (server_memory - missing_memory))) {
1307    const unsigned int logical_processors =
1308      VM_Version::logical_processors_per_package();
1309    if (logical_processors > 1) {
1310      const unsigned int physical_packages =
1311        os::active_processor_count() / logical_processors;
1312      if (physical_packages > server_processors) {
1313        result = true;
1314      }
1315    } else {
1316      result = true;
1317    }
1318  }
1319  return result;
1320}
1321
1322// Read file line by line, if line is longer than bsize,
1323// skip rest of line.
1324int os::get_line_chars(int fd, char* buf, const size_t bsize){
1325  size_t sz, i = 0;
1326
1327  // read until EOF, EOL or buf is full
1328  while ((sz = (int) read(fd, &buf[i], 1)) == 1 && i < (bsize-2) && buf[i] != '\n') {
1329     ++i;
1330  }
1331
1332  if (buf[i] == '\n') {
1333    // EOL reached so ignore EOL character and return
1334
1335    buf[i] = 0;
1336    return (int) i;
1337  }
1338
1339  buf[i+1] = 0;
1340
1341  if (sz != 1) {
1342    // EOF reached. if we read chars before EOF return them and
1343    // return EOF on next call otherwise return EOF
1344
1345    return (i == 0) ? -1 : (int) i;
1346  }
1347
1348  // line is longer than size of buf, skip to EOL
1349  char ch;
1350  while (read(fd, &ch, 1) == 1 && ch != '\n') {
1351    // Do nothing
1352  }
1353
1354  // return initial part of line that fits in buf.
1355  // If we reached EOF, it will be returned on next call.
1356
1357  return (int) i;
1358}
1359