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