1 /*
2 * Copyright (c) 1997, 2020, 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 "jvm.h"
27 #include "classfile/classLoader.hpp"
28 #include "classfile/javaClasses.hpp"
29 #include "classfile/moduleEntry.hpp"
30 #include "classfile/systemDictionary.hpp"
31 #include "classfile/vmSymbols.hpp"
32 #include "code/codeCache.hpp"
33 #include "code/icBuffer.hpp"
34 #include "code/vtableStubs.hpp"
35 #include "gc/shared/gcVMOperations.hpp"
36 #include "logging/log.hpp"
37 #include "interpreter/interpreter.hpp"
38 #include "logging/log.hpp"
39 #include "logging/logStream.hpp"
40 #include "memory/allocation.inline.hpp"
41 #include "memory/guardedMemory.hpp"
42 #include "memory/resourceArea.hpp"
43 #include "memory/universe.hpp"
44 #include "oops/compressedOops.inline.hpp"
45 #include "oops/oop.inline.hpp"
46 #include "prims/jvm_misc.hpp"
47 #include "runtime/arguments.hpp"
48 #include "runtime/atomic.hpp"
49 #include "runtime/frame.inline.hpp"
50 #include "runtime/handles.inline.hpp"
51 #include "runtime/interfaceSupport.inline.hpp"
52 #include "runtime/java.hpp"
53 #include "runtime/javaCalls.hpp"
54 #include "runtime/mutexLocker.hpp"
55 #include "runtime/os.inline.hpp"
56 #include "runtime/sharedRuntime.hpp"
57 #include "runtime/stubRoutines.hpp"
58 #include "runtime/thread.inline.hpp"
59 #include "runtime/threadSMR.hpp"
60 #include "runtime/vm_version.hpp"
61 #include "services/attachListener.hpp"
62 #include "services/mallocTracker.hpp"
63 #include "services/memTracker.hpp"
64 #include "services/nmtCommon.hpp"
65 #include "services/threadService.hpp"
66 #include "utilities/align.hpp"
67 #include "utilities/defaultStream.hpp"
68 #include "utilities/events.hpp"
69
70 # include <signal.h>
71 # include <errno.h>
72
73 OSThread* os::_starting_thread = NULL;
74 address os::_polling_page = NULL;
75 volatile unsigned int os::_rand_seed = 1;
76 int os::_processor_count = 0;
77 int os::_initial_active_processor_count = 0;
78 size_t os::_page_sizes[os::page_sizes_max];
79
80 #ifndef PRODUCT
81 julong os::num_mallocs = 0; // # of calls to malloc/realloc
82 julong os::alloc_bytes = 0; // # of bytes allocated
83 julong os::num_frees = 0; // # of calls to free
84 julong os::free_bytes = 0; // # of bytes freed
85 #endif
86
87 static size_t cur_malloc_words = 0; // current size for MallocMaxTestWords
88
DEBUG_ONLY(bool os::_mutex_init_done=false;)89 DEBUG_ONLY(bool os::_mutex_init_done = false;)
90
91 static time_t get_timezone(const struct tm* time_struct) {
92 #if defined(_ALLBSD_SOURCE)
93 return time_struct->tm_gmtoff;
94 #elif defined(_WINDOWS)
95 long zone;
96 _get_timezone(&zone);
97 return static_cast<time_t>(zone);
98 #else
99 return timezone;
100 #endif
101 }
102
snprintf(char * buf,size_t len,const char * fmt,...)103 int os::snprintf(char* buf, size_t len, const char* fmt, ...) {
104 va_list args;
105 va_start(args, fmt);
106 int result = os::vsnprintf(buf, len, fmt, args);
107 va_end(args);
108 return result;
109 }
110
111 // Fill in buffer with current local time as an ISO-8601 string.
112 // E.g., yyyy-mm-ddThh:mm:ss-zzzz.
113 // Returns buffer, or NULL if it failed.
114 // This would mostly be a call to
115 // strftime(...., "%Y-%m-%d" "T" "%H:%M:%S" "%z", ....)
116 // except that on Windows the %z behaves badly, so we do it ourselves.
117 // Also, people wanted milliseconds on there,
118 // and strftime doesn't do milliseconds.
iso8601_time(char * buffer,size_t buffer_length,bool utc)119 char* os::iso8601_time(char* buffer, size_t buffer_length, bool utc) {
120 // Output will be of the form "YYYY-MM-DDThh:mm:ss.mmm+zzzz\0"
121 // 1 2
122 // 12345678901234567890123456789
123 // format string: "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d"
124 static const size_t needed_buffer = 29;
125
126 // Sanity check the arguments
127 if (buffer == NULL) {
128 assert(false, "NULL buffer");
129 return NULL;
130 }
131 if (buffer_length < needed_buffer) {
132 assert(false, "buffer_length too small");
133 return NULL;
134 }
135 // Get the current time
136 jlong milliseconds_since_19700101 = javaTimeMillis();
137 const int milliseconds_per_microsecond = 1000;
138 const time_t seconds_since_19700101 =
139 milliseconds_since_19700101 / milliseconds_per_microsecond;
140 const int milliseconds_after_second =
141 milliseconds_since_19700101 % milliseconds_per_microsecond;
142 // Convert the time value to a tm and timezone variable
143 struct tm time_struct;
144 if (utc) {
145 if (gmtime_pd(&seconds_since_19700101, &time_struct) == NULL) {
146 assert(false, "Failed gmtime_pd");
147 return NULL;
148 }
149 } else {
150 if (localtime_pd(&seconds_since_19700101, &time_struct) == NULL) {
151 assert(false, "Failed localtime_pd");
152 return NULL;
153 }
154 }
155 const time_t zone = get_timezone(&time_struct);
156
157 // If daylight savings time is in effect,
158 // we are 1 hour East of our time zone
159 const time_t seconds_per_minute = 60;
160 const time_t minutes_per_hour = 60;
161 const time_t seconds_per_hour = seconds_per_minute * minutes_per_hour;
162 time_t UTC_to_local = zone;
163 if (time_struct.tm_isdst > 0) {
164 UTC_to_local = UTC_to_local - seconds_per_hour;
165 }
166
167 // No offset when dealing with UTC
168 if (utc) {
169 UTC_to_local = 0;
170 }
171
172 // Compute the time zone offset.
173 // localtime_pd() sets timezone to the difference (in seconds)
174 // between UTC and and local time.
175 // ISO 8601 says we need the difference between local time and UTC,
176 // we change the sign of the localtime_pd() result.
177 const time_t local_to_UTC = -(UTC_to_local);
178 // Then we have to figure out if if we are ahead (+) or behind (-) UTC.
179 char sign_local_to_UTC = '+';
180 time_t abs_local_to_UTC = local_to_UTC;
181 if (local_to_UTC < 0) {
182 sign_local_to_UTC = '-';
183 abs_local_to_UTC = -(abs_local_to_UTC);
184 }
185 // Convert time zone offset seconds to hours and minutes.
186 const time_t zone_hours = (abs_local_to_UTC / seconds_per_hour);
187 const time_t zone_min =
188 ((abs_local_to_UTC % seconds_per_hour) / seconds_per_minute);
189
190 // Print an ISO 8601 date and time stamp into the buffer
191 const int year = 1900 + time_struct.tm_year;
192 const int month = 1 + time_struct.tm_mon;
193 const int printed = jio_snprintf(buffer, buffer_length,
194 "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d",
195 year,
196 month,
197 time_struct.tm_mday,
198 time_struct.tm_hour,
199 time_struct.tm_min,
200 time_struct.tm_sec,
201 milliseconds_after_second,
202 sign_local_to_UTC,
203 zone_hours,
204 zone_min);
205 if (printed == 0) {
206 assert(false, "Failed jio_printf");
207 return NULL;
208 }
209 return buffer;
210 }
211
set_priority(Thread * thread,ThreadPriority p)212 OSReturn os::set_priority(Thread* thread, ThreadPriority p) {
213 debug_only(Thread::check_for_dangling_thread_pointer(thread);)
214
215 if ((p >= MinPriority && p <= MaxPriority) ||
216 (p == CriticalPriority && thread->is_ConcurrentGC_thread())) {
217 int priority = java_to_os_priority[p];
218 return set_native_priority(thread, priority);
219 } else {
220 assert(false, "Should not happen");
221 return OS_ERR;
222 }
223 }
224
225 // The mapping from OS priority back to Java priority may be inexact because
226 // Java priorities can map M:1 with native priorities. If you want the definite
227 // Java priority then use JavaThread::java_priority()
get_priority(const Thread * const thread,ThreadPriority & priority)228 OSReturn os::get_priority(const Thread* const thread, ThreadPriority& priority) {
229 int p;
230 int os_prio;
231 OSReturn ret = get_native_priority(thread, &os_prio);
232 if (ret != OS_OK) return ret;
233
234 if (java_to_os_priority[MaxPriority] > java_to_os_priority[MinPriority]) {
235 for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] > os_prio; p--) ;
236 } else {
237 // niceness values are in reverse order
238 for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] < os_prio; p--) ;
239 }
240 priority = (ThreadPriority)p;
241 return OS_OK;
242 }
243
dll_build_name(char * buffer,size_t size,const char * fname)244 bool os::dll_build_name(char* buffer, size_t size, const char* fname) {
245 int n = jio_snprintf(buffer, size, "%s%s%s", JNI_LIB_PREFIX, fname, JNI_LIB_SUFFIX);
246 return (n != -1);
247 }
248
249 #if !defined(LINUX) && !defined(_WINDOWS)
committed_in_range(address start,size_t size,address & committed_start,size_t & committed_size)250 bool os::committed_in_range(address start, size_t size, address& committed_start, size_t& committed_size) {
251 committed_start = start;
252 committed_size = size;
253 return true;
254 }
255 #endif
256
257 // Helper for dll_locate_lib.
258 // Pass buffer and printbuffer as we already printed the path to buffer
259 // when we called get_current_directory. This way we avoid another buffer
260 // of size MAX_PATH.
conc_path_file_and_check(char * buffer,char * printbuffer,size_t printbuflen,const char * pname,char lastchar,const char * fname)261 static bool conc_path_file_and_check(char *buffer, char *printbuffer, size_t printbuflen,
262 const char* pname, char lastchar, const char* fname) {
263
264 // Concatenate path and file name, but don't print double path separators.
265 const char *filesep = (WINDOWS_ONLY(lastchar == ':' ||) lastchar == os::file_separator()[0]) ?
266 "" : os::file_separator();
267 int ret = jio_snprintf(printbuffer, printbuflen, "%s%s%s", pname, filesep, fname);
268 // Check whether file exists.
269 if (ret != -1) {
270 struct stat statbuf;
271 return os::stat(buffer, &statbuf) == 0;
272 }
273 return false;
274 }
275
276 // Frees all memory allocated on the heap for the
277 // supplied array of arrays of chars (a), where n
278 // is the number of elements in the array.
free_array_of_char_arrays(char ** a,size_t n)279 static void free_array_of_char_arrays(char** a, size_t n) {
280 while (n > 0) {
281 n--;
282 if (a[n] != NULL) {
283 FREE_C_HEAP_ARRAY(char, a[n]);
284 }
285 }
286 FREE_C_HEAP_ARRAY(char*, a);
287 }
288
dll_locate_lib(char * buffer,size_t buflen,const char * pname,const char * fname)289 bool os::dll_locate_lib(char *buffer, size_t buflen,
290 const char* pname, const char* fname) {
291 bool retval = false;
292
293 size_t fullfnamelen = strlen(JNI_LIB_PREFIX) + strlen(fname) + strlen(JNI_LIB_SUFFIX);
294 char* fullfname = NEW_C_HEAP_ARRAY(char, fullfnamelen + 1, mtInternal);
295 if (dll_build_name(fullfname, fullfnamelen + 1, fname)) {
296 const size_t pnamelen = pname ? strlen(pname) : 0;
297
298 if (pnamelen == 0) {
299 // If no path given, use current working directory.
300 const char* p = get_current_directory(buffer, buflen);
301 if (p != NULL) {
302 const size_t plen = strlen(buffer);
303 const char lastchar = buffer[plen - 1];
304 retval = conc_path_file_and_check(buffer, &buffer[plen], buflen - plen,
305 "", lastchar, fullfname);
306 }
307 } else if (strchr(pname, *os::path_separator()) != NULL) {
308 // A list of paths. Search for the path that contains the library.
309 size_t n;
310 char** pelements = split_path(pname, &n, fullfnamelen);
311 if (pelements != NULL) {
312 for (size_t i = 0; i < n; i++) {
313 char* path = pelements[i];
314 // Really shouldn't be NULL, but check can't hurt.
315 size_t plen = (path == NULL) ? 0 : strlen(path);
316 if (plen == 0) {
317 continue; // Skip the empty path values.
318 }
319 const char lastchar = path[plen - 1];
320 retval = conc_path_file_and_check(buffer, buffer, buflen, path, lastchar, fullfname);
321 if (retval) break;
322 }
323 // Release the storage allocated by split_path.
324 free_array_of_char_arrays(pelements, n);
325 }
326 } else {
327 // A definite path.
328 const char lastchar = pname[pnamelen-1];
329 retval = conc_path_file_and_check(buffer, buffer, buflen, pname, lastchar, fullfname);
330 }
331 }
332
333 FREE_C_HEAP_ARRAY(char*, fullfname);
334 return retval;
335 }
336
337 // --------------------- sun.misc.Signal (optional) ---------------------
338
339
340 // SIGBREAK is sent by the keyboard to query the VM state
341 #ifndef SIGBREAK
342 #define SIGBREAK SIGQUIT
343 #endif
344
345 // sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread.
346
347
signal_thread_entry(JavaThread * thread,TRAPS)348 static void signal_thread_entry(JavaThread* thread, TRAPS) {
349 os::set_priority(thread, NearMaxPriority);
350 while (true) {
351 int sig;
352 {
353 // FIXME : Currently we have not decided what should be the status
354 // for this java thread blocked here. Once we decide about
355 // that we should fix this.
356 sig = os::signal_wait();
357 }
358 if (sig == os::sigexitnum_pd()) {
359 // Terminate the signal thread
360 return;
361 }
362
363 switch (sig) {
364 case SIGBREAK: {
365 #if INCLUDE_SERVICES
366 // Check if the signal is a trigger to start the Attach Listener - in that
367 // case don't print stack traces.
368 if (!DisableAttachMechanism) {
369 // Attempt to transit state to AL_INITIALIZING.
370 AttachListenerState cur_state = AttachListener::transit_state(AL_INITIALIZING, AL_NOT_INITIALIZED);
371 if (cur_state == AL_INITIALIZING) {
372 // Attach Listener has been started to initialize. Ignore this signal.
373 continue;
374 } else if (cur_state == AL_NOT_INITIALIZED) {
375 // Start to initialize.
376 if (AttachListener::is_init_trigger()) {
377 // Attach Listener has been initialized.
378 // Accept subsequent request.
379 continue;
380 } else {
381 // Attach Listener could not be started.
382 // So we need to transit the state to AL_NOT_INITIALIZED.
383 AttachListener::set_state(AL_NOT_INITIALIZED);
384 }
385 } else if (AttachListener::check_socket_file()) {
386 // Attach Listener has been started, but unix domain socket file
387 // does not exist. So restart Attach Listener.
388 continue;
389 }
390 }
391 #endif
392 // Print stack traces
393 // Any SIGBREAK operations added here should make sure to flush
394 // the output stream (e.g. tty->flush()) after output. See 4803766.
395 // Each module also prints an extra carriage return after its output.
396 VM_PrintThreads op;
397 VMThread::execute(&op);
398 VM_PrintJNI jni_op;
399 VMThread::execute(&jni_op);
400 VM_FindDeadlocks op1(tty);
401 VMThread::execute(&op1);
402 Universe::print_heap_at_SIGBREAK();
403 if (PrintClassHistogram) {
404 VM_GC_HeapInspection op1(tty, true /* force full GC before heap inspection */);
405 VMThread::execute(&op1);
406 }
407 if (JvmtiExport::should_post_data_dump()) {
408 JvmtiExport::post_data_dump();
409 }
410 break;
411 }
412 default: {
413 // Dispatch the signal to java
414 HandleMark hm(THREAD);
415 Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_misc_Signal(), THREAD);
416 if (klass != NULL) {
417 JavaValue result(T_VOID);
418 JavaCallArguments args;
419 args.push_int(sig);
420 JavaCalls::call_static(
421 &result,
422 klass,
423 vmSymbols::dispatch_name(),
424 vmSymbols::int_void_signature(),
425 &args,
426 THREAD
427 );
428 }
429 if (HAS_PENDING_EXCEPTION) {
430 // tty is initialized early so we don't expect it to be null, but
431 // if it is we can't risk doing an initialization that might
432 // trigger additional out-of-memory conditions
433 if (tty != NULL) {
434 char klass_name[256];
435 char tmp_sig_name[16];
436 const char* sig_name = "UNKNOWN";
437 InstanceKlass::cast(PENDING_EXCEPTION->klass())->
438 name()->as_klass_external_name(klass_name, 256);
439 if (os::exception_name(sig, tmp_sig_name, 16) != NULL)
440 sig_name = tmp_sig_name;
441 warning("Exception %s occurred dispatching signal %s to handler"
442 "- the VM may need to be forcibly terminated",
443 klass_name, sig_name );
444 }
445 CLEAR_PENDING_EXCEPTION;
446 }
447 }
448 }
449 }
450 }
451
init_before_ergo()452 void os::init_before_ergo() {
453 initialize_initial_active_processor_count();
454 // We need to initialize large page support here because ergonomics takes some
455 // decisions depending on large page support and the calculated large page size.
456 large_page_init();
457
458 // We need to adapt the configured number of stack protection pages given
459 // in 4K pages to the actual os page size. We must do this before setting
460 // up minimal stack sizes etc. in os::init_2().
461 JavaThread::set_stack_red_zone_size (align_up(StackRedPages * 4 * K, vm_page_size()));
462 JavaThread::set_stack_yellow_zone_size (align_up(StackYellowPages * 4 * K, vm_page_size()));
463 JavaThread::set_stack_reserved_zone_size(align_up(StackReservedPages * 4 * K, vm_page_size()));
464 JavaThread::set_stack_shadow_zone_size (align_up(StackShadowPages * 4 * K, vm_page_size()));
465
466 // VM version initialization identifies some characteristics of the
467 // platform that are used during ergonomic decisions.
468 VM_Version::init_before_ergo();
469 }
470
initialize_jdk_signal_support(TRAPS)471 void os::initialize_jdk_signal_support(TRAPS) {
472 if (!ReduceSignalUsage) {
473 // Setup JavaThread for processing signals
474 const char thread_name[] = "Signal Dispatcher";
475 Handle string = java_lang_String::create_from_str(thread_name, CHECK);
476
477 // Initialize thread_oop to put it into the system threadGroup
478 Handle thread_group (THREAD, Universe::system_thread_group());
479 Handle thread_oop = JavaCalls::construct_new_instance(SystemDictionary::Thread_klass(),
480 vmSymbols::threadgroup_string_void_signature(),
481 thread_group,
482 string,
483 CHECK);
484
485 Klass* group = SystemDictionary::ThreadGroup_klass();
486 JavaValue result(T_VOID);
487 JavaCalls::call_special(&result,
488 thread_group,
489 group,
490 vmSymbols::add_method_name(),
491 vmSymbols::thread_void_signature(),
492 thread_oop,
493 CHECK);
494
495 { MutexLocker mu(THREAD, Threads_lock);
496 JavaThread* signal_thread = new JavaThread(&signal_thread_entry);
497
498 // At this point it may be possible that no osthread was created for the
499 // JavaThread due to lack of memory. We would have to throw an exception
500 // in that case. However, since this must work and we do not allow
501 // exceptions anyway, check and abort if this fails.
502 if (signal_thread == NULL || signal_thread->osthread() == NULL) {
503 vm_exit_during_initialization("java.lang.OutOfMemoryError",
504 os::native_thread_creation_failed_msg());
505 }
506
507 java_lang_Thread::set_thread(thread_oop(), signal_thread);
508 java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
509 java_lang_Thread::set_daemon(thread_oop());
510
511 signal_thread->set_threadObj(thread_oop());
512 Threads::add(signal_thread);
513 Thread::start(signal_thread);
514 }
515 // Handle ^BREAK
516 os::signal(SIGBREAK, os::user_handler());
517 }
518 }
519
520
terminate_signal_thread()521 void os::terminate_signal_thread() {
522 if (!ReduceSignalUsage)
523 signal_notify(sigexitnum_pd());
524 }
525
526
527 // --------------------- loading libraries ---------------------
528
529 typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
530 extern struct JavaVM_ main_vm;
531
532 static void* _native_java_library = NULL;
533
native_java_library()534 void* os::native_java_library() {
535 if (_native_java_library == NULL) {
536 char buffer[JVM_MAXPATHLEN];
537 char ebuf[1024];
538
539 // Load java dll
540 if (dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
541 "java")) {
542 _native_java_library = dll_load(buffer, ebuf, sizeof(ebuf));
543 }
544 if (_native_java_library == NULL) {
545 vm_exit_during_initialization("Unable to load native library", ebuf);
546 }
547 }
548 return _native_java_library;
549 }
550
551 /*
552 * Support for finding Agent_On(Un)Load/Attach<_lib_name> if it exists.
553 * If check_lib == true then we are looking for an
554 * Agent_OnLoad_lib_name or Agent_OnAttach_lib_name function to determine if
555 * this library is statically linked into the image.
556 * If check_lib == false then we will look for the appropriate symbol in the
557 * executable if agent_lib->is_static_lib() == true or in the shared library
558 * referenced by 'handle'.
559 */
find_agent_function(AgentLibrary * agent_lib,bool check_lib,const char * syms[],size_t syms_len)560 void* os::find_agent_function(AgentLibrary *agent_lib, bool check_lib,
561 const char *syms[], size_t syms_len) {
562 assert(agent_lib != NULL, "sanity check");
563 const char *lib_name;
564 void *handle = agent_lib->os_lib();
565 void *entryName = NULL;
566 char *agent_function_name;
567 size_t i;
568
569 // If checking then use the agent name otherwise test is_static_lib() to
570 // see how to process this lookup
571 lib_name = ((check_lib || agent_lib->is_static_lib()) ? agent_lib->name() : NULL);
572 for (i = 0; i < syms_len; i++) {
573 agent_function_name = build_agent_function_name(syms[i], lib_name, agent_lib->is_absolute_path());
574 if (agent_function_name == NULL) {
575 break;
576 }
577 entryName = dll_lookup(handle, agent_function_name);
578 FREE_C_HEAP_ARRAY(char, agent_function_name);
579 if (entryName != NULL) {
580 break;
581 }
582 }
583 return entryName;
584 }
585
586 // See if the passed in agent is statically linked into the VM image.
find_builtin_agent(AgentLibrary * agent_lib,const char * syms[],size_t syms_len)587 bool os::find_builtin_agent(AgentLibrary *agent_lib, const char *syms[],
588 size_t syms_len) {
589 void *ret;
590 void *proc_handle;
591 void *save_handle;
592
593 assert(agent_lib != NULL, "sanity check");
594 if (agent_lib->name() == NULL) {
595 return false;
596 }
597 proc_handle = get_default_process_handle();
598 // Check for Agent_OnLoad/Attach_lib_name function
599 save_handle = agent_lib->os_lib();
600 // We want to look in this process' symbol table.
601 agent_lib->set_os_lib(proc_handle);
602 ret = find_agent_function(agent_lib, true, syms, syms_len);
603 if (ret != NULL) {
604 // Found an entry point like Agent_OnLoad_lib_name so we have a static agent
605 agent_lib->set_valid();
606 agent_lib->set_static_lib(true);
607 return true;
608 }
609 agent_lib->set_os_lib(save_handle);
610 return false;
611 }
612
613 // --------------------- heap allocation utilities ---------------------
614
strdup(const char * str,MEMFLAGS flags)615 char *os::strdup(const char *str, MEMFLAGS flags) {
616 size_t size = strlen(str);
617 char *dup_str = (char *)malloc(size + 1, flags);
618 if (dup_str == NULL) return NULL;
619 strcpy(dup_str, str);
620 return dup_str;
621 }
622
strdup_check_oom(const char * str,MEMFLAGS flags)623 char* os::strdup_check_oom(const char* str, MEMFLAGS flags) {
624 char* p = os::strdup(str, flags);
625 if (p == NULL) {
626 vm_exit_out_of_memory(strlen(str) + 1, OOM_MALLOC_ERROR, "os::strdup_check_oom");
627 }
628 return p;
629 }
630
631
632 #define paranoid 0 /* only set to 1 if you suspect checking code has bug */
633
634 #ifdef ASSERT
635
verify_memory(void * ptr)636 static void verify_memory(void* ptr) {
637 GuardedMemory guarded(ptr);
638 if (!guarded.verify_guards()) {
639 LogTarget(Warning, malloc, free) lt;
640 ResourceMark rm;
641 LogStream ls(lt);
642 ls.print_cr("## nof_mallocs = " UINT64_FORMAT ", nof_frees = " UINT64_FORMAT, os::num_mallocs, os::num_frees);
643 ls.print_cr("## memory stomp:");
644 guarded.print_on(&ls);
645 fatal("memory stomping error");
646 }
647 }
648
649 #endif
650
651 //
652 // This function supports testing of the malloc out of memory
653 // condition without really running the system out of memory.
654 //
has_reached_max_malloc_test_peak(size_t alloc_size)655 static bool has_reached_max_malloc_test_peak(size_t alloc_size) {
656 if (MallocMaxTestWords > 0) {
657 size_t words = (alloc_size / BytesPerWord);
658
659 if ((cur_malloc_words + words) > MallocMaxTestWords) {
660 return true;
661 }
662 Atomic::add(&cur_malloc_words, words);
663 }
664 return false;
665 }
666
malloc(size_t size,MEMFLAGS flags)667 void* os::malloc(size_t size, MEMFLAGS flags) {
668 return os::malloc(size, flags, CALLER_PC);
669 }
670
malloc(size_t size,MEMFLAGS memflags,const NativeCallStack & stack)671 void* os::malloc(size_t size, MEMFLAGS memflags, const NativeCallStack& stack) {
672 NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
673 NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
674
675 // Since os::malloc can be called when the libjvm.{dll,so} is
676 // first loaded and we don't have a thread yet we must accept NULL also here.
677 assert(!os::ThreadCrashProtection::is_crash_protected(Thread::current_or_null()),
678 "malloc() not allowed when crash protection is set");
679
680 if (size == 0) {
681 // return a valid pointer if size is zero
682 // if NULL is returned the calling functions assume out of memory.
683 size = 1;
684 }
685
686 // NMT support
687 NMT_TrackingLevel level = MemTracker::tracking_level();
688 size_t nmt_header_size = MemTracker::malloc_header_size(level);
689
690 #ifndef ASSERT
691 const size_t alloc_size = size + nmt_header_size;
692 #else
693 const size_t alloc_size = GuardedMemory::get_total_size(size + nmt_header_size);
694 if (size + nmt_header_size > alloc_size) { // Check for rollover.
695 return NULL;
696 }
697 #endif
698
699 // For the test flag -XX:MallocMaxTestWords
700 if (has_reached_max_malloc_test_peak(size)) {
701 return NULL;
702 }
703
704 u_char* ptr;
705 ptr = (u_char*)::malloc(alloc_size);
706
707 #ifdef ASSERT
708 if (ptr == NULL) {
709 return NULL;
710 }
711 // Wrap memory with guard
712 GuardedMemory guarded(ptr, size + nmt_header_size);
713 ptr = guarded.get_user_ptr();
714
715 if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
716 log_warning(malloc, free)("os::malloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, p2i(ptr));
717 breakpoint();
718 }
719 if (paranoid) {
720 verify_memory(ptr);
721 }
722 #endif
723
724 // we do not track guard memory
725 return MemTracker::record_malloc((address)ptr, size, memflags, stack, level);
726 }
727
realloc(void * memblock,size_t size,MEMFLAGS flags)728 void* os::realloc(void *memblock, size_t size, MEMFLAGS flags) {
729 return os::realloc(memblock, size, flags, CALLER_PC);
730 }
731
realloc(void * memblock,size_t size,MEMFLAGS memflags,const NativeCallStack & stack)732 void* os::realloc(void *memblock, size_t size, MEMFLAGS memflags, const NativeCallStack& stack) {
733
734 // For the test flag -XX:MallocMaxTestWords
735 if (has_reached_max_malloc_test_peak(size)) {
736 return NULL;
737 }
738
739 if (size == 0) {
740 // return a valid pointer if size is zero
741 // if NULL is returned the calling functions assume out of memory.
742 size = 1;
743 }
744
745 #ifndef ASSERT
746 NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
747 NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
748 // NMT support
749 NMT_TrackingLevel level = MemTracker::tracking_level();
750 void* membase = MemTracker::record_free(memblock, level);
751 size_t nmt_header_size = MemTracker::malloc_header_size(level);
752 void* ptr = ::realloc(membase, size + nmt_header_size);
753 return MemTracker::record_malloc(ptr, size, memflags, stack, level);
754 #else
755 if (memblock == NULL) {
756 return os::malloc(size, memflags, stack);
757 }
758 if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
759 log_warning(malloc, free)("os::realloc caught " PTR_FORMAT, p2i(memblock));
760 breakpoint();
761 }
762 // NMT support
763 void* membase = MemTracker::malloc_base(memblock);
764 verify_memory(membase);
765 // always move the block
766 void* ptr = os::malloc(size, memflags, stack);
767 // Copy to new memory if malloc didn't fail
768 if (ptr != NULL ) {
769 GuardedMemory guarded(MemTracker::malloc_base(memblock));
770 // Guard's user data contains NMT header
771 size_t memblock_size = guarded.get_user_size() - MemTracker::malloc_header_size(memblock);
772 memcpy(ptr, memblock, MIN2(size, memblock_size));
773 if (paranoid) {
774 verify_memory(MemTracker::malloc_base(ptr));
775 }
776 os::free(memblock);
777 }
778 return ptr;
779 #endif
780 }
781
782 // handles NULL pointers
free(void * memblock)783 void os::free(void *memblock) {
784 NOT_PRODUCT(inc_stat_counter(&num_frees, 1));
785 #ifdef ASSERT
786 if (memblock == NULL) return;
787 if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
788 log_warning(malloc, free)("os::free caught " PTR_FORMAT, p2i(memblock));
789 breakpoint();
790 }
791 void* membase = MemTracker::record_free(memblock, MemTracker::tracking_level());
792 verify_memory(membase);
793
794 GuardedMemory guarded(membase);
795 size_t size = guarded.get_user_size();
796 inc_stat_counter(&free_bytes, size);
797 membase = guarded.release_for_freeing();
798 ::free(membase);
799 #else
800 void* membase = MemTracker::record_free(memblock, MemTracker::tracking_level());
801 ::free(membase);
802 #endif
803 }
804
init_random(unsigned int initval)805 void os::init_random(unsigned int initval) {
806 _rand_seed = initval;
807 }
808
809
random_helper(unsigned int rand_seed)810 static int random_helper(unsigned int rand_seed) {
811 /* standard, well-known linear congruential random generator with
812 * next_rand = (16807*seed) mod (2**31-1)
813 * see
814 * (1) "Random Number Generators: Good Ones Are Hard to Find",
815 * S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988),
816 * (2) "Two Fast Implementations of the 'Minimal Standard' Random
817 * Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88.
818 */
819 const unsigned int a = 16807;
820 const unsigned int m = 2147483647;
821 const int q = m / a; assert(q == 127773, "weird math");
822 const int r = m % a; assert(r == 2836, "weird math");
823
824 // compute az=2^31p+q
825 unsigned int lo = a * (rand_seed & 0xFFFF);
826 unsigned int hi = a * (rand_seed >> 16);
827 lo += (hi & 0x7FFF) << 16;
828
829 // if q overflowed, ignore the overflow and increment q
830 if (lo > m) {
831 lo &= m;
832 ++lo;
833 }
834 lo += hi >> 15;
835
836 // if (p+q) overflowed, ignore the overflow and increment (p+q)
837 if (lo > m) {
838 lo &= m;
839 ++lo;
840 }
841 return lo;
842 }
843
random()844 int os::random() {
845 // Make updating the random seed thread safe.
846 while (true) {
847 unsigned int seed = _rand_seed;
848 unsigned int rand = random_helper(seed);
849 if (Atomic::cmpxchg(&_rand_seed, seed, rand) == seed) {
850 return static_cast<int>(rand);
851 }
852 }
853 }
854
855 // The INITIALIZED state is distinguished from the SUSPENDED state because the
856 // conditions in which a thread is first started are different from those in which
857 // a suspension is resumed. These differences make it hard for us to apply the
858 // tougher checks when starting threads that we want to do when resuming them.
859 // However, when start_thread is called as a result of Thread.start, on a Java
860 // thread, the operation is synchronized on the Java Thread object. So there
861 // cannot be a race to start the thread and hence for the thread to exit while
862 // we are working on it. Non-Java threads that start Java threads either have
863 // to do so in a context in which races are impossible, or should do appropriate
864 // locking.
865
start_thread(Thread * thread)866 void os::start_thread(Thread* thread) {
867 // guard suspend/resume
868 MutexLocker ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag);
869 OSThread* osthread = thread->osthread();
870 osthread->set_state(RUNNABLE);
871 pd_start_thread(thread);
872 }
873
abort(bool dump_core)874 void os::abort(bool dump_core) {
875 abort(dump_core && CreateCoredumpOnCrash, NULL, NULL);
876 }
877
878 //---------------------------------------------------------------------------
879 // Helper functions for fatal error handler
880
print_hex_dump(outputStream * st,address start,address end,int unitsize)881 void os::print_hex_dump(outputStream* st, address start, address end, int unitsize) {
882 assert(unitsize == 1 || unitsize == 2 || unitsize == 4 || unitsize == 8, "just checking");
883
884 start = align_down(start, unitsize);
885
886 int cols = 0;
887 int cols_per_line = 0;
888 switch (unitsize) {
889 case 1: cols_per_line = 16; break;
890 case 2: cols_per_line = 8; break;
891 case 4: cols_per_line = 4; break;
892 case 8: cols_per_line = 2; break;
893 default: return;
894 }
895
896 address p = start;
897 st->print(PTR_FORMAT ": ", p2i(start));
898 while (p < end) {
899 if (is_readable_pointer(p)) {
900 switch (unitsize) {
901 case 1: st->print("%02x", *(u1*)p); break;
902 case 2: st->print("%04x", *(u2*)p); break;
903 case 4: st->print("%08x", *(u4*)p); break;
904 case 8: st->print("%016" FORMAT64_MODIFIER "x", *(u8*)p); break;
905 }
906 } else {
907 st->print("%*.*s", 2*unitsize, 2*unitsize, "????????????????");
908 }
909 p += unitsize;
910 cols++;
911 if (cols >= cols_per_line && p < end) {
912 cols = 0;
913 st->cr();
914 st->print(PTR_FORMAT ": ", p2i(p));
915 } else {
916 st->print(" ");
917 }
918 }
919 st->cr();
920 }
921
print_dhm(outputStream * st,const char * startStr,long sec)922 void os::print_dhm(outputStream* st, const char* startStr, long sec) {
923 long days = sec/86400;
924 long hours = (sec/3600) - (days * 24);
925 long minutes = (sec/60) - (days * 1440) - (hours * 60);
926 if (startStr == NULL) startStr = "";
927 st->print_cr("%s %ld days %ld:%02ld hours", startStr, days, hours, minutes);
928 }
929
print_instructions(outputStream * st,address pc,int unitsize)930 void os::print_instructions(outputStream* st, address pc, int unitsize) {
931 st->print_cr("Instructions: (pc=" PTR_FORMAT ")", p2i(pc));
932 print_hex_dump(st, pc - 256, pc + 256, unitsize);
933 }
934
print_environment_variables(outputStream * st,const char ** env_list)935 void os::print_environment_variables(outputStream* st, const char** env_list) {
936 if (env_list) {
937 st->print_cr("Environment Variables:");
938
939 for (int i = 0; env_list[i] != NULL; i++) {
940 char *envvar = ::getenv(env_list[i]);
941 if (envvar != NULL) {
942 st->print("%s", env_list[i]);
943 st->print("=");
944 st->print_cr("%s", envvar);
945 }
946 }
947 }
948 }
949
print_cpu_info(outputStream * st,char * buf,size_t buflen)950 void os::print_cpu_info(outputStream* st, char* buf, size_t buflen) {
951 // cpu
952 st->print("CPU:");
953 st->print(" total %d", os::processor_count());
954 // It's not safe to query number of active processors after crash
955 // st->print("(active %d)", os::active_processor_count()); but we can
956 // print the initial number of active processors.
957 // We access the raw value here because the assert in the accessor will
958 // fail if the crash occurs before initialization of this value.
959 st->print(" (initial active %d)", _initial_active_processor_count);
960 st->print(" %s", VM_Version::features_string());
961 st->cr();
962 pd_print_cpu_info(st, buf, buflen);
963 }
964
965 // Print a one line string summarizing the cpu, number of cores, memory, and operating system version
print_summary_info(outputStream * st,char * buf,size_t buflen)966 void os::print_summary_info(outputStream* st, char* buf, size_t buflen) {
967 st->print("Host: ");
968 #ifndef PRODUCT
969 if (get_host_name(buf, buflen)) {
970 st->print("%s, ", buf);
971 }
972 #endif // PRODUCT
973 get_summary_cpu_info(buf, buflen);
974 st->print("%s, ", buf);
975 size_t mem = physical_memory()/G;
976 if (mem == 0) { // for low memory systems
977 mem = physical_memory()/M;
978 st->print("%d cores, " SIZE_FORMAT "M, ", processor_count(), mem);
979 } else {
980 st->print("%d cores, " SIZE_FORMAT "G, ", processor_count(), mem);
981 }
982 get_summary_os_info(buf, buflen);
983 st->print_raw(buf);
984 st->cr();
985 }
986
print_date_and_time(outputStream * st,char * buf,size_t buflen)987 void os::print_date_and_time(outputStream *st, char* buf, size_t buflen) {
988 const int secs_per_day = 86400;
989 const int secs_per_hour = 3600;
990 const int secs_per_min = 60;
991
992 time_t tloc;
993 (void)time(&tloc);
994 char* timestring = ctime(&tloc); // ctime adds newline.
995 // edit out the newline
996 char* nl = strchr(timestring, '\n');
997 if (nl != NULL) {
998 *nl = '\0';
999 }
1000
1001 struct tm tz;
1002 if (localtime_pd(&tloc, &tz) != NULL) {
1003 ::strftime(buf, buflen, "%Z", &tz);
1004 st->print("Time: %s %s", timestring, buf);
1005 } else {
1006 st->print("Time: %s", timestring);
1007 }
1008
1009 double t = os::elapsedTime();
1010 // NOTE: a crash using printf("%f",...) on Linux was historically noted here.
1011 int eltime = (int)t; // elapsed time in seconds
1012 int eltimeFraction = (int) ((t - eltime) * 1000000);
1013
1014 // print elapsed time in a human-readable format:
1015 int eldays = eltime / secs_per_day;
1016 int day_secs = eldays * secs_per_day;
1017 int elhours = (eltime - day_secs) / secs_per_hour;
1018 int hour_secs = elhours * secs_per_hour;
1019 int elmins = (eltime - day_secs - hour_secs) / secs_per_min;
1020 int minute_secs = elmins * secs_per_min;
1021 int elsecs = (eltime - day_secs - hour_secs - minute_secs);
1022 st->print_cr(" elapsed time: %d.%06d seconds (%dd %dh %dm %ds)", eltime, eltimeFraction, eldays, elhours, elmins, elsecs);
1023 }
1024
1025
1026 // Check if pointer can be read from (4-byte read access).
1027 // Helps to prove validity of a not-NULL pointer.
1028 // Returns true in very early stages of VM life when stub is not yet generated.
1029 #define SAFEFETCH_DEFAULT true
is_readable_pointer(const void * p)1030 bool os::is_readable_pointer(const void* p) {
1031 if (!CanUseSafeFetch32()) {
1032 return SAFEFETCH_DEFAULT;
1033 }
1034 int* const aligned = (int*) align_down((intptr_t)p, 4);
1035 int cafebabe = 0xcafebabe; // tester value 1
1036 int deadbeef = 0xdeadbeef; // tester value 2
1037 return (SafeFetch32(aligned, cafebabe) != cafebabe) || (SafeFetch32(aligned, deadbeef) != deadbeef);
1038 }
1039
is_readable_range(const void * from,const void * to)1040 bool os::is_readable_range(const void* from, const void* to) {
1041 if ((uintptr_t)from >= (uintptr_t)to) return false;
1042 for (uintptr_t p = align_down((uintptr_t)from, min_page_size()); p < (uintptr_t)to; p += min_page_size()) {
1043 if (!is_readable_pointer((const void*)p)) {
1044 return false;
1045 }
1046 }
1047 return true;
1048 }
1049
1050
1051 // moved from debug.cpp (used to be find()) but still called from there
1052 // The verbose parameter is only set by the debug code in one case
print_location(outputStream * st,intptr_t x,bool verbose)1053 void os::print_location(outputStream* st, intptr_t x, bool verbose) {
1054 address addr = (address)x;
1055 // Handle NULL first, so later checks don't need to protect against it.
1056 if (addr == NULL) {
1057 st->print_cr("0x0 is NULL");
1058 return;
1059 }
1060
1061 // Check if addr points into a code blob.
1062 CodeBlob* b = CodeCache::find_blob_unsafe(addr);
1063 if (b != NULL) {
1064 b->dump_for_addr(addr, st, verbose);
1065 return;
1066 }
1067
1068 // Check if addr points into Java heap.
1069 if (Universe::heap()->print_location(st, addr)) {
1070 return;
1071 }
1072
1073 bool accessible = is_readable_pointer(addr);
1074
1075 // Check if addr is a JNI handle.
1076 if (align_down((intptr_t)addr, sizeof(intptr_t)) != 0 && accessible) {
1077 if (JNIHandles::is_global_handle((jobject) addr)) {
1078 st->print_cr(INTPTR_FORMAT " is a global jni handle", p2i(addr));
1079 return;
1080 }
1081 if (JNIHandles::is_weak_global_handle((jobject) addr)) {
1082 st->print_cr(INTPTR_FORMAT " is a weak global jni handle", p2i(addr));
1083 return;
1084 }
1085 #ifndef PRODUCT
1086 // we don't keep the block list in product mode
1087 if (JNIHandles::is_local_handle((jobject) addr)) {
1088 st->print_cr(INTPTR_FORMAT " is a local jni handle", p2i(addr));
1089 return;
1090 }
1091 #endif
1092 }
1093
1094 // Check if addr belongs to a Java thread.
1095 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) {
1096 // If the addr is a java thread print information about that.
1097 if (addr == (address)thread) {
1098 if (verbose) {
1099 thread->print_on(st);
1100 } else {
1101 st->print_cr(INTPTR_FORMAT " is a thread", p2i(addr));
1102 }
1103 return;
1104 }
1105 // If the addr is in the stack region for this thread then report that
1106 // and print thread info
1107 if (thread->is_in_full_stack(addr)) {
1108 st->print_cr(INTPTR_FORMAT " is pointing into the stack for thread: "
1109 INTPTR_FORMAT, p2i(addr), p2i(thread));
1110 if (verbose) thread->print_on(st);
1111 return;
1112 }
1113 }
1114
1115 // Check if in metaspace and print types that have vptrs
1116 if (Metaspace::contains(addr)) {
1117 if (Klass::is_valid((Klass*)addr)) {
1118 st->print_cr(INTPTR_FORMAT " is a pointer to class: ", p2i(addr));
1119 ((Klass*)addr)->print_on(st);
1120 } else if (Method::is_valid_method((const Method*)addr)) {
1121 ((Method*)addr)->print_value_on(st);
1122 st->cr();
1123 } else {
1124 // Use addr->print() from the debugger instead (not here)
1125 st->print_cr(INTPTR_FORMAT " is pointing into metadata", p2i(addr));
1126 }
1127 return;
1128 }
1129
1130 // Compressed klass needs to be decoded first.
1131 #ifdef _LP64
1132 if (UseCompressedClassPointers && ((uintptr_t)addr &~ (uintptr_t)max_juint) == 0) {
1133 narrowKlass narrow_klass = (narrowKlass)(uintptr_t)addr;
1134 Klass* k = CompressedKlassPointers::decode_raw(narrow_klass);
1135
1136 if (Klass::is_valid(k)) {
1137 st->print_cr(UINT32_FORMAT " is a compressed pointer to class: " INTPTR_FORMAT, narrow_klass, p2i((HeapWord*)k));
1138 k->print_on(st);
1139 return;
1140 }
1141 }
1142 #endif
1143
1144 // Try an OS specific find
1145 if (os::find(addr, st)) {
1146 return;
1147 }
1148
1149 if (accessible) {
1150 st->print(INTPTR_FORMAT " points into unknown readable memory:", p2i(addr));
1151 if (is_aligned(addr, sizeof(intptr_t))) {
1152 st->print(" " PTR_FORMAT " |", *(intptr_t*)addr);
1153 }
1154 for (address p = addr; p < align_up(addr + 1, sizeof(intptr_t)); ++p) {
1155 st->print(" %02x", *(u1*)p);
1156 }
1157 st->cr();
1158 return;
1159 }
1160
1161 st->print_cr(INTPTR_FORMAT " is an unknown value", p2i(addr));
1162 }
1163
1164 // Looks like all platforms can use the same function to check if C
1165 // stack is walkable beyond current frame. The check for fp() is not
1166 // necessary on Sparc, but it's harmless.
is_first_C_frame(frame * fr)1167 bool os::is_first_C_frame(frame* fr) {
1168 // Load up sp, fp, sender sp and sender fp, check for reasonable values.
1169 // Check usp first, because if that's bad the other accessors may fault
1170 // on some architectures. Ditto ufp second, etc.
1171 uintptr_t fp_align_mask = (uintptr_t)(sizeof(address)-1);
1172 // sp on amd can be 32 bit aligned.
1173 uintptr_t sp_align_mask = (uintptr_t)(sizeof(int)-1);
1174
1175 uintptr_t usp = (uintptr_t)fr->sp();
1176 if ((usp & sp_align_mask) != 0) return true;
1177
1178 uintptr_t ufp = (uintptr_t)fr->fp();
1179 if ((ufp & fp_align_mask) != 0) return true;
1180
1181 uintptr_t old_sp = (uintptr_t)fr->sender_sp();
1182 if ((old_sp & sp_align_mask) != 0) return true;
1183 if (old_sp == 0 || old_sp == (uintptr_t)-1) return true;
1184
1185 uintptr_t old_fp = (uintptr_t)fr->link();
1186 if ((old_fp & fp_align_mask) != 0) return true;
1187 if (old_fp == 0 || old_fp == (uintptr_t)-1 || old_fp == ufp) return true;
1188
1189 // stack grows downwards; if old_fp is below current fp or if the stack
1190 // frame is too large, either the stack is corrupted or fp is not saved
1191 // on stack (i.e. on x86, ebp may be used as general register). The stack
1192 // is not walkable beyond current frame.
1193 if (old_fp < ufp) return true;
1194 if (old_fp - ufp > 64 * K) return true;
1195
1196 return false;
1197 }
1198
1199
1200 // Set up the boot classpath.
1201
format_boot_path(const char * format_string,const char * home,int home_len,char fileSep,char pathSep)1202 char* os::format_boot_path(const char* format_string,
1203 const char* home,
1204 int home_len,
1205 char fileSep,
1206 char pathSep) {
1207 assert((fileSep == '/' && pathSep == ':') ||
1208 (fileSep == '\\' && pathSep == ';'), "unexpected separator chars");
1209
1210 // Scan the format string to determine the length of the actual
1211 // boot classpath, and handle platform dependencies as well.
1212 int formatted_path_len = 0;
1213 const char* p;
1214 for (p = format_string; *p != 0; ++p) {
1215 if (*p == '%') formatted_path_len += home_len - 1;
1216 ++formatted_path_len;
1217 }
1218
1219 char* formatted_path = NEW_C_HEAP_ARRAY(char, formatted_path_len + 1, mtInternal);
1220
1221 // Create boot classpath from format, substituting separator chars and
1222 // java home directory.
1223 char* q = formatted_path;
1224 for (p = format_string; *p != 0; ++p) {
1225 switch (*p) {
1226 case '%':
1227 strcpy(q, home);
1228 q += home_len;
1229 break;
1230 case '/':
1231 *q++ = fileSep;
1232 break;
1233 case ':':
1234 *q++ = pathSep;
1235 break;
1236 default:
1237 *q++ = *p;
1238 }
1239 }
1240 *q = '\0';
1241
1242 assert((q - formatted_path) == formatted_path_len, "formatted_path size botched");
1243 return formatted_path;
1244 }
1245
1246 // This function is a proxy to fopen, it tries to add a non standard flag ('e' or 'N')
1247 // that ensures automatic closing of the file on exec. If it can not find support in
1248 // the underlying c library, it will make an extra system call (fcntl) to ensure automatic
1249 // closing of the file on exec.
fopen(const char * path,const char * mode)1250 FILE* os::fopen(const char* path, const char* mode) {
1251 char modified_mode[20];
1252 assert(strlen(mode) + 1 < sizeof(modified_mode), "mode chars plus one extra must fit in buffer");
1253 sprintf(modified_mode, "%s" LINUX_ONLY("e") BSD_ONLY("e") WINDOWS_ONLY("N"), mode);
1254 FILE* file = ::fopen(path, modified_mode);
1255
1256 #if !(defined LINUX || defined BSD || defined _WINDOWS)
1257 // assume fcntl FD_CLOEXEC support as a backup solution when 'e' or 'N'
1258 // is not supported as mode in fopen
1259 if (file != NULL) {
1260 int fd = fileno(file);
1261 if (fd != -1) {
1262 int fd_flags = fcntl(fd, F_GETFD);
1263 if (fd_flags != -1) {
1264 fcntl(fd, F_SETFD, fd_flags | FD_CLOEXEC);
1265 }
1266 }
1267 }
1268 #endif
1269
1270 return file;
1271 }
1272
set_boot_path(char fileSep,char pathSep)1273 bool os::set_boot_path(char fileSep, char pathSep) {
1274 const char* home = Arguments::get_java_home();
1275 int home_len = (int)strlen(home);
1276
1277 struct stat st;
1278
1279 // modular image if "modules" jimage exists
1280 char* jimage = format_boot_path("%/lib/" MODULES_IMAGE_NAME, home, home_len, fileSep, pathSep);
1281 if (jimage == NULL) return false;
1282 bool has_jimage = (os::stat(jimage, &st) == 0);
1283 if (has_jimage) {
1284 Arguments::set_sysclasspath(jimage, true);
1285 FREE_C_HEAP_ARRAY(char, jimage);
1286 return true;
1287 }
1288 FREE_C_HEAP_ARRAY(char, jimage);
1289
1290 // check if developer build with exploded modules
1291 char* base_classes = format_boot_path("%/modules/" JAVA_BASE_NAME, home, home_len, fileSep, pathSep);
1292 if (base_classes == NULL) return false;
1293 if (os::stat(base_classes, &st) == 0) {
1294 Arguments::set_sysclasspath(base_classes, false);
1295 FREE_C_HEAP_ARRAY(char, base_classes);
1296 return true;
1297 }
1298 FREE_C_HEAP_ARRAY(char, base_classes);
1299
1300 return false;
1301 }
1302
1303 // Splits a path, based on its separator, the number of
1304 // elements is returned back in "elements".
1305 // file_name_length is used as a modifier for each path's
1306 // length when compared to JVM_MAXPATHLEN. So if you know
1307 // each returned path will have something appended when
1308 // in use, you can pass the length of that in
1309 // file_name_length, to ensure we detect if any path
1310 // exceeds the maximum path length once prepended onto
1311 // the sub-path/file name.
1312 // It is the callers responsibility to:
1313 // a> check the value of "elements", which may be 0.
1314 // b> ignore any empty path elements
1315 // c> free up the data.
split_path(const char * path,size_t * elements,size_t file_name_length)1316 char** os::split_path(const char* path, size_t* elements, size_t file_name_length) {
1317 *elements = (size_t)0;
1318 if (path == NULL || strlen(path) == 0 || file_name_length == (size_t)NULL) {
1319 return NULL;
1320 }
1321 const char psepchar = *os::path_separator();
1322 char* inpath = NEW_C_HEAP_ARRAY(char, strlen(path) + 1, mtInternal);
1323 strcpy(inpath, path);
1324 size_t count = 1;
1325 char* p = strchr(inpath, psepchar);
1326 // Get a count of elements to allocate memory
1327 while (p != NULL) {
1328 count++;
1329 p++;
1330 p = strchr(p, psepchar);
1331 }
1332
1333 char** opath = NEW_C_HEAP_ARRAY(char*, count, mtInternal);
1334
1335 // do the actual splitting
1336 p = inpath;
1337 for (size_t i = 0 ; i < count ; i++) {
1338 size_t len = strcspn(p, os::path_separator());
1339 if (len + file_name_length > JVM_MAXPATHLEN) {
1340 // release allocated storage before exiting the vm
1341 free_array_of_char_arrays(opath, i++);
1342 vm_exit_during_initialization("The VM tried to use a path that exceeds the maximum path length for "
1343 "this system. Review path-containing parameters and properties, such as "
1344 "sun.boot.library.path, to identify potential sources for this path.");
1345 }
1346 // allocate the string and add terminator storage
1347 char* s = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
1348 strncpy(s, p, len);
1349 s[len] = '\0';
1350 opath[i] = s;
1351 p += len + 1;
1352 }
1353 FREE_C_HEAP_ARRAY(char, inpath);
1354 *elements = count;
1355 return opath;
1356 }
1357
1358 // Returns true if the current stack pointer is above the stack shadow
1359 // pages, false otherwise.
stack_shadow_pages_available(Thread * thread,const methodHandle & method,address sp)1360 bool os::stack_shadow_pages_available(Thread *thread, const methodHandle& method, address sp) {
1361 if (!thread->is_Java_thread()) return false;
1362 // Check if we have StackShadowPages above the yellow zone. This parameter
1363 // is dependent on the depth of the maximum VM call stack possible from
1364 // the handler for stack overflow. 'instanceof' in the stack overflow
1365 // handler or a println uses at least 8k stack of VM and native code
1366 // respectively.
1367 const int framesize_in_bytes =
1368 Interpreter::size_top_interpreter_activation(method()) * wordSize;
1369
1370 address limit = ((JavaThread*)thread)->stack_end() +
1371 (JavaThread::stack_guard_zone_size() + JavaThread::stack_shadow_zone_size());
1372
1373 return sp > (limit + framesize_in_bytes);
1374 }
1375
page_size_for_region(size_t region_size,size_t min_pages,bool must_be_aligned)1376 size_t os::page_size_for_region(size_t region_size, size_t min_pages, bool must_be_aligned) {
1377 assert(min_pages > 0, "sanity");
1378 if (UseLargePages) {
1379 const size_t max_page_size = region_size / min_pages;
1380
1381 for (size_t i = 0; _page_sizes[i] != 0; ++i) {
1382 const size_t page_size = _page_sizes[i];
1383 if (page_size <= max_page_size) {
1384 if (!must_be_aligned || is_aligned(region_size, page_size)) {
1385 return page_size;
1386 }
1387 }
1388 }
1389 }
1390
1391 return vm_page_size();
1392 }
1393
page_size_for_region_aligned(size_t region_size,size_t min_pages)1394 size_t os::page_size_for_region_aligned(size_t region_size, size_t min_pages) {
1395 return page_size_for_region(region_size, min_pages, true);
1396 }
1397
page_size_for_region_unaligned(size_t region_size,size_t min_pages)1398 size_t os::page_size_for_region_unaligned(size_t region_size, size_t min_pages) {
1399 return page_size_for_region(region_size, min_pages, false);
1400 }
1401
errno_to_string(int e,bool short_text)1402 static const char* errno_to_string (int e, bool short_text) {
1403 #define ALL_SHARED_ENUMS(X) \
1404 X(E2BIG, "Argument list too long") \
1405 X(EACCES, "Permission denied") \
1406 X(EADDRINUSE, "Address in use") \
1407 X(EADDRNOTAVAIL, "Address not available") \
1408 X(EAFNOSUPPORT, "Address family not supported") \
1409 X(EAGAIN, "Resource unavailable, try again") \
1410 X(EALREADY, "Connection already in progress") \
1411 X(EBADF, "Bad file descriptor") \
1412 X(EBADMSG, "Bad message") \
1413 X(EBUSY, "Device or resource busy") \
1414 X(ECANCELED, "Operation canceled") \
1415 X(ECHILD, "No child processes") \
1416 X(ECONNABORTED, "Connection aborted") \
1417 X(ECONNREFUSED, "Connection refused") \
1418 X(ECONNRESET, "Connection reset") \
1419 X(EDEADLK, "Resource deadlock would occur") \
1420 X(EDESTADDRREQ, "Destination address required") \
1421 X(EDOM, "Mathematics argument out of domain of function") \
1422 X(EEXIST, "File exists") \
1423 X(EFAULT, "Bad address") \
1424 X(EFBIG, "File too large") \
1425 X(EHOSTUNREACH, "Host is unreachable") \
1426 X(EIDRM, "Identifier removed") \
1427 X(EILSEQ, "Illegal byte sequence") \
1428 X(EINPROGRESS, "Operation in progress") \
1429 X(EINTR, "Interrupted function") \
1430 X(EINVAL, "Invalid argument") \
1431 X(EIO, "I/O error") \
1432 X(EISCONN, "Socket is connected") \
1433 X(EISDIR, "Is a directory") \
1434 X(ELOOP, "Too many levels of symbolic links") \
1435 X(EMFILE, "Too many open files") \
1436 X(EMLINK, "Too many links") \
1437 X(EMSGSIZE, "Message too large") \
1438 X(ENAMETOOLONG, "Filename too long") \
1439 X(ENETDOWN, "Network is down") \
1440 X(ENETRESET, "Connection aborted by network") \
1441 X(ENETUNREACH, "Network unreachable") \
1442 X(ENFILE, "Too many files open in system") \
1443 X(ENOBUFS, "No buffer space available") \
1444 X(ENODEV, "No such device") \
1445 X(ENOENT, "No such file or directory") \
1446 X(ENOEXEC, "Executable file format error") \
1447 X(ENOLCK, "No locks available") \
1448 X(ENOMEM, "Not enough space") \
1449 X(ENOMSG, "No message of the desired type") \
1450 X(ENOPROTOOPT, "Protocol not available") \
1451 X(ENOSPC, "No space left on device") \
1452 X(ENOSYS, "Function not supported") \
1453 X(ENOTCONN, "The socket is not connected") \
1454 X(ENOTDIR, "Not a directory") \
1455 X(ENOTEMPTY, "Directory not empty") \
1456 X(ENOTSOCK, "Not a socket") \
1457 X(ENOTSUP, "Not supported") \
1458 X(ENOTTY, "Inappropriate I/O control operation") \
1459 X(ENXIO, "No such device or address") \
1460 X(EOPNOTSUPP, "Operation not supported on socket") \
1461 X(EOVERFLOW, "Value too large to be stored in data type") \
1462 X(EPERM, "Operation not permitted") \
1463 X(EPIPE, "Broken pipe") \
1464 X(EPROTO, "Protocol error") \
1465 X(EPROTONOSUPPORT, "Protocol not supported") \
1466 X(EPROTOTYPE, "Protocol wrong type for socket") \
1467 X(ERANGE, "Result too large") \
1468 X(EROFS, "Read-only file system") \
1469 X(ESPIPE, "Invalid seek") \
1470 X(ESRCH, "No such process") \
1471 X(ETIMEDOUT, "Connection timed out") \
1472 X(ETXTBSY, "Text file busy") \
1473 X(EWOULDBLOCK, "Operation would block") \
1474 X(EXDEV, "Cross-device link")
1475
1476 #define DEFINE_ENTRY(e, text) { e, #e, text },
1477
1478 static const struct {
1479 int v;
1480 const char* short_text;
1481 const char* long_text;
1482 } table [] = {
1483
1484 ALL_SHARED_ENUMS(DEFINE_ENTRY)
1485
1486 // The following enums are not defined on all platforms.
1487 #ifdef ESTALE
1488 DEFINE_ENTRY(ESTALE, "Reserved")
1489 #endif
1490 #ifdef EDQUOT
1491 DEFINE_ENTRY(EDQUOT, "Reserved")
1492 #endif
1493 #ifdef EMULTIHOP
1494 DEFINE_ENTRY(EMULTIHOP, "Reserved")
1495 #endif
1496 #ifdef ENODATA
1497 DEFINE_ENTRY(ENODATA, "No message is available on the STREAM head read queue")
1498 #endif
1499 #ifdef ENOLINK
1500 DEFINE_ENTRY(ENOLINK, "Reserved")
1501 #endif
1502 #ifdef ENOSR
1503 DEFINE_ENTRY(ENOSR, "No STREAM resources")
1504 #endif
1505 #ifdef ENOSTR
1506 DEFINE_ENTRY(ENOSTR, "Not a STREAM")
1507 #endif
1508 #ifdef ETIME
1509 DEFINE_ENTRY(ETIME, "Stream ioctl() timeout")
1510 #endif
1511
1512 // End marker.
1513 { -1, "Unknown errno", "Unknown error" }
1514
1515 };
1516
1517 #undef DEFINE_ENTRY
1518 #undef ALL_FLAGS
1519
1520 int i = 0;
1521 while (table[i].v != -1 && table[i].v != e) {
1522 i ++;
1523 }
1524
1525 return short_text ? table[i].short_text : table[i].long_text;
1526
1527 }
1528
strerror(int e)1529 const char* os::strerror(int e) {
1530 return errno_to_string(e, false);
1531 }
1532
errno_name(int e)1533 const char* os::errno_name(int e) {
1534 return errno_to_string(e, true);
1535 }
1536
trace_page_sizes(const char * str,const size_t * page_sizes,int count)1537 void os::trace_page_sizes(const char* str, const size_t* page_sizes, int count) {
1538 LogTarget(Info, pagesize) log;
1539 if (log.is_enabled()) {
1540 LogStream out(log);
1541
1542 out.print("%s: ", str);
1543 for (int i = 0; i < count; ++i) {
1544 out.print(" " SIZE_FORMAT, page_sizes[i]);
1545 }
1546 out.cr();
1547 }
1548 }
1549
1550 #define trace_page_size_params(size) byte_size_in_exact_unit(size), exact_unit_for_byte_size(size)
1551
trace_page_sizes(const char * str,const size_t region_min_size,const size_t region_max_size,const size_t page_size,const char * base,const size_t size)1552 void os::trace_page_sizes(const char* str,
1553 const size_t region_min_size,
1554 const size_t region_max_size,
1555 const size_t page_size,
1556 const char* base,
1557 const size_t size) {
1558
1559 log_info(pagesize)("%s: "
1560 " min=" SIZE_FORMAT "%s"
1561 " max=" SIZE_FORMAT "%s"
1562 " base=" PTR_FORMAT
1563 " page_size=" SIZE_FORMAT "%s"
1564 " size=" SIZE_FORMAT "%s",
1565 str,
1566 trace_page_size_params(region_min_size),
1567 trace_page_size_params(region_max_size),
1568 p2i(base),
1569 trace_page_size_params(page_size),
1570 trace_page_size_params(size));
1571 }
1572
trace_page_sizes_for_requested_size(const char * str,const size_t requested_size,const size_t page_size,const size_t alignment,const char * base,const size_t size)1573 void os::trace_page_sizes_for_requested_size(const char* str,
1574 const size_t requested_size,
1575 const size_t page_size,
1576 const size_t alignment,
1577 const char* base,
1578 const size_t size) {
1579
1580 log_info(pagesize)("%s:"
1581 " req_size=" SIZE_FORMAT "%s"
1582 " base=" PTR_FORMAT
1583 " page_size=" SIZE_FORMAT "%s"
1584 " alignment=" SIZE_FORMAT "%s"
1585 " size=" SIZE_FORMAT "%s",
1586 str,
1587 trace_page_size_params(requested_size),
1588 p2i(base),
1589 trace_page_size_params(page_size),
1590 trace_page_size_params(alignment),
1591 trace_page_size_params(size));
1592 }
1593
1594
1595 // This is the working definition of a server class machine:
1596 // >= 2 physical CPU's and >=2GB of memory, with some fuzz
1597 // because the graphics memory (?) sometimes masks physical memory.
1598 // If you want to change the definition of a server class machine
1599 // on some OS or platform, e.g., >=4GB on Windows platforms,
1600 // then you'll have to parameterize this method based on that state,
1601 // as was done for logical processors here, or replicate and
1602 // specialize this method for each platform. (Or fix os to have
1603 // some inheritance structure and use subclassing. Sigh.)
1604 // If you want some platform to always or never behave as a server
1605 // class machine, change the setting of AlwaysActAsServerClassMachine
1606 // and NeverActAsServerClassMachine in globals*.hpp.
is_server_class_machine()1607 bool os::is_server_class_machine() {
1608 // First check for the early returns
1609 if (NeverActAsServerClassMachine) {
1610 return false;
1611 }
1612 if (AlwaysActAsServerClassMachine) {
1613 return true;
1614 }
1615 // Then actually look at the machine
1616 bool result = false;
1617 const unsigned int server_processors = 2;
1618 const julong server_memory = 2UL * G;
1619 // We seem not to get our full complement of memory.
1620 // We allow some part (1/8?) of the memory to be "missing",
1621 // based on the sizes of DIMMs, and maybe graphics cards.
1622 const julong missing_memory = 256UL * M;
1623
1624 /* Is this a server class machine? */
1625 if ((os::active_processor_count() >= (int)server_processors) &&
1626 (os::physical_memory() >= (server_memory - missing_memory))) {
1627 const unsigned int logical_processors =
1628 VM_Version::logical_processors_per_package();
1629 if (logical_processors > 1) {
1630 const unsigned int physical_packages =
1631 os::active_processor_count() / logical_processors;
1632 if (physical_packages >= server_processors) {
1633 result = true;
1634 }
1635 } else {
1636 result = true;
1637 }
1638 }
1639 return result;
1640 }
1641
initialize_initial_active_processor_count()1642 void os::initialize_initial_active_processor_count() {
1643 assert(_initial_active_processor_count == 0, "Initial active processor count already set.");
1644 _initial_active_processor_count = active_processor_count();
1645 log_debug(os)("Initial active processor count set to %d" , _initial_active_processor_count);
1646 }
1647
run()1648 void os::SuspendedThreadTask::run() {
1649 internal_do_task();
1650 _done = true;
1651 }
1652
create_stack_guard_pages(char * addr,size_t bytes)1653 bool os::create_stack_guard_pages(char* addr, size_t bytes) {
1654 return os::pd_create_stack_guard_pages(addr, bytes);
1655 }
1656
reserve_memory(size_t bytes,char * addr,size_t alignment_hint,int file_desc)1657 char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint, int file_desc) {
1658 char* result = NULL;
1659
1660 if (file_desc != -1) {
1661 // Could have called pd_reserve_memory() followed by replace_existing_mapping_with_file_mapping(),
1662 // but AIX may use SHM in which case its more trouble to detach the segment and remap memory to the file.
1663 result = os::map_memory_to_file(addr, bytes, file_desc);
1664 if (result != NULL) {
1665 MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC);
1666 }
1667 } else {
1668 result = pd_reserve_memory(bytes, addr, alignment_hint);
1669 if (result != NULL) {
1670 MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
1671 }
1672 }
1673
1674 return result;
1675 }
1676
reserve_memory(size_t bytes,char * addr,size_t alignment_hint,MEMFLAGS flags)1677 char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint,
1678 MEMFLAGS flags) {
1679 char* result = pd_reserve_memory(bytes, addr, alignment_hint);
1680 if (result != NULL) {
1681 MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
1682 MemTracker::record_virtual_memory_type((address)result, flags);
1683 }
1684
1685 return result;
1686 }
1687
attempt_reserve_memory_at(size_t bytes,char * addr,int file_desc)1688 char* os::attempt_reserve_memory_at(size_t bytes, char* addr, int file_desc) {
1689 char* result = NULL;
1690 if (file_desc != -1) {
1691 result = pd_attempt_reserve_memory_at(bytes, addr, file_desc);
1692 if (result != NULL) {
1693 MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC);
1694 }
1695 } else {
1696 result = pd_attempt_reserve_memory_at(bytes, addr);
1697 if (result != NULL) {
1698 MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
1699 }
1700 }
1701 return result;
1702 }
1703
commit_memory(char * addr,size_t bytes,bool executable)1704 bool os::commit_memory(char* addr, size_t bytes, bool executable) {
1705 bool res = pd_commit_memory(addr, bytes, executable);
1706 if (res) {
1707 MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
1708 }
1709 return res;
1710 }
1711
commit_memory(char * addr,size_t size,size_t alignment_hint,bool executable)1712 bool os::commit_memory(char* addr, size_t size, size_t alignment_hint,
1713 bool executable) {
1714 bool res = os::pd_commit_memory(addr, size, alignment_hint, executable);
1715 if (res) {
1716 MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
1717 }
1718 return res;
1719 }
1720
commit_memory_or_exit(char * addr,size_t bytes,bool executable,const char * mesg)1721 void os::commit_memory_or_exit(char* addr, size_t bytes, bool executable,
1722 const char* mesg) {
1723 pd_commit_memory_or_exit(addr, bytes, executable, mesg);
1724 MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
1725 }
1726
commit_memory_or_exit(char * addr,size_t size,size_t alignment_hint,bool executable,const char * mesg)1727 void os::commit_memory_or_exit(char* addr, size_t size, size_t alignment_hint,
1728 bool executable, const char* mesg) {
1729 os::pd_commit_memory_or_exit(addr, size, alignment_hint, executable, mesg);
1730 MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
1731 }
1732
uncommit_memory(char * addr,size_t bytes)1733 bool os::uncommit_memory(char* addr, size_t bytes) {
1734 bool res;
1735 if (MemTracker::tracking_level() > NMT_minimal) {
1736 Tracker tkr(Tracker::uncommit);
1737 res = pd_uncommit_memory(addr, bytes);
1738 if (res) {
1739 tkr.record((address)addr, bytes);
1740 }
1741 } else {
1742 res = pd_uncommit_memory(addr, bytes);
1743 }
1744 return res;
1745 }
1746
release_memory(char * addr,size_t bytes)1747 bool os::release_memory(char* addr, size_t bytes) {
1748 bool res;
1749 if (MemTracker::tracking_level() > NMT_minimal) {
1750 // Note: Tracker contains a ThreadCritical.
1751 Tracker tkr(Tracker::release);
1752 res = pd_release_memory(addr, bytes);
1753 if (res) {
1754 tkr.record((address)addr, bytes);
1755 }
1756 } else {
1757 res = pd_release_memory(addr, bytes);
1758 }
1759 return res;
1760 }
1761
pretouch_memory(void * start,void * end,size_t page_size)1762 void os::pretouch_memory(void* start, void* end, size_t page_size) {
1763 for (volatile char *p = (char*)start; p < (char*)end; p += page_size) {
1764 *p = 0;
1765 }
1766 }
1767
map_memory(int fd,const char * file_name,size_t file_offset,char * addr,size_t bytes,bool read_only,bool allow_exec,MEMFLAGS flags)1768 char* os::map_memory(int fd, const char* file_name, size_t file_offset,
1769 char *addr, size_t bytes, bool read_only,
1770 bool allow_exec, MEMFLAGS flags) {
1771 char* result = pd_map_memory(fd, file_name, file_offset, addr, bytes, read_only, allow_exec);
1772 if (result != NULL) {
1773 MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC, flags);
1774 }
1775 return result;
1776 }
1777
remap_memory(int fd,const char * file_name,size_t file_offset,char * addr,size_t bytes,bool read_only,bool allow_exec)1778 char* os::remap_memory(int fd, const char* file_name, size_t file_offset,
1779 char *addr, size_t bytes, bool read_only,
1780 bool allow_exec) {
1781 return pd_remap_memory(fd, file_name, file_offset, addr, bytes,
1782 read_only, allow_exec);
1783 }
1784
unmap_memory(char * addr,size_t bytes)1785 bool os::unmap_memory(char *addr, size_t bytes) {
1786 bool result;
1787 if (MemTracker::tracking_level() > NMT_minimal) {
1788 Tracker tkr(Tracker::release);
1789 result = pd_unmap_memory(addr, bytes);
1790 if (result) {
1791 tkr.record((address)addr, bytes);
1792 }
1793 } else {
1794 result = pd_unmap_memory(addr, bytes);
1795 }
1796 return result;
1797 }
1798
free_memory(char * addr,size_t bytes,size_t alignment_hint)1799 void os::free_memory(char *addr, size_t bytes, size_t alignment_hint) {
1800 pd_free_memory(addr, bytes, alignment_hint);
1801 }
1802
realign_memory(char * addr,size_t bytes,size_t alignment_hint)1803 void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
1804 pd_realign_memory(addr, bytes, alignment_hint);
1805 }
1806
reserve_memory_special(size_t size,size_t alignment,char * addr,bool executable)1807 char* os::reserve_memory_special(size_t size, size_t alignment,
1808 char* addr, bool executable) {
1809
1810 assert(is_aligned(addr, alignment), "Unaligned request address");
1811
1812 char* result = pd_reserve_memory_special(size, alignment, addr, executable);
1813 if (result != NULL) {
1814 // The memory is committed
1815 MemTracker::record_virtual_memory_reserve_and_commit((address)result, size, CALLER_PC);
1816 }
1817
1818 return result;
1819 }
1820
release_memory_special(char * addr,size_t bytes)1821 bool os::release_memory_special(char* addr, size_t bytes) {
1822 bool res;
1823 if (MemTracker::tracking_level() > NMT_minimal) {
1824 // Note: Tracker contains a ThreadCritical.
1825 Tracker tkr(Tracker::release);
1826 res = pd_release_memory_special(addr, bytes);
1827 if (res) {
1828 tkr.record((address)addr, bytes);
1829 }
1830 } else {
1831 res = pd_release_memory_special(addr, bytes);
1832 }
1833 return res;
1834 }
1835
1836 #ifndef _WINDOWS
1837 /* try to switch state from state "from" to state "to"
1838 * returns the state set after the method is complete
1839 */
switch_state(os::SuspendResume::State from,os::SuspendResume::State to)1840 os::SuspendResume::State os::SuspendResume::switch_state(os::SuspendResume::State from,
1841 os::SuspendResume::State to)
1842 {
1843 os::SuspendResume::State result = Atomic::cmpxchg(&_state, from, to);
1844 if (result == from) {
1845 // success
1846 return to;
1847 }
1848 return result;
1849 }
1850 #endif
1851
1852 // Convenience wrapper around naked_short_sleep to allow for longer sleep
1853 // times. Only for use by non-JavaThreads.
naked_sleep(jlong millis)1854 void os::naked_sleep(jlong millis) {
1855 assert(!Thread::current()->is_Java_thread(), "not for use by JavaThreads");
1856 const jlong limit = 999;
1857 while (millis > limit) {
1858 naked_short_sleep(limit);
1859 millis -= limit;
1860 }
1861 naked_short_sleep(millis);
1862 }
1863