< prev index next >

src/hotspot/os/windows/os_windows.cpp

Print this page
8248238: Adding Windows support to OpenJDK on AArch64

Summary: Adding Windows support for AArch64

Contributed-by: Ludovic Henry <luhenry@microsoft.com>, Monica Beckwith <monica.beckwith@microsoft.com>
Reviewed-by:


  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 // Must be at least Windows Vista or Server 2008 to use InitOnceExecuteOnce
  26 #define _WIN32_WINNT 0x0600
  27 
  28 // no precompiled headers
  29 #include "jvm.h"
  30 #include "classfile/classLoader.hpp"
  31 #include "classfile/systemDictionary.hpp"
  32 #include "classfile/vmSymbols.hpp"
  33 #include "code/icBuffer.hpp"

  34 #include "code/vtableStubs.hpp"
  35 #include "compiler/compileBroker.hpp"
  36 #include "compiler/disassembler.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/filemap.hpp"
  42 #include "oops/oop.inline.hpp"
  43 #include "os_share_windows.hpp"
  44 #include "os_windows.inline.hpp"
  45 #include "prims/jniFastGetField.hpp"
  46 #include "prims/jvm_misc.hpp"
  47 #include "runtime/arguments.hpp"
  48 #include "runtime/atomic.hpp"
  49 #include "runtime/extendedPC.hpp"
  50 #include "runtime/globals.hpp"
  51 #include "runtime/interfaceSupport.inline.hpp"
  52 #include "runtime/java.hpp"
  53 #include "runtime/javaCalls.hpp"


 101 #include <mmsystem.h>
 102 #include <winsock2.h>
 103 
 104 // for timer info max values which include all bits
 105 #define ALL_64_BITS CONST64(-1)
 106 
 107 // For DLL loading/load error detection
 108 // Values of PE COFF
 109 #define IMAGE_FILE_PTR_TO_SIGNATURE 0x3c
 110 #define IMAGE_FILE_SIGNATURE_LENGTH 4
 111 
 112 static HANDLE main_process;
 113 static HANDLE main_thread;
 114 static int    main_thread_id;
 115 
 116 static FILETIME process_creation_time;
 117 static FILETIME process_exit_time;
 118 static FILETIME process_user_time;
 119 static FILETIME process_kernel_time;
 120 
 121 #ifdef _M_AMD64


 122   #define __CPU__ amd64
 123 #else
 124   #define __CPU__ i486
 125 #endif
 126 
 127 #if INCLUDE_AOT


 128 PVOID  topLevelVectoredExceptionHandler = NULL;
 129 LONG WINAPI topLevelVectoredExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo);
 130 #endif
 131 
 132 // save DLL module handle, used by GetModuleFileName
 133 
 134 HINSTANCE vm_lib_handle;
 135 
 136 BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) {
 137   switch (reason) {
 138   case DLL_PROCESS_ATTACH:
 139     vm_lib_handle = hinst;
 140     if (ForceTimeHighResolution) {
 141       timeBeginPeriod(1L);
 142     }
 143     WindowsDbgHelp::pre_initialize();
 144     SymbolEngine::pre_initialize();
 145     break;
 146   case DLL_PROCESS_DETACH:
 147     if (ForceTimeHighResolution) {
 148       timeEndPeriod(1L);
 149     }
 150 #if INCLUDE_AOT
 151     if (topLevelVectoredExceptionHandler != NULL) {
 152       RemoveVectoredExceptionHandler(topLevelVectoredExceptionHandler);
 153       topLevelVectoredExceptionHandler = NULL;
 154     }
 155 #endif
 156     break;
 157   default:
 158     break;
 159   }
 160   return true;
 161 }
 162 
 163 static inline double fileTimeAsDouble(FILETIME* time) {
 164   const double high  = (double) ((unsigned int) ~0);
 165   const double split = 10000000.0;
 166   double result = (time->dwLowDateTime / split) +
 167                    time->dwHighDateTime * (high/split);
 168   return result;
 169 }
 170 


 439   thread->initialize_thread_current();
 440 
 441   OSThread* osthr = thread->osthread();
 442   assert(osthr->get_state() == RUNNABLE, "invalid os thread state");
 443 
 444   if (UseNUMA) {
 445     int lgrp_id = os::numa_get_group_id();
 446     if (lgrp_id != -1) {
 447       thread->set_lgrp_id(lgrp_id);
 448     }
 449   }
 450 
 451   // Diagnostic code to investigate JDK-6573254
 452   int res = 30115;  // non-java thread
 453   if (thread->is_Java_thread()) {
 454     res = 20115;    // java thread
 455   }
 456 
 457   log_info(os, thread)("Thread is alive (tid: " UINTX_FORMAT ").", os::current_thread_id());
 458 






 459   // Install a win32 structured exception handler around every thread created
 460   // by VM, so VM can generate error dump when an exception occurred in non-
 461   // Java thread (e.g. VM thread).
 462   __try {
 463     thread->call_run();
 464   } __except(topLevelExceptionFilter(
 465                                      (_EXCEPTION_POINTERS*)_exception_info())) {
 466     // Nothing to do.
 467   }

 468 
 469   // Note: at this point the thread object may already have deleted itself.
 470   // Do not dereference it from here on out.
 471 
 472   log_info(os, thread)("Thread finished (tid: " UINTX_FORMAT ").", os::current_thread_id());
 473 
 474   // One less thread is executing
 475   // When the VMThread gets here, the main thread may have already exited
 476   // which frees the CodeHeap containing the Atomic::add code
 477   if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) {
 478     Atomic::dec(&os::win32::_os_thread_count);
 479   }
 480 
 481   // Thread must not return from exit_process_or_thread(), but if it does,
 482   // let it proceed to exit normally
 483   return (unsigned)os::win32::exit_process_or_thread(os::win32::EPT_THREAD, res);
 484 }
 485 
 486 static OSThread* create_os_thread(Thread* thread, HANDLE thread_handle,
 487                                   int thread_id) {


1410      signature_offset + IMAGE_FILE_SIGNATURE_LENGTH) < 0)
1411      ||
1412      // Read field that contains code of architecture
1413      // that dll was built for
1414      (sizeof(lib_arch) != (os::read(fd, (void*)&lib_arch, sizeof(lib_arch))))
1415     );
1416 
1417   ::close(fd);
1418   if (failed_to_get_lib_arch) {
1419     // file i/o error - report os::lasterror(...) msg
1420     return NULL;
1421   }
1422 
1423   typedef struct {
1424     uint16_t arch_code;
1425     char* arch_name;
1426   } arch_t;
1427 
1428   static const arch_t arch_array[] = {
1429     {IMAGE_FILE_MACHINE_I386,      (char*)"IA 32"},
1430     {IMAGE_FILE_MACHINE_AMD64,     (char*)"AMD 64"}

1431   };
1432 #if (defined _M_AMD64)


1433   static const uint16_t running_arch = IMAGE_FILE_MACHINE_AMD64;
1434 #elif (defined _M_IX86)
1435   static const uint16_t running_arch = IMAGE_FILE_MACHINE_I386;
1436 #else
1437   #error Method os::dll_load requires that one of following \
1438          is defined :_M_AMD64 or _M_IX86
1439 #endif
1440 
1441 
1442   // Obtain a string for printf operation
1443   // lib_arch_str shall contain string what platform this .dll was built for
1444   // running_arch_str shall string contain what platform Hotspot was built for
1445   char *running_arch_str = NULL, *lib_arch_str = NULL;
1446   for (unsigned int i = 0; i < ARRAY_SIZE(arch_array); i++) {
1447     if (lib_arch == arch_array[i].arch_code) {
1448       lib_arch_str = arch_array[i].arch_name;
1449     }
1450     if (running_arch == arch_array[i].arch_code) {
1451       running_arch_str = arch_array[i].arch_name;
1452     }
1453   }
1454 
1455   assert(running_arch_str,
1456          "Didn't find running architecture code in arch_array");
1457 
1458   // If the architecture is right


1715       // Windows server 2019 GA 10/2018 build number is 17763
1716       if (build_number > 17762) {
1717         st->print("Server 2019");
1718       } else {
1719         st->print("Server 2016");
1720       }
1721     }
1722     break;
1723 
1724   default:
1725     // Unrecognized windows, print out its major and minor versions
1726     st->print("%d.%d", major_version, minor_version);
1727     break;
1728   }
1729 
1730   // Retrieve SYSTEM_INFO from GetNativeSystemInfo call so that we could
1731   // find out whether we are running on 64 bit processor or not
1732   SYSTEM_INFO si;
1733   ZeroMemory(&si, sizeof(SYSTEM_INFO));
1734   GetNativeSystemInfo(&si);
1735   if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {

1736     st->print(" , 64 bit");
1737   }
1738 
1739   st->print(" Build %d", build_number);
1740   st->print(" (%d.%d.%d.%d)", major_version, minor_version, build_number, build_minor);
1741   st->cr();
1742 }
1743 
1744 void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {
1745   // Nothing to do for now.
1746 }
1747 
1748 void os::get_summary_cpu_info(char* buf, size_t buflen) {
1749   HKEY key;
1750   DWORD status = RegOpenKey(HKEY_LOCAL_MACHINE,
1751                "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", &key);
1752   if (status == ERROR_SUCCESS) {
1753     DWORD size = (DWORD)buflen;
1754     status = RegQueryValueEx(key, "ProcessorNameString", NULL, NULL, (byte*)buf, &size);
1755     if (status != ERROR_SUCCESS) {


2123         // while suspended because that would surprise the thread that
2124         // suspended us.
2125         sig_sem->signal();
2126 
2127         thread->java_suspend_self();
2128       }
2129     } while (threadIsSuspended);
2130   }
2131 }
2132 
2133 int os::signal_wait() {
2134   return check_pending_signals();
2135 }
2136 
2137 // Implicit OS exception handling
2138 
2139 LONG Handle_Exception(struct _EXCEPTION_POINTERS* exceptionInfo,
2140                       address handler) {
2141   JavaThread* thread = (JavaThread*) Thread::current_or_null();
2142   // Save pc in thread
2143 #ifdef _M_AMD64







2144   // Do not blow up if no thread info available.
2145   if (thread) {
2146     thread->set_saved_exception_pc((address)(DWORD_PTR)exceptionInfo->ContextRecord->Rip);
2147   }
2148   // Set pc to handler
2149   exceptionInfo->ContextRecord->Rip = (DWORD64)handler;
2150 #else
2151   // Do not blow up if no thread info available.
2152   if (thread) {
2153     thread->set_saved_exception_pc((address)(DWORD_PTR)exceptionInfo->ContextRecord->Eip);
2154   }
2155   // Set pc to handler
2156   exceptionInfo->ContextRecord->Eip = (DWORD)(DWORD_PTR)handler;
2157 #endif
2158 
2159   // Continue the execution
2160   return EXCEPTION_CONTINUE_EXECUTION;
2161 }
2162 
2163 


2221 };
2222 
2223 #undef def_excpt
2224 
2225 const char* os::exception_name(int exception_code, char *buf, size_t size) {
2226   uint code = static_cast<uint>(exception_code);
2227   for (uint i = 0; i < ARRAY_SIZE(exceptlabels); ++i) {
2228     if (exceptlabels[i].number == code) {
2229       jio_snprintf(buf, size, "%s", exceptlabels[i].name);
2230       return buf;
2231     }
2232   }
2233 
2234   return NULL;
2235 }
2236 
2237 //-----------------------------------------------------------------------------
2238 LONG Handle_IDiv_Exception(struct _EXCEPTION_POINTERS* exceptionInfo) {
2239   // handle exception caused by idiv; should only happen for -MinInt/-1
2240   // (division by zero is handled explicitly)
2241 #ifdef  _M_AMD64










2242   PCONTEXT ctx = exceptionInfo->ContextRecord;
2243   address pc = (address)ctx->Rip;
2244   assert(pc[0] >= Assembler::REX && pc[0] <= Assembler::REX_WRXB && pc[1] == 0xF7 || pc[0] == 0xF7, "not an idiv opcode");
2245   assert(pc[0] >= Assembler::REX && pc[0] <= Assembler::REX_WRXB && (pc[2] & ~0x7) == 0xF8 || (pc[1] & ~0x7) == 0xF8, "cannot handle non-register operands");
2246   if (pc[0] == 0xF7) {
2247     // set correct result values and continue after idiv instruction
2248     ctx->Rip = (DWORD64)pc + 2;        // idiv reg, reg  is 2 bytes
2249   } else {
2250     ctx->Rip = (DWORD64)pc + 3;        // REX idiv reg, reg  is 3 bytes
2251   }
2252   // Do not set ctx->Rax as it already contains the correct value (either 32 or 64 bit, depending on the operation)
2253   // this is the case because the exception only happens for -MinValue/-1 and -MinValue is always in rax because of the
2254   // idiv opcode (0xF7).
2255   ctx->Rdx = (DWORD)0;             // remainder
2256   // Continue the execution
2257 #else
2258   PCONTEXT ctx = exceptionInfo->ContextRecord;
2259   address pc = (address)ctx->Eip;
2260   assert(pc[0] == 0xF7, "not an idiv opcode");
2261   assert((pc[1] & ~0x7) == 0xF8, "cannot handle non-register operands");
2262   assert(ctx->Eax == min_jint, "unexpected idiv exception");
2263   // set correct result values and continue after idiv instruction
2264   ctx->Eip = (DWORD)pc + 2;        // idiv reg, reg  is 2 bytes
2265   ctx->Eax = (DWORD)min_jint;      // result
2266   ctx->Edx = (DWORD)0;             // remainder
2267   // Continue the execution
2268 #endif
2269   return EXCEPTION_CONTINUE_EXECUTION;
2270 }
2271 

2272 //-----------------------------------------------------------------------------
2273 LONG WINAPI Handle_FLT_Exception(struct _EXCEPTION_POINTERS* exceptionInfo) {
2274   PCONTEXT ctx = exceptionInfo->ContextRecord;
2275 #ifndef  _WIN64
2276   // handle exception caused by native method modifying control word
2277   DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode;
2278 
2279   switch (exception_code) {
2280   case EXCEPTION_FLT_DENORMAL_OPERAND:
2281   case EXCEPTION_FLT_DIVIDE_BY_ZERO:
2282   case EXCEPTION_FLT_INEXACT_RESULT:
2283   case EXCEPTION_FLT_INVALID_OPERATION:
2284   case EXCEPTION_FLT_OVERFLOW:
2285   case EXCEPTION_FLT_STACK_CHECK:
2286   case EXCEPTION_FLT_UNDERFLOW:
2287     jint fp_control_word = (* (jint*) StubRoutines::addr_fpu_cntrl_wrd_std());
2288     if (fp_control_word != ctx->FloatSave.ControlWord) {
2289       // Restore FPCW and mask out FLT exceptions
2290       ctx->FloatSave.ControlWord = fp_control_word | 0xffffffc0;
2291       // Mask out pending FLT exceptions


2297   if (prev_uef_handler != NULL) {
2298     // We didn't handle this exception so pass it to the previous
2299     // UnhandledExceptionFilter.
2300     return (prev_uef_handler)(exceptionInfo);
2301   }
2302 #else // !_WIN64
2303   // On Windows, the mxcsr control bits are non-volatile across calls
2304   // See also CR 6192333
2305   //
2306   jint MxCsr = INITIAL_MXCSR;
2307   // we can't use StubRoutines::addr_mxcsr_std()
2308   // because in Win64 mxcsr is not saved there
2309   if (MxCsr != ctx->MxCsr) {
2310     ctx->MxCsr = MxCsr;
2311     return EXCEPTION_CONTINUE_EXECUTION;
2312   }
2313 #endif // !_WIN64
2314 
2315   return EXCEPTION_CONTINUE_SEARCH;
2316 }

2317 
2318 static inline void report_error(Thread* t, DWORD exception_code,
2319                                 address addr, void* siginfo, void* context) {
2320   VMError::report_and_die(t, exception_code, addr, siginfo, context);
2321 
2322   // If UseOsErrorReporting, this will return here and save the error file
2323   // somewhere where we can find it in the minidump.
2324 }
2325 
2326 bool os::win32::get_frame_at_stack_banging_point(JavaThread* thread,
2327         struct _EXCEPTION_POINTERS* exceptionInfo, address pc, frame* fr) {
2328   PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
2329   address addr = (address) exceptionRecord->ExceptionInformation[1];
2330   if (Interpreter::contains(pc)) {
2331     *fr = os::fetch_frame_from_context((void*)exceptionInfo->ContextRecord);
2332     if (!fr->is_first_java_frame()) {
2333       // get_frame_at_stack_banging_point() is only called when we
2334       // have well defined stacks so java_sender() calls do not need
2335       // to assert safe_for_sender() first.
2336       *fr = fr->java_sender();
2337     }
2338   } else {
2339     // more complex code with compiled code
2340     assert(!Interpreter::contains(pc), "Interpreted methods should have been handled above");
2341     CodeBlob* cb = CodeCache::find_blob(pc);
2342     if (cb == NULL || !cb->is_nmethod() || cb->is_frame_complete_at(pc)) {
2343       // Not sure where the pc points to, fallback to default
2344       // stack overflow handling
2345       return false;
2346     } else {
2347       *fr = os::fetch_frame_from_context((void*)exceptionInfo->ContextRecord);
2348       // in compiled code, the stack banging is performed just after the return pc
2349       // has been pushed on the stack
2350       *fr = frame(fr->sp() + 1, fr->fp(), (address)*(fr->sp()));
2351       if (!fr->is_java_frame()) {
2352         // See java_sender() comment above.
2353         *fr = fr->java_sender();
2354       }
2355     }
2356   }
2357   assert(fr->is_java_frame(), "Safety check");
2358   return true;
2359 }
2360 
2361 #if INCLUDE_AOT
2362 LONG WINAPI topLevelVectoredExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) {
2363   PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
2364   address addr = (address) exceptionRecord->ExceptionInformation[1];
2365   address pc = (address) exceptionInfo->ContextRecord->Rip;
2366 
2367   // Handle the case where we get an implicit exception in AOT generated
2368   // code.  AOT DLL's loaded are not registered for structured exceptions.
2369   // If the exception occurred in the codeCache or AOT code, pass control
2370   // to our normal exception handler.
2371   CodeBlob* cb = CodeCache::find_blob(pc);
2372   if (cb != NULL) {
2373     return topLevelExceptionFilter(exceptionInfo);
2374   }
2375 
2376   return EXCEPTION_CONTINUE_SEARCH;
2377 }
2378 #endif
2379 
2380 //-----------------------------------------------------------------------------
2381 LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) {
2382   if (InterceptOSException) return EXCEPTION_CONTINUE_SEARCH;
2383   DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode;
2384 #ifdef _M_AMD64


2385   address pc = (address) exceptionInfo->ContextRecord->Rip;
2386 #else
2387   address pc = (address) exceptionInfo->ContextRecord->Eip;
2388 #endif
2389   Thread* t = Thread::current_or_null_safe();
2390 
2391   // Handle SafeFetch32 and SafeFetchN exceptions.
2392   if (StubRoutines::is_safefetch_fault(pc)) {
2393     return Handle_Exception(exceptionInfo, StubRoutines::continuation_for_safefetch_fault(pc));
2394   }
2395 
2396 #ifndef _WIN64
2397   // Execution protection violation - win32 running on AMD64 only
2398   // Handled first to avoid misdiagnosis as a "normal" access violation;
2399   // This is safe to do because we have a new/unique ExceptionInformation
2400   // code for this condition.
2401   if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
2402     PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
2403     int exception_subcode = (int) exceptionRecord->ExceptionInformation[0];
2404     address addr = (address) exceptionRecord->ExceptionInformation[1];


2455           // local last_addr, these solutions are unnecessary complication:
2456           // this handler is a best-effort safety net, not a complete solution.
2457           // It is disabled by default and should only be used as a workaround
2458           // in case we missed any no-execute-unsafe VM code.
2459 
2460           last_addr = addr;
2461 
2462           return EXCEPTION_CONTINUE_EXECUTION;
2463         }
2464       }
2465 
2466       // Last unguard failed or not unguarding
2467       tty->print_raw_cr("Execution protection violation");
2468       report_error(t, exception_code, addr, exceptionInfo->ExceptionRecord,
2469                    exceptionInfo->ContextRecord);
2470       return EXCEPTION_CONTINUE_SEARCH;
2471     }
2472   }
2473 #endif // _WIN64
2474 

2475   if ((exception_code == EXCEPTION_ACCESS_VIOLATION) &&
2476       VM_Version::is_cpuinfo_segv_addr(pc)) {
2477     // Verify that OS save/restore AVX registers.
2478     return Handle_Exception(exceptionInfo, VM_Version::cpuinfo_cont_addr());
2479   }

2480 
2481   if (t != NULL && t->is_Java_thread()) {
2482     JavaThread* thread = (JavaThread*) t;
2483     bool in_java = thread->thread_state() == _thread_in_Java;
2484 
2485     // Handle potential stack overflows up front.
2486     if (exception_code == EXCEPTION_STACK_OVERFLOW) {
2487       if (thread->stack_guards_enabled()) {
2488         if (in_java) {
2489           frame fr;
2490           PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
2491           address addr = (address) exceptionRecord->ExceptionInformation[1];
2492           if (os::win32::get_frame_at_stack_banging_point(thread, exceptionInfo, pc, &fr)) {
2493             assert(fr.is_java_frame(), "Must be a Java frame");
2494             SharedRuntime::look_for_reserved_stack_annotated_method(thread, fr);
2495           }
2496         }
2497         // Yellow zone violation.  The o/s has unprotected the first yellow
2498         // zone page for us.  Note:  must call disable_stack_yellow_zone to
2499         // update the enabled status, even if the zone contains only one page.


2544             addr = (address)((uintptr_t)addr &
2545                              (~((uintptr_t)os::vm_page_size() - (uintptr_t)1)));
2546             os::commit_memory((char *)addr, thread->stack_base() - addr,
2547                               !ExecMem);
2548             return EXCEPTION_CONTINUE_EXECUTION;
2549           } else
2550 #endif
2551           {
2552             // Null pointer exception.
2553             if (MacroAssembler::uses_implicit_null_check((void*)addr)) {
2554               address stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
2555               if (stub != NULL) return Handle_Exception(exceptionInfo, stub);
2556             }
2557             report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
2558                          exceptionInfo->ContextRecord);
2559             return EXCEPTION_CONTINUE_SEARCH;
2560           }
2561         }
2562       }
2563 























2564 #ifdef _WIN64
2565       // Special care for fast JNI field accessors.
2566       // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks
2567       // in and the heap gets shrunk before the field access.
2568       if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
2569         address addr = JNI_FastGetField::find_slowcase_pc(pc);
2570         if (addr != (address)-1) {
2571           return Handle_Exception(exceptionInfo, addr);
2572         }
2573       }
2574 #endif
2575 
2576       // Stack overflow or null pointer exception in native code.
2577       report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
2578                    exceptionInfo->ContextRecord);
2579       return EXCEPTION_CONTINUE_SEARCH;
2580     } // /EXCEPTION_ACCESS_VIOLATION
2581     // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2582 
2583     if (exception_code == EXCEPTION_IN_PAGE_ERROR) {


2585       JavaThread* thread = (JavaThread*)t;
2586       if (in_java) {
2587         CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
2588         nm = (cb != NULL) ? cb->as_compiled_method_or_null() : NULL;
2589       }
2590 
2591       bool is_unsafe_arraycopy = (thread->thread_state() == _thread_in_native || in_java) && UnsafeCopyMemory::contains_pc(pc);
2592       if (((thread->thread_state() == _thread_in_vm ||
2593            thread->thread_state() == _thread_in_native ||
2594            is_unsafe_arraycopy) &&
2595           thread->doing_unsafe_access()) ||
2596           (nm != NULL && nm->has_unsafe_access())) {
2597         address next_pc =  Assembler::locate_next_instruction(pc);
2598         if (is_unsafe_arraycopy) {
2599           next_pc = UnsafeCopyMemory::page_error_continue_pc(pc);
2600         }
2601         return Handle_Exception(exceptionInfo, SharedRuntime::handle_unsafe_access(thread, next_pc));
2602       }
2603     }
2604 













2605     if (in_java) {
2606       switch (exception_code) {
2607       case EXCEPTION_INT_DIVIDE_BY_ZERO:
2608         return Handle_Exception(exceptionInfo, SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_DIVIDE_BY_ZERO));
2609 
2610       case EXCEPTION_INT_OVERFLOW:
2611         return Handle_IDiv_Exception(exceptionInfo);
2612 
2613       } // switch
2614     }


2615     if (((thread->thread_state() == _thread_in_Java) ||
2616          (thread->thread_state() == _thread_in_native)) &&
2617          exception_code != EXCEPTION_UNCAUGHT_CXX_EXCEPTION) {
2618       LONG result=Handle_FLT_Exception(exceptionInfo);
2619       if (result==EXCEPTION_CONTINUE_EXECUTION) return result;
2620     }

2621   }
2622 
2623   if (exception_code != EXCEPTION_BREAKPOINT) {
2624     report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
2625                  exceptionInfo->ContextRecord);
2626   }
2627   return EXCEPTION_CONTINUE_SEARCH;
2628 }
2629 
2630 #ifndef _WIN64
2631 // Special care for fast JNI accessors.
2632 // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in and
2633 // the heap gets shrunk before the field access.
2634 // Need to install our own structured exception handler since native code may
2635 // install its own.
2636 LONG WINAPI fastJNIAccessorExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) {
2637   DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode;
2638   if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
2639     address pc = (address) exceptionInfo->ContextRecord->Eip;
2640     address addr = JNI_FastGetField::find_slowcase_pc(pc);


3608   }
3609 }
3610 
3611 int os::numa_get_group_id_for_address(const void* address) {
3612   return 0;
3613 }
3614 
3615 bool os::get_page_info(char *start, page_info* info) {
3616   return false;
3617 }
3618 
3619 char *os::scan_pages(char *start, char* end, page_info* page_expected,
3620                      page_info* page_found) {
3621   return end;
3622 }
3623 
3624 char* os::non_memory_address_word() {
3625   // Must never look like an address returned by reserve_memory,
3626   // even in its subfields (as defined by the CPU immediate fields,
3627   // if the CPU splits constants across multiple instructions).




3628   return (char*)-1;

3629 }
3630 
3631 #define MAX_ERROR_COUNT 100
3632 #define SYS_THREAD_ERROR 0xffffffffUL
3633 
3634 void os::pd_start_thread(Thread* thread) {
3635   DWORD ret = ResumeThread(thread->osthread()->thread_handle());
3636   // Returns previous suspend state:
3637   // 0:  Thread was not suspended
3638   // 1:  Thread is running now
3639   // >1: Thread is still suspended.
3640   assert(ret != SYS_THREAD_ERROR, "StartThread failed"); // should propagate back
3641 }
3642 
3643 
3644 // Short sleep, direct OS call.
3645 //
3646 // ms = 0, means allow others (if any) to run.
3647 //
3648 void os::naked_short_sleep(jlong ms) {


3804   case VER_PLATFORM_WIN32_NT:
3805     {
3806       int os_vers = oi.dwMajorVersion * 1000 + oi.dwMinorVersion;
3807       if (oi.wProductType == VER_NT_DOMAIN_CONTROLLER ||
3808           oi.wProductType == VER_NT_SERVER) {
3809         _is_windows_server = true;
3810       }
3811     }
3812     break;
3813   default: fatal("Unknown platform");
3814   }
3815 
3816   _default_stack_size = os::current_stack_size();
3817   assert(_default_stack_size > (size_t) _vm_page_size, "invalid stack size");
3818   assert((_default_stack_size & (_vm_page_size - 1)) == 0,
3819          "stack size not a multiple of page size");
3820 
3821   initialize_performance_counter();
3822 }
3823 




























3824 
3825 HINSTANCE os::win32::load_Windows_dll(const char* name, char *ebuf,
3826                                       int ebuflen) {
3827   char path[MAX_PATH];
3828   DWORD size;
3829   DWORD pathLen = (DWORD)sizeof(path);
3830   HINSTANCE result = NULL;
3831 
3832   // only allow library name without path component
3833   assert(strchr(name, '\\') == NULL, "path not allowed");
3834   assert(strchr(name, ':') == NULL, "path not allowed");
3835   if (strchr(name, '\\') != NULL || strchr(name, ':') != NULL) {
3836     jio_snprintf(ebuf, ebuflen,
3837                  "Invalid parameter while calling os::win32::load_windows_dll(): cannot take path: %s", name);
3838     return NULL;
3839   }
3840 
3841   // search system directory
3842   if ((size = GetSystemDirectory(path, pathLen)) > 0) {
3843     if (size >= pathLen) {


4132 }
4133 
4134 // To install functions for atexit processing
4135 extern "C" {
4136   static void perfMemory_exit_helper() {
4137     perfMemory_exit();
4138   }
4139 }
4140 
4141 static jint initSock();
4142 
4143 // this is called _after_ the global arguments have been parsed
4144 jint os::init_2(void) {
4145 
4146   // This could be set any time but all platforms
4147   // have to set it the same so we have to mirror Solaris.
4148   DEBUG_ONLY(os::set_mutex_init_done();)
4149 
4150   // Setup Windows Exceptions
4151 
4152 #if INCLUDE_AOT


4153   // If AOT is enabled we need to install a vectored exception handler
4154   // in order to forward implicit exceptions from code in AOT
4155   // generated DLLs.  This is necessary since these DLLs are not
4156   // registered for structured exceptions like codecache methods are.
4157   if (AOTLibrary != NULL && (UseAOT || FLAG_IS_DEFAULT(UseAOT))) {
4158     topLevelVectoredExceptionHandler = AddVectoredExceptionHandler( 1, topLevelVectoredExceptionFilter);
4159   }
4160 #endif
4161 
4162   // for debugging float code generation bugs
4163   if (ForceFloatExceptions) {
4164 #ifndef  _WIN64
4165     static long fp_control_word = 0;
4166     __asm { fstcw fp_control_word }
4167     // see Intel PPro Manual, Vol. 2, p 7-16
4168     const long precision = 0x20;
4169     const long underflow = 0x10;
4170     const long overflow  = 0x08;
4171     const long zero_div  = 0x04;
4172     const long denorm    = 0x02;


5591 
5592 int os::connect(int fd, struct sockaddr* him, socklen_t len) {
5593   return ::connect(fd, him, len);
5594 }
5595 
5596 int os::recv(int fd, char* buf, size_t nBytes, uint flags) {
5597   return ::recv(fd, buf, (int)nBytes, flags);
5598 }
5599 
5600 int os::send(int fd, char* buf, size_t nBytes, uint flags) {
5601   return ::send(fd, buf, (int)nBytes, flags);
5602 }
5603 
5604 int os::raw_send(int fd, char* buf, size_t nBytes, uint flags) {
5605   return ::send(fd, buf, (int)nBytes, flags);
5606 }
5607 
5608 // WINDOWS CONTEXT Flags for THREAD_SAMPLING
5609 #if defined(IA32)
5610   #define sampling_context_flags (CONTEXT_FULL | CONTEXT_FLOATING_POINT | CONTEXT_EXTENDED_REGISTERS)
5611 #elif defined (AMD64)
5612   #define sampling_context_flags (CONTEXT_FULL | CONTEXT_FLOATING_POINT)
5613 #endif
5614 
5615 // returns true if thread could be suspended,
5616 // false otherwise
5617 static bool do_suspend(HANDLE* h) {
5618   if (h != NULL) {
5619     if (SuspendThread(*h) != ~0) {
5620       return true;
5621     }
5622   }
5623   return false;
5624 }
5625 
5626 // resume the thread
5627 // calling resume on an active thread is a no-op
5628 static void do_resume(HANDLE* h) {
5629   if (h != NULL) {
5630     ResumeThread(*h);
5631   }




  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 // Must be at least Windows Vista or Server 2008 to use InitOnceExecuteOnce
  26 #define _WIN32_WINNT 0x0600
  27 
  28 // no precompiled headers
  29 #include "jvm.h"
  30 #include "classfile/classLoader.hpp"
  31 #include "classfile/systemDictionary.hpp"
  32 #include "classfile/vmSymbols.hpp"
  33 #include "code/icBuffer.hpp"
  34 #include "code/nativeInst.hpp"
  35 #include "code/vtableStubs.hpp"
  36 #include "compiler/compileBroker.hpp"
  37 #include "compiler/disassembler.hpp"
  38 #include "interpreter/interpreter.hpp"
  39 #include "logging/log.hpp"
  40 #include "logging/logStream.hpp"
  41 #include "memory/allocation.inline.hpp"
  42 #include "memory/filemap.hpp"
  43 #include "oops/oop.inline.hpp"
  44 #include "os_share_windows.hpp"
  45 #include "os_windows.inline.hpp"
  46 #include "prims/jniFastGetField.hpp"
  47 #include "prims/jvm_misc.hpp"
  48 #include "runtime/arguments.hpp"
  49 #include "runtime/atomic.hpp"
  50 #include "runtime/extendedPC.hpp"
  51 #include "runtime/globals.hpp"
  52 #include "runtime/interfaceSupport.inline.hpp"
  53 #include "runtime/java.hpp"
  54 #include "runtime/javaCalls.hpp"


 102 #include <mmsystem.h>
 103 #include <winsock2.h>
 104 
 105 // for timer info max values which include all bits
 106 #define ALL_64_BITS CONST64(-1)
 107 
 108 // For DLL loading/load error detection
 109 // Values of PE COFF
 110 #define IMAGE_FILE_PTR_TO_SIGNATURE 0x3c
 111 #define IMAGE_FILE_SIGNATURE_LENGTH 4
 112 
 113 static HANDLE main_process;
 114 static HANDLE main_thread;
 115 static int    main_thread_id;
 116 
 117 static FILETIME process_creation_time;
 118 static FILETIME process_exit_time;
 119 static FILETIME process_user_time;
 120 static FILETIME process_kernel_time;
 121 
 122 #if defined(_M_ARM64)
 123   #define __CPU__ aarch64
 124 #elif defined(_M_AMD64)
 125   #define __CPU__ amd64
 126 #else
 127   #define __CPU__ i486
 128 #endif
 129 
 130 #if defined(USE_VECTORED_EXCEPTION_HANDLING)
 131 PVOID  topLevelVectoredExceptionHandler = NULL;
 132 #elif INCLUDE_AOT
 133 PVOID  topLevelVectoredExceptionHandler = NULL;
 134 LONG WINAPI topLevelVectoredExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo);
 135 #endif
 136 
 137 // save DLL module handle, used by GetModuleFileName
 138 
 139 HINSTANCE vm_lib_handle;
 140 
 141 BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) {
 142   switch (reason) {
 143   case DLL_PROCESS_ATTACH:
 144     vm_lib_handle = hinst;
 145     if (ForceTimeHighResolution) {
 146       timeBeginPeriod(1L);
 147     }
 148     WindowsDbgHelp::pre_initialize();
 149     SymbolEngine::pre_initialize();
 150     break;
 151   case DLL_PROCESS_DETACH:
 152     if (ForceTimeHighResolution) {
 153       timeEndPeriod(1L);
 154     }
 155 #if defined(USE_VECTORED_EXCEPTION_HANDLING) || INCLUDE_AOT
 156     if (topLevelVectoredExceptionHandler != NULL) {
 157       RemoveVectoredExceptionHandler(topLevelVectoredExceptionHandler);
 158       topLevelVectoredExceptionHandler = NULL;
 159     }
 160 #endif
 161     break;
 162   default:
 163     break;
 164   }
 165   return true;
 166 }
 167 
 168 static inline double fileTimeAsDouble(FILETIME* time) {
 169   const double high  = (double) ((unsigned int) ~0);
 170   const double split = 10000000.0;
 171   double result = (time->dwLowDateTime / split) +
 172                    time->dwHighDateTime * (high/split);
 173   return result;
 174 }
 175 


 444   thread->initialize_thread_current();
 445 
 446   OSThread* osthr = thread->osthread();
 447   assert(osthr->get_state() == RUNNABLE, "invalid os thread state");
 448 
 449   if (UseNUMA) {
 450     int lgrp_id = os::numa_get_group_id();
 451     if (lgrp_id != -1) {
 452       thread->set_lgrp_id(lgrp_id);
 453     }
 454   }
 455 
 456   // Diagnostic code to investigate JDK-6573254
 457   int res = 30115;  // non-java thread
 458   if (thread->is_Java_thread()) {
 459     res = 20115;    // java thread
 460   }
 461 
 462   log_info(os, thread)("Thread is alive (tid: " UINTX_FORMAT ").", os::current_thread_id());
 463 
 464 #ifdef USE_VECTORED_EXCEPTION_HANDLING
 465   // Any exception is caught by the Vectored Exception Handler, so VM can
 466   // generate error dump when an exception occurred in non-Java thread
 467   // (e.g. VM thread).
 468   thread->call_run();
 469 #else
 470   // Install a win32 structured exception handler around every thread created
 471   // by VM, so VM can generate error dump when an exception occurred in non-
 472   // Java thread (e.g. VM thread).
 473   __try {
 474     thread->call_run();
 475   } __except(topLevelExceptionFilter(
 476                                      (_EXCEPTION_POINTERS*)_exception_info())) {
 477     // Nothing to do.
 478   }
 479 #endif
 480 
 481   // Note: at this point the thread object may already have deleted itself.
 482   // Do not dereference it from here on out.
 483 
 484   log_info(os, thread)("Thread finished (tid: " UINTX_FORMAT ").", os::current_thread_id());
 485 
 486   // One less thread is executing
 487   // When the VMThread gets here, the main thread may have already exited
 488   // which frees the CodeHeap containing the Atomic::add code
 489   if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) {
 490     Atomic::dec(&os::win32::_os_thread_count);
 491   }
 492 
 493   // Thread must not return from exit_process_or_thread(), but if it does,
 494   // let it proceed to exit normally
 495   return (unsigned)os::win32::exit_process_or_thread(os::win32::EPT_THREAD, res);
 496 }
 497 
 498 static OSThread* create_os_thread(Thread* thread, HANDLE thread_handle,
 499                                   int thread_id) {


1422      signature_offset + IMAGE_FILE_SIGNATURE_LENGTH) < 0)
1423      ||
1424      // Read field that contains code of architecture
1425      // that dll was built for
1426      (sizeof(lib_arch) != (os::read(fd, (void*)&lib_arch, sizeof(lib_arch))))
1427     );
1428 
1429   ::close(fd);
1430   if (failed_to_get_lib_arch) {
1431     // file i/o error - report os::lasterror(...) msg
1432     return NULL;
1433   }
1434 
1435   typedef struct {
1436     uint16_t arch_code;
1437     char* arch_name;
1438   } arch_t;
1439 
1440   static const arch_t arch_array[] = {
1441     {IMAGE_FILE_MACHINE_I386,      (char*)"IA 32"},
1442     {IMAGE_FILE_MACHINE_AMD64,     (char*)"AMD 64"},
1443     {IMAGE_FILE_MACHINE_ARM64,     (char*)"ARM 64"}
1444   };
1445 #if (defined _M_ARM64)
1446   static const uint16_t running_arch = IMAGE_FILE_MACHINE_ARM64;
1447 #elif (defined _M_AMD64)
1448   static const uint16_t running_arch = IMAGE_FILE_MACHINE_AMD64;
1449 #elif (defined _M_IX86)
1450   static const uint16_t running_arch = IMAGE_FILE_MACHINE_I386;
1451 #else
1452   #error Method os::dll_load requires that one of following \
1453          is defined :_M_AMD64 or _M_IX86 or _M_ARM64
1454 #endif
1455 
1456 
1457   // Obtain a string for printf operation
1458   // lib_arch_str shall contain string what platform this .dll was built for
1459   // running_arch_str shall string contain what platform Hotspot was built for
1460   char *running_arch_str = NULL, *lib_arch_str = NULL;
1461   for (unsigned int i = 0; i < ARRAY_SIZE(arch_array); i++) {
1462     if (lib_arch == arch_array[i].arch_code) {
1463       lib_arch_str = arch_array[i].arch_name;
1464     }
1465     if (running_arch == arch_array[i].arch_code) {
1466       running_arch_str = arch_array[i].arch_name;
1467     }
1468   }
1469 
1470   assert(running_arch_str,
1471          "Didn't find running architecture code in arch_array");
1472 
1473   // If the architecture is right


1730       // Windows server 2019 GA 10/2018 build number is 17763
1731       if (build_number > 17762) {
1732         st->print("Server 2019");
1733       } else {
1734         st->print("Server 2016");
1735       }
1736     }
1737     break;
1738 
1739   default:
1740     // Unrecognized windows, print out its major and minor versions
1741     st->print("%d.%d", major_version, minor_version);
1742     break;
1743   }
1744 
1745   // Retrieve SYSTEM_INFO from GetNativeSystemInfo call so that we could
1746   // find out whether we are running on 64 bit processor or not
1747   SYSTEM_INFO si;
1748   ZeroMemory(&si, sizeof(SYSTEM_INFO));
1749   GetNativeSystemInfo(&si);
1750   if ((si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) ||
1751       (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM64)) {
1752     st->print(" , 64 bit");
1753   }
1754 
1755   st->print(" Build %d", build_number);
1756   st->print(" (%d.%d.%d.%d)", major_version, minor_version, build_number, build_minor);
1757   st->cr();
1758 }
1759 
1760 void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {
1761   // Nothing to do for now.
1762 }
1763 
1764 void os::get_summary_cpu_info(char* buf, size_t buflen) {
1765   HKEY key;
1766   DWORD status = RegOpenKey(HKEY_LOCAL_MACHINE,
1767                "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", &key);
1768   if (status == ERROR_SUCCESS) {
1769     DWORD size = (DWORD)buflen;
1770     status = RegQueryValueEx(key, "ProcessorNameString", NULL, NULL, (byte*)buf, &size);
1771     if (status != ERROR_SUCCESS) {


2139         // while suspended because that would surprise the thread that
2140         // suspended us.
2141         sig_sem->signal();
2142 
2143         thread->java_suspend_self();
2144       }
2145     } while (threadIsSuspended);
2146   }
2147 }
2148 
2149 int os::signal_wait() {
2150   return check_pending_signals();
2151 }
2152 
2153 // Implicit OS exception handling
2154 
2155 LONG Handle_Exception(struct _EXCEPTION_POINTERS* exceptionInfo,
2156                       address handler) {
2157   JavaThread* thread = (JavaThread*) Thread::current_or_null();
2158   // Save pc in thread
2159 #if defined(_M_ARM64)
2160   // Do not blow up if no thread info available.
2161   if (thread) {
2162     thread->set_saved_exception_pc((address)(DWORD_PTR)exceptionInfo->ContextRecord->Pc);
2163   }
2164   // Set pc to handler
2165   exceptionInfo->ContextRecord->Pc = (DWORD64)handler;
2166 #elif defined(_M_AMD64)
2167   // Do not blow up if no thread info available.
2168   if (thread) {
2169     thread->set_saved_exception_pc((address)(DWORD_PTR)exceptionInfo->ContextRecord->Rip);
2170   }
2171   // Set pc to handler
2172   exceptionInfo->ContextRecord->Rip = (DWORD64)handler;
2173 #else
2174   // Do not blow up if no thread info available.
2175   if (thread) {
2176     thread->set_saved_exception_pc((address)(DWORD_PTR)exceptionInfo->ContextRecord->Eip);
2177   }
2178   // Set pc to handler
2179   exceptionInfo->ContextRecord->Eip = (DWORD)(DWORD_PTR)handler;
2180 #endif
2181 
2182   // Continue the execution
2183   return EXCEPTION_CONTINUE_EXECUTION;
2184 }
2185 
2186 


2244 };
2245 
2246 #undef def_excpt
2247 
2248 const char* os::exception_name(int exception_code, char *buf, size_t size) {
2249   uint code = static_cast<uint>(exception_code);
2250   for (uint i = 0; i < ARRAY_SIZE(exceptlabels); ++i) {
2251     if (exceptlabels[i].number == code) {
2252       jio_snprintf(buf, size, "%s", exceptlabels[i].name);
2253       return buf;
2254     }
2255   }
2256 
2257   return NULL;
2258 }
2259 
2260 //-----------------------------------------------------------------------------
2261 LONG Handle_IDiv_Exception(struct _EXCEPTION_POINTERS* exceptionInfo) {
2262   // handle exception caused by idiv; should only happen for -MinInt/-1
2263   // (division by zero is handled explicitly)
2264 #if defined(_M_ARM64)
2265   PCONTEXT ctx = exceptionInfo->ContextRecord;
2266   address pc = (address)ctx->Sp;
2267   assert(pc[0] == 0x83, "not an sdiv opcode"); //Fixme did i get the right opcode?
2268   assert(ctx->X4 == min_jint, "unexpected idiv exception");
2269   // set correct result values and continue after idiv instruction
2270   ctx->Pc = (uint64_t)pc + 4;        // idiv reg, reg, reg  is 4 bytes
2271   ctx->X4 = (uint64_t)min_jint;      // result
2272   ctx->X5 = (uint64_t)0;             // remainder
2273   // Continue the execution
2274 #elif defined(_M_AMD64)
2275   PCONTEXT ctx = exceptionInfo->ContextRecord;
2276   address pc = (address)ctx->Rip;
2277   assert(pc[0] >= Assembler::REX && pc[0] <= Assembler::REX_WRXB && pc[1] == 0xF7 || pc[0] == 0xF7, "not an idiv opcode");
2278   assert(pc[0] >= Assembler::REX && pc[0] <= Assembler::REX_WRXB && (pc[2] & ~0x7) == 0xF8 || (pc[1] & ~0x7) == 0xF8, "cannot handle non-register operands");
2279   if (pc[0] == 0xF7) {
2280     // set correct result values and continue after idiv instruction
2281     ctx->Rip = (DWORD64)pc + 2;        // idiv reg, reg  is 2 bytes
2282   } else {
2283     ctx->Rip = (DWORD64)pc + 3;        // REX idiv reg, reg  is 3 bytes
2284   }
2285   // Do not set ctx->Rax as it already contains the correct value (either 32 or 64 bit, depending on the operation)
2286   // this is the case because the exception only happens for -MinValue/-1 and -MinValue is always in rax because of the
2287   // idiv opcode (0xF7).
2288   ctx->Rdx = (DWORD)0;             // remainder
2289   // Continue the execution
2290 #else
2291   PCONTEXT ctx = exceptionInfo->ContextRecord;
2292   address pc = (address)ctx->Eip;
2293   assert(pc[0] == 0xF7, "not an idiv opcode");
2294   assert((pc[1] & ~0x7) == 0xF8, "cannot handle non-register operands");
2295   assert(ctx->Eax == min_jint, "unexpected idiv exception");
2296   // set correct result values and continue after idiv instruction
2297   ctx->Eip = (DWORD)pc + 2;        // idiv reg, reg  is 2 bytes
2298   ctx->Eax = (DWORD)min_jint;      // result
2299   ctx->Edx = (DWORD)0;             // remainder
2300   // Continue the execution
2301 #endif
2302   return EXCEPTION_CONTINUE_EXECUTION;
2303 }
2304 
2305 #if defined(_M_AMD64) || defined(_M_IX86)
2306 //-----------------------------------------------------------------------------
2307 LONG WINAPI Handle_FLT_Exception(struct _EXCEPTION_POINTERS* exceptionInfo) {
2308   PCONTEXT ctx = exceptionInfo->ContextRecord;
2309 #ifndef  _WIN64
2310   // handle exception caused by native method modifying control word
2311   DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode;
2312 
2313   switch (exception_code) {
2314   case EXCEPTION_FLT_DENORMAL_OPERAND:
2315   case EXCEPTION_FLT_DIVIDE_BY_ZERO:
2316   case EXCEPTION_FLT_INEXACT_RESULT:
2317   case EXCEPTION_FLT_INVALID_OPERATION:
2318   case EXCEPTION_FLT_OVERFLOW:
2319   case EXCEPTION_FLT_STACK_CHECK:
2320   case EXCEPTION_FLT_UNDERFLOW:
2321     jint fp_control_word = (* (jint*) StubRoutines::addr_fpu_cntrl_wrd_std());
2322     if (fp_control_word != ctx->FloatSave.ControlWord) {
2323       // Restore FPCW and mask out FLT exceptions
2324       ctx->FloatSave.ControlWord = fp_control_word | 0xffffffc0;
2325       // Mask out pending FLT exceptions


2331   if (prev_uef_handler != NULL) {
2332     // We didn't handle this exception so pass it to the previous
2333     // UnhandledExceptionFilter.
2334     return (prev_uef_handler)(exceptionInfo);
2335   }
2336 #else // !_WIN64
2337   // On Windows, the mxcsr control bits are non-volatile across calls
2338   // See also CR 6192333
2339   //
2340   jint MxCsr = INITIAL_MXCSR;
2341   // we can't use StubRoutines::addr_mxcsr_std()
2342   // because in Win64 mxcsr is not saved there
2343   if (MxCsr != ctx->MxCsr) {
2344     ctx->MxCsr = MxCsr;
2345     return EXCEPTION_CONTINUE_EXECUTION;
2346   }
2347 #endif // !_WIN64
2348 
2349   return EXCEPTION_CONTINUE_SEARCH;
2350 }
2351 #endif
2352 
2353 static inline void report_error(Thread* t, DWORD exception_code,
2354                                 address addr, void* siginfo, void* context) {
2355   VMError::report_and_die(t, exception_code, addr, siginfo, context);
2356 
2357   // If UseOsErrorReporting, this will return here and save the error file
2358   // somewhere where we can find it in the minidump.
2359 }
2360 
2361 #if !defined(USE_VECTORED_EXCEPTION_HANDLING) && INCLUDE_AOT



































2362 LONG WINAPI topLevelVectoredExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) {
2363   PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
2364   address addr = (address) exceptionRecord->ExceptionInformation[1];
2365   address pc = (address) exceptionInfo->ContextRecord->Rip;
2366 
2367   // Handle the case where we get an implicit exception in AOT generated
2368   // code.  AOT DLL's loaded are not registered for structured exceptions.
2369   // If the exception occurred in the codeCache or AOT code, pass control
2370   // to our normal exception handler.
2371   CodeBlob* cb = CodeCache::find_blob(pc);
2372   if (cb != NULL) {
2373     return topLevelExceptionFilter(exceptionInfo);
2374   }
2375 
2376   return EXCEPTION_CONTINUE_SEARCH;
2377 }
2378 #endif
2379 
2380 //-----------------------------------------------------------------------------
2381 LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) {
2382   if (InterceptOSException) return EXCEPTION_CONTINUE_SEARCH;
2383   DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode;
2384 #if defined(_M_ARM64)
2385   address pc = (address)exceptionInfo->ContextRecord->Pc;
2386 #elif defined(_M_AMD64)
2387   address pc = (address) exceptionInfo->ContextRecord->Rip;
2388 #else
2389   address pc = (address) exceptionInfo->ContextRecord->Eip;
2390 #endif
2391   Thread* t = Thread::current_or_null_safe();
2392 
2393   // Handle SafeFetch32 and SafeFetchN exceptions.
2394   if (StubRoutines::is_safefetch_fault(pc)) {
2395     return Handle_Exception(exceptionInfo, StubRoutines::continuation_for_safefetch_fault(pc));
2396   }
2397 
2398 #ifndef _WIN64
2399   // Execution protection violation - win32 running on AMD64 only
2400   // Handled first to avoid misdiagnosis as a "normal" access violation;
2401   // This is safe to do because we have a new/unique ExceptionInformation
2402   // code for this condition.
2403   if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
2404     PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
2405     int exception_subcode = (int) exceptionRecord->ExceptionInformation[0];
2406     address addr = (address) exceptionRecord->ExceptionInformation[1];


2457           // local last_addr, these solutions are unnecessary complication:
2458           // this handler is a best-effort safety net, not a complete solution.
2459           // It is disabled by default and should only be used as a workaround
2460           // in case we missed any no-execute-unsafe VM code.
2461 
2462           last_addr = addr;
2463 
2464           return EXCEPTION_CONTINUE_EXECUTION;
2465         }
2466       }
2467 
2468       // Last unguard failed or not unguarding
2469       tty->print_raw_cr("Execution protection violation");
2470       report_error(t, exception_code, addr, exceptionInfo->ExceptionRecord,
2471                    exceptionInfo->ContextRecord);
2472       return EXCEPTION_CONTINUE_SEARCH;
2473     }
2474   }
2475 #endif // _WIN64
2476 
2477 #if defined(_M_AMD64) || defined(_M_IX86)
2478   if ((exception_code == EXCEPTION_ACCESS_VIOLATION) &&
2479       VM_Version::is_cpuinfo_segv_addr(pc)) {
2480     // Verify that OS save/restore AVX registers.
2481     return Handle_Exception(exceptionInfo, VM_Version::cpuinfo_cont_addr());
2482   }
2483 #endif
2484 
2485   if (t != NULL && t->is_Java_thread()) {
2486     JavaThread* thread = (JavaThread*) t;
2487     bool in_java = thread->thread_state() == _thread_in_Java;
2488 
2489     // Handle potential stack overflows up front.
2490     if (exception_code == EXCEPTION_STACK_OVERFLOW) {
2491       if (thread->stack_guards_enabled()) {
2492         if (in_java) {
2493           frame fr;
2494           PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
2495           address addr = (address) exceptionRecord->ExceptionInformation[1];
2496           if (os::win32::get_frame_at_stack_banging_point(thread, exceptionInfo, pc, &fr)) {
2497             assert(fr.is_java_frame(), "Must be a Java frame");
2498             SharedRuntime::look_for_reserved_stack_annotated_method(thread, fr);
2499           }
2500         }
2501         // Yellow zone violation.  The o/s has unprotected the first yellow
2502         // zone page for us.  Note:  must call disable_stack_yellow_zone to
2503         // update the enabled status, even if the zone contains only one page.


2548             addr = (address)((uintptr_t)addr &
2549                              (~((uintptr_t)os::vm_page_size() - (uintptr_t)1)));
2550             os::commit_memory((char *)addr, thread->stack_base() - addr,
2551                               !ExecMem);
2552             return EXCEPTION_CONTINUE_EXECUTION;
2553           } else
2554 #endif
2555           {
2556             // Null pointer exception.
2557             if (MacroAssembler::uses_implicit_null_check((void*)addr)) {
2558               address stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
2559               if (stub != NULL) return Handle_Exception(exceptionInfo, stub);
2560             }
2561             report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
2562                          exceptionInfo->ContextRecord);
2563             return EXCEPTION_CONTINUE_SEARCH;
2564           }
2565         }
2566       }
2567 
2568 #ifdef _M_ARM64
2569       // Unsafe memory access
2570       CompiledMethod* nm = NULL;
2571       JavaThread* thread = (JavaThread*)t;
2572       if (in_java) {
2573         CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
2574         nm = (cb != NULL) ? cb->as_compiled_method_or_null() : NULL;
2575       }
2576 
2577       bool is_unsafe_arraycopy = (thread->thread_state() == _thread_in_native || in_java) && UnsafeCopyMemory::contains_pc(pc);
2578       if (is_unsafe_arraycopy ||
2579           ((thread->thread_state() == _thread_in_vm ||
2580               thread->thread_state() == _thread_in_native) &&
2581             thread->doing_unsafe_access()) ||
2582           (nm != NULL && nm->has_unsafe_access())) {
2583         address next_pc =  Assembler::locate_next_instruction(pc);
2584         if (is_unsafe_arraycopy) {
2585           next_pc = UnsafeCopyMemory::page_error_continue_pc(pc);
2586         }
2587         return Handle_Exception(exceptionInfo, SharedRuntime::handle_unsafe_access(thread, next_pc));
2588       }
2589 #endif
2590 
2591 #ifdef _WIN64
2592       // Special care for fast JNI field accessors.
2593       // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks
2594       // in and the heap gets shrunk before the field access.
2595       if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
2596         address addr = JNI_FastGetField::find_slowcase_pc(pc);
2597         if (addr != (address)-1) {
2598           return Handle_Exception(exceptionInfo, addr);
2599         }
2600       }
2601 #endif
2602 
2603       // Stack overflow or null pointer exception in native code.
2604       report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
2605                    exceptionInfo->ContextRecord);
2606       return EXCEPTION_CONTINUE_SEARCH;
2607     } // /EXCEPTION_ACCESS_VIOLATION
2608     // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2609 
2610     if (exception_code == EXCEPTION_IN_PAGE_ERROR) {


2612       JavaThread* thread = (JavaThread*)t;
2613       if (in_java) {
2614         CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
2615         nm = (cb != NULL) ? cb->as_compiled_method_or_null() : NULL;
2616       }
2617 
2618       bool is_unsafe_arraycopy = (thread->thread_state() == _thread_in_native || in_java) && UnsafeCopyMemory::contains_pc(pc);
2619       if (((thread->thread_state() == _thread_in_vm ||
2620            thread->thread_state() == _thread_in_native ||
2621            is_unsafe_arraycopy) &&
2622           thread->doing_unsafe_access()) ||
2623           (nm != NULL && nm->has_unsafe_access())) {
2624         address next_pc =  Assembler::locate_next_instruction(pc);
2625         if (is_unsafe_arraycopy) {
2626           next_pc = UnsafeCopyMemory::page_error_continue_pc(pc);
2627         }
2628         return Handle_Exception(exceptionInfo, SharedRuntime::handle_unsafe_access(thread, next_pc));
2629       }
2630     }
2631 
2632 #ifdef _M_ARM64
2633     if (in_java &&
2634         (exception_code == EXCEPTION_ILLEGAL_INSTRUCTION ||
2635           exception_code == EXCEPTION_ILLEGAL_INSTRUCTION_2)) {
2636       if (nativeInstruction_at(pc)->is_sigill_zombie_not_entrant()) {
2637         if (TraceTraps) {
2638           tty->print_cr("trap: zombie_not_entrant");
2639         }
2640         return Handle_Exception(exceptionInfo, SharedRuntime::get_handle_wrong_method_stub());
2641       }
2642     }
2643 #endif
2644 
2645     if (in_java) {
2646       switch (exception_code) {
2647       case EXCEPTION_INT_DIVIDE_BY_ZERO:
2648         return Handle_Exception(exceptionInfo, SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_DIVIDE_BY_ZERO));
2649 
2650       case EXCEPTION_INT_OVERFLOW:
2651         return Handle_IDiv_Exception(exceptionInfo);
2652 
2653       } // switch
2654     }
2655 
2656 #if defined(_M_AMD64) || defined(_M_IX86)
2657     if (((thread->thread_state() == _thread_in_Java) ||
2658          (thread->thread_state() == _thread_in_native)) &&
2659          exception_code != EXCEPTION_UNCAUGHT_CXX_EXCEPTION) {
2660       LONG result=Handle_FLT_Exception(exceptionInfo);
2661       if (result==EXCEPTION_CONTINUE_EXECUTION) return result;
2662     }
2663 #endif
2664   }
2665 
2666   if (exception_code != EXCEPTION_BREAKPOINT) {
2667     report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
2668                  exceptionInfo->ContextRecord);
2669   }
2670   return EXCEPTION_CONTINUE_SEARCH;
2671 }
2672 
2673 #ifndef _WIN64
2674 // Special care for fast JNI accessors.
2675 // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in and
2676 // the heap gets shrunk before the field access.
2677 // Need to install our own structured exception handler since native code may
2678 // install its own.
2679 LONG WINAPI fastJNIAccessorExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) {
2680   DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode;
2681   if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
2682     address pc = (address) exceptionInfo->ContextRecord->Eip;
2683     address addr = JNI_FastGetField::find_slowcase_pc(pc);


3651   }
3652 }
3653 
3654 int os::numa_get_group_id_for_address(const void* address) {
3655   return 0;
3656 }
3657 
3658 bool os::get_page_info(char *start, page_info* info) {
3659   return false;
3660 }
3661 
3662 char *os::scan_pages(char *start, char* end, page_info* page_expected,
3663                      page_info* page_found) {
3664   return end;
3665 }
3666 
3667 char* os::non_memory_address_word() {
3668   // Must never look like an address returned by reserve_memory,
3669   // even in its subfields (as defined by the CPU immediate fields,
3670   // if the CPU splits constants across multiple instructions).
3671 #ifdef _M_ARM64
3672   // AArch64 has a maximum addressable space of 48-bits
3673   return (char*)((1ull << 48) - 1);
3674 #else
3675   return (char*)-1;
3676 #endif
3677 }
3678 
3679 #define MAX_ERROR_COUNT 100
3680 #define SYS_THREAD_ERROR 0xffffffffUL
3681 
3682 void os::pd_start_thread(Thread* thread) {
3683   DWORD ret = ResumeThread(thread->osthread()->thread_handle());
3684   // Returns previous suspend state:
3685   // 0:  Thread was not suspended
3686   // 1:  Thread is running now
3687   // >1: Thread is still suspended.
3688   assert(ret != SYS_THREAD_ERROR, "StartThread failed"); // should propagate back
3689 }
3690 
3691 
3692 // Short sleep, direct OS call.
3693 //
3694 // ms = 0, means allow others (if any) to run.
3695 //
3696 void os::naked_short_sleep(jlong ms) {


3852   case VER_PLATFORM_WIN32_NT:
3853     {
3854       int os_vers = oi.dwMajorVersion * 1000 + oi.dwMinorVersion;
3855       if (oi.wProductType == VER_NT_DOMAIN_CONTROLLER ||
3856           oi.wProductType == VER_NT_SERVER) {
3857         _is_windows_server = true;
3858       }
3859     }
3860     break;
3861   default: fatal("Unknown platform");
3862   }
3863 
3864   _default_stack_size = os::current_stack_size();
3865   assert(_default_stack_size > (size_t) _vm_page_size, "invalid stack size");
3866   assert((_default_stack_size & (_vm_page_size - 1)) == 0,
3867          "stack size not a multiple of page size");
3868 
3869   initialize_performance_counter();
3870 }
3871 
3872 int os::win32::get_cacheline_size() {
3873   PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL;
3874   DWORD returnLength = 0;
3875 
3876   // See https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformation
3877 
3878   GetLogicalProcessorInformation(NULL, &returnLength);
3879   assert(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Unexpected return from GetLogicalProcessorInformation");
3880 
3881   buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)os::malloc(returnLength, mtInternal);
3882   BOOL rc = GetLogicalProcessorInformation(buffer, &returnLength);
3883   assert(rc, "Unexpected return from GetLogicalProcessorInformation");
3884 
3885   int line_sz = -1;
3886   for (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = buffer; ptr < buffer + returnLength / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); ptr++) {
3887     switch (ptr->Relationship) {
3888     case RelationCache:
3889       // Cache data is in ptr->Cache, one CACHE_DESCRIPTOR structure for each cache.
3890       PCACHE_DESCRIPTOR Cache = &ptr->Cache;
3891       if (Cache->Level == 1) {
3892         line_sz = Cache->LineSize;
3893       }
3894       break;
3895     }
3896   }
3897   os::free(buffer);
3898   return line_sz;
3899 }
3900 
3901 HINSTANCE os::win32::load_Windows_dll(const char* name, char *ebuf,
3902                                       int ebuflen) {
3903   char path[MAX_PATH];
3904   DWORD size;
3905   DWORD pathLen = (DWORD)sizeof(path);
3906   HINSTANCE result = NULL;
3907 
3908   // only allow library name without path component
3909   assert(strchr(name, '\\') == NULL, "path not allowed");
3910   assert(strchr(name, ':') == NULL, "path not allowed");
3911   if (strchr(name, '\\') != NULL || strchr(name, ':') != NULL) {
3912     jio_snprintf(ebuf, ebuflen,
3913                  "Invalid parameter while calling os::win32::load_windows_dll(): cannot take path: %s", name);
3914     return NULL;
3915   }
3916 
3917   // search system directory
3918   if ((size = GetSystemDirectory(path, pathLen)) > 0) {
3919     if (size >= pathLen) {


4208 }
4209 
4210 // To install functions for atexit processing
4211 extern "C" {
4212   static void perfMemory_exit_helper() {
4213     perfMemory_exit();
4214   }
4215 }
4216 
4217 static jint initSock();
4218 
4219 // this is called _after_ the global arguments have been parsed
4220 jint os::init_2(void) {
4221 
4222   // This could be set any time but all platforms
4223   // have to set it the same so we have to mirror Solaris.
4224   DEBUG_ONLY(os::set_mutex_init_done();)
4225 
4226   // Setup Windows Exceptions
4227 
4228 #if defined(USE_VECTORED_EXCEPTION_HANDLING)
4229   topLevelVectoredExceptionHandler = AddVectoredExceptionHandler(1, topLevelExceptionFilter);
4230 #elif INCLUDE_AOT
4231   // If AOT is enabled we need to install a vectored exception handler
4232   // in order to forward implicit exceptions from code in AOT
4233   // generated DLLs.  This is necessary since these DLLs are not
4234   // registered for structured exceptions like codecache methods are.
4235   if (AOTLibrary != NULL && (UseAOT || FLAG_IS_DEFAULT(UseAOT))) {
4236     topLevelVectoredExceptionHandler = AddVectoredExceptionHandler( 1, topLevelVectoredExceptionFilter);
4237   }
4238 #endif
4239 
4240   // for debugging float code generation bugs
4241   if (ForceFloatExceptions) {
4242 #ifndef  _WIN64
4243     static long fp_control_word = 0;
4244     __asm { fstcw fp_control_word }
4245     // see Intel PPro Manual, Vol. 2, p 7-16
4246     const long precision = 0x20;
4247     const long underflow = 0x10;
4248     const long overflow  = 0x08;
4249     const long zero_div  = 0x04;
4250     const long denorm    = 0x02;


5669 
5670 int os::connect(int fd, struct sockaddr* him, socklen_t len) {
5671   return ::connect(fd, him, len);
5672 }
5673 
5674 int os::recv(int fd, char* buf, size_t nBytes, uint flags) {
5675   return ::recv(fd, buf, (int)nBytes, flags);
5676 }
5677 
5678 int os::send(int fd, char* buf, size_t nBytes, uint flags) {
5679   return ::send(fd, buf, (int)nBytes, flags);
5680 }
5681 
5682 int os::raw_send(int fd, char* buf, size_t nBytes, uint flags) {
5683   return ::send(fd, buf, (int)nBytes, flags);
5684 }
5685 
5686 // WINDOWS CONTEXT Flags for THREAD_SAMPLING
5687 #if defined(IA32)
5688   #define sampling_context_flags (CONTEXT_FULL | CONTEXT_FLOATING_POINT | CONTEXT_EXTENDED_REGISTERS)
5689 #elif defined(AMD64) || defined(_M_ARM64)
5690   #define sampling_context_flags (CONTEXT_FULL | CONTEXT_FLOATING_POINT)
5691 #endif
5692 
5693 // returns true if thread could be suspended,
5694 // false otherwise
5695 static bool do_suspend(HANDLE* h) {
5696   if (h != NULL) {
5697     if (SuspendThread(*h) != ~0) {
5698       return true;
5699     }
5700   }
5701   return false;
5702 }
5703 
5704 // resume the thread
5705 // calling resume on an active thread is a no-op
5706 static void do_resume(HANDLE* h) {
5707   if (h != NULL) {
5708     ResumeThread(*h);
5709   }


< prev index next >