1 /*
2 * Copyright (c) 1999, 2021, 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 // no precompiled headers
26 #include "jvm.h"
27 #include "asm/macroAssembler.hpp"
28 #include "classfile/vmSymbols.hpp"
29 #include "code/icBuffer.hpp"
30 #include "code/vtableStubs.hpp"
31 #include "interpreter/interpreter.hpp"
32 #include "memory/allocation.inline.hpp"
33 #include "memory/resourceArea.hpp"
34 #include "nativeInst_x86.hpp"
35 #include "os_share_windows.hpp"
36 #include "prims/jniFastGetField.hpp"
37 #include "prims/jvm_misc.hpp"
38 #include "runtime/arguments.hpp"
39 #include "runtime/frame.inline.hpp"
40 #include "runtime/interfaceSupport.inline.hpp"
41 #include "runtime/java.hpp"
42 #include "runtime/javaCalls.hpp"
43 #include "runtime/mutexLocker.hpp"
44 #include "runtime/osThread.hpp"
45 #include "runtime/sharedRuntime.hpp"
46 #include "runtime/stubRoutines.hpp"
47 #include "runtime/thread.inline.hpp"
48 #include "runtime/timer.hpp"
49 #include "symbolengine.hpp"
50 #include "unwind_windows_x86.hpp"
51 #include "utilities/events.hpp"
52 #include "utilities/vmError.hpp"
53 #include "windbghelp.hpp"
54
55
56 #undef REG_SP
57 #undef REG_FP
58 #undef REG_PC
59 #ifdef AMD64
60 #define REG_SP Rsp
61 #define REG_FP Rbp
62 #define REG_PC Rip
63 #else
64 #define REG_SP Esp
65 #define REG_FP Ebp
66 #define REG_PC Eip
67 #endif // AMD64
68
69 JNIEXPORT
70 extern LONG WINAPI topLevelExceptionFilter(_EXCEPTION_POINTERS* );
71
72 // Install a win32 structured exception handler around thread.
os_exception_wrapper(java_call_t f,JavaValue * value,const methodHandle & method,JavaCallArguments * args,JavaThread * thread)73 void os::os_exception_wrapper(java_call_t f, JavaValue* value, const methodHandle& method, JavaCallArguments* args, JavaThread* thread) {
74 __try {
75
76 #ifndef AMD64
77 // We store the current thread in this wrapperthread location
78 // and determine how far away this address is from the structured
79 // execption pointer that FS:[0] points to. This get_thread
80 // code can then get the thread pointer via FS.
81 //
82 // Warning: This routine must NEVER be inlined since we'd end up with
83 // multiple offsets.
84 //
85 volatile Thread* wrapperthread = thread;
86
87 if (os::win32::get_thread_ptr_offset() == 0) {
88 int thread_ptr_offset;
89 __asm {
90 lea eax, dword ptr wrapperthread;
91 sub eax, dword ptr FS:[0H];
92 mov thread_ptr_offset, eax
93 };
94 os::win32::set_thread_ptr_offset(thread_ptr_offset);
95 }
96 #ifdef ASSERT
97 // Verify that the offset hasn't changed since we initally captured
98 // it. This might happen if we accidentally ended up with an
99 // inlined version of this routine.
100 else {
101 int test_thread_ptr_offset;
102 __asm {
103 lea eax, dword ptr wrapperthread;
104 sub eax, dword ptr FS:[0H];
105 mov test_thread_ptr_offset, eax
106 };
107 assert(test_thread_ptr_offset == os::win32::get_thread_ptr_offset(),
108 "thread pointer offset from SEH changed");
109 }
110 #endif // ASSERT
111 #endif // !AMD64
112
113 f(value, method, args, thread);
114 } __except(topLevelExceptionFilter((_EXCEPTION_POINTERS*)_exception_info())) {
115 // Nothing to do.
116 }
117 }
118
119 #ifdef AMD64
120
121 // This is the language specific handler for exceptions
122 // originating from dynamically generated code.
123 // We call the standard structured exception handler
124 // We only expect Continued Execution since we cannot unwind
125 // from generated code.
HandleExceptionFromCodeCache(IN PEXCEPTION_RECORD ExceptionRecord,IN ULONG64 EstablisherFrame,IN OUT PCONTEXT ContextRecord,IN OUT PDISPATCHER_CONTEXT DispatcherContext)126 LONG HandleExceptionFromCodeCache(
127 IN PEXCEPTION_RECORD ExceptionRecord,
128 IN ULONG64 EstablisherFrame,
129 IN OUT PCONTEXT ContextRecord,
130 IN OUT PDISPATCHER_CONTEXT DispatcherContext) {
131 EXCEPTION_POINTERS ep;
132 LONG result;
133
134 ep.ExceptionRecord = ExceptionRecord;
135 ep.ContextRecord = ContextRecord;
136
137 result = topLevelExceptionFilter(&ep);
138
139 // We better only get a CONTINUE_EXECUTION from our handler
140 // since we don't have unwind information registered.
141
142 guarantee( result == EXCEPTION_CONTINUE_EXECUTION,
143 "Unexpected result from topLevelExceptionFilter");
144
145 return(ExceptionContinueExecution);
146 }
147
148
149 // Structure containing the Windows Data Structures required
150 // to register our Code Cache exception handler.
151 // We put these in the CodeCache since the API requires
152 // all addresses in these structures are relative to the Code
153 // area registered with RtlAddFunctionTable.
154 typedef struct {
155 char ExceptionHandlerInstr[16]; // jmp HandleExceptionFromCodeCache
156 RUNTIME_FUNCTION rt;
157 UNWIND_INFO_EH_ONLY unw;
158 } DynamicCodeData, *pDynamicCodeData;
159
160 #endif // AMD64
161 //
162 // Register our CodeCache area with the OS so it will dispatch exceptions
163 // to our topLevelExceptionFilter when we take an exception in our
164 // dynamically generated code.
165 //
166 // Arguments: low and high are the address of the full reserved
167 // codeCache area
168 //
register_code_area(char * low,char * high)169 bool os::register_code_area(char *low, char *high) {
170 #ifdef AMD64
171
172 ResourceMark rm;
173
174 pDynamicCodeData pDCD;
175 PRUNTIME_FUNCTION prt;
176 PUNWIND_INFO_EH_ONLY punwind;
177
178 BufferBlob* blob = BufferBlob::create("CodeCache Exception Handler", sizeof(DynamicCodeData));
179 CodeBuffer cb(blob);
180 MacroAssembler* masm = new MacroAssembler(&cb);
181 pDCD = (pDynamicCodeData) masm->pc();
182
183 masm->jump(ExternalAddress((address)&HandleExceptionFromCodeCache));
184 masm->flush();
185
186 // Create an Unwind Structure specifying no unwind info
187 // other than an Exception Handler
188 punwind = &pDCD->unw;
189 punwind->Version = 1;
190 punwind->Flags = UNW_FLAG_EHANDLER;
191 punwind->SizeOfProlog = 0;
192 punwind->CountOfCodes = 0;
193 punwind->FrameRegister = 0;
194 punwind->FrameOffset = 0;
195 punwind->ExceptionHandler = (char *)(&(pDCD->ExceptionHandlerInstr[0])) -
196 (char*)low;
197 punwind->ExceptionData[0] = 0;
198
199 // This structure describes the covered dynamic code area.
200 // Addresses are relative to the beginning on the code cache area
201 prt = &pDCD->rt;
202 prt->BeginAddress = 0;
203 prt->EndAddress = (ULONG)(high - low);
204 prt->UnwindData = ((char *)punwind - low);
205
206 guarantee(RtlAddFunctionTable(prt, 1, (ULONGLONG)low),
207 "Failed to register Dynamic Code Exception Handler with RtlAddFunctionTable");
208
209 #endif // AMD64
210 return true;
211 }
212
213 #ifdef AMD64
214 /*
215 * Windows/x64 does not use stack frames the way expected by Java:
216 * [1] in most cases, there is no frame pointer. All locals are addressed via RSP
217 * [2] in rare cases, when alloca() is used, a frame pointer is used, but this may
218 * not be RBP.
219 * See http://msdn.microsoft.com/en-us/library/ew5tede7.aspx
220 *
221 * So it's not possible to print the native stack using the
222 * while (...) {... fr = os::get_sender_for_C_frame(&fr); }
223 * loop in vmError.cpp. We need to roll our own loop.
224 */
platform_print_native_stack(outputStream * st,const void * context,char * buf,int buf_size)225 bool os::platform_print_native_stack(outputStream* st, const void* context,
226 char *buf, int buf_size)
227 {
228 CONTEXT ctx;
229 if (context != NULL) {
230 memcpy(&ctx, context, sizeof(ctx));
231 } else {
232 RtlCaptureContext(&ctx);
233 }
234
235 st->print_cr("Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)");
236
237 STACKFRAME stk;
238 memset(&stk, 0, sizeof(stk));
239 stk.AddrStack.Offset = ctx.Rsp;
240 stk.AddrStack.Mode = AddrModeFlat;
241 stk.AddrFrame.Offset = ctx.Rbp;
242 stk.AddrFrame.Mode = AddrModeFlat;
243 stk.AddrPC.Offset = ctx.Rip;
244 stk.AddrPC.Mode = AddrModeFlat;
245
246 int count = 0;
247 address lastpc = 0;
248 while (count++ < StackPrintLimit) {
249 intptr_t* sp = (intptr_t*)stk.AddrStack.Offset;
250 intptr_t* fp = (intptr_t*)stk.AddrFrame.Offset; // NOT necessarily the same as ctx.Rbp!
251 address pc = (address)stk.AddrPC.Offset;
252
253 if (pc != NULL) {
254 if (count == 2 && lastpc == pc) {
255 // Skip it -- StackWalk64() may return the same PC
256 // (but different SP) on the first try.
257 } else {
258 // Don't try to create a frame(sp, fp, pc) -- on WinX64, stk.AddrFrame
259 // may not contain what Java expects, and may cause the frame() constructor
260 // to crash. Let's just print out the symbolic address.
261 frame::print_C_frame(st, buf, buf_size, pc);
262 // print source file and line, if available
263 char buf[128];
264 int line_no;
265 if (SymbolEngine::get_source_info(pc, buf, sizeof(buf), &line_no)) {
266 st->print(" (%s:%d)", buf, line_no);
267 }
268 st->cr();
269 }
270 lastpc = pc;
271 }
272
273 PVOID p = WindowsDbgHelp::symFunctionTableAccess64(GetCurrentProcess(), stk.AddrPC.Offset);
274 if (!p) {
275 // StackWalk64() can't handle this PC. Calling StackWalk64 again may cause crash.
276 break;
277 }
278
279 BOOL result = WindowsDbgHelp::stackWalk64(
280 IMAGE_FILE_MACHINE_AMD64, // __in DWORD MachineType,
281 GetCurrentProcess(), // __in HANDLE hProcess,
282 GetCurrentThread(), // __in HANDLE hThread,
283 &stk, // __inout LP STACKFRAME64 StackFrame,
284 &ctx); // __inout PVOID ContextRecord,
285
286 if (!result) {
287 break;
288 }
289 }
290 if (count > StackPrintLimit) {
291 st->print_cr("...<more frames>...");
292 }
293 st->cr();
294
295 return true;
296 }
297 #endif // AMD64
298
fetch_frame_from_context(const void * ucVoid,intptr_t ** ret_sp,intptr_t ** ret_fp)299 address os::fetch_frame_from_context(const void* ucVoid,
300 intptr_t** ret_sp, intptr_t** ret_fp) {
301
302 address epc;
303 CONTEXT* uc = (CONTEXT*)ucVoid;
304
305 if (uc != NULL) {
306 epc = (address)uc->REG_PC;
307 if (ret_sp) *ret_sp = (intptr_t*)uc->REG_SP;
308 if (ret_fp) *ret_fp = (intptr_t*)uc->REG_FP;
309 } else {
310 epc = NULL;
311 if (ret_sp) *ret_sp = (intptr_t *)NULL;
312 if (ret_fp) *ret_fp = (intptr_t *)NULL;
313 }
314
315 return epc;
316 }
317
fetch_frame_from_context(const void * ucVoid)318 frame os::fetch_frame_from_context(const void* ucVoid) {
319 intptr_t* sp;
320 intptr_t* fp;
321 address epc = fetch_frame_from_context(ucVoid, &sp, &fp);
322 return frame(sp, fp, epc);
323 }
324
325 #ifndef AMD64
326 // Ignore "C4172: returning address of local variable or temporary" on 32bit
327 PRAGMA_DIAG_PUSH
328 PRAGMA_DISABLE_MSVC_WARNING(4172)
329 // Returns an estimate of the current stack pointer. Result must be guaranteed
330 // to point into the calling threads stack, and be no lower than the current
331 // stack pointer.
current_stack_pointer()332 address os::current_stack_pointer() {
333 int dummy;
334 address sp = (address)&dummy;
335 return sp;
336 }
337 PRAGMA_DIAG_POP
338 #else
339 // Returns the current stack pointer. Accurate value needed for
340 // os::verify_stack_alignment().
341 address os::current_stack_pointer() {
342 typedef address get_sp_func();
343 get_sp_func* func = CAST_TO_FN_PTR(get_sp_func*,
344 StubRoutines::x86::get_previous_sp_entry());
345 return (*func)();
346 }
347 #endif
348
get_frame_at_stack_banging_point(JavaThread * thread,struct _EXCEPTION_POINTERS * exceptionInfo,address pc,frame * fr)349 bool os::win32::get_frame_at_stack_banging_point(JavaThread* thread,
350 struct _EXCEPTION_POINTERS* exceptionInfo, address pc, frame* fr) {
351 PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
352 address addr = (address) exceptionRecord->ExceptionInformation[1];
353 if (Interpreter::contains(pc)) {
354 *fr = os::fetch_frame_from_context((void*)exceptionInfo->ContextRecord);
355 if (!fr->is_first_java_frame()) {
356 // get_frame_at_stack_banging_point() is only called when we
357 // have well defined stacks so java_sender() calls do not need
358 // to assert safe_for_sender() first.
359 *fr = fr->java_sender();
360 }
361 } else {
362 // more complex code with compiled code
363 assert(!Interpreter::contains(pc), "Interpreted methods should have been handled above");
364 CodeBlob* cb = CodeCache::find_blob(pc);
365 if (cb == NULL || !cb->is_nmethod() || cb->is_frame_complete_at(pc)) {
366 // Not sure where the pc points to, fallback to default
367 // stack overflow handling
368 return false;
369 } else {
370 // in compiled code, the stack banging is performed just after the return pc
371 // has been pushed on the stack
372 intptr_t* fp = (intptr_t*)exceptionInfo->ContextRecord->REG_FP;
373 intptr_t* sp = (intptr_t*)exceptionInfo->ContextRecord->REG_SP;
374 *fr = frame(sp + 1, fp, (address)*sp);
375 if (!fr->is_java_frame()) {
376 // See java_sender() comment above.
377 *fr = fr->java_sender();
378 }
379 }
380 }
381 assert(fr->is_java_frame(), "Safety check");
382 return true;
383 }
384
385
386 // VC++ does not save frame pointer on stack in optimized build. It
387 // can be turned off by /Oy-. If we really want to walk C frames,
388 // we can use the StackWalk() API.
get_sender_for_C_frame(frame * fr)389 frame os::get_sender_for_C_frame(frame* fr) {
390 ShouldNotReachHere();
391 return frame();
392 }
393
current_frame()394 frame os::current_frame() {
395 return frame(); // cannot walk Windows frames this way. See os::get_native_stack
396 // and os::platform_print_native_stack
397 }
398
print_context(outputStream * st,const void * context)399 void os::print_context(outputStream *st, const void *context) {
400 if (context == NULL) return;
401
402 const CONTEXT* uc = (const CONTEXT*)context;
403
404 st->print_cr("Registers:");
405 #ifdef AMD64
406 st->print( "RAX=" INTPTR_FORMAT, uc->Rax);
407 st->print(", RBX=" INTPTR_FORMAT, uc->Rbx);
408 st->print(", RCX=" INTPTR_FORMAT, uc->Rcx);
409 st->print(", RDX=" INTPTR_FORMAT, uc->Rdx);
410 st->cr();
411 st->print( "RSP=" INTPTR_FORMAT, uc->Rsp);
412 st->print(", RBP=" INTPTR_FORMAT, uc->Rbp);
413 st->print(", RSI=" INTPTR_FORMAT, uc->Rsi);
414 st->print(", RDI=" INTPTR_FORMAT, uc->Rdi);
415 st->cr();
416 st->print( "R8 =" INTPTR_FORMAT, uc->R8);
417 st->print(", R9 =" INTPTR_FORMAT, uc->R9);
418 st->print(", R10=" INTPTR_FORMAT, uc->R10);
419 st->print(", R11=" INTPTR_FORMAT, uc->R11);
420 st->cr();
421 st->print( "R12=" INTPTR_FORMAT, uc->R12);
422 st->print(", R13=" INTPTR_FORMAT, uc->R13);
423 st->print(", R14=" INTPTR_FORMAT, uc->R14);
424 st->print(", R15=" INTPTR_FORMAT, uc->R15);
425 st->cr();
426 st->print( "RIP=" INTPTR_FORMAT, uc->Rip);
427 st->print(", EFLAGS=" INTPTR_FORMAT, uc->EFlags);
428 #else
429 st->print( "EAX=" INTPTR_FORMAT, uc->Eax);
430 st->print(", EBX=" INTPTR_FORMAT, uc->Ebx);
431 st->print(", ECX=" INTPTR_FORMAT, uc->Ecx);
432 st->print(", EDX=" INTPTR_FORMAT, uc->Edx);
433 st->cr();
434 st->print( "ESP=" INTPTR_FORMAT, uc->Esp);
435 st->print(", EBP=" INTPTR_FORMAT, uc->Ebp);
436 st->print(", ESI=" INTPTR_FORMAT, uc->Esi);
437 st->print(", EDI=" INTPTR_FORMAT, uc->Edi);
438 st->cr();
439 st->print( "EIP=" INTPTR_FORMAT, uc->Eip);
440 st->print(", EFLAGS=" INTPTR_FORMAT, uc->EFlags);
441 #endif // AMD64
442 st->cr();
443 st->cr();
444
445 intptr_t *sp = (intptr_t *)uc->REG_SP;
446 st->print_cr("Top of Stack: (sp=" PTR_FORMAT ")", sp);
447 print_hex_dump(st, (address)sp, (address)(sp + 32), sizeof(intptr_t));
448 st->cr();
449
450 // Note: it may be unsafe to inspect memory near pc. For example, pc may
451 // point to garbage if entry point in an nmethod is corrupted. Leave
452 // this at the end, and hope for the best.
453 address pc = (address)uc->REG_PC;
454 print_instructions(st, pc, sizeof(char));
455 st->cr();
456 }
457
458
print_register_info(outputStream * st,const void * context)459 void os::print_register_info(outputStream *st, const void *context) {
460 if (context == NULL) return;
461
462 const CONTEXT* uc = (const CONTEXT*)context;
463
464 st->print_cr("Register to memory mapping:");
465 st->cr();
466
467 // this is only for the "general purpose" registers
468
469 #ifdef AMD64
470 st->print("RIP="); print_location(st, uc->Rip);
471 st->print("RAX="); print_location(st, uc->Rax);
472 st->print("RBX="); print_location(st, uc->Rbx);
473 st->print("RCX="); print_location(st, uc->Rcx);
474 st->print("RDX="); print_location(st, uc->Rdx);
475 st->print("RSP="); print_location(st, uc->Rsp);
476 st->print("RBP="); print_location(st, uc->Rbp);
477 st->print("RSI="); print_location(st, uc->Rsi);
478 st->print("RDI="); print_location(st, uc->Rdi);
479 st->print("R8 ="); print_location(st, uc->R8);
480 st->print("R9 ="); print_location(st, uc->R9);
481 st->print("R10="); print_location(st, uc->R10);
482 st->print("R11="); print_location(st, uc->R11);
483 st->print("R12="); print_location(st, uc->R12);
484 st->print("R13="); print_location(st, uc->R13);
485 st->print("R14="); print_location(st, uc->R14);
486 st->print("R15="); print_location(st, uc->R15);
487 #else
488 st->print("EIP="); print_location(st, uc->Eip);
489 st->print("EAX="); print_location(st, uc->Eax);
490 st->print("EBX="); print_location(st, uc->Ebx);
491 st->print("ECX="); print_location(st, uc->Ecx);
492 st->print("EDX="); print_location(st, uc->Edx);
493 st->print("ESP="); print_location(st, uc->Esp);
494 st->print("EBP="); print_location(st, uc->Ebp);
495 st->print("ESI="); print_location(st, uc->Esi);
496 st->print("EDI="); print_location(st, uc->Edi);
497 #endif
498
499 st->cr();
500 }
501
SpinPause()502 extern "C" int SpinPause () {
503 #ifdef AMD64
504 return 0 ;
505 #else
506 // pause == rep:nop
507 // On systems that don't support pause a rep:nop
508 // is executed as a nop. The rep: prefix is ignored.
509 _asm {
510 pause ;
511 };
512 return 1 ;
513 #endif // AMD64
514 }
515
cpu_microcode_revision()516 juint os::cpu_microcode_revision() {
517 juint result = 0;
518 BYTE data[8] = {0};
519 HKEY key;
520 DWORD status = RegOpenKey(HKEY_LOCAL_MACHINE,
521 "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", &key);
522 if (status == ERROR_SUCCESS) {
523 DWORD size = sizeof(data);
524 status = RegQueryValueEx(key, "Update Revision", NULL, NULL, data, &size);
525 if (status == ERROR_SUCCESS) {
526 if (size == 4) result = *((juint*)data);
527 if (size == 8) result = *((juint*)data + 1); // upper 32-bits
528 }
529 RegCloseKey(key);
530 }
531 return result;
532 }
533
setup_fpu()534 void os::setup_fpu() {
535 #ifndef AMD64
536 int fpu_cntrl_word = StubRoutines::x86::fpu_cntrl_wrd_std();
537 __asm fldcw fpu_cntrl_word;
538 #endif // !AMD64
539 }
540
541 #ifndef PRODUCT
verify_stack_alignment()542 void os::verify_stack_alignment() {
543 #ifdef AMD64
544 // The current_stack_pointer() calls generated get_previous_sp stub routine.
545 // Only enable the assert after the routine becomes available.
546 if (StubRoutines::code1() != NULL) {
547 assert(((intptr_t)os::current_stack_pointer() & (StackAlignmentInBytes-1)) == 0, "incorrect stack alignment");
548 }
549 #endif
550 }
551 #endif
552
extra_bang_size_in_bytes()553 int os::extra_bang_size_in_bytes() {
554 // JDK-8050147 requires the full cache line bang for x86.
555 return VM_Version::L1_line_size();
556 }
557