VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMAll/IEMAllCImpl.cpp@ 104627

Last change on this file since 104627 was 104516, checked in by vboxsync, 9 months ago

VMM/GCM,IEM,HM: Integrate GCM with IEM, extending it to cover the mesa drv situation and valid ring-0 IN instructions to same port. Untested. TODO: NEM. bugref:9735 bugref:10683

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 364.3 KB
Line 
1/* $Id: IEMAllCImpl.cpp 104516 2024-05-04 01:53:42Z vboxsync $ */
2/** @file
3 * IEM - Instruction Implementation in C/C++ (code include).
4 */
5
6/*
7 * Copyright (C) 2011-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define LOG_GROUP LOG_GROUP_IEM
33#define VMCPU_INCL_CPUM_GST_CTX
34#define IEM_WITH_OPAQUE_DECODER_STATE
35#include <VBox/vmm/iem.h>
36#include <VBox/vmm/cpum.h>
37#include <VBox/vmm/apic.h>
38#include <VBox/vmm/pdm.h>
39#include <VBox/vmm/pgm.h>
40#include <VBox/vmm/iom.h>
41#include <VBox/vmm/em.h>
42#include <VBox/vmm/hm.h>
43#include <VBox/vmm/nem.h>
44#include <VBox/vmm/gim.h>
45#include <VBox/vmm/gcm.h>
46#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
47# include <VBox/vmm/em.h>
48# include <VBox/vmm/hm_svm.h>
49#endif
50#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
51# include <VBox/vmm/hmvmxinline.h>
52#endif
53#ifndef VBOX_WITHOUT_CPUID_HOST_CALL
54# include <VBox/vmm/cpuidcall.h>
55#endif
56#include <VBox/vmm/tm.h>
57#include <VBox/vmm/dbgf.h>
58#include <VBox/vmm/dbgftrace.h>
59#include "IEMInternal.h"
60#include <VBox/vmm/vmcc.h>
61#include <VBox/log.h>
62#include <VBox/err.h>
63#include <VBox/param.h>
64#include <VBox/dis.h>
65#include <iprt/asm-math.h>
66#include <iprt/assert.h>
67#include <iprt/string.h>
68#include <iprt/x86.h>
69
70#include "IEMInline.h"
71
72
73/*********************************************************************************************************************************
74* Defined Constants And Macros *
75*********************************************************************************************************************************/
76/**
77 * Flushes the prefetch buffer, light version.
78 * @todo The \#if conditions here must match the ones in iemOpcodeFlushLight().
79 */
80#ifndef IEM_WITH_CODE_TLB
81# define IEM_FLUSH_PREFETCH_LIGHT(a_pVCpu, a_cbInstr) iemOpcodeFlushLight(a_pVCpu, a_cbInstr)
82#else
83# define IEM_FLUSH_PREFETCH_LIGHT(a_pVCpu, a_cbInstr) do { } while (0)
84#endif
85
86/**
87 * Flushes the prefetch buffer, heavy version.
88 * @todo The \#if conditions here must match the ones in iemOpcodeFlushHeavy().
89 */
90#if !defined(IEM_WITH_CODE_TLB) || 1
91# define IEM_FLUSH_PREFETCH_HEAVY(a_pVCpu, a_cbInstr) iemOpcodeFlushHeavy(a_pVCpu, a_cbInstr)
92#else
93# define IEM_FLUSH_PREFETCH_HEAVY(a_pVCpu, a_cbInstr) do { } while (0)
94#endif
95
96
97
98/** @name Misc Helpers
99 * @{
100 */
101
102
103/**
104 * Worker function for iemHlpCheckPortIOPermission, don't call directly.
105 *
106 * @returns Strict VBox status code.
107 *
108 * @param pVCpu The cross context virtual CPU structure of the calling thread.
109 * @param u16Port The port number.
110 * @param cbOperand The operand size.
111 */
112static VBOXSTRICTRC iemHlpCheckPortIOPermissionBitmap(PVMCPUCC pVCpu, uint16_t u16Port, uint8_t cbOperand)
113{
114 /* The TSS bits we're interested in are the same on 386 and AMD64. */
115 AssertCompile(AMD64_SEL_TYPE_SYS_TSS_BUSY == X86_SEL_TYPE_SYS_386_TSS_BUSY);
116 AssertCompile(AMD64_SEL_TYPE_SYS_TSS_AVAIL == X86_SEL_TYPE_SYS_386_TSS_AVAIL);
117 AssertCompileMembersAtSameOffset(X86TSS32, offIoBitmap, X86TSS64, offIoBitmap);
118 AssertCompile(sizeof(X86TSS32) == sizeof(X86TSS64));
119
120 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_TR);
121
122 /*
123 * Check the TSS type, 16-bit TSSes doesn't have any I/O permission bitmap.
124 */
125 Assert(!pVCpu->cpum.GstCtx.tr.Attr.n.u1DescType);
126 if (RT_UNLIKELY( pVCpu->cpum.GstCtx.tr.Attr.n.u4Type != AMD64_SEL_TYPE_SYS_TSS_BUSY
127 && pVCpu->cpum.GstCtx.tr.Attr.n.u4Type != AMD64_SEL_TYPE_SYS_TSS_AVAIL))
128 {
129 Log(("iemHlpCheckPortIOPermissionBitmap: Port=%#x cb=%d - TSS type %#x (attr=%#x) has no I/O bitmap -> #GP(0)\n",
130 u16Port, cbOperand, pVCpu->cpum.GstCtx.tr.Attr.n.u4Type, pVCpu->cpum.GstCtx.tr.Attr.u));
131 return iemRaiseGeneralProtectionFault0(pVCpu);
132 }
133
134 /*
135 * Read the bitmap offset (may #PF).
136 */
137 uint16_t offBitmap;
138 VBOXSTRICTRC rcStrict = iemMemFetchSysU16(pVCpu, &offBitmap, UINT8_MAX,
139 pVCpu->cpum.GstCtx.tr.u64Base + RT_UOFFSETOF(X86TSS64, offIoBitmap));
140 if (rcStrict != VINF_SUCCESS)
141 {
142 Log(("iemHlpCheckPortIOPermissionBitmap: Error reading offIoBitmap (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
143 return rcStrict;
144 }
145
146 /*
147 * The bit range from u16Port to (u16Port + cbOperand - 1), however intel
148 * describes the CPU actually reading two bytes regardless of whether the
149 * bit range crosses a byte boundrary. Thus the + 1 in the test below.
150 */
151 uint32_t offFirstBit = (uint32_t)u16Port / 8 + offBitmap;
152 /** @todo check if real CPUs ensures that offBitmap has a minimum value of
153 * for instance sizeof(X86TSS32). */
154 if (offFirstBit + 1 > pVCpu->cpum.GstCtx.tr.u32Limit) /* the limit is inclusive */
155 {
156 Log(("iemHlpCheckPortIOPermissionBitmap: offFirstBit=%#x + 1 is beyond u32Limit=%#x -> #GP(0)\n",
157 offFirstBit, pVCpu->cpum.GstCtx.tr.u32Limit));
158 return iemRaiseGeneralProtectionFault0(pVCpu);
159 }
160
161 /*
162 * Read the necessary bits.
163 */
164 /** @todo Test the assertion in the intel manual that the CPU reads two
165 * bytes. The question is how this works wrt to \#PF and \#GP on the
166 * 2nd byte when it's not required. */
167 uint16_t bmBytes = UINT16_MAX;
168 rcStrict = iemMemFetchSysU16(pVCpu, &bmBytes, UINT8_MAX, pVCpu->cpum.GstCtx.tr.u64Base + offFirstBit);
169 if (rcStrict != VINF_SUCCESS)
170 {
171 Log(("iemHlpCheckPortIOPermissionBitmap: Error reading I/O bitmap @%#x (%Rrc)\n", offFirstBit, VBOXSTRICTRC_VAL(rcStrict)));
172 return rcStrict;
173 }
174
175 /*
176 * Perform the check.
177 */
178 uint16_t fPortMask = (1 << cbOperand) - 1;
179 bmBytes >>= (u16Port & 7);
180 if (bmBytes & fPortMask)
181 {
182 Log(("iemHlpCheckPortIOPermissionBitmap: u16Port=%#x LB %u - access denied (bm=%#x mask=%#x) -> #GP(0)\n",
183 u16Port, cbOperand, bmBytes, fPortMask));
184 return iemRaiseGeneralProtectionFault0(pVCpu);
185 }
186
187 return VINF_SUCCESS;
188}
189
190
191/**
192 * Checks if we are allowed to access the given I/O port, raising the
193 * appropriate exceptions if we aren't (or if the I/O bitmap is not
194 * accessible).
195 *
196 * @returns Strict VBox status code.
197 *
198 * @param pVCpu The cross context virtual CPU structure of the calling thread.
199 * @param u16Port The port number.
200 * @param cbOperand The operand size.
201 */
202DECLINLINE(VBOXSTRICTRC) iemHlpCheckPortIOPermission(PVMCPUCC pVCpu, uint16_t u16Port, uint8_t cbOperand)
203{
204 X86EFLAGS Efl;
205 Efl.u = IEMMISC_GET_EFL(pVCpu);
206 if ( (pVCpu->cpum.GstCtx.cr0 & X86_CR0_PE)
207 && ( IEM_GET_CPL(pVCpu) > Efl.Bits.u2IOPL
208 || Efl.Bits.u1VM) )
209 return iemHlpCheckPortIOPermissionBitmap(pVCpu, u16Port, cbOperand);
210 return VINF_SUCCESS;
211}
212
213
214#if 0
215/**
216 * Calculates the parity bit.
217 *
218 * @returns true if the bit is set, false if not.
219 * @param u8Result The least significant byte of the result.
220 */
221static bool iemHlpCalcParityFlag(uint8_t u8Result)
222{
223 /*
224 * Parity is set if the number of bits in the least significant byte of
225 * the result is even.
226 */
227 uint8_t cBits;
228 cBits = u8Result & 1; /* 0 */
229 u8Result >>= 1;
230 cBits += u8Result & 1;
231 u8Result >>= 1;
232 cBits += u8Result & 1;
233 u8Result >>= 1;
234 cBits += u8Result & 1;
235 u8Result >>= 1;
236 cBits += u8Result & 1; /* 4 */
237 u8Result >>= 1;
238 cBits += u8Result & 1;
239 u8Result >>= 1;
240 cBits += u8Result & 1;
241 u8Result >>= 1;
242 cBits += u8Result & 1;
243 return !(cBits & 1);
244}
245#endif /* not used */
246
247
248/**
249 * Updates the specified flags according to a 8-bit result.
250 *
251 * @param pVCpu The cross context virtual CPU structure of the calling thread.
252 * @param u8Result The result to set the flags according to.
253 * @param fToUpdate The flags to update.
254 * @param fUndefined The flags that are specified as undefined.
255 */
256static void iemHlpUpdateArithEFlagsU8(PVMCPUCC pVCpu, uint8_t u8Result, uint32_t fToUpdate, uint32_t fUndefined)
257{
258 uint32_t fEFlags = iemAImpl_test_u8(pVCpu->cpum.GstCtx.eflags.u, &u8Result, u8Result);
259 pVCpu->cpum.GstCtx.eflags.u &= ~(fToUpdate | fUndefined);
260 pVCpu->cpum.GstCtx.eflags.u |= (fToUpdate | fUndefined) & fEFlags;
261}
262
263
264/**
265 * Updates the specified flags according to a 16-bit result.
266 *
267 * @param pVCpu The cross context virtual CPU structure of the calling thread.
268 * @param u16Result The result to set the flags according to.
269 * @param fToUpdate The flags to update.
270 * @param fUndefined The flags that are specified as undefined.
271 */
272static void iemHlpUpdateArithEFlagsU16(PVMCPUCC pVCpu, uint16_t u16Result, uint32_t fToUpdate, uint32_t fUndefined)
273{
274 uint32_t fEFlags = iemAImpl_test_u16(pVCpu->cpum.GstCtx.eflags.u, &u16Result, u16Result);
275 pVCpu->cpum.GstCtx.eflags.u &= ~(fToUpdate | fUndefined);
276 pVCpu->cpum.GstCtx.eflags.u |= (fToUpdate | fUndefined) & fEFlags;
277}
278
279
280/**
281 * Helper used by iret.
282 *
283 * @param pVCpu The cross context virtual CPU structure of the calling thread.
284 * @param uCpl The new CPL.
285 * @param pSReg Pointer to the segment register.
286 */
287static void iemHlpAdjustSelectorForNewCpl(PVMCPUCC pVCpu, uint8_t uCpl, PCPUMSELREG pSReg)
288{
289 Assert(CPUMSELREG_ARE_HIDDEN_PARTS_VALID(pVCpu, pSReg));
290 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_SREG_MASK);
291
292 if ( uCpl > pSReg->Attr.n.u2Dpl
293 && pSReg->Attr.n.u1DescType /* code or data, not system */
294 && (pSReg->Attr.n.u4Type & (X86_SEL_TYPE_CODE | X86_SEL_TYPE_CONF))
295 != (X86_SEL_TYPE_CODE | X86_SEL_TYPE_CONF)) /* not conforming code */
296 iemHlpLoadNullDataSelectorProt(pVCpu, pSReg, 0);
297}
298
299
300/**
301 * Indicates that we have modified the FPU state.
302 *
303 * @param pVCpu The cross context virtual CPU structure of the calling thread.
304 */
305DECLINLINE(void) iemHlpUsedFpu(PVMCPUCC pVCpu)
306{
307 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_FPU_REM);
308}
309
310/** @} */
311
312/** @name C Implementations
313 * @{
314 */
315
316
317/**
318 * Implements a pop [mem16].
319 */
320IEM_CIMPL_DEF_2(iemCImpl_pop_mem16, uint16_t, iEffSeg, RTGCPTR, GCPtrEffDst)
321{
322 uint16_t u16Value;
323 RTUINT64U TmpRsp;
324 TmpRsp.u = pVCpu->cpum.GstCtx.rsp;
325 VBOXSTRICTRC rcStrict = iemMemStackPopU16Ex(pVCpu, &u16Value, &TmpRsp);
326 if (rcStrict == VINF_SUCCESS)
327 {
328 rcStrict = iemMemStoreDataU16(pVCpu, iEffSeg, GCPtrEffDst, u16Value);
329 if (rcStrict == VINF_SUCCESS)
330 {
331 pVCpu->cpum.GstCtx.rsp = TmpRsp.u;
332 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
333 }
334 }
335 return rcStrict;
336
337}
338
339
340/**
341 * Implements a pop [mem32].
342 */
343IEM_CIMPL_DEF_2(iemCImpl_pop_mem32, uint16_t, iEffSeg, RTGCPTR, GCPtrEffDst)
344{
345 uint32_t u32Value;
346 RTUINT64U TmpRsp;
347 TmpRsp.u = pVCpu->cpum.GstCtx.rsp;
348 VBOXSTRICTRC rcStrict = iemMemStackPopU32Ex(pVCpu, &u32Value, &TmpRsp);
349 if (rcStrict == VINF_SUCCESS)
350 {
351 rcStrict = iemMemStoreDataU32(pVCpu, iEffSeg, GCPtrEffDst, u32Value);
352 if (rcStrict == VINF_SUCCESS)
353 {
354 pVCpu->cpum.GstCtx.rsp = TmpRsp.u;
355 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
356 }
357 }
358 return rcStrict;
359
360}
361
362
363/**
364 * Implements a pop [mem64].
365 */
366IEM_CIMPL_DEF_2(iemCImpl_pop_mem64, uint16_t, iEffSeg, RTGCPTR, GCPtrEffDst)
367{
368 uint64_t u64Value;
369 RTUINT64U TmpRsp;
370 TmpRsp.u = pVCpu->cpum.GstCtx.rsp;
371 VBOXSTRICTRC rcStrict = iemMemStackPopU64Ex(pVCpu, &u64Value, &TmpRsp);
372 if (rcStrict == VINF_SUCCESS)
373 {
374 rcStrict = iemMemStoreDataU64(pVCpu, iEffSeg, GCPtrEffDst, u64Value);
375 if (rcStrict == VINF_SUCCESS)
376 {
377 pVCpu->cpum.GstCtx.rsp = TmpRsp.u;
378 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
379 }
380 }
381 return rcStrict;
382
383}
384
385
386/**
387 * Implements a 16-bit popa.
388 */
389IEM_CIMPL_DEF_0(iemCImpl_popa_16)
390{
391 RTGCPTR GCPtrStart = iemRegGetEffRsp(pVCpu);
392 RTGCPTR GCPtrLast = GCPtrStart + 15;
393 VBOXSTRICTRC rcStrict;
394
395 /*
396 * The docs are a bit hard to comprehend here, but it looks like we wrap
397 * around in real mode as long as none of the individual "popa" crosses the
398 * end of the stack segment. In protected mode we check the whole access
399 * in one go. For efficiency, only do the word-by-word thing if we're in
400 * danger of wrapping around.
401 */
402 /** @todo do popa boundary / wrap-around checks. */
403 if (RT_UNLIKELY( IEM_IS_REAL_OR_V86_MODE(pVCpu)
404 && (pVCpu->cpum.GstCtx.cs.u32Limit < GCPtrLast)) ) /* ASSUMES 64-bit RTGCPTR */
405 {
406 /* word-by-word */
407 RTUINT64U TmpRsp;
408 TmpRsp.u = pVCpu->cpum.GstCtx.rsp;
409 rcStrict = iemMemStackPopU16Ex(pVCpu, &pVCpu->cpum.GstCtx.di, &TmpRsp);
410 if (rcStrict == VINF_SUCCESS)
411 rcStrict = iemMemStackPopU16Ex(pVCpu, &pVCpu->cpum.GstCtx.si, &TmpRsp);
412 if (rcStrict == VINF_SUCCESS)
413 rcStrict = iemMemStackPopU16Ex(pVCpu, &pVCpu->cpum.GstCtx.bp, &TmpRsp);
414 if (rcStrict == VINF_SUCCESS)
415 {
416 iemRegAddToRspEx(pVCpu, &TmpRsp, 2); /* sp */
417 rcStrict = iemMemStackPopU16Ex(pVCpu, &pVCpu->cpum.GstCtx.bx, &TmpRsp);
418 }
419 if (rcStrict == VINF_SUCCESS)
420 rcStrict = iemMemStackPopU16Ex(pVCpu, &pVCpu->cpum.GstCtx.dx, &TmpRsp);
421 if (rcStrict == VINF_SUCCESS)
422 rcStrict = iemMemStackPopU16Ex(pVCpu, &pVCpu->cpum.GstCtx.cx, &TmpRsp);
423 if (rcStrict == VINF_SUCCESS)
424 rcStrict = iemMemStackPopU16Ex(pVCpu, &pVCpu->cpum.GstCtx.ax, &TmpRsp);
425 if (rcStrict == VINF_SUCCESS)
426 {
427 pVCpu->cpum.GstCtx.rsp = TmpRsp.u;
428 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
429 }
430 }
431 else
432 {
433 uint8_t bUnmapInfo;
434 uint16_t const *pau16Mem = NULL;
435 rcStrict = iemMemMap(pVCpu, (void **)&pau16Mem, &bUnmapInfo, 16, X86_SREG_SS, GCPtrStart,
436 IEM_ACCESS_STACK_R, sizeof(*pau16Mem) - 1);
437 if (rcStrict == VINF_SUCCESS)
438 {
439 pVCpu->cpum.GstCtx.di = pau16Mem[7 - X86_GREG_xDI];
440 pVCpu->cpum.GstCtx.si = pau16Mem[7 - X86_GREG_xSI];
441 pVCpu->cpum.GstCtx.bp = pau16Mem[7 - X86_GREG_xBP];
442 /* skip sp */
443 pVCpu->cpum.GstCtx.bx = pau16Mem[7 - X86_GREG_xBX];
444 pVCpu->cpum.GstCtx.dx = pau16Mem[7 - X86_GREG_xDX];
445 pVCpu->cpum.GstCtx.cx = pau16Mem[7 - X86_GREG_xCX];
446 pVCpu->cpum.GstCtx.ax = pau16Mem[7 - X86_GREG_xAX];
447 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
448 if (rcStrict == VINF_SUCCESS)
449 {
450 iemRegAddToRsp(pVCpu, 16);
451 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
452 }
453 }
454 }
455 return rcStrict;
456}
457
458
459/**
460 * Implements a 32-bit popa.
461 */
462IEM_CIMPL_DEF_0(iemCImpl_popa_32)
463{
464 RTGCPTR GCPtrStart = iemRegGetEffRsp(pVCpu);
465 RTGCPTR GCPtrLast = GCPtrStart + 31;
466 VBOXSTRICTRC rcStrict;
467
468 /*
469 * The docs are a bit hard to comprehend here, but it looks like we wrap
470 * around in real mode as long as none of the individual "popa" crosses the
471 * end of the stack segment. In protected mode we check the whole access
472 * in one go. For efficiency, only do the word-by-word thing if we're in
473 * danger of wrapping around.
474 */
475 /** @todo do popa boundary / wrap-around checks. */
476 if (RT_UNLIKELY( IEM_IS_REAL_OR_V86_MODE(pVCpu)
477 && (pVCpu->cpum.GstCtx.cs.u32Limit < GCPtrLast)) ) /* ASSUMES 64-bit RTGCPTR */
478 {
479 /* word-by-word */
480 RTUINT64U TmpRsp;
481 TmpRsp.u = pVCpu->cpum.GstCtx.rsp;
482 rcStrict = iemMemStackPopU32Ex(pVCpu, &pVCpu->cpum.GstCtx.edi, &TmpRsp);
483 if (rcStrict == VINF_SUCCESS)
484 rcStrict = iemMemStackPopU32Ex(pVCpu, &pVCpu->cpum.GstCtx.esi, &TmpRsp);
485 if (rcStrict == VINF_SUCCESS)
486 rcStrict = iemMemStackPopU32Ex(pVCpu, &pVCpu->cpum.GstCtx.ebp, &TmpRsp);
487 if (rcStrict == VINF_SUCCESS)
488 {
489 iemRegAddToRspEx(pVCpu, &TmpRsp, 2); /* sp */
490 rcStrict = iemMemStackPopU32Ex(pVCpu, &pVCpu->cpum.GstCtx.ebx, &TmpRsp);
491 }
492 if (rcStrict == VINF_SUCCESS)
493 rcStrict = iemMemStackPopU32Ex(pVCpu, &pVCpu->cpum.GstCtx.edx, &TmpRsp);
494 if (rcStrict == VINF_SUCCESS)
495 rcStrict = iemMemStackPopU32Ex(pVCpu, &pVCpu->cpum.GstCtx.ecx, &TmpRsp);
496 if (rcStrict == VINF_SUCCESS)
497 rcStrict = iemMemStackPopU32Ex(pVCpu, &pVCpu->cpum.GstCtx.eax, &TmpRsp);
498 if (rcStrict == VINF_SUCCESS)
499 {
500#if 1 /** @todo what actually happens with the high bits when we're in 16-bit mode? */
501 pVCpu->cpum.GstCtx.rdi &= UINT32_MAX;
502 pVCpu->cpum.GstCtx.rsi &= UINT32_MAX;
503 pVCpu->cpum.GstCtx.rbp &= UINT32_MAX;
504 pVCpu->cpum.GstCtx.rbx &= UINT32_MAX;
505 pVCpu->cpum.GstCtx.rdx &= UINT32_MAX;
506 pVCpu->cpum.GstCtx.rcx &= UINT32_MAX;
507 pVCpu->cpum.GstCtx.rax &= UINT32_MAX;
508#endif
509 pVCpu->cpum.GstCtx.rsp = TmpRsp.u;
510 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
511 }
512 }
513 else
514 {
515 uint8_t bUnmapInfo;
516 uint32_t const *pau32Mem;
517 rcStrict = iemMemMap(pVCpu, (void **)&pau32Mem, &bUnmapInfo, 32, X86_SREG_SS, GCPtrStart,
518 IEM_ACCESS_STACK_R, sizeof(*pau32Mem) - 1);
519 if (rcStrict == VINF_SUCCESS)
520 {
521 pVCpu->cpum.GstCtx.rdi = pau32Mem[7 - X86_GREG_xDI];
522 pVCpu->cpum.GstCtx.rsi = pau32Mem[7 - X86_GREG_xSI];
523 pVCpu->cpum.GstCtx.rbp = pau32Mem[7 - X86_GREG_xBP];
524 /* skip esp */
525 pVCpu->cpum.GstCtx.rbx = pau32Mem[7 - X86_GREG_xBX];
526 pVCpu->cpum.GstCtx.rdx = pau32Mem[7 - X86_GREG_xDX];
527 pVCpu->cpum.GstCtx.rcx = pau32Mem[7 - X86_GREG_xCX];
528 pVCpu->cpum.GstCtx.rax = pau32Mem[7 - X86_GREG_xAX];
529 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
530 if (rcStrict == VINF_SUCCESS)
531 {
532 iemRegAddToRsp(pVCpu, 32);
533 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
534 }
535 }
536 }
537 return rcStrict;
538}
539
540
541/**
542 * Implements a 16-bit pusha.
543 */
544IEM_CIMPL_DEF_0(iemCImpl_pusha_16)
545{
546 RTGCPTR GCPtrTop = iemRegGetEffRsp(pVCpu);
547 RTGCPTR GCPtrBottom = GCPtrTop - 15;
548 VBOXSTRICTRC rcStrict;
549
550 /*
551 * The docs are a bit hard to comprehend here, but it looks like we wrap
552 * around in real mode as long as none of the individual "pushd" crosses the
553 * end of the stack segment. In protected mode we check the whole access
554 * in one go. For efficiency, only do the word-by-word thing if we're in
555 * danger of wrapping around.
556 */
557 /** @todo do pusha boundary / wrap-around checks. */
558 if (RT_UNLIKELY( GCPtrBottom > GCPtrTop
559 && IEM_IS_REAL_OR_V86_MODE(pVCpu) ) )
560 {
561 /* word-by-word */
562 RTUINT64U TmpRsp;
563 TmpRsp.u = pVCpu->cpum.GstCtx.rsp;
564 rcStrict = iemMemStackPushU16Ex(pVCpu, pVCpu->cpum.GstCtx.ax, &TmpRsp);
565 if (rcStrict == VINF_SUCCESS)
566 rcStrict = iemMemStackPushU16Ex(pVCpu, pVCpu->cpum.GstCtx.cx, &TmpRsp);
567 if (rcStrict == VINF_SUCCESS)
568 rcStrict = iemMemStackPushU16Ex(pVCpu, pVCpu->cpum.GstCtx.dx, &TmpRsp);
569 if (rcStrict == VINF_SUCCESS)
570 rcStrict = iemMemStackPushU16Ex(pVCpu, pVCpu->cpum.GstCtx.bx, &TmpRsp);
571 if (rcStrict == VINF_SUCCESS)
572 rcStrict = iemMemStackPushU16Ex(pVCpu, pVCpu->cpum.GstCtx.sp, &TmpRsp);
573 if (rcStrict == VINF_SUCCESS)
574 rcStrict = iemMemStackPushU16Ex(pVCpu, pVCpu->cpum.GstCtx.bp, &TmpRsp);
575 if (rcStrict == VINF_SUCCESS)
576 rcStrict = iemMemStackPushU16Ex(pVCpu, pVCpu->cpum.GstCtx.si, &TmpRsp);
577 if (rcStrict == VINF_SUCCESS)
578 rcStrict = iemMemStackPushU16Ex(pVCpu, pVCpu->cpum.GstCtx.di, &TmpRsp);
579 if (rcStrict == VINF_SUCCESS)
580 {
581 pVCpu->cpum.GstCtx.rsp = TmpRsp.u;
582 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
583 }
584 }
585 else
586 {
587 GCPtrBottom--;
588 uint8_t bUnmapInfo;
589 uint16_t *pau16Mem = NULL;
590 rcStrict = iemMemMap(pVCpu, (void **)&pau16Mem, &bUnmapInfo, 16, X86_SREG_SS, GCPtrBottom,
591 IEM_ACCESS_STACK_W, sizeof(*pau16Mem) - 1);
592 if (rcStrict == VINF_SUCCESS)
593 {
594 pau16Mem[7 - X86_GREG_xDI] = pVCpu->cpum.GstCtx.di;
595 pau16Mem[7 - X86_GREG_xSI] = pVCpu->cpum.GstCtx.si;
596 pau16Mem[7 - X86_GREG_xBP] = pVCpu->cpum.GstCtx.bp;
597 pau16Mem[7 - X86_GREG_xSP] = pVCpu->cpum.GstCtx.sp;
598 pau16Mem[7 - X86_GREG_xBX] = pVCpu->cpum.GstCtx.bx;
599 pau16Mem[7 - X86_GREG_xDX] = pVCpu->cpum.GstCtx.dx;
600 pau16Mem[7 - X86_GREG_xCX] = pVCpu->cpum.GstCtx.cx;
601 pau16Mem[7 - X86_GREG_xAX] = pVCpu->cpum.GstCtx.ax;
602 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
603 if (rcStrict == VINF_SUCCESS)
604 {
605 iemRegSubFromRsp(pVCpu, 16);
606 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
607 }
608 }
609 }
610 return rcStrict;
611}
612
613
614/**
615 * Implements a 32-bit pusha.
616 */
617IEM_CIMPL_DEF_0(iemCImpl_pusha_32)
618{
619 RTGCPTR GCPtrTop = iemRegGetEffRsp(pVCpu);
620 RTGCPTR GCPtrBottom = GCPtrTop - 31;
621 VBOXSTRICTRC rcStrict;
622
623 /*
624 * The docs are a bit hard to comprehend here, but it looks like we wrap
625 * around in real mode as long as none of the individual "pusha" crosses the
626 * end of the stack segment. In protected mode we check the whole access
627 * in one go. For efficiency, only do the word-by-word thing if we're in
628 * danger of wrapping around.
629 */
630 /** @todo do pusha boundary / wrap-around checks. */
631 if (RT_UNLIKELY( GCPtrBottom > GCPtrTop
632 && IEM_IS_REAL_OR_V86_MODE(pVCpu) ) )
633 {
634 /* word-by-word */
635 RTUINT64U TmpRsp;
636 TmpRsp.u = pVCpu->cpum.GstCtx.rsp;
637 rcStrict = iemMemStackPushU32Ex(pVCpu, pVCpu->cpum.GstCtx.eax, &TmpRsp);
638 if (rcStrict == VINF_SUCCESS)
639 rcStrict = iemMemStackPushU32Ex(pVCpu, pVCpu->cpum.GstCtx.ecx, &TmpRsp);
640 if (rcStrict == VINF_SUCCESS)
641 rcStrict = iemMemStackPushU32Ex(pVCpu, pVCpu->cpum.GstCtx.edx, &TmpRsp);
642 if (rcStrict == VINF_SUCCESS)
643 rcStrict = iemMemStackPushU32Ex(pVCpu, pVCpu->cpum.GstCtx.ebx, &TmpRsp);
644 if (rcStrict == VINF_SUCCESS)
645 rcStrict = iemMemStackPushU32Ex(pVCpu, pVCpu->cpum.GstCtx.esp, &TmpRsp);
646 if (rcStrict == VINF_SUCCESS)
647 rcStrict = iemMemStackPushU32Ex(pVCpu, pVCpu->cpum.GstCtx.ebp, &TmpRsp);
648 if (rcStrict == VINF_SUCCESS)
649 rcStrict = iemMemStackPushU32Ex(pVCpu, pVCpu->cpum.GstCtx.esi, &TmpRsp);
650 if (rcStrict == VINF_SUCCESS)
651 rcStrict = iemMemStackPushU32Ex(pVCpu, pVCpu->cpum.GstCtx.edi, &TmpRsp);
652 if (rcStrict == VINF_SUCCESS)
653 {
654 pVCpu->cpum.GstCtx.rsp = TmpRsp.u;
655 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
656 }
657 }
658 else
659 {
660 GCPtrBottom--;
661 uint8_t bUnmapInfo;
662 uint32_t *pau32Mem;
663 rcStrict = iemMemMap(pVCpu, (void **)&pau32Mem, &bUnmapInfo, 32, X86_SREG_SS, GCPtrBottom,
664 IEM_ACCESS_STACK_W, sizeof(*pau32Mem) - 1);
665 if (rcStrict == VINF_SUCCESS)
666 {
667 pau32Mem[7 - X86_GREG_xDI] = pVCpu->cpum.GstCtx.edi;
668 pau32Mem[7 - X86_GREG_xSI] = pVCpu->cpum.GstCtx.esi;
669 pau32Mem[7 - X86_GREG_xBP] = pVCpu->cpum.GstCtx.ebp;
670 pau32Mem[7 - X86_GREG_xSP] = pVCpu->cpum.GstCtx.esp;
671 pau32Mem[7 - X86_GREG_xBX] = pVCpu->cpum.GstCtx.ebx;
672 pau32Mem[7 - X86_GREG_xDX] = pVCpu->cpum.GstCtx.edx;
673 pau32Mem[7 - X86_GREG_xCX] = pVCpu->cpum.GstCtx.ecx;
674 pau32Mem[7 - X86_GREG_xAX] = pVCpu->cpum.GstCtx.eax;
675 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
676 if (rcStrict == VINF_SUCCESS)
677 {
678 iemRegSubFromRsp(pVCpu, 32);
679 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
680 }
681 }
682 }
683 return rcStrict;
684}
685
686
687/**
688 * Implements pushf.
689 *
690 *
691 * @param enmEffOpSize The effective operand size.
692 */
693IEM_CIMPL_DEF_1(iemCImpl_pushf, IEMMODE, enmEffOpSize)
694{
695 VBOXSTRICTRC rcStrict;
696
697 if (!IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_PUSHF))
698 { /* probable */ }
699 else
700 {
701 Log2(("pushf: Guest intercept -> #VMEXIT\n"));
702 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
703 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_PUSHF, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
704 }
705
706 /*
707 * If we're in V8086 mode some care is required (which is why we're in
708 * doing this in a C implementation).
709 */
710 uint32_t fEfl = IEMMISC_GET_EFL(pVCpu);
711 if ( (fEfl & X86_EFL_VM)
712 && X86_EFL_GET_IOPL(fEfl) != 3 )
713 {
714 Assert(pVCpu->cpum.GstCtx.cr0 & X86_CR0_PE);
715 if ( enmEffOpSize != IEMMODE_16BIT
716 || !(pVCpu->cpum.GstCtx.cr4 & X86_CR4_VME))
717 return iemRaiseGeneralProtectionFault0(pVCpu);
718 fEfl &= ~X86_EFL_IF; /* (RF and VM are out of range) */
719 fEfl |= (fEfl & X86_EFL_VIF) >> (19 - 9);
720 rcStrict = iemMemStackPushU16(pVCpu, (uint16_t)fEfl);
721 }
722 else
723 {
724
725 /*
726 * Ok, clear RF and VM, adjust for ancient CPUs, and push the flags.
727 */
728 fEfl &= ~(X86_EFL_RF | X86_EFL_VM);
729
730 switch (enmEffOpSize)
731 {
732 case IEMMODE_16BIT:
733 AssertCompile(IEMTARGETCPU_8086 <= IEMTARGETCPU_186 && IEMTARGETCPU_V20 <= IEMTARGETCPU_186 && IEMTARGETCPU_286 > IEMTARGETCPU_186);
734 if (IEM_GET_TARGET_CPU(pVCpu) <= IEMTARGETCPU_186)
735 fEfl |= UINT16_C(0xf000);
736 rcStrict = iemMemStackPushU16(pVCpu, (uint16_t)fEfl);
737 break;
738 case IEMMODE_32BIT:
739 rcStrict = iemMemStackPushU32(pVCpu, fEfl);
740 break;
741 case IEMMODE_64BIT:
742 rcStrict = iemMemStackPushU64(pVCpu, fEfl);
743 break;
744 IEM_NOT_REACHED_DEFAULT_CASE_RET();
745 }
746 }
747
748 if (rcStrict == VINF_SUCCESS)
749 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
750 return rcStrict;
751}
752
753
754/**
755 * Implements popf.
756 *
757 * @param enmEffOpSize The effective operand size.
758 */
759IEM_CIMPL_DEF_1(iemCImpl_popf, IEMMODE, enmEffOpSize)
760{
761 uint32_t const fEflOld = IEMMISC_GET_EFL(pVCpu);
762 VBOXSTRICTRC rcStrict;
763 uint32_t fEflNew;
764
765 if (!IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_POPF))
766 { /* probable */ }
767 else
768 {
769 Log2(("popf: Guest intercept -> #VMEXIT\n"));
770 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
771 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_POPF, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
772 }
773
774 /*
775 * V8086 is special as usual.
776 */
777 if (fEflOld & X86_EFL_VM)
778 {
779 /*
780 * Almost anything goes if IOPL is 3.
781 */
782 if (X86_EFL_GET_IOPL(fEflOld) == 3)
783 {
784 switch (enmEffOpSize)
785 {
786 case IEMMODE_16BIT:
787 {
788 uint16_t u16Value;
789 rcStrict = iemMemStackPopU16(pVCpu, &u16Value);
790 if (rcStrict != VINF_SUCCESS)
791 return rcStrict;
792 fEflNew = u16Value | (fEflOld & UINT32_C(0xffff0000));
793 break;
794 }
795 case IEMMODE_32BIT:
796 rcStrict = iemMemStackPopU32(pVCpu, &fEflNew);
797 if (rcStrict != VINF_SUCCESS)
798 return rcStrict;
799 break;
800 IEM_NOT_REACHED_DEFAULT_CASE_RET();
801 }
802
803 const uint32_t fPopfBits = pVCpu->CTX_SUFF(pVM)->cpum.ro.GuestFeatures.enmMicroarch != kCpumMicroarch_Intel_80386
804 ? X86_EFL_POPF_BITS : X86_EFL_POPF_BITS_386;
805 fEflNew &= fPopfBits & ~(X86_EFL_IOPL);
806 fEflNew |= ~(fPopfBits & ~(X86_EFL_IOPL)) & fEflOld;
807 }
808 /*
809 * Interrupt flag virtualization with CR4.VME=1.
810 */
811 else if ( enmEffOpSize == IEMMODE_16BIT
812 && (pVCpu->cpum.GstCtx.cr4 & X86_CR4_VME) )
813 {
814 uint16_t u16Value;
815 RTUINT64U TmpRsp;
816 TmpRsp.u = pVCpu->cpum.GstCtx.rsp;
817 rcStrict = iemMemStackPopU16Ex(pVCpu, &u16Value, &TmpRsp);
818 if (rcStrict != VINF_SUCCESS)
819 return rcStrict;
820
821 /** @todo Is the popf VME \#GP(0) delivered after updating RSP+RIP
822 * or before? */
823 if ( ( (u16Value & X86_EFL_IF)
824 && (fEflOld & X86_EFL_VIP))
825 || (u16Value & X86_EFL_TF) )
826 return iemRaiseGeneralProtectionFault0(pVCpu);
827
828 fEflNew = u16Value | (fEflOld & UINT32_C(0xffff0000) & ~X86_EFL_VIF);
829 fEflNew |= (fEflNew & X86_EFL_IF) << (19 - 9);
830 fEflNew &= X86_EFL_POPF_BITS & ~(X86_EFL_IOPL | X86_EFL_IF);
831 fEflNew |= ~(X86_EFL_POPF_BITS & ~(X86_EFL_IOPL | X86_EFL_IF)) & fEflOld;
832
833 pVCpu->cpum.GstCtx.rsp = TmpRsp.u;
834 }
835 else
836 return iemRaiseGeneralProtectionFault0(pVCpu);
837
838 }
839 /*
840 * Not in V8086 mode.
841 */
842 else
843 {
844 /* Pop the flags. */
845 switch (enmEffOpSize)
846 {
847 case IEMMODE_16BIT:
848 {
849 uint16_t u16Value;
850 rcStrict = iemMemStackPopU16(pVCpu, &u16Value);
851 if (rcStrict != VINF_SUCCESS)
852 return rcStrict;
853 fEflNew = u16Value | (fEflOld & UINT32_C(0xffff0000));
854
855 /*
856 * Ancient CPU adjustments:
857 * - 8086, 80186, V20/30:
858 * Fixed bits 15:12 bits are not kept correctly internally, mostly for
859 * practical reasons (masking below). We add them when pushing flags.
860 * - 80286:
861 * The NT and IOPL flags cannot be popped from real mode and are
862 * therefore always zero (since a 286 can never exit from PM and
863 * their initial value is zero). This changed on a 386 and can
864 * therefore be used to detect 286 or 386 CPU in real mode.
865 */
866 if ( IEM_GET_TARGET_CPU(pVCpu) == IEMTARGETCPU_286
867 && !(pVCpu->cpum.GstCtx.cr0 & X86_CR0_PE) )
868 fEflNew &= ~(X86_EFL_NT | X86_EFL_IOPL);
869 break;
870 }
871 case IEMMODE_32BIT:
872 rcStrict = iemMemStackPopU32(pVCpu, &fEflNew);
873 if (rcStrict != VINF_SUCCESS)
874 return rcStrict;
875 break;
876 case IEMMODE_64BIT:
877 {
878 uint64_t u64Value;
879 rcStrict = iemMemStackPopU64(pVCpu, &u64Value);
880 if (rcStrict != VINF_SUCCESS)
881 return rcStrict;
882 fEflNew = u64Value; /** @todo testcase: Check exactly what happens if high bits are set. */
883 break;
884 }
885 IEM_NOT_REACHED_DEFAULT_CASE_RET();
886 }
887
888 /* Merge them with the current flags. */
889 const uint32_t fPopfBits = pVCpu->CTX_SUFF(pVM)->cpum.ro.GuestFeatures.enmMicroarch != kCpumMicroarch_Intel_80386
890 ? X86_EFL_POPF_BITS : X86_EFL_POPF_BITS_386;
891 if ( (fEflNew & (X86_EFL_IOPL | X86_EFL_IF)) == (fEflOld & (X86_EFL_IOPL | X86_EFL_IF))
892 || IEM_GET_CPL(pVCpu) == 0)
893 {
894 fEflNew &= fPopfBits;
895 fEflNew |= ~fPopfBits & fEflOld;
896 }
897 else if (IEM_GET_CPL(pVCpu) <= X86_EFL_GET_IOPL(fEflOld))
898 {
899 fEflNew &= fPopfBits & ~(X86_EFL_IOPL);
900 fEflNew |= ~(fPopfBits & ~(X86_EFL_IOPL)) & fEflOld;
901 }
902 else
903 {
904 fEflNew &= fPopfBits & ~(X86_EFL_IOPL | X86_EFL_IF);
905 fEflNew |= ~(fPopfBits & ~(X86_EFL_IOPL | X86_EFL_IF)) & fEflOld;
906 }
907 }
908
909 /*
910 * Commit the flags.
911 */
912 Assert(fEflNew & RT_BIT_32(1));
913 IEMMISC_SET_EFL(pVCpu, fEflNew);
914 return iemRegAddToRipAndFinishingClearingRfEx(pVCpu, cbInstr, fEflOld);
915}
916
917
918/**
919 * Implements far jumps and calls thru task segments (TSS).
920 *
921 * @returns VBox strict status code.
922 * @param pVCpu The cross context virtual CPU structure of the
923 * calling thread.
924 * @param cbInstr The current instruction length.
925 * @param uSel The selector.
926 * @param enmBranch The kind of branching we're performing.
927 * @param enmEffOpSize The effective operand size.
928 * @param pDesc The descriptor corresponding to @a uSel. The type is
929 * task gate.
930 */
931static VBOXSTRICTRC iemCImpl_BranchTaskSegment(PVMCPUCC pVCpu, uint8_t cbInstr, uint16_t uSel, IEMBRANCH enmBranch,
932 IEMMODE enmEffOpSize, PIEMSELDESC pDesc)
933{
934#ifndef IEM_IMPLEMENTS_TASKSWITCH
935 IEM_RETURN_ASPECT_NOT_IMPLEMENTED();
936#else
937 Assert(enmBranch == IEMBRANCH_JUMP || enmBranch == IEMBRANCH_CALL);
938 Assert( pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_286_TSS_AVAIL
939 || pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_386_TSS_AVAIL);
940 RT_NOREF_PV(enmEffOpSize);
941 IEM_CTX_ASSERT(pVCpu, IEM_CPUMCTX_EXTRN_XCPT_MASK);
942
943 if ( pDesc->Legacy.Gate.u2Dpl < IEM_GET_CPL(pVCpu)
944 || pDesc->Legacy.Gate.u2Dpl < (uSel & X86_SEL_RPL))
945 {
946 Log(("BranchTaskSegment invalid priv. uSel=%04x TSS DPL=%d CPL=%u Sel RPL=%u -> #GP\n", uSel, pDesc->Legacy.Gate.u2Dpl,
947 IEM_GET_CPL(pVCpu), (uSel & X86_SEL_RPL)));
948 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel & X86_SEL_MASK_OFF_RPL);
949 }
950
951 /** @todo This is checked earlier for far jumps (see iemCImpl_FarJmp) but not
952 * far calls (see iemCImpl_callf). Most likely in both cases it should be
953 * checked here, need testcases. */
954 if (!pDesc->Legacy.Gen.u1Present)
955 {
956 Log(("BranchTaskSegment TSS not present uSel=%04x -> #NP\n", uSel));
957 return iemRaiseSelectorNotPresentBySelector(pVCpu, uSel & X86_SEL_MASK_OFF_RPL);
958 }
959
960 uint32_t uNextEip = pVCpu->cpum.GstCtx.eip + cbInstr;
961 return iemTaskSwitch(pVCpu, enmBranch == IEMBRANCH_JUMP ? IEMTASKSWITCH_JUMP : IEMTASKSWITCH_CALL,
962 uNextEip, 0 /* fFlags */, 0 /* uErr */, 0 /* uCr2 */, uSel, pDesc);
963#endif
964}
965
966
967/**
968 * Implements far jumps and calls thru task gates.
969 *
970 * @returns VBox strict status code.
971 * @param pVCpu The cross context virtual CPU structure of the
972 * calling thread.
973 * @param cbInstr The current instruction length.
974 * @param uSel The selector.
975 * @param enmBranch The kind of branching we're performing.
976 * @param enmEffOpSize The effective operand size.
977 * @param pDesc The descriptor corresponding to @a uSel. The type is
978 * task gate.
979 */
980static VBOXSTRICTRC iemCImpl_BranchTaskGate(PVMCPUCC pVCpu, uint8_t cbInstr, uint16_t uSel, IEMBRANCH enmBranch,
981 IEMMODE enmEffOpSize, PIEMSELDESC pDesc)
982{
983#ifndef IEM_IMPLEMENTS_TASKSWITCH
984 IEM_RETURN_ASPECT_NOT_IMPLEMENTED();
985#else
986 Assert(enmBranch == IEMBRANCH_JUMP || enmBranch == IEMBRANCH_CALL);
987 RT_NOREF_PV(enmEffOpSize);
988 IEM_CTX_ASSERT(pVCpu, IEM_CPUMCTX_EXTRN_XCPT_MASK);
989
990 if ( pDesc->Legacy.Gate.u2Dpl < IEM_GET_CPL(pVCpu)
991 || pDesc->Legacy.Gate.u2Dpl < (uSel & X86_SEL_RPL))
992 {
993 Log(("BranchTaskGate invalid priv. uSel=%04x TSS DPL=%d CPL=%u Sel RPL=%u -> #GP\n", uSel, pDesc->Legacy.Gate.u2Dpl,
994 IEM_GET_CPL(pVCpu), (uSel & X86_SEL_RPL)));
995 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel & X86_SEL_MASK_OFF_RPL);
996 }
997
998 /** @todo This is checked earlier for far jumps (see iemCImpl_FarJmp) but not
999 * far calls (see iemCImpl_callf). Most likely in both cases it should be
1000 * checked here, need testcases. */
1001 if (!pDesc->Legacy.Gen.u1Present)
1002 {
1003 Log(("BranchTaskSegment segment not present uSel=%04x -> #NP\n", uSel));
1004 return iemRaiseSelectorNotPresentBySelector(pVCpu, uSel & X86_SEL_MASK_OFF_RPL);
1005 }
1006
1007 /*
1008 * Fetch the new TSS descriptor from the GDT.
1009 */
1010 RTSEL uSelTss = pDesc->Legacy.Gate.u16Sel;
1011 if (uSelTss & X86_SEL_LDT)
1012 {
1013 Log(("BranchTaskGate TSS is in LDT. uSel=%04x uSelTss=%04x -> #GP\n", uSel, uSelTss));
1014 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel & X86_SEL_MASK_OFF_RPL);
1015 }
1016
1017 IEMSELDESC TssDesc;
1018 VBOXSTRICTRC rcStrict = iemMemFetchSelDesc(pVCpu, &TssDesc, uSelTss, X86_XCPT_GP);
1019 if (rcStrict != VINF_SUCCESS)
1020 return rcStrict;
1021
1022 if (TssDesc.Legacy.Gate.u4Type & X86_SEL_TYPE_SYS_TSS_BUSY_MASK)
1023 {
1024 Log(("BranchTaskGate TSS is busy. uSel=%04x uSelTss=%04x DescType=%#x -> #GP\n", uSel, uSelTss,
1025 TssDesc.Legacy.Gate.u4Type));
1026 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel & X86_SEL_MASK_OFF_RPL);
1027 }
1028
1029 if (!TssDesc.Legacy.Gate.u1Present)
1030 {
1031 Log(("BranchTaskGate TSS is not present. uSel=%04x uSelTss=%04x -> #NP\n", uSel, uSelTss));
1032 return iemRaiseSelectorNotPresentBySelector(pVCpu, uSelTss & X86_SEL_MASK_OFF_RPL);
1033 }
1034
1035 uint32_t uNextEip = pVCpu->cpum.GstCtx.eip + cbInstr;
1036 return iemTaskSwitch(pVCpu, enmBranch == IEMBRANCH_JUMP ? IEMTASKSWITCH_JUMP : IEMTASKSWITCH_CALL,
1037 uNextEip, 0 /* fFlags */, 0 /* uErr */, 0 /* uCr2 */, uSelTss, &TssDesc);
1038#endif
1039}
1040
1041
1042/**
1043 * Implements far jumps and calls thru call gates.
1044 *
1045 * @returns VBox strict status code.
1046 * @param pVCpu The cross context virtual CPU structure of the
1047 * calling thread.
1048 * @param cbInstr The current instruction length.
1049 * @param uSel The selector.
1050 * @param enmBranch The kind of branching we're performing.
1051 * @param enmEffOpSize The effective operand size.
1052 * @param pDesc The descriptor corresponding to @a uSel. The type is
1053 * call gate.
1054 */
1055static VBOXSTRICTRC iemCImpl_BranchCallGate(PVMCPUCC pVCpu, uint8_t cbInstr, uint16_t uSel, IEMBRANCH enmBranch,
1056 IEMMODE enmEffOpSize, PIEMSELDESC pDesc)
1057{
1058#define IEM_IMPLEMENTS_CALLGATE
1059#ifndef IEM_IMPLEMENTS_CALLGATE
1060 IEM_RETURN_ASPECT_NOT_IMPLEMENTED();
1061#else
1062 RT_NOREF_PV(enmEffOpSize);
1063 IEM_CTX_ASSERT(pVCpu, IEM_CPUMCTX_EXTRN_XCPT_MASK);
1064
1065 /* NB: Far jumps can only do intra-privilege transfers. Far calls support
1066 * inter-privilege calls and are much more complex.
1067 *
1068 * NB: 64-bit call gate has the same type as a 32-bit call gate! If
1069 * EFER.LMA=1, the gate must be 64-bit. Conversely if EFER.LMA=0, the gate
1070 * must be 16-bit or 32-bit.
1071 */
1072 /** @todo effective operand size is probably irrelevant here, only the
1073 * call gate bitness matters??
1074 */
1075 VBOXSTRICTRC rcStrict;
1076 RTPTRUNION uPtrRet;
1077 uint64_t uNewRsp;
1078 uint64_t uNewRip;
1079 uint64_t u64Base;
1080 uint32_t cbLimit;
1081 RTSEL uNewCS;
1082 IEMSELDESC DescCS;
1083
1084 AssertCompile(X86_SEL_TYPE_SYS_386_CALL_GATE == AMD64_SEL_TYPE_SYS_CALL_GATE);
1085 Assert(enmBranch == IEMBRANCH_JUMP || enmBranch == IEMBRANCH_CALL);
1086 Assert( pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_286_CALL_GATE
1087 || pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_386_CALL_GATE);
1088
1089 /* Determine the new instruction pointer from the gate descriptor. */
1090 uNewRip = pDesc->Legacy.Gate.u16OffsetLow
1091 | ((uint32_t)pDesc->Legacy.Gate.u16OffsetHigh << 16)
1092 | ((uint64_t)pDesc->Long.Gate.u32OffsetTop << 32);
1093
1094 /* Perform DPL checks on the gate descriptor. */
1095 if ( pDesc->Legacy.Gate.u2Dpl < IEM_GET_CPL(pVCpu)
1096 || pDesc->Legacy.Gate.u2Dpl < (uSel & X86_SEL_RPL))
1097 {
1098 Log(("BranchCallGate invalid priv. uSel=%04x Gate DPL=%d CPL=%u Sel RPL=%u -> #GP\n", uSel, pDesc->Legacy.Gate.u2Dpl,
1099 IEM_GET_CPL(pVCpu), (uSel & X86_SEL_RPL)));
1100 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
1101 }
1102
1103 /** @todo does this catch NULL selectors, too? */
1104 if (!pDesc->Legacy.Gen.u1Present)
1105 {
1106 Log(("BranchCallGate Gate not present uSel=%04x -> #NP\n", uSel));
1107 return iemRaiseSelectorNotPresentBySelector(pVCpu, uSel);
1108 }
1109
1110 /*
1111 * Fetch the target CS descriptor from the GDT or LDT.
1112 */
1113 uNewCS = pDesc->Legacy.Gate.u16Sel;
1114 rcStrict = iemMemFetchSelDesc(pVCpu, &DescCS, uNewCS, X86_XCPT_GP);
1115 if (rcStrict != VINF_SUCCESS)
1116 return rcStrict;
1117
1118 /* Target CS must be a code selector. */
1119 if ( !DescCS.Legacy.Gen.u1DescType
1120 || !(DescCS.Legacy.Gen.u4Type & X86_SEL_TYPE_CODE) )
1121 {
1122 Log(("BranchCallGate %04x:%08RX64 -> not a code selector (u1DescType=%u u4Type=%#x).\n",
1123 uNewCS, uNewRip, DescCS.Legacy.Gen.u1DescType, DescCS.Legacy.Gen.u4Type));
1124 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCS);
1125 }
1126
1127 /* Privilege checks on target CS. */
1128 if (enmBranch == IEMBRANCH_JUMP)
1129 {
1130 if (DescCS.Legacy.Gen.u4Type & X86_SEL_TYPE_CONF)
1131 {
1132 if (DescCS.Legacy.Gen.u2Dpl > IEM_GET_CPL(pVCpu))
1133 {
1134 Log(("BranchCallGate jump (conforming) bad DPL uNewCS=%04x Gate DPL=%d CPL=%u -> #GP\n",
1135 uNewCS, DescCS.Legacy.Gen.u2Dpl, IEM_GET_CPL(pVCpu)));
1136 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCS);
1137 }
1138 }
1139 else
1140 {
1141 if (DescCS.Legacy.Gen.u2Dpl != IEM_GET_CPL(pVCpu))
1142 {
1143 Log(("BranchCallGate jump (non-conforming) bad DPL uNewCS=%04x Gate DPL=%d CPL=%u -> #GP\n",
1144 uNewCS, DescCS.Legacy.Gen.u2Dpl, IEM_GET_CPL(pVCpu)));
1145 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCS);
1146 }
1147 }
1148 }
1149 else
1150 {
1151 Assert(enmBranch == IEMBRANCH_CALL);
1152 if (DescCS.Legacy.Gen.u2Dpl > IEM_GET_CPL(pVCpu))
1153 {
1154 Log(("BranchCallGate call invalid priv. uNewCS=%04x Gate DPL=%d CPL=%u -> #GP\n",
1155 uNewCS, DescCS.Legacy.Gen.u2Dpl, IEM_GET_CPL(pVCpu)));
1156 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCS & X86_SEL_MASK_OFF_RPL);
1157 }
1158 }
1159
1160 /* Additional long mode checks. */
1161 if (IEM_IS_LONG_MODE(pVCpu))
1162 {
1163 if (!DescCS.Legacy.Gen.u1Long)
1164 {
1165 Log(("BranchCallGate uNewCS %04x -> not a 64-bit code segment.\n", uNewCS));
1166 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCS);
1167 }
1168
1169 /* L vs D. */
1170 if ( DescCS.Legacy.Gen.u1Long
1171 && DescCS.Legacy.Gen.u1DefBig)
1172 {
1173 Log(("BranchCallGate uNewCS %04x -> both L and D are set.\n", uNewCS));
1174 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCS);
1175 }
1176 }
1177
1178 if (!DescCS.Legacy.Gate.u1Present)
1179 {
1180 Log(("BranchCallGate target CS is not present. uSel=%04x uNewCS=%04x -> #NP(CS)\n", uSel, uNewCS));
1181 return iemRaiseSelectorNotPresentBySelector(pVCpu, uNewCS);
1182 }
1183
1184 if (enmBranch == IEMBRANCH_JUMP)
1185 {
1186 /** @todo This is very similar to regular far jumps; merge! */
1187 /* Jumps are fairly simple... */
1188
1189 /* Chop the high bits off if 16-bit gate (Intel says so). */
1190 if (pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_286_CALL_GATE)
1191 uNewRip = (uint16_t)uNewRip;
1192
1193 /* Limit check for non-long segments. */
1194 cbLimit = X86DESC_LIMIT_G(&DescCS.Legacy);
1195 if (DescCS.Legacy.Gen.u1Long)
1196 u64Base = 0;
1197 else
1198 {
1199 if (uNewRip > cbLimit)
1200 {
1201 Log(("BranchCallGate jump %04x:%08RX64 -> out of bounds (%#x) -> #GP(0)\n", uNewCS, uNewRip, cbLimit));
1202 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, 0);
1203 }
1204 u64Base = X86DESC_BASE(&DescCS.Legacy);
1205 }
1206
1207 /* Canonical address check. */
1208 if (!IEM_IS_CANONICAL(uNewRip))
1209 {
1210 Log(("BranchCallGate jump %04x:%016RX64 - not canonical -> #GP\n", uNewCS, uNewRip));
1211 return iemRaiseNotCanonical(pVCpu);
1212 }
1213
1214 /*
1215 * Ok, everything checked out fine. Now set the accessed bit before
1216 * committing the result into CS, CSHID and RIP.
1217 */
1218 if (!(DescCS.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
1219 {
1220 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uNewCS);
1221 if (rcStrict != VINF_SUCCESS)
1222 return rcStrict;
1223 /** @todo check what VT-x and AMD-V does. */
1224 DescCS.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
1225 }
1226
1227 /* commit */
1228 pVCpu->cpum.GstCtx.rip = uNewRip;
1229 pVCpu->cpum.GstCtx.cs.Sel = uNewCS & X86_SEL_MASK_OFF_RPL;
1230 pVCpu->cpum.GstCtx.cs.Sel |= IEM_GET_CPL(pVCpu); /** @todo is this right for conforming segs? or in general? */
1231 pVCpu->cpum.GstCtx.cs.ValidSel = pVCpu->cpum.GstCtx.cs.Sel;
1232 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
1233 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESC_GET_HID_ATTR(&DescCS.Legacy);
1234 pVCpu->cpum.GstCtx.cs.u32Limit = cbLimit;
1235 pVCpu->cpum.GstCtx.cs.u64Base = u64Base;
1236 }
1237 else
1238 {
1239 Assert(enmBranch == IEMBRANCH_CALL);
1240 /* Calls are much more complicated. */
1241
1242 if (!(DescCS.Legacy.Gen.u4Type & X86_SEL_TYPE_CONF) && (DescCS.Legacy.Gen.u2Dpl < IEM_GET_CPL(pVCpu)))
1243 {
1244 /* More privilege. This is the fun part. */
1245 Assert(!(DescCS.Legacy.Gen.u4Type & X86_SEL_TYPE_CONF)); /* Filtered out above. */
1246
1247 /*
1248 * Determine new SS:rSP from the TSS.
1249 */
1250 Assert(!pVCpu->cpum.GstCtx.tr.Attr.n.u1DescType);
1251
1252 /* Figure out where the new stack pointer is stored in the TSS. */
1253 uint8_t const uNewCSDpl = DescCS.Legacy.Gen.u2Dpl;
1254 uint16_t offNewStack; /* Offset of new stack in TSS. */
1255 uint16_t cbNewStack; /* Number of bytes the stack information takes up in TSS. */
1256 if (!IEM_IS_LONG_MODE(pVCpu))
1257 {
1258 if (pVCpu->cpum.GstCtx.tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_BUSY)
1259 {
1260 offNewStack = RT_UOFFSETOF(X86TSS32, esp0) + uNewCSDpl * 8;
1261 cbNewStack = RT_SIZEOFMEMB(X86TSS32, esp0) + RT_SIZEOFMEMB(X86TSS32, ss0);
1262 }
1263 else
1264 {
1265 Assert(pVCpu->cpum.GstCtx.tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_286_TSS_BUSY);
1266 offNewStack = RT_UOFFSETOF(X86TSS16, sp0) + uNewCSDpl * 4;
1267 cbNewStack = RT_SIZEOFMEMB(X86TSS16, sp0) + RT_SIZEOFMEMB(X86TSS16, ss0);
1268 }
1269 }
1270 else
1271 {
1272 Assert(pVCpu->cpum.GstCtx.tr.Attr.n.u4Type == AMD64_SEL_TYPE_SYS_TSS_BUSY);
1273 offNewStack = RT_UOFFSETOF(X86TSS64, rsp0) + uNewCSDpl * RT_SIZEOFMEMB(X86TSS64, rsp0);
1274 cbNewStack = RT_SIZEOFMEMB(X86TSS64, rsp0);
1275 }
1276
1277 /* Check against TSS limit. */
1278 if ((uint16_t)(offNewStack + cbNewStack - 1) > pVCpu->cpum.GstCtx.tr.u32Limit)
1279 {
1280 Log(("BranchCallGate inner stack past TSS limit - %u > %u -> #TS(TSS)\n", offNewStack + cbNewStack - 1, pVCpu->cpum.GstCtx.tr.u32Limit));
1281 return iemRaiseTaskSwitchFaultBySelector(pVCpu, pVCpu->cpum.GstCtx.tr.Sel);
1282 }
1283
1284 uint8_t bUnmapInfo;
1285 RTPTRUNION uPtrTss;
1286 RTGCPTR GCPtrTss = pVCpu->cpum.GstCtx.tr.u64Base + offNewStack;
1287 rcStrict = iemMemMap(pVCpu, &uPtrTss.pv, &bUnmapInfo, cbNewStack, UINT8_MAX, GCPtrTss, IEM_ACCESS_SYS_R, 0);
1288 if (rcStrict != VINF_SUCCESS)
1289 {
1290 Log(("BranchCallGate: TSS mapping failed (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
1291 return rcStrict;
1292 }
1293
1294 RTSEL uNewSS;
1295 if (!IEM_IS_LONG_MODE(pVCpu))
1296 {
1297 if (pVCpu->cpum.GstCtx.tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_BUSY)
1298 {
1299 uNewRsp = uPtrTss.pu32[0];
1300 uNewSS = uPtrTss.pu16[2];
1301 }
1302 else
1303 {
1304 Assert(pVCpu->cpum.GstCtx.tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_286_TSS_BUSY);
1305 uNewRsp = uPtrTss.pu16[0];
1306 uNewSS = uPtrTss.pu16[1];
1307 }
1308 }
1309 else
1310 {
1311 Assert(pVCpu->cpum.GstCtx.tr.Attr.n.u4Type == AMD64_SEL_TYPE_SYS_TSS_BUSY);
1312 /* SS will be a NULL selector, but that's valid. */
1313 uNewRsp = uPtrTss.pu64[0];
1314 uNewSS = uNewCSDpl;
1315 }
1316
1317 /* Done with the TSS now. */
1318 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
1319 if (rcStrict != VINF_SUCCESS)
1320 {
1321 Log(("BranchCallGate: TSS unmapping failed (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
1322 return rcStrict;
1323 }
1324
1325 /* Only used outside of long mode. */
1326 uint8_t const cbWords = pDesc->Legacy.Gate.u5ParmCount;
1327
1328 /* If EFER.LMA is 0, there's extra work to do. */
1329 IEMSELDESC DescSS;
1330 if (!IEM_IS_LONG_MODE(pVCpu))
1331 {
1332 if ((uNewSS & X86_SEL_MASK_OFF_RPL) == 0)
1333 {
1334 Log(("BranchCallGate new SS NULL -> #TS(NewSS)\n"));
1335 return iemRaiseTaskSwitchFaultBySelector(pVCpu, uNewSS);
1336 }
1337
1338 /* Grab the new SS descriptor. */
1339 rcStrict = iemMemFetchSelDesc(pVCpu, &DescSS, uNewSS, X86_XCPT_SS);
1340 if (rcStrict != VINF_SUCCESS)
1341 return rcStrict;
1342
1343 /* Ensure that CS.DPL == SS.RPL == SS.DPL. */
1344 if ( (DescCS.Legacy.Gen.u2Dpl != (uNewSS & X86_SEL_RPL))
1345 || (DescCS.Legacy.Gen.u2Dpl != DescSS.Legacy.Gen.u2Dpl))
1346 {
1347 Log(("BranchCallGate call bad RPL/DPL uNewSS=%04x SS DPL=%d CS DPL=%u -> #TS(NewSS)\n",
1348 uNewSS, DescCS.Legacy.Gen.u2Dpl, DescCS.Legacy.Gen.u2Dpl));
1349 return iemRaiseTaskSwitchFaultBySelector(pVCpu, uNewSS);
1350 }
1351
1352 /* Ensure new SS is a writable data segment. */
1353 if ((DescSS.Legacy.Gen.u4Type & (X86_SEL_TYPE_CODE | X86_SEL_TYPE_WRITE)) != X86_SEL_TYPE_WRITE)
1354 {
1355 Log(("BranchCallGate call new SS -> not a writable data selector (u4Type=%#x)\n", DescSS.Legacy.Gen.u4Type));
1356 return iemRaiseTaskSwitchFaultBySelector(pVCpu, uNewSS);
1357 }
1358
1359 if (!DescSS.Legacy.Gen.u1Present)
1360 {
1361 Log(("BranchCallGate New stack not present uSel=%04x -> #SS(NewSS)\n", uNewSS));
1362 return iemRaiseStackSelectorNotPresentBySelector(pVCpu, uNewSS);
1363 }
1364 if (pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_386_CALL_GATE)
1365 cbNewStack = (uint16_t)sizeof(uint32_t) * (4 + cbWords);
1366 else
1367 cbNewStack = (uint16_t)sizeof(uint16_t) * (4 + cbWords);
1368 }
1369 else
1370 {
1371 /* Just grab the new (NULL) SS descriptor. */
1372 /** @todo testcase: Check whether the zero GDT entry is actually loaded here
1373 * like we do... */
1374 rcStrict = iemMemFetchSelDesc(pVCpu, &DescSS, uNewSS, X86_XCPT_SS);
1375 if (rcStrict != VINF_SUCCESS)
1376 return rcStrict;
1377
1378 cbNewStack = sizeof(uint64_t) * 4;
1379 }
1380
1381 /** @todo According to Intel, new stack is checked for enough space first,
1382 * then switched. According to AMD, the stack is switched first and
1383 * then pushes might fault!
1384 * NB: OS/2 Warp 3/4 actively relies on the fact that possible
1385 * incoming stack \#PF happens before actual stack switch. AMD is
1386 * either lying or implicitly assumes that new state is committed
1387 * only if and when an instruction doesn't fault.
1388 */
1389
1390 /** @todo According to AMD, CS is loaded first, then SS.
1391 * According to Intel, it's the other way around!?
1392 */
1393
1394 /** @todo Intel and AMD disagree on when exactly the CPL changes! */
1395
1396 /* Set the accessed bit before committing new SS. */
1397 if (!(DescSS.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
1398 {
1399 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uNewSS);
1400 if (rcStrict != VINF_SUCCESS)
1401 return rcStrict;
1402 DescSS.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
1403 }
1404
1405 /* Remember the old SS:rSP and their linear address. */
1406 RTSEL const uOldSS = pVCpu->cpum.GstCtx.ss.Sel;
1407 uint64_t const uOldRsp = pVCpu->cpum.GstCtx.ss.Attr.n.u1DefBig ? pVCpu->cpum.GstCtx.rsp : pVCpu->cpum.GstCtx.sp;
1408
1409 RTGCPTR const GCPtrParmWds = pVCpu->cpum.GstCtx.ss.u64Base + uOldRsp;
1410
1411 /* HACK ALERT! Probe if the write to the new stack will succeed. May #SS(NewSS)
1412 or #PF, the former is not implemented in this workaround. */
1413 /** @todo Proper fix callgate target stack exceptions. */
1414 /** @todo testcase: Cover callgates with partially or fully inaccessible
1415 * target stacks. */
1416 void *pvNewFrame;
1417 RTGCPTR GCPtrNewStack = X86DESC_BASE(&DescSS.Legacy) + uNewRsp - cbNewStack;
1418 rcStrict = iemMemMap(pVCpu, &pvNewFrame, &bUnmapInfo, cbNewStack, UINT8_MAX, GCPtrNewStack, IEM_ACCESS_SYS_RW, 0);
1419 if (rcStrict != VINF_SUCCESS)
1420 {
1421 Log(("BranchCallGate: Incoming stack (%04x:%08RX64) not accessible, rc=%Rrc\n", uNewSS, uNewRsp, VBOXSTRICTRC_VAL(rcStrict)));
1422 return rcStrict;
1423 }
1424 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
1425 if (rcStrict != VINF_SUCCESS)
1426 {
1427 Log(("BranchCallGate: New stack probe unmapping failed (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
1428 return rcStrict;
1429 }
1430
1431 /* Commit new SS:rSP. */
1432 pVCpu->cpum.GstCtx.ss.Sel = uNewSS;
1433 pVCpu->cpum.GstCtx.ss.ValidSel = uNewSS;
1434 pVCpu->cpum.GstCtx.ss.Attr.u = X86DESC_GET_HID_ATTR(&DescSS.Legacy);
1435 pVCpu->cpum.GstCtx.ss.u32Limit = X86DESC_LIMIT_G(&DescSS.Legacy);
1436 pVCpu->cpum.GstCtx.ss.u64Base = X86DESC_BASE(&DescSS.Legacy);
1437 pVCpu->cpum.GstCtx.ss.fFlags = CPUMSELREG_FLAGS_VALID;
1438 pVCpu->cpum.GstCtx.rsp = uNewRsp;
1439 IEM_SET_CPL(pVCpu, uNewCSDpl); /** @todo Are the parameter words accessed using the new CPL or the old CPL? */
1440 Assert(CPUMSELREG_ARE_HIDDEN_PARTS_VALID(pVCpu, &pVCpu->cpum.GstCtx.ss));
1441 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_HIDDEN_SEL_REGS);
1442
1443 /* At this point the stack access must not fail because new state was already committed. */
1444 /** @todo this can still fail due to SS.LIMIT not check. */
1445 uint8_t bUnmapInfoRet;
1446 rcStrict = iemMemStackPushBeginSpecial(pVCpu, cbNewStack,
1447 IEM_IS_LONG_MODE(pVCpu) ? 7
1448 : pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_386_CALL_GATE ? 3 : 1,
1449 &uPtrRet.pv, &bUnmapInfoRet, &uNewRsp);
1450 AssertMsgReturn(rcStrict == VINF_SUCCESS, ("BranchCallGate: New stack mapping failed (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)),
1451 VERR_INTERNAL_ERROR_5);
1452
1453 if (!IEM_IS_LONG_MODE(pVCpu))
1454 {
1455 if (pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_386_CALL_GATE)
1456 {
1457 if (cbWords)
1458 {
1459 /* Map the relevant chunk of the old stack. */
1460 RTPTRUNION uPtrParmWds;
1461 rcStrict = iemMemMap(pVCpu, &uPtrParmWds.pv, &bUnmapInfo, cbWords * 4, UINT8_MAX, GCPtrParmWds,
1462 IEM_ACCESS_DATA_R, 0 /** @todo Can uNewCSDpl == 3? Then we need alignment mask here! */);
1463 if (rcStrict != VINF_SUCCESS)
1464 {
1465 Log(("BranchCallGate: Old stack mapping (32-bit) failed (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
1466 return rcStrict;
1467 }
1468
1469 /* Copy the parameter (d)words. */
1470 for (int i = 0; i < cbWords; ++i)
1471 uPtrRet.pu32[2 + i] = uPtrParmWds.pu32[i];
1472
1473 /* Unmap the old stack. */
1474 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
1475 if (rcStrict != VINF_SUCCESS)
1476 {
1477 Log(("BranchCallGate: Old stack unmapping (32-bit) failed (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
1478 return rcStrict;
1479 }
1480 }
1481
1482 /* Push the old CS:rIP. */
1483 uPtrRet.pu32[0] = pVCpu->cpum.GstCtx.eip + cbInstr;
1484 uPtrRet.pu32[1] = pVCpu->cpum.GstCtx.cs.Sel; /** @todo Testcase: What is written to the high word when pushing CS? */
1485
1486 /* Push the old SS:rSP. */
1487 uPtrRet.pu32[2 + cbWords + 0] = uOldRsp;
1488 uPtrRet.pu32[2 + cbWords + 1] = uOldSS;
1489 }
1490 else
1491 {
1492 Assert(pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_286_CALL_GATE);
1493
1494 if (cbWords)
1495 {
1496 /* Map the relevant chunk of the old stack. */
1497 RTPTRUNION uPtrParmWds;
1498 rcStrict = iemMemMap(pVCpu, &uPtrParmWds.pv, &bUnmapInfo, cbWords * 2, UINT8_MAX, GCPtrParmWds,
1499 IEM_ACCESS_DATA_R, 0 /** @todo Can uNewCSDpl == 3? Then we need alignment mask here! */);
1500 if (rcStrict != VINF_SUCCESS)
1501 {
1502 Log(("BranchCallGate: Old stack mapping (16-bit) failed (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
1503 return rcStrict;
1504 }
1505
1506 /* Copy the parameter words. */
1507 for (int i = 0; i < cbWords; ++i)
1508 uPtrRet.pu16[2 + i] = uPtrParmWds.pu16[i];
1509
1510 /* Unmap the old stack. */
1511 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
1512 if (rcStrict != VINF_SUCCESS)
1513 {
1514 Log(("BranchCallGate: Old stack unmapping (32-bit) failed (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
1515 return rcStrict;
1516 }
1517 }
1518
1519 /* Push the old CS:rIP. */
1520 uPtrRet.pu16[0] = pVCpu->cpum.GstCtx.ip + cbInstr;
1521 uPtrRet.pu16[1] = pVCpu->cpum.GstCtx.cs.Sel;
1522
1523 /* Push the old SS:rSP. */
1524 uPtrRet.pu16[2 + cbWords + 0] = uOldRsp;
1525 uPtrRet.pu16[2 + cbWords + 1] = uOldSS;
1526 }
1527 }
1528 else
1529 {
1530 Assert(pDesc->Legacy.Gate.u4Type == AMD64_SEL_TYPE_SYS_CALL_GATE);
1531
1532 /* For 64-bit gates, no parameters are copied. Just push old SS:rSP and CS:rIP. */
1533 uPtrRet.pu64[0] = pVCpu->cpum.GstCtx.rip + cbInstr;
1534 uPtrRet.pu64[1] = pVCpu->cpum.GstCtx.cs.Sel; /** @todo Testcase: What is written to the high words when pushing CS? */
1535 uPtrRet.pu64[2] = uOldRsp;
1536 uPtrRet.pu64[3] = uOldSS; /** @todo Testcase: What is written to the high words when pushing SS? */
1537 }
1538
1539 rcStrict = iemMemStackPushCommitSpecial(pVCpu, bUnmapInfoRet, uNewRsp);
1540 if (rcStrict != VINF_SUCCESS)
1541 {
1542 Log(("BranchCallGate: New stack unmapping failed (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
1543 return rcStrict;
1544 }
1545
1546 /* Chop the high bits off if 16-bit gate (Intel says so). */
1547 if (pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_286_CALL_GATE)
1548 uNewRip = (uint16_t)uNewRip;
1549
1550 /* Limit / canonical check. */
1551 cbLimit = X86DESC_LIMIT_G(&DescCS.Legacy);
1552 if (!IEM_IS_LONG_MODE(pVCpu))
1553 {
1554 if (uNewRip > cbLimit)
1555 {
1556 Log(("BranchCallGate %04x:%08RX64 -> out of bounds (%#x)\n", uNewCS, uNewRip, cbLimit));
1557 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, 0);
1558 }
1559 u64Base = X86DESC_BASE(&DescCS.Legacy);
1560 }
1561 else
1562 {
1563 Assert(pDesc->Legacy.Gate.u4Type == AMD64_SEL_TYPE_SYS_CALL_GATE);
1564 if (!IEM_IS_CANONICAL(uNewRip))
1565 {
1566 Log(("BranchCallGate call %04x:%016RX64 - not canonical -> #GP\n", uNewCS, uNewRip));
1567 return iemRaiseNotCanonical(pVCpu);
1568 }
1569 u64Base = 0;
1570 }
1571
1572 /*
1573 * Now set the accessed bit before
1574 * writing the return address to the stack and committing the result into
1575 * CS, CSHID and RIP.
1576 */
1577 /** @todo Testcase: Need to check WHEN exactly the accessed bit is set. */
1578 if (!(DescCS.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
1579 {
1580 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uNewCS);
1581 if (rcStrict != VINF_SUCCESS)
1582 return rcStrict;
1583 /** @todo check what VT-x and AMD-V does. */
1584 DescCS.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
1585 }
1586
1587 /* Commit new CS:rIP. */
1588 pVCpu->cpum.GstCtx.rip = uNewRip;
1589 pVCpu->cpum.GstCtx.cs.Sel = uNewCS & X86_SEL_MASK_OFF_RPL;
1590 pVCpu->cpum.GstCtx.cs.Sel |= IEM_GET_CPL(pVCpu);
1591 pVCpu->cpum.GstCtx.cs.ValidSel = pVCpu->cpum.GstCtx.cs.Sel;
1592 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
1593 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESC_GET_HID_ATTR(&DescCS.Legacy);
1594 pVCpu->cpum.GstCtx.cs.u32Limit = cbLimit;
1595 pVCpu->cpum.GstCtx.cs.u64Base = u64Base;
1596 }
1597 else
1598 {
1599 /* Same privilege. */
1600 /** @todo This is very similar to regular far calls; merge! */
1601
1602 /* Check stack first - may #SS(0). */
1603 /** @todo check how gate size affects pushing of CS! Does callf 16:32 in
1604 * 16-bit code cause a two or four byte CS to be pushed? */
1605 uint8_t bUnmapInfoRet;
1606 rcStrict = iemMemStackPushBeginSpecial(pVCpu,
1607 IEM_IS_LONG_MODE(pVCpu) ? 8+8
1608 : pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_386_CALL_GATE ? 4+4 : 2+2,
1609 IEM_IS_LONG_MODE(pVCpu) ? 7
1610 : pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_386_CALL_GATE ? 3 : 2,
1611 &uPtrRet.pv, &bUnmapInfoRet, &uNewRsp);
1612 if (rcStrict != VINF_SUCCESS)
1613 return rcStrict;
1614
1615 /* Chop the high bits off if 16-bit gate (Intel says so). */
1616 if (pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_286_CALL_GATE)
1617 uNewRip = (uint16_t)uNewRip;
1618
1619 /* Limit / canonical check. */
1620 cbLimit = X86DESC_LIMIT_G(&DescCS.Legacy);
1621 if (!IEM_IS_LONG_MODE(pVCpu))
1622 {
1623 if (uNewRip > cbLimit)
1624 {
1625 Log(("BranchCallGate %04x:%08RX64 -> out of bounds (%#x)\n", uNewCS, uNewRip, cbLimit));
1626 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, 0);
1627 }
1628 u64Base = X86DESC_BASE(&DescCS.Legacy);
1629 }
1630 else
1631 {
1632 if (!IEM_IS_CANONICAL(uNewRip))
1633 {
1634 Log(("BranchCallGate call %04x:%016RX64 - not canonical -> #GP\n", uNewCS, uNewRip));
1635 return iemRaiseNotCanonical(pVCpu);
1636 }
1637 u64Base = 0;
1638 }
1639
1640 /*
1641 * Now set the accessed bit before
1642 * writing the return address to the stack and committing the result into
1643 * CS, CSHID and RIP.
1644 */
1645 /** @todo Testcase: Need to check WHEN exactly the accessed bit is set. */
1646 if (!(DescCS.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
1647 {
1648 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uNewCS);
1649 if (rcStrict != VINF_SUCCESS)
1650 return rcStrict;
1651 /** @todo check what VT-x and AMD-V does. */
1652 DescCS.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
1653 }
1654
1655 /* stack */
1656 if (!IEM_IS_LONG_MODE(pVCpu))
1657 {
1658 if (pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_386_CALL_GATE)
1659 {
1660 uPtrRet.pu32[0] = pVCpu->cpum.GstCtx.eip + cbInstr;
1661 uPtrRet.pu32[1] = pVCpu->cpum.GstCtx.cs.Sel; /** @todo Testcase: What is written to the high word when pushing CS? */
1662 }
1663 else
1664 {
1665 Assert(pDesc->Legacy.Gate.u4Type == X86_SEL_TYPE_SYS_286_CALL_GATE);
1666 uPtrRet.pu16[0] = pVCpu->cpum.GstCtx.ip + cbInstr;
1667 uPtrRet.pu16[1] = pVCpu->cpum.GstCtx.cs.Sel;
1668 }
1669 }
1670 else
1671 {
1672 Assert(pDesc->Legacy.Gate.u4Type == AMD64_SEL_TYPE_SYS_CALL_GATE);
1673 uPtrRet.pu64[0] = pVCpu->cpum.GstCtx.rip + cbInstr;
1674 uPtrRet.pu64[1] = pVCpu->cpum.GstCtx.cs.Sel; /** @todo Testcase: What is written to the high words when pushing CS? */
1675 }
1676
1677 rcStrict = iemMemStackPushCommitSpecial(pVCpu, bUnmapInfoRet, uNewRsp);
1678 if (rcStrict != VINF_SUCCESS)
1679 return rcStrict;
1680
1681 /* commit */
1682 pVCpu->cpum.GstCtx.rip = uNewRip;
1683 pVCpu->cpum.GstCtx.cs.Sel = uNewCS & X86_SEL_MASK_OFF_RPL;
1684 pVCpu->cpum.GstCtx.cs.Sel |= IEM_GET_CPL(pVCpu);
1685 pVCpu->cpum.GstCtx.cs.ValidSel = pVCpu->cpum.GstCtx.cs.Sel;
1686 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
1687 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESC_GET_HID_ATTR(&DescCS.Legacy);
1688 pVCpu->cpum.GstCtx.cs.u32Limit = cbLimit;
1689 pVCpu->cpum.GstCtx.cs.u64Base = u64Base;
1690 }
1691 }
1692 pVCpu->cpum.GstCtx.eflags.Bits.u1RF = 0;
1693
1694 iemRecalcExecModeAndCplFlags(pVCpu);
1695
1696/** @todo single stepping */
1697
1698 /* Flush the prefetch buffer. */
1699 IEM_FLUSH_PREFETCH_HEAVY(pVCpu, cbInstr);
1700 return VINF_SUCCESS;
1701#endif /* IEM_IMPLEMENTS_CALLGATE */
1702}
1703
1704
1705/**
1706 * Implements far jumps and calls thru system selectors.
1707 *
1708 * @returns VBox strict status code.
1709 * @param pVCpu The cross context virtual CPU structure of the
1710 * calling thread.
1711 * @param cbInstr The current instruction length.
1712 * @param uSel The selector.
1713 * @param enmBranch The kind of branching we're performing.
1714 * @param enmEffOpSize The effective operand size.
1715 * @param pDesc The descriptor corresponding to @a uSel.
1716 */
1717static VBOXSTRICTRC iemCImpl_BranchSysSel(PVMCPUCC pVCpu, uint8_t cbInstr, uint16_t uSel, IEMBRANCH enmBranch,
1718 IEMMODE enmEffOpSize, PIEMSELDESC pDesc)
1719{
1720 Assert(enmBranch == IEMBRANCH_JUMP || enmBranch == IEMBRANCH_CALL);
1721 Assert((uSel & X86_SEL_MASK_OFF_RPL));
1722 IEM_CTX_IMPORT_RET(pVCpu, IEM_CPUMCTX_EXTRN_XCPT_MASK);
1723
1724 if (IEM_IS_LONG_MODE(pVCpu))
1725 switch (pDesc->Legacy.Gen.u4Type)
1726 {
1727 case AMD64_SEL_TYPE_SYS_CALL_GATE:
1728 return iemCImpl_BranchCallGate(pVCpu, cbInstr, uSel, enmBranch, enmEffOpSize, pDesc);
1729
1730 default:
1731 case AMD64_SEL_TYPE_SYS_LDT:
1732 case AMD64_SEL_TYPE_SYS_TSS_BUSY:
1733 case AMD64_SEL_TYPE_SYS_TSS_AVAIL:
1734 case AMD64_SEL_TYPE_SYS_TRAP_GATE:
1735 case AMD64_SEL_TYPE_SYS_INT_GATE:
1736 Log(("branch %04x -> wrong sys selector (64-bit): %d\n", uSel, pDesc->Legacy.Gen.u4Type));
1737 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
1738 }
1739
1740 switch (pDesc->Legacy.Gen.u4Type)
1741 {
1742 case X86_SEL_TYPE_SYS_286_CALL_GATE:
1743 case X86_SEL_TYPE_SYS_386_CALL_GATE:
1744 return iemCImpl_BranchCallGate(pVCpu, cbInstr, uSel, enmBranch, enmEffOpSize, pDesc);
1745
1746 case X86_SEL_TYPE_SYS_TASK_GATE:
1747 return iemCImpl_BranchTaskGate(pVCpu, cbInstr, uSel, enmBranch, enmEffOpSize, pDesc);
1748
1749 case X86_SEL_TYPE_SYS_286_TSS_AVAIL:
1750 case X86_SEL_TYPE_SYS_386_TSS_AVAIL:
1751 return iemCImpl_BranchTaskSegment(pVCpu, cbInstr, uSel, enmBranch, enmEffOpSize, pDesc);
1752
1753 case X86_SEL_TYPE_SYS_286_TSS_BUSY:
1754 Log(("branch %04x -> busy 286 TSS\n", uSel));
1755 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
1756
1757 case X86_SEL_TYPE_SYS_386_TSS_BUSY:
1758 Log(("branch %04x -> busy 386 TSS\n", uSel));
1759 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
1760
1761 default:
1762 case X86_SEL_TYPE_SYS_LDT:
1763 case X86_SEL_TYPE_SYS_286_INT_GATE:
1764 case X86_SEL_TYPE_SYS_286_TRAP_GATE:
1765 case X86_SEL_TYPE_SYS_386_INT_GATE:
1766 case X86_SEL_TYPE_SYS_386_TRAP_GATE:
1767 Log(("branch %04x -> wrong sys selector: %d\n", uSel, pDesc->Legacy.Gen.u4Type));
1768 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
1769 }
1770}
1771
1772
1773/**
1774 * Implements far jumps.
1775 *
1776 * @param uSel The selector.
1777 * @param offSeg The segment offset.
1778 * @param enmEffOpSize The effective operand size.
1779 */
1780IEM_CIMPL_DEF_3(iemCImpl_FarJmp, uint16_t, uSel, uint64_t, offSeg, IEMMODE, enmEffOpSize)
1781{
1782 NOREF(cbInstr);
1783 Assert(offSeg <= UINT32_MAX || (!IEM_IS_GUEST_CPU_AMD(pVCpu) && IEM_IS_64BIT_CODE(pVCpu)));
1784
1785 /*
1786 * Real mode and V8086 mode are easy. The only snag seems to be that
1787 * CS.limit doesn't change and the limit check is done against the current
1788 * limit.
1789 */
1790 /** @todo Robert Collins claims (The Segment Descriptor Cache, DDJ August
1791 * 1998) that up to and including the Intel 486, far control
1792 * transfers in real mode set default CS attributes (0x93) and also
1793 * set a 64K segment limit. Starting with the Pentium, the
1794 * attributes and limit are left alone but the access rights are
1795 * ignored. We only implement the Pentium+ behavior.
1796 * */
1797 if (IEM_IS_REAL_OR_V86_MODE(pVCpu))
1798 {
1799 Assert(enmEffOpSize == IEMMODE_16BIT || enmEffOpSize == IEMMODE_32BIT);
1800 if (offSeg > pVCpu->cpum.GstCtx.cs.u32Limit)
1801 {
1802 Log(("iemCImpl_FarJmp: 16-bit limit\n"));
1803 return iemRaiseGeneralProtectionFault0(pVCpu);
1804 }
1805
1806 if (enmEffOpSize == IEMMODE_16BIT) /** @todo WRONG, must pass this. */
1807 pVCpu->cpum.GstCtx.rip = offSeg;
1808 else
1809 pVCpu->cpum.GstCtx.rip = offSeg & UINT16_MAX;
1810 pVCpu->cpum.GstCtx.cs.Sel = uSel;
1811 pVCpu->cpum.GstCtx.cs.ValidSel = uSel;
1812 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
1813 pVCpu->cpum.GstCtx.cs.u64Base = (uint32_t)uSel << 4;
1814
1815 /* Update the FLAT 32-bit mode flag, if we're in 32-bit unreal mode (unlikely): */
1816 if (RT_LIKELY(!IEM_IS_32BIT_CODE(pVCpu)))
1817 { /* likely */ }
1818 else if (uSel != 0)
1819 pVCpu->iem.s.fExec &= ~IEM_F_MODE_X86_FLAT_OR_PRE_386_MASK;
1820 else
1821 pVCpu->iem.s.fExec = (pVCpu->iem.s.fExec & ~IEM_F_MODE_X86_FLAT_OR_PRE_386_MASK)
1822 | iemCalc32BitFlatIndicator(pVCpu);
1823
1824 return iemRegFinishClearingRF(pVCpu, VINF_SUCCESS);
1825 }
1826
1827 /*
1828 * Protected mode. Need to parse the specified descriptor...
1829 */
1830 if (!(uSel & X86_SEL_MASK_OFF_RPL))
1831 {
1832 Log(("jmpf %04x:%08RX64 -> invalid selector, #GP(0)\n", uSel, offSeg));
1833 return iemRaiseGeneralProtectionFault0(pVCpu);
1834 }
1835
1836 /* Fetch the descriptor. */
1837 IEMSELDESC Desc;
1838 VBOXSTRICTRC rcStrict = iemMemFetchSelDesc(pVCpu, &Desc, uSel, X86_XCPT_GP);
1839 if (rcStrict != VINF_SUCCESS)
1840 return rcStrict;
1841
1842 /* Is it there? */
1843 if (!Desc.Legacy.Gen.u1Present) /** @todo this is probably checked too early. Testcase! */
1844 {
1845 Log(("jmpf %04x:%08RX64 -> segment not present\n", uSel, offSeg));
1846 return iemRaiseSelectorNotPresentBySelector(pVCpu, uSel);
1847 }
1848
1849 /*
1850 * Deal with it according to its type. We do the standard code selectors
1851 * here and dispatch the system selectors to worker functions.
1852 */
1853 if (!Desc.Legacy.Gen.u1DescType)
1854 return iemCImpl_BranchSysSel(pVCpu, cbInstr, uSel, IEMBRANCH_JUMP, enmEffOpSize, &Desc);
1855
1856 /* Only code segments. */
1857 if (!(Desc.Legacy.Gen.u4Type & X86_SEL_TYPE_CODE))
1858 {
1859 Log(("jmpf %04x:%08RX64 -> not a code selector (u4Type=%#x).\n", uSel, offSeg, Desc.Legacy.Gen.u4Type));
1860 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
1861 }
1862
1863 /* L vs D. */
1864 if ( Desc.Legacy.Gen.u1Long
1865 && Desc.Legacy.Gen.u1DefBig
1866 && IEM_IS_LONG_MODE(pVCpu))
1867 {
1868 Log(("jmpf %04x:%08RX64 -> both L and D are set.\n", uSel, offSeg));
1869 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
1870 }
1871
1872 /* DPL/RPL/CPL check, where conforming segments makes a difference. */
1873 if (Desc.Legacy.Gen.u4Type & X86_SEL_TYPE_CONF)
1874 {
1875 if (IEM_GET_CPL(pVCpu) < Desc.Legacy.Gen.u2Dpl)
1876 {
1877 Log(("jmpf %04x:%08RX64 -> DPL violation (conforming); DPL=%d CPL=%u\n",
1878 uSel, offSeg, Desc.Legacy.Gen.u2Dpl, IEM_GET_CPL(pVCpu)));
1879 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
1880 }
1881 }
1882 else
1883 {
1884 if (IEM_GET_CPL(pVCpu) != Desc.Legacy.Gen.u2Dpl)
1885 {
1886 Log(("jmpf %04x:%08RX64 -> CPL != DPL; DPL=%d CPL=%u\n", uSel, offSeg, Desc.Legacy.Gen.u2Dpl, IEM_GET_CPL(pVCpu)));
1887 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
1888 }
1889 if ((uSel & X86_SEL_RPL) > IEM_GET_CPL(pVCpu))
1890 {
1891 Log(("jmpf %04x:%08RX64 -> RPL > DPL; RPL=%d CPL=%u\n", uSel, offSeg, (uSel & X86_SEL_RPL), IEM_GET_CPL(pVCpu)));
1892 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
1893 }
1894 }
1895
1896 /* Chop the high bits if 16-bit (Intel says so). */
1897 if (enmEffOpSize == IEMMODE_16BIT)
1898 offSeg &= UINT16_MAX;
1899
1900 /* Limit check and get the base. */
1901 uint64_t u64Base;
1902 uint32_t cbLimit = X86DESC_LIMIT_G(&Desc.Legacy);
1903 if ( !Desc.Legacy.Gen.u1Long
1904 || !IEM_IS_LONG_MODE(pVCpu))
1905 {
1906 if (RT_LIKELY(offSeg <= cbLimit))
1907 u64Base = X86DESC_BASE(&Desc.Legacy);
1908 else
1909 {
1910 Log(("jmpf %04x:%08RX64 -> out of bounds (%#x)\n", uSel, offSeg, cbLimit));
1911 /** @todo Intel says this is \#GP(0)! */
1912 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
1913 }
1914 }
1915 else
1916 u64Base = 0;
1917
1918 /*
1919 * Ok, everything checked out fine. Now set the accessed bit before
1920 * committing the result into CS, CSHID and RIP.
1921 */
1922 if (!(Desc.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
1923 {
1924 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uSel);
1925 if (rcStrict != VINF_SUCCESS)
1926 return rcStrict;
1927 /** @todo check what VT-x and AMD-V does. */
1928 Desc.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
1929 }
1930
1931 /* commit */
1932 pVCpu->cpum.GstCtx.rip = offSeg;
1933 pVCpu->cpum.GstCtx.cs.Sel = uSel & X86_SEL_MASK_OFF_RPL;
1934 pVCpu->cpum.GstCtx.cs.Sel |= IEM_GET_CPL(pVCpu); /** @todo is this right for conforming segs? or in general? */
1935 pVCpu->cpum.GstCtx.cs.ValidSel = pVCpu->cpum.GstCtx.cs.Sel;
1936 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
1937 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESC_GET_HID_ATTR(&Desc.Legacy);
1938 pVCpu->cpum.GstCtx.cs.u32Limit = cbLimit;
1939 pVCpu->cpum.GstCtx.cs.u64Base = u64Base;
1940
1941 /** @todo check if the hidden bits are loaded correctly for 64-bit
1942 * mode. */
1943
1944 iemRecalcExecModeAndCplFlags(pVCpu);
1945
1946 /* Flush the prefetch buffer. */
1947 IEM_FLUSH_PREFETCH_HEAVY(pVCpu, cbInstr);
1948
1949 return iemRegFinishClearingRF(pVCpu, VINF_SUCCESS);
1950}
1951
1952
1953/**
1954 * Implements far calls.
1955 *
1956 * This very similar to iemCImpl_FarJmp.
1957 *
1958 * @param uSel The selector.
1959 * @param offSeg The segment offset.
1960 * @param enmEffOpSize The operand size (in case we need it).
1961 */
1962IEM_CIMPL_DEF_3(iemCImpl_callf, uint16_t, uSel, uint64_t, offSeg, IEMMODE, enmEffOpSize)
1963{
1964 VBOXSTRICTRC rcStrict;
1965 uint64_t uNewRsp;
1966 RTPTRUNION uPtrRet;
1967 uint8_t bUnmapInfo;
1968
1969 /*
1970 * Real mode and V8086 mode are easy. The only snag seems to be that
1971 * CS.limit doesn't change and the limit check is done against the current
1972 * limit.
1973 */
1974 /** @todo See comment for similar code in iemCImpl_FarJmp */
1975 if (IEM_IS_REAL_OR_V86_MODE(pVCpu))
1976 {
1977 Assert(enmEffOpSize == IEMMODE_16BIT || enmEffOpSize == IEMMODE_32BIT);
1978
1979 /* Check stack first - may #SS(0). */
1980 rcStrict = iemMemStackPushBeginSpecial(pVCpu, enmEffOpSize == IEMMODE_32BIT ? 4+4 : 2+2,
1981 enmEffOpSize == IEMMODE_32BIT ? 3 : 1,
1982 &uPtrRet.pv, &bUnmapInfo, &uNewRsp);
1983 if (rcStrict != VINF_SUCCESS)
1984 return rcStrict;
1985
1986 /* Check the target address range. */
1987/** @todo this must be wrong! Write unreal mode tests! */
1988 if (offSeg > UINT32_MAX)
1989 return iemRaiseGeneralProtectionFault0(pVCpu);
1990
1991 /* Everything is fine, push the return address. */
1992 if (enmEffOpSize == IEMMODE_16BIT)
1993 {
1994 uPtrRet.pu16[0] = pVCpu->cpum.GstCtx.ip + cbInstr;
1995 uPtrRet.pu16[1] = pVCpu->cpum.GstCtx.cs.Sel;
1996 }
1997 else
1998 {
1999 uPtrRet.pu32[0] = pVCpu->cpum.GstCtx.eip + cbInstr;
2000 uPtrRet.pu16[2] = pVCpu->cpum.GstCtx.cs.Sel;
2001 }
2002 rcStrict = iemMemStackPushCommitSpecial(pVCpu, bUnmapInfo, uNewRsp);
2003 if (rcStrict != VINF_SUCCESS)
2004 return rcStrict;
2005
2006 /* Branch. */
2007 pVCpu->cpum.GstCtx.rip = offSeg;
2008 pVCpu->cpum.GstCtx.cs.Sel = uSel;
2009 pVCpu->cpum.GstCtx.cs.ValidSel = uSel;
2010 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
2011 pVCpu->cpum.GstCtx.cs.u64Base = (uint32_t)uSel << 4;
2012
2013 return iemRegFinishClearingRF(pVCpu, VINF_SUCCESS);
2014 }
2015
2016 /*
2017 * Protected mode. Need to parse the specified descriptor...
2018 */
2019 if (!(uSel & X86_SEL_MASK_OFF_RPL))
2020 {
2021 Log(("callf %04x:%08RX64 -> invalid selector, #GP(0)\n", uSel, offSeg));
2022 return iemRaiseGeneralProtectionFault0(pVCpu);
2023 }
2024
2025 /* Fetch the descriptor. */
2026 IEMSELDESC Desc;
2027 rcStrict = iemMemFetchSelDesc(pVCpu, &Desc, uSel, X86_XCPT_GP);
2028 if (rcStrict != VINF_SUCCESS)
2029 return rcStrict;
2030
2031 /*
2032 * Deal with it according to its type. We do the standard code selectors
2033 * here and dispatch the system selectors to worker functions.
2034 */
2035 if (!Desc.Legacy.Gen.u1DescType)
2036 return iemCImpl_BranchSysSel(pVCpu, cbInstr, uSel, IEMBRANCH_CALL, enmEffOpSize, &Desc);
2037
2038 /* Only code segments. */
2039 if (!(Desc.Legacy.Gen.u4Type & X86_SEL_TYPE_CODE))
2040 {
2041 Log(("callf %04x:%08RX64 -> not a code selector (u4Type=%#x).\n", uSel, offSeg, Desc.Legacy.Gen.u4Type));
2042 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
2043 }
2044
2045 /* L vs D. */
2046 if ( Desc.Legacy.Gen.u1Long
2047 && Desc.Legacy.Gen.u1DefBig
2048 && IEM_IS_LONG_MODE(pVCpu))
2049 {
2050 Log(("callf %04x:%08RX64 -> both L and D are set.\n", uSel, offSeg));
2051 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
2052 }
2053
2054 /* DPL/RPL/CPL check, where conforming segments makes a difference. */
2055 if (Desc.Legacy.Gen.u4Type & X86_SEL_TYPE_CONF)
2056 {
2057 if (IEM_GET_CPL(pVCpu) < Desc.Legacy.Gen.u2Dpl)
2058 {
2059 Log(("callf %04x:%08RX64 -> DPL violation (conforming); DPL=%d CPL=%u\n",
2060 uSel, offSeg, Desc.Legacy.Gen.u2Dpl, IEM_GET_CPL(pVCpu)));
2061 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
2062 }
2063 }
2064 else
2065 {
2066 if (IEM_GET_CPL(pVCpu) != Desc.Legacy.Gen.u2Dpl)
2067 {
2068 Log(("callf %04x:%08RX64 -> CPL != DPL; DPL=%d CPL=%u\n", uSel, offSeg, Desc.Legacy.Gen.u2Dpl, IEM_GET_CPL(pVCpu)));
2069 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
2070 }
2071 if ((uSel & X86_SEL_RPL) > IEM_GET_CPL(pVCpu))
2072 {
2073 Log(("callf %04x:%08RX64 -> RPL > DPL; RPL=%d CPL=%u\n", uSel, offSeg, (uSel & X86_SEL_RPL), IEM_GET_CPL(pVCpu)));
2074 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
2075 }
2076 }
2077
2078 /* Is it there? */
2079 if (!Desc.Legacy.Gen.u1Present)
2080 {
2081 Log(("callf %04x:%08RX64 -> segment not present\n", uSel, offSeg));
2082 return iemRaiseSelectorNotPresentBySelector(pVCpu, uSel);
2083 }
2084
2085 /* Check stack first - may #SS(0). */
2086 /** @todo check how operand prefix affects pushing of CS! Does callf 16:32 in
2087 * 16-bit code cause a two or four byte CS to be pushed? */
2088 rcStrict = iemMemStackPushBeginSpecial(pVCpu,
2089 enmEffOpSize == IEMMODE_64BIT ? 8+8 : enmEffOpSize == IEMMODE_32BIT ? 4+4 : 2+2,
2090 enmEffOpSize == IEMMODE_64BIT ? 7 : enmEffOpSize == IEMMODE_32BIT ? 3 : 1,
2091 &uPtrRet.pv, &bUnmapInfo, &uNewRsp);
2092 if (rcStrict != VINF_SUCCESS)
2093 return rcStrict;
2094
2095 /* Chop the high bits if 16-bit (Intel says so). */
2096 if (enmEffOpSize == IEMMODE_16BIT)
2097 offSeg &= UINT16_MAX;
2098
2099 /* Limit / canonical check. */
2100 uint64_t u64Base;
2101 uint32_t cbLimit = X86DESC_LIMIT_G(&Desc.Legacy);
2102 if ( !Desc.Legacy.Gen.u1Long
2103 || !IEM_IS_LONG_MODE(pVCpu))
2104 {
2105 if (RT_LIKELY(offSeg <= cbLimit))
2106 u64Base = X86DESC_BASE(&Desc.Legacy);
2107 else
2108 {
2109 Log(("callf %04x:%08RX64 -> out of bounds (%#x)\n", uSel, offSeg, cbLimit));
2110 /** @todo Intel says this is \#GP(0)! */
2111 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
2112 }
2113 }
2114 else if (IEM_IS_CANONICAL(offSeg))
2115 u64Base = 0;
2116 else
2117 {
2118 Log(("callf %04x:%016RX64 - not canonical -> #GP\n", uSel, offSeg));
2119 return iemRaiseNotCanonical(pVCpu);
2120 }
2121
2122 /*
2123 * Now set the accessed bit before
2124 * writing the return address to the stack and committing the result into
2125 * CS, CSHID and RIP.
2126 */
2127 /** @todo Testcase: Need to check WHEN exactly the accessed bit is set. */
2128 if (!(Desc.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
2129 {
2130 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uSel);
2131 if (rcStrict != VINF_SUCCESS)
2132 return rcStrict;
2133 /** @todo check what VT-x and AMD-V does. */
2134 Desc.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
2135 }
2136
2137 /* stack */
2138 if (enmEffOpSize == IEMMODE_16BIT)
2139 {
2140 uPtrRet.pu16[0] = pVCpu->cpum.GstCtx.ip + cbInstr;
2141 uPtrRet.pu16[1] = pVCpu->cpum.GstCtx.cs.Sel;
2142 }
2143 else if (enmEffOpSize == IEMMODE_32BIT)
2144 {
2145 uPtrRet.pu32[0] = pVCpu->cpum.GstCtx.eip + cbInstr;
2146 uPtrRet.pu32[1] = pVCpu->cpum.GstCtx.cs.Sel; /** @todo Testcase: What is written to the high word when callf is pushing CS? */
2147 }
2148 else
2149 {
2150 uPtrRet.pu64[0] = pVCpu->cpum.GstCtx.rip + cbInstr;
2151 uPtrRet.pu64[1] = pVCpu->cpum.GstCtx.cs.Sel; /** @todo Testcase: What is written to the high words when callf is pushing CS? */
2152 }
2153 rcStrict = iemMemStackPushCommitSpecial(pVCpu, bUnmapInfo, uNewRsp);
2154 if (rcStrict != VINF_SUCCESS)
2155 return rcStrict;
2156
2157 /* commit */
2158 pVCpu->cpum.GstCtx.rip = offSeg;
2159 pVCpu->cpum.GstCtx.cs.Sel = uSel & X86_SEL_MASK_OFF_RPL;
2160 pVCpu->cpum.GstCtx.cs.Sel |= IEM_GET_CPL(pVCpu);
2161 pVCpu->cpum.GstCtx.cs.ValidSel = pVCpu->cpum.GstCtx.cs.Sel;
2162 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
2163 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESC_GET_HID_ATTR(&Desc.Legacy);
2164 pVCpu->cpum.GstCtx.cs.u32Limit = cbLimit;
2165 pVCpu->cpum.GstCtx.cs.u64Base = u64Base;
2166
2167 /** @todo check if the hidden bits are loaded correctly for 64-bit
2168 * mode. */
2169
2170 iemRecalcExecModeAndCplFlags(pVCpu);
2171
2172 /* Flush the prefetch buffer. */
2173 IEM_FLUSH_PREFETCH_HEAVY(pVCpu, cbInstr);
2174
2175 return iemRegFinishClearingRF(pVCpu, VINF_SUCCESS);
2176}
2177
2178
2179/**
2180 * Implements retf.
2181 *
2182 * @param enmEffOpSize The effective operand size.
2183 * @param cbPop The amount of arguments to pop from the stack
2184 * (bytes).
2185 */
2186IEM_CIMPL_DEF_2(iemCImpl_retf, IEMMODE, enmEffOpSize, uint16_t, cbPop)
2187{
2188 NOREF(cbInstr);
2189
2190 /*
2191 * Read the stack values first.
2192 */
2193 RTUINT64U NewRsp;
2194 uint8_t bUnmapInfo;
2195 RTCPTRUNION uPtrFrame;
2196 uint32_t cbRetPtr = enmEffOpSize == IEMMODE_16BIT ? 2+2
2197 : enmEffOpSize == IEMMODE_32BIT ? 4+4 : 8+8;
2198 VBOXSTRICTRC rcStrict = iemMemStackPopBeginSpecial(pVCpu, cbRetPtr,
2199 enmEffOpSize == IEMMODE_16BIT ? 1 : enmEffOpSize == IEMMODE_32BIT ? 3 : 7,
2200 &uPtrFrame.pv, &bUnmapInfo, &NewRsp.u);
2201 if (rcStrict != VINF_SUCCESS)
2202 return rcStrict;
2203
2204 uint64_t uNewRip;
2205 uint16_t uNewCs;
2206 if (enmEffOpSize == IEMMODE_16BIT)
2207 {
2208 uNewRip = uPtrFrame.pu16[0];
2209 uNewCs = uPtrFrame.pu16[1];
2210 }
2211 else if (enmEffOpSize == IEMMODE_32BIT)
2212 {
2213 uNewRip = uPtrFrame.pu32[0];
2214 uNewCs = uPtrFrame.pu16[2];
2215 }
2216 else
2217 {
2218 uNewRip = uPtrFrame.pu64[0];
2219 uNewCs = uPtrFrame.pu16[4];
2220 }
2221
2222 rcStrict = iemMemStackPopDoneSpecial(pVCpu, bUnmapInfo);
2223 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
2224 { /* extremely likely */ }
2225 else
2226 return rcStrict;
2227
2228 /*
2229 * Real mode and V8086 mode are easy.
2230 */
2231 /** @todo See comment for similar code in iemCImpl_FarJmp */
2232 if (IEM_IS_REAL_OR_V86_MODE(pVCpu))
2233 {
2234 Assert(enmEffOpSize == IEMMODE_32BIT || enmEffOpSize == IEMMODE_16BIT);
2235 /** @todo check how this is supposed to work if sp=0xfffe. */
2236
2237 /* Check the limit of the new EIP. */
2238 /** @todo Intel pseudo code only does the limit check for 16-bit
2239 * operands, AMD does not make any distinction. What is right? */
2240 if (uNewRip > pVCpu->cpum.GstCtx.cs.u32Limit)
2241 return iemRaiseSelectorBounds(pVCpu, X86_SREG_CS, IEM_ACCESS_INSTRUCTION);
2242
2243 /* commit the operation. */
2244 if (cbPop)
2245 iemRegAddToRspEx(pVCpu, &NewRsp, cbPop);
2246 pVCpu->cpum.GstCtx.rsp = NewRsp.u;
2247 pVCpu->cpum.GstCtx.rip = uNewRip;
2248 pVCpu->cpum.GstCtx.cs.Sel = uNewCs;
2249 pVCpu->cpum.GstCtx.cs.ValidSel = uNewCs;
2250 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
2251 pVCpu->cpum.GstCtx.cs.u64Base = (uint32_t)uNewCs << 4;
2252 return iemRegFinishClearingRF(pVCpu, VINF_SUCCESS);
2253 }
2254
2255 /*
2256 * Protected mode is complicated, of course.
2257 */
2258 if (!(uNewCs & X86_SEL_MASK_OFF_RPL))
2259 {
2260 Log(("retf %04x:%08RX64 -> invalid selector, #GP(0)\n", uNewCs, uNewRip));
2261 return iemRaiseGeneralProtectionFault0(pVCpu);
2262 }
2263
2264 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_GDTR | CPUMCTX_EXTRN_LDTR);
2265
2266 /* Fetch the descriptor. */
2267 IEMSELDESC DescCs;
2268 rcStrict = iemMemFetchSelDesc(pVCpu, &DescCs, uNewCs, X86_XCPT_GP);
2269 if (rcStrict != VINF_SUCCESS)
2270 return rcStrict;
2271
2272 /* Can only return to a code selector. */
2273 if ( !DescCs.Legacy.Gen.u1DescType
2274 || !(DescCs.Legacy.Gen.u4Type & X86_SEL_TYPE_CODE) )
2275 {
2276 Log(("retf %04x:%08RX64 -> not a code selector (u1DescType=%u u4Type=%#x).\n",
2277 uNewCs, uNewRip, DescCs.Legacy.Gen.u1DescType, DescCs.Legacy.Gen.u4Type));
2278 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
2279 }
2280
2281 /* L vs D. */
2282 if ( DescCs.Legacy.Gen.u1Long /** @todo Testcase: far return to a selector with both L and D set. */
2283 && DescCs.Legacy.Gen.u1DefBig
2284 && IEM_IS_LONG_MODE(pVCpu))
2285 {
2286 Log(("retf %04x:%08RX64 -> both L & D set.\n", uNewCs, uNewRip));
2287 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
2288 }
2289
2290 /* DPL/RPL/CPL checks. */
2291 if ((uNewCs & X86_SEL_RPL) < IEM_GET_CPL(pVCpu))
2292 {
2293 Log(("retf %04x:%08RX64 -> RPL < CPL(%d).\n", uNewCs, uNewRip, IEM_GET_CPL(pVCpu)));
2294 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
2295 }
2296
2297 if (DescCs.Legacy.Gen.u4Type & X86_SEL_TYPE_CONF)
2298 {
2299 if ((uNewCs & X86_SEL_RPL) < DescCs.Legacy.Gen.u2Dpl)
2300 {
2301 Log(("retf %04x:%08RX64 -> DPL violation (conforming); DPL=%u RPL=%u\n",
2302 uNewCs, uNewRip, DescCs.Legacy.Gen.u2Dpl, (uNewCs & X86_SEL_RPL)));
2303 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
2304 }
2305 }
2306 else
2307 {
2308 if ((uNewCs & X86_SEL_RPL) != DescCs.Legacy.Gen.u2Dpl)
2309 {
2310 Log(("retf %04x:%08RX64 -> RPL != DPL; DPL=%u RPL=%u\n",
2311 uNewCs, uNewRip, DescCs.Legacy.Gen.u2Dpl, (uNewCs & X86_SEL_RPL)));
2312 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
2313 }
2314 }
2315
2316 /* Is it there? */
2317 if (!DescCs.Legacy.Gen.u1Present)
2318 {
2319 Log(("retf %04x:%08RX64 -> segment not present\n", uNewCs, uNewRip));
2320 return iemRaiseSelectorNotPresentBySelector(pVCpu, uNewCs);
2321 }
2322
2323 /*
2324 * Return to outer privilege? (We'll typically have entered via a call gate.)
2325 */
2326 if ((uNewCs & X86_SEL_RPL) != IEM_GET_CPL(pVCpu))
2327 {
2328 /* Read the outer stack pointer stored *after* the parameters. */
2329 rcStrict = iemMemStackPopContinueSpecial(pVCpu, cbPop /*off*/, cbRetPtr, &uPtrFrame.pv, &bUnmapInfo, NewRsp.u);
2330 if (rcStrict != VINF_SUCCESS)
2331 return rcStrict;
2332
2333 uint16_t uNewOuterSs;
2334 RTUINT64U NewOuterRsp;
2335 if (enmEffOpSize == IEMMODE_16BIT)
2336 {
2337 NewOuterRsp.u = uPtrFrame.pu16[0];
2338 uNewOuterSs = uPtrFrame.pu16[1];
2339 }
2340 else if (enmEffOpSize == IEMMODE_32BIT)
2341 {
2342 NewOuterRsp.u = uPtrFrame.pu32[0];
2343 uNewOuterSs = uPtrFrame.pu16[2];
2344 }
2345 else
2346 {
2347 NewOuterRsp.u = uPtrFrame.pu64[0];
2348 uNewOuterSs = uPtrFrame.pu16[4];
2349 }
2350 rcStrict = iemMemStackPopDoneSpecial(pVCpu, bUnmapInfo);
2351 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
2352 { /* extremely likely */ }
2353 else
2354 return rcStrict;
2355
2356 /* Check for NULL stack selector (invalid in ring-3 and non-long mode)
2357 and read the selector. */
2358 IEMSELDESC DescSs;
2359 if (!(uNewOuterSs & X86_SEL_MASK_OFF_RPL))
2360 {
2361 if ( !DescCs.Legacy.Gen.u1Long
2362 || (uNewOuterSs & X86_SEL_RPL) == 3)
2363 {
2364 Log(("retf %04x:%08RX64 %04x:%08RX64 -> invalid stack selector, #GP\n",
2365 uNewCs, uNewRip, uNewOuterSs, NewOuterRsp.u));
2366 return iemRaiseGeneralProtectionFault0(pVCpu);
2367 }
2368 /** @todo Testcase: Return far to ring-1 or ring-2 with SS=0. */
2369 iemMemFakeStackSelDesc(&DescSs, (uNewOuterSs & X86_SEL_RPL));
2370 }
2371 else
2372 {
2373 /* Fetch the descriptor for the new stack segment. */
2374 rcStrict = iemMemFetchSelDesc(pVCpu, &DescSs, uNewOuterSs, X86_XCPT_GP);
2375 if (rcStrict != VINF_SUCCESS)
2376 return rcStrict;
2377 }
2378
2379 /* Check that RPL of stack and code selectors match. */
2380 if ((uNewCs & X86_SEL_RPL) != (uNewOuterSs & X86_SEL_RPL))
2381 {
2382 Log(("retf %04x:%08RX64 %04x:%08RX64 - SS.RPL != CS.RPL -> #GP(SS)\n", uNewCs, uNewRip, uNewOuterSs, NewOuterRsp.u));
2383 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewOuterSs);
2384 }
2385
2386 /* Must be a writable data segment. */
2387 if ( !DescSs.Legacy.Gen.u1DescType
2388 || (DescSs.Legacy.Gen.u4Type & X86_SEL_TYPE_CODE)
2389 || !(DescSs.Legacy.Gen.u4Type & X86_SEL_TYPE_WRITE) )
2390 {
2391 Log(("retf %04x:%08RX64 %04x:%08RX64 - SS not a writable data segment (u1DescType=%u u4Type=%#x) -> #GP(SS).\n",
2392 uNewCs, uNewRip, uNewOuterSs, NewOuterRsp.u, DescSs.Legacy.Gen.u1DescType, DescSs.Legacy.Gen.u4Type));
2393 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewOuterSs);
2394 }
2395
2396 /* L vs D. (Not mentioned by intel.) */
2397 if ( DescSs.Legacy.Gen.u1Long /** @todo Testcase: far return to a stack selector with both L and D set. */
2398 && DescSs.Legacy.Gen.u1DefBig
2399 && IEM_IS_LONG_MODE(pVCpu))
2400 {
2401 Log(("retf %04x:%08RX64 %04x:%08RX64 - SS has both L & D set -> #GP(SS).\n",
2402 uNewCs, uNewRip, uNewOuterSs, NewOuterRsp.u));
2403 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewOuterSs);
2404 }
2405
2406 /* DPL/RPL/CPL checks. */
2407 if (DescSs.Legacy.Gen.u2Dpl != (uNewCs & X86_SEL_RPL))
2408 {
2409 Log(("retf %04x:%08RX64 %04x:%08RX64 - SS.DPL(%u) != CS.RPL (%u) -> #GP(SS).\n",
2410 uNewCs, uNewRip, uNewOuterSs, NewOuterRsp.u, DescSs.Legacy.Gen.u2Dpl, uNewCs & X86_SEL_RPL));
2411 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewOuterSs);
2412 }
2413
2414 /* Is it there? */
2415 if (!DescSs.Legacy.Gen.u1Present)
2416 {
2417 Log(("retf %04x:%08RX64 %04x:%08RX64 - SS not present -> #NP(SS).\n", uNewCs, uNewRip, uNewOuterSs, NewOuterRsp.u));
2418 return iemRaiseSelectorNotPresentBySelector(pVCpu, uNewCs);
2419 }
2420
2421 /* Calc SS limit.*/
2422 uint64_t u64BaseSs;
2423 uint32_t cbLimitSs = X86DESC_LIMIT_G(&DescSs.Legacy);
2424
2425 /* Is RIP canonical or within CS.limit? */
2426 uint64_t u64BaseCs;
2427 uint32_t cbLimitCs = X86DESC_LIMIT_G(&DescCs.Legacy);
2428
2429 /** @todo Testcase: Is this correct? */
2430 if ( DescCs.Legacy.Gen.u1Long
2431 && IEM_IS_LONG_MODE(pVCpu) )
2432 {
2433 if (!IEM_IS_CANONICAL(uNewRip))
2434 {
2435 Log(("retf %04x:%08RX64 %04x:%08RX64 - not canonical -> #GP.\n", uNewCs, uNewRip, uNewOuterSs, NewOuterRsp.u));
2436 return iemRaiseNotCanonical(pVCpu);
2437 }
2438 u64BaseCs = 0;
2439 u64BaseSs = 0;
2440 }
2441 else
2442 {
2443 if (uNewRip > cbLimitCs)
2444 {
2445 Log(("retf %04x:%08RX64 %04x:%08RX64 - out of bounds (%#x)-> #GP(CS).\n",
2446 uNewCs, uNewRip, uNewOuterSs, NewOuterRsp.u, cbLimitCs));
2447 /** @todo Intel says this is \#GP(0)! */
2448 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
2449 }
2450 u64BaseCs = X86DESC_BASE(&DescCs.Legacy);
2451 u64BaseSs = X86DESC_BASE(&DescSs.Legacy);
2452 }
2453
2454 /*
2455 * Now set the accessed bit before
2456 * writing the return address to the stack and committing the result into
2457 * CS, CSHID and RIP.
2458 */
2459 /** @todo Testcase: Need to check WHEN exactly the CS accessed bit is set. */
2460 if (!(DescCs.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
2461 {
2462 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uNewCs);
2463 if (rcStrict != VINF_SUCCESS)
2464 return rcStrict;
2465 /** @todo check what VT-x and AMD-V does. */
2466 DescCs.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
2467 }
2468 /** @todo Testcase: Need to check WHEN exactly the SS accessed bit is set. */
2469 if (!(DescSs.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
2470 {
2471 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uNewOuterSs);
2472 if (rcStrict != VINF_SUCCESS)
2473 return rcStrict;
2474 /** @todo check what VT-x and AMD-V does. */
2475 DescSs.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
2476 }
2477
2478 /* commit */
2479 if (enmEffOpSize == IEMMODE_16BIT)
2480 pVCpu->cpum.GstCtx.rip = uNewRip & UINT16_MAX; /** @todo Testcase: When exactly does this occur? With call it happens prior to the limit check according to Intel... */
2481 else
2482 pVCpu->cpum.GstCtx.rip = uNewRip;
2483 pVCpu->cpum.GstCtx.cs.Sel = uNewCs;
2484 pVCpu->cpum.GstCtx.cs.ValidSel = uNewCs;
2485 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
2486 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESC_GET_HID_ATTR(&DescCs.Legacy);
2487 pVCpu->cpum.GstCtx.cs.u32Limit = cbLimitCs;
2488 pVCpu->cpum.GstCtx.cs.u64Base = u64BaseCs;
2489 pVCpu->cpum.GstCtx.ss.Sel = uNewOuterSs;
2490 pVCpu->cpum.GstCtx.ss.ValidSel = uNewOuterSs;
2491 pVCpu->cpum.GstCtx.ss.fFlags = CPUMSELREG_FLAGS_VALID;
2492 pVCpu->cpum.GstCtx.ss.Attr.u = X86DESC_GET_HID_ATTR(&DescSs.Legacy);
2493 pVCpu->cpum.GstCtx.ss.u32Limit = cbLimitSs;
2494 pVCpu->cpum.GstCtx.ss.u64Base = u64BaseSs;
2495
2496 iemHlpAdjustSelectorForNewCpl(pVCpu, uNewCs & X86_SEL_RPL, &pVCpu->cpum.GstCtx.ds);
2497 iemHlpAdjustSelectorForNewCpl(pVCpu, uNewCs & X86_SEL_RPL, &pVCpu->cpum.GstCtx.es);
2498 iemHlpAdjustSelectorForNewCpl(pVCpu, uNewCs & X86_SEL_RPL, &pVCpu->cpum.GstCtx.fs);
2499 iemHlpAdjustSelectorForNewCpl(pVCpu, uNewCs & X86_SEL_RPL, &pVCpu->cpum.GstCtx.gs);
2500
2501 iemRecalcExecModeAndCplFlags(pVCpu); /* Affects iemRegAddToRspEx and the setting of RSP/SP below. */
2502
2503 if (cbPop)
2504 iemRegAddToRspEx(pVCpu, &NewOuterRsp, cbPop);
2505 if (IEM_IS_64BIT_CODE(pVCpu))
2506 pVCpu->cpum.GstCtx.rsp = NewOuterRsp.u;
2507 else if (pVCpu->cpum.GstCtx.ss.Attr.n.u1DefBig)
2508 pVCpu->cpum.GstCtx.rsp = (uint32_t)NewOuterRsp.u;
2509 else
2510 pVCpu->cpum.GstCtx.sp = (uint16_t)NewOuterRsp.u;
2511
2512 iemRecalcExecModeAndCplFlags(pVCpu); /* Affects iemRegAddToRspEx and the setting of RSP/SP below. */
2513
2514 /** @todo check if the hidden bits are loaded correctly for 64-bit
2515 * mode. */
2516 }
2517 /*
2518 * Return to the same privilege level
2519 */
2520 else
2521 {
2522 /* Limit / canonical check. */
2523 uint64_t u64Base;
2524 uint32_t cbLimitCs = X86DESC_LIMIT_G(&DescCs.Legacy);
2525
2526 /** @todo Testcase: Is this correct? */
2527 bool f64BitCs = false;
2528 if ( DescCs.Legacy.Gen.u1Long
2529 && IEM_IS_LONG_MODE(pVCpu) )
2530 {
2531 if (!IEM_IS_CANONICAL(uNewRip))
2532 {
2533 Log(("retf %04x:%08RX64 - not canonical -> #GP\n", uNewCs, uNewRip));
2534 return iemRaiseNotCanonical(pVCpu);
2535 }
2536 u64Base = 0;
2537 f64BitCs = true;
2538 f64BitCs = true;
2539 }
2540 else
2541 {
2542 if (uNewRip > cbLimitCs)
2543 {
2544 Log(("retf %04x:%08RX64 -> out of bounds (%#x)\n", uNewCs, uNewRip, cbLimitCs));
2545 /** @todo Intel says this is \#GP(0)! */
2546 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
2547 }
2548 u64Base = X86DESC_BASE(&DescCs.Legacy);
2549 }
2550
2551 /*
2552 * Now set the accessed bit before
2553 * writing the return address to the stack and committing the result into
2554 * CS, CSHID and RIP.
2555 */
2556 /** @todo Testcase: Need to check WHEN exactly the accessed bit is set. */
2557 if (!(DescCs.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
2558 {
2559 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uNewCs);
2560 if (rcStrict != VINF_SUCCESS)
2561 return rcStrict;
2562 /** @todo check what VT-x and AMD-V does. */
2563 DescCs.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
2564 }
2565
2566 /* commit */
2567 if (cbPop)
2568/** @todo This cannot be right. We're using the old CS mode here, and iemRegAddToRspEx checks fExec. */
2569 iemRegAddToRspEx(pVCpu, &NewRsp, cbPop);
2570 if (pVCpu->cpum.GstCtx.ss.Attr.n.u1DefBig || f64BitCs)
2571 pVCpu->cpum.GstCtx.rsp = NewRsp.u;
2572 else
2573 pVCpu->cpum.GstCtx.sp = (uint16_t)NewRsp.u;
2574 if (enmEffOpSize == IEMMODE_16BIT)
2575 pVCpu->cpum.GstCtx.rip = uNewRip & UINT16_MAX; /** @todo Testcase: When exactly does this occur? With call it happens prior to the limit check according to Intel... */
2576 else
2577 pVCpu->cpum.GstCtx.rip = uNewRip;
2578 pVCpu->cpum.GstCtx.cs.Sel = uNewCs;
2579 pVCpu->cpum.GstCtx.cs.ValidSel = uNewCs;
2580 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
2581 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESC_GET_HID_ATTR(&DescCs.Legacy);
2582 pVCpu->cpum.GstCtx.cs.u32Limit = cbLimitCs;
2583 pVCpu->cpum.GstCtx.cs.u64Base = u64Base;
2584 /** @todo check if the hidden bits are loaded correctly for 64-bit
2585 * mode. */
2586
2587 iemRecalcExecModeAndCplFlags(pVCpu);
2588 }
2589
2590 /* Flush the prefetch buffer. */
2591 IEM_FLUSH_PREFETCH_HEAVY(pVCpu, cbInstr); /** @todo use light flush for same privilege? */
2592
2593 return iemRegFinishClearingRF(pVCpu, VINF_SUCCESS);
2594}
2595
2596
2597/**
2598 * Implements enter.
2599 *
2600 * We're doing this in C because the instruction is insane, even for the
2601 * u8NestingLevel=0 case dealing with the stack is tedious.
2602 *
2603 * @param enmEffOpSize The effective operand size.
2604 * @param cbFrame Frame size.
2605 * @param cParameters Frame parameter count.
2606 */
2607IEM_CIMPL_DEF_3(iemCImpl_enter, IEMMODE, enmEffOpSize, uint16_t, cbFrame, uint8_t, cParameters)
2608{
2609 /* Push RBP, saving the old value in TmpRbp. */
2610 RTUINT64U NewRsp; NewRsp.u = pVCpu->cpum.GstCtx.rsp;
2611 RTUINT64U TmpRbp; TmpRbp.u = pVCpu->cpum.GstCtx.rbp;
2612 RTUINT64U NewRbp;
2613 VBOXSTRICTRC rcStrict;
2614 if (enmEffOpSize == IEMMODE_64BIT)
2615 {
2616 rcStrict = iemMemStackPushU64Ex(pVCpu, TmpRbp.u, &NewRsp);
2617 NewRbp = NewRsp;
2618 }
2619 else if (enmEffOpSize == IEMMODE_32BIT)
2620 {
2621 rcStrict = iemMemStackPushU32Ex(pVCpu, TmpRbp.DWords.dw0, &NewRsp);
2622 NewRbp = NewRsp;
2623 }
2624 else
2625 {
2626 rcStrict = iemMemStackPushU16Ex(pVCpu, TmpRbp.Words.w0, &NewRsp);
2627 NewRbp = TmpRbp;
2628 NewRbp.Words.w0 = NewRsp.Words.w0;
2629 }
2630 if (rcStrict != VINF_SUCCESS)
2631 return rcStrict;
2632
2633 /* Copy the parameters (aka nesting levels by Intel). */
2634 cParameters &= 0x1f;
2635 if (cParameters > 0)
2636 {
2637 switch (enmEffOpSize)
2638 {
2639 case IEMMODE_16BIT:
2640 if (pVCpu->cpum.GstCtx.ss.Attr.n.u1DefBig)
2641 TmpRbp.DWords.dw0 -= 2;
2642 else
2643 TmpRbp.Words.w0 -= 2;
2644 do
2645 {
2646 uint16_t u16Tmp;
2647 rcStrict = iemMemStackPopU16Ex(pVCpu, &u16Tmp, &TmpRbp);
2648 if (rcStrict != VINF_SUCCESS)
2649 break;
2650 rcStrict = iemMemStackPushU16Ex(pVCpu, u16Tmp, &NewRsp);
2651 } while (--cParameters > 0 && rcStrict == VINF_SUCCESS);
2652 break;
2653
2654 case IEMMODE_32BIT:
2655 if (pVCpu->cpum.GstCtx.ss.Attr.n.u1DefBig)
2656 TmpRbp.DWords.dw0 -= 4;
2657 else
2658 TmpRbp.Words.w0 -= 4;
2659 do
2660 {
2661 uint32_t u32Tmp;
2662 rcStrict = iemMemStackPopU32Ex(pVCpu, &u32Tmp, &TmpRbp);
2663 if (rcStrict != VINF_SUCCESS)
2664 break;
2665 rcStrict = iemMemStackPushU32Ex(pVCpu, u32Tmp, &NewRsp);
2666 } while (--cParameters > 0 && rcStrict == VINF_SUCCESS);
2667 break;
2668
2669 case IEMMODE_64BIT:
2670 TmpRbp.u -= 8;
2671 do
2672 {
2673 uint64_t u64Tmp;
2674 rcStrict = iemMemStackPopU64Ex(pVCpu, &u64Tmp, &TmpRbp);
2675 if (rcStrict != VINF_SUCCESS)
2676 break;
2677 rcStrict = iemMemStackPushU64Ex(pVCpu, u64Tmp, &NewRsp);
2678 } while (--cParameters > 0 && rcStrict == VINF_SUCCESS);
2679 break;
2680
2681 IEM_NOT_REACHED_DEFAULT_CASE_RET();
2682 }
2683 if (rcStrict != VINF_SUCCESS)
2684 return VINF_SUCCESS;
2685
2686 /* Push the new RBP */
2687 if (enmEffOpSize == IEMMODE_64BIT)
2688 rcStrict = iemMemStackPushU64Ex(pVCpu, NewRbp.u, &NewRsp);
2689 else if (enmEffOpSize == IEMMODE_32BIT)
2690 rcStrict = iemMemStackPushU32Ex(pVCpu, NewRbp.DWords.dw0, &NewRsp);
2691 else
2692 rcStrict = iemMemStackPushU16Ex(pVCpu, NewRbp.Words.w0, &NewRsp);
2693 if (rcStrict != VINF_SUCCESS)
2694 return rcStrict;
2695
2696 }
2697
2698 /* Recalc RSP. */
2699 iemRegSubFromRspEx(pVCpu, &NewRsp, cbFrame);
2700
2701 /** @todo Should probe write access at the new RSP according to AMD. */
2702 /** @todo Should handle accesses to the VMX APIC-access page. */
2703
2704 /* Commit it. */
2705 pVCpu->cpum.GstCtx.rbp = NewRbp.u;
2706 pVCpu->cpum.GstCtx.rsp = NewRsp.u;
2707 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
2708}
2709
2710
2711
2712/**
2713 * Implements leave.
2714 *
2715 * We're doing this in C because messing with the stack registers is annoying
2716 * since they depends on SS attributes.
2717 *
2718 * @param enmEffOpSize The effective operand size.
2719 */
2720IEM_CIMPL_DEF_1(iemCImpl_leave, IEMMODE, enmEffOpSize)
2721{
2722 /* Calculate the intermediate RSP from RBP and the stack attributes. */
2723 RTUINT64U NewRsp;
2724 if (IEM_IS_64BIT_CODE(pVCpu))
2725 NewRsp.u = pVCpu->cpum.GstCtx.rbp;
2726 else if (pVCpu->cpum.GstCtx.ss.Attr.n.u1DefBig)
2727 NewRsp.u = pVCpu->cpum.GstCtx.ebp;
2728 else
2729 {
2730 /** @todo Check that LEAVE actually preserve the high EBP bits. */
2731 NewRsp.u = pVCpu->cpum.GstCtx.rsp;
2732 NewRsp.Words.w0 = pVCpu->cpum.GstCtx.bp;
2733 }
2734
2735 /* Pop RBP according to the operand size. */
2736 VBOXSTRICTRC rcStrict;
2737 RTUINT64U NewRbp;
2738 switch (enmEffOpSize)
2739 {
2740 case IEMMODE_16BIT:
2741 NewRbp.u = pVCpu->cpum.GstCtx.rbp;
2742 rcStrict = iemMemStackPopU16Ex(pVCpu, &NewRbp.Words.w0, &NewRsp);
2743 break;
2744 case IEMMODE_32BIT:
2745 NewRbp.u = 0;
2746 rcStrict = iemMemStackPopU32Ex(pVCpu, &NewRbp.DWords.dw0, &NewRsp);
2747 break;
2748 case IEMMODE_64BIT:
2749 rcStrict = iemMemStackPopU64Ex(pVCpu, &NewRbp.u, &NewRsp);
2750 break;
2751 IEM_NOT_REACHED_DEFAULT_CASE_RET();
2752 }
2753 if (rcStrict != VINF_SUCCESS)
2754 return rcStrict;
2755
2756
2757 /* Commit it. */
2758 pVCpu->cpum.GstCtx.rbp = NewRbp.u;
2759 pVCpu->cpum.GstCtx.rsp = NewRsp.u;
2760 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
2761}
2762
2763
2764/**
2765 * Implements int3 and int XX.
2766 *
2767 * @param u8Int The interrupt vector number.
2768 * @param enmInt The int instruction type.
2769 */
2770IEM_CIMPL_DEF_2(iemCImpl_int, uint8_t, u8Int, IEMINT, enmInt)
2771{
2772 Assert(pVCpu->iem.s.cXcptRecursions == 0);
2773
2774 /*
2775 * We must check if this INT3 might belong to DBGF before raising a #BP.
2776 */
2777 if (u8Int == 3)
2778 {
2779 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
2780 if (pVM->dbgf.ro.cEnabledInt3Breakpoints == 0)
2781 { /* likely: No vbox debugger breakpoints */ }
2782 else
2783 {
2784 VBOXSTRICTRC rcStrict = DBGFTrap03Handler(pVM, pVCpu, &pVCpu->cpum.GstCtx);
2785 Log(("iemCImpl_int: DBGFTrap03Handler -> %Rrc\n", VBOXSTRICTRC_VAL(rcStrict) ));
2786 if (rcStrict != VINF_EM_RAW_GUEST_TRAP)
2787 return iemSetPassUpStatus(pVCpu, rcStrict);
2788 }
2789 }
2790/** @todo single stepping */
2791 return iemRaiseXcptOrInt(pVCpu,
2792 cbInstr,
2793 u8Int,
2794 IEM_XCPT_FLAGS_T_SOFT_INT | enmInt,
2795 0,
2796 0);
2797}
2798
2799
2800/**
2801 * Implements iret for real mode and V8086 mode.
2802 *
2803 * @param enmEffOpSize The effective operand size.
2804 */
2805IEM_CIMPL_DEF_1(iemCImpl_iret_real_v8086, IEMMODE, enmEffOpSize)
2806{
2807 X86EFLAGS Efl;
2808 Efl.u = IEMMISC_GET_EFL(pVCpu);
2809 NOREF(cbInstr);
2810
2811 /*
2812 * iret throws an exception if VME isn't enabled.
2813 */
2814 if ( Efl.Bits.u1VM
2815 && Efl.Bits.u2IOPL != 3
2816 && !(pVCpu->cpum.GstCtx.cr4 & X86_CR4_VME))
2817 return iemRaiseGeneralProtectionFault0(pVCpu);
2818
2819 /*
2820 * Do the stack bits, but don't commit RSP before everything checks
2821 * out right.
2822 */
2823 Assert(enmEffOpSize == IEMMODE_32BIT || enmEffOpSize == IEMMODE_16BIT);
2824 VBOXSTRICTRC rcStrict;
2825 uint8_t bUnmapInfo;
2826 RTCPTRUNION uFrame;
2827 uint16_t uNewCs;
2828 uint32_t uNewEip;
2829 uint32_t uNewFlags;
2830 uint64_t uNewRsp;
2831 if (enmEffOpSize == IEMMODE_32BIT)
2832 {
2833 rcStrict = iemMemStackPopBeginSpecial(pVCpu, 12, 1, &uFrame.pv, &bUnmapInfo, &uNewRsp);
2834 if (rcStrict != VINF_SUCCESS)
2835 return rcStrict;
2836 uNewEip = uFrame.pu32[0];
2837 if (uNewEip > UINT16_MAX)
2838 return iemRaiseGeneralProtectionFault0(pVCpu);
2839
2840 uNewCs = (uint16_t)uFrame.pu32[1];
2841 uNewFlags = uFrame.pu32[2];
2842 uNewFlags &= X86_EFL_CF | X86_EFL_PF | X86_EFL_AF | X86_EFL_ZF | X86_EFL_SF
2843 | X86_EFL_TF | X86_EFL_IF | X86_EFL_DF | X86_EFL_OF | X86_EFL_IOPL | X86_EFL_NT
2844 | X86_EFL_RF /*| X86_EFL_VM*/ | X86_EFL_AC /*|X86_EFL_VIF*/ /*|X86_EFL_VIP*/
2845 | X86_EFL_ID;
2846 if (IEM_GET_TARGET_CPU(pVCpu) <= IEMTARGETCPU_386)
2847 uNewFlags &= ~(X86_EFL_AC | X86_EFL_ID | X86_EFL_VIF | X86_EFL_VIP);
2848 uNewFlags |= Efl.u & (X86_EFL_VM | X86_EFL_VIF | X86_EFL_VIP | X86_EFL_1);
2849 }
2850 else
2851 {
2852 rcStrict = iemMemStackPopBeginSpecial(pVCpu, 6, 1, &uFrame.pv, &bUnmapInfo, &uNewRsp);
2853 if (rcStrict != VINF_SUCCESS)
2854 return rcStrict;
2855 uNewEip = uFrame.pu16[0];
2856 uNewCs = uFrame.pu16[1];
2857 uNewFlags = uFrame.pu16[2];
2858 uNewFlags &= X86_EFL_CF | X86_EFL_PF | X86_EFL_AF | X86_EFL_ZF | X86_EFL_SF
2859 | X86_EFL_TF | X86_EFL_IF | X86_EFL_DF | X86_EFL_OF | X86_EFL_IOPL | X86_EFL_NT;
2860 uNewFlags |= Efl.u & ((UINT32_C(0xffff0000) | X86_EFL_1) & ~X86_EFL_RF);
2861 /** @todo The intel pseudo code does not indicate what happens to
2862 * reserved flags. We just ignore them. */
2863 /* Ancient CPU adjustments: See iemCImpl_popf. */
2864 if (IEM_GET_TARGET_CPU(pVCpu) == IEMTARGETCPU_286)
2865 uNewFlags &= ~(X86_EFL_NT | X86_EFL_IOPL);
2866 }
2867 rcStrict = iemMemStackPopDoneSpecial(pVCpu, bUnmapInfo);
2868 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
2869 { /* extremely likely */ }
2870 else
2871 return rcStrict;
2872
2873 /** @todo Check how this is supposed to work if sp=0xfffe. */
2874 Log7(("iemCImpl_iret_real_v8086: uNewCs=%#06x uNewRip=%#010x uNewFlags=%#x uNewRsp=%#18llx\n",
2875 uNewCs, uNewEip, uNewFlags, uNewRsp));
2876
2877 /*
2878 * Check the limit of the new EIP.
2879 */
2880 /** @todo Only the AMD pseudo code check the limit here, what's
2881 * right? */
2882 if (uNewEip > pVCpu->cpum.GstCtx.cs.u32Limit)
2883 return iemRaiseSelectorBounds(pVCpu, X86_SREG_CS, IEM_ACCESS_INSTRUCTION);
2884
2885 /*
2886 * V8086 checks and flag adjustments
2887 */
2888 if (Efl.Bits.u1VM)
2889 {
2890 if (Efl.Bits.u2IOPL == 3)
2891 {
2892 /* Preserve IOPL and clear RF. */
2893 uNewFlags &= ~(X86_EFL_IOPL | X86_EFL_RF);
2894 uNewFlags |= Efl.u & (X86_EFL_IOPL);
2895 }
2896 else if ( enmEffOpSize == IEMMODE_16BIT
2897 && ( !(uNewFlags & X86_EFL_IF)
2898 || !Efl.Bits.u1VIP )
2899 && !(uNewFlags & X86_EFL_TF) )
2900 {
2901 /* Move IF to VIF, clear RF and preserve IF and IOPL.*/
2902 uNewFlags &= ~X86_EFL_VIF;
2903 uNewFlags |= (uNewFlags & X86_EFL_IF) << (19 - 9);
2904 uNewFlags &= ~(X86_EFL_IF | X86_EFL_IOPL | X86_EFL_RF);
2905 uNewFlags |= Efl.u & (X86_EFL_IF | X86_EFL_IOPL);
2906 }
2907 else
2908 return iemRaiseGeneralProtectionFault0(pVCpu);
2909 Log7(("iemCImpl_iret_real_v8086: u1VM=1: adjusted uNewFlags=%#x\n", uNewFlags));
2910 }
2911
2912 /*
2913 * Commit the operation.
2914 */
2915#ifdef DBGFTRACE_ENABLED
2916 RTTraceBufAddMsgF(pVCpu->CTX_SUFF(pVM)->CTX_SUFF(hTraceBuf), "iret/rm %04x:%04x -> %04x:%04x %x %04llx",
2917 pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip, uNewCs, uNewEip, uNewFlags, uNewRsp);
2918#endif
2919 pVCpu->cpum.GstCtx.rsp = uNewRsp;
2920 pVCpu->cpum.GstCtx.rip = uNewEip;
2921 pVCpu->cpum.GstCtx.cs.Sel = uNewCs;
2922 pVCpu->cpum.GstCtx.cs.ValidSel = uNewCs;
2923 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
2924 pVCpu->cpum.GstCtx.cs.u64Base = (uint32_t)uNewCs << 4;
2925 /** @todo do we load attribs and limit as well? */
2926 Assert(uNewFlags & X86_EFL_1);
2927 IEMMISC_SET_EFL(pVCpu, uNewFlags);
2928
2929 /* Flush the prefetch buffer. */
2930 IEM_FLUSH_PREFETCH_HEAVY(pVCpu, cbInstr); /** @todo can do light flush in real mode at least */
2931
2932/** @todo single stepping */
2933 return VINF_SUCCESS;
2934}
2935
2936
2937/**
2938 * Loads a segment register when entering V8086 mode.
2939 *
2940 * @param pSReg The segment register.
2941 * @param uSeg The segment to load.
2942 */
2943static void iemCImplCommonV8086LoadSeg(PCPUMSELREG pSReg, uint16_t uSeg)
2944{
2945 pSReg->Sel = uSeg;
2946 pSReg->ValidSel = uSeg;
2947 pSReg->fFlags = CPUMSELREG_FLAGS_VALID;
2948 pSReg->u64Base = (uint32_t)uSeg << 4;
2949 pSReg->u32Limit = 0xffff;
2950 pSReg->Attr.u = X86_SEL_TYPE_RW_ACC | RT_BIT(4) /*!sys*/ | RT_BIT(7) /*P*/ | (3 /*DPL*/ << 5); /* VT-x wants 0xf3 */
2951 /** @todo Testcase: Check if VT-x really needs this and what it does itself when
2952 * IRET'ing to V8086. */
2953}
2954
2955
2956/**
2957 * Implements iret for protected mode returning to V8086 mode.
2958 *
2959 * @param uNewEip The new EIP.
2960 * @param uNewCs The new CS.
2961 * @param uNewFlags The new EFLAGS.
2962 * @param uNewRsp The RSP after the initial IRET frame.
2963 *
2964 * @note This can only be a 32-bit iret du to the X86_EFL_VM position.
2965 */
2966IEM_CIMPL_DEF_4(iemCImpl_iret_prot_v8086, uint32_t, uNewEip, uint16_t, uNewCs, uint32_t, uNewFlags, uint64_t, uNewRsp)
2967{
2968 RT_NOREF_PV(cbInstr);
2969 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_SREG_MASK);
2970
2971 /*
2972 * Pop the V8086 specific frame bits off the stack.
2973 */
2974 uint8_t bUnmapInfo;
2975 RTCPTRUNION uFrame;
2976 VBOXSTRICTRC rcStrict = iemMemStackPopContinueSpecial(pVCpu, 0 /*off*/, 24 /*cbMem*/, &uFrame.pv, &bUnmapInfo, uNewRsp);
2977 if (rcStrict != VINF_SUCCESS)
2978 return rcStrict;
2979 uint32_t uNewEsp = uFrame.pu32[0];
2980 uint16_t uNewSs = uFrame.pu32[1];
2981 uint16_t uNewEs = uFrame.pu32[2];
2982 uint16_t uNewDs = uFrame.pu32[3];
2983 uint16_t uNewFs = uFrame.pu32[4];
2984 uint16_t uNewGs = uFrame.pu32[5];
2985 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo); /* don't use iemMemStackPopCommitSpecial here. */
2986 if (rcStrict != VINF_SUCCESS)
2987 return rcStrict;
2988
2989 /*
2990 * Commit the operation.
2991 */
2992 uNewFlags &= X86_EFL_LIVE_MASK;
2993 uNewFlags |= X86_EFL_RA1_MASK;
2994#ifdef DBGFTRACE_ENABLED
2995 RTTraceBufAddMsgF(pVCpu->CTX_SUFF(pVM)->CTX_SUFF(hTraceBuf), "iret/p/v %04x:%08x -> %04x:%04x %x %04x:%04x",
2996 pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip, uNewCs, uNewEip, uNewFlags, uNewSs, uNewEsp);
2997#endif
2998 Log7(("iemCImpl_iret_prot_v8086: %04x:%08x -> %04x:%04x %x %04x:%04x\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip, uNewCs, uNewEip, uNewFlags, uNewSs, uNewEsp));
2999
3000 IEMMISC_SET_EFL(pVCpu, uNewFlags);
3001 iemCImplCommonV8086LoadSeg(&pVCpu->cpum.GstCtx.cs, uNewCs);
3002 iemCImplCommonV8086LoadSeg(&pVCpu->cpum.GstCtx.ss, uNewSs);
3003 iemCImplCommonV8086LoadSeg(&pVCpu->cpum.GstCtx.es, uNewEs);
3004 iemCImplCommonV8086LoadSeg(&pVCpu->cpum.GstCtx.ds, uNewDs);
3005 iemCImplCommonV8086LoadSeg(&pVCpu->cpum.GstCtx.fs, uNewFs);
3006 iemCImplCommonV8086LoadSeg(&pVCpu->cpum.GstCtx.gs, uNewGs);
3007 pVCpu->cpum.GstCtx.rip = (uint16_t)uNewEip;
3008 pVCpu->cpum.GstCtx.rsp = uNewEsp; /** @todo check this out! */
3009 pVCpu->iem.s.fExec = (pVCpu->iem.s.fExec & ~(IEM_F_MODE_MASK | IEM_F_X86_CPL_MASK))
3010 | (3 << IEM_F_X86_CPL_SHIFT)
3011 | IEM_F_MODE_X86_16BIT_PROT_V86;
3012
3013 /* Flush the prefetch buffer. */
3014 IEM_FLUSH_PREFETCH_HEAVY(pVCpu, cbInstr);
3015
3016/** @todo single stepping */
3017 return VINF_SUCCESS;
3018}
3019
3020
3021/**
3022 * Implements iret for protected mode returning via a nested task.
3023 *
3024 * @param enmEffOpSize The effective operand size.
3025 */
3026IEM_CIMPL_DEF_1(iemCImpl_iret_prot_NestedTask, IEMMODE, enmEffOpSize)
3027{
3028 Log7(("iemCImpl_iret_prot_NestedTask:\n"));
3029#ifndef IEM_IMPLEMENTS_TASKSWITCH
3030 IEM_RETURN_ASPECT_NOT_IMPLEMENTED();
3031#else
3032 RT_NOREF_PV(enmEffOpSize);
3033
3034 /*
3035 * Read the segment selector in the link-field of the current TSS.
3036 */
3037 RTSEL uSelRet;
3038 VBOXSTRICTRC rcStrict = iemMemFetchSysU16(pVCpu, &uSelRet, UINT8_MAX, pVCpu->cpum.GstCtx.tr.u64Base);
3039 if (rcStrict != VINF_SUCCESS)
3040 return rcStrict;
3041
3042 /*
3043 * Fetch the returning task's TSS descriptor from the GDT.
3044 */
3045 if (uSelRet & X86_SEL_LDT)
3046 {
3047 Log(("iret_prot_NestedTask TSS not in LDT. uSelRet=%04x -> #TS\n", uSelRet));
3048 return iemRaiseTaskSwitchFaultBySelector(pVCpu, uSelRet);
3049 }
3050
3051 IEMSELDESC TssDesc;
3052 rcStrict = iemMemFetchSelDesc(pVCpu, &TssDesc, uSelRet, X86_XCPT_GP);
3053 if (rcStrict != VINF_SUCCESS)
3054 return rcStrict;
3055
3056 if (TssDesc.Legacy.Gate.u1DescType)
3057 {
3058 Log(("iret_prot_NestedTask Invalid TSS type. uSelRet=%04x -> #TS\n", uSelRet));
3059 return iemRaiseTaskSwitchFaultBySelector(pVCpu, uSelRet & X86_SEL_MASK_OFF_RPL);
3060 }
3061
3062 if ( TssDesc.Legacy.Gate.u4Type != X86_SEL_TYPE_SYS_286_TSS_BUSY
3063 && TssDesc.Legacy.Gate.u4Type != X86_SEL_TYPE_SYS_386_TSS_BUSY)
3064 {
3065 Log(("iret_prot_NestedTask TSS is not busy. uSelRet=%04x DescType=%#x -> #TS\n", uSelRet, TssDesc.Legacy.Gate.u4Type));
3066 return iemRaiseTaskSwitchFaultBySelector(pVCpu, uSelRet & X86_SEL_MASK_OFF_RPL);
3067 }
3068
3069 if (!TssDesc.Legacy.Gate.u1Present)
3070 {
3071 Log(("iret_prot_NestedTask TSS is not present. uSelRet=%04x -> #NP\n", uSelRet));
3072 return iemRaiseSelectorNotPresentBySelector(pVCpu, uSelRet & X86_SEL_MASK_OFF_RPL);
3073 }
3074
3075 uint32_t uNextEip = pVCpu->cpum.GstCtx.eip + cbInstr;
3076 return iemTaskSwitch(pVCpu, IEMTASKSWITCH_IRET, uNextEip, 0 /* fFlags */, 0 /* uErr */,
3077 0 /* uCr2 */, uSelRet, &TssDesc);
3078#endif
3079}
3080
3081
3082/**
3083 * Implements iret for protected mode
3084 *
3085 * @param enmEffOpSize The effective operand size.
3086 */
3087IEM_CIMPL_DEF_1(iemCImpl_iret_prot, IEMMODE, enmEffOpSize)
3088{
3089 NOREF(cbInstr);
3090 Assert(enmEffOpSize == IEMMODE_32BIT || enmEffOpSize == IEMMODE_16BIT);
3091
3092 /*
3093 * Nested task return.
3094 */
3095 if (pVCpu->cpum.GstCtx.eflags.Bits.u1NT)
3096 return IEM_CIMPL_CALL_1(iemCImpl_iret_prot_NestedTask, enmEffOpSize);
3097
3098 /*
3099 * Normal return.
3100 *
3101 * Do the stack bits, but don't commit RSP before everything checks
3102 * out right.
3103 */
3104 Assert(enmEffOpSize == IEMMODE_32BIT || enmEffOpSize == IEMMODE_16BIT);
3105 uint8_t bUnmapInfo;
3106 VBOXSTRICTRC rcStrict;
3107 RTCPTRUNION uFrame;
3108 uint16_t uNewCs;
3109 uint32_t uNewEip;
3110 uint32_t uNewFlags;
3111 uint64_t uNewRsp;
3112 if (enmEffOpSize == IEMMODE_32BIT)
3113 {
3114 rcStrict = iemMemStackPopBeginSpecial(pVCpu, 12, 3, &uFrame.pv, &bUnmapInfo, &uNewRsp);
3115 if (rcStrict != VINF_SUCCESS)
3116 return rcStrict;
3117 uNewEip = uFrame.pu32[0];
3118 uNewCs = (uint16_t)uFrame.pu32[1];
3119 uNewFlags = uFrame.pu32[2];
3120 }
3121 else
3122 {
3123 rcStrict = iemMemStackPopBeginSpecial(pVCpu, 6, 1, &uFrame.pv, &bUnmapInfo, &uNewRsp);
3124 if (rcStrict != VINF_SUCCESS)
3125 return rcStrict;
3126 uNewEip = uFrame.pu16[0];
3127 uNewCs = uFrame.pu16[1];
3128 uNewFlags = uFrame.pu16[2];
3129 }
3130 rcStrict = iemMemStackPopDoneSpecial(pVCpu, bUnmapInfo); /* don't use iemMemStackPopCommitSpecial here. */
3131 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
3132 { /* extremely likely */ }
3133 else
3134 return rcStrict;
3135 Log7(("iemCImpl_iret_prot: uNewCs=%#06x uNewEip=%#010x uNewFlags=%#x uNewRsp=%#18llx uCpl=%u\n", uNewCs, uNewEip, uNewFlags, uNewRsp, IEM_GET_CPL(pVCpu)));
3136
3137 /*
3138 * We're hopefully not returning to V8086 mode...
3139 */
3140 if ( (uNewFlags & X86_EFL_VM)
3141 && IEM_GET_CPL(pVCpu) == 0)
3142 {
3143 Assert(enmEffOpSize == IEMMODE_32BIT);
3144 return IEM_CIMPL_CALL_4(iemCImpl_iret_prot_v8086, uNewEip, uNewCs, uNewFlags, uNewRsp);
3145 }
3146
3147 /*
3148 * Protected mode.
3149 */
3150 /* Read the CS descriptor. */
3151 if (!(uNewCs & X86_SEL_MASK_OFF_RPL))
3152 {
3153 Log(("iret %04x:%08x -> invalid CS selector, #GP(0)\n", uNewCs, uNewEip));
3154 return iemRaiseGeneralProtectionFault0(pVCpu);
3155 }
3156
3157 IEMSELDESC DescCS;
3158 rcStrict = iemMemFetchSelDesc(pVCpu, &DescCS, uNewCs, X86_XCPT_GP);
3159 if (rcStrict != VINF_SUCCESS)
3160 {
3161 Log(("iret %04x:%08x - rcStrict=%Rrc when fetching CS\n", uNewCs, uNewEip, VBOXSTRICTRC_VAL(rcStrict)));
3162 return rcStrict;
3163 }
3164
3165 /* Must be a code descriptor. */
3166 if (!DescCS.Legacy.Gen.u1DescType)
3167 {
3168 Log(("iret %04x:%08x - CS is system segment (%#x) -> #GP\n", uNewCs, uNewEip, DescCS.Legacy.Gen.u4Type));
3169 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
3170 }
3171 if (!(DescCS.Legacy.Gen.u4Type & X86_SEL_TYPE_CODE))
3172 {
3173 Log(("iret %04x:%08x - not code segment (%#x) -> #GP\n", uNewCs, uNewEip, DescCS.Legacy.Gen.u4Type));
3174 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
3175 }
3176
3177 /* Privilege checks. */
3178 if (!(DescCS.Legacy.Gen.u4Type & X86_SEL_TYPE_CONF))
3179 {
3180 if ((uNewCs & X86_SEL_RPL) != DescCS.Legacy.Gen.u2Dpl)
3181 {
3182 Log(("iret %04x:%08x - RPL != DPL (%d) -> #GP\n", uNewCs, uNewEip, DescCS.Legacy.Gen.u2Dpl));
3183 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
3184 }
3185 }
3186 else if ((uNewCs & X86_SEL_RPL) < DescCS.Legacy.Gen.u2Dpl)
3187 {
3188 Log(("iret %04x:%08x - RPL < DPL (%d) -> #GP\n", uNewCs, uNewEip, DescCS.Legacy.Gen.u2Dpl));
3189 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
3190 }
3191 if ((uNewCs & X86_SEL_RPL) < IEM_GET_CPL(pVCpu))
3192 {
3193 Log(("iret %04x:%08x - RPL < CPL (%d) -> #GP\n", uNewCs, uNewEip, IEM_GET_CPL(pVCpu)));
3194 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
3195 }
3196
3197 /* Present? */
3198 if (!DescCS.Legacy.Gen.u1Present)
3199 {
3200 Log(("iret %04x:%08x - CS not present -> #NP\n", uNewCs, uNewEip));
3201 return iemRaiseSelectorNotPresentBySelector(pVCpu, uNewCs);
3202 }
3203
3204 uint32_t cbLimitCS = X86DESC_LIMIT_G(&DescCS.Legacy);
3205
3206 /*
3207 * Return to outer level?
3208 */
3209 if ((uNewCs & X86_SEL_RPL) != IEM_GET_CPL(pVCpu))
3210 {
3211 uint16_t uNewSS;
3212 uint32_t uNewESP;
3213 if (enmEffOpSize == IEMMODE_32BIT)
3214 {
3215 rcStrict = iemMemStackPopContinueSpecial(pVCpu, 0/*off*/, 8 /*cbMem*/, &uFrame.pv, &bUnmapInfo, uNewRsp);
3216 if (rcStrict != VINF_SUCCESS)
3217 return rcStrict;
3218/** @todo We might be popping a 32-bit ESP from the IRET frame, but whether
3219 * 16-bit or 32-bit are being loaded into SP depends on the D/B
3220 * bit of the popped SS selector it turns out. */
3221 uNewESP = uFrame.pu32[0];
3222 uNewSS = (uint16_t)uFrame.pu32[1];
3223 }
3224 else
3225 {
3226 rcStrict = iemMemStackPopContinueSpecial(pVCpu, 0 /*off*/, 4 /*cbMem*/, &uFrame.pv, &bUnmapInfo, uNewRsp);
3227 if (rcStrict != VINF_SUCCESS)
3228 return rcStrict;
3229 uNewESP = uFrame.pu16[0];
3230 uNewSS = uFrame.pu16[1];
3231 }
3232 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
3233 if (rcStrict != VINF_SUCCESS)
3234 return rcStrict;
3235 Log7(("iemCImpl_iret_prot: uNewSS=%#06x uNewESP=%#010x\n", uNewSS, uNewESP));
3236
3237 /* Read the SS descriptor. */
3238 if (!(uNewSS & X86_SEL_MASK_OFF_RPL))
3239 {
3240 Log(("iret %04x:%08x/%04x:%08x -> invalid SS selector, #GP(0)\n", uNewCs, uNewEip, uNewSS, uNewESP));
3241 return iemRaiseGeneralProtectionFault0(pVCpu);
3242 }
3243
3244 IEMSELDESC DescSS;
3245 rcStrict = iemMemFetchSelDesc(pVCpu, &DescSS, uNewSS, X86_XCPT_GP); /** @todo Correct exception? */
3246 if (rcStrict != VINF_SUCCESS)
3247 {
3248 Log(("iret %04x:%08x/%04x:%08x - %Rrc when fetching SS\n",
3249 uNewCs, uNewEip, uNewSS, uNewESP, VBOXSTRICTRC_VAL(rcStrict)));
3250 return rcStrict;
3251 }
3252
3253 /* Privilege checks. */
3254 if ((uNewSS & X86_SEL_RPL) != (uNewCs & X86_SEL_RPL))
3255 {
3256 Log(("iret %04x:%08x/%04x:%08x -> SS.RPL != CS.RPL -> #GP\n", uNewCs, uNewEip, uNewSS, uNewESP));
3257 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewSS);
3258 }
3259 if (DescSS.Legacy.Gen.u2Dpl != (uNewCs & X86_SEL_RPL))
3260 {
3261 Log(("iret %04x:%08x/%04x:%08x -> SS.DPL (%d) != CS.RPL -> #GP\n",
3262 uNewCs, uNewEip, uNewSS, uNewESP, DescSS.Legacy.Gen.u2Dpl));
3263 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewSS);
3264 }
3265
3266 /* Must be a writeable data segment descriptor. */
3267 if (!DescSS.Legacy.Gen.u1DescType)
3268 {
3269 Log(("iret %04x:%08x/%04x:%08x -> SS is system segment (%#x) -> #GP\n",
3270 uNewCs, uNewEip, uNewSS, uNewESP, DescSS.Legacy.Gen.u4Type));
3271 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewSS);
3272 }
3273 if ((DescSS.Legacy.Gen.u4Type & (X86_SEL_TYPE_CODE | X86_SEL_TYPE_WRITE)) != X86_SEL_TYPE_WRITE)
3274 {
3275 Log(("iret %04x:%08x/%04x:%08x - not writable data segment (%#x) -> #GP\n",
3276 uNewCs, uNewEip, uNewSS, uNewESP, DescSS.Legacy.Gen.u4Type));
3277 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewSS);
3278 }
3279
3280 /* Present? */
3281 if (!DescSS.Legacy.Gen.u1Present)
3282 {
3283 Log(("iret %04x:%08x/%04x:%08x -> SS not present -> #SS\n", uNewCs, uNewEip, uNewSS, uNewESP));
3284 return iemRaiseStackSelectorNotPresentBySelector(pVCpu, uNewSS);
3285 }
3286
3287 uint32_t cbLimitSs = X86DESC_LIMIT_G(&DescSS.Legacy);
3288
3289 /* Check EIP. */
3290 if (uNewEip > cbLimitCS)
3291 {
3292 Log(("iret %04x:%08x/%04x:%08x -> EIP is out of bounds (%#x) -> #GP(0)\n",
3293 uNewCs, uNewEip, uNewSS, uNewESP, cbLimitCS));
3294 /** @todo Which is it, \#GP(0) or \#GP(sel)? */
3295 return iemRaiseSelectorBoundsBySelector(pVCpu, uNewCs);
3296 }
3297
3298 /*
3299 * Commit the changes, marking CS and SS accessed first since
3300 * that may fail.
3301 */
3302 if (!(DescCS.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
3303 {
3304 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uNewCs);
3305 if (rcStrict != VINF_SUCCESS)
3306 return rcStrict;
3307 DescCS.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
3308 }
3309 if (!(DescSS.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
3310 {
3311 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uNewSS);
3312 if (rcStrict != VINF_SUCCESS)
3313 return rcStrict;
3314 DescSS.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
3315 }
3316
3317 uint32_t fEFlagsMask = X86_EFL_CF | X86_EFL_PF | X86_EFL_AF | X86_EFL_ZF | X86_EFL_SF
3318 | X86_EFL_TF | X86_EFL_DF | X86_EFL_OF | X86_EFL_NT;
3319 if (enmEffOpSize != IEMMODE_16BIT)
3320 fEFlagsMask |= X86_EFL_RF | X86_EFL_AC | X86_EFL_ID;
3321 if (IEM_GET_CPL(pVCpu) == 0)
3322 fEFlagsMask |= X86_EFL_IF | X86_EFL_IOPL | X86_EFL_VIF | X86_EFL_VIP; /* VM is 0 */
3323 else if (IEM_GET_CPL(pVCpu) <= pVCpu->cpum.GstCtx.eflags.Bits.u2IOPL)
3324 fEFlagsMask |= X86_EFL_IF;
3325 if (IEM_GET_TARGET_CPU(pVCpu) <= IEMTARGETCPU_386)
3326 fEFlagsMask &= ~(X86_EFL_AC | X86_EFL_ID | X86_EFL_VIF | X86_EFL_VIP);
3327 uint32_t fEFlagsNew = IEMMISC_GET_EFL(pVCpu);
3328 fEFlagsNew &= ~fEFlagsMask;
3329 fEFlagsNew |= uNewFlags & fEFlagsMask;
3330#ifdef DBGFTRACE_ENABLED
3331 RTTraceBufAddMsgF(pVCpu->CTX_SUFF(pVM)->CTX_SUFF(hTraceBuf), "iret/%up%u %04x:%08x -> %04x:%04x %x %04x:%04x",
3332 IEM_GET_CPL(pVCpu), uNewCs & X86_SEL_RPL, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip,
3333 uNewCs, uNewEip, uNewFlags, uNewSS, uNewESP);
3334#endif
3335
3336 IEMMISC_SET_EFL(pVCpu, fEFlagsNew);
3337 pVCpu->cpum.GstCtx.rip = uNewEip;
3338 pVCpu->cpum.GstCtx.cs.Sel = uNewCs;
3339 pVCpu->cpum.GstCtx.cs.ValidSel = uNewCs;
3340 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
3341 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESC_GET_HID_ATTR(&DescCS.Legacy);
3342 pVCpu->cpum.GstCtx.cs.u32Limit = cbLimitCS;
3343 pVCpu->cpum.GstCtx.cs.u64Base = X86DESC_BASE(&DescCS.Legacy);
3344
3345 pVCpu->cpum.GstCtx.ss.Sel = uNewSS;
3346 pVCpu->cpum.GstCtx.ss.ValidSel = uNewSS;
3347 pVCpu->cpum.GstCtx.ss.fFlags = CPUMSELREG_FLAGS_VALID;
3348 pVCpu->cpum.GstCtx.ss.Attr.u = X86DESC_GET_HID_ATTR(&DescSS.Legacy);
3349 pVCpu->cpum.GstCtx.ss.u32Limit = cbLimitSs;
3350 pVCpu->cpum.GstCtx.ss.u64Base = X86DESC_BASE(&DescSS.Legacy);
3351 if (!pVCpu->cpum.GstCtx.ss.Attr.n.u1DefBig)
3352 pVCpu->cpum.GstCtx.sp = (uint16_t)uNewESP;
3353 else
3354 pVCpu->cpum.GstCtx.rsp = uNewESP;
3355
3356 iemHlpAdjustSelectorForNewCpl(pVCpu, uNewCs & X86_SEL_RPL, &pVCpu->cpum.GstCtx.ds);
3357 iemHlpAdjustSelectorForNewCpl(pVCpu, uNewCs & X86_SEL_RPL, &pVCpu->cpum.GstCtx.es);
3358 iemHlpAdjustSelectorForNewCpl(pVCpu, uNewCs & X86_SEL_RPL, &pVCpu->cpum.GstCtx.fs);
3359 iemHlpAdjustSelectorForNewCpl(pVCpu, uNewCs & X86_SEL_RPL, &pVCpu->cpum.GstCtx.gs);
3360
3361 iemRecalcExecModeAndCplFlags(pVCpu);
3362
3363 /* Done! */
3364
3365 }
3366 /*
3367 * Return to the same level.
3368 */
3369 else
3370 {
3371 /* Check EIP. */
3372 if (uNewEip > cbLimitCS)
3373 {
3374 Log(("iret %04x:%08x - EIP is out of bounds (%#x) -> #GP(0)\n", uNewCs, uNewEip, cbLimitCS));
3375 /** @todo Which is it, \#GP(0) or \#GP(sel)? */
3376 return iemRaiseSelectorBoundsBySelector(pVCpu, uNewCs);
3377 }
3378
3379 /*
3380 * Commit the changes, marking CS first since it may fail.
3381 */
3382 if (!(DescCS.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
3383 {
3384 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uNewCs);
3385 if (rcStrict != VINF_SUCCESS)
3386 return rcStrict;
3387 DescCS.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
3388 }
3389
3390 X86EFLAGS NewEfl;
3391 NewEfl.u = IEMMISC_GET_EFL(pVCpu);
3392 uint32_t fEFlagsMask = X86_EFL_CF | X86_EFL_PF | X86_EFL_AF | X86_EFL_ZF | X86_EFL_SF
3393 | X86_EFL_TF | X86_EFL_DF | X86_EFL_OF | X86_EFL_NT;
3394 if (enmEffOpSize != IEMMODE_16BIT)
3395 fEFlagsMask |= X86_EFL_RF | X86_EFL_AC | X86_EFL_ID;
3396 if (IEM_GET_CPL(pVCpu) == 0)
3397 fEFlagsMask |= X86_EFL_IF | X86_EFL_IOPL | X86_EFL_VIF | X86_EFL_VIP; /* VM is 0 */
3398 else if (IEM_GET_CPL(pVCpu) <= NewEfl.Bits.u2IOPL)
3399 fEFlagsMask |= X86_EFL_IF;
3400 if (IEM_GET_TARGET_CPU(pVCpu) <= IEMTARGETCPU_386)
3401 fEFlagsMask &= ~(X86_EFL_AC | X86_EFL_ID | X86_EFL_VIF | X86_EFL_VIP);
3402 NewEfl.u &= ~fEFlagsMask;
3403 NewEfl.u |= fEFlagsMask & uNewFlags;
3404#ifdef DBGFTRACE_ENABLED
3405 RTTraceBufAddMsgF(pVCpu->CTX_SUFF(pVM)->CTX_SUFF(hTraceBuf), "iret/%up %04x:%08x -> %04x:%04x %x %04x:%04llx",
3406 IEM_GET_CPL(pVCpu), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip,
3407 uNewCs, uNewEip, uNewFlags, pVCpu->cpum.GstCtx.ss.Sel, uNewRsp);
3408#endif
3409
3410 IEMMISC_SET_EFL(pVCpu, NewEfl.u);
3411 pVCpu->cpum.GstCtx.rip = uNewEip;
3412 pVCpu->cpum.GstCtx.cs.Sel = uNewCs;
3413 pVCpu->cpum.GstCtx.cs.ValidSel = uNewCs;
3414 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
3415 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESC_GET_HID_ATTR(&DescCS.Legacy);
3416 pVCpu->cpum.GstCtx.cs.u32Limit = cbLimitCS;
3417 pVCpu->cpum.GstCtx.cs.u64Base = X86DESC_BASE(&DescCS.Legacy);
3418 if (!pVCpu->cpum.GstCtx.ss.Attr.n.u1DefBig)
3419 pVCpu->cpum.GstCtx.sp = (uint16_t)uNewRsp;
3420 else
3421 pVCpu->cpum.GstCtx.rsp = uNewRsp;
3422
3423 iemRecalcExecModeAndCplFlags(pVCpu);
3424
3425 /* Done! */
3426 }
3427
3428 /* Flush the prefetch buffer. */
3429 IEM_FLUSH_PREFETCH_HEAVY(pVCpu, cbInstr); /** @todo may light flush if same ring? */
3430
3431/** @todo single stepping */
3432 return VINF_SUCCESS;
3433}
3434
3435
3436/**
3437 * Implements iret for long mode
3438 *
3439 * @param enmEffOpSize The effective operand size.
3440 */
3441IEM_CIMPL_DEF_1(iemCImpl_iret_64bit, IEMMODE, enmEffOpSize)
3442{
3443 NOREF(cbInstr);
3444
3445 /*
3446 * Nested task return is not supported in long mode.
3447 */
3448 if (pVCpu->cpum.GstCtx.eflags.Bits.u1NT)
3449 {
3450 Log(("iretq with NT=1 (eflags=%#x) -> #GP(0)\n", pVCpu->cpum.GstCtx.eflags.u));
3451 return iemRaiseGeneralProtectionFault0(pVCpu);
3452 }
3453
3454 /*
3455 * Normal return.
3456 *
3457 * Do the stack bits, but don't commit RSP before everything checks
3458 * out right.
3459 */
3460 VBOXSTRICTRC rcStrict;
3461 uint8_t bUnmapInfo;
3462 RTCPTRUNION uFrame;
3463 uint64_t uNewRip;
3464 uint16_t uNewCs;
3465 uint16_t uNewSs;
3466 uint32_t uNewFlags;
3467 uint64_t uNewRsp;
3468 if (enmEffOpSize == IEMMODE_64BIT)
3469 {
3470 rcStrict = iemMemStackPopBeginSpecial(pVCpu, 5*8, 7, &uFrame.pv, &bUnmapInfo, &uNewRsp);
3471 if (rcStrict != VINF_SUCCESS)
3472 return rcStrict;
3473 uNewRip = uFrame.pu64[0];
3474 uNewCs = (uint16_t)uFrame.pu64[1];
3475 uNewFlags = (uint32_t)uFrame.pu64[2];
3476 uNewRsp = uFrame.pu64[3];
3477 uNewSs = (uint16_t)uFrame.pu64[4];
3478 }
3479 else if (enmEffOpSize == IEMMODE_32BIT)
3480 {
3481 rcStrict = iemMemStackPopBeginSpecial(pVCpu, 5*4, 3, &uFrame.pv, &bUnmapInfo, &uNewRsp);
3482 if (rcStrict != VINF_SUCCESS)
3483 return rcStrict;
3484 uNewRip = uFrame.pu32[0];
3485 uNewCs = (uint16_t)uFrame.pu32[1];
3486 uNewFlags = uFrame.pu32[2];
3487 uNewRsp = uFrame.pu32[3];
3488 uNewSs = (uint16_t)uFrame.pu32[4];
3489 }
3490 else
3491 {
3492 Assert(enmEffOpSize == IEMMODE_16BIT);
3493 rcStrict = iemMemStackPopBeginSpecial(pVCpu, 5*2, 1, &uFrame.pv, &bUnmapInfo, &uNewRsp);
3494 if (rcStrict != VINF_SUCCESS)
3495 return rcStrict;
3496 uNewRip = uFrame.pu16[0];
3497 uNewCs = uFrame.pu16[1];
3498 uNewFlags = uFrame.pu16[2];
3499 uNewRsp = uFrame.pu16[3];
3500 uNewSs = uFrame.pu16[4];
3501 }
3502 rcStrict = iemMemStackPopDoneSpecial(pVCpu, bUnmapInfo); /* don't use iemMemStackPopCommitSpecial here. */
3503 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
3504 { /* extremely like */ }
3505 else
3506 return rcStrict;
3507 Log7(("iretq stack: cs:rip=%04x:%016RX64 rflags=%016RX64 ss:rsp=%04x:%016RX64\n", uNewCs, uNewRip, uNewFlags, uNewSs, uNewRsp));
3508
3509 /*
3510 * Check stuff.
3511 */
3512 /* Read the CS descriptor. */
3513 if (!(uNewCs & X86_SEL_MASK_OFF_RPL))
3514 {
3515 Log(("iret %04x:%016RX64/%04x:%016RX64 -> invalid CS selector, #GP(0)\n", uNewCs, uNewRip, uNewSs, uNewRsp));
3516 return iemRaiseGeneralProtectionFault0(pVCpu);
3517 }
3518
3519 IEMSELDESC DescCS;
3520 rcStrict = iemMemFetchSelDesc(pVCpu, &DescCS, uNewCs, X86_XCPT_GP);
3521 if (rcStrict != VINF_SUCCESS)
3522 {
3523 Log(("iret %04x:%016RX64/%04x:%016RX64 - rcStrict=%Rrc when fetching CS\n",
3524 uNewCs, uNewRip, uNewSs, uNewRsp, VBOXSTRICTRC_VAL(rcStrict)));
3525 return rcStrict;
3526 }
3527
3528 /* Must be a code descriptor. */
3529 if ( !DescCS.Legacy.Gen.u1DescType
3530 || !(DescCS.Legacy.Gen.u4Type & X86_SEL_TYPE_CODE))
3531 {
3532 Log(("iret %04x:%016RX64/%04x:%016RX64 - CS is not a code segment T=%u T=%#xu -> #GP\n",
3533 uNewCs, uNewRip, uNewSs, uNewRsp, DescCS.Legacy.Gen.u1DescType, DescCS.Legacy.Gen.u4Type));
3534 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
3535 }
3536
3537 /* Privilege checks. */
3538 uint8_t const uNewCpl = uNewCs & X86_SEL_RPL;
3539 if (!(DescCS.Legacy.Gen.u4Type & X86_SEL_TYPE_CONF))
3540 {
3541 if ((uNewCs & X86_SEL_RPL) != DescCS.Legacy.Gen.u2Dpl)
3542 {
3543 Log(("iret %04x:%016RX64 - RPL != DPL (%d) -> #GP\n", uNewCs, uNewRip, DescCS.Legacy.Gen.u2Dpl));
3544 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
3545 }
3546 }
3547 else if ((uNewCs & X86_SEL_RPL) < DescCS.Legacy.Gen.u2Dpl)
3548 {
3549 Log(("iret %04x:%016RX64 - RPL < DPL (%d) -> #GP\n", uNewCs, uNewRip, DescCS.Legacy.Gen.u2Dpl));
3550 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
3551 }
3552 if ((uNewCs & X86_SEL_RPL) < IEM_GET_CPL(pVCpu))
3553 {
3554 Log(("iret %04x:%016RX64 - RPL < CPL (%d) -> #GP\n", uNewCs, uNewRip, IEM_GET_CPL(pVCpu)));
3555 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewCs);
3556 }
3557
3558 /* Present? */
3559 if (!DescCS.Legacy.Gen.u1Present)
3560 {
3561 Log(("iret %04x:%016RX64/%04x:%016RX64 - CS not present -> #NP\n", uNewCs, uNewRip, uNewSs, uNewRsp));
3562 return iemRaiseSelectorNotPresentBySelector(pVCpu, uNewCs);
3563 }
3564
3565 uint32_t cbLimitCS = X86DESC_LIMIT_G(&DescCS.Legacy);
3566
3567 /* Read the SS descriptor. */
3568 IEMSELDESC DescSS;
3569 if (!(uNewSs & X86_SEL_MASK_OFF_RPL))
3570 {
3571 if ( !DescCS.Legacy.Gen.u1Long
3572 || DescCS.Legacy.Gen.u1DefBig /** @todo exactly how does iret (and others) behave with u1Long=1 and u1DefBig=1? \#GP(sel)? */
3573 || uNewCpl > 2) /** @todo verify SS=0 impossible for ring-3. */
3574 {
3575 Log(("iret %04x:%016RX64/%04x:%016RX64 -> invalid SS selector, #GP(0)\n", uNewCs, uNewRip, uNewSs, uNewRsp));
3576 return iemRaiseGeneralProtectionFault0(pVCpu);
3577 }
3578 /* Make sure SS is sensible, marked as accessed etc. */
3579 iemMemFakeStackSelDesc(&DescSS, (uNewSs & X86_SEL_RPL));
3580 }
3581 else
3582 {
3583 rcStrict = iemMemFetchSelDesc(pVCpu, &DescSS, uNewSs, X86_XCPT_GP); /** @todo Correct exception? */
3584 if (rcStrict != VINF_SUCCESS)
3585 {
3586 Log(("iret %04x:%016RX64/%04x:%016RX64 - %Rrc when fetching SS\n",
3587 uNewCs, uNewRip, uNewSs, uNewRsp, VBOXSTRICTRC_VAL(rcStrict)));
3588 return rcStrict;
3589 }
3590 }
3591
3592 /* Privilege checks. */
3593 if ((uNewSs & X86_SEL_RPL) != (uNewCs & X86_SEL_RPL))
3594 {
3595 Log(("iret %04x:%016RX64/%04x:%016RX64 -> SS.RPL != CS.RPL -> #GP\n", uNewCs, uNewRip, uNewSs, uNewRsp));
3596 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewSs);
3597 }
3598
3599 uint32_t cbLimitSs;
3600 if (!(uNewSs & X86_SEL_MASK_OFF_RPL))
3601 cbLimitSs = UINT32_MAX;
3602 else
3603 {
3604 if (DescSS.Legacy.Gen.u2Dpl != (uNewCs & X86_SEL_RPL))
3605 {
3606 Log(("iret %04x:%016RX64/%04x:%016RX64 -> SS.DPL (%d) != CS.RPL -> #GP\n",
3607 uNewCs, uNewRip, uNewSs, uNewRsp, DescSS.Legacy.Gen.u2Dpl));
3608 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewSs);
3609 }
3610
3611 /* Must be a writeable data segment descriptor. */
3612 if (!DescSS.Legacy.Gen.u1DescType)
3613 {
3614 Log(("iret %04x:%016RX64/%04x:%016RX64 -> SS is system segment (%#x) -> #GP\n",
3615 uNewCs, uNewRip, uNewSs, uNewRsp, DescSS.Legacy.Gen.u4Type));
3616 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewSs);
3617 }
3618 if ((DescSS.Legacy.Gen.u4Type & (X86_SEL_TYPE_CODE | X86_SEL_TYPE_WRITE)) != X86_SEL_TYPE_WRITE)
3619 {
3620 Log(("iret %04x:%016RX64/%04x:%016RX64 - not writable data segment (%#x) -> #GP\n",
3621 uNewCs, uNewRip, uNewSs, uNewRsp, DescSS.Legacy.Gen.u4Type));
3622 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewSs);
3623 }
3624
3625 /* Present? */
3626 if (!DescSS.Legacy.Gen.u1Present)
3627 {
3628 Log(("iret %04x:%016RX64/%04x:%016RX64 -> SS not present -> #SS\n", uNewCs, uNewRip, uNewSs, uNewRsp));
3629 return iemRaiseStackSelectorNotPresentBySelector(pVCpu, uNewSs);
3630 }
3631 cbLimitSs = X86DESC_LIMIT_G(&DescSS.Legacy);
3632 }
3633
3634 /* Check EIP. */
3635 if (DescCS.Legacy.Gen.u1Long)
3636 {
3637 if (!IEM_IS_CANONICAL(uNewRip))
3638 {
3639 Log(("iret %04x:%016RX64/%04x:%016RX64 -> RIP is not canonical -> #GP(0)\n",
3640 uNewCs, uNewRip, uNewSs, uNewRsp));
3641 return iemRaiseNotCanonical(pVCpu);
3642 }
3643/** @todo check the location of this... Testcase. */
3644 if (RT_LIKELY(!DescCS.Legacy.Gen.u1DefBig))
3645 { /* likely */ }
3646 else
3647 {
3648 Log(("iret %04x:%016RX64/%04x:%016RX64 -> both L and D are set -> #GP(0)\n", uNewCs, uNewRip, uNewSs, uNewRsp));
3649 return iemRaiseGeneralProtectionFault0(pVCpu);
3650 }
3651 }
3652 else
3653 {
3654 if (uNewRip > cbLimitCS)
3655 {
3656 Log(("iret %04x:%016RX64/%04x:%016RX64 -> EIP is out of bounds (%#x) -> #GP(0)\n",
3657 uNewCs, uNewRip, uNewSs, uNewRsp, cbLimitCS));
3658 /** @todo Which is it, \#GP(0) or \#GP(sel)? */
3659 return iemRaiseSelectorBoundsBySelector(pVCpu, uNewCs);
3660 }
3661 }
3662
3663 /*
3664 * Commit the changes, marking CS and SS accessed first since
3665 * that may fail.
3666 */
3667 /** @todo where exactly are these actually marked accessed by a real CPU? */
3668 if (!(DescCS.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
3669 {
3670 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uNewCs);
3671 if (rcStrict != VINF_SUCCESS)
3672 return rcStrict;
3673 DescCS.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
3674 }
3675 if (!(DescSS.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
3676 {
3677 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uNewSs);
3678 if (rcStrict != VINF_SUCCESS)
3679 return rcStrict;
3680 DescSS.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
3681 }
3682
3683 uint32_t fEFlagsMask = X86_EFL_CF | X86_EFL_PF | X86_EFL_AF | X86_EFL_ZF | X86_EFL_SF
3684 | X86_EFL_TF | X86_EFL_DF | X86_EFL_OF | X86_EFL_NT;
3685 if (enmEffOpSize != IEMMODE_16BIT)
3686 fEFlagsMask |= X86_EFL_RF | X86_EFL_AC | X86_EFL_ID;
3687 if (IEM_GET_CPL(pVCpu) == 0)
3688 fEFlagsMask |= X86_EFL_IF | X86_EFL_IOPL | X86_EFL_VIF | X86_EFL_VIP; /* VM is ignored */
3689 else if (IEM_GET_CPL(pVCpu) <= pVCpu->cpum.GstCtx.eflags.Bits.u2IOPL)
3690 fEFlagsMask |= X86_EFL_IF;
3691 uint32_t fEFlagsNew = IEMMISC_GET_EFL(pVCpu);
3692 fEFlagsNew &= ~fEFlagsMask;
3693 fEFlagsNew |= uNewFlags & fEFlagsMask;
3694#ifdef DBGFTRACE_ENABLED
3695 RTTraceBufAddMsgF(pVCpu->CTX_SUFF(pVM)->CTX_SUFF(hTraceBuf), "iret/%ul%u %08llx -> %04x:%04llx %llx %04x:%04llx",
3696 IEM_GET_CPL(pVCpu), uNewCpl, pVCpu->cpum.GstCtx.rip, uNewCs, uNewRip, uNewFlags, uNewSs, uNewRsp);
3697#endif
3698
3699 IEMMISC_SET_EFL(pVCpu, fEFlagsNew);
3700 pVCpu->cpum.GstCtx.rip = uNewRip;
3701 pVCpu->cpum.GstCtx.cs.Sel = uNewCs;
3702 pVCpu->cpum.GstCtx.cs.ValidSel = uNewCs;
3703 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
3704 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESC_GET_HID_ATTR(&DescCS.Legacy);
3705 pVCpu->cpum.GstCtx.cs.u32Limit = cbLimitCS;
3706 pVCpu->cpum.GstCtx.cs.u64Base = X86DESC_BASE(&DescCS.Legacy);
3707 if (pVCpu->cpum.GstCtx.cs.Attr.n.u1Long || pVCpu->cpum.GstCtx.cs.Attr.n.u1DefBig)
3708 pVCpu->cpum.GstCtx.rsp = uNewRsp;
3709 else
3710 pVCpu->cpum.GstCtx.sp = (uint16_t)uNewRsp;
3711 pVCpu->cpum.GstCtx.ss.Sel = uNewSs;
3712 pVCpu->cpum.GstCtx.ss.ValidSel = uNewSs;
3713 if (!(uNewSs & X86_SEL_MASK_OFF_RPL))
3714 {
3715 pVCpu->cpum.GstCtx.ss.fFlags = CPUMSELREG_FLAGS_VALID;
3716 pVCpu->cpum.GstCtx.ss.Attr.u = X86DESCATTR_UNUSABLE | (uNewCpl << X86DESCATTR_DPL_SHIFT);
3717 pVCpu->cpum.GstCtx.ss.u32Limit = UINT32_MAX;
3718 pVCpu->cpum.GstCtx.ss.u64Base = 0;
3719 Log2(("iretq new SS: NULL\n"));
3720 }
3721 else
3722 {
3723 pVCpu->cpum.GstCtx.ss.fFlags = CPUMSELREG_FLAGS_VALID;
3724 pVCpu->cpum.GstCtx.ss.Attr.u = X86DESC_GET_HID_ATTR(&DescSS.Legacy);
3725 pVCpu->cpum.GstCtx.ss.u32Limit = cbLimitSs;
3726 pVCpu->cpum.GstCtx.ss.u64Base = X86DESC_BASE(&DescSS.Legacy);
3727 Log2(("iretq new SS: base=%#RX64 lim=%#x attr=%#x\n", pVCpu->cpum.GstCtx.ss.u64Base, pVCpu->cpum.GstCtx.ss.u32Limit, pVCpu->cpum.GstCtx.ss.Attr.u));
3728 }
3729
3730 if (IEM_GET_CPL(pVCpu) != uNewCpl)
3731 {
3732 iemHlpAdjustSelectorForNewCpl(pVCpu, uNewCpl, &pVCpu->cpum.GstCtx.ds);
3733 iemHlpAdjustSelectorForNewCpl(pVCpu, uNewCpl, &pVCpu->cpum.GstCtx.es);
3734 iemHlpAdjustSelectorForNewCpl(pVCpu, uNewCpl, &pVCpu->cpum.GstCtx.fs);
3735 iemHlpAdjustSelectorForNewCpl(pVCpu, uNewCpl, &pVCpu->cpum.GstCtx.gs);
3736 }
3737
3738 iemRecalcExecModeAndCplFlags(pVCpu);
3739
3740 /* Flush the prefetch buffer. */
3741 IEM_FLUSH_PREFETCH_HEAVY(pVCpu, cbInstr); /** @todo may light flush if the ring + mode doesn't change */
3742
3743/** @todo single stepping */
3744 return VINF_SUCCESS;
3745}
3746
3747
3748/**
3749 * Implements iret.
3750 *
3751 * @param enmEffOpSize The effective operand size.
3752 */
3753IEM_CIMPL_DEF_1(iemCImpl_iret, IEMMODE, enmEffOpSize)
3754{
3755 bool fBlockingNmi = CPUMAreInterruptsInhibitedByNmi(&pVCpu->cpum.GstCtx);
3756
3757 if (!IEM_IS_IN_GUEST(pVCpu))
3758 { /* probable */ }
3759#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3760 else if (IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
3761 {
3762 /*
3763 * Record whether NMI (or virtual-NMI) blocking is in effect during the execution
3764 * of this IRET instruction. We need to provide this information as part of some
3765 * VM-exits.
3766 *
3767 * See Intel spec. 27.2.2 "Information for VM Exits Due to Vectored Events".
3768 */
3769 if (IEM_VMX_IS_PINCTLS_SET(pVCpu, VMX_PIN_CTLS_VIRT_NMI))
3770 pVCpu->cpum.GstCtx.hwvirt.vmx.fNmiUnblockingIret = pVCpu->cpum.GstCtx.hwvirt.vmx.fVirtNmiBlocking;
3771 else
3772 pVCpu->cpum.GstCtx.hwvirt.vmx.fNmiUnblockingIret = fBlockingNmi;
3773
3774 /*
3775 * If "NMI exiting" is set, IRET does not affect blocking of NMIs.
3776 * See Intel Spec. 25.3 "Changes To Instruction Behavior In VMX Non-root Operation".
3777 */
3778 if (IEM_VMX_IS_PINCTLS_SET(pVCpu, VMX_PIN_CTLS_NMI_EXIT))
3779 fBlockingNmi = false;
3780
3781 /* Clear virtual-NMI blocking, if any, before causing any further exceptions. */
3782 pVCpu->cpum.GstCtx.hwvirt.vmx.fVirtNmiBlocking = false;
3783 }
3784#endif
3785 /*
3786 * The SVM nested-guest intercept for IRET takes priority over all exceptions,
3787 * The NMI is still held pending (which I assume means blocking of further NMIs
3788 * is in effect).
3789 *
3790 * See AMD spec. 15.9 "Instruction Intercepts".
3791 * See AMD spec. 15.21.9 "NMI Support".
3792 */
3793 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_IRET))
3794 {
3795 Log(("iret: Guest intercept -> #VMEXIT\n"));
3796 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
3797 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_IRET, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
3798 }
3799
3800 /*
3801 * Clear NMI blocking, if any, before causing any further exceptions.
3802 * See Intel spec. 6.7.1 "Handling Multiple NMIs".
3803 */
3804 if (fBlockingNmi)
3805 CPUMClearInterruptInhibitingByNmi(&pVCpu->cpum.GstCtx);
3806
3807 /*
3808 * Call a mode specific worker.
3809 */
3810 VBOXSTRICTRC rcStrict;
3811 if (IEM_IS_REAL_OR_V86_MODE(pVCpu))
3812 rcStrict = IEM_CIMPL_CALL_1(iemCImpl_iret_real_v8086, enmEffOpSize);
3813 else
3814 {
3815 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_GDTR | CPUMCTX_EXTRN_LDTR);
3816 if (IEM_IS_64BIT_CODE(pVCpu))
3817 rcStrict = IEM_CIMPL_CALL_1(iemCImpl_iret_64bit, enmEffOpSize);
3818 else
3819 rcStrict = IEM_CIMPL_CALL_1(iemCImpl_iret_prot, enmEffOpSize);
3820 }
3821
3822#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3823 /*
3824 * Clear NMI unblocking IRET state with the completion of IRET.
3825 */
3826 if (IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
3827 pVCpu->cpum.GstCtx.hwvirt.vmx.fNmiUnblockingIret = false;
3828#endif
3829 return rcStrict;
3830}
3831
3832
3833static void iemLoadallSetSelector(PVMCPUCC pVCpu, uint8_t iSegReg, uint16_t uSel)
3834{
3835 PCPUMSELREGHID pHid = iemSRegGetHid(pVCpu, iSegReg);
3836
3837 pHid->Sel = uSel;
3838 pHid->ValidSel = uSel;
3839 pHid->fFlags = CPUMSELREG_FLAGS_VALID;
3840}
3841
3842
3843static void iemLoadall286SetDescCache(PVMCPUCC pVCpu, uint8_t iSegReg, uint8_t const *pbMem)
3844{
3845 PCPUMSELREGHID pHid = iemSRegGetHid(pVCpu, iSegReg);
3846
3847 /* The base is in the first three bytes. */
3848 pHid->u64Base = pbMem[0] + (pbMem[1] << 8) + (pbMem[2] << 16);
3849 /* The attributes are in the fourth byte. */
3850 pHid->Attr.u = pbMem[3];
3851 pHid->Attr.u &= ~(X86DESCATTR_L | X86DESCATTR_D); /* (just to be on the safe side) */
3852 /* The limit is in the last two bytes. */
3853 pHid->u32Limit = pbMem[4] + (pbMem[5] << 8);
3854}
3855
3856
3857/**
3858 * Implements 286 LOADALL (286 CPUs only).
3859 */
3860IEM_CIMPL_DEF_0(iemCImpl_loadall286)
3861{
3862 NOREF(cbInstr);
3863
3864 /* Data is loaded from a buffer at 800h. No checks are done on the
3865 * validity of loaded state.
3866 *
3867 * LOADALL only loads the internal CPU state, it does not access any
3868 * GDT, LDT, or similar tables.
3869 */
3870
3871 if (IEM_GET_CPL(pVCpu) != 0)
3872 {
3873 Log(("loadall286: CPL must be 0 not %u -> #GP(0)\n", IEM_GET_CPL(pVCpu)));
3874 return iemRaiseGeneralProtectionFault0(pVCpu);
3875 }
3876
3877 uint8_t bUnmapInfo;
3878 uint8_t const *pbMem = NULL;
3879 RTGCPHYS GCPtrStart = 0x800; /* Fixed table location. */
3880 VBOXSTRICTRC rcStrict = iemMemMap(pVCpu, (void **)&pbMem, &bUnmapInfo, 0x66, UINT8_MAX, GCPtrStart, IEM_ACCESS_SYS_R, 0);
3881 if (rcStrict != VINF_SUCCESS)
3882 return rcStrict;
3883
3884 /* The MSW is at offset 0x06. */
3885 uint16_t const *pau16Mem = (uint16_t const *)(pbMem + 0x06);
3886 /* Even LOADALL can't clear the MSW.PE bit, though it can set it. */
3887 uint64_t uNewCr0 = pVCpu->cpum.GstCtx.cr0 & ~(X86_CR0_MP | X86_CR0_EM | X86_CR0_TS);
3888 uNewCr0 |= *pau16Mem & (X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS);
3889 uint64_t const uOldCr0 = pVCpu->cpum.GstCtx.cr0;
3890
3891 CPUMSetGuestCR0(pVCpu, uNewCr0);
3892 Assert(pVCpu->cpum.GstCtx.cr0 == uNewCr0);
3893
3894 /* Inform PGM if mode changed. */
3895 if ((uNewCr0 & X86_CR0_PE) != (uOldCr0 & X86_CR0_PE))
3896 {
3897 int rc = PGMFlushTLB(pVCpu, pVCpu->cpum.GstCtx.cr3, true /* global */);
3898 AssertRCReturn(rc, rc);
3899 /* ignore informational status codes */
3900 }
3901 rcStrict = PGMChangeMode(pVCpu, pVCpu->cpum.GstCtx.cr0, pVCpu->cpum.GstCtx.cr4, pVCpu->cpum.GstCtx.msrEFER,
3902 false /* fForce */);
3903
3904 /* TR selector is at offset 0x16. */
3905 pau16Mem = (uint16_t const *)(pbMem + 0x16);
3906 pVCpu->cpum.GstCtx.tr.Sel = pau16Mem[0];
3907 pVCpu->cpum.GstCtx.tr.ValidSel = pau16Mem[0];
3908 pVCpu->cpum.GstCtx.tr.fFlags = CPUMSELREG_FLAGS_VALID;
3909
3910 /* Followed by FLAGS... */
3911 pVCpu->cpum.GstCtx.eflags.u = pau16Mem[1] | X86_EFL_1;
3912 pVCpu->cpum.GstCtx.ip = pau16Mem[2]; /* ...and IP. */
3913
3914 /* LDT is at offset 0x1C. */
3915 pau16Mem = (uint16_t const *)(pbMem + 0x1C);
3916 pVCpu->cpum.GstCtx.ldtr.Sel = pau16Mem[0];
3917 pVCpu->cpum.GstCtx.ldtr.ValidSel = pau16Mem[0];
3918 pVCpu->cpum.GstCtx.ldtr.fFlags = CPUMSELREG_FLAGS_VALID;
3919
3920 /* Segment registers are at offset 0x1E. */
3921 pau16Mem = (uint16_t const *)(pbMem + 0x1E);
3922 iemLoadallSetSelector(pVCpu, X86_SREG_DS, pau16Mem[0]);
3923 iemLoadallSetSelector(pVCpu, X86_SREG_SS, pau16Mem[1]);
3924 iemLoadallSetSelector(pVCpu, X86_SREG_CS, pau16Mem[2]);
3925 iemLoadallSetSelector(pVCpu, X86_SREG_ES, pau16Mem[3]);
3926
3927 /* GPRs are at offset 0x26. */
3928 pau16Mem = (uint16_t const *)(pbMem + 0x26);
3929 pVCpu->cpum.GstCtx.di = pau16Mem[0];
3930 pVCpu->cpum.GstCtx.si = pau16Mem[1];
3931 pVCpu->cpum.GstCtx.bp = pau16Mem[2];
3932 pVCpu->cpum.GstCtx.sp = pau16Mem[3];
3933 pVCpu->cpum.GstCtx.bx = pau16Mem[4];
3934 pVCpu->cpum.GstCtx.dx = pau16Mem[5];
3935 pVCpu->cpum.GstCtx.cx = pau16Mem[6];
3936 pVCpu->cpum.GstCtx.ax = pau16Mem[7];
3937
3938 /* Descriptor caches are at offset 0x36, 6 bytes per entry. */
3939 iemLoadall286SetDescCache(pVCpu, X86_SREG_ES, pbMem + 0x36);
3940 iemLoadall286SetDescCache(pVCpu, X86_SREG_CS, pbMem + 0x3C);
3941 iemLoadall286SetDescCache(pVCpu, X86_SREG_SS, pbMem + 0x42);
3942 iemLoadall286SetDescCache(pVCpu, X86_SREG_DS, pbMem + 0x48);
3943
3944 /* GDTR contents are at offset 0x4E, 6 bytes. */
3945 uint8_t const *pau8Mem = pbMem + 0x4E;
3946 /* NB: Fourth byte "should be zero"; we are ignoring it. */
3947 RTGCPHYS GCPtrBase = pau8Mem[0] + ((uint32_t)pau8Mem[1] << 8) + ((uint32_t)pau8Mem[2] << 16);
3948 uint16_t cbLimit = pau8Mem[4] + ((uint32_t)pau8Mem[5] << 8);
3949 CPUMSetGuestGDTR(pVCpu, GCPtrBase, cbLimit);
3950
3951 /* IDTR contents are at offset 0x5A, 6 bytes. */
3952 pau8Mem = pbMem + 0x5A;
3953 GCPtrBase = pau8Mem[0] + ((uint32_t)pau8Mem[1] << 8) + ((uint32_t)pau8Mem[2] << 16);
3954 cbLimit = pau8Mem[4] + ((uint32_t)pau8Mem[5] << 8);
3955 CPUMSetGuestIDTR(pVCpu, GCPtrBase, cbLimit);
3956
3957 Log(("LOADALL: GDTR:%08RX64/%04X, IDTR:%08RX64/%04X\n", pVCpu->cpum.GstCtx.gdtr.pGdt, pVCpu->cpum.GstCtx.gdtr.cbGdt, pVCpu->cpum.GstCtx.idtr.pIdt, pVCpu->cpum.GstCtx.idtr.cbIdt));
3958 Log(("LOADALL: CS:%04X, CS base:%08X, limit:%04X, attrs:%02X\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.cs.u64Base, pVCpu->cpum.GstCtx.cs.u32Limit, pVCpu->cpum.GstCtx.cs.Attr.u));
3959 Log(("LOADALL: DS:%04X, DS base:%08X, limit:%04X, attrs:%02X\n", pVCpu->cpum.GstCtx.ds.Sel, pVCpu->cpum.GstCtx.ds.u64Base, pVCpu->cpum.GstCtx.ds.u32Limit, pVCpu->cpum.GstCtx.ds.Attr.u));
3960 Log(("LOADALL: ES:%04X, ES base:%08X, limit:%04X, attrs:%02X\n", pVCpu->cpum.GstCtx.es.Sel, pVCpu->cpum.GstCtx.es.u64Base, pVCpu->cpum.GstCtx.es.u32Limit, pVCpu->cpum.GstCtx.es.Attr.u));
3961 Log(("LOADALL: SS:%04X, SS base:%08X, limit:%04X, attrs:%02X\n", pVCpu->cpum.GstCtx.ss.Sel, pVCpu->cpum.GstCtx.ss.u64Base, pVCpu->cpum.GstCtx.ss.u32Limit, pVCpu->cpum.GstCtx.ss.Attr.u));
3962 Log(("LOADALL: SI:%04X, DI:%04X, AX:%04X, BX:%04X, CX:%04X, DX:%04X\n", pVCpu->cpum.GstCtx.si, pVCpu->cpum.GstCtx.di, pVCpu->cpum.GstCtx.bx, pVCpu->cpum.GstCtx.bx, pVCpu->cpum.GstCtx.cx, pVCpu->cpum.GstCtx.dx));
3963
3964 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
3965 if (rcStrict != VINF_SUCCESS)
3966 return rcStrict;
3967
3968 /*
3969 * The CPL may change and protected mode may change enabled. It is taken
3970 * from the "DPL fields of the SS and CS descriptor caches" but there is no
3971 * word as to what happens if those are not identical (probably bad things).
3972 */
3973 iemRecalcExecModeAndCplFlags(pVCpu);
3974 Assert(IEM_IS_16BIT_CODE(pVCpu));
3975
3976 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_HIDDEN_SEL_REGS | CPUM_CHANGED_IDTR | CPUM_CHANGED_GDTR | CPUM_CHANGED_TR | CPUM_CHANGED_LDTR);
3977
3978 /* Flush the prefetch buffer. */
3979 IEM_FLUSH_PREFETCH_HEAVY(pVCpu, cbInstr);
3980
3981/** @todo single stepping */
3982 return rcStrict;
3983}
3984
3985
3986/**
3987 * Implements SYSCALL (AMD and Intel64).
3988 */
3989IEM_CIMPL_DEF_0(iemCImpl_syscall)
3990{
3991 /** @todo hack, LOADALL should be decoded as such on a 286. */
3992 if (RT_UNLIKELY(pVCpu->iem.s.uTargetCpu == IEMTARGETCPU_286))
3993 return iemCImpl_loadall286(pVCpu, cbInstr);
3994
3995 /*
3996 * Check preconditions.
3997 *
3998 * Note that CPUs described in the documentation may load a few odd values
3999 * into CS and SS than we allow here. This has yet to be checked on real
4000 * hardware.
4001 */
4002 if (!(pVCpu->cpum.GstCtx.msrEFER & MSR_K6_EFER_SCE))
4003 {
4004 Log(("syscall: Not enabled in EFER -> #UD\n"));
4005 return iemRaiseUndefinedOpcode(pVCpu);
4006 }
4007 if (!(pVCpu->cpum.GstCtx.cr0 & X86_CR0_PE))
4008 {
4009 Log(("syscall: Protected mode is required -> #GP(0)\n"));
4010 return iemRaiseGeneralProtectionFault0(pVCpu);
4011 }
4012 if (IEM_IS_GUEST_CPU_INTEL(pVCpu) && !CPUMIsGuestInLongModeEx(IEM_GET_CTX(pVCpu)))
4013 {
4014 Log(("syscall: Only available in long mode on intel -> #UD\n"));
4015 return iemRaiseUndefinedOpcode(pVCpu);
4016 }
4017
4018 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_SYSCALL_MSRS);
4019
4020 /** @todo verify RPL ignoring and CS=0xfff8 (i.e. SS == 0). */
4021 /** @todo what about LDT selectors? Shouldn't matter, really. */
4022 uint16_t uNewCs = (pVCpu->cpum.GstCtx.msrSTAR >> MSR_K6_STAR_SYSCALL_CS_SS_SHIFT) & X86_SEL_MASK_OFF_RPL;
4023 uint16_t uNewSs = uNewCs + 8;
4024 if (uNewCs == 0 || uNewSs == 0)
4025 {
4026 /** @todo Neither Intel nor AMD document this check. */
4027 Log(("syscall: msrSTAR.CS = 0 or SS = 0 -> #GP(0)\n"));
4028 return iemRaiseGeneralProtectionFault0(pVCpu);
4029 }
4030
4031 /* Long mode and legacy mode differs. */
4032 if (CPUMIsGuestInLongModeEx(IEM_GET_CTX(pVCpu)))
4033 {
4034 uint64_t uNewRip = IEM_IS_64BIT_CODE(pVCpu) ? pVCpu->cpum.GstCtx.msrLSTAR : pVCpu->cpum.GstCtx. msrCSTAR;
4035
4036 /* This test isn't in the docs, but I'm not trusting the guys writing
4037 the MSRs to have validated the values as canonical like they should. */
4038 if (!IEM_IS_CANONICAL(uNewRip))
4039 {
4040 /** @todo Intel claims this can't happen because IA32_LSTAR MSR can't be written with non-canonical address. */
4041 Log(("syscall: New RIP not canonical -> #UD\n"));
4042 return iemRaiseUndefinedOpcode(pVCpu);
4043 }
4044
4045 /*
4046 * Commit it.
4047 */
4048 Log(("syscall: %04x:%016RX64 [efl=%#llx] -> %04x:%016RX64\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.rflags.u, uNewCs, uNewRip));
4049 pVCpu->cpum.GstCtx.rcx = pVCpu->cpum.GstCtx.rip + cbInstr;
4050 pVCpu->cpum.GstCtx.rip = uNewRip;
4051
4052 pVCpu->cpum.GstCtx.rflags.u &= ~X86_EFL_RF;
4053 pVCpu->cpum.GstCtx.r11 = pVCpu->cpum.GstCtx.rflags.u;
4054 pVCpu->cpum.GstCtx.rflags.u &= ~pVCpu->cpum.GstCtx.msrSFMASK;
4055 pVCpu->cpum.GstCtx.rflags.u |= X86_EFL_RA1_MASK;
4056
4057 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESCATTR_P | X86DESCATTR_G | X86DESCATTR_L | X86DESCATTR_DT | X86_SEL_TYPE_ER_ACC;
4058 pVCpu->cpum.GstCtx.ss.Attr.u = X86DESCATTR_P | X86DESCATTR_G | X86DESCATTR_D | X86DESCATTR_DT | X86_SEL_TYPE_RW_ACC;
4059
4060 pVCpu->iem.s.fExec = (pVCpu->iem.s.fExec & ~(IEM_F_MODE_MASK | IEM_F_X86_CPL_MASK))
4061 | IEM_F_MODE_X86_64BIT;
4062 }
4063 else
4064 {
4065 /*
4066 * Commit it.
4067 */
4068 Log(("syscall: %04x:%08RX32 [efl=%#x] -> %04x:%08RX32\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip, pVCpu->cpum.GstCtx.eflags.u, uNewCs, (uint32_t)(pVCpu->cpum.GstCtx.msrSTAR & MSR_K6_STAR_SYSCALL_EIP_MASK)));
4069 pVCpu->cpum.GstCtx.rcx = pVCpu->cpum.GstCtx.eip + cbInstr;
4070 pVCpu->cpum.GstCtx.rip = pVCpu->cpum.GstCtx.msrSTAR & MSR_K6_STAR_SYSCALL_EIP_MASK;
4071 pVCpu->cpum.GstCtx.rflags.u &= ~(X86_EFL_VM | X86_EFL_IF | X86_EFL_RF);
4072
4073 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESCATTR_P | X86DESCATTR_G | X86DESCATTR_D | X86DESCATTR_DT | X86_SEL_TYPE_ER_ACC;
4074 pVCpu->cpum.GstCtx.ss.Attr.u = X86DESCATTR_P | X86DESCATTR_G | X86DESCATTR_D | X86DESCATTR_DT | X86_SEL_TYPE_RW_ACC;
4075
4076 pVCpu->iem.s.fExec = (pVCpu->iem.s.fExec & ~(IEM_F_MODE_MASK | IEM_F_X86_CPL_MASK))
4077 | IEM_F_MODE_X86_32BIT_PROT
4078 | iemCalc32BitFlatIndicatorEsDs(pVCpu);
4079 }
4080 pVCpu->cpum.GstCtx.cs.Sel = uNewCs;
4081 pVCpu->cpum.GstCtx.cs.ValidSel = uNewCs;
4082 pVCpu->cpum.GstCtx.cs.u64Base = 0;
4083 pVCpu->cpum.GstCtx.cs.u32Limit = UINT32_MAX;
4084 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
4085
4086 pVCpu->cpum.GstCtx.ss.Sel = uNewSs;
4087 pVCpu->cpum.GstCtx.ss.ValidSel = uNewSs;
4088 pVCpu->cpum.GstCtx.ss.u64Base = 0;
4089 pVCpu->cpum.GstCtx.ss.u32Limit = UINT32_MAX;
4090 pVCpu->cpum.GstCtx.ss.fFlags = CPUMSELREG_FLAGS_VALID;
4091
4092 /* Flush the prefetch buffer. */
4093 IEM_FLUSH_PREFETCH_HEAVY(pVCpu, cbInstr);
4094
4095/** @todo single step */
4096 return VINF_SUCCESS;
4097}
4098
4099
4100/**
4101 * Implements SYSRET (AMD and Intel64).
4102 *
4103 * @param enmEffOpSize The effective operand size.
4104 */
4105IEM_CIMPL_DEF_1(iemCImpl_sysret, IEMMODE, enmEffOpSize)
4106
4107{
4108 RT_NOREF_PV(cbInstr);
4109
4110 /*
4111 * Check preconditions.
4112 *
4113 * Note that CPUs described in the documentation may load a few odd values
4114 * into CS and SS than we allow here. This has yet to be checked on real
4115 * hardware.
4116 */
4117 if (!(pVCpu->cpum.GstCtx.msrEFER & MSR_K6_EFER_SCE))
4118 {
4119 Log(("sysret: Not enabled in EFER -> #UD\n"));
4120 return iemRaiseUndefinedOpcode(pVCpu);
4121 }
4122 if (IEM_IS_GUEST_CPU_INTEL(pVCpu) && !CPUMIsGuestInLongModeEx(IEM_GET_CTX(pVCpu)))
4123 {
4124 Log(("sysret: Only available in long mode on intel -> #UD\n"));
4125 return iemRaiseUndefinedOpcode(pVCpu);
4126 }
4127 if (!(pVCpu->cpum.GstCtx.cr0 & X86_CR0_PE))
4128 {
4129 Log(("sysret: Protected mode is required -> #GP(0)\n"));
4130 return iemRaiseGeneralProtectionFault0(pVCpu);
4131 }
4132 if (IEM_GET_CPL(pVCpu) != 0)
4133 {
4134 Log(("sysret: CPL must be 0 not %u -> #GP(0)\n", IEM_GET_CPL(pVCpu)));
4135 return iemRaiseGeneralProtectionFault0(pVCpu);
4136 }
4137
4138 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_SYSCALL_MSRS);
4139
4140 /** @todo Does SYSRET verify CS != 0 and SS != 0? Neither is valid in ring-3. */
4141 uint16_t uNewCs = (pVCpu->cpum.GstCtx.msrSTAR >> MSR_K6_STAR_SYSRET_CS_SS_SHIFT) & X86_SEL_MASK_OFF_RPL;
4142 uint16_t uNewSs = uNewCs + 8;
4143 if (enmEffOpSize == IEMMODE_64BIT)
4144 uNewCs += 16;
4145 if (uNewCs == 0 || uNewSs == 0)
4146 {
4147 Log(("sysret: msrSTAR.CS = 0 or SS = 0 -> #GP(0)\n"));
4148 return iemRaiseGeneralProtectionFault0(pVCpu);
4149 }
4150
4151 /*
4152 * Commit it.
4153 */
4154 bool f32Bit = true;
4155 if (CPUMIsGuestInLongModeEx(IEM_GET_CTX(pVCpu)))
4156 {
4157 if (enmEffOpSize == IEMMODE_64BIT)
4158 {
4159 Log(("sysret: %04x:%016RX64 [efl=%#llx] -> %04x:%016RX64 [r11=%#llx]\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.rflags.u, uNewCs, pVCpu->cpum.GstCtx.rcx, pVCpu->cpum.GstCtx.r11));
4160 /* Note! We disregard intel manual regarding the RCX canonical
4161 check, ask intel+xen why AMD doesn't do it. */
4162 pVCpu->cpum.GstCtx.rip = pVCpu->cpum.GstCtx.rcx;
4163 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESCATTR_P | X86DESCATTR_G | X86DESCATTR_L | X86DESCATTR_DT | X86_SEL_TYPE_ER_ACC
4164 | (3 << X86DESCATTR_DPL_SHIFT);
4165 f32Bit = false;
4166 }
4167 else
4168 {
4169 Log(("sysret: %04x:%016RX64 [efl=%#llx] -> %04x:%08RX32 [r11=%#llx]\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.rflags.u, uNewCs, pVCpu->cpum.GstCtx.ecx, pVCpu->cpum.GstCtx.r11));
4170 pVCpu->cpum.GstCtx.rip = pVCpu->cpum.GstCtx.ecx;
4171 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESCATTR_P | X86DESCATTR_G | X86DESCATTR_D | X86DESCATTR_DT | X86_SEL_TYPE_ER_ACC
4172 | (3 << X86DESCATTR_DPL_SHIFT);
4173 }
4174 /** @todo testcase: See what kind of flags we can make SYSRET restore and
4175 * what it really ignores. RF and VM are hinted at being zero, by AMD.
4176 * Intel says: RFLAGS := (R11 & 3C7FD7H) | 2; */
4177 pVCpu->cpum.GstCtx.rflags.u = pVCpu->cpum.GstCtx.r11 & (X86_EFL_POPF_BITS | X86_EFL_VIF | X86_EFL_VIP);
4178 pVCpu->cpum.GstCtx.rflags.u |= X86_EFL_RA1_MASK;
4179 }
4180 else
4181 {
4182 Log(("sysret: %04x:%08RX32 [efl=%#x] -> %04x:%08RX32\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip, pVCpu->cpum.GstCtx.eflags.u, uNewCs, pVCpu->cpum.GstCtx.ecx));
4183 pVCpu->cpum.GstCtx.rip = pVCpu->cpum.GstCtx.rcx;
4184 pVCpu->cpum.GstCtx.rflags.u |= X86_EFL_IF;
4185 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESCATTR_P | X86DESCATTR_G | X86DESCATTR_D | X86DESCATTR_DT | X86_SEL_TYPE_ER_ACC
4186 | (3 << X86DESCATTR_DPL_SHIFT);
4187 }
4188 pVCpu->cpum.GstCtx.cs.Sel = uNewCs | 3;
4189 pVCpu->cpum.GstCtx.cs.ValidSel = uNewCs | 3;
4190 pVCpu->cpum.GstCtx.cs.u64Base = 0;
4191 pVCpu->cpum.GstCtx.cs.u32Limit = UINT32_MAX;
4192 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
4193
4194 /* The SS hidden bits remains unchanged says AMD, we presume they set DPL to 3.
4195 Intel (and presuably VIA) OTOH sets loads valid ring-3 values it seems, see
4196 X86_BUG_SYSRET_SS_ATTRS in linux 5.3. */
4197 if (IEM_IS_GUEST_CPU_AMD(pVCpu))
4198 {
4199 Log(("sysret: ss:rsp=%04x:%08RX64 attr=%x -> %04x:%08RX64 attr=%#x\n", pVCpu->cpum.GstCtx.ss.Sel, pVCpu->cpum.GstCtx.rsp, pVCpu->cpum.GstCtx.ss.Attr.u, uNewSs | 3, pVCpu->cpum.GstCtx.rsp, pVCpu->cpum.GstCtx.ss.Attr.u | (3 << X86DESCATTR_DPL_SHIFT) ));
4200 pVCpu->cpum.GstCtx.ss.Attr.u |= (3 << X86DESCATTR_DPL_SHIFT);
4201 }
4202 else
4203 {
4204 Log(("sysret: ss:rsp=%04x:%08RX64 attr=%x -> %04x:%08RX64 attr=%#x\n", pVCpu->cpum.GstCtx.ss.Sel, pVCpu->cpum.GstCtx.rsp, pVCpu->cpum.GstCtx.ss.Attr.u, uNewSs | 3, pVCpu->cpum.GstCtx.rsp, X86DESCATTR_P | X86DESCATTR_G | X86DESCATTR_D | X86DESCATTR_DT | X86_SEL_TYPE_RW_ACC | (3 << X86DESCATTR_DPL_SHIFT) ));
4205 pVCpu->cpum.GstCtx.ss.Attr.u = X86DESCATTR_P | X86DESCATTR_G | X86DESCATTR_D | X86DESCATTR_DT | X86_SEL_TYPE_RW_ACC
4206 | (3 << X86DESCATTR_DPL_SHIFT);
4207 pVCpu->cpum.GstCtx.ss.u64Base = 0;
4208 pVCpu->cpum.GstCtx.ss.u32Limit = UINT32_MAX;
4209 }
4210 pVCpu->cpum.GstCtx.ss.Sel = uNewSs | 3;
4211 pVCpu->cpum.GstCtx.ss.ValidSel = uNewSs | 3;
4212 pVCpu->cpum.GstCtx.ss.fFlags = CPUMSELREG_FLAGS_VALID;
4213 /** @todo Testcase: verify that SS.u1Long and SS.u1DefBig are left unchanged
4214 * on sysret on AMD and not on intel. */
4215
4216 if (!f32Bit)
4217 pVCpu->iem.s.fExec = (pVCpu->iem.s.fExec & ~(IEM_F_MODE_MASK | IEM_F_X86_CPL_MASK))
4218 | (3 << IEM_F_X86_CPL_SHIFT)
4219 | IEM_F_MODE_X86_64BIT;
4220 else
4221 pVCpu->iem.s.fExec = (pVCpu->iem.s.fExec & ~(IEM_F_MODE_MASK | IEM_F_X86_CPL_MASK))
4222 | (3 << IEM_F_X86_CPL_SHIFT)
4223 | IEM_F_MODE_X86_32BIT_PROT
4224 /** @todo sort out the SS.BASE/LIM/ATTR claim by AMD and maybe we can switch to
4225 * iemCalc32BitFlatIndicatorDsEs and move this up into the above branch. */
4226 | iemCalc32BitFlatIndicator(pVCpu);
4227
4228 /* Flush the prefetch buffer. */
4229 IEM_FLUSH_PREFETCH_HEAVY(pVCpu, cbInstr);
4230
4231/** @todo single step */
4232 return VINF_SUCCESS;
4233}
4234
4235
4236/**
4237 * Implements SYSENTER (Intel, 32-bit AMD).
4238 */
4239IEM_CIMPL_DEF_0(iemCImpl_sysenter)
4240{
4241 RT_NOREF(cbInstr);
4242
4243 /*
4244 * Check preconditions.
4245 *
4246 * Note that CPUs described in the documentation may load a few odd values
4247 * into CS and SS than we allow here. This has yet to be checked on real
4248 * hardware.
4249 */
4250 if (!IEM_GET_GUEST_CPU_FEATURES(pVCpu)->fSysEnter)
4251 {
4252 Log(("sysenter: not supported -=> #UD\n"));
4253 return iemRaiseUndefinedOpcode(pVCpu);
4254 }
4255 if (!(pVCpu->cpum.GstCtx.cr0 & X86_CR0_PE))
4256 {
4257 Log(("sysenter: Protected or long mode is required -> #GP(0)\n"));
4258 return iemRaiseGeneralProtectionFault0(pVCpu);
4259 }
4260 bool fIsLongMode = CPUMIsGuestInLongModeEx(IEM_GET_CTX(pVCpu));
4261 if (IEM_IS_GUEST_CPU_AMD(pVCpu) && fIsLongMode)
4262 {
4263 Log(("sysenter: Only available in protected mode on AMD -> #UD\n"));
4264 return iemRaiseUndefinedOpcode(pVCpu);
4265 }
4266 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_SYSENTER_MSRS);
4267 uint16_t uNewCs = pVCpu->cpum.GstCtx.SysEnter.cs;
4268 if ((uNewCs & X86_SEL_MASK_OFF_RPL) == 0)
4269 {
4270 Log(("sysenter: SYSENTER_CS = %#x -> #GP(0)\n", uNewCs));
4271 return iemRaiseGeneralProtectionFault0(pVCpu);
4272 }
4273
4274 /* This test isn't in the docs, it's just a safeguard against missing
4275 canonical checks when writing the registers. */
4276 if (RT_LIKELY( !fIsLongMode
4277 || ( IEM_IS_CANONICAL(pVCpu->cpum.GstCtx.SysEnter.eip)
4278 && IEM_IS_CANONICAL(pVCpu->cpum.GstCtx.SysEnter.esp))))
4279 { /* likely */ }
4280 else
4281 {
4282 Log(("sysenter: SYSENTER_EIP = %#RX64 or/and SYSENTER_ESP = %#RX64 not canonical -> #GP(0)\n",
4283 pVCpu->cpum.GstCtx.SysEnter.eip, pVCpu->cpum.GstCtx.SysEnter.esp));
4284 return iemRaiseUndefinedOpcode(pVCpu);
4285 }
4286
4287/** @todo Test: Sysenter from ring-0, ring-1 and ring-2. */
4288
4289 /*
4290 * Update registers and commit.
4291 */
4292 if (fIsLongMode)
4293 {
4294 Log(("sysenter: %04x:%016RX64 [efl=%#llx] -> %04x:%016RX64\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
4295 pVCpu->cpum.GstCtx.rflags.u, uNewCs & X86_SEL_MASK_OFF_RPL, pVCpu->cpum.GstCtx.SysEnter.eip));
4296 pVCpu->cpum.GstCtx.rip = pVCpu->cpum.GstCtx.SysEnter.eip;
4297 pVCpu->cpum.GstCtx.rsp = pVCpu->cpum.GstCtx.SysEnter.esp;
4298 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESCATTR_L | X86DESCATTR_G | X86DESCATTR_P | X86DESCATTR_DT
4299 | X86DESCATTR_LIMIT_HIGH | X86_SEL_TYPE_ER_ACC;
4300 pVCpu->iem.s.fExec = (pVCpu->iem.s.fExec & ~(IEM_F_MODE_MASK | IEM_F_X86_CPL_MASK))
4301 | IEM_F_MODE_X86_64BIT;
4302 }
4303 else
4304 {
4305 Log(("sysenter: %04x:%08RX32 [efl=%#llx] -> %04x:%08RX32\n", pVCpu->cpum.GstCtx.cs.Sel, (uint32_t)pVCpu->cpum.GstCtx.rip,
4306 pVCpu->cpum.GstCtx.rflags.u, uNewCs & X86_SEL_MASK_OFF_RPL, (uint32_t)pVCpu->cpum.GstCtx.SysEnter.eip));
4307 pVCpu->cpum.GstCtx.rip = (uint32_t)pVCpu->cpum.GstCtx.SysEnter.eip;
4308 pVCpu->cpum.GstCtx.rsp = (uint32_t)pVCpu->cpum.GstCtx.SysEnter.esp;
4309 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESCATTR_D | X86DESCATTR_G | X86DESCATTR_P | X86DESCATTR_DT
4310 | X86DESCATTR_LIMIT_HIGH | X86_SEL_TYPE_ER_ACC;
4311 pVCpu->iem.s.fExec = (pVCpu->iem.s.fExec & ~(IEM_F_MODE_MASK | IEM_F_X86_CPL_MASK))
4312 | IEM_F_MODE_X86_32BIT_PROT
4313 | iemCalc32BitFlatIndicatorEsDs(pVCpu);
4314 }
4315 pVCpu->cpum.GstCtx.cs.Sel = uNewCs & X86_SEL_MASK_OFF_RPL;
4316 pVCpu->cpum.GstCtx.cs.ValidSel = uNewCs & X86_SEL_MASK_OFF_RPL;
4317 pVCpu->cpum.GstCtx.cs.u64Base = 0;
4318 pVCpu->cpum.GstCtx.cs.u32Limit = UINT32_MAX;
4319 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
4320
4321 pVCpu->cpum.GstCtx.ss.Sel = (uNewCs & X86_SEL_MASK_OFF_RPL) + 8;
4322 pVCpu->cpum.GstCtx.ss.ValidSel = (uNewCs & X86_SEL_MASK_OFF_RPL) + 8;
4323 pVCpu->cpum.GstCtx.ss.u64Base = 0;
4324 pVCpu->cpum.GstCtx.ss.u32Limit = UINT32_MAX;
4325 pVCpu->cpum.GstCtx.ss.Attr.u = X86DESCATTR_D | X86DESCATTR_G | X86DESCATTR_P | X86DESCATTR_DT
4326 | X86DESCATTR_LIMIT_HIGH | X86_SEL_TYPE_RW_ACC;
4327 pVCpu->cpum.GstCtx.ss.fFlags = CPUMSELREG_FLAGS_VALID;
4328
4329 pVCpu->cpum.GstCtx.rflags.Bits.u1IF = 0;
4330 pVCpu->cpum.GstCtx.rflags.Bits.u1VM = 0;
4331 pVCpu->cpum.GstCtx.rflags.Bits.u1RF = 0;
4332
4333 /* Flush the prefetch buffer. */
4334 IEM_FLUSH_PREFETCH_HEAVY(pVCpu, cbInstr);
4335
4336/** @todo single stepping */
4337 return VINF_SUCCESS;
4338}
4339
4340
4341/**
4342 * Implements SYSEXIT (Intel, 32-bit AMD).
4343 *
4344 * @param enmEffOpSize The effective operand size.
4345 */
4346IEM_CIMPL_DEF_1(iemCImpl_sysexit, IEMMODE, enmEffOpSize)
4347{
4348 RT_NOREF(cbInstr);
4349
4350 /*
4351 * Check preconditions.
4352 *
4353 * Note that CPUs described in the documentation may load a few odd values
4354 * into CS and SS than we allow here. This has yet to be checked on real
4355 * hardware.
4356 */
4357 if (!IEM_GET_GUEST_CPU_FEATURES(pVCpu)->fSysEnter)
4358 {
4359 Log(("sysexit: not supported -=> #UD\n"));
4360 return iemRaiseUndefinedOpcode(pVCpu);
4361 }
4362 if (!(pVCpu->cpum.GstCtx.cr0 & X86_CR0_PE))
4363 {
4364 Log(("sysexit: Protected or long mode is required -> #GP(0)\n"));
4365 return iemRaiseGeneralProtectionFault0(pVCpu);
4366 }
4367 bool fIsLongMode = CPUMIsGuestInLongModeEx(IEM_GET_CTX(pVCpu));
4368 if (IEM_IS_GUEST_CPU_AMD(pVCpu) && fIsLongMode)
4369 {
4370 Log(("sysexit: Only available in protected mode on AMD -> #UD\n"));
4371 return iemRaiseUndefinedOpcode(pVCpu);
4372 }
4373 if (IEM_GET_CPL(pVCpu) != 0)
4374 {
4375 Log(("sysexit: CPL(=%u) != 0 -> #GP(0)\n", IEM_GET_CPL(pVCpu)));
4376 return iemRaiseGeneralProtectionFault0(pVCpu);
4377 }
4378 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_SYSENTER_MSRS);
4379 uint16_t uNewCs = pVCpu->cpum.GstCtx.SysEnter.cs;
4380 if ((uNewCs & X86_SEL_MASK_OFF_RPL) == 0)
4381 {
4382 Log(("sysexit: SYSENTER_CS = %#x -> #GP(0)\n", uNewCs));
4383 return iemRaiseGeneralProtectionFault0(pVCpu);
4384 }
4385
4386 /*
4387 * Update registers and commit.
4388 */
4389 if (enmEffOpSize == IEMMODE_64BIT)
4390 {
4391 Log(("sysexit: %04x:%016RX64 [efl=%#llx] -> %04x:%016RX64\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
4392 pVCpu->cpum.GstCtx.rflags.u, (uNewCs | 3) + 32, pVCpu->cpum.GstCtx.rcx));
4393 pVCpu->cpum.GstCtx.rip = pVCpu->cpum.GstCtx.rdx;
4394 pVCpu->cpum.GstCtx.rsp = pVCpu->cpum.GstCtx.rcx;
4395 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESCATTR_L | X86DESCATTR_G | X86DESCATTR_P | X86DESCATTR_DT
4396 | X86DESCATTR_LIMIT_HIGH | X86_SEL_TYPE_ER_ACC | (3 << X86DESCATTR_DPL_SHIFT);
4397 pVCpu->cpum.GstCtx.cs.Sel = (uNewCs | 3) + 32;
4398 pVCpu->cpum.GstCtx.cs.ValidSel = (uNewCs | 3) + 32;
4399 pVCpu->cpum.GstCtx.ss.Sel = (uNewCs | 3) + 40;
4400 pVCpu->cpum.GstCtx.ss.ValidSel = (uNewCs | 3) + 40;
4401
4402 pVCpu->iem.s.fExec = (pVCpu->iem.s.fExec & ~(IEM_F_MODE_MASK | IEM_F_X86_CPL_MASK))
4403 | (3 << IEM_F_X86_CPL_SHIFT)
4404 | IEM_F_MODE_X86_64BIT;
4405 }
4406 else
4407 {
4408 Log(("sysexit: %04x:%08RX64 [efl=%#llx] -> %04x:%08RX32\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
4409 pVCpu->cpum.GstCtx.rflags.u, (uNewCs | 3) + 16, (uint32_t)pVCpu->cpum.GstCtx.edx));
4410 pVCpu->cpum.GstCtx.rip = pVCpu->cpum.GstCtx.edx;
4411 pVCpu->cpum.GstCtx.rsp = pVCpu->cpum.GstCtx.ecx;
4412 pVCpu->cpum.GstCtx.cs.Attr.u = X86DESCATTR_D | X86DESCATTR_G | X86DESCATTR_P | X86DESCATTR_DT
4413 | X86DESCATTR_LIMIT_HIGH | X86_SEL_TYPE_ER_ACC | (3 << X86DESCATTR_DPL_SHIFT);
4414 pVCpu->cpum.GstCtx.cs.Sel = (uNewCs | 3) + 16;
4415 pVCpu->cpum.GstCtx.cs.ValidSel = (uNewCs | 3) + 16;
4416 pVCpu->cpum.GstCtx.ss.Sel = (uNewCs | 3) + 24;
4417 pVCpu->cpum.GstCtx.ss.ValidSel = (uNewCs | 3) + 24;
4418
4419 pVCpu->iem.s.fExec = (pVCpu->iem.s.fExec & ~(IEM_F_MODE_MASK | IEM_F_X86_CPL_MASK))
4420 | (3 << IEM_F_X86_CPL_SHIFT)
4421 | IEM_F_MODE_X86_32BIT_PROT
4422 | iemCalc32BitFlatIndicatorEsDs(pVCpu);
4423 }
4424 pVCpu->cpum.GstCtx.cs.u64Base = 0;
4425 pVCpu->cpum.GstCtx.cs.u32Limit = UINT32_MAX;
4426 pVCpu->cpum.GstCtx.cs.fFlags = CPUMSELREG_FLAGS_VALID;
4427
4428 pVCpu->cpum.GstCtx.ss.u64Base = 0;
4429 pVCpu->cpum.GstCtx.ss.u32Limit = UINT32_MAX;
4430 pVCpu->cpum.GstCtx.ss.Attr.u = X86DESCATTR_D | X86DESCATTR_G | X86DESCATTR_P | X86DESCATTR_DT
4431 | X86DESCATTR_LIMIT_HIGH | X86_SEL_TYPE_RW_ACC | (3 << X86DESCATTR_DPL_SHIFT);
4432 pVCpu->cpum.GstCtx.ss.fFlags = CPUMSELREG_FLAGS_VALID;
4433 pVCpu->cpum.GstCtx.rflags.Bits.u1RF = 0;
4434
4435/** @todo single stepping */
4436
4437 /* Flush the prefetch buffer. */
4438 IEM_FLUSH_PREFETCH_HEAVY(pVCpu, cbInstr);
4439
4440 return VINF_SUCCESS;
4441}
4442
4443
4444/**
4445 * Completes a MOV SReg,XXX or POP SReg instruction.
4446 *
4447 * When not modifying SS or when we're already in an interrupt shadow we
4448 * can update RIP and finish the instruction the normal way.
4449 *
4450 * Otherwise, the MOV/POP SS interrupt shadow that we now enable will block
4451 * both TF and DBx events. The TF will be ignored while the DBx ones will
4452 * be delayed till the next instruction boundrary. For more details see
4453 * @sdmv3{077,200,6.8.3,Masking Exceptions and Interrupts When Switching Stacks}.
4454 */
4455DECLINLINE(VBOXSTRICTRC) iemCImpl_LoadSRegFinish(PVMCPUCC pVCpu, uint8_t cbInstr, uint8_t iSegReg)
4456{
4457 if (iSegReg != X86_SREG_SS || CPUMIsInInterruptShadow(&pVCpu->cpum.GstCtx))
4458 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
4459
4460 iemRegAddToRip(pVCpu, cbInstr);
4461 pVCpu->cpum.GstCtx.eflags.uBoth &= ~X86_EFL_RF; /* Shadow int isn't set and DRx is delayed, so only clear RF. */
4462 CPUMSetInInterruptShadowSs(&pVCpu->cpum.GstCtx);
4463
4464 return VINF_SUCCESS;
4465}
4466
4467
4468/**
4469 * Common worker for 'pop SReg', 'mov SReg, GReg' and 'lXs GReg, reg/mem'.
4470 *
4471 * @param pVCpu The cross context virtual CPU structure of the calling
4472 * thread.
4473 * @param iSegReg The segment register number (valid).
4474 * @param uSel The new selector value.
4475 */
4476static VBOXSTRICTRC iemCImpl_LoadSRegWorker(PVMCPUCC pVCpu, uint8_t iSegReg, uint16_t uSel)
4477{
4478 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_SREG_FROM_IDX(iSegReg));
4479 uint16_t *pSel = iemSRegRef(pVCpu, iSegReg);
4480 PCPUMSELREGHID pHid = iemSRegGetHid(pVCpu, iSegReg);
4481
4482 Assert(iSegReg <= X86_SREG_GS && iSegReg != X86_SREG_CS);
4483
4484 /*
4485 * Real mode and V8086 mode are easy.
4486 */
4487 if (IEM_IS_REAL_OR_V86_MODE(pVCpu))
4488 {
4489 *pSel = uSel;
4490 pHid->u64Base = (uint32_t)uSel << 4;
4491 pHid->ValidSel = uSel;
4492 pHid->fFlags = CPUMSELREG_FLAGS_VALID;
4493#if 0 /* AMD Volume 2, chapter 4.1 - "real mode segmentation" - states that limit and attributes are untouched. */
4494 /** @todo Does the CPU actually load limits and attributes in the
4495 * real/V8086 mode segment load case? It doesn't for CS in far
4496 * jumps... Affects unreal mode. */
4497 pHid->u32Limit = 0xffff;
4498 pHid->Attr.u = 0;
4499 pHid->Attr.n.u1Present = 1;
4500 pHid->Attr.n.u1DescType = 1;
4501 pHid->Attr.n.u4Type = iSegReg != X86_SREG_CS
4502 ? X86_SEL_TYPE_RW
4503 : X86_SEL_TYPE_READ | X86_SEL_TYPE_CODE;
4504#endif
4505
4506 /* Update the FLAT 32-bit mode flag, if we're in 32-bit unreal mode (unlikely): */
4507 if (RT_LIKELY(!IEM_IS_32BIT_CODE(pVCpu)))
4508 { /* likely */ }
4509 else if (uSel != 0)
4510 pVCpu->iem.s.fExec &= ~IEM_F_MODE_X86_FLAT_OR_PRE_386_MASK;
4511 else
4512 pVCpu->iem.s.fExec = (pVCpu->iem.s.fExec & ~IEM_F_MODE_X86_FLAT_OR_PRE_386_MASK)
4513 | iemCalc32BitFlatIndicator(pVCpu);
4514 }
4515 /*
4516 * Protected / long mode - null segment.
4517 *
4518 * Check if it's a null segment selector value first, that's OK for DS, ES,
4519 * FS and GS. If not null, then we have to load and parse the descriptor.
4520 */
4521 else if (!(uSel & X86_SEL_MASK_OFF_RPL))
4522 {
4523 Assert(iSegReg != X86_SREG_CS); /** @todo testcase for \#UD on MOV CS, ax! */
4524 if (iSegReg == X86_SREG_SS)
4525 {
4526 /* In 64-bit kernel mode, the stack can be 0 because of the way
4527 interrupts are dispatched. AMD seems to have a slighly more
4528 relaxed relationship to SS.RPL than intel does. */
4529 /** @todo We cannot 'mov ss, 3' in 64-bit kernel mode, can we? There is a testcase (bs-cpu-xcpt-1), but double check this! */
4530 if ( !IEM_IS_64BIT_CODE(pVCpu)
4531 || IEM_GET_CPL(pVCpu) > 2
4532 || ( uSel != IEM_GET_CPL(pVCpu)
4533 && !IEM_IS_GUEST_CPU_AMD(pVCpu)) )
4534 {
4535 Log(("load sreg %#x -> invalid stack selector, #GP(0)\n", uSel));
4536 return iemRaiseGeneralProtectionFault0(pVCpu);
4537 }
4538 }
4539
4540 *pSel = uSel; /* Not RPL, remember :-) */
4541 iemHlpLoadNullDataSelectorProt(pVCpu, pHid, uSel);
4542 if (iSegReg == X86_SREG_SS)
4543 pHid->Attr.u |= IEM_GET_CPL(pVCpu) << X86DESCATTR_DPL_SHIFT;
4544
4545 /* This will affect the FLAT 32-bit mode flag: */
4546 if ( iSegReg < X86_SREG_FS
4547 && IEM_IS_32BIT_CODE(pVCpu))
4548 pVCpu->iem.s.fExec &= ~IEM_F_MODE_X86_FLAT_OR_PRE_386_MASK;
4549 }
4550 /*
4551 * Protected / long mode.
4552 */
4553 else
4554 {
4555 /* Fetch the descriptor. */
4556 IEMSELDESC Desc;
4557 VBOXSTRICTRC rcStrict = iemMemFetchSelDesc(pVCpu, &Desc, uSel, X86_XCPT_GP); /** @todo Correct exception? */
4558 if (rcStrict != VINF_SUCCESS)
4559 return rcStrict;
4560
4561 /* Check GPs first. */
4562 if (!Desc.Legacy.Gen.u1DescType)
4563 {
4564 Log(("load sreg %d (=%#x) - system selector (%#x) -> #GP\n", iSegReg, uSel, Desc.Legacy.Gen.u4Type));
4565 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
4566 }
4567 if (iSegReg == X86_SREG_SS) /* SS gets different treatment */
4568 {
4569 if ( (Desc.Legacy.Gen.u4Type & X86_SEL_TYPE_CODE)
4570 || !(Desc.Legacy.Gen.u4Type & X86_SEL_TYPE_WRITE) )
4571 {
4572 Log(("load sreg SS, %#x - code or read only (%#x) -> #GP\n", uSel, Desc.Legacy.Gen.u4Type));
4573 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
4574 }
4575 if ((uSel & X86_SEL_RPL) != IEM_GET_CPL(pVCpu))
4576 {
4577 Log(("load sreg SS, %#x - RPL and CPL (%d) differs -> #GP\n", uSel, IEM_GET_CPL(pVCpu)));
4578 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
4579 }
4580 if (Desc.Legacy.Gen.u2Dpl != IEM_GET_CPL(pVCpu))
4581 {
4582 Log(("load sreg SS, %#x - DPL (%d) and CPL (%d) differs -> #GP\n", uSel, Desc.Legacy.Gen.u2Dpl, IEM_GET_CPL(pVCpu)));
4583 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
4584 }
4585 }
4586 else
4587 {
4588 if ((Desc.Legacy.Gen.u4Type & (X86_SEL_TYPE_CODE | X86_SEL_TYPE_READ)) == X86_SEL_TYPE_CODE)
4589 {
4590 Log(("load sreg%u, %#x - execute only segment -> #GP\n", iSegReg, uSel));
4591 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
4592 }
4593 if ( (Desc.Legacy.Gen.u4Type & (X86_SEL_TYPE_CODE | X86_SEL_TYPE_CONF))
4594 != (X86_SEL_TYPE_CODE | X86_SEL_TYPE_CONF))
4595 {
4596#if 0 /* this is what intel says. */
4597 if ( (uSel & X86_SEL_RPL) > Desc.Legacy.Gen.u2Dpl
4598 && IEM_GET_CPL(pVCpu) > Desc.Legacy.Gen.u2Dpl)
4599 {
4600 Log(("load sreg%u, %#x - both RPL (%d) and CPL (%d) are greater than DPL (%d) -> #GP\n",
4601 iSegReg, uSel, (uSel & X86_SEL_RPL), IEM_GET_CPL(pVCpu), Desc.Legacy.Gen.u2Dpl));
4602 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
4603 }
4604#else /* this is what makes more sense. */
4605 if ((unsigned)(uSel & X86_SEL_RPL) > Desc.Legacy.Gen.u2Dpl)
4606 {
4607 Log(("load sreg%u, %#x - RPL (%d) is greater than DPL (%d) -> #GP\n",
4608 iSegReg, uSel, (uSel & X86_SEL_RPL), Desc.Legacy.Gen.u2Dpl));
4609 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
4610 }
4611 if (IEM_GET_CPL(pVCpu) > Desc.Legacy.Gen.u2Dpl)
4612 {
4613 Log(("load sreg%u, %#x - CPL (%d) is greater than DPL (%d) -> #GP\n",
4614 iSegReg, uSel, IEM_GET_CPL(pVCpu), Desc.Legacy.Gen.u2Dpl));
4615 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uSel);
4616 }
4617#endif
4618 }
4619 }
4620
4621 /* Is it there? */
4622 if (!Desc.Legacy.Gen.u1Present)
4623 {
4624 Log(("load sreg%d,%#x - segment not present -> #NP\n", iSegReg, uSel));
4625 return iemRaiseSelectorNotPresentBySelector(pVCpu, uSel);
4626 }
4627
4628 /* The base and limit. */
4629 uint32_t cbLimit = X86DESC_LIMIT_G(&Desc.Legacy);
4630 uint64_t u64Base = X86DESC_BASE(&Desc.Legacy);
4631
4632 /*
4633 * Ok, everything checked out fine. Now set the accessed bit before
4634 * committing the result into the registers.
4635 */
4636 if (!(Desc.Legacy.Gen.u4Type & X86_SEL_TYPE_ACCESSED))
4637 {
4638 rcStrict = iemMemMarkSelDescAccessed(pVCpu, uSel);
4639 if (rcStrict != VINF_SUCCESS)
4640 return rcStrict;
4641 Desc.Legacy.Gen.u4Type |= X86_SEL_TYPE_ACCESSED;
4642 }
4643
4644 /* commit */
4645 *pSel = uSel;
4646 pHid->Attr.u = X86DESC_GET_HID_ATTR(&Desc.Legacy);
4647 pHid->u32Limit = cbLimit;
4648 pHid->u64Base = u64Base;
4649 pHid->ValidSel = uSel;
4650 pHid->fFlags = CPUMSELREG_FLAGS_VALID;
4651
4652 /** @todo check if the hidden bits are loaded correctly for 64-bit
4653 * mode. */
4654
4655 /* This will affect the FLAT 32-bit mode flag: */
4656 if ( iSegReg < X86_SREG_FS
4657 && IEM_IS_32BIT_CODE(pVCpu))
4658 pVCpu->iem.s.fExec = (pVCpu->iem.s.fExec & ~IEM_F_MODE_X86_FLAT_OR_PRE_386_MASK)
4659 | iemCalc32BitFlatIndicator(pVCpu);
4660 }
4661
4662 Assert(CPUMSELREG_ARE_HIDDEN_PARTS_VALID(pVCpu, pHid));
4663 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_HIDDEN_SEL_REGS);
4664 return VINF_SUCCESS;
4665}
4666
4667
4668/**
4669 * Implements 'mov SReg, r/m'.
4670 *
4671 * @param iSegReg The segment register number (valid).
4672 * @param uSel The new selector value.
4673 */
4674IEM_CIMPL_DEF_2(iemCImpl_load_SReg, uint8_t, iSegReg, uint16_t, uSel)
4675{
4676 VBOXSTRICTRC rcStrict = iemCImpl_LoadSRegWorker(pVCpu, iSegReg, uSel);
4677 if (rcStrict == VINF_SUCCESS)
4678 rcStrict = iemCImpl_LoadSRegFinish(pVCpu, cbInstr, iSegReg);
4679 return rcStrict;
4680}
4681
4682
4683/**
4684 * Implements 'pop SReg'.
4685 *
4686 * @param iSegReg The segment register number (valid).
4687 * @param enmEffOpSize The efficient operand size (valid).
4688 */
4689IEM_CIMPL_DEF_2(iemCImpl_pop_Sreg, uint8_t, iSegReg, IEMMODE, enmEffOpSize)
4690{
4691 VBOXSTRICTRC rcStrict;
4692
4693 /*
4694 * Read the selector off the stack and join paths with mov ss, reg.
4695 */
4696 RTUINT64U TmpRsp;
4697 TmpRsp.u = pVCpu->cpum.GstCtx.rsp;
4698 switch (enmEffOpSize)
4699 {
4700 case IEMMODE_16BIT:
4701 {
4702 uint16_t uSel;
4703 rcStrict = iemMemStackPopU16Ex(pVCpu, &uSel, &TmpRsp);
4704 if (rcStrict == VINF_SUCCESS)
4705 rcStrict = iemCImpl_LoadSRegWorker(pVCpu, iSegReg, uSel);
4706 break;
4707 }
4708
4709 case IEMMODE_32BIT:
4710 {
4711 /* Modern Intel CPU only does a WORD sized access here, both as
4712 segmentation and paging is concerned. So, we have to emulate
4713 this to make bs3-cpu-weird-1 happy. */
4714 if (IEM_IS_GUEST_CPU_INTEL(pVCpu))
4715 {
4716 /* We don't have flexible enough stack primitives here, so just
4717 do a word pop and add two bytes to SP/RSP on success. */
4718 uint16_t uSel;
4719 rcStrict = iemMemStackPopU16Ex(pVCpu, &uSel, &TmpRsp);
4720 if (rcStrict == VINF_SUCCESS)
4721 {
4722 iemRegAddToRspEx(pVCpu, &TmpRsp, sizeof(uint32_t) - sizeof(uint16_t));
4723 rcStrict = iemCImpl_LoadSRegWorker(pVCpu, iSegReg, uSel);
4724 }
4725 }
4726 else
4727 {
4728 uint32_t u32Value;
4729 rcStrict = iemMemStackPopU32Ex(pVCpu, &u32Value, &TmpRsp);
4730 if (rcStrict == VINF_SUCCESS)
4731 rcStrict = iemCImpl_LoadSRegWorker(pVCpu, iSegReg, (uint16_t)u32Value);
4732 }
4733 break;
4734 }
4735
4736 case IEMMODE_64BIT:
4737 {
4738 /* Like for the 32-bit case above, intel only does a WORD access. */
4739 if (IEM_IS_GUEST_CPU_INTEL(pVCpu))
4740 {
4741 uint16_t uSel;
4742 rcStrict = iemMemStackPopU16Ex(pVCpu, &uSel, &TmpRsp);
4743 if (rcStrict == VINF_SUCCESS)
4744 {
4745 iemRegAddToRspEx(pVCpu, &TmpRsp, sizeof(uint64_t) - sizeof(uint16_t));
4746 rcStrict = iemCImpl_LoadSRegWorker(pVCpu, iSegReg, uSel);
4747 }
4748 }
4749 else
4750 {
4751 uint64_t u64Value;
4752 rcStrict = iemMemStackPopU64Ex(pVCpu, &u64Value, &TmpRsp);
4753 if (rcStrict == VINF_SUCCESS)
4754 rcStrict = iemCImpl_LoadSRegWorker(pVCpu, iSegReg, (uint16_t)u64Value);
4755 }
4756 break;
4757 }
4758 IEM_NOT_REACHED_DEFAULT_CASE_RET();
4759 }
4760
4761 /*
4762 * If the load succeeded, commit the stack change and finish the instruction.
4763 */
4764 if (rcStrict == VINF_SUCCESS)
4765 {
4766 pVCpu->cpum.GstCtx.rsp = TmpRsp.u;
4767 rcStrict = iemCImpl_LoadSRegFinish(pVCpu, cbInstr, iSegReg);
4768 }
4769
4770 return rcStrict;
4771}
4772
4773
4774/**
4775 * Implements lgs, lfs, les, lds & lss.
4776 */
4777IEM_CIMPL_DEF_5(iemCImpl_load_SReg_Greg, uint16_t, uSel, uint64_t, offSeg, uint8_t, iSegReg, uint8_t, iGReg, IEMMODE, enmEffOpSize)
4778{
4779 /*
4780 * Use iemCImpl_LoadSRegWorker to do the tricky segment register loading.
4781 */
4782 /** @todo verify and test that mov, pop and lXs works the segment
4783 * register loading in the exact same way. */
4784 VBOXSTRICTRC rcStrict = iemCImpl_LoadSRegWorker(pVCpu, iSegReg, uSel);
4785 if (rcStrict == VINF_SUCCESS)
4786 {
4787 switch (enmEffOpSize)
4788 {
4789 case IEMMODE_16BIT:
4790 iemGRegStoreU16(pVCpu, iGReg, offSeg);
4791 break;
4792 case IEMMODE_32BIT:
4793 case IEMMODE_64BIT:
4794 iemGRegStoreU64(pVCpu, iGReg, offSeg);
4795 break;
4796 IEM_NOT_REACHED_DEFAULT_CASE_RET();
4797 }
4798 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
4799 }
4800 return rcStrict;
4801}
4802
4803
4804/**
4805 * Helper for VERR, VERW, LAR, and LSL and loads the descriptor into memory.
4806 *
4807 * @retval VINF_SUCCESS on success.
4808 * @retval VINF_IEM_SELECTOR_NOT_OK if the selector isn't ok.
4809 * @retval iemMemFetchSysU64 return value.
4810 *
4811 * @param pVCpu The cross context virtual CPU structure of the calling thread.
4812 * @param uSel The selector value.
4813 * @param fAllowSysDesc Whether system descriptors are OK or not.
4814 * @param pDesc Where to return the descriptor on success.
4815 */
4816static VBOXSTRICTRC iemCImpl_LoadDescHelper(PVMCPUCC pVCpu, uint16_t uSel, bool fAllowSysDesc, PIEMSELDESC pDesc)
4817{
4818 pDesc->Long.au64[0] = 0;
4819 pDesc->Long.au64[1] = 0;
4820
4821 if (!(uSel & X86_SEL_MASK_OFF_RPL)) /** @todo test this on 64-bit. */
4822 return VINF_IEM_SELECTOR_NOT_OK;
4823
4824 /* Within the table limits? */
4825 RTGCPTR GCPtrBase;
4826 if (uSel & X86_SEL_LDT)
4827 {
4828 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_LDTR);
4829 if ( !pVCpu->cpum.GstCtx.ldtr.Attr.n.u1Present
4830 || (uSel | X86_SEL_RPL_LDT) > pVCpu->cpum.GstCtx.ldtr.u32Limit )
4831 return VINF_IEM_SELECTOR_NOT_OK;
4832 GCPtrBase = pVCpu->cpum.GstCtx.ldtr.u64Base;
4833 }
4834 else
4835 {
4836 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_GDTR);
4837 if ((uSel | X86_SEL_RPL_LDT) > pVCpu->cpum.GstCtx.gdtr.cbGdt)
4838 return VINF_IEM_SELECTOR_NOT_OK;
4839 GCPtrBase = pVCpu->cpum.GstCtx.gdtr.pGdt;
4840 }
4841
4842 /* Fetch the descriptor. */
4843 VBOXSTRICTRC rcStrict = iemMemFetchSysU64(pVCpu, &pDesc->Legacy.u, UINT8_MAX, GCPtrBase + (uSel & X86_SEL_MASK));
4844 if (rcStrict != VINF_SUCCESS)
4845 return rcStrict;
4846 if (!pDesc->Legacy.Gen.u1DescType)
4847 {
4848 if (!fAllowSysDesc)
4849 return VINF_IEM_SELECTOR_NOT_OK;
4850 if (CPUMIsGuestInLongModeEx(IEM_GET_CTX(pVCpu)))
4851 {
4852 rcStrict = iemMemFetchSysU64(pVCpu, &pDesc->Long.au64[1], UINT8_MAX, GCPtrBase + (uSel & X86_SEL_MASK) + 8);
4853 if (rcStrict != VINF_SUCCESS)
4854 return rcStrict;
4855 }
4856
4857 }
4858
4859 return VINF_SUCCESS;
4860}
4861
4862
4863/**
4864 * Implements verr (fWrite = false) and verw (fWrite = true).
4865 */
4866IEM_CIMPL_DEF_2(iemCImpl_VerX, uint16_t, uSel, bool, fWrite)
4867{
4868 Assert(!IEM_IS_REAL_OR_V86_MODE(pVCpu));
4869
4870 /** @todo figure whether the accessed bit is set or not. */
4871
4872 bool fAccessible = true;
4873 IEMSELDESC Desc;
4874 VBOXSTRICTRC rcStrict = iemCImpl_LoadDescHelper(pVCpu, uSel, false /*fAllowSysDesc*/, &Desc);
4875 if (rcStrict == VINF_SUCCESS)
4876 {
4877 /* Check the descriptor, order doesn't matter much here. */
4878 if ( !Desc.Legacy.Gen.u1DescType
4879 || !Desc.Legacy.Gen.u1Present)
4880 fAccessible = false;
4881 else
4882 {
4883 if ( fWrite
4884 ? (Desc.Legacy.Gen.u4Type & (X86_SEL_TYPE_CODE | X86_SEL_TYPE_WRITE)) != X86_SEL_TYPE_WRITE
4885 : (Desc.Legacy.Gen.u4Type & (X86_SEL_TYPE_CODE | X86_SEL_TYPE_READ)) == X86_SEL_TYPE_CODE)
4886 fAccessible = false;
4887
4888 /** @todo testcase for the conforming behavior. */
4889 if ( (Desc.Legacy.Gen.u4Type & (X86_SEL_TYPE_CODE | X86_SEL_TYPE_CONF))
4890 != (X86_SEL_TYPE_CODE | X86_SEL_TYPE_CONF))
4891 {
4892 if ((unsigned)(uSel & X86_SEL_RPL) > Desc.Legacy.Gen.u2Dpl)
4893 fAccessible = false;
4894 else if (IEM_GET_CPL(pVCpu) > Desc.Legacy.Gen.u2Dpl)
4895 fAccessible = false;
4896 }
4897 }
4898
4899 }
4900 else if (rcStrict == VINF_IEM_SELECTOR_NOT_OK)
4901 fAccessible = false;
4902 else
4903 return rcStrict;
4904
4905 /* commit */
4906 pVCpu->cpum.GstCtx.eflags.Bits.u1ZF = fAccessible;
4907
4908 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
4909}
4910
4911
4912/**
4913 * Implements LAR and LSL with 64-bit operand size.
4914 *
4915 * @returns VINF_SUCCESS.
4916 * @param pu64Dst Pointer to the destination register.
4917 * @param uSel The selector to load details for.
4918 * @param fIsLar true = LAR, false = LSL.
4919 */
4920IEM_CIMPL_DEF_3(iemCImpl_LarLsl_u64, uint64_t *, pu64Dst, uint16_t, uSel, bool, fIsLar)
4921{
4922 Assert(!IEM_IS_REAL_OR_V86_MODE(pVCpu));
4923
4924 /** @todo figure whether the accessed bit is set or not. */
4925
4926 bool fDescOk = true;
4927 IEMSELDESC Desc;
4928 VBOXSTRICTRC rcStrict = iemCImpl_LoadDescHelper(pVCpu, uSel, true /*fAllowSysDesc*/, &Desc);
4929 if (rcStrict == VINF_SUCCESS)
4930 {
4931 /*
4932 * Check the descriptor type.
4933 */
4934 if (!Desc.Legacy.Gen.u1DescType)
4935 {
4936 if (CPUMIsGuestInLongModeEx(IEM_GET_CTX(pVCpu)))
4937 {
4938 if (Desc.Long.Gen.u5Zeros)
4939 fDescOk = false;
4940 else
4941 switch (Desc.Long.Gen.u4Type)
4942 {
4943 /** @todo Intel lists 0 as valid for LSL, verify whether that's correct */
4944 case AMD64_SEL_TYPE_SYS_TSS_AVAIL:
4945 case AMD64_SEL_TYPE_SYS_TSS_BUSY:
4946 case AMD64_SEL_TYPE_SYS_LDT: /** @todo Intel lists this as invalid for LAR, AMD and 32-bit does otherwise. */
4947 break;
4948 case AMD64_SEL_TYPE_SYS_CALL_GATE:
4949 fDescOk = fIsLar;
4950 break;
4951 default:
4952 fDescOk = false;
4953 break;
4954 }
4955 }
4956 else
4957 {
4958 switch (Desc.Long.Gen.u4Type)
4959 {
4960 case X86_SEL_TYPE_SYS_286_TSS_AVAIL:
4961 case X86_SEL_TYPE_SYS_286_TSS_BUSY:
4962 case X86_SEL_TYPE_SYS_386_TSS_AVAIL:
4963 case X86_SEL_TYPE_SYS_386_TSS_BUSY:
4964 case X86_SEL_TYPE_SYS_LDT:
4965 break;
4966 case X86_SEL_TYPE_SYS_286_CALL_GATE:
4967 case X86_SEL_TYPE_SYS_TASK_GATE:
4968 case X86_SEL_TYPE_SYS_386_CALL_GATE:
4969 fDescOk = fIsLar;
4970 break;
4971 default:
4972 fDescOk = false;
4973 break;
4974 }
4975 }
4976 }
4977 if (fDescOk)
4978 {
4979 /*
4980 * Check the RPL/DPL/CPL interaction..
4981 */
4982 /** @todo testcase for the conforming behavior. */
4983 if ( (Desc.Legacy.Gen.u4Type & (X86_SEL_TYPE_CODE | X86_SEL_TYPE_CONF)) != (X86_SEL_TYPE_CODE | X86_SEL_TYPE_CONF)
4984 || !Desc.Legacy.Gen.u1DescType)
4985 {
4986 if ((unsigned)(uSel & X86_SEL_RPL) > Desc.Legacy.Gen.u2Dpl)
4987 fDescOk = false;
4988 else if (IEM_GET_CPL(pVCpu) > Desc.Legacy.Gen.u2Dpl)
4989 fDescOk = false;
4990 }
4991 }
4992
4993 if (fDescOk)
4994 {
4995 /*
4996 * All fine, start committing the result.
4997 */
4998 if (fIsLar)
4999 *pu64Dst = Desc.Legacy.au32[1] & UINT32_C(0x00ffff00);
5000 else
5001 *pu64Dst = X86DESC_LIMIT_G(&Desc.Legacy);
5002 }
5003
5004 }
5005 else if (rcStrict == VINF_IEM_SELECTOR_NOT_OK)
5006 fDescOk = false;
5007 else
5008 return rcStrict;
5009
5010 /* commit flags value and advance rip. */
5011 pVCpu->cpum.GstCtx.eflags.Bits.u1ZF = fDescOk;
5012 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5013}
5014
5015
5016/**
5017 * Implements LAR and LSL with 16-bit operand size.
5018 *
5019 * @returns VINF_SUCCESS.
5020 * @param pu16Dst Pointer to the destination register.
5021 * @param uSel The selector to load details for.
5022 * @param fIsLar true = LAR, false = LSL.
5023 */
5024IEM_CIMPL_DEF_3(iemCImpl_LarLsl_u16, uint16_t *, pu16Dst, uint16_t, uSel, bool, fIsLar)
5025{
5026 uint64_t u64TmpDst = *pu16Dst;
5027 IEM_CIMPL_CALL_3(iemCImpl_LarLsl_u64, &u64TmpDst, uSel, fIsLar);
5028 *pu16Dst = u64TmpDst;
5029 return VINF_SUCCESS;
5030}
5031
5032
5033/**
5034 * Implements lgdt.
5035 *
5036 * @param iEffSeg The segment of the new gdtr contents
5037 * @param GCPtrEffSrc The address of the new gdtr contents.
5038 * @param enmEffOpSize The effective operand size.
5039 */
5040IEM_CIMPL_DEF_3(iemCImpl_lgdt, uint8_t, iEffSeg, RTGCPTR, GCPtrEffSrc, IEMMODE, enmEffOpSize)
5041{
5042 if (IEM_GET_CPL(pVCpu) != 0)
5043 return iemRaiseGeneralProtectionFault0(pVCpu);
5044 Assert(!pVCpu->cpum.GstCtx.eflags.Bits.u1VM);
5045
5046 if (!IEM_IS_IN_GUEST(pVCpu))
5047 { /* probable */ }
5048 else if ( IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
5049 && IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_DESC_TABLE_EXIT))
5050 {
5051 Log(("lgdt: Guest intercept -> VM-exit\n"));
5052 IEM_VMX_VMEXIT_INSTR_NEEDS_INFO_RET(pVCpu, VMX_EXIT_GDTR_IDTR_ACCESS, VMXINSTRID_LGDT, cbInstr);
5053 }
5054 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_GDTR_WRITES))
5055 {
5056 Log(("lgdt: Guest intercept -> #VMEXIT\n"));
5057 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
5058 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_GDTR_WRITE, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
5059 }
5060
5061 /*
5062 * Fetch the limit and base address.
5063 */
5064 uint16_t cbLimit;
5065 RTGCPTR GCPtrBase;
5066 VBOXSTRICTRC rcStrict = iemMemFetchDataXdtr(pVCpu, &cbLimit, &GCPtrBase, iEffSeg, GCPtrEffSrc, enmEffOpSize);
5067 if (rcStrict == VINF_SUCCESS)
5068 {
5069 if ( !IEM_IS_64BIT_CODE(pVCpu)
5070 || X86_IS_CANONICAL(GCPtrBase))
5071 {
5072 rcStrict = CPUMSetGuestGDTR(pVCpu, GCPtrBase, cbLimit);
5073 if (rcStrict == VINF_SUCCESS)
5074 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5075 }
5076 else
5077 {
5078 Log(("iemCImpl_lgdt: Non-canonical base %04x:%RGv\n", cbLimit, GCPtrBase));
5079 return iemRaiseGeneralProtectionFault0(pVCpu);
5080 }
5081 }
5082 return rcStrict;
5083}
5084
5085
5086/**
5087 * Implements sgdt.
5088 *
5089 * @param iEffSeg The segment where to store the gdtr content.
5090 * @param GCPtrEffDst The address where to store the gdtr content.
5091 */
5092IEM_CIMPL_DEF_2(iemCImpl_sgdt, uint8_t, iEffSeg, RTGCPTR, GCPtrEffDst)
5093{
5094 /*
5095 * Join paths with sidt.
5096 * Note! No CPL or V8086 checks here, it's a really sad story, ask Intel if
5097 * you really must know.
5098 */
5099 if (!IEM_IS_IN_GUEST(pVCpu))
5100 { /* probable */ }
5101 else if ( IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
5102 && IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_DESC_TABLE_EXIT))
5103 {
5104 Log(("sgdt: Guest intercept -> VM-exit\n"));
5105 IEM_VMX_VMEXIT_INSTR_NEEDS_INFO_RET(pVCpu, VMX_EXIT_GDTR_IDTR_ACCESS, VMXINSTRID_SGDT, cbInstr);
5106 }
5107 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_GDTR_READS))
5108 {
5109 Log(("sgdt: Guest intercept -> #VMEXIT\n"));
5110 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
5111 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_GDTR_READ, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
5112 }
5113
5114 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_GDTR);
5115 VBOXSTRICTRC rcStrict = iemMemStoreDataXdtr(pVCpu, pVCpu->cpum.GstCtx.gdtr.cbGdt, pVCpu->cpum.GstCtx.gdtr.pGdt, iEffSeg, GCPtrEffDst);
5116 if (rcStrict == VINF_SUCCESS)
5117 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5118 return rcStrict;
5119}
5120
5121
5122/**
5123 * Implements lidt.
5124 *
5125 * @param iEffSeg The segment of the new idtr contents
5126 * @param GCPtrEffSrc The address of the new idtr contents.
5127 * @param enmEffOpSize The effective operand size.
5128 */
5129IEM_CIMPL_DEF_3(iemCImpl_lidt, uint8_t, iEffSeg, RTGCPTR, GCPtrEffSrc, IEMMODE, enmEffOpSize)
5130{
5131 if (IEM_GET_CPL(pVCpu) != 0)
5132 return iemRaiseGeneralProtectionFault0(pVCpu);
5133 Assert(!pVCpu->cpum.GstCtx.eflags.Bits.u1VM);
5134
5135 if (!IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_IDTR_WRITES))
5136 { /* probable */ }
5137 else
5138 {
5139 Log(("lidt: Guest intercept -> #VMEXIT\n"));
5140 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
5141 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_IDTR_WRITE, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
5142 }
5143
5144 /*
5145 * Fetch the limit and base address.
5146 */
5147 uint16_t cbLimit;
5148 RTGCPTR GCPtrBase;
5149 VBOXSTRICTRC rcStrict = iemMemFetchDataXdtr(pVCpu, &cbLimit, &GCPtrBase, iEffSeg, GCPtrEffSrc, enmEffOpSize);
5150 if (rcStrict == VINF_SUCCESS)
5151 {
5152 if ( !IEM_IS_64BIT_CODE(pVCpu)
5153 || X86_IS_CANONICAL(GCPtrBase))
5154 {
5155 CPUMSetGuestIDTR(pVCpu, GCPtrBase, cbLimit);
5156 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5157 }
5158 else
5159 {
5160 Log(("iemCImpl_lidt: Non-canonical base %04x:%RGv\n", cbLimit, GCPtrBase));
5161 return iemRaiseGeneralProtectionFault0(pVCpu);
5162 }
5163 }
5164 return rcStrict;
5165}
5166
5167
5168/**
5169 * Implements sidt.
5170 *
5171 * @param iEffSeg The segment where to store the idtr content.
5172 * @param GCPtrEffDst The address where to store the idtr content.
5173 */
5174IEM_CIMPL_DEF_2(iemCImpl_sidt, uint8_t, iEffSeg, RTGCPTR, GCPtrEffDst)
5175{
5176 /*
5177 * Join paths with sgdt.
5178 * Note! No CPL or V8086 checks here, it's a really sad story, ask Intel if
5179 * you really must know.
5180 */
5181 if (!IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_IDTR_READS))
5182 { /* probable */ }
5183 else
5184 {
5185 Log(("sidt: Guest intercept -> #VMEXIT\n"));
5186 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
5187 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_IDTR_READ, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
5188 }
5189
5190 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_IDTR);
5191 VBOXSTRICTRC rcStrict = iemMemStoreDataXdtr(pVCpu, pVCpu->cpum.GstCtx.idtr.cbIdt, pVCpu->cpum.GstCtx.idtr.pIdt, iEffSeg, GCPtrEffDst);
5192 if (rcStrict == VINF_SUCCESS)
5193 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5194 return rcStrict;
5195}
5196
5197
5198/**
5199 * Implements lldt.
5200 *
5201 * @param uNewLdt The new LDT selector value.
5202 */
5203IEM_CIMPL_DEF_1(iemCImpl_lldt, uint16_t, uNewLdt)
5204{
5205 /*
5206 * Check preconditions.
5207 */
5208 if (IEM_IS_REAL_OR_V86_MODE(pVCpu))
5209 {
5210 Log(("lldt %04x - real or v8086 mode -> #GP(0)\n", uNewLdt));
5211 return iemRaiseUndefinedOpcode(pVCpu);
5212 }
5213 if (IEM_GET_CPL(pVCpu) != 0)
5214 {
5215 Log(("lldt %04x - CPL is %d -> #GP(0)\n", uNewLdt, IEM_GET_CPL(pVCpu)));
5216 return iemRaiseGeneralProtectionFault0(pVCpu);
5217 }
5218
5219 /* Nested-guest VMX intercept (SVM is after all checks). */
5220 /** @todo testcase: exit vs check order. */
5221 if ( !IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
5222 || !IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_DESC_TABLE_EXIT))
5223 { /* probable */ }
5224 else
5225 {
5226 Log(("lldt: Guest intercept -> VM-exit\n"));
5227 IEM_VMX_VMEXIT_INSTR_NEEDS_INFO_RET(pVCpu, VMX_EXIT_LDTR_TR_ACCESS, VMXINSTRID_LLDT, cbInstr);
5228 }
5229
5230 if (uNewLdt & X86_SEL_LDT)
5231 {
5232 Log(("lldt %04x - LDT selector -> #GP\n", uNewLdt));
5233 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewLdt);
5234 }
5235
5236 /*
5237 * Now, loading a NULL selector is easy.
5238 */
5239 if (!(uNewLdt & X86_SEL_MASK_OFF_RPL))
5240 {
5241 /* Nested-guest SVM intercept. */
5242 if (!IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_LDTR_WRITES))
5243 { /* probable */ }
5244 else
5245 {
5246 Log(("lldt: Guest intercept -> #VMEXIT\n"));
5247 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
5248 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_LDTR_WRITE, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
5249 }
5250
5251 Log(("lldt %04x: Loading NULL selector.\n", uNewLdt));
5252 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_LDTR;
5253 CPUMSetGuestLDTR(pVCpu, uNewLdt);
5254 pVCpu->cpum.GstCtx.ldtr.ValidSel = uNewLdt;
5255 pVCpu->cpum.GstCtx.ldtr.fFlags = CPUMSELREG_FLAGS_VALID;
5256 if (IEM_IS_GUEST_CPU_AMD(pVCpu))
5257 {
5258 /* AMD-V seems to leave the base and limit alone. */
5259 pVCpu->cpum.GstCtx.ldtr.Attr.u = X86DESCATTR_UNUSABLE;
5260 }
5261 else
5262 {
5263 /* VT-x (Intel 3960x) seems to be doing the following. */
5264 pVCpu->cpum.GstCtx.ldtr.Attr.u = X86DESCATTR_UNUSABLE | X86DESCATTR_G | X86DESCATTR_D;
5265 pVCpu->cpum.GstCtx.ldtr.u64Base = 0;
5266 pVCpu->cpum.GstCtx.ldtr.u32Limit = UINT32_MAX;
5267 }
5268
5269 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5270 }
5271
5272 /*
5273 * Read the descriptor.
5274 */
5275 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_LDTR | CPUMCTX_EXTRN_GDTR);
5276 IEMSELDESC Desc;
5277 VBOXSTRICTRC rcStrict = iemMemFetchSelDesc(pVCpu, &Desc, uNewLdt, X86_XCPT_GP); /** @todo Correct exception? */
5278 if (rcStrict != VINF_SUCCESS)
5279 return rcStrict;
5280
5281 /* Check GPs first. */
5282 if (Desc.Legacy.Gen.u1DescType)
5283 {
5284 Log(("lldt %#x - not system selector (type %x) -> #GP\n", uNewLdt, Desc.Legacy.Gen.u4Type));
5285 return iemRaiseGeneralProtectionFault(pVCpu, uNewLdt & X86_SEL_MASK_OFF_RPL);
5286 }
5287 if (Desc.Legacy.Gen.u4Type != X86_SEL_TYPE_SYS_LDT)
5288 {
5289 Log(("lldt %#x - not LDT selector (type %x) -> #GP\n", uNewLdt, Desc.Legacy.Gen.u4Type));
5290 return iemRaiseGeneralProtectionFault(pVCpu, uNewLdt & X86_SEL_MASK_OFF_RPL);
5291 }
5292 uint64_t u64Base;
5293 if (!IEM_IS_LONG_MODE(pVCpu))
5294 u64Base = X86DESC_BASE(&Desc.Legacy);
5295 else
5296 {
5297 if (Desc.Long.Gen.u5Zeros)
5298 {
5299 Log(("lldt %#x - u5Zeros=%#x -> #GP\n", uNewLdt, Desc.Long.Gen.u5Zeros));
5300 return iemRaiseGeneralProtectionFault(pVCpu, uNewLdt & X86_SEL_MASK_OFF_RPL);
5301 }
5302
5303 u64Base = X86DESC64_BASE(&Desc.Long);
5304 if (!IEM_IS_CANONICAL(u64Base))
5305 {
5306 Log(("lldt %#x - non-canonical base address %#llx -> #GP\n", uNewLdt, u64Base));
5307 return iemRaiseGeneralProtectionFault(pVCpu, uNewLdt & X86_SEL_MASK_OFF_RPL);
5308 }
5309 }
5310
5311 /* NP */
5312 if (!Desc.Legacy.Gen.u1Present)
5313 {
5314 Log(("lldt %#x - segment not present -> #NP\n", uNewLdt));
5315 return iemRaiseSelectorNotPresentBySelector(pVCpu, uNewLdt);
5316 }
5317
5318 /* Nested-guest SVM intercept. */
5319 if (!IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_LDTR_WRITES))
5320 { /* probable */ }
5321 else
5322 {
5323 Log(("lldt: Guest intercept -> #VMEXIT\n"));
5324 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
5325 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_LDTR_WRITE, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
5326 }
5327
5328 /*
5329 * It checks out alright, update the registers.
5330 */
5331/** @todo check if the actual value is loaded or if the RPL is dropped */
5332 CPUMSetGuestLDTR(pVCpu, uNewLdt & X86_SEL_MASK_OFF_RPL);
5333 pVCpu->cpum.GstCtx.ldtr.ValidSel = uNewLdt & X86_SEL_MASK_OFF_RPL;
5334 pVCpu->cpum.GstCtx.ldtr.fFlags = CPUMSELREG_FLAGS_VALID;
5335 pVCpu->cpum.GstCtx.ldtr.Attr.u = X86DESC_GET_HID_ATTR(&Desc.Legacy);
5336 pVCpu->cpum.GstCtx.ldtr.u32Limit = X86DESC_LIMIT_G(&Desc.Legacy);
5337 pVCpu->cpum.GstCtx.ldtr.u64Base = u64Base;
5338
5339 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5340}
5341
5342
5343/**
5344 * Implements sldt GReg
5345 *
5346 * @param iGReg The general register to store the CRx value in.
5347 * @param enmEffOpSize The operand size.
5348 */
5349IEM_CIMPL_DEF_2(iemCImpl_sldt_reg, uint8_t, iGReg, uint8_t, enmEffOpSize)
5350{
5351 if (!IEM_IS_IN_GUEST(pVCpu))
5352 { /* probable */ }
5353 else if ( IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
5354 && IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_DESC_TABLE_EXIT))
5355 {
5356 Log(("sldt: Guest intercept -> VM-exit\n"));
5357 IEM_VMX_VMEXIT_INSTR_NEEDS_INFO_RET(pVCpu, VMX_EXIT_LDTR_TR_ACCESS, VMXINSTRID_SLDT, cbInstr);
5358 }
5359 else
5360 IEM_SVM_CHECK_INSTR_INTERCEPT(pVCpu, SVM_CTRL_INTERCEPT_LDTR_READS, SVM_EXIT_LDTR_READ, 0, 0, cbInstr);
5361
5362 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_LDTR);
5363 switch (enmEffOpSize)
5364 {
5365 case IEMMODE_16BIT:
5366 iemGRegStoreU16(pVCpu, iGReg, pVCpu->cpum.GstCtx.ldtr.Sel);
5367 break;
5368 case IEMMODE_32BIT:
5369 case IEMMODE_64BIT:
5370 iemGRegStoreU64(pVCpu, iGReg, pVCpu->cpum.GstCtx.ldtr.Sel);
5371 break;
5372 IEM_NOT_REACHED_DEFAULT_CASE_RET();
5373 }
5374 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5375}
5376
5377
5378/**
5379 * Implements sldt mem.
5380 *
5381 * @param iEffSeg The effective segment register to use with @a GCPtrMem.
5382 * @param GCPtrEffDst Where to store the 16-bit CR0 value.
5383 */
5384IEM_CIMPL_DEF_2(iemCImpl_sldt_mem, uint8_t, iEffSeg, RTGCPTR, GCPtrEffDst)
5385{
5386 IEM_SVM_CHECK_INSTR_INTERCEPT(pVCpu, SVM_CTRL_INTERCEPT_LDTR_READS, SVM_EXIT_LDTR_READ, 0, 0, cbInstr);
5387
5388 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_LDTR);
5389 VBOXSTRICTRC rcStrict = iemMemStoreDataU16(pVCpu, iEffSeg, GCPtrEffDst, pVCpu->cpum.GstCtx.ldtr.Sel);
5390 if (rcStrict == VINF_SUCCESS)
5391 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5392 return rcStrict;
5393}
5394
5395
5396/**
5397 * Implements ltr.
5398 *
5399 * @param uNewTr The new TSS selector value.
5400 */
5401IEM_CIMPL_DEF_1(iemCImpl_ltr, uint16_t, uNewTr)
5402{
5403 /*
5404 * Check preconditions.
5405 */
5406 if (IEM_IS_REAL_OR_V86_MODE(pVCpu))
5407 {
5408 Log(("ltr %04x - real or v8086 mode -> #GP(0)\n", uNewTr));
5409 return iemRaiseUndefinedOpcode(pVCpu);
5410 }
5411 if (IEM_GET_CPL(pVCpu) != 0)
5412 {
5413 Log(("ltr %04x - CPL is %d -> #GP(0)\n", uNewTr, IEM_GET_CPL(pVCpu)));
5414 return iemRaiseGeneralProtectionFault0(pVCpu);
5415 }
5416 if ( !IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
5417 || !IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_DESC_TABLE_EXIT))
5418 { /* probable */ }
5419 else
5420 {
5421 Log(("ltr: Guest intercept -> VM-exit\n"));
5422 IEM_VMX_VMEXIT_INSTR_NEEDS_INFO_RET(pVCpu, VMX_EXIT_LDTR_TR_ACCESS, VMXINSTRID_LTR, cbInstr);
5423 }
5424 if (uNewTr & X86_SEL_LDT)
5425 {
5426 Log(("ltr %04x - LDT selector -> #GP\n", uNewTr));
5427 return iemRaiseGeneralProtectionFaultBySelector(pVCpu, uNewTr);
5428 }
5429 if (!(uNewTr & X86_SEL_MASK_OFF_RPL))
5430 {
5431 Log(("ltr %04x - NULL selector -> #GP(0)\n", uNewTr));
5432 return iemRaiseGeneralProtectionFault0(pVCpu);
5433 }
5434 if (!IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_TR_WRITES))
5435 { /* probable */ }
5436 else
5437 {
5438 Log(("ltr: Guest intercept -> #VMEXIT\n"));
5439 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
5440 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_TR_WRITE, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
5441 }
5442
5443 /*
5444 * Read the descriptor.
5445 */
5446 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_LDTR | CPUMCTX_EXTRN_GDTR | CPUMCTX_EXTRN_TR);
5447 IEMSELDESC Desc;
5448 VBOXSTRICTRC rcStrict = iemMemFetchSelDesc(pVCpu, &Desc, uNewTr, X86_XCPT_GP); /** @todo Correct exception? */
5449 if (rcStrict != VINF_SUCCESS)
5450 return rcStrict;
5451
5452 /* Check GPs first. */
5453 if (Desc.Legacy.Gen.u1DescType)
5454 {
5455 Log(("ltr %#x - not system selector (type %x) -> #GP\n", uNewTr, Desc.Legacy.Gen.u4Type));
5456 return iemRaiseGeneralProtectionFault(pVCpu, uNewTr & X86_SEL_MASK_OFF_RPL);
5457 }
5458 if ( Desc.Legacy.Gen.u4Type != X86_SEL_TYPE_SYS_386_TSS_AVAIL /* same as AMD64_SEL_TYPE_SYS_TSS_AVAIL */
5459 && ( Desc.Legacy.Gen.u4Type != X86_SEL_TYPE_SYS_286_TSS_AVAIL
5460 || IEM_IS_LONG_MODE(pVCpu)) )
5461 {
5462 Log(("ltr %#x - not an available TSS selector (type %x) -> #GP\n", uNewTr, Desc.Legacy.Gen.u4Type));
5463 return iemRaiseGeneralProtectionFault(pVCpu, uNewTr & X86_SEL_MASK_OFF_RPL);
5464 }
5465 uint64_t u64Base;
5466 if (!IEM_IS_LONG_MODE(pVCpu))
5467 u64Base = X86DESC_BASE(&Desc.Legacy);
5468 else
5469 {
5470 if (Desc.Long.Gen.u5Zeros)
5471 {
5472 Log(("ltr %#x - u5Zeros=%#x -> #GP\n", uNewTr, Desc.Long.Gen.u5Zeros));
5473 return iemRaiseGeneralProtectionFault(pVCpu, uNewTr & X86_SEL_MASK_OFF_RPL);
5474 }
5475
5476 u64Base = X86DESC64_BASE(&Desc.Long);
5477 if (!IEM_IS_CANONICAL(u64Base))
5478 {
5479 Log(("ltr %#x - non-canonical base address %#llx -> #GP\n", uNewTr, u64Base));
5480 return iemRaiseGeneralProtectionFault(pVCpu, uNewTr & X86_SEL_MASK_OFF_RPL);
5481 }
5482 }
5483
5484 /* NP */
5485 if (!Desc.Legacy.Gen.u1Present)
5486 {
5487 Log(("ltr %#x - segment not present -> #NP\n", uNewTr));
5488 return iemRaiseSelectorNotPresentBySelector(pVCpu, uNewTr);
5489 }
5490
5491 /*
5492 * Set it busy.
5493 * Note! Intel says this should lock down the whole descriptor, but we'll
5494 * restrict our selves to 32-bit for now due to lack of inline
5495 * assembly and such.
5496 */
5497 uint8_t bUnmapInfo;
5498 void *pvDesc;
5499 rcStrict = iemMemMap(pVCpu, &pvDesc, &bUnmapInfo, 8, UINT8_MAX,
5500 pVCpu->cpum.GstCtx.gdtr.pGdt + (uNewTr & X86_SEL_MASK_OFF_RPL), IEM_ACCESS_DATA_RW, 0);
5501 if (rcStrict != VINF_SUCCESS)
5502 return rcStrict;
5503 switch ((uintptr_t)pvDesc & 3)
5504 {
5505 case 0: ASMAtomicBitSet(pvDesc, 40 + 1); break;
5506 case 1: ASMAtomicBitSet((uint8_t *)pvDesc + 3, 40 + 1 - 24); break;
5507 case 2: ASMAtomicBitSet((uint8_t *)pvDesc + 2, 40 + 1 - 16); break;
5508 case 3: ASMAtomicBitSet((uint8_t *)pvDesc + 1, 40 + 1 - 8); break;
5509 }
5510 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
5511 if (rcStrict != VINF_SUCCESS)
5512 return rcStrict;
5513 Desc.Legacy.Gen.u4Type |= X86_SEL_TYPE_SYS_TSS_BUSY_MASK;
5514
5515 /*
5516 * It checks out alright, update the registers.
5517 */
5518/** @todo check if the actual value is loaded or if the RPL is dropped */
5519 CPUMSetGuestTR(pVCpu, uNewTr & X86_SEL_MASK_OFF_RPL);
5520 pVCpu->cpum.GstCtx.tr.ValidSel = uNewTr & X86_SEL_MASK_OFF_RPL;
5521 pVCpu->cpum.GstCtx.tr.fFlags = CPUMSELREG_FLAGS_VALID;
5522 pVCpu->cpum.GstCtx.tr.Attr.u = X86DESC_GET_HID_ATTR(&Desc.Legacy);
5523 pVCpu->cpum.GstCtx.tr.u32Limit = X86DESC_LIMIT_G(&Desc.Legacy);
5524 pVCpu->cpum.GstCtx.tr.u64Base = u64Base;
5525
5526 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5527}
5528
5529
5530/**
5531 * Implements str GReg
5532 *
5533 * @param iGReg The general register to store the CRx value in.
5534 * @param enmEffOpSize The operand size.
5535 */
5536IEM_CIMPL_DEF_2(iemCImpl_str_reg, uint8_t, iGReg, uint8_t, enmEffOpSize)
5537{
5538 if (!IEM_IS_IN_GUEST(pVCpu))
5539 { /* probable */ }
5540 else if ( IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
5541 && IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_DESC_TABLE_EXIT))
5542 {
5543 Log(("str_reg: Guest intercept -> VM-exit\n"));
5544 IEM_VMX_VMEXIT_INSTR_NEEDS_INFO_RET(pVCpu, VMX_EXIT_LDTR_TR_ACCESS, VMXINSTRID_STR, cbInstr);
5545 }
5546 else
5547 IEM_SVM_CHECK_INSTR_INTERCEPT(pVCpu, SVM_CTRL_INTERCEPT_TR_READS, SVM_EXIT_TR_READ, 0, 0, cbInstr);
5548
5549 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_TR);
5550 switch (enmEffOpSize)
5551 {
5552 case IEMMODE_16BIT:
5553 iemGRegStoreU16(pVCpu, iGReg, pVCpu->cpum.GstCtx.tr.Sel);
5554 break;
5555 case IEMMODE_32BIT:
5556 case IEMMODE_64BIT:
5557 iemGRegStoreU64(pVCpu, iGReg, pVCpu->cpum.GstCtx.tr.Sel);
5558 break;
5559 IEM_NOT_REACHED_DEFAULT_CASE_RET();
5560 }
5561 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5562}
5563
5564
5565/**
5566 * Implements str mem.
5567 *
5568 * @param iEffSeg The effective segment register to use with @a GCPtrMem.
5569 * @param GCPtrEffDst Where to store the 16-bit CR0 value.
5570 */
5571IEM_CIMPL_DEF_2(iemCImpl_str_mem, uint8_t, iEffSeg, RTGCPTR, GCPtrEffDst)
5572{
5573 if (!IEM_IS_IN_GUEST(pVCpu))
5574 { /* probable */ }
5575 else if ( IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
5576 && IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_DESC_TABLE_EXIT))
5577 {
5578 Log(("str_mem: Guest intercept -> VM-exit\n"));
5579 IEM_VMX_VMEXIT_INSTR_NEEDS_INFO_RET(pVCpu, VMX_EXIT_LDTR_TR_ACCESS, VMXINSTRID_STR, cbInstr);
5580 }
5581 else
5582 IEM_SVM_CHECK_INSTR_INTERCEPT(pVCpu, SVM_CTRL_INTERCEPT_TR_READS, SVM_EXIT_TR_READ, 0, 0, cbInstr);
5583
5584 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_TR);
5585 VBOXSTRICTRC rcStrict = iemMemStoreDataU16(pVCpu, iEffSeg, GCPtrEffDst, pVCpu->cpum.GstCtx.tr.Sel);
5586 if (rcStrict == VINF_SUCCESS)
5587 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5588 return rcStrict;
5589}
5590
5591
5592/**
5593 * Implements mov GReg,CRx.
5594 *
5595 * @param iGReg The general register to store the CRx value in.
5596 * @param iCrReg The CRx register to read (valid).
5597 */
5598IEM_CIMPL_DEF_2(iemCImpl_mov_Rd_Cd, uint8_t, iGReg, uint8_t, iCrReg)
5599{
5600 if (IEM_GET_CPL(pVCpu) != 0)
5601 return iemRaiseGeneralProtectionFault0(pVCpu);
5602 Assert(!pVCpu->cpum.GstCtx.eflags.Bits.u1VM);
5603
5604 if (!IEM_SVM_IS_READ_CR_INTERCEPT_SET(pVCpu, iCrReg))
5605 { /* probable */ }
5606 else
5607 {
5608 Log(("iemCImpl_mov_Rd_Cd: Guest intercept CR%u -> #VMEXIT\n", iCrReg));
5609 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
5610 IEM_SVM_CRX_VMEXIT_RET(pVCpu, SVM_EXIT_READ_CR0 + iCrReg, IEMACCESSCRX_MOV_CRX, iGReg);
5611 }
5612
5613 /* Read it. */
5614 uint64_t crX;
5615 switch (iCrReg)
5616 {
5617 case 0:
5618 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
5619 crX = pVCpu->cpum.GstCtx.cr0;
5620 if (IEM_GET_TARGET_CPU(pVCpu) <= IEMTARGETCPU_386)
5621 crX |= UINT32_C(0x7fffffe0); /* All reserved CR0 flags are set on a 386, just like MSW on 286. */
5622 break;
5623 case 2:
5624 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_CR2);
5625 crX = pVCpu->cpum.GstCtx.cr2;
5626 break;
5627 case 3:
5628 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR3);
5629 crX = pVCpu->cpum.GstCtx.cr3;
5630 break;
5631 case 4:
5632 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
5633 crX = pVCpu->cpum.GstCtx.cr4;
5634 break;
5635 case 8:
5636 {
5637 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_APIC_TPR);
5638 if (!IEM_IS_IN_GUEST(pVCpu))
5639 { /* probable */ }
5640#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5641 else if (IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
5642 {
5643 VBOXSTRICTRC rcStrict = iemVmxVmexitInstrMovFromCr8(pVCpu, iGReg, cbInstr);
5644 if (rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE)
5645 return rcStrict;
5646
5647 /*
5648 * If the Mov-from-CR8 doesn't cause a VM-exit, bits 7:4 of the VTPR is copied
5649 * to bits 0:3 of the destination operand. Bits 63:4 of the destination operand
5650 * are cleared.
5651 *
5652 * See Intel Spec. 29.3 "Virtualizing CR8-based TPR Accesses"
5653 */
5654 if (IEM_VMX_IS_PROCCTLS_SET(pVCpu, VMX_PROC_CTLS_USE_TPR_SHADOW))
5655 {
5656 uint32_t const uTpr = iemVmxVirtApicReadRaw32(pVCpu, XAPIC_OFF_TPR);
5657 crX = (uTpr >> 4) & 0xf;
5658 break;
5659 }
5660 }
5661#endif
5662#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5663 else if (pVCpu->iem.s.fExec & IEM_F_X86_CTX_SVM)
5664 {
5665 PCSVMVMCBCTRL pVmcbCtrl = &pVCpu->cpum.GstCtx.hwvirt.svm.Vmcb.ctrl;
5666 if (CPUMIsGuestSvmVirtIntrMasking(pVCpu, IEM_GET_CTX(pVCpu)))
5667 {
5668 crX = pVmcbCtrl->IntCtrl.n.u8VTPR & 0xf;
5669 break;
5670 }
5671 }
5672#endif
5673 uint8_t uTpr;
5674 int rc = APICGetTpr(pVCpu, &uTpr, NULL, NULL);
5675 if (RT_SUCCESS(rc))
5676 crX = uTpr >> 4;
5677 else
5678 crX = 0;
5679 break;
5680 }
5681 IEM_NOT_REACHED_DEFAULT_CASE_RET(); /* call checks */
5682 }
5683
5684#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5685 if (!IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
5686 { /* probable */ }
5687 else
5688 switch (iCrReg)
5689 {
5690 /* CR0/CR4 reads are subject to masking when in VMX non-root mode. */
5691 case 0: crX = CPUMGetGuestVmxMaskedCr0(&pVCpu->cpum.GstCtx, pVCpu->cpum.GstCtx.hwvirt.vmx.Vmcs.u64Cr0Mask.u); break;
5692 case 4: crX = CPUMGetGuestVmxMaskedCr4(&pVCpu->cpum.GstCtx, pVCpu->cpum.GstCtx.hwvirt.vmx.Vmcs.u64Cr4Mask.u); break;
5693 case 3:
5694 {
5695 VBOXSTRICTRC rcStrict = iemVmxVmexitInstrMovFromCr3(pVCpu, iGReg, cbInstr);
5696 if (rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE)
5697 return rcStrict;
5698 break;
5699 }
5700 }
5701#endif
5702
5703 /* Store it. */
5704 if (IEM_IS_64BIT_CODE(pVCpu))
5705 iemGRegStoreU64(pVCpu, iGReg, crX);
5706 else
5707 iemGRegStoreU64(pVCpu, iGReg, (uint32_t)crX);
5708
5709 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5710}
5711
5712
5713/**
5714 * Implements smsw GReg.
5715 *
5716 * @param iGReg The general register to store the CRx value in.
5717 * @param enmEffOpSize The operand size.
5718 */
5719IEM_CIMPL_DEF_2(iemCImpl_smsw_reg, uint8_t, iGReg, uint8_t, enmEffOpSize)
5720{
5721 IEM_SVM_CHECK_READ_CR0_INTERCEPT(pVCpu, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */, cbInstr);
5722
5723#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5724 uint64_t u64MaskedCr0;
5725 if (!IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
5726 u64MaskedCr0 = pVCpu->cpum.GstCtx.cr0;
5727 else
5728 u64MaskedCr0 = CPUMGetGuestVmxMaskedCr0(&pVCpu->cpum.GstCtx, pVCpu->cpum.GstCtx.hwvirt.vmx.Vmcs.u64Cr0Mask.u);
5729 uint64_t const u64GuestCr0 = u64MaskedCr0;
5730#else
5731 uint64_t const u64GuestCr0 = pVCpu->cpum.GstCtx.cr0;
5732#endif
5733
5734 switch (enmEffOpSize)
5735 {
5736 case IEMMODE_16BIT:
5737 if (IEM_GET_TARGET_CPU(pVCpu) > IEMTARGETCPU_386)
5738 iemGRegStoreU16(pVCpu, iGReg, (uint16_t)u64GuestCr0);
5739 /* Unused bits are set on 386 and older CPU: */
5740 else if (IEM_GET_TARGET_CPU(pVCpu) >= IEMTARGETCPU_386)
5741 iemGRegStoreU16(pVCpu, iGReg, (uint16_t)u64GuestCr0 | 0xffe0);
5742 else
5743 iemGRegStoreU16(pVCpu, iGReg, (uint16_t)u64GuestCr0 | 0xfff0);
5744 break;
5745
5746/** @todo testcase for bits 31:16. We're not doing that correctly. */
5747
5748 case IEMMODE_32BIT:
5749 if (IEM_GET_TARGET_CPU(pVCpu) >= IEMTARGETCPU_386)
5750 iemGRegStoreU32(pVCpu, iGReg, (uint32_t)u64GuestCr0);
5751 else /** @todo test this! */
5752 iemGRegStoreU32(pVCpu, iGReg, (uint32_t)u64GuestCr0 | UINT32_C(0x7fffffe0)); /* Unused bits are set on 386. */
5753 break;
5754
5755 case IEMMODE_64BIT:
5756 iemGRegStoreU64(pVCpu, iGReg, u64GuestCr0);
5757 break;
5758
5759 IEM_NOT_REACHED_DEFAULT_CASE_RET();
5760 }
5761
5762 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5763}
5764
5765
5766/**
5767 * Implements smsw mem.
5768 *
5769 * @param iEffSeg The effective segment register to use with @a GCPtrMem.
5770 * @param GCPtrEffDst Where to store the 16-bit CR0 value.
5771 */
5772IEM_CIMPL_DEF_2(iemCImpl_smsw_mem, uint8_t, iEffSeg, RTGCPTR, GCPtrEffDst)
5773{
5774 uint64_t u64GuestCr0 = pVCpu->cpum.GstCtx.cr0;
5775 if (!IEM_IS_IN_GUEST(pVCpu))
5776 { /* probable */ }
5777 else if (IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
5778 u64GuestCr0 = CPUMGetGuestVmxMaskedCr0(&pVCpu->cpum.GstCtx, pVCpu->cpum.GstCtx.hwvirt.vmx.Vmcs.u64Cr0Mask.u);
5779 else
5780 IEM_SVM_CHECK_READ_CR0_INTERCEPT(pVCpu, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */, cbInstr);
5781
5782 uint16_t u16Value;
5783 if (IEM_GET_TARGET_CPU(pVCpu) > IEMTARGETCPU_386)
5784 u16Value = (uint16_t)u64GuestCr0;
5785 else if (IEM_GET_TARGET_CPU(pVCpu) >= IEMTARGETCPU_386)
5786 u16Value = (uint16_t)u64GuestCr0 | 0xffe0;
5787 else
5788 u16Value = (uint16_t)u64GuestCr0 | 0xfff0;
5789
5790 VBOXSTRICTRC rcStrict = iemMemStoreDataU16(pVCpu, iEffSeg, GCPtrEffDst, u16Value);
5791 if (rcStrict == VINF_SUCCESS)
5792 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
5793 return rcStrict;
5794}
5795
5796
5797/**
5798 * Helper for mapping CR3 and PAE PDPEs for 'mov CRx,GReg'.
5799 */
5800#define IEM_MAP_PAE_PDPES_AT_CR3_RET(a_pVCpu, a_iCrReg, a_uCr3) \
5801 do \
5802 { \
5803 int const rcX = PGMGstMapPaePdpesAtCr3(a_pVCpu, a_uCr3); \
5804 if (RT_SUCCESS(rcX)) \
5805 { /* likely */ } \
5806 else \
5807 { \
5808 /* Either invalid PDPTEs or CR3 second-level translation failed. Raise #GP(0) either way. */ \
5809 Log(("iemCImpl_load_Cr%#x: Trying to load invalid PAE PDPEs\n", a_iCrReg)); \
5810 return iemRaiseGeneralProtectionFault0(a_pVCpu); \
5811 } \
5812 } while (0)
5813
5814
5815/**
5816 * Used to implemented 'mov CRx,GReg' and 'lmsw r/m16'.
5817 *
5818 * @param iCrReg The CRx register to write (valid).
5819 * @param uNewCrX The new value.
5820 * @param enmAccessCrX The instruction that caused the CrX load.
5821 * @param iGReg The general register in case of a 'mov CRx,GReg'
5822 * instruction.
5823 */
5824IEM_CIMPL_DEF_4(iemCImpl_load_CrX, uint8_t, iCrReg, uint64_t, uNewCrX, IEMACCESSCRX, enmAccessCrX, uint8_t, iGReg)
5825{
5826 VBOXSTRICTRC rcStrict;
5827 int rc;
5828#ifndef VBOX_WITH_NESTED_HWVIRT_SVM
5829 RT_NOREF2(iGReg, enmAccessCrX);
5830#endif
5831
5832 /*
5833 * Try store it.
5834 * Unfortunately, CPUM only does a tiny bit of the work.
5835 */
5836 switch (iCrReg)
5837 {
5838 case 0:
5839 {
5840 /*
5841 * Perform checks.
5842 */
5843 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
5844
5845 uint64_t const uOldCrX = pVCpu->cpum.GstCtx.cr0;
5846 uint32_t const fValid = CPUMGetGuestCR0ValidMask();
5847
5848 /* ET is hardcoded on 486 and later. */
5849 if (IEM_GET_TARGET_CPU(pVCpu) > IEMTARGETCPU_486)
5850 uNewCrX |= X86_CR0_ET;
5851 /* The 386 and 486 didn't #GP(0) on attempting to set reserved CR0 bits. ET was settable on 386. */
5852 else if (IEM_GET_TARGET_CPU(pVCpu) == IEMTARGETCPU_486)
5853 {
5854 uNewCrX &= fValid;
5855 uNewCrX |= X86_CR0_ET;
5856 }
5857 else
5858 uNewCrX &= X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG | X86_CR0_ET;
5859
5860 /* Check for reserved bits. */
5861 if (uNewCrX & ~(uint64_t)fValid)
5862 {
5863 Log(("Trying to set reserved CR0 bits: NewCR0=%#llx InvalidBits=%#llx\n", uNewCrX, uNewCrX & ~(uint64_t)fValid));
5864 return iemRaiseGeneralProtectionFault0(pVCpu);
5865 }
5866
5867 /* Check for invalid combinations. */
5868 if ( (uNewCrX & X86_CR0_PG)
5869 && !(uNewCrX & X86_CR0_PE) )
5870 {
5871 Log(("Trying to set CR0.PG without CR0.PE\n"));
5872 return iemRaiseGeneralProtectionFault0(pVCpu);
5873 }
5874
5875 if ( !(uNewCrX & X86_CR0_CD)
5876 && (uNewCrX & X86_CR0_NW) )
5877 {
5878 Log(("Trying to clear CR0.CD while leaving CR0.NW set\n"));
5879 return iemRaiseGeneralProtectionFault0(pVCpu);
5880 }
5881
5882 if ( !(uNewCrX & X86_CR0_PG)
5883 && (pVCpu->cpum.GstCtx.cr4 & X86_CR4_PCIDE))
5884 {
5885 Log(("Trying to clear CR0.PG while leaving CR4.PCID set\n"));
5886 return iemRaiseGeneralProtectionFault0(pVCpu);
5887 }
5888
5889 /* Long mode consistency checks. */
5890 if ( (uNewCrX & X86_CR0_PG)
5891 && !(uOldCrX & X86_CR0_PG)
5892 && (pVCpu->cpum.GstCtx.msrEFER & MSR_K6_EFER_LME) )
5893 {
5894 if (!(pVCpu->cpum.GstCtx.cr4 & X86_CR4_PAE))
5895 {
5896 Log(("Trying to enabled long mode paging without CR4.PAE set\n"));
5897 return iemRaiseGeneralProtectionFault0(pVCpu);
5898 }
5899 if (pVCpu->cpum.GstCtx.cs.Attr.n.u1Long)
5900 {
5901 Log(("Trying to enabled long mode paging with a long CS descriptor loaded.\n"));
5902 return iemRaiseGeneralProtectionFault0(pVCpu);
5903 }
5904 }
5905
5906 /** @todo testcase: what happens if we disable paging while in 64-bit code? */
5907
5908 if (!IEM_IS_IN_GUEST(pVCpu))
5909 { /* probable */ }
5910#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5911 /* Check for bits that must remain set or cleared in VMX operation,
5912 see Intel spec. 23.8 "Restrictions on VMX operation". */
5913 else if (IEM_VMX_IS_ROOT_MODE(pVCpu))
5914 {
5915 uint64_t const uCr0Fixed0 = iemVmxGetCr0Fixed0(pVCpu, IEM_VMX_IS_NON_ROOT_MODE(pVCpu));
5916 if ((uNewCrX & uCr0Fixed0) != uCr0Fixed0)
5917 {
5918 Log(("Trying to clear reserved CR0 bits in VMX operation: NewCr0=%#llx MB1=%#llx\n", uNewCrX, uCr0Fixed0));
5919 return iemRaiseGeneralProtectionFault0(pVCpu);
5920 }
5921
5922 uint64_t const uCr0Fixed1 = pVCpu->cpum.GstCtx.hwvirt.vmx.Msrs.u64Cr0Fixed1;
5923 if (uNewCrX & ~uCr0Fixed1)
5924 {
5925 Log(("Trying to set reserved CR0 bits in VMX operation: NewCr0=%#llx MB0=%#llx\n", uNewCrX, uCr0Fixed1));
5926 return iemRaiseGeneralProtectionFault0(pVCpu);
5927 }
5928 }
5929#endif
5930 /*
5931 * SVM nested-guest CR0 write intercepts.
5932 */
5933 else if (IEM_SVM_IS_WRITE_CR_INTERCEPT_SET(pVCpu, iCrReg))
5934 {
5935 Log(("iemCImpl_load_Cr%#x: Guest intercept -> #VMEXIT\n", iCrReg));
5936 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
5937 IEM_SVM_CRX_VMEXIT_RET(pVCpu, SVM_EXIT_WRITE_CR0, enmAccessCrX, iGReg);
5938 }
5939 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_CR0_SEL_WRITE))
5940 {
5941 /* 'lmsw' intercepts regardless of whether the TS/MP bits are actually toggled. */
5942 if ( enmAccessCrX == IEMACCESSCRX_LMSW
5943 || (uNewCrX & ~(X86_CR0_TS | X86_CR0_MP)) != (uOldCrX & ~(X86_CR0_TS | X86_CR0_MP)))
5944 {
5945 Assert(enmAccessCrX != IEMACCESSCRX_CLTS);
5946 Log(("iemCImpl_load_Cr%#x: lmsw or bits other than TS/MP changed: Guest intercept -> #VMEXIT\n", iCrReg));
5947 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
5948 IEM_SVM_CRX_VMEXIT_RET(pVCpu, SVM_EXIT_CR0_SEL_WRITE, enmAccessCrX, iGReg);
5949 }
5950 }
5951
5952 /*
5953 * Change EFER.LMA if entering or leaving long mode.
5954 */
5955 uint64_t NewEFER = pVCpu->cpum.GstCtx.msrEFER;
5956 if ( (uNewCrX & X86_CR0_PG) != (uOldCrX & X86_CR0_PG)
5957 && (pVCpu->cpum.GstCtx.msrEFER & MSR_K6_EFER_LME) )
5958 {
5959 if (uNewCrX & X86_CR0_PG)
5960 NewEFER |= MSR_K6_EFER_LMA;
5961 else
5962 NewEFER &= ~MSR_K6_EFER_LMA;
5963
5964 CPUMSetGuestEFER(pVCpu, NewEFER);
5965 Assert(pVCpu->cpum.GstCtx.msrEFER == NewEFER);
5966 }
5967
5968 /*
5969 * Inform PGM.
5970 */
5971 if ( (uNewCrX & (X86_CR0_PG | X86_CR0_WP | X86_CR0_PE | X86_CR0_CD | X86_CR0_NW))
5972 != (uOldCrX & (X86_CR0_PG | X86_CR0_WP | X86_CR0_PE | X86_CR0_CD | X86_CR0_NW)) )
5973 {
5974 if ( enmAccessCrX != IEMACCESSCRX_MOV_CRX
5975 || !CPUMIsPaePagingEnabled(uNewCrX, pVCpu->cpum.GstCtx.cr4, NewEFER)
5976 || CPUMIsGuestInSvmNestedHwVirtMode(IEM_GET_CTX(pVCpu)))
5977 { /* likely */ }
5978 else
5979 IEM_MAP_PAE_PDPES_AT_CR3_RET(pVCpu, iCrReg, pVCpu->cpum.GstCtx.cr3);
5980 rc = PGMFlushTLB(pVCpu, pVCpu->cpum.GstCtx.cr3, true /* global */);
5981 AssertRCReturn(rc, rc);
5982 /* ignore informational status codes */
5983 }
5984
5985 /*
5986 * Change CR0.
5987 */
5988 CPUMSetGuestCR0(pVCpu, uNewCrX);
5989 Assert(pVCpu->cpum.GstCtx.cr0 == uNewCrX);
5990
5991 /* Update the fExec flags if PE changed. */
5992 if ((uNewCrX ^ uOldCrX) & X86_CR0_PE)
5993 iemRecalcExecModeAndCplFlags(pVCpu);
5994
5995 /*
5996 * Inform PGM some more...
5997 */
5998 rcStrict = PGMChangeMode(pVCpu, pVCpu->cpum.GstCtx.cr0, pVCpu->cpum.GstCtx.cr4, pVCpu->cpum.GstCtx.msrEFER,
5999 false /* fForce */);
6000 break;
6001 }
6002
6003 /*
6004 * CR2 can be changed without any restrictions.
6005 */
6006 case 2:
6007 {
6008 if (!IEM_SVM_IS_WRITE_CR_INTERCEPT_SET(pVCpu, /*cr*/ 2))
6009 { /* probable */ }
6010 else
6011 {
6012 Log(("iemCImpl_load_Cr%#x: Guest intercept -> #VMEXIT\n", iCrReg));
6013 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
6014 IEM_SVM_CRX_VMEXIT_RET(pVCpu, SVM_EXIT_WRITE_CR2, enmAccessCrX, iGReg);
6015 }
6016 pVCpu->cpum.GstCtx.cr2 = uNewCrX;
6017 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_CR2;
6018 rcStrict = VINF_SUCCESS;
6019 break;
6020 }
6021
6022 /*
6023 * CR3 is relatively simple, although AMD and Intel have different
6024 * accounts of how setting reserved bits are handled. We take intel's
6025 * word for the lower bits and AMD's for the high bits (63:52). The
6026 * lower reserved bits are ignored and left alone; OpenBSD 5.8 relies
6027 * on this.
6028 */
6029 /** @todo Testcase: Setting reserved bits in CR3, especially before
6030 * enabling paging. */
6031 case 3:
6032 {
6033 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR3);
6034
6035 /* Bit 63 being clear in the source operand with PCIDE indicates no invalidations are required. */
6036 if ( (pVCpu->cpum.GstCtx.cr4 & X86_CR4_PCIDE)
6037 && (uNewCrX & RT_BIT_64(63)))
6038 {
6039 /** @todo r=ramshankar: avoiding a TLB flush altogether here causes Windows 10
6040 * SMP(w/o nested-paging) to hang during bootup on Skylake systems, see
6041 * Intel spec. 4.10.4.1 "Operations that Invalidate TLBs and
6042 * Paging-Structure Caches". */
6043 uNewCrX &= ~RT_BIT_64(63);
6044 }
6045
6046 /* Check / mask the value. */
6047#ifdef VBOX_WITH_NESTED_HWVIRT_VMX_EPT
6048 /* See Intel spec. 27.2.2 "EPT Translation Mechanism" footnote. */
6049 uint64_t const fInvPhysMask = !CPUMIsGuestVmxEptPagingEnabledEx(IEM_GET_CTX(pVCpu))
6050 ? (UINT64_MAX << IEM_GET_GUEST_CPU_FEATURES(pVCpu)->cMaxPhysAddrWidth)
6051 : (~X86_CR3_EPT_PAGE_MASK & X86_PAGE_4K_BASE_MASK);
6052#else
6053 uint64_t const fInvPhysMask = UINT64_C(0xfff0000000000000);
6054#endif
6055 if (uNewCrX & fInvPhysMask)
6056 {
6057 /** @todo Should we raise this only for 64-bit mode like Intel claims? AMD is
6058 * very vague in this area. As mentioned above, need testcase on real
6059 * hardware... Sigh. */
6060 Log(("Trying to load CR3 with invalid high bits set: %#llx\n", uNewCrX));
6061 return iemRaiseGeneralProtectionFault0(pVCpu);
6062 }
6063
6064 uint64_t fValid;
6065 if ( (pVCpu->cpum.GstCtx.cr4 & X86_CR4_PAE)
6066 && (pVCpu->cpum.GstCtx.msrEFER & MSR_K6_EFER_LME))
6067 {
6068 /** @todo Redundant? This value has already been validated above. */
6069 fValid = UINT64_C(0x000fffffffffffff);
6070 }
6071 else
6072 fValid = UINT64_C(0xffffffff);
6073 if (uNewCrX & ~fValid)
6074 {
6075 Log(("Automatically clearing reserved MBZ bits in CR3 load: NewCR3=%#llx ClearedBits=%#llx\n",
6076 uNewCrX, uNewCrX & ~fValid));
6077 uNewCrX &= fValid;
6078 }
6079
6080 if (!IEM_SVM_IS_WRITE_CR_INTERCEPT_SET(pVCpu, /*cr*/ 3))
6081 { /* probable */ }
6082 else
6083 {
6084 Log(("iemCImpl_load_Cr%#x: Guest intercept -> #VMEXIT\n", iCrReg));
6085 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
6086 IEM_SVM_CRX_VMEXIT_RET(pVCpu, SVM_EXIT_WRITE_CR3, enmAccessCrX, iGReg);
6087 }
6088
6089 /* Inform PGM. */
6090 if (pVCpu->cpum.GstCtx.cr0 & X86_CR0_PG)
6091 {
6092 if ( !CPUMIsGuestInPAEModeEx(IEM_GET_CTX(pVCpu))
6093 || CPUMIsGuestInSvmNestedHwVirtMode(IEM_GET_CTX(pVCpu)))
6094 { /* likely */ }
6095 else
6096 {
6097 Assert(enmAccessCrX == IEMACCESSCRX_MOV_CRX);
6098 IEM_MAP_PAE_PDPES_AT_CR3_RET(pVCpu, iCrReg, uNewCrX);
6099 }
6100 rc = PGMFlushTLB(pVCpu, uNewCrX, !(pVCpu->cpum.GstCtx.cr4 & X86_CR4_PGE));
6101 AssertRCReturn(rc, rc);
6102 /* ignore informational status codes */
6103 }
6104
6105 /* Make the change. */
6106 rc = CPUMSetGuestCR3(pVCpu, uNewCrX);
6107 AssertRCSuccessReturn(rc, rc);
6108
6109 rcStrict = VINF_SUCCESS;
6110 break;
6111 }
6112
6113 /*
6114 * CR4 is a bit more tedious as there are bits which cannot be cleared
6115 * under some circumstances and such.
6116 */
6117 case 4:
6118 {
6119 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
6120 uint64_t const uOldCrX = pVCpu->cpum.GstCtx.cr4;
6121
6122 /* Reserved bits. */
6123 uint32_t const fValid = CPUMGetGuestCR4ValidMask(pVCpu->CTX_SUFF(pVM));
6124 if (uNewCrX & ~(uint64_t)fValid)
6125 {
6126 Log(("Trying to set reserved CR4 bits: NewCR4=%#llx InvalidBits=%#llx\n", uNewCrX, uNewCrX & ~(uint64_t)fValid));
6127 return iemRaiseGeneralProtectionFault0(pVCpu);
6128 }
6129
6130 bool const fPcide = !(uOldCrX & X86_CR4_PCIDE) && (uNewCrX & X86_CR4_PCIDE);
6131 bool const fLongMode = CPUMIsGuestInLongModeEx(IEM_GET_CTX(pVCpu));
6132
6133 /* PCIDE check. */
6134 if ( fPcide
6135 && ( !fLongMode
6136 || (pVCpu->cpum.GstCtx.cr3 & UINT64_C(0xfff))))
6137 {
6138 Log(("Trying to set PCIDE with invalid PCID or outside long mode. Pcid=%#x\n", (pVCpu->cpum.GstCtx.cr3 & UINT64_C(0xfff))));
6139 return iemRaiseGeneralProtectionFault0(pVCpu);
6140 }
6141
6142 /* PAE check. */
6143 if ( fLongMode
6144 && (uOldCrX & X86_CR4_PAE)
6145 && !(uNewCrX & X86_CR4_PAE))
6146 {
6147 Log(("Trying to set clear CR4.PAE while long mode is active\n"));
6148 return iemRaiseGeneralProtectionFault0(pVCpu);
6149 }
6150
6151 if (!IEM_SVM_IS_WRITE_CR_INTERCEPT_SET(pVCpu, /*cr*/ 4))
6152 { /* probable */ }
6153 else
6154 {
6155 Log(("iemCImpl_load_Cr%#x: Guest intercept -> #VMEXIT\n", iCrReg));
6156 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
6157 IEM_SVM_CRX_VMEXIT_RET(pVCpu, SVM_EXIT_WRITE_CR4, enmAccessCrX, iGReg);
6158 }
6159
6160 /* Check for bits that must remain set or cleared in VMX operation,
6161 see Intel spec. 23.8 "Restrictions on VMX operation". */
6162 if (!IEM_VMX_IS_ROOT_MODE(pVCpu))
6163 { /* probable */ }
6164 else
6165 {
6166 uint64_t const uCr4Fixed0 = pVCpu->cpum.GstCtx.hwvirt.vmx.Msrs.u64Cr4Fixed0;
6167 if ((uNewCrX & uCr4Fixed0) != uCr4Fixed0)
6168 {
6169 Log(("Trying to clear reserved CR4 bits in VMX operation: NewCr4=%#llx MB1=%#llx\n", uNewCrX, uCr4Fixed0));
6170 return iemRaiseGeneralProtectionFault0(pVCpu);
6171 }
6172
6173 uint64_t const uCr4Fixed1 = pVCpu->cpum.GstCtx.hwvirt.vmx.Msrs.u64Cr4Fixed1;
6174 if (uNewCrX & ~uCr4Fixed1)
6175 {
6176 Log(("Trying to set reserved CR4 bits in VMX operation: NewCr4=%#llx MB0=%#llx\n", uNewCrX, uCr4Fixed1));
6177 return iemRaiseGeneralProtectionFault0(pVCpu);
6178 }
6179 }
6180
6181 /*
6182 * Notify PGM.
6183 */
6184 if ((uNewCrX ^ uOldCrX) & (X86_CR4_PSE | X86_CR4_PAE | X86_CR4_PGE | X86_CR4_PCIDE /* | X86_CR4_SMEP */))
6185 {
6186 if ( !CPUMIsPaePagingEnabled(pVCpu->cpum.GstCtx.cr0, uNewCrX, pVCpu->cpum.GstCtx.msrEFER)
6187 || CPUMIsGuestInSvmNestedHwVirtMode(IEM_GET_CTX(pVCpu)))
6188 { /* likely */ }
6189 else
6190 {
6191 Assert(enmAccessCrX == IEMACCESSCRX_MOV_CRX);
6192 IEM_MAP_PAE_PDPES_AT_CR3_RET(pVCpu, iCrReg, pVCpu->cpum.GstCtx.cr3);
6193 }
6194 rc = PGMFlushTLB(pVCpu, pVCpu->cpum.GstCtx.cr3, true /* global */);
6195 AssertRCReturn(rc, rc);
6196 /* ignore informational status codes */
6197 }
6198
6199 /*
6200 * Change it.
6201 */
6202 rc = CPUMSetGuestCR4(pVCpu, uNewCrX);
6203 AssertRCSuccessReturn(rc, rc);
6204 Assert(pVCpu->cpum.GstCtx.cr4 == uNewCrX);
6205
6206 rcStrict = PGMChangeMode(pVCpu, pVCpu->cpum.GstCtx.cr0, pVCpu->cpum.GstCtx.cr4, pVCpu->cpum.GstCtx.msrEFER,
6207 false /* fForce */);
6208 break;
6209 }
6210
6211 /*
6212 * CR8 maps to the APIC TPR.
6213 */
6214 case 8:
6215 {
6216 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_APIC_TPR);
6217 if (uNewCrX & ~(uint64_t)0xf)
6218 {
6219 Log(("Trying to set reserved CR8 bits (%#RX64)\n", uNewCrX));
6220 return iemRaiseGeneralProtectionFault0(pVCpu);
6221 }
6222
6223 if (!IEM_IS_IN_GUEST(pVCpu))
6224 { /* probable */ }
6225#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
6226 else if ( IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
6227 && IEM_VMX_IS_PROCCTLS_SET(pVCpu, VMX_PROC_CTLS_USE_TPR_SHADOW))
6228 {
6229 /*
6230 * If the Mov-to-CR8 doesn't cause a VM-exit, bits 0:3 of the source operand
6231 * is copied to bits 7:4 of the VTPR. Bits 0:3 and bits 31:8 of the VTPR are
6232 * cleared. Following this the processor performs TPR virtualization.
6233 *
6234 * However, we should not perform TPR virtualization immediately here but
6235 * after this instruction has completed.
6236 *
6237 * See Intel spec. 29.3 "Virtualizing CR8-based TPR Accesses"
6238 * See Intel spec. 27.1 "Architectural State Before A VM-exit"
6239 */
6240 uint32_t const uTpr = (uNewCrX & 0xf) << 4;
6241 Log(("iemCImpl_load_Cr%#x: Virtualizing TPR (%#x) write\n", iCrReg, uTpr));
6242 iemVmxVirtApicWriteRaw32(pVCpu, XAPIC_OFF_TPR, uTpr);
6243 iemVmxVirtApicSetPendingWrite(pVCpu, XAPIC_OFF_TPR);
6244 rcStrict = VINF_SUCCESS;
6245 break;
6246 }
6247#endif
6248#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
6249 else if (pVCpu->iem.s.fExec & IEM_F_X86_CTX_SVM)
6250 {
6251 if (IEM_SVM_IS_WRITE_CR_INTERCEPT_SET(pVCpu, /*cr*/ 8))
6252 {
6253 Log(("iemCImpl_load_Cr%#x: Guest intercept -> #VMEXIT\n", iCrReg));
6254 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
6255 IEM_SVM_CRX_VMEXIT_RET(pVCpu, SVM_EXIT_WRITE_CR8, enmAccessCrX, iGReg);
6256 }
6257
6258 pVCpu->cpum.GstCtx.hwvirt.svm.Vmcb.ctrl.IntCtrl.n.u8VTPR = uNewCrX;
6259 if (CPUMIsGuestSvmVirtIntrMasking(pVCpu, IEM_GET_CTX(pVCpu)))
6260 {
6261 rcStrict = VINF_SUCCESS;
6262 break;
6263 }
6264 }
6265#endif
6266 uint8_t const u8Tpr = (uint8_t)uNewCrX << 4;
6267 APICSetTpr(pVCpu, u8Tpr);
6268 rcStrict = VINF_SUCCESS;
6269 break;
6270 }
6271
6272 IEM_NOT_REACHED_DEFAULT_CASE_RET(); /* call checks */
6273 }
6274
6275 /*
6276 * Advance the RIP on success.
6277 */
6278 if (RT_SUCCESS(rcStrict))
6279 {
6280 if (rcStrict != VINF_SUCCESS)
6281 iemSetPassUpStatus(pVCpu, rcStrict);
6282 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
6283 }
6284
6285 return rcStrict;
6286}
6287
6288
6289/**
6290 * Implements mov CRx,GReg.
6291 *
6292 * @param iCrReg The CRx register to write (valid).
6293 * @param iGReg The general register to load the CRx value from.
6294 */
6295IEM_CIMPL_DEF_2(iemCImpl_mov_Cd_Rd, uint8_t, iCrReg, uint8_t, iGReg)
6296{
6297 if (IEM_GET_CPL(pVCpu) != 0)
6298 return iemRaiseGeneralProtectionFault0(pVCpu);
6299 Assert(!pVCpu->cpum.GstCtx.eflags.Bits.u1VM);
6300
6301 /*
6302 * Read the new value from the source register and call common worker.
6303 */
6304 uint64_t uNewCrX;
6305 if (IEM_IS_64BIT_CODE(pVCpu))
6306 uNewCrX = iemGRegFetchU64(pVCpu, iGReg);
6307 else
6308 uNewCrX = iemGRegFetchU32(pVCpu, iGReg);
6309
6310#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
6311 if (!IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
6312 { /* probable */ }
6313 else
6314 {
6315 VBOXSTRICTRC rcStrict = VINF_VMX_INTERCEPT_NOT_ACTIVE;
6316 switch (iCrReg)
6317 {
6318 case 0:
6319 case 4: rcStrict = iemVmxVmexitInstrMovToCr0Cr4(pVCpu, iCrReg, &uNewCrX, iGReg, cbInstr); break;
6320 case 3: rcStrict = iemVmxVmexitInstrMovToCr3(pVCpu, uNewCrX, iGReg, cbInstr); break;
6321 case 8: rcStrict = iemVmxVmexitInstrMovToCr8(pVCpu, iGReg, cbInstr); break;
6322 }
6323 if (rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE)
6324 return rcStrict;
6325 }
6326#endif
6327
6328 return IEM_CIMPL_CALL_4(iemCImpl_load_CrX, iCrReg, uNewCrX, IEMACCESSCRX_MOV_CRX, iGReg);
6329}
6330
6331
6332/**
6333 * Implements 'LMSW r/m16'
6334 *
6335 * @param u16NewMsw The new value.
6336 * @param GCPtrEffDst The guest-linear address of the source operand in case
6337 * of a memory operand. For register operand, pass
6338 * NIL_RTGCPTR.
6339 */
6340IEM_CIMPL_DEF_2(iemCImpl_lmsw, uint16_t, u16NewMsw, RTGCPTR, GCPtrEffDst)
6341{
6342 if (IEM_GET_CPL(pVCpu) != 0)
6343 return iemRaiseGeneralProtectionFault0(pVCpu);
6344 Assert(!pVCpu->cpum.GstCtx.eflags.Bits.u1VM);
6345 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
6346
6347#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
6348 /* Check nested-guest VMX intercept and get updated MSW if there's no VM-exit. */
6349 if (!IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
6350 { /* probable */ }
6351 else
6352 {
6353 VBOXSTRICTRC rcStrict = iemVmxVmexitInstrLmsw(pVCpu, pVCpu->cpum.GstCtx.cr0, &u16NewMsw, GCPtrEffDst, cbInstr);
6354 if (rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE)
6355 return rcStrict;
6356 }
6357#else
6358 RT_NOREF_PV(GCPtrEffDst);
6359#endif
6360
6361 /*
6362 * Compose the new CR0 value and call common worker.
6363 */
6364 uint64_t uNewCr0 = pVCpu->cpum.GstCtx.cr0 & ~(X86_CR0_MP | X86_CR0_EM | X86_CR0_TS);
6365 uNewCr0 |= u16NewMsw & (X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS);
6366 return IEM_CIMPL_CALL_4(iemCImpl_load_CrX, /*cr*/ 0, uNewCr0, IEMACCESSCRX_LMSW, UINT8_MAX /* iGReg */);
6367}
6368
6369
6370/**
6371 * Implements 'CLTS'.
6372 */
6373IEM_CIMPL_DEF_0(iemCImpl_clts)
6374{
6375 if (IEM_GET_CPL(pVCpu) != 0)
6376 return iemRaiseGeneralProtectionFault0(pVCpu);
6377
6378 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
6379 uint64_t uNewCr0 = pVCpu->cpum.GstCtx.cr0;
6380 uNewCr0 &= ~X86_CR0_TS;
6381
6382#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
6383 if (!IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
6384 { /* probable */ }
6385 else
6386 {
6387 VBOXSTRICTRC rcStrict = iemVmxVmexitInstrClts(pVCpu, cbInstr);
6388 if (rcStrict == VINF_VMX_MODIFIES_BEHAVIOR)
6389 uNewCr0 |= (pVCpu->cpum.GstCtx.cr0 & X86_CR0_TS);
6390 else if (rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE)
6391 return rcStrict;
6392 }
6393#endif
6394
6395 return IEM_CIMPL_CALL_4(iemCImpl_load_CrX, /*cr*/ 0, uNewCr0, IEMACCESSCRX_CLTS, UINT8_MAX /* iGReg */);
6396}
6397
6398
6399/**
6400 * Implements mov GReg,DRx.
6401 *
6402 * @param iGReg The general register to store the DRx value in.
6403 * @param iDrReg The DRx register to read (0-7).
6404 */
6405IEM_CIMPL_DEF_2(iemCImpl_mov_Rd_Dd, uint8_t, iGReg, uint8_t, iDrReg)
6406{
6407#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
6408 /*
6409 * Check nested-guest VMX intercept.
6410 * Unlike most other intercepts, the Mov DRx intercept takes preceedence
6411 * over CPL and CR4.DE and even DR4/DR5 checks.
6412 *
6413 * See Intel spec. 25.1.3 "Instructions That Cause VM Exits Conditionally".
6414 */
6415 if (!IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
6416 { /* probable */ }
6417 else
6418 {
6419 VBOXSTRICTRC rcStrict = iemVmxVmexitInstrMovDrX(pVCpu, VMXINSTRID_MOV_FROM_DRX, iDrReg, iGReg, cbInstr);
6420 if (rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE)
6421 return rcStrict;
6422 }
6423#endif
6424
6425 /*
6426 * Check preconditions.
6427 */
6428 /* Raise GPs. */
6429 if (IEM_GET_CPL(pVCpu) != 0)
6430 return iemRaiseGeneralProtectionFault0(pVCpu);
6431 Assert(!pVCpu->cpum.GstCtx.eflags.Bits.u1VM);
6432 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_DR7);
6433
6434 /** @todo \#UD in outside ring-0 too? */
6435 if (iDrReg == 4 || iDrReg == 5)
6436 {
6437 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_CR4);
6438 if (pVCpu->cpum.GstCtx.cr4 & X86_CR4_DE)
6439 {
6440 Log(("mov r%u,dr%u: CR4.DE=1 -> #GP(0)\n", iGReg, iDrReg));
6441 return iemRaiseGeneralProtectionFault0(pVCpu);
6442 }
6443 iDrReg += 2;
6444 }
6445
6446 /* Raise #DB if general access detect is enabled. */
6447 if (pVCpu->cpum.GstCtx.dr[7] & X86_DR7_GD)
6448 {
6449 Log(("mov r%u,dr%u: DR7.GD=1 -> #DB\n", iGReg, iDrReg));
6450 return iemRaiseDebugException(pVCpu);
6451 }
6452
6453 /*
6454 * Read the debug register and store it in the specified general register.
6455 */
6456 uint64_t drX;
6457 switch (iDrReg)
6458 {
6459 case 0:
6460 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_DR0_DR3);
6461 drX = pVCpu->cpum.GstCtx.dr[0];
6462 break;
6463 case 1:
6464 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_DR0_DR3);
6465 drX = pVCpu->cpum.GstCtx.dr[1];
6466 break;
6467 case 2:
6468 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_DR0_DR3);
6469 drX = pVCpu->cpum.GstCtx.dr[2];
6470 break;
6471 case 3:
6472 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_DR0_DR3);
6473 drX = pVCpu->cpum.GstCtx.dr[3];
6474 break;
6475 case 6:
6476 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_DR6);
6477 drX = pVCpu->cpum.GstCtx.dr[6];
6478 drX |= X86_DR6_RA1_MASK;
6479 drX &= ~X86_DR6_RAZ_MASK;
6480 break;
6481 case 7:
6482 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_DR7);
6483 drX = pVCpu->cpum.GstCtx.dr[7];
6484 drX |=X86_DR7_RA1_MASK;
6485 drX &= ~X86_DR7_RAZ_MASK;
6486 break;
6487 IEM_NOT_REACHED_DEFAULT_CASE_RET(); /* caller checks */
6488 }
6489
6490 /** @todo SVM nested-guest intercept for DR8-DR15? */
6491 /*
6492 * Check for any SVM nested-guest intercepts for the DRx read.
6493 */
6494 if (!IEM_SVM_IS_READ_DR_INTERCEPT_SET(pVCpu, iDrReg))
6495 { /* probable */ }
6496 else
6497 {
6498 Log(("mov r%u,dr%u: Guest intercept -> #VMEXIT\n", iGReg, iDrReg));
6499 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
6500 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_READ_DR0 + (iDrReg & 0xf),
6501 IEM_GET_GUEST_CPU_FEATURES(pVCpu)->fSvmDecodeAssists ? (iGReg & 7) : 0, 0 /* uExitInfo2 */);
6502 }
6503
6504 if (IEM_IS_64BIT_CODE(pVCpu))
6505 iemGRegStoreU64(pVCpu, iGReg, drX);
6506 else
6507 iemGRegStoreU32(pVCpu, iGReg, (uint32_t)drX);
6508
6509 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
6510}
6511
6512
6513/**
6514 * Implements mov DRx,GReg.
6515 *
6516 * @param iDrReg The DRx register to write (valid).
6517 * @param iGReg The general register to load the DRx value from.
6518 */
6519IEM_CIMPL_DEF_2(iemCImpl_mov_Dd_Rd, uint8_t, iDrReg, uint8_t, iGReg)
6520{
6521#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
6522 /*
6523 * Check nested-guest VMX intercept.
6524 * Unlike most other intercepts, the Mov DRx intercept takes preceedence
6525 * over CPL and CR4.DE and even DR4/DR5 checks.
6526 *
6527 * See Intel spec. 25.1.3 "Instructions That Cause VM Exits Conditionally".
6528 */
6529 if (!IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
6530 { /* probable */ }
6531 else
6532 {
6533 VBOXSTRICTRC rcStrict = iemVmxVmexitInstrMovDrX(pVCpu, VMXINSTRID_MOV_TO_DRX, iDrReg, iGReg, cbInstr);
6534 if (rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE)
6535 return rcStrict;
6536 }
6537#endif
6538
6539 /*
6540 * Check preconditions.
6541 */
6542 if (IEM_GET_CPL(pVCpu) != 0)
6543 return iemRaiseGeneralProtectionFault0(pVCpu);
6544 Assert(!pVCpu->cpum.GstCtx.eflags.Bits.u1VM);
6545 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_DR7);
6546
6547 if (iDrReg == 4 || iDrReg == 5)
6548 {
6549 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_CR4);
6550 if (pVCpu->cpum.GstCtx.cr4 & X86_CR4_DE)
6551 {
6552 Log(("mov dr%u,r%u: CR4.DE=1 -> #GP(0)\n", iDrReg, iGReg));
6553 return iemRaiseGeneralProtectionFault0(pVCpu);
6554 }
6555 iDrReg += 2;
6556 }
6557
6558 /* Raise #DB if general access detect is enabled. */
6559 /** @todo is \#DB/DR7.GD raised before any reserved high bits in DR7/DR6
6560 * \#GP? */
6561 if (pVCpu->cpum.GstCtx.dr[7] & X86_DR7_GD)
6562 {
6563 Log(("mov dr%u,r%u: DR7.GD=1 -> #DB\n", iDrReg, iGReg));
6564 return iemRaiseDebugException(pVCpu);
6565 }
6566
6567 /*
6568 * Read the new value from the source register.
6569 */
6570 uint64_t uNewDrX;
6571 if (IEM_IS_64BIT_CODE(pVCpu))
6572 uNewDrX = iemGRegFetchU64(pVCpu, iGReg);
6573 else
6574 uNewDrX = iemGRegFetchU32(pVCpu, iGReg);
6575
6576 /*
6577 * Adjust it.
6578 */
6579 switch (iDrReg)
6580 {
6581 case 0:
6582 case 1:
6583 case 2:
6584 case 3:
6585 /* nothing to adjust */
6586 break;
6587
6588 case 6:
6589 if (uNewDrX & X86_DR6_MBZ_MASK)
6590 {
6591 Log(("mov dr%u,%#llx: DR6 high bits are not zero -> #GP(0)\n", iDrReg, uNewDrX));
6592 return iemRaiseGeneralProtectionFault0(pVCpu);
6593 }
6594 uNewDrX |= X86_DR6_RA1_MASK;
6595 uNewDrX &= ~X86_DR6_RAZ_MASK;
6596 break;
6597
6598 case 7:
6599 if (uNewDrX & X86_DR7_MBZ_MASK)
6600 {
6601 Log(("mov dr%u,%#llx: DR7 high bits are not zero -> #GP(0)\n", iDrReg, uNewDrX));
6602 return iemRaiseGeneralProtectionFault0(pVCpu);
6603 }
6604 uNewDrX |= X86_DR7_RA1_MASK;
6605 uNewDrX &= ~X86_DR7_RAZ_MASK;
6606 break;
6607
6608 IEM_NOT_REACHED_DEFAULT_CASE_RET();
6609 }
6610
6611 /** @todo SVM nested-guest intercept for DR8-DR15? */
6612 /*
6613 * Check for any SVM nested-guest intercepts for the DRx write.
6614 */
6615 if (!IEM_SVM_IS_WRITE_DR_INTERCEPT_SET(pVCpu, iDrReg))
6616 { /* probable */ }
6617 else
6618 {
6619 Log2(("mov dr%u,r%u: Guest intercept -> #VMEXIT\n", iDrReg, iGReg));
6620 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
6621 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_WRITE_DR0 + (iDrReg & 0xf),
6622 IEM_GET_GUEST_CPU_FEATURES(pVCpu)->fSvmDecodeAssists ? (iGReg & 7) : 0, 0 /* uExitInfo2 */);
6623 }
6624
6625 /*
6626 * Do the actual setting.
6627 */
6628 if (iDrReg < 4)
6629 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_DR0_DR3);
6630 else if (iDrReg == 6)
6631 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_DR6);
6632
6633 int rc = CPUMSetGuestDRx(pVCpu, iDrReg, uNewDrX);
6634 AssertRCSuccessReturn(rc, RT_SUCCESS_NP(rc) ? VERR_IEM_IPE_1 : rc);
6635
6636 /*
6637 * Re-init hardware breakpoint summary if it was DR7 that got changed.
6638 */
6639 if (iDrReg == 7)
6640 iemRecalcExecDbgFlags(pVCpu);
6641
6642 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
6643}
6644
6645
6646/**
6647 * Implements mov GReg,TRx.
6648 *
6649 * @param iGReg The general register to store the
6650 * TRx value in.
6651 * @param iTrReg The TRx register to read (6/7).
6652 */
6653IEM_CIMPL_DEF_2(iemCImpl_mov_Rd_Td, uint8_t, iGReg, uint8_t, iTrReg)
6654{
6655 /*
6656 * Check preconditions. NB: This instruction is 386/486 only.
6657 */
6658
6659 /* Raise GPs. */
6660 if (IEM_GET_CPL(pVCpu) != 0)
6661 return iemRaiseGeneralProtectionFault0(pVCpu);
6662 Assert(!pVCpu->cpum.GstCtx.eflags.Bits.u1VM);
6663
6664 if (iTrReg < 6 || iTrReg > 7)
6665 {
6666 /** @todo Do Intel CPUs reject this or are the TRs aliased? */
6667 Log(("mov r%u,tr%u: invalid register -> #GP(0)\n", iGReg, iTrReg));
6668 return iemRaiseGeneralProtectionFault0(pVCpu);
6669 }
6670
6671 /*
6672 * Read the test register and store it in the specified general register.
6673 * This is currently a dummy implementation that only exists to satisfy
6674 * old debuggers like WDEB386 or OS/2 KDB which unconditionally read the
6675 * TR6/TR7 registers. Software which actually depends on the TR values
6676 * (different on 386/486) is exceedingly rare.
6677 */
6678 uint32_t trX;
6679 switch (iTrReg)
6680 {
6681 case 6:
6682 trX = 0; /* Currently a dummy. */
6683 break;
6684 case 7:
6685 trX = 0; /* Currently a dummy. */
6686 break;
6687 IEM_NOT_REACHED_DEFAULT_CASE_RET(); /* call checks */
6688 }
6689
6690 iemGRegStoreU32(pVCpu, iGReg, trX);
6691
6692 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
6693}
6694
6695
6696/**
6697 * Implements mov TRx,GReg.
6698 *
6699 * @param iTrReg The TRx register to write (valid).
6700 * @param iGReg The general register to load the TRx
6701 * value from.
6702 */
6703IEM_CIMPL_DEF_2(iemCImpl_mov_Td_Rd, uint8_t, iTrReg, uint8_t, iGReg)
6704{
6705 /*
6706 * Check preconditions. NB: This instruction is 386/486 only.
6707 */
6708
6709 /* Raise GPs. */
6710 if (IEM_GET_CPL(pVCpu) != 0)
6711 return iemRaiseGeneralProtectionFault0(pVCpu);
6712 Assert(!pVCpu->cpum.GstCtx.eflags.Bits.u1VM);
6713
6714 if (iTrReg < 6 || iTrReg > 7)
6715 {
6716 /** @todo Do Intel CPUs reject this or are the TRs aliased? */
6717 Log(("mov r%u,tr%u: invalid register -> #GP(0)\n", iGReg, iTrReg));
6718 return iemRaiseGeneralProtectionFault0(pVCpu);
6719 }
6720
6721 /*
6722 * Read the new value from the source register.
6723 */
6724 uint32_t uNewTrX = iemGRegFetchU32(pVCpu, iGReg);
6725
6726 /*
6727 * Here we would do the actual setting if this weren't a dummy implementation.
6728 * This is currently a dummy implementation that only exists to prevent
6729 * old debuggers like WDEB386 or OS/2 KDB from crashing.
6730 */
6731 RT_NOREF(uNewTrX);
6732
6733 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
6734}
6735
6736
6737/**
6738 * Implements 'INVLPG m'.
6739 *
6740 * @param GCPtrPage The effective address of the page to invalidate.
6741 * @remarks Updates the RIP.
6742 */
6743IEM_CIMPL_DEF_1(iemCImpl_invlpg, RTGCPTR, GCPtrPage)
6744{
6745 /* ring-0 only. */
6746 if (IEM_GET_CPL(pVCpu) != 0)
6747 return iemRaiseGeneralProtectionFault0(pVCpu);
6748 Assert(!pVCpu->cpum.GstCtx.eflags.Bits.u1VM);
6749 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR3 | CPUMCTX_EXTRN_CR4 | CPUMCTX_EXTRN_EFER);
6750
6751 if (!IEM_IS_IN_GUEST(pVCpu))
6752 { /* probable */ }
6753#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
6754 else if ( IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
6755 && IEM_VMX_IS_PROCCTLS_SET(pVCpu, VMX_PROC_CTLS_INVLPG_EXIT))
6756 {
6757 Log(("invlpg: Guest intercept (%RGp) -> VM-exit\n", GCPtrPage));
6758 return iemVmxVmexitInstrInvlpg(pVCpu, GCPtrPage, cbInstr);
6759 }
6760#endif
6761 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_INVLPG))
6762 {
6763 Log(("invlpg: Guest intercept (%RGp) -> #VMEXIT\n", GCPtrPage));
6764 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
6765 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_INVLPG,
6766 IEM_GET_GUEST_CPU_FEATURES(pVCpu)->fSvmDecodeAssists ? GCPtrPage : 0, 0 /* uExitInfo2 */);
6767 }
6768
6769 int rc = PGMInvalidatePage(pVCpu, GCPtrPage);
6770 if (rc == VINF_SUCCESS)
6771 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
6772 if (rc == VINF_PGM_SYNC_CR3)
6773 {
6774 iemSetPassUpStatus(pVCpu, rc);
6775 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
6776 }
6777
6778 AssertMsg(RT_FAILURE_NP(rc), ("%Rrc\n", rc));
6779 Log(("PGMInvalidatePage(%RGv) -> %Rrc\n", GCPtrPage, rc));
6780 return rc;
6781}
6782
6783
6784/**
6785 * Implements INVPCID.
6786 *
6787 * @param iEffSeg The segment of the invpcid descriptor.
6788 * @param GCPtrInvpcidDesc The address of invpcid descriptor.
6789 * @param uInvpcidType The invalidation type.
6790 * @remarks Updates the RIP.
6791 */
6792IEM_CIMPL_DEF_3(iemCImpl_invpcid, uint8_t, iEffSeg, RTGCPTR, GCPtrInvpcidDesc, uint64_t, uInvpcidType)
6793{
6794 /*
6795 * Check preconditions.
6796 */
6797 if (!IEM_GET_GUEST_CPU_FEATURES(pVCpu)->fInvpcid)
6798 return iemRaiseUndefinedOpcode(pVCpu);
6799
6800 /* When in VMX non-root mode and INVPCID is not enabled, it results in #UD. */
6801 if (RT_LIKELY( !IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
6802 || IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_INVPCID)))
6803 { /* likely */ }
6804 else
6805 {
6806 Log(("invpcid: Not enabled for nested-guest execution -> #UD\n"));
6807 return iemRaiseUndefinedOpcode(pVCpu);
6808 }
6809
6810 if (IEM_GET_CPL(pVCpu) != 0)
6811 {
6812 Log(("invpcid: CPL != 0 -> #GP(0)\n"));
6813 return iemRaiseGeneralProtectionFault0(pVCpu);
6814 }
6815
6816 if (IEM_IS_V86_MODE(pVCpu))
6817 {
6818 Log(("invpcid: v8086 mode -> #GP(0)\n"));
6819 return iemRaiseGeneralProtectionFault0(pVCpu);
6820 }
6821
6822 /*
6823 * Check nested-guest intercept.
6824 *
6825 * INVPCID causes a VM-exit if "enable INVPCID" and "INVLPG exiting" are
6826 * both set. We have already checked the former earlier in this function.
6827 *
6828 * CPL and virtual-8086 mode checks take priority over this VM-exit.
6829 * See Intel spec. "25.1.1 Relative Priority of Faults and VM Exits".
6830 */
6831 if ( !IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
6832 || !IEM_VMX_IS_PROCCTLS_SET(pVCpu, VMX_PROC_CTLS_INVLPG_EXIT))
6833 { /* probable */ }
6834 else
6835 {
6836 Log(("invpcid: Guest intercept -> #VM-exit\n"));
6837 IEM_VMX_VMEXIT_INSTR_NEEDS_INFO_RET(pVCpu, VMX_EXIT_INVPCID, VMXINSTRID_NONE, cbInstr);
6838 }
6839
6840 if (uInvpcidType > X86_INVPCID_TYPE_MAX_VALID)
6841 {
6842 Log(("invpcid: invalid/unrecognized invpcid type %#RX64 -> #GP(0)\n", uInvpcidType));
6843 return iemRaiseGeneralProtectionFault0(pVCpu);
6844 }
6845 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR3 | CPUMCTX_EXTRN_CR4 | CPUMCTX_EXTRN_EFER);
6846
6847 /*
6848 * Fetch the invpcid descriptor from guest memory.
6849 */
6850 RTUINT128U uDesc;
6851 VBOXSTRICTRC rcStrict = iemMemFetchDataU128(pVCpu, &uDesc, iEffSeg, GCPtrInvpcidDesc);
6852 if (rcStrict == VINF_SUCCESS)
6853 {
6854 /*
6855 * Validate the descriptor.
6856 */
6857 if (uDesc.s.Lo > 0xfff)
6858 {
6859 Log(("invpcid: reserved bits set in invpcid descriptor %#RX64 -> #GP(0)\n", uDesc.s.Lo));
6860 return iemRaiseGeneralProtectionFault0(pVCpu);
6861 }
6862
6863 RTGCUINTPTR64 const GCPtrInvAddr = uDesc.s.Hi;
6864 uint8_t const uPcid = uDesc.s.Lo & UINT64_C(0xfff);
6865 uint32_t const uCr4 = pVCpu->cpum.GstCtx.cr4;
6866 uint64_t const uCr3 = pVCpu->cpum.GstCtx.cr3;
6867 switch (uInvpcidType)
6868 {
6869 case X86_INVPCID_TYPE_INDV_ADDR:
6870 {
6871 if (!IEM_IS_CANONICAL(GCPtrInvAddr))
6872 {
6873 Log(("invpcid: invalidation address %#RGP is not canonical -> #GP(0)\n", GCPtrInvAddr));
6874 return iemRaiseGeneralProtectionFault0(pVCpu);
6875 }
6876 if ( !(uCr4 & X86_CR4_PCIDE)
6877 && uPcid != 0)
6878 {
6879 Log(("invpcid: invalid pcid %#x\n", uPcid));
6880 return iemRaiseGeneralProtectionFault0(pVCpu);
6881 }
6882
6883 /* Invalidate mappings for the linear address tagged with PCID except global translations. */
6884 PGMFlushTLB(pVCpu, uCr3, false /* fGlobal */);
6885 break;
6886 }
6887
6888 case X86_INVPCID_TYPE_SINGLE_CONTEXT:
6889 {
6890 if ( !(uCr4 & X86_CR4_PCIDE)
6891 && uPcid != 0)
6892 {
6893 Log(("invpcid: invalid pcid %#x\n", uPcid));
6894 return iemRaiseGeneralProtectionFault0(pVCpu);
6895 }
6896 /* Invalidate all mappings associated with PCID except global translations. */
6897 PGMFlushTLB(pVCpu, uCr3, false /* fGlobal */);
6898 break;
6899 }
6900
6901 case X86_INVPCID_TYPE_ALL_CONTEXT_INCL_GLOBAL:
6902 {
6903 PGMFlushTLB(pVCpu, uCr3, true /* fGlobal */);
6904 break;
6905 }
6906
6907 case X86_INVPCID_TYPE_ALL_CONTEXT_EXCL_GLOBAL:
6908 {
6909 PGMFlushTLB(pVCpu, uCr3, false /* fGlobal */);
6910 break;
6911 }
6912 IEM_NOT_REACHED_DEFAULT_CASE_RET();
6913 }
6914 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
6915 }
6916 return rcStrict;
6917}
6918
6919
6920/**
6921 * Implements INVD.
6922 */
6923IEM_CIMPL_DEF_0(iemCImpl_invd)
6924{
6925 if (IEM_GET_CPL(pVCpu) != 0)
6926 {
6927 Log(("invd: CPL != 0 -> #GP(0)\n"));
6928 return iemRaiseGeneralProtectionFault0(pVCpu);
6929 }
6930
6931 if (!IEM_IS_IN_GUEST(pVCpu))
6932 { /* probable */ }
6933 else if (IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
6934 IEM_VMX_VMEXIT_INSTR_RET(pVCpu, VMX_EXIT_INVD, cbInstr);
6935 else
6936 IEM_SVM_CHECK_INSTR_INTERCEPT(pVCpu, SVM_CTRL_INTERCEPT_INVD, SVM_EXIT_INVD, 0, 0, cbInstr);
6937
6938 /* We currently take no action here. */
6939 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
6940}
6941
6942
6943/**
6944 * Implements WBINVD.
6945 */
6946IEM_CIMPL_DEF_0(iemCImpl_wbinvd)
6947{
6948 if (IEM_GET_CPL(pVCpu) != 0)
6949 {
6950 Log(("wbinvd: CPL != 0 -> #GP(0)\n"));
6951 return iemRaiseGeneralProtectionFault0(pVCpu);
6952 }
6953
6954 if (!IEM_IS_IN_GUEST(pVCpu))
6955 { /* probable */ }
6956 else if (IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
6957 IEM_VMX_VMEXIT_INSTR_RET(pVCpu, VMX_EXIT_WBINVD, cbInstr);
6958 else
6959 IEM_SVM_CHECK_INSTR_INTERCEPT(pVCpu, SVM_CTRL_INTERCEPT_WBINVD, SVM_EXIT_WBINVD, 0, 0, cbInstr);
6960
6961 /* We currently take no action here. */
6962 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
6963}
6964
6965
6966/** Opcode 0x0f 0xaa. */
6967IEM_CIMPL_DEF_0(iemCImpl_rsm)
6968{
6969 IEM_SVM_CHECK_INSTR_INTERCEPT(pVCpu, SVM_CTRL_INTERCEPT_RSM, SVM_EXIT_RSM, 0, 0, cbInstr);
6970 NOREF(cbInstr);
6971 return iemRaiseUndefinedOpcode(pVCpu);
6972}
6973
6974
6975/**
6976 * Implements RDTSC.
6977 */
6978IEM_CIMPL_DEF_0(iemCImpl_rdtsc)
6979{
6980 /*
6981 * Check preconditions.
6982 */
6983 if (!IEM_GET_GUEST_CPU_FEATURES(pVCpu)->fTsc)
6984 return iemRaiseUndefinedOpcode(pVCpu);
6985
6986 if (IEM_GET_CPL(pVCpu) != 0)
6987 {
6988 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
6989 if (pVCpu->cpum.GstCtx.cr4 & X86_CR4_TSD)
6990 {
6991 Log(("rdtsc: CR4.TSD and CPL=%u -> #GP(0)\n", IEM_GET_CPL(pVCpu)));
6992 return iemRaiseGeneralProtectionFault0(pVCpu);
6993 }
6994 }
6995
6996 if (!IEM_IS_IN_GUEST(pVCpu))
6997 { /* probable */ }
6998 else if ( IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
6999 && IEM_VMX_IS_PROCCTLS_SET(pVCpu, VMX_PROC_CTLS_RDTSC_EXIT))
7000 {
7001 Log(("rdtsc: Guest intercept -> VM-exit\n"));
7002 IEM_VMX_VMEXIT_INSTR_RET(pVCpu, VMX_EXIT_RDTSC, cbInstr);
7003 }
7004 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_RDTSC))
7005 {
7006 Log(("rdtsc: Guest intercept -> #VMEXIT\n"));
7007 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
7008 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_RDTSC, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
7009 }
7010
7011 /*
7012 * Do the job.
7013 */
7014 uint64_t uTicks = TMCpuTickGet(pVCpu);
7015#if defined(VBOX_WITH_NESTED_HWVIRT_SVM) || defined(VBOX_WITH_NESTED_HWVIRT_VMX)
7016 uTicks = CPUMApplyNestedGuestTscOffset(pVCpu, uTicks);
7017#endif
7018 pVCpu->cpum.GstCtx.rax = RT_LO_U32(uTicks);
7019 pVCpu->cpum.GstCtx.rdx = RT_HI_U32(uTicks);
7020 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RDX); /* For IEMExecDecodedRdtsc. */
7021 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7022}
7023
7024
7025/**
7026 * Implements RDTSC.
7027 */
7028IEM_CIMPL_DEF_0(iemCImpl_rdtscp)
7029{
7030 /*
7031 * Check preconditions.
7032 */
7033 if (!IEM_GET_GUEST_CPU_FEATURES(pVCpu)->fRdTscP)
7034 return iemRaiseUndefinedOpcode(pVCpu);
7035
7036 if (RT_LIKELY( !IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
7037 || IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_RDTSCP)))
7038 { /* likely */ }
7039 else
7040 {
7041 Log(("rdtscp: Not enabled for VMX non-root mode -> #UD\n"));
7042 return iemRaiseUndefinedOpcode(pVCpu);
7043 }
7044
7045 if (IEM_GET_CPL(pVCpu) != 0)
7046 {
7047 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
7048 if (pVCpu->cpum.GstCtx.cr4 & X86_CR4_TSD)
7049 {
7050 Log(("rdtscp: CR4.TSD and CPL=%u -> #GP(0)\n", IEM_GET_CPL(pVCpu)));
7051 return iemRaiseGeneralProtectionFault0(pVCpu);
7052 }
7053 }
7054
7055 if (!IEM_IS_IN_GUEST(pVCpu))
7056 { /* probable */ }
7057 else if ( IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
7058 && IEM_VMX_IS_PROCCTLS_SET(pVCpu, VMX_PROC_CTLS_RDTSC_EXIT))
7059 {
7060 Log(("rdtscp: Guest intercept -> VM-exit\n"));
7061 IEM_VMX_VMEXIT_INSTR_RET(pVCpu, VMX_EXIT_RDTSCP, cbInstr);
7062 }
7063 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_RDTSCP))
7064 {
7065 Log(("rdtscp: Guest intercept -> #VMEXIT\n"));
7066 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
7067 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_RDTSCP, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
7068 }
7069
7070 /*
7071 * Do the job.
7072 * Query the MSR first in case of trips to ring-3.
7073 */
7074 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_TSC_AUX);
7075 VBOXSTRICTRC rcStrict = CPUMQueryGuestMsr(pVCpu, MSR_K8_TSC_AUX, &pVCpu->cpum.GstCtx.rcx);
7076 if (rcStrict == VINF_SUCCESS)
7077 {
7078 /* Low dword of the TSC_AUX msr only. */
7079 pVCpu->cpum.GstCtx.rcx &= UINT32_C(0xffffffff);
7080
7081 uint64_t uTicks = TMCpuTickGet(pVCpu);
7082#if defined(VBOX_WITH_NESTED_HWVIRT_SVM) || defined(VBOX_WITH_NESTED_HWVIRT_VMX)
7083 uTicks = CPUMApplyNestedGuestTscOffset(pVCpu, uTicks);
7084#endif
7085 pVCpu->cpum.GstCtx.rax = RT_LO_U32(uTicks);
7086 pVCpu->cpum.GstCtx.rdx = RT_HI_U32(uTicks);
7087 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RCX); /* For IEMExecDecodedRdtscp. */
7088 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7089 }
7090 return rcStrict;
7091}
7092
7093
7094/**
7095 * Implements RDPMC.
7096 */
7097IEM_CIMPL_DEF_0(iemCImpl_rdpmc)
7098{
7099 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
7100
7101 if ( IEM_GET_CPL(pVCpu) != 0
7102 && !(pVCpu->cpum.GstCtx.cr4 & X86_CR4_PCE))
7103 return iemRaiseGeneralProtectionFault0(pVCpu);
7104
7105 if (!IEM_IS_IN_GUEST(pVCpu))
7106 { /* probable */ }
7107 else if ( IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
7108 && IEM_VMX_IS_PROCCTLS_SET(pVCpu, VMX_PROC_CTLS_RDPMC_EXIT))
7109 {
7110 Log(("rdpmc: Guest intercept -> VM-exit\n"));
7111 IEM_VMX_VMEXIT_INSTR_RET(pVCpu, VMX_EXIT_RDPMC, cbInstr);
7112 }
7113 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_RDPMC))
7114 {
7115 Log(("rdpmc: Guest intercept -> #VMEXIT\n"));
7116 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
7117 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_RDPMC, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
7118 }
7119
7120 /** @todo Emulate performance counters, for now just return 0. */
7121 pVCpu->cpum.GstCtx.rax = 0;
7122 pVCpu->cpum.GstCtx.rdx = 0;
7123 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RDX);
7124 /** @todo We should trigger a \#GP here if the CPU doesn't support the index in
7125 * ecx but see @bugref{3472}! */
7126
7127 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7128}
7129
7130
7131/**
7132 * Implements RDMSR.
7133 */
7134IEM_CIMPL_DEF_0(iemCImpl_rdmsr)
7135{
7136 /*
7137 * Check preconditions.
7138 */
7139 if (!IEM_GET_GUEST_CPU_FEATURES(pVCpu)->fMsr)
7140 return iemRaiseUndefinedOpcode(pVCpu);
7141 if (IEM_GET_CPL(pVCpu) != 0)
7142 return iemRaiseGeneralProtectionFault0(pVCpu);
7143
7144 /*
7145 * Check nested-guest intercepts.
7146 */
7147 if (!IEM_IS_IN_GUEST(pVCpu))
7148 { /* probable */ }
7149#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7150 else if (IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
7151 {
7152 if (iemVmxIsRdmsrWrmsrInterceptSet(pVCpu, VMX_EXIT_RDMSR, pVCpu->cpum.GstCtx.ecx))
7153 IEM_VMX_VMEXIT_INSTR_RET(pVCpu, VMX_EXIT_RDMSR, cbInstr);
7154 }
7155#endif
7156#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
7157 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_MSR_PROT))
7158 {
7159 VBOXSTRICTRC rcStrict = iemSvmHandleMsrIntercept(pVCpu, pVCpu->cpum.GstCtx.ecx, false /* fWrite */, cbInstr);
7160 if (rcStrict == VINF_SVM_VMEXIT)
7161 return VINF_SUCCESS;
7162 if (rcStrict != VINF_SVM_INTERCEPT_NOT_ACTIVE)
7163 {
7164 Log(("IEM: SVM intercepted rdmsr(%#x) failed. rc=%Rrc\n", pVCpu->cpum.GstCtx.ecx, VBOXSTRICTRC_VAL(rcStrict)));
7165 return rcStrict;
7166 }
7167 }
7168#endif
7169
7170 /*
7171 * Do the job.
7172 */
7173 RTUINT64U uValue;
7174 /** @todo make CPUMAllMsrs.cpp import the necessary MSR state. */
7175 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_ALL_MSRS);
7176
7177 VBOXSTRICTRC rcStrict = CPUMQueryGuestMsr(pVCpu, pVCpu->cpum.GstCtx.ecx, &uValue.u);
7178 if (rcStrict == VINF_SUCCESS)
7179 {
7180 pVCpu->cpum.GstCtx.rax = uValue.s.Lo;
7181 pVCpu->cpum.GstCtx.rdx = uValue.s.Hi;
7182 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RDX);
7183
7184 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7185 }
7186
7187#ifndef IN_RING3
7188 /* Deferred to ring-3. */
7189 if (rcStrict == VINF_CPUM_R3_MSR_READ)
7190 {
7191 Log(("IEM: rdmsr(%#x) -> ring-3\n", pVCpu->cpum.GstCtx.ecx));
7192 return rcStrict;
7193 }
7194#endif
7195
7196 /* Often a unimplemented MSR or MSR bit, so worth logging. */
7197 if (pVCpu->iem.s.cLogRelRdMsr < 32)
7198 {
7199 pVCpu->iem.s.cLogRelRdMsr++;
7200 LogRel(("IEM: rdmsr(%#x) -> #GP(0)\n", pVCpu->cpum.GstCtx.ecx));
7201 }
7202 else
7203 Log(( "IEM: rdmsr(%#x) -> #GP(0)\n", pVCpu->cpum.GstCtx.ecx));
7204 AssertMsgReturn(rcStrict == VERR_CPUM_RAISE_GP_0, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)), VERR_IPE_UNEXPECTED_STATUS);
7205 return iemRaiseGeneralProtectionFault0(pVCpu);
7206}
7207
7208
7209/**
7210 * Implements WRMSR.
7211 */
7212IEM_CIMPL_DEF_0(iemCImpl_wrmsr)
7213{
7214 /*
7215 * Check preconditions.
7216 */
7217 if (!IEM_GET_GUEST_CPU_FEATURES(pVCpu)->fMsr)
7218 return iemRaiseUndefinedOpcode(pVCpu);
7219 if (IEM_GET_CPL(pVCpu) != 0)
7220 return iemRaiseGeneralProtectionFault0(pVCpu);
7221
7222 RTUINT64U uValue;
7223 uValue.s.Lo = pVCpu->cpum.GstCtx.eax;
7224 uValue.s.Hi = pVCpu->cpum.GstCtx.edx;
7225
7226 uint32_t const idMsr = pVCpu->cpum.GstCtx.ecx;
7227
7228 /** @todo make CPUMAllMsrs.cpp import the necessary MSR state. */
7229 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_ALL_MSRS);
7230
7231 /*
7232 * Check nested-guest intercepts.
7233 */
7234 if (!IEM_IS_IN_GUEST(pVCpu))
7235 { /* probable */ }
7236#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7237 else if (IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
7238 {
7239 if (iemVmxIsRdmsrWrmsrInterceptSet(pVCpu, VMX_EXIT_WRMSR, idMsr))
7240 IEM_VMX_VMEXIT_INSTR_RET(pVCpu, VMX_EXIT_WRMSR, cbInstr);
7241 }
7242#endif
7243#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
7244 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_MSR_PROT))
7245 {
7246 VBOXSTRICTRC rcStrict = iemSvmHandleMsrIntercept(pVCpu, idMsr, true /* fWrite */, cbInstr);
7247 if (rcStrict == VINF_SVM_VMEXIT)
7248 return VINF_SUCCESS;
7249 if (rcStrict != VINF_SVM_INTERCEPT_NOT_ACTIVE)
7250 {
7251 Log(("IEM: SVM intercepted rdmsr(%#x) failed. rc=%Rrc\n", idMsr, VBOXSTRICTRC_VAL(rcStrict)));
7252 return rcStrict;
7253 }
7254 }
7255#endif
7256
7257 /*
7258 * Do the job.
7259 */
7260 VBOXSTRICTRC rcStrict = CPUMSetGuestMsr(pVCpu, idMsr, uValue.u);
7261 if (rcStrict == VINF_SUCCESS)
7262 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7263
7264#ifndef IN_RING3
7265 /* Deferred to ring-3. */
7266 if (rcStrict == VINF_CPUM_R3_MSR_WRITE)
7267 {
7268 Log(("IEM: wrmsr(%#x) -> ring-3\n", idMsr));
7269 return rcStrict;
7270 }
7271#endif
7272
7273 /* Often a unimplemented MSR or MSR bit, so worth logging. */
7274 if (pVCpu->iem.s.cLogRelWrMsr < 32)
7275 {
7276 pVCpu->iem.s.cLogRelWrMsr++;
7277 LogRel(("IEM: wrmsr(%#x,%#x`%08x) -> #GP(0)\n", idMsr, uValue.s.Hi, uValue.s.Lo));
7278 }
7279 else
7280 Log(( "IEM: wrmsr(%#x,%#x`%08x) -> #GP(0)\n", idMsr, uValue.s.Hi, uValue.s.Lo));
7281 AssertMsgReturn(rcStrict == VERR_CPUM_RAISE_GP_0, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)), VERR_IPE_UNEXPECTED_STATUS);
7282 return iemRaiseGeneralProtectionFault0(pVCpu);
7283}
7284
7285
7286/**
7287 * Implements 'IN eAX, port'.
7288 *
7289 * @param u16Port The source port.
7290 * @param cbReg The register size.
7291 * @param bImmAndEffAddrMode Bit 7: Whether the port was specified through an
7292 * immediate operand or the implicit DX register.
7293 * Bits 3-0: Effective address mode.
7294 */
7295IEM_CIMPL_DEF_3(iemCImpl_in, uint16_t, u16Port, uint8_t, cbReg, uint8_t, bImmAndEffAddrMode)
7296{
7297 /*
7298 * GCM intercept.
7299 *
7300 * This must be placed before the IOPL check as the mesa driver intercept
7301 * would otherwise trigger a #GP(0).
7302 */
7303 if (!IEM_IS_IN_GUEST(pVCpu) && GCMIsInterceptingIOPortRead(pVCpu, u16Port, cbReg))
7304 {
7305 VBOXSTRICTRC rcStrict = GCMInterceptedIOPortRead(pVCpu, &pVCpu->cpum.GstCtx, u16Port, cbReg);
7306 if (rcStrict == VINF_GCM_HANDLED_ADVANCE_RIP || rcStrict == VINF_GCM_HANDLED)
7307 {
7308 Log(("iemCImpl_in: u16Port=%#x cbReg=%d was handled by GCMIOPortRead (%d)\n", u16Port, cbReg, VBOXSTRICTRC_VAL(rcStrict)));
7309 if (rcStrict == VINF_GCM_HANDLED_ADVANCE_RIP)
7310 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7311 else
7312 rcStrict = VINF_SUCCESS;
7313 return rcStrict;
7314 }
7315 Assert(rcStrict == VERR_GCM_NOT_HANDLED);
7316 }
7317
7318 /*
7319 * CPL check
7320 */
7321 VBOXSTRICTRC rcStrict = iemHlpCheckPortIOPermission(pVCpu, u16Port, cbReg);
7322 if (rcStrict != VINF_SUCCESS)
7323 return rcStrict;
7324
7325 if (!IEM_IS_IN_GUEST(pVCpu))
7326 { /* probable */ }
7327
7328 /*
7329 * Check VMX nested-guest IO intercept.
7330 */
7331#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7332 else if (IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
7333 {
7334 rcStrict = iemVmxVmexitInstrIo(pVCpu, VMXINSTRID_IO_IN, u16Port, RT_BOOL(bImmAndEffAddrMode & 0x80), cbReg, cbInstr);
7335 if (rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE)
7336 return rcStrict;
7337 }
7338#endif
7339
7340 /*
7341 * Check SVM nested-guest IO intercept.
7342 */
7343#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
7344 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_IOIO_PROT))
7345 {
7346 uint8_t cAddrSizeBits;
7347 switch (bImmAndEffAddrMode & 0xf)
7348 {
7349 case IEMMODE_16BIT: cAddrSizeBits = 16; break;
7350 case IEMMODE_32BIT: cAddrSizeBits = 32; break;
7351 case IEMMODE_64BIT: cAddrSizeBits = 64; break;
7352 IEM_NOT_REACHED_DEFAULT_CASE_RET();
7353 }
7354 rcStrict = iemSvmHandleIOIntercept(pVCpu, u16Port, SVMIOIOTYPE_IN, cbReg, cAddrSizeBits, 0 /* N/A - iEffSeg */,
7355 false /* fRep */, false /* fStrIo */, cbInstr);
7356 if (rcStrict == VINF_SVM_VMEXIT)
7357 return VINF_SUCCESS;
7358 if (rcStrict != VINF_SVM_INTERCEPT_NOT_ACTIVE)
7359 {
7360 Log(("iemCImpl_in: iemSvmHandleIOIntercept failed (u16Port=%#x, cbReg=%u) rc=%Rrc\n", u16Port, cbReg,
7361 VBOXSTRICTRC_VAL(rcStrict)));
7362 return rcStrict;
7363 }
7364 }
7365#endif
7366#if !defined(VBOX_WITH_NESTED_HWVIRT_VMX) && !defined(VBOX_WITH_NESTED_HWVIRT_SVM)
7367 RT_NOREF(bImmAndEffAddrMode);
7368#endif
7369
7370 /*
7371 * Perform the I/O.
7372 */
7373 PVMCC const pVM = pVCpu->CTX_SUFF(pVM);
7374 uint32_t u32Value = 0;
7375 rcStrict = IOMIOPortRead(pVM, pVCpu, u16Port, &u32Value, cbReg);
7376 if (IOM_SUCCESS(rcStrict))
7377 {
7378 switch (cbReg)
7379 {
7380 case 1: pVCpu->cpum.GstCtx.al = (uint8_t)u32Value; break;
7381 case 2: pVCpu->cpum.GstCtx.ax = (uint16_t)u32Value; break;
7382 case 4: pVCpu->cpum.GstCtx.rax = u32Value; break;
7383 default: AssertFailedReturn(VERR_IEM_IPE_3);
7384 }
7385
7386 pVCpu->iem.s.cPotentialExits++;
7387 if (rcStrict != VINF_SUCCESS)
7388 iemSetPassUpStatus(pVCpu, rcStrict);
7389
7390 /*
7391 * Check for I/O breakpoints before we complete the instruction.
7392 */
7393 uint32_t const fDr7 = pVCpu->cpum.GstCtx.dr[7];
7394 if (RT_UNLIKELY( ( ( (fDr7 & X86_DR7_ENABLED_MASK)
7395 && X86_DR7_ANY_RW_IO(fDr7)
7396 && (pVCpu->cpum.GstCtx.cr4 & X86_CR4_DE))
7397 || pVM->dbgf.ro.cEnabledHwIoBreakpoints > 0)
7398 && rcStrict == VINF_SUCCESS))
7399 {
7400 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_DR0_DR3 | CPUMCTX_EXTRN_DR6);
7401 pVCpu->cpum.GstCtx.eflags.uBoth |= DBGFBpCheckIo2(pVM, pVCpu, u16Port, cbReg);
7402 }
7403
7404 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7405 }
7406
7407 return rcStrict;
7408}
7409
7410
7411/**
7412 * Implements 'IN eAX, DX'.
7413 *
7414 * @param cbReg The register size.
7415 * @param enmEffAddrMode Effective address mode.
7416 */
7417IEM_CIMPL_DEF_2(iemCImpl_in_eAX_DX, uint8_t, cbReg, IEMMODE, enmEffAddrMode)
7418{
7419 return IEM_CIMPL_CALL_3(iemCImpl_in, pVCpu->cpum.GstCtx.dx, cbReg, 0 /* fImm */ | enmEffAddrMode);
7420}
7421
7422
7423/**
7424 * Implements 'OUT port, eAX'.
7425 *
7426 * @param u16Port The destination port.
7427 * @param cbReg The register size.
7428 * @param bImmAndEffAddrMode Bit 7: Whether the port was specified through an
7429 * immediate operand or the implicit DX register.
7430 * Bits 3-0: Effective address mode.
7431 */
7432IEM_CIMPL_DEF_3(iemCImpl_out, uint16_t, u16Port, uint8_t, cbReg, uint8_t, bImmAndEffAddrMode)
7433{
7434 /*
7435 * CPL check
7436 */
7437 VBOXSTRICTRC rcStrict = iemHlpCheckPortIOPermission(pVCpu, u16Port, cbReg);
7438 if (rcStrict != VINF_SUCCESS)
7439 return rcStrict;
7440
7441 if (!IEM_IS_IN_GUEST(pVCpu))
7442 { /* probable */ }
7443
7444 /*
7445 * Check VMX nested-guest I/O intercept.
7446 */
7447#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7448 else if (IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
7449 {
7450 rcStrict = iemVmxVmexitInstrIo(pVCpu, VMXINSTRID_IO_OUT, u16Port, RT_BOOL(bImmAndEffAddrMode & 0x80), cbReg, cbInstr);
7451 if (rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE)
7452 return rcStrict;
7453 }
7454#endif
7455
7456 /*
7457 * Check SVM nested-guest I/O intercept.
7458 */
7459#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
7460 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_IOIO_PROT))
7461 {
7462 uint8_t cAddrSizeBits;
7463 switch (bImmAndEffAddrMode & 0xf)
7464 {
7465 case IEMMODE_16BIT: cAddrSizeBits = 16; break;
7466 case IEMMODE_32BIT: cAddrSizeBits = 32; break;
7467 case IEMMODE_64BIT: cAddrSizeBits = 64; break;
7468 IEM_NOT_REACHED_DEFAULT_CASE_RET();
7469 }
7470 rcStrict = iemSvmHandleIOIntercept(pVCpu, u16Port, SVMIOIOTYPE_OUT, cbReg, cAddrSizeBits, 0 /* N/A - iEffSeg */,
7471 false /* fRep */, false /* fStrIo */, cbInstr);
7472 if (rcStrict == VINF_SVM_VMEXIT)
7473 return VINF_SUCCESS;
7474 if (rcStrict != VINF_SVM_INTERCEPT_NOT_ACTIVE)
7475 {
7476 Log(("iemCImpl_out: iemSvmHandleIOIntercept failed (u16Port=%#x, cbReg=%u) rc=%Rrc\n", u16Port, cbReg,
7477 VBOXSTRICTRC_VAL(rcStrict)));
7478 return rcStrict;
7479 }
7480 }
7481#endif
7482#if !defined(VBOX_WITH_NESTED_HWVIRT_VMX) && !defined(VBOX_WITH_NESTED_HWVIRT_SVM)
7483 RT_NOREF(bImmAndEffAddrMode);
7484#endif
7485
7486 /*
7487 * Perform the I/O.
7488 */
7489 PVMCC const pVM = pVCpu->CTX_SUFF(pVM);
7490 uint32_t u32Value;
7491 switch (cbReg)
7492 {
7493 case 1: u32Value = pVCpu->cpum.GstCtx.al; break;
7494 case 2: u32Value = pVCpu->cpum.GstCtx.ax; break;
7495 case 4: u32Value = pVCpu->cpum.GstCtx.eax; break;
7496 default: AssertFailedReturn(VERR_IEM_IPE_4);
7497 }
7498 rcStrict = IOMIOPortWrite(pVM, pVCpu, u16Port, u32Value, cbReg);
7499 if (IOM_SUCCESS(rcStrict))
7500 {
7501 pVCpu->iem.s.cPotentialExits++;
7502 if (rcStrict != VINF_SUCCESS)
7503 iemSetPassUpStatus(pVCpu, rcStrict);
7504
7505 /*
7506 * Check for I/O breakpoints before we complete the instruction.
7507 */
7508 uint32_t const fDr7 = pVCpu->cpum.GstCtx.dr[7];
7509 if (RT_UNLIKELY( ( ( (fDr7 & X86_DR7_ENABLED_MASK)
7510 && X86_DR7_ANY_RW_IO(fDr7)
7511 && (pVCpu->cpum.GstCtx.cr4 & X86_CR4_DE))
7512 || pVM->dbgf.ro.cEnabledHwIoBreakpoints > 0)
7513 && rcStrict == VINF_SUCCESS))
7514 {
7515 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_DR0_DR3 | CPUMCTX_EXTRN_DR6);
7516 pVCpu->cpum.GstCtx.eflags.uBoth |= DBGFBpCheckIo2(pVM, pVCpu, u16Port, cbReg);
7517 }
7518
7519 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7520 }
7521 return rcStrict;
7522}
7523
7524
7525/**
7526 * Implements 'OUT DX, eAX'.
7527 *
7528 * @param cbReg The register size.
7529 * @param enmEffAddrMode Effective address mode.
7530 */
7531IEM_CIMPL_DEF_2(iemCImpl_out_DX_eAX, uint8_t, cbReg, IEMMODE, enmEffAddrMode)
7532{
7533 return IEM_CIMPL_CALL_3(iemCImpl_out, pVCpu->cpum.GstCtx.dx, cbReg, 0 /* fImm */ | enmEffAddrMode);
7534}
7535
7536
7537/**
7538 * Implements 'CLI'.
7539 */
7540IEM_CIMPL_DEF_0(iemCImpl_cli)
7541{
7542 uint32_t fEfl = IEMMISC_GET_EFL(pVCpu);
7543#ifdef LOG_ENABLED
7544 uint32_t const fEflOld = fEfl;
7545#endif
7546
7547 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR4);
7548 if (pVCpu->cpum.GstCtx.cr0 & X86_CR0_PE)
7549 {
7550 uint8_t const uIopl = X86_EFL_GET_IOPL(fEfl);
7551 if (!(fEfl & X86_EFL_VM))
7552 {
7553 if (IEM_GET_CPL(pVCpu) <= uIopl)
7554 fEfl &= ~X86_EFL_IF;
7555 else if ( IEM_GET_CPL(pVCpu) == 3
7556 && (pVCpu->cpum.GstCtx.cr4 & X86_CR4_PVI) )
7557 fEfl &= ~X86_EFL_VIF;
7558 else
7559 return iemRaiseGeneralProtectionFault0(pVCpu);
7560 }
7561 /* V8086 */
7562 else if (uIopl == 3)
7563 fEfl &= ~X86_EFL_IF;
7564 else if ( uIopl < 3
7565 && (pVCpu->cpum.GstCtx.cr4 & X86_CR4_VME) )
7566 fEfl &= ~X86_EFL_VIF;
7567 else
7568 return iemRaiseGeneralProtectionFault0(pVCpu);
7569 }
7570 /* real mode */
7571 else
7572 fEfl &= ~X86_EFL_IF;
7573
7574 /* Commit. */
7575 IEMMISC_SET_EFL(pVCpu, fEfl);
7576 VBOXSTRICTRC const rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7577 Log2(("CLI: %#x -> %#x\n", fEflOld, fEfl));
7578 return rcStrict;
7579}
7580
7581
7582/**
7583 * Implements 'STI'.
7584 */
7585IEM_CIMPL_DEF_0(iemCImpl_sti)
7586{
7587 uint32_t fEfl = IEMMISC_GET_EFL(pVCpu);
7588 uint32_t const fEflOld = fEfl;
7589
7590 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR4);
7591 if (pVCpu->cpum.GstCtx.cr0 & X86_CR0_PE)
7592 {
7593 uint8_t const uIopl = X86_EFL_GET_IOPL(fEfl);
7594 if (!(fEfl & X86_EFL_VM))
7595 {
7596 if (IEM_GET_CPL(pVCpu) <= uIopl)
7597 fEfl |= X86_EFL_IF;
7598 else if ( IEM_GET_CPL(pVCpu) == 3
7599 && (pVCpu->cpum.GstCtx.cr4 & X86_CR4_PVI)
7600 && !(fEfl & X86_EFL_VIP) )
7601 fEfl |= X86_EFL_VIF;
7602 else
7603 return iemRaiseGeneralProtectionFault0(pVCpu);
7604 }
7605 /* V8086 */
7606 else if (uIopl == 3)
7607 fEfl |= X86_EFL_IF;
7608 else if ( uIopl < 3
7609 && (pVCpu->cpum.GstCtx.cr4 & X86_CR4_VME)
7610 && !(fEfl & X86_EFL_VIP) )
7611 fEfl |= X86_EFL_VIF;
7612 else
7613 return iemRaiseGeneralProtectionFault0(pVCpu);
7614 }
7615 /* real mode */
7616 else
7617 fEfl |= X86_EFL_IF;
7618
7619 /*
7620 * Commit.
7621 *
7622 * Note! Setting the shadow interrupt flag must be done after RIP updating.
7623 */
7624 IEMMISC_SET_EFL(pVCpu, fEfl);
7625 VBOXSTRICTRC const rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7626 if (!(fEflOld & X86_EFL_IF) && (fEfl & X86_EFL_IF))
7627 {
7628 /** @todo only set it the shadow flag if it was clear before? */
7629 CPUMSetInInterruptShadowSti(&pVCpu->cpum.GstCtx);
7630 }
7631 pVCpu->iem.s.fTbCurInstrIsSti = true;
7632 Log2(("STI: %#x -> %#x\n", fEflOld, fEfl));
7633 return rcStrict;
7634}
7635
7636
7637/**
7638 * Implements 'HLT'.
7639 */
7640IEM_CIMPL_DEF_0(iemCImpl_hlt)
7641{
7642 if (IEM_GET_CPL(pVCpu) != 0)
7643 return iemRaiseGeneralProtectionFault0(pVCpu);
7644
7645 if (!IEM_IS_IN_GUEST(pVCpu))
7646 { /* probable */ }
7647 else if ( IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
7648 && IEM_VMX_IS_PROCCTLS_SET(pVCpu, VMX_PROC_CTLS_HLT_EXIT))
7649 {
7650 Log2(("hlt: Guest intercept -> VM-exit\n"));
7651 IEM_VMX_VMEXIT_INSTR_RET(pVCpu, VMX_EXIT_HLT, cbInstr);
7652 }
7653 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_HLT))
7654 {
7655 Log2(("hlt: Guest intercept -> #VMEXIT\n"));
7656 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
7657 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_HLT, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
7658 }
7659
7660 /** @todo finish: This ASSUMES that iemRegAddToRipAndFinishingClearingRF won't
7661 * be returning any status codes relating to non-guest events being raised, as
7662 * we'll mess up the guest HALT otherwise. */
7663 VBOXSTRICTRC rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7664 if (rcStrict == VINF_SUCCESS)
7665 rcStrict = VINF_EM_HALT;
7666 return rcStrict;
7667}
7668
7669
7670/**
7671 * Implements 'MONITOR'.
7672 */
7673IEM_CIMPL_DEF_1(iemCImpl_monitor, uint8_t, iEffSeg)
7674{
7675 /*
7676 * Permission checks.
7677 */
7678 if (IEM_GET_CPL(pVCpu) != 0)
7679 {
7680 Log2(("monitor: CPL != 0\n"));
7681 return iemRaiseUndefinedOpcode(pVCpu); /** @todo MSR[0xC0010015].MonMwaitUserEn if we care. */
7682 }
7683 if (!IEM_GET_GUEST_CPU_FEATURES(pVCpu)->fMonitorMWait)
7684 {
7685 Log2(("monitor: Not in CPUID\n"));
7686 return iemRaiseUndefinedOpcode(pVCpu);
7687 }
7688
7689 /*
7690 * Check VMX guest-intercept.
7691 * This should be considered a fault-like VM-exit.
7692 * See Intel spec. 25.1.1 "Relative Priority of Faults and VM Exits".
7693 */
7694 if ( !IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
7695 || !IEM_VMX_IS_PROCCTLS_SET(pVCpu, VMX_PROC_CTLS_MONITOR_EXIT))
7696 { /* probable */ }
7697 else
7698 {
7699 Log2(("monitor: Guest intercept -> #VMEXIT\n"));
7700 IEM_VMX_VMEXIT_INSTR_RET(pVCpu, VMX_EXIT_MONITOR, cbInstr);
7701 }
7702
7703 /*
7704 * Gather the operands and validate them.
7705 */
7706 RTGCPTR GCPtrMem = IEM_IS_64BIT_CODE(pVCpu) ? pVCpu->cpum.GstCtx.rax : pVCpu->cpum.GstCtx.eax;
7707 uint32_t uEcx = pVCpu->cpum.GstCtx.ecx;
7708 uint32_t uEdx = pVCpu->cpum.GstCtx.edx;
7709/** @todo Test whether EAX or ECX is processed first, i.e. do we get \#PF or
7710 * \#GP first. */
7711 if (uEcx != 0)
7712 {
7713 Log2(("monitor rax=%RX64, ecx=%RX32, edx=%RX32; ECX != 0 -> #GP(0)\n", GCPtrMem, uEcx, uEdx)); NOREF(uEdx);
7714 return iemRaiseGeneralProtectionFault0(pVCpu);
7715 }
7716
7717 VBOXSTRICTRC rcStrict = iemMemApplySegment(pVCpu, IEM_ACCESS_TYPE_READ | IEM_ACCESS_WHAT_DATA, iEffSeg, 1, &GCPtrMem);
7718 if (rcStrict != VINF_SUCCESS)
7719 return rcStrict;
7720
7721 RTGCPHYS GCPhysMem;
7722 /** @todo access size */
7723 rcStrict = iemMemPageTranslateAndCheckAccess(pVCpu, GCPtrMem, 1, IEM_ACCESS_TYPE_READ | IEM_ACCESS_WHAT_DATA, &GCPhysMem);
7724 if (rcStrict != VINF_SUCCESS)
7725 return rcStrict;
7726
7727 if (!IEM_IS_IN_GUEST(pVCpu))
7728 { /* probable */ }
7729#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7730 else if ( IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
7731 && IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_VIRT_APIC_ACCESS))
7732 {
7733 /*
7734 * MONITOR does not access the memory, just monitors the address. However,
7735 * if the address falls in the APIC-access page, the address monitored must
7736 * instead be the corresponding address in the virtual-APIC page.
7737 *
7738 * See Intel spec. 29.4.4 "Instruction-Specific Considerations".
7739 */
7740 rcStrict = iemVmxVirtApicAccessUnused(pVCpu, &GCPhysMem, 1, IEM_ACCESS_TYPE_READ | IEM_ACCESS_WHAT_DATA);
7741 if ( rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE
7742 && rcStrict != VINF_VMX_MODIFIES_BEHAVIOR)
7743 return rcStrict;
7744 }
7745#endif
7746 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_MONITOR))
7747 {
7748 Log2(("monitor: Guest intercept -> #VMEXIT\n"));
7749 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
7750 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_MONITOR, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
7751 }
7752
7753 /*
7754 * Call EM to prepare the monitor/wait.
7755 */
7756 rcStrict = EMMonitorWaitPrepare(pVCpu, pVCpu->cpum.GstCtx.rax, pVCpu->cpum.GstCtx.rcx, pVCpu->cpum.GstCtx.rdx, GCPhysMem);
7757 Assert(rcStrict == VINF_SUCCESS);
7758 if (rcStrict == VINF_SUCCESS)
7759 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7760 return rcStrict;
7761}
7762
7763
7764/**
7765 * Implements 'MWAIT'.
7766 */
7767IEM_CIMPL_DEF_0(iemCImpl_mwait)
7768{
7769 /*
7770 * Permission checks.
7771 */
7772 if (IEM_GET_CPL(pVCpu) != 0)
7773 {
7774 Log2(("mwait: CPL != 0\n"));
7775 /** @todo MSR[0xC0010015].MonMwaitUserEn if we care. (Remember to check
7776 * EFLAGS.VM then.) */
7777 return iemRaiseUndefinedOpcode(pVCpu);
7778 }
7779 if (!IEM_GET_GUEST_CPU_FEATURES(pVCpu)->fMonitorMWait)
7780 {
7781 Log2(("mwait: Not in CPUID\n"));
7782 return iemRaiseUndefinedOpcode(pVCpu);
7783 }
7784
7785 /* Check VMX nested-guest intercept. */
7786 if ( !IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
7787 || !IEM_VMX_IS_PROCCTLS_SET(pVCpu, VMX_PROC_CTLS_MWAIT_EXIT))
7788 { /* probable */ }
7789 else
7790 IEM_VMX_VMEXIT_MWAIT_RET(pVCpu, EMMonitorIsArmed(pVCpu), cbInstr);
7791
7792 /*
7793 * Gather the operands and validate them.
7794 */
7795 uint32_t const uEax = pVCpu->cpum.GstCtx.eax;
7796 uint32_t const uEcx = pVCpu->cpum.GstCtx.ecx;
7797 if (uEcx != 0)
7798 {
7799 /* Only supported extension is break on IRQ when IF=0. */
7800 if (uEcx > 1)
7801 {
7802 Log2(("mwait eax=%RX32, ecx=%RX32; ECX > 1 -> #GP(0)\n", uEax, uEcx));
7803 return iemRaiseGeneralProtectionFault0(pVCpu);
7804 }
7805 uint32_t fMWaitFeatures = 0;
7806 uint32_t uIgnore = 0;
7807 CPUMGetGuestCpuId(pVCpu, 5, 0, -1 /*f64BitMode*/, &uIgnore, &uIgnore, &fMWaitFeatures, &uIgnore);
7808 if ( (fMWaitFeatures & (X86_CPUID_MWAIT_ECX_EXT | X86_CPUID_MWAIT_ECX_BREAKIRQIF0))
7809 != (X86_CPUID_MWAIT_ECX_EXT | X86_CPUID_MWAIT_ECX_BREAKIRQIF0))
7810 {
7811 Log2(("mwait eax=%RX32, ecx=%RX32; break-on-IRQ-IF=0 extension not enabled -> #GP(0)\n", uEax, uEcx));
7812 return iemRaiseGeneralProtectionFault0(pVCpu);
7813 }
7814
7815#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7816 /*
7817 * If the interrupt-window exiting control is set or a virtual-interrupt is pending
7818 * for delivery; and interrupts are disabled the processor does not enter its
7819 * mwait state but rather passes control to the next instruction.
7820 *
7821 * See Intel spec. 25.3 "Changes to Instruction Behavior In VMX Non-root Operation".
7822 */
7823 if ( !IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
7824 || pVCpu->cpum.GstCtx.eflags.Bits.u1IF)
7825 { /* probable */ }
7826 else if ( IEM_VMX_IS_PROCCTLS_SET(pVCpu, VMX_PROC_CTLS_INT_WINDOW_EXIT)
7827 || VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST))
7828 /** @todo finish: check up this out after we move int window stuff out of the
7829 * run loop and into the instruction finishing logic here. */
7830 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7831#endif
7832 }
7833
7834 /*
7835 * Check SVM nested-guest mwait intercepts.
7836 */
7837 if (!IEM_IS_IN_GUEST(pVCpu))
7838 { /* probable */ }
7839 else if ( IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_MWAIT_ARMED)
7840 && EMMonitorIsArmed(pVCpu))
7841 {
7842 Log2(("mwait: Guest intercept (monitor hardware armed) -> #VMEXIT\n"));
7843 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
7844 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_MWAIT_ARMED, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
7845 }
7846 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_MWAIT))
7847 {
7848 Log2(("mwait: Guest intercept -> #VMEXIT\n"));
7849 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
7850 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_MWAIT, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
7851 }
7852
7853 /*
7854 * Call EM to prepare the monitor/wait.
7855 *
7856 * This will return VINF_EM_HALT. If there the trap flag is set, we may
7857 * override it when executing iemRegAddToRipAndFinishingClearingRF ASSUMING
7858 * that will only return guest related events.
7859 */
7860 VBOXSTRICTRC rcStrict = EMMonitorWaitPerform(pVCpu, uEax, uEcx);
7861
7862 /** @todo finish: This needs more thinking as we should suppress internal
7863 * debugger events here, or we'll bugger up the guest state even more than we
7864 * alread do around VINF_EM_HALT. */
7865 VBOXSTRICTRC rcStrict2 = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7866 if (rcStrict2 != VINF_SUCCESS)
7867 {
7868 Log2(("mwait: %Rrc (perform) -> %Rrc (finish)!\n", VBOXSTRICTRC_VAL(rcStrict), VBOXSTRICTRC_VAL(rcStrict2) ));
7869 rcStrict = rcStrict2;
7870 }
7871
7872 return rcStrict;
7873}
7874
7875
7876/**
7877 * Implements 'SWAPGS'.
7878 */
7879IEM_CIMPL_DEF_0(iemCImpl_swapgs)
7880{
7881 Assert(IEM_IS_64BIT_CODE(pVCpu)); /* Caller checks this. */
7882
7883 /*
7884 * Permission checks.
7885 */
7886 if (IEM_GET_CPL(pVCpu) != 0)
7887 {
7888 Log2(("swapgs: CPL != 0\n"));
7889 return iemRaiseUndefinedOpcode(pVCpu);
7890 }
7891
7892 /*
7893 * Do the job.
7894 */
7895 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_KERNEL_GS_BASE | CPUMCTX_EXTRN_GS);
7896 uint64_t uOtherGsBase = pVCpu->cpum.GstCtx.msrKERNELGSBASE;
7897 pVCpu->cpum.GstCtx.msrKERNELGSBASE = pVCpu->cpum.GstCtx.gs.u64Base;
7898 pVCpu->cpum.GstCtx.gs.u64Base = uOtherGsBase;
7899
7900 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
7901}
7902
7903
7904#ifndef VBOX_WITHOUT_CPUID_HOST_CALL
7905/**
7906 * Handles a CPUID call.
7907 */
7908static VBOXSTRICTRC iemCpuIdVBoxCall(PVMCPUCC pVCpu, uint32_t iFunction,
7909 uint32_t *pEax, uint32_t *pEbx, uint32_t *pEcx, uint32_t *pEdx)
7910{
7911 switch (iFunction)
7912 {
7913 case VBOX_CPUID_FN_ID:
7914 LogFlow(("iemCpuIdVBoxCall: VBOX_CPUID_FN_ID\n"));
7915 *pEax = VBOX_CPUID_RESP_ID_EAX;
7916 *pEbx = VBOX_CPUID_RESP_ID_EBX;
7917 *pEcx = VBOX_CPUID_RESP_ID_ECX;
7918 *pEdx = VBOX_CPUID_RESP_ID_EDX;
7919 break;
7920
7921 case VBOX_CPUID_FN_LOG:
7922 {
7923 CPUM_IMPORT_EXTRN_RET(pVCpu, CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RBX | CPUMCTX_EXTRN_RSI
7924 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
7925
7926 /* Validate input. */
7927 uint32_t cchToLog = *pEdx;
7928 if (cchToLog <= _2M)
7929 {
7930 uint32_t const uLogPicker = *pEbx;
7931 if (uLogPicker <= 1)
7932 {
7933 /* Resolve the logger. */
7934 PRTLOGGER const pLogger = !uLogPicker
7935 ? RTLogDefaultInstanceEx(UINT32_MAX) : RTLogRelGetDefaultInstanceEx(UINT32_MAX);
7936 if (pLogger)
7937 {
7938 /* Copy over the data: */
7939 RTGCPTR GCPtrSrc = pVCpu->cpum.GstCtx.rsi;
7940 while (cchToLog > 0)
7941 {
7942 uint32_t cbToMap = GUEST_PAGE_SIZE - (GCPtrSrc & GUEST_PAGE_OFFSET_MASK);
7943 if (cbToMap > cchToLog)
7944 cbToMap = cchToLog;
7945 /** @todo Extend iemMemMap to allowing page size accessing and avoid 7
7946 * unnecessary calls & iterations per pages. */
7947 if (cbToMap > 512)
7948 cbToMap = 512;
7949 uint8_t bUnmapInfo;
7950 void *pvSrc = NULL;
7951 VBOXSTRICTRC rcStrict = iemMemMap(pVCpu, &pvSrc, &bUnmapInfo, cbToMap,
7952 UINT8_MAX, GCPtrSrc, IEM_ACCESS_DATA_R, 0);
7953 if (rcStrict == VINF_SUCCESS)
7954 {
7955 RTLogBulkNestedWrite(pLogger, (const char *)pvSrc, cbToMap, "Gst:");
7956 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
7957 AssertRCSuccessReturn(VBOXSTRICTRC_VAL(rcStrict), rcStrict);
7958 }
7959 else
7960 {
7961 Log(("iemCpuIdVBoxCall: %Rrc at %RGp LB %#x\n", VBOXSTRICTRC_VAL(rcStrict), GCPtrSrc, cbToMap));
7962 return rcStrict;
7963 }
7964
7965 /* Advance. */
7966 pVCpu->cpum.GstCtx.rsi = GCPtrSrc += cbToMap;
7967 *pEdx = cchToLog -= cbToMap;
7968 }
7969 *pEax = VINF_SUCCESS;
7970 }
7971 else
7972 *pEax = (uint32_t)VERR_NOT_FOUND;
7973 }
7974 else
7975 *pEax = (uint32_t)VERR_NOT_FOUND;
7976 }
7977 else
7978 *pEax = (uint32_t)VERR_TOO_MUCH_DATA;
7979 *pEdx = VBOX_CPUID_RESP_GEN_EDX;
7980 *pEcx = VBOX_CPUID_RESP_GEN_ECX;
7981 *pEbx = VBOX_CPUID_RESP_GEN_EBX;
7982 break;
7983 }
7984
7985 default:
7986 LogFlow(("iemCpuIdVBoxCall: Invalid function %#x (%#x, %#x)\n", iFunction, *pEbx, *pEdx));
7987 *pEax = (uint32_t)VERR_INVALID_FUNCTION;
7988 *pEbx = (uint32_t)VERR_INVALID_FUNCTION;
7989 *pEcx = (uint32_t)VERR_INVALID_FUNCTION;
7990 *pEdx = (uint32_t)VERR_INVALID_FUNCTION;
7991 break;
7992 }
7993 return VINF_SUCCESS;
7994}
7995#endif /* VBOX_WITHOUT_CPUID_HOST_CALL */
7996
7997/**
7998 * Implements 'CPUID'.
7999 */
8000IEM_CIMPL_DEF_0(iemCImpl_cpuid)
8001{
8002 if (!IEM_IS_IN_GUEST(pVCpu))
8003 { /* probable */ }
8004 else if (IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
8005 {
8006 Log2(("cpuid: Guest intercept -> VM-exit\n"));
8007 IEM_VMX_VMEXIT_INSTR_RET(pVCpu, VMX_EXIT_CPUID, cbInstr);
8008 }
8009 else if (IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_CPUID))
8010 {
8011 Log2(("cpuid: Guest intercept -> #VMEXIT\n"));
8012 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
8013 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_CPUID, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
8014 }
8015
8016
8017 uint32_t const uEax = pVCpu->cpum.GstCtx.eax;
8018 uint32_t const uEcx = pVCpu->cpum.GstCtx.ecx;
8019
8020#ifndef VBOX_WITHOUT_CPUID_HOST_CALL
8021 /*
8022 * CPUID host call backdoor.
8023 */
8024 if ( uEax == VBOX_CPUID_REQ_EAX_FIXED
8025 && (uEcx & VBOX_CPUID_REQ_ECX_FIXED_MASK) == VBOX_CPUID_REQ_ECX_FIXED
8026 && pVCpu->CTX_SUFF(pVM)->iem.s.fCpuIdHostCall)
8027 {
8028 VBOXSTRICTRC rcStrict = iemCpuIdVBoxCall(pVCpu, uEcx & VBOX_CPUID_REQ_ECX_FN_MASK,
8029 &pVCpu->cpum.GstCtx.eax, &pVCpu->cpum.GstCtx.ebx,
8030 &pVCpu->cpum.GstCtx.ecx, &pVCpu->cpum.GstCtx.edx);
8031 if (rcStrict != VINF_SUCCESS)
8032 return rcStrict;
8033 }
8034 /*
8035 * Regular CPUID.
8036 */
8037 else
8038#endif
8039 CPUMGetGuestCpuId(pVCpu, uEax, uEcx, pVCpu->cpum.GstCtx.cs.Attr.n.u1Long,
8040 &pVCpu->cpum.GstCtx.eax, &pVCpu->cpum.GstCtx.ebx, &pVCpu->cpum.GstCtx.ecx, &pVCpu->cpum.GstCtx.edx);
8041
8042 pVCpu->cpum.GstCtx.rax &= UINT32_C(0xffffffff);
8043 pVCpu->cpum.GstCtx.rbx &= UINT32_C(0xffffffff);
8044 pVCpu->cpum.GstCtx.rcx &= UINT32_C(0xffffffff);
8045 pVCpu->cpum.GstCtx.rdx &= UINT32_C(0xffffffff);
8046 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RBX);
8047
8048 pVCpu->iem.s.cPotentialExits++;
8049 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8050}
8051
8052
8053/**
8054 * Implements 'AAD'.
8055 *
8056 * @param bImm The immediate operand.
8057 */
8058IEM_CIMPL_DEF_1(iemCImpl_aad, uint8_t, bImm)
8059{
8060 uint16_t const ax = pVCpu->cpum.GstCtx.ax;
8061 uint8_t const al = (uint8_t)ax + (uint8_t)(ax >> 8) * bImm;
8062 pVCpu->cpum.GstCtx.ax = al;
8063 iemHlpUpdateArithEFlagsU8(pVCpu, al,
8064 X86_EFL_SF | X86_EFL_ZF | X86_EFL_PF,
8065 X86_EFL_OF | X86_EFL_AF | X86_EFL_CF);
8066
8067 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8068}
8069
8070
8071/**
8072 * Implements 'AAM'.
8073 *
8074 * @param bImm The immediate operand. Cannot be 0.
8075 */
8076IEM_CIMPL_DEF_1(iemCImpl_aam, uint8_t, bImm)
8077{
8078 Assert(bImm != 0); /* #DE on 0 is handled in the decoder. */
8079
8080 uint16_t const ax = pVCpu->cpum.GstCtx.ax;
8081 uint8_t const al = (uint8_t)ax % bImm;
8082 uint8_t const ah = (uint8_t)ax / bImm;
8083 pVCpu->cpum.GstCtx.ax = (ah << 8) + al;
8084 iemHlpUpdateArithEFlagsU8(pVCpu, al,
8085 X86_EFL_SF | X86_EFL_ZF | X86_EFL_PF,
8086 X86_EFL_OF | X86_EFL_AF | X86_EFL_CF);
8087
8088 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8089}
8090
8091
8092/**
8093 * Implements 'DAA'.
8094 */
8095IEM_CIMPL_DEF_0(iemCImpl_daa)
8096{
8097 uint8_t const al = pVCpu->cpum.GstCtx.al;
8098 bool const fCarry = pVCpu->cpum.GstCtx.eflags.Bits.u1CF;
8099
8100 if ( pVCpu->cpum.GstCtx.eflags.Bits.u1AF
8101 || (al & 0xf) >= 10)
8102 {
8103 pVCpu->cpum.GstCtx.al = al + 6;
8104 pVCpu->cpum.GstCtx.eflags.Bits.u1AF = 1;
8105 }
8106 else
8107 pVCpu->cpum.GstCtx.eflags.Bits.u1AF = 0;
8108
8109 if (al >= 0x9a || fCarry)
8110 {
8111 pVCpu->cpum.GstCtx.al += 0x60;
8112 pVCpu->cpum.GstCtx.eflags.Bits.u1CF = 1;
8113 }
8114 else
8115 pVCpu->cpum.GstCtx.eflags.Bits.u1CF = 0;
8116
8117 iemHlpUpdateArithEFlagsU8(pVCpu, pVCpu->cpum.GstCtx.al, X86_EFL_SF | X86_EFL_ZF | X86_EFL_PF, X86_EFL_OF);
8118 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8119}
8120
8121
8122/**
8123 * Implements 'DAS'.
8124 */
8125IEM_CIMPL_DEF_0(iemCImpl_das)
8126{
8127 uint8_t const uInputAL = pVCpu->cpum.GstCtx.al;
8128 bool const fCarry = pVCpu->cpum.GstCtx.eflags.Bits.u1CF;
8129
8130 if ( pVCpu->cpum.GstCtx.eflags.Bits.u1AF
8131 || (uInputAL & 0xf) >= 10)
8132 {
8133 pVCpu->cpum.GstCtx.eflags.Bits.u1AF = 1;
8134 if (uInputAL < 6)
8135 pVCpu->cpum.GstCtx.eflags.Bits.u1CF = 1;
8136 pVCpu->cpum.GstCtx.al = uInputAL - 6;
8137 }
8138 else
8139 {
8140 pVCpu->cpum.GstCtx.eflags.Bits.u1AF = 0;
8141 pVCpu->cpum.GstCtx.eflags.Bits.u1CF = 0;
8142 }
8143
8144 if (uInputAL >= 0x9a || fCarry)
8145 {
8146 pVCpu->cpum.GstCtx.al -= 0x60;
8147 pVCpu->cpum.GstCtx.eflags.Bits.u1CF = 1;
8148 }
8149
8150 iemHlpUpdateArithEFlagsU8(pVCpu, pVCpu->cpum.GstCtx.al, X86_EFL_SF | X86_EFL_ZF | X86_EFL_PF, X86_EFL_OF);
8151 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8152}
8153
8154
8155/**
8156 * Implements 'AAA'.
8157 */
8158IEM_CIMPL_DEF_0(iemCImpl_aaa)
8159{
8160 if (IEM_IS_GUEST_CPU_AMD(pVCpu))
8161 {
8162 if ( pVCpu->cpum.GstCtx.eflags.Bits.u1AF
8163 || (pVCpu->cpum.GstCtx.ax & 0xf) >= 10)
8164 {
8165 pVCpu->cpum.GstCtx.eflags.uBoth = iemAImpl_add_u16(pVCpu->cpum.GstCtx.eflags.uBoth, &pVCpu->cpum.GstCtx.ax, 0x106);
8166 pVCpu->cpum.GstCtx.eflags.Bits.u1AF = 1;
8167 pVCpu->cpum.GstCtx.eflags.Bits.u1CF = 1;
8168 }
8169 else
8170 {
8171 iemHlpUpdateArithEFlagsU16(pVCpu, pVCpu->cpum.GstCtx.ax, X86_EFL_SF | X86_EFL_ZF | X86_EFL_PF, X86_EFL_OF);
8172 pVCpu->cpum.GstCtx.eflags.Bits.u1AF = 0;
8173 pVCpu->cpum.GstCtx.eflags.Bits.u1CF = 0;
8174 }
8175 pVCpu->cpum.GstCtx.ax &= UINT16_C(0xff0f);
8176 }
8177 else
8178 {
8179 if ( pVCpu->cpum.GstCtx.eflags.Bits.u1AF
8180 || (pVCpu->cpum.GstCtx.ax & 0xf) >= 10)
8181 {
8182 pVCpu->cpum.GstCtx.ax += UINT16_C(0x106);
8183 pVCpu->cpum.GstCtx.eflags.Bits.u1AF = 1;
8184 pVCpu->cpum.GstCtx.eflags.Bits.u1CF = 1;
8185 }
8186 else
8187 {
8188 pVCpu->cpum.GstCtx.eflags.Bits.u1AF = 0;
8189 pVCpu->cpum.GstCtx.eflags.Bits.u1CF = 0;
8190 }
8191 pVCpu->cpum.GstCtx.ax &= UINT16_C(0xff0f);
8192 iemHlpUpdateArithEFlagsU8(pVCpu, pVCpu->cpum.GstCtx.al, X86_EFL_SF | X86_EFL_ZF | X86_EFL_PF, X86_EFL_OF);
8193 }
8194
8195 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8196}
8197
8198
8199/**
8200 * Implements 'AAS'.
8201 */
8202IEM_CIMPL_DEF_0(iemCImpl_aas)
8203{
8204 if (IEM_IS_GUEST_CPU_AMD(pVCpu))
8205 {
8206 if ( pVCpu->cpum.GstCtx.eflags.Bits.u1AF
8207 || (pVCpu->cpum.GstCtx.ax & 0xf) >= 10)
8208 {
8209 pVCpu->cpum.GstCtx.eflags.uBoth = iemAImpl_sub_u16(pVCpu->cpum.GstCtx.eflags.uBoth, &pVCpu->cpum.GstCtx.ax, 0x106);
8210 pVCpu->cpum.GstCtx.eflags.Bits.u1AF = 1;
8211 pVCpu->cpum.GstCtx.eflags.Bits.u1CF = 1;
8212 }
8213 else
8214 {
8215 iemHlpUpdateArithEFlagsU16(pVCpu, pVCpu->cpum.GstCtx.ax, X86_EFL_SF | X86_EFL_ZF | X86_EFL_PF, X86_EFL_OF);
8216 pVCpu->cpum.GstCtx.eflags.Bits.u1AF = 0;
8217 pVCpu->cpum.GstCtx.eflags.Bits.u1CF = 0;
8218 }
8219 pVCpu->cpum.GstCtx.ax &= UINT16_C(0xff0f);
8220 }
8221 else
8222 {
8223 if ( pVCpu->cpum.GstCtx.eflags.Bits.u1AF
8224 || (pVCpu->cpum.GstCtx.ax & 0xf) >= 10)
8225 {
8226 pVCpu->cpum.GstCtx.ax -= UINT16_C(0x106);
8227 pVCpu->cpum.GstCtx.eflags.Bits.u1AF = 1;
8228 pVCpu->cpum.GstCtx.eflags.Bits.u1CF = 1;
8229 }
8230 else
8231 {
8232 pVCpu->cpum.GstCtx.eflags.Bits.u1AF = 0;
8233 pVCpu->cpum.GstCtx.eflags.Bits.u1CF = 0;
8234 }
8235 pVCpu->cpum.GstCtx.ax &= UINT16_C(0xff0f);
8236 iemHlpUpdateArithEFlagsU8(pVCpu, pVCpu->cpum.GstCtx.al, X86_EFL_SF | X86_EFL_ZF | X86_EFL_PF, X86_EFL_OF);
8237 }
8238
8239 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8240}
8241
8242
8243/**
8244 * Implements the 16-bit version of 'BOUND'.
8245 *
8246 * @note We have separate 16-bit and 32-bit variants of this function due to
8247 * the decoder using unsigned parameters, whereas we want signed one to
8248 * do the job. This is significant for a recompiler.
8249 */
8250IEM_CIMPL_DEF_3(iemCImpl_bound_16, int16_t, idxArray, int16_t, idxLowerBound, int16_t, idxUpperBound)
8251{
8252 /*
8253 * Check if the index is inside the bounds, otherwise raise #BR.
8254 */
8255 if ( idxArray >= idxLowerBound
8256 && idxArray <= idxUpperBound)
8257 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8258 return iemRaiseBoundRangeExceeded(pVCpu);
8259}
8260
8261
8262/**
8263 * Implements the 32-bit version of 'BOUND'.
8264 */
8265IEM_CIMPL_DEF_3(iemCImpl_bound_32, int32_t, idxArray, int32_t, idxLowerBound, int32_t, idxUpperBound)
8266{
8267 /*
8268 * Check if the index is inside the bounds, otherwise raise #BR.
8269 */
8270 if ( idxArray >= idxLowerBound
8271 && idxArray <= idxUpperBound)
8272 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8273 return iemRaiseBoundRangeExceeded(pVCpu);
8274}
8275
8276
8277
8278/*
8279 * Instantiate the various string operation combinations.
8280 */
8281#define OP_SIZE 8
8282#define ADDR_SIZE 16
8283#include "IEMAllCImplStrInstr.cpp.h"
8284#define OP_SIZE 8
8285#define ADDR_SIZE 32
8286#include "IEMAllCImplStrInstr.cpp.h"
8287#define OP_SIZE 8
8288#define ADDR_SIZE 64
8289#include "IEMAllCImplStrInstr.cpp.h"
8290
8291#define OP_SIZE 16
8292#define ADDR_SIZE 16
8293#include "IEMAllCImplStrInstr.cpp.h"
8294#define OP_SIZE 16
8295#define ADDR_SIZE 32
8296#include "IEMAllCImplStrInstr.cpp.h"
8297#define OP_SIZE 16
8298#define ADDR_SIZE 64
8299#include "IEMAllCImplStrInstr.cpp.h"
8300
8301#define OP_SIZE 32
8302#define ADDR_SIZE 16
8303#include "IEMAllCImplStrInstr.cpp.h"
8304#define OP_SIZE 32
8305#define ADDR_SIZE 32
8306#include "IEMAllCImplStrInstr.cpp.h"
8307#define OP_SIZE 32
8308#define ADDR_SIZE 64
8309#include "IEMAllCImplStrInstr.cpp.h"
8310
8311#define OP_SIZE 64
8312#define ADDR_SIZE 32
8313#include "IEMAllCImplStrInstr.cpp.h"
8314#define OP_SIZE 64
8315#define ADDR_SIZE 64
8316#include "IEMAllCImplStrInstr.cpp.h"
8317
8318
8319/**
8320 * Implements 'XGETBV'.
8321 */
8322IEM_CIMPL_DEF_0(iemCImpl_xgetbv)
8323{
8324 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
8325 if (pVCpu->cpum.GstCtx.cr4 & X86_CR4_OSXSAVE)
8326 {
8327 uint32_t uEcx = pVCpu->cpum.GstCtx.ecx;
8328 switch (uEcx)
8329 {
8330 case 0:
8331 break;
8332
8333 case 1: /** @todo Implement XCR1 support. */
8334 default:
8335 Log(("xgetbv ecx=%RX32 -> #GP(0)\n", uEcx));
8336 return iemRaiseGeneralProtectionFault0(pVCpu);
8337
8338 }
8339 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_XCRx);
8340 pVCpu->cpum.GstCtx.rax = RT_LO_U32(pVCpu->cpum.GstCtx.aXcr[uEcx]);
8341 pVCpu->cpum.GstCtx.rdx = RT_HI_U32(pVCpu->cpum.GstCtx.aXcr[uEcx]);
8342
8343 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8344 }
8345 Log(("xgetbv CR4.OSXSAVE=0 -> UD\n"));
8346 return iemRaiseUndefinedOpcode(pVCpu);
8347}
8348
8349
8350/**
8351 * Implements 'XSETBV'.
8352 */
8353IEM_CIMPL_DEF_0(iemCImpl_xsetbv)
8354{
8355 if (pVCpu->cpum.GstCtx.cr4 & X86_CR4_OSXSAVE)
8356 {
8357 /** @todo explain why this happens before the CPL check. */
8358 if (!IEM_SVM_IS_CTRL_INTERCEPT_SET(pVCpu, SVM_CTRL_INTERCEPT_XSETBV))
8359 { /* probable */ }
8360 else
8361 {
8362 Log2(("xsetbv: Guest intercept -> #VMEXIT\n"));
8363 IEM_SVM_UPDATE_NRIP(pVCpu, cbInstr);
8364 IEM_SVM_VMEXIT_RET(pVCpu, SVM_EXIT_XSETBV, 0 /* uExitInfo1 */, 0 /* uExitInfo2 */);
8365 }
8366
8367 if (IEM_GET_CPL(pVCpu) == 0)
8368 {
8369 IEM_CTX_IMPORT_RET(pVCpu, CPUMCTX_EXTRN_XCRx);
8370
8371 if (!IEM_VMX_IS_NON_ROOT_MODE(pVCpu))
8372 { /* probable */ }
8373 else
8374 IEM_VMX_VMEXIT_INSTR_RET(pVCpu, VMX_EXIT_XSETBV, cbInstr);
8375
8376 uint32_t uEcx = pVCpu->cpum.GstCtx.ecx;
8377 uint64_t uNewValue = RT_MAKE_U64(pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.edx);
8378 switch (uEcx)
8379 {
8380 case 0:
8381 {
8382 int rc = CPUMSetGuestXcr0(pVCpu, uNewValue);
8383 if (rc == VINF_SUCCESS)
8384 break;
8385 Assert(rc == VERR_CPUM_RAISE_GP_0);
8386 Log(("xsetbv ecx=%RX32 (newvalue=%RX64) -> #GP(0)\n", uEcx, uNewValue));
8387 return iemRaiseGeneralProtectionFault0(pVCpu);
8388 }
8389
8390 case 1: /** @todo Implement XCR1 support. */
8391 default:
8392 Log(("xsetbv ecx=%RX32 (newvalue=%RX64) -> #GP(0)\n", uEcx, uNewValue));
8393 return iemRaiseGeneralProtectionFault0(pVCpu);
8394
8395 }
8396
8397 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8398 }
8399
8400 Log(("xsetbv cpl=%u -> GP(0)\n", IEM_GET_CPL(pVCpu)));
8401 return iemRaiseGeneralProtectionFault0(pVCpu);
8402 }
8403 Log(("xsetbv CR4.OSXSAVE=0 -> UD\n"));
8404 return iemRaiseUndefinedOpcode(pVCpu);
8405}
8406
8407#ifndef RT_ARCH_ARM64
8408# ifdef IN_RING3
8409
8410/** Argument package for iemCImpl_cmpxchg16b_fallback_rendezvous_callback. */
8411struct IEMCIMPLCX16ARGS
8412{
8413 PRTUINT128U pu128Dst;
8414 PRTUINT128U pu128RaxRdx;
8415 PRTUINT128U pu128RbxRcx;
8416 uint32_t *pEFlags;
8417# ifdef VBOX_STRICT
8418 uint32_t cCalls;
8419# endif
8420};
8421
8422/**
8423 * @callback_method_impl{FNVMMEMTRENDEZVOUS,
8424 * Worker for iemCImpl_cmpxchg16b_fallback_rendezvous}
8425 */
8426static DECLCALLBACK(VBOXSTRICTRC) iemCImpl_cmpxchg16b_fallback_rendezvous_callback(PVM pVM, PVMCPUCC pVCpu, void *pvUser)
8427{
8428 RT_NOREF(pVM, pVCpu);
8429 struct IEMCIMPLCX16ARGS *pArgs = (struct IEMCIMPLCX16ARGS *)pvUser;
8430# ifdef VBOX_STRICT
8431 Assert(pArgs->cCalls == 0);
8432 pArgs->cCalls++;
8433# endif
8434
8435 iemAImpl_cmpxchg16b_fallback(pArgs->pu128Dst, pArgs->pu128RaxRdx, pArgs->pu128RbxRcx, pArgs->pEFlags);
8436 return VINF_SUCCESS;
8437}
8438
8439# endif /* IN_RING3 */
8440
8441/**
8442 * Implements 'CMPXCHG16B' fallback using rendezvous.
8443 */
8444IEM_CIMPL_DEF_5(iemCImpl_cmpxchg16b_fallback_rendezvous, PRTUINT128U, pu128Dst, PRTUINT128U, pu128RaxRdx,
8445 PRTUINT128U, pu128RbxRcx, uint32_t *, pEFlags, uint8_t, bUnmapInfo)
8446{
8447# ifdef IN_RING3
8448 struct IEMCIMPLCX16ARGS Args;
8449 Args.pu128Dst = pu128Dst;
8450 Args.pu128RaxRdx = pu128RaxRdx;
8451 Args.pu128RbxRcx = pu128RbxRcx;
8452 Args.pEFlags = pEFlags;
8453# ifdef VBOX_STRICT
8454 Args.cCalls = 0;
8455# endif
8456 VBOXSTRICTRC rcStrict = VMMR3EmtRendezvous(pVCpu->CTX_SUFF(pVM), VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE,
8457 iemCImpl_cmpxchg16b_fallback_rendezvous_callback, &Args);
8458 Assert(Args.cCalls == 1);
8459 if (rcStrict == VINF_SUCCESS)
8460 {
8461 /* Duplicated tail code. */
8462 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
8463 if (rcStrict == VINF_SUCCESS)
8464 {
8465 pVCpu->cpum.GstCtx.eflags.u = *pEFlags; /* IEM_MC_COMMIT_EFLAGS */
8466 if (!(*pEFlags & X86_EFL_ZF))
8467 {
8468 pVCpu->cpum.GstCtx.rax = pu128RaxRdx->s.Lo;
8469 pVCpu->cpum.GstCtx.rdx = pu128RaxRdx->s.Hi;
8470 }
8471 rcStrict = iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8472 }
8473 }
8474 return rcStrict;
8475# else
8476 RT_NOREF(pVCpu, cbInstr, pu128Dst, pu128RaxRdx, pu128RbxRcx, pEFlags, bUnmapInfo);
8477 return VERR_IEM_ASPECT_NOT_IMPLEMENTED; /* This should get us to ring-3 for now. Should perhaps be replaced later. */
8478# endif
8479}
8480
8481#endif /* RT_ARCH_ARM64 */
8482
8483/**
8484 * Implements 'CLFLUSH' and 'CLFLUSHOPT'.
8485 *
8486 * This is implemented in C because it triggers a load like behaviour without
8487 * actually reading anything. Since that's not so common, it's implemented
8488 * here.
8489 *
8490 * @param iEffSeg The effective segment.
8491 * @param GCPtrEff The address of the image.
8492 */
8493IEM_CIMPL_DEF_2(iemCImpl_clflush_clflushopt, uint8_t, iEffSeg, RTGCPTR, GCPtrEff)
8494{
8495 /*
8496 * Pretend to do a load w/o reading (see also iemCImpl_monitor and iemMemMap).
8497 */
8498 VBOXSTRICTRC rcStrict = iemMemApplySegment(pVCpu, IEM_ACCESS_TYPE_READ | IEM_ACCESS_WHAT_DATA, iEffSeg, 1, &GCPtrEff);
8499 if (rcStrict == VINF_SUCCESS)
8500 {
8501 RTGCPHYS GCPhysMem;
8502 /** @todo access size. */
8503 rcStrict = iemMemPageTranslateAndCheckAccess(pVCpu, GCPtrEff, 1, IEM_ACCESS_TYPE_READ | IEM_ACCESS_WHAT_DATA, &GCPhysMem);
8504 if (rcStrict == VINF_SUCCESS)
8505 {
8506#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8507 if ( !IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
8508 || !IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_VIRT_APIC_ACCESS))
8509 { /* probable */ }
8510 else
8511 {
8512 /*
8513 * CLFLUSH/CLFLUSHOPT does not access the memory, but flushes the cache-line
8514 * that contains the address. However, if the address falls in the APIC-access
8515 * page, the address flushed must instead be the corresponding address in the
8516 * virtual-APIC page.
8517 *
8518 * See Intel spec. 29.4.4 "Instruction-Specific Considerations".
8519 */
8520 rcStrict = iemVmxVirtApicAccessUnused(pVCpu, &GCPhysMem, 1, IEM_ACCESS_TYPE_READ | IEM_ACCESS_WHAT_DATA);
8521 if ( rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE
8522 && rcStrict != VINF_VMX_MODIFIES_BEHAVIOR)
8523 return rcStrict;
8524 }
8525#endif
8526 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8527 }
8528 }
8529
8530 return rcStrict;
8531}
8532
8533
8534/**
8535 * Implements 'FINIT' and 'FNINIT'.
8536 *
8537 * @param fCheckXcpts Whether to check for umasked pending exceptions or
8538 * not.
8539 */
8540IEM_CIMPL_DEF_1(iemCImpl_finit, bool, fCheckXcpts)
8541{
8542 /*
8543 * Exceptions.
8544 */
8545 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
8546 if (pVCpu->cpum.GstCtx.cr0 & (X86_CR0_EM | X86_CR0_TS))
8547 return iemRaiseDeviceNotAvailable(pVCpu);
8548
8549 iemFpuActualizeStateForChange(pVCpu);
8550 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_X87);
8551
8552 /* FINIT: Raise #MF on pending exception(s): */
8553 if (fCheckXcpts && (pVCpu->cpum.GstCtx.XState.x87.FSW & X86_FSW_ES))
8554 return iemRaiseMathFault(pVCpu);
8555
8556 /*
8557 * Reset the state.
8558 */
8559 PX86XSAVEAREA pXState = &pVCpu->cpum.GstCtx.XState;
8560
8561 /* Rotate the stack to account for changed TOS. */
8562 iemFpuRotateStackSetTop(&pXState->x87, 0);
8563
8564 pXState->x87.FCW = 0x37f;
8565 pXState->x87.FSW = 0;
8566 pXState->x87.FTW = 0x00; /* 0 - empty. */
8567 /** @todo Intel says the instruction and data pointers are not cleared on
8568 * 387, presume that 8087 and 287 doesn't do so either. */
8569 /** @todo test this stuff. */
8570 if (IEM_GET_TARGET_CPU(pVCpu) > IEMTARGETCPU_386)
8571 {
8572 pXState->x87.FPUDP = 0;
8573 pXState->x87.DS = 0; //??
8574 pXState->x87.Rsrvd2 = 0;
8575 pXState->x87.FPUIP = 0;
8576 pXState->x87.CS = 0; //??
8577 pXState->x87.Rsrvd1 = 0;
8578 }
8579 pXState->x87.FOP = 0;
8580
8581 iemHlpUsedFpu(pVCpu);
8582 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8583}
8584
8585
8586/**
8587 * Implements 'FXSAVE'.
8588 *
8589 * @param iEffSeg The effective segment.
8590 * @param GCPtrEff The address of the image.
8591 * @param enmEffOpSize The operand size (only REX.W really matters).
8592 */
8593IEM_CIMPL_DEF_3(iemCImpl_fxsave, uint8_t, iEffSeg, RTGCPTR, GCPtrEff, IEMMODE, enmEffOpSize)
8594{
8595 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_X87 | CPUMCTX_EXTRN_SSE_AVX);
8596
8597 /** @todo check out bugref{1529} and AMD behaviour */
8598
8599 /*
8600 * Raise exceptions.
8601 */
8602 if (pVCpu->cpum.GstCtx.cr0 & (X86_CR0_TS | X86_CR0_EM))
8603 return iemRaiseDeviceNotAvailable(pVCpu);
8604
8605 /*
8606 * Access the memory.
8607 */
8608 uint8_t bUnmapInfo;
8609 void *pvMem512;
8610 VBOXSTRICTRC rcStrict = iemMemMap(pVCpu, &pvMem512, &bUnmapInfo, 512,
8611 iEffSeg, GCPtrEff, IEM_ACCESS_DATA_W | IEM_ACCESS_PARTIAL_WRITE,
8612 15 | IEM_MEMMAP_F_ALIGN_GP | IEM_MEMMAP_F_ALIGN_GP_OR_AC);
8613 if (rcStrict != VINF_SUCCESS)
8614 return rcStrict;
8615 PX86FXSTATE pDst = (PX86FXSTATE)pvMem512;
8616 PCX86FXSTATE pSrc = &pVCpu->cpum.GstCtx.XState.x87;
8617
8618 /*
8619 * Store the registers.
8620 */
8621 /** @todo CPU/VM detection possible! If CR4.OSFXSR=0 MXCSR it's
8622 * implementation specific whether MXCSR and XMM0-XMM7 are saved. */
8623
8624 /* common for all formats */
8625 pDst->FCW = pSrc->FCW;
8626 pDst->FSW = pSrc->FSW;
8627 pDst->FTW = pSrc->FTW & UINT16_C(0xff);
8628 pDst->FOP = pSrc->FOP;
8629 pDst->MXCSR = pSrc->MXCSR;
8630 pDst->MXCSR_MASK = CPUMGetGuestMxCsrMask(pVCpu->CTX_SUFF(pVM));
8631 for (uint32_t i = 0; i < RT_ELEMENTS(pDst->aRegs); i++)
8632 {
8633 /** @todo Testcase: What actually happens to the 6 reserved bytes? I'm clearing
8634 * them for now... */
8635 pDst->aRegs[i].au32[0] = pSrc->aRegs[i].au32[0];
8636 pDst->aRegs[i].au32[1] = pSrc->aRegs[i].au32[1];
8637 pDst->aRegs[i].au32[2] = pSrc->aRegs[i].au32[2] & UINT32_C(0xffff);
8638 pDst->aRegs[i].au32[3] = 0;
8639 }
8640
8641 /* FPU IP, CS, DP and DS. */
8642 pDst->FPUIP = pSrc->FPUIP;
8643 pDst->CS = pSrc->CS;
8644 pDst->FPUDP = pSrc->FPUDP;
8645 pDst->DS = pSrc->DS;
8646 if (enmEffOpSize == IEMMODE_64BIT)
8647 {
8648 /* Save upper 16-bits of FPUIP (IP:CS:Rsvd1) and FPUDP (DP:DS:Rsvd2). */
8649 pDst->Rsrvd1 = pSrc->Rsrvd1;
8650 pDst->Rsrvd2 = pSrc->Rsrvd2;
8651 }
8652 else
8653 {
8654 pDst->Rsrvd1 = 0;
8655 pDst->Rsrvd2 = 0;
8656 }
8657
8658 /* XMM registers. Skipped in 64-bit CPL0 if EFER.FFXSR (AMD only) is set. */
8659 if ( !(pVCpu->cpum.GstCtx.msrEFER & MSR_K6_EFER_FFXSR)
8660 || !IEM_IS_64BIT_CODE(pVCpu)
8661 || IEM_GET_CPL(pVCpu) != 0)
8662 {
8663 uint32_t cXmmRegs = IEM_IS_64BIT_CODE(pVCpu) ? 16 : 8;
8664 for (uint32_t i = 0; i < cXmmRegs; i++)
8665 pDst->aXMM[i] = pSrc->aXMM[i];
8666 /** @todo Testcase: What happens to the reserved XMM registers? Untouched,
8667 * right? */
8668 }
8669
8670 /*
8671 * Commit the memory.
8672 */
8673 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
8674 if (rcStrict != VINF_SUCCESS)
8675 return rcStrict;
8676
8677 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8678}
8679
8680
8681/**
8682 * Implements 'FXRSTOR'.
8683 *
8684 * @param iEffSeg The effective segment register for @a GCPtrEff.
8685 * @param GCPtrEff The address of the image.
8686 * @param enmEffOpSize The operand size (only REX.W really matters).
8687 */
8688IEM_CIMPL_DEF_3(iemCImpl_fxrstor, uint8_t, iEffSeg, RTGCPTR, GCPtrEff, IEMMODE, enmEffOpSize)
8689{
8690 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_X87 | CPUMCTX_EXTRN_SSE_AVX);
8691
8692 /** @todo check out bugref{1529} and AMD behaviour */
8693
8694 /*
8695 * Raise exceptions.
8696 */
8697 if (pVCpu->cpum.GstCtx.cr0 & (X86_CR0_TS | X86_CR0_EM))
8698 return iemRaiseDeviceNotAvailable(pVCpu);
8699
8700 /*
8701 * Access the memory.
8702 */
8703 uint8_t bUnmapInfo;
8704 void *pvMem512;
8705 VBOXSTRICTRC rcStrict = iemMemMap(pVCpu, &pvMem512, &bUnmapInfo, 512, iEffSeg, GCPtrEff, IEM_ACCESS_DATA_R,
8706 15 | IEM_MEMMAP_F_ALIGN_GP | IEM_MEMMAP_F_ALIGN_GP_OR_AC);
8707 if (rcStrict != VINF_SUCCESS)
8708 return rcStrict;
8709 PCX86FXSTATE pSrc = (PCX86FXSTATE)pvMem512;
8710 PX86FXSTATE pDst = &pVCpu->cpum.GstCtx.XState.x87;
8711
8712 /*
8713 * Check the state for stuff which will #GP(0).
8714 */
8715 uint32_t const fMXCSR = pSrc->MXCSR;
8716 uint32_t const fMXCSR_MASK = CPUMGetGuestMxCsrMask(pVCpu->CTX_SUFF(pVM));
8717 if (fMXCSR & ~fMXCSR_MASK)
8718 {
8719 Log(("fxrstor: MXCSR=%#x (MXCSR_MASK=%#x) -> #GP(0)\n", fMXCSR, fMXCSR_MASK));
8720 return iemRaiseGeneralProtectionFault0(pVCpu);
8721 }
8722
8723 /*
8724 * Load the registers.
8725 */
8726 /** @todo CPU/VM detection possible! If CR4.OSFXSR=0 MXCSR it's
8727 * implementation specific whether MXCSR and XMM0-XMM7 are
8728 * restored according to Intel.
8729 * AMD says MXCSR and XMM registers are never loaded if
8730 * CR4.OSFXSR=0.
8731 */
8732
8733 /* common for all formats */
8734 pDst->FCW = pSrc->FCW;
8735 pDst->FSW = pSrc->FSW;
8736 pDst->FTW = pSrc->FTW & UINT16_C(0xff);
8737 pDst->FOP = pSrc->FOP;
8738 pDst->MXCSR = fMXCSR;
8739 /* (MXCSR_MASK is read-only) */
8740 for (uint32_t i = 0; i < RT_ELEMENTS(pSrc->aRegs); i++)
8741 {
8742 pDst->aRegs[i].au32[0] = pSrc->aRegs[i].au32[0];
8743 pDst->aRegs[i].au32[1] = pSrc->aRegs[i].au32[1];
8744 pDst->aRegs[i].au32[2] = pSrc->aRegs[i].au32[2] & UINT32_C(0xffff);
8745 pDst->aRegs[i].au32[3] = 0;
8746 }
8747
8748 /* FPU IP, CS, DP and DS. */
8749 /** @todo AMD says this is only done if FSW.ES is set after loading. */
8750 if (enmEffOpSize == IEMMODE_64BIT)
8751 {
8752 pDst->FPUIP = pSrc->FPUIP;
8753 pDst->CS = pSrc->CS;
8754 pDst->Rsrvd1 = pSrc->Rsrvd1;
8755 pDst->FPUDP = pSrc->FPUDP;
8756 pDst->DS = pSrc->DS;
8757 pDst->Rsrvd2 = pSrc->Rsrvd2;
8758 }
8759 else
8760 {
8761 pDst->FPUIP = pSrc->FPUIP;
8762 pDst->CS = pSrc->CS;
8763 pDst->Rsrvd1 = 0;
8764 pDst->FPUDP = pSrc->FPUDP;
8765 pDst->DS = pSrc->DS;
8766 pDst->Rsrvd2 = 0;
8767 }
8768
8769 /* XMM registers. Skipped in 64-bit CPL0 if EFER.FFXSR (AMD only) is set.
8770 * Does not affect MXCSR, only registers.
8771 */
8772 if ( !(pVCpu->cpum.GstCtx.msrEFER & MSR_K6_EFER_FFXSR)
8773 || !IEM_IS_64BIT_CODE(pVCpu)
8774 || IEM_GET_CPL(pVCpu) != 0)
8775 {
8776 uint32_t cXmmRegs = IEM_IS_64BIT_CODE(pVCpu) ? 16 : 8;
8777 for (uint32_t i = 0; i < cXmmRegs; i++)
8778 pDst->aXMM[i] = pSrc->aXMM[i];
8779 }
8780
8781 pDst->FCW &= ~X86_FCW_ZERO_MASK | X86_FCW_IC_MASK; /* Intel 10980xe allows setting the IC bit. Win 3.11 CALC.EXE sets it. */
8782 iemFpuRecalcExceptionStatus(pDst);
8783
8784 if (pDst->FSW & X86_FSW_ES)
8785 Log11(("fxrstor: %04x:%08RX64: loading state with pending FPU exception (FSW=%#x)\n",
8786 pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pSrc->FSW));
8787
8788 /*
8789 * Unmap the memory.
8790 */
8791 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
8792 if (rcStrict != VINF_SUCCESS)
8793 return rcStrict;
8794
8795 iemHlpUsedFpu(pVCpu);
8796 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8797}
8798
8799
8800/**
8801 * Implements 'XSAVE'.
8802 *
8803 * @param iEffSeg The effective segment.
8804 * @param GCPtrEff The address of the image.
8805 * @param enmEffOpSize The operand size (only REX.W really matters).
8806 */
8807IEM_CIMPL_DEF_3(iemCImpl_xsave, uint8_t, iEffSeg, RTGCPTR, GCPtrEff, IEMMODE, enmEffOpSize)
8808{
8809 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_X87 | CPUMCTX_EXTRN_SSE_AVX | CPUMCTX_EXTRN_OTHER_XSAVE | CPUMCTX_EXTRN_XCRx);
8810
8811 /*
8812 * Raise exceptions.
8813 */
8814 if (!(pVCpu->cpum.GstCtx.cr4 & X86_CR4_OSXSAVE))
8815 return iemRaiseUndefinedOpcode(pVCpu);
8816 /* When in VMX non-root mode and XSAVE/XRSTOR is not enabled, it results in #UD. */
8817 if (RT_LIKELY( !IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
8818 || IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_XSAVES_XRSTORS)))
8819 { /* likely */ }
8820 else
8821 {
8822 Log(("xrstor: Not enabled for nested-guest execution -> #UD\n"));
8823 return iemRaiseUndefinedOpcode(pVCpu);
8824 }
8825 if (pVCpu->cpum.GstCtx.cr0 & X86_CR0_TS)
8826 return iemRaiseDeviceNotAvailable(pVCpu);
8827
8828 /*
8829 * Calc the requested mask.
8830 */
8831 uint64_t const fReqComponents = RT_MAKE_U64(pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.edx) & pVCpu->cpum.GstCtx.aXcr[0];
8832 AssertLogRelReturn(!(fReqComponents & ~(XSAVE_C_X87 | XSAVE_C_SSE | XSAVE_C_YMM)), VERR_IEM_ASPECT_NOT_IMPLEMENTED);
8833 uint64_t const fXInUse = pVCpu->cpum.GstCtx.aXcr[0];
8834
8835/** @todo figure out the exact protocol for the memory access. Currently we
8836 * just need this crap to work halfways to make it possible to test
8837 * AVX instructions. */
8838/** @todo figure out the XINUSE and XMODIFIED */
8839
8840 /*
8841 * Access the x87 memory state.
8842 */
8843 /* The x87+SSE state. */
8844 uint8_t bUnmapInfoMem512;
8845 void *pvMem512;
8846 VBOXSTRICTRC rcStrict = iemMemMap(pVCpu, &pvMem512, &bUnmapInfoMem512, 512,
8847 iEffSeg, GCPtrEff, IEM_ACCESS_DATA_W | IEM_ACCESS_PARTIAL_WRITE,
8848 63 | IEM_MEMMAP_F_ALIGN_GP | IEM_MEMMAP_F_ALIGN_GP_OR_AC);
8849 if (rcStrict != VINF_SUCCESS)
8850 return rcStrict;
8851 PX86FXSTATE pDst = (PX86FXSTATE)pvMem512;
8852 PCX86FXSTATE pSrc = &pVCpu->cpum.GstCtx.XState.x87;
8853
8854 /* The header. */
8855 uint8_t bUnmapInfoHdr;
8856 PX86XSAVEHDR pHdr;
8857 rcStrict = iemMemMap(pVCpu, (void **)&pHdr, &bUnmapInfoHdr, sizeof(pHdr),
8858 iEffSeg, GCPtrEff + 512, IEM_ACCESS_DATA_RW, 0 /* checked above */);
8859 if (rcStrict != VINF_SUCCESS)
8860 return rcStrict;
8861
8862 /*
8863 * Store the X87 state.
8864 */
8865 if (fReqComponents & XSAVE_C_X87)
8866 {
8867 /* common for all formats */
8868 pDst->FCW = pSrc->FCW;
8869 pDst->FSW = pSrc->FSW;
8870 pDst->FTW = pSrc->FTW & UINT16_C(0xff);
8871 pDst->FOP = pSrc->FOP;
8872 pDst->FPUIP = pSrc->FPUIP;
8873 pDst->CS = pSrc->CS;
8874 pDst->FPUDP = pSrc->FPUDP;
8875 pDst->DS = pSrc->DS;
8876 if (enmEffOpSize == IEMMODE_64BIT)
8877 {
8878 /* Save upper 16-bits of FPUIP (IP:CS:Rsvd1) and FPUDP (DP:DS:Rsvd2). */
8879 pDst->Rsrvd1 = pSrc->Rsrvd1;
8880 pDst->Rsrvd2 = pSrc->Rsrvd2;
8881 }
8882 else
8883 {
8884 pDst->Rsrvd1 = 0;
8885 pDst->Rsrvd2 = 0;
8886 }
8887 for (uint32_t i = 0; i < RT_ELEMENTS(pDst->aRegs); i++)
8888 {
8889 /** @todo Testcase: What actually happens to the 6 reserved bytes? I'm clearing
8890 * them for now... */
8891 pDst->aRegs[i].au32[0] = pSrc->aRegs[i].au32[0];
8892 pDst->aRegs[i].au32[1] = pSrc->aRegs[i].au32[1];
8893 pDst->aRegs[i].au32[2] = pSrc->aRegs[i].au32[2] & UINT32_C(0xffff);
8894 pDst->aRegs[i].au32[3] = 0;
8895 }
8896
8897 }
8898
8899 if (fReqComponents & (XSAVE_C_SSE | XSAVE_C_YMM))
8900 {
8901 pDst->MXCSR = pSrc->MXCSR;
8902 pDst->MXCSR_MASK = CPUMGetGuestMxCsrMask(pVCpu->CTX_SUFF(pVM));
8903 }
8904
8905 if (fReqComponents & XSAVE_C_SSE)
8906 {
8907 /* XMM registers. */
8908 uint32_t cXmmRegs = enmEffOpSize == IEMMODE_64BIT ? 16 : 8;
8909 for (uint32_t i = 0; i < cXmmRegs; i++)
8910 pDst->aXMM[i] = pSrc->aXMM[i];
8911 /** @todo Testcase: What happens to the reserved XMM registers? Untouched,
8912 * right? */
8913 }
8914
8915 /* Commit the x87 state bits. (probably wrong) */
8916 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfoMem512);
8917 if (rcStrict != VINF_SUCCESS)
8918 return rcStrict;
8919
8920 /*
8921 * Store AVX state.
8922 */
8923 if (fReqComponents & XSAVE_C_YMM)
8924 {
8925 /** @todo testcase: xsave64 vs xsave32 wrt XSAVE_C_YMM. */
8926 AssertLogRelReturn(pVCpu->cpum.GstCtx.aoffXState[XSAVE_C_YMM_BIT] != UINT16_MAX, VERR_IEM_IPE_9);
8927 uint8_t bUnmapInfoComp;
8928 PCX86XSAVEYMMHI pCompSrc = CPUMCTX_XSAVE_C_PTR(IEM_GET_CTX(pVCpu), XSAVE_C_YMM_BIT, PCX86XSAVEYMMHI);
8929 PX86XSAVEYMMHI pCompDst;
8930 rcStrict = iemMemMap(pVCpu, (void **)&pCompDst, &bUnmapInfoComp, sizeof(*pCompDst), iEffSeg,
8931 GCPtrEff + pVCpu->cpum.GstCtx.aoffXState[XSAVE_C_YMM_BIT],
8932 IEM_ACCESS_DATA_W | IEM_ACCESS_PARTIAL_WRITE, 0 /* checked above */);
8933 if (rcStrict != VINF_SUCCESS)
8934 return rcStrict;
8935
8936 uint32_t cXmmRegs = enmEffOpSize == IEMMODE_64BIT ? 16 : 8;
8937 for (uint32_t i = 0; i < cXmmRegs; i++)
8938 pCompDst->aYmmHi[i] = pCompSrc->aYmmHi[i];
8939
8940 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfoComp);
8941 if (rcStrict != VINF_SUCCESS)
8942 return rcStrict;
8943 }
8944
8945 /*
8946 * Update the header.
8947 */
8948 pHdr->bmXState = (pHdr->bmXState & ~fReqComponents)
8949 | (fReqComponents & fXInUse);
8950
8951 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfoHdr);
8952 if (rcStrict != VINF_SUCCESS)
8953 return rcStrict;
8954
8955 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
8956}
8957
8958
8959/**
8960 * Implements 'XRSTOR'.
8961 *
8962 * @param iEffSeg The effective segment.
8963 * @param GCPtrEff The address of the image.
8964 * @param enmEffOpSize The operand size (only REX.W really matters).
8965 */
8966IEM_CIMPL_DEF_3(iemCImpl_xrstor, uint8_t, iEffSeg, RTGCPTR, GCPtrEff, IEMMODE, enmEffOpSize)
8967{
8968 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_X87 | CPUMCTX_EXTRN_SSE_AVX | CPUMCTX_EXTRN_OTHER_XSAVE | CPUMCTX_EXTRN_XCRx);
8969
8970 /*
8971 * Raise exceptions.
8972 */
8973 if (!(pVCpu->cpum.GstCtx.cr4 & X86_CR4_OSXSAVE))
8974 return iemRaiseUndefinedOpcode(pVCpu);
8975 /* When in VMX non-root mode and XSAVE/XRSTOR is not enabled, it results in #UD. */
8976 if (RT_LIKELY( !IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
8977 || IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_XSAVES_XRSTORS)))
8978 { /* likely */ }
8979 else
8980 {
8981 Log(("xrstor: Not enabled for nested-guest execution -> #UD\n"));
8982 return iemRaiseUndefinedOpcode(pVCpu);
8983 }
8984 if (pVCpu->cpum.GstCtx.cr0 & X86_CR0_TS)
8985 return iemRaiseDeviceNotAvailable(pVCpu);
8986 if (GCPtrEff & 63)
8987 {
8988 /** @todo CPU/VM detection possible! \#AC might not be signal for
8989 * all/any misalignment sizes, intel says its an implementation detail. */
8990 if ( (pVCpu->cpum.GstCtx.cr0 & X86_CR0_AM)
8991 && pVCpu->cpum.GstCtx.eflags.Bits.u1AC
8992 && IEM_GET_CPL(pVCpu) == 3)
8993 return iemRaiseAlignmentCheckException(pVCpu);
8994 return iemRaiseGeneralProtectionFault0(pVCpu);
8995 }
8996
8997/** @todo figure out the exact protocol for the memory access. Currently we
8998 * just need this crap to work halfways to make it possible to test
8999 * AVX instructions. */
9000/** @todo figure out the XINUSE and XMODIFIED */
9001
9002 /*
9003 * Access the x87 memory state.
9004 */
9005 /* The x87+SSE state. */
9006 uint8_t bUnmapInfoMem512;
9007 void *pvMem512;
9008 VBOXSTRICTRC rcStrict = iemMemMap(pVCpu, &pvMem512, &bUnmapInfoMem512, 512, iEffSeg, GCPtrEff, IEM_ACCESS_DATA_R,
9009 63 | IEM_MEMMAP_F_ALIGN_GP | IEM_MEMMAP_F_ALIGN_GP_OR_AC);
9010 if (rcStrict != VINF_SUCCESS)
9011 return rcStrict;
9012 PCX86FXSTATE pSrc = (PCX86FXSTATE)pvMem512;
9013 PX86FXSTATE pDst = &pVCpu->cpum.GstCtx.XState.x87;
9014
9015 /*
9016 * Calc the requested mask
9017 */
9018 uint8_t bUnmapInfoHdr;
9019 PX86XSAVEHDR pHdrDst = &pVCpu->cpum.GstCtx.XState.Hdr;
9020 PCX86XSAVEHDR pHdrSrc;
9021 rcStrict = iemMemMap(pVCpu, (void **)&pHdrSrc, &bUnmapInfoHdr, sizeof(*pHdrSrc), iEffSeg, GCPtrEff + 512,
9022 IEM_ACCESS_DATA_R, 0 /* checked above */);
9023 if (rcStrict != VINF_SUCCESS)
9024 return rcStrict;
9025
9026 uint64_t const fReqComponents = RT_MAKE_U64(pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.edx) & pVCpu->cpum.GstCtx.aXcr[0];
9027 AssertLogRelReturn(!(fReqComponents & ~(XSAVE_C_X87 | XSAVE_C_SSE | XSAVE_C_YMM)), VERR_IEM_ASPECT_NOT_IMPLEMENTED);
9028 //uint64_t const fXInUse = pVCpu->cpum.GstCtx.aXcr[0];
9029 uint64_t const fRstorMask = pHdrSrc->bmXState;
9030 uint64_t const fCompMask = pHdrSrc->bmXComp;
9031
9032 AssertLogRelReturn(!(fCompMask & XSAVE_C_X), VERR_IEM_ASPECT_NOT_IMPLEMENTED);
9033
9034 uint32_t const cXmmRegs = enmEffOpSize == IEMMODE_64BIT ? 16 : 8;
9035
9036 /* We won't need this any longer. */
9037 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfoHdr);
9038 if (rcStrict != VINF_SUCCESS)
9039 return rcStrict;
9040
9041 /*
9042 * Load the X87 state.
9043 */
9044 if (fReqComponents & XSAVE_C_X87)
9045 {
9046 if (fRstorMask & XSAVE_C_X87)
9047 {
9048 pDst->FCW = pSrc->FCW;
9049 pDst->FSW = pSrc->FSW;
9050 pDst->FTW = pSrc->FTW & UINT16_C(0xff);
9051 pDst->FOP = pSrc->FOP;
9052 pDst->FPUIP = pSrc->FPUIP;
9053 pDst->CS = pSrc->CS;
9054 pDst->FPUDP = pSrc->FPUDP;
9055 pDst->DS = pSrc->DS;
9056 if (enmEffOpSize == IEMMODE_64BIT)
9057 {
9058 /* Load upper 16-bits of FPUIP (IP:CS:Rsvd1) and FPUDP (DP:DS:Rsvd2). */
9059 pDst->Rsrvd1 = pSrc->Rsrvd1;
9060 pDst->Rsrvd2 = pSrc->Rsrvd2;
9061 }
9062 else
9063 {
9064 pDst->Rsrvd1 = 0;
9065 pDst->Rsrvd2 = 0;
9066 }
9067 for (uint32_t i = 0; i < RT_ELEMENTS(pDst->aRegs); i++)
9068 {
9069 pDst->aRegs[i].au32[0] = pSrc->aRegs[i].au32[0];
9070 pDst->aRegs[i].au32[1] = pSrc->aRegs[i].au32[1];
9071 pDst->aRegs[i].au32[2] = pSrc->aRegs[i].au32[2] & UINT32_C(0xffff);
9072 pDst->aRegs[i].au32[3] = 0;
9073 }
9074
9075 pDst->FCW &= ~X86_FCW_ZERO_MASK | X86_FCW_IC_MASK; /* Intel 10980xe allows setting the IC bit. Win 3.11 CALC.EXE sets it. */
9076 iemFpuRecalcExceptionStatus(pDst);
9077
9078 if (pDst->FSW & X86_FSW_ES)
9079 Log11(("xrstor: %04x:%08RX64: loading state with pending FPU exception (FSW=%#x)\n",
9080 pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pSrc->FSW));
9081 }
9082 else
9083 {
9084 pDst->FCW = 0x37f;
9085 pDst->FSW = 0;
9086 pDst->FTW = 0x00; /* 0 - empty. */
9087 pDst->FPUDP = 0;
9088 pDst->DS = 0; //??
9089 pDst->Rsrvd2= 0;
9090 pDst->FPUIP = 0;
9091 pDst->CS = 0; //??
9092 pDst->Rsrvd1= 0;
9093 pDst->FOP = 0;
9094 for (uint32_t i = 0; i < RT_ELEMENTS(pSrc->aRegs); i++)
9095 {
9096 pDst->aRegs[i].au32[0] = 0;
9097 pDst->aRegs[i].au32[1] = 0;
9098 pDst->aRegs[i].au32[2] = 0;
9099 pDst->aRegs[i].au32[3] = 0;
9100 }
9101 }
9102 pHdrDst->bmXState |= XSAVE_C_X87; /* playing safe for now */
9103 }
9104
9105 /* MXCSR */
9106 if (fReqComponents & (XSAVE_C_SSE | XSAVE_C_YMM))
9107 {
9108 if (fRstorMask & (XSAVE_C_SSE | XSAVE_C_YMM))
9109 pDst->MXCSR = pSrc->MXCSR;
9110 else
9111 pDst->MXCSR = 0x1f80;
9112 }
9113
9114 /* XMM registers. */
9115 if (fReqComponents & XSAVE_C_SSE)
9116 {
9117 if (fRstorMask & XSAVE_C_SSE)
9118 {
9119 for (uint32_t i = 0; i < cXmmRegs; i++)
9120 pDst->aXMM[i] = pSrc->aXMM[i];
9121 /** @todo Testcase: What happens to the reserved XMM registers? Untouched,
9122 * right? */
9123 }
9124 else
9125 {
9126 for (uint32_t i = 0; i < cXmmRegs; i++)
9127 {
9128 pDst->aXMM[i].au64[0] = 0;
9129 pDst->aXMM[i].au64[1] = 0;
9130 }
9131 }
9132 pHdrDst->bmXState |= XSAVE_C_SSE; /* playing safe for now */
9133 }
9134
9135 /* Unmap the x87 state bits (so we've don't run out of mapping). */
9136 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfoMem512);
9137 if (rcStrict != VINF_SUCCESS)
9138 return rcStrict;
9139
9140 /*
9141 * Restore AVX state.
9142 */
9143 if (fReqComponents & XSAVE_C_YMM)
9144 {
9145 AssertLogRelReturn(pVCpu->cpum.GstCtx.aoffXState[XSAVE_C_YMM_BIT] != UINT16_MAX, VERR_IEM_IPE_9);
9146 PX86XSAVEYMMHI pCompDst = CPUMCTX_XSAVE_C_PTR(IEM_GET_CTX(pVCpu), XSAVE_C_YMM_BIT, PX86XSAVEYMMHI);
9147
9148 if (fRstorMask & XSAVE_C_YMM)
9149 {
9150 /** @todo testcase: xsave64 vs xsave32 wrt XSAVE_C_YMM. */
9151 uint8_t bUnmapInfoComp;
9152 PCX86XSAVEYMMHI pCompSrc;
9153 rcStrict = iemMemMap(pVCpu, (void **)&pCompSrc, &bUnmapInfoComp, sizeof(*pCompDst),
9154 iEffSeg, GCPtrEff + pVCpu->cpum.GstCtx.aoffXState[XSAVE_C_YMM_BIT],
9155 IEM_ACCESS_DATA_R, 0 /* checked above */);
9156 if (rcStrict != VINF_SUCCESS)
9157 return rcStrict;
9158
9159 for (uint32_t i = 0; i < cXmmRegs; i++)
9160 {
9161 pCompDst->aYmmHi[i].au64[0] = pCompSrc->aYmmHi[i].au64[0];
9162 pCompDst->aYmmHi[i].au64[1] = pCompSrc->aYmmHi[i].au64[1];
9163 }
9164
9165 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfoComp);
9166 if (rcStrict != VINF_SUCCESS)
9167 return rcStrict;
9168 }
9169 else
9170 {
9171 for (uint32_t i = 0; i < cXmmRegs; i++)
9172 {
9173 pCompDst->aYmmHi[i].au64[0] = 0;
9174 pCompDst->aYmmHi[i].au64[1] = 0;
9175 }
9176 }
9177 pHdrDst->bmXState |= XSAVE_C_YMM; /* playing safe for now */
9178 }
9179
9180 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
9181}
9182
9183
9184
9185
9186/**
9187 * Implements 'STMXCSR'.
9188 *
9189 * @param iEffSeg The effective segment register for @a GCPtrEff.
9190 * @param GCPtrEff The address of the image.
9191 */
9192IEM_CIMPL_DEF_2(iemCImpl_stmxcsr, uint8_t, iEffSeg, RTGCPTR, GCPtrEff)
9193{
9194 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_X87 | CPUMCTX_EXTRN_SSE_AVX);
9195
9196 /*
9197 * Raise exceptions.
9198 */
9199 if ( !(pVCpu->cpum.GstCtx.cr0 & X86_CR0_EM)
9200 && (pVCpu->cpum.GstCtx.cr4 & X86_CR4_OSFXSR))
9201 {
9202 if (!(pVCpu->cpum.GstCtx.cr0 & X86_CR0_TS))
9203 {
9204 /*
9205 * Do the job.
9206 */
9207 VBOXSTRICTRC rcStrict = iemMemStoreDataU32(pVCpu, iEffSeg, GCPtrEff, pVCpu->cpum.GstCtx.XState.x87.MXCSR);
9208 if (rcStrict == VINF_SUCCESS)
9209 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
9210 return rcStrict;
9211 }
9212 return iemRaiseDeviceNotAvailable(pVCpu);
9213 }
9214 return iemRaiseUndefinedOpcode(pVCpu);
9215}
9216
9217
9218/**
9219 * Implements 'VSTMXCSR'.
9220 *
9221 * @param iEffSeg The effective segment register for @a GCPtrEff.
9222 * @param GCPtrEff The address of the image.
9223 */
9224IEM_CIMPL_DEF_2(iemCImpl_vstmxcsr, uint8_t, iEffSeg, RTGCPTR, GCPtrEff)
9225{
9226 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_X87 | CPUMCTX_EXTRN_SSE_AVX | CPUMCTX_EXTRN_XCRx);
9227
9228 /*
9229 * Raise exceptions.
9230 */
9231 if ( ( !IEM_IS_GUEST_CPU_AMD(pVCpu)
9232 ? (pVCpu->cpum.GstCtx.aXcr[0] & (XSAVE_C_SSE | XSAVE_C_YMM)) == (XSAVE_C_SSE | XSAVE_C_YMM)
9233 : !(pVCpu->cpum.GstCtx.cr0 & X86_CR0_EM)) /* AMD Jaguar CPU (f0x16,m0,s1) behaviour */
9234 && (pVCpu->cpum.GstCtx.cr4 & X86_CR4_OSXSAVE))
9235 {
9236 if (!(pVCpu->cpum.GstCtx.cr0 & X86_CR0_TS))
9237 {
9238 /*
9239 * Do the job.
9240 */
9241 VBOXSTRICTRC rcStrict = iemMemStoreDataU32(pVCpu, iEffSeg, GCPtrEff, pVCpu->cpum.GstCtx.XState.x87.MXCSR);
9242 if (rcStrict == VINF_SUCCESS)
9243 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
9244 return rcStrict;
9245 }
9246 return iemRaiseDeviceNotAvailable(pVCpu);
9247 }
9248 return iemRaiseUndefinedOpcode(pVCpu);
9249}
9250
9251
9252/**
9253 * Implements 'LDMXCSR'.
9254 *
9255 * @param iEffSeg The effective segment register for @a GCPtrEff.
9256 * @param GCPtrEff The address of the image.
9257 */
9258IEM_CIMPL_DEF_2(iemCImpl_ldmxcsr, uint8_t, iEffSeg, RTGCPTR, GCPtrEff)
9259{
9260 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_X87 | CPUMCTX_EXTRN_SSE_AVX);
9261
9262 /*
9263 * Raise exceptions.
9264 */
9265 /** @todo testcase - order of LDMXCSR faults. Does \#PF, \#GP and \#SS
9266 * happen after or before \#UD and \#EM? */
9267 if ( !(pVCpu->cpum.GstCtx.cr0 & X86_CR0_EM)
9268 && (pVCpu->cpum.GstCtx.cr4 & X86_CR4_OSFXSR))
9269 {
9270 if (!(pVCpu->cpum.GstCtx.cr0 & X86_CR0_TS))
9271 {
9272 /*
9273 * Do the job.
9274 */
9275 uint32_t fNewMxCsr;
9276 VBOXSTRICTRC rcStrict = iemMemFetchDataU32(pVCpu, &fNewMxCsr, iEffSeg, GCPtrEff);
9277 if (rcStrict == VINF_SUCCESS)
9278 {
9279 uint32_t const fMxCsrMask = CPUMGetGuestMxCsrMask(pVCpu->CTX_SUFF(pVM));
9280 if (!(fNewMxCsr & ~fMxCsrMask))
9281 {
9282 pVCpu->cpum.GstCtx.XState.x87.MXCSR = fNewMxCsr;
9283 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
9284 }
9285 Log(("ldmxcsr: New MXCSR=%#RX32 & ~MASK=%#RX32 = %#RX32 -> #GP(0)\n",
9286 fNewMxCsr, fMxCsrMask, fNewMxCsr & ~fMxCsrMask));
9287 return iemRaiseGeneralProtectionFault0(pVCpu);
9288 }
9289 return rcStrict;
9290 }
9291 return iemRaiseDeviceNotAvailable(pVCpu);
9292 }
9293 return iemRaiseUndefinedOpcode(pVCpu);
9294}
9295
9296
9297/**
9298 * Commmon routine for fnstenv and fnsave.
9299 *
9300 * @param pVCpu The cross context virtual CPU structure of the calling thread.
9301 * @param enmEffOpSize The effective operand size.
9302 * @param uPtr Where to store the state.
9303 */
9304static void iemCImplCommonFpuStoreEnv(PVMCPUCC pVCpu, IEMMODE enmEffOpSize, RTPTRUNION uPtr)
9305{
9306 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_X87);
9307 PCX86FXSTATE pSrcX87 = &pVCpu->cpum.GstCtx.XState.x87;
9308 if (enmEffOpSize == IEMMODE_16BIT)
9309 {
9310 uPtr.pu16[0] = pSrcX87->FCW;
9311 uPtr.pu16[1] = pSrcX87->FSW;
9312 uPtr.pu16[2] = iemFpuCalcFullFtw(pSrcX87);
9313 if (IEM_IS_REAL_OR_V86_MODE(pVCpu))
9314 {
9315 /** @todo Testcase: How does this work when the FPUIP/CS was saved in
9316 * protected mode or long mode and we save it in real mode? And vice
9317 * versa? And with 32-bit operand size? I think CPU is storing the
9318 * effective address ((CS << 4) + IP) in the offset register and not
9319 * doing any address calculations here. */
9320 uPtr.pu16[3] = (uint16_t)pSrcX87->FPUIP;
9321 uPtr.pu16[4] = ((pSrcX87->FPUIP >> 4) & UINT16_C(0xf000)) | pSrcX87->FOP;
9322 uPtr.pu16[5] = (uint16_t)pSrcX87->FPUDP;
9323 uPtr.pu16[6] = (pSrcX87->FPUDP >> 4) & UINT16_C(0xf000);
9324 }
9325 else
9326 {
9327 uPtr.pu16[3] = pSrcX87->FPUIP;
9328 uPtr.pu16[4] = pSrcX87->CS;
9329 uPtr.pu16[5] = pSrcX87->FPUDP;
9330 uPtr.pu16[6] = pSrcX87->DS;
9331 }
9332 }
9333 else
9334 {
9335 /** @todo Testcase: what is stored in the "gray" areas? (figure 8-9 and 8-10) */
9336 uPtr.pu16[0*2] = pSrcX87->FCW;
9337 uPtr.pu16[0*2+1] = 0xffff; /* (0xffff observed on intel skylake.) */
9338 uPtr.pu16[1*2] = pSrcX87->FSW;
9339 uPtr.pu16[1*2+1] = 0xffff;
9340 uPtr.pu16[2*2] = iemFpuCalcFullFtw(pSrcX87);
9341 uPtr.pu16[2*2+1] = 0xffff;
9342 if (IEM_IS_REAL_OR_V86_MODE(pVCpu))
9343 {
9344 uPtr.pu16[3*2] = (uint16_t)pSrcX87->FPUIP;
9345 uPtr.pu32[4] = ((pSrcX87->FPUIP & UINT32_C(0xffff0000)) >> 4) | pSrcX87->FOP;
9346 uPtr.pu16[5*2] = (uint16_t)pSrcX87->FPUDP;
9347 uPtr.pu32[6] = (pSrcX87->FPUDP & UINT32_C(0xffff0000)) >> 4;
9348 }
9349 else
9350 {
9351 uPtr.pu32[3] = pSrcX87->FPUIP;
9352 uPtr.pu16[4*2] = pSrcX87->CS;
9353 uPtr.pu16[4*2+1] = pSrcX87->FOP;
9354 uPtr.pu32[5] = pSrcX87->FPUDP;
9355 uPtr.pu16[6*2] = pSrcX87->DS;
9356 uPtr.pu16[6*2+1] = 0xffff;
9357 }
9358 }
9359}
9360
9361
9362/**
9363 * Commmon routine for fldenv and frstor
9364 *
9365 * @param pVCpu The cross context virtual CPU structure of the calling thread.
9366 * @param enmEffOpSize The effective operand size.
9367 * @param uPtr Where to store the state.
9368 */
9369static void iemCImplCommonFpuRestoreEnv(PVMCPUCC pVCpu, IEMMODE enmEffOpSize, RTCPTRUNION uPtr)
9370{
9371 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_X87);
9372 PX86FXSTATE pDstX87 = &pVCpu->cpum.GstCtx.XState.x87;
9373 if (enmEffOpSize == IEMMODE_16BIT)
9374 {
9375 pDstX87->FCW = uPtr.pu16[0];
9376 pDstX87->FSW = uPtr.pu16[1];
9377 pDstX87->FTW = uPtr.pu16[2];
9378 if (IEM_IS_REAL_OR_V86_MODE(pVCpu))
9379 {
9380 pDstX87->FPUIP = uPtr.pu16[3] | ((uint32_t)(uPtr.pu16[4] & UINT16_C(0xf000)) << 4);
9381 pDstX87->FPUDP = uPtr.pu16[5] | ((uint32_t)(uPtr.pu16[6] & UINT16_C(0xf000)) << 4);
9382 pDstX87->FOP = uPtr.pu16[4] & UINT16_C(0x07ff);
9383 pDstX87->CS = 0;
9384 pDstX87->Rsrvd1= 0;
9385 pDstX87->DS = 0;
9386 pDstX87->Rsrvd2= 0;
9387 }
9388 else
9389 {
9390 pDstX87->FPUIP = uPtr.pu16[3];
9391 pDstX87->CS = uPtr.pu16[4];
9392 pDstX87->Rsrvd1= 0;
9393 pDstX87->FPUDP = uPtr.pu16[5];
9394 pDstX87->DS = uPtr.pu16[6];
9395 pDstX87->Rsrvd2= 0;
9396 /** @todo Testcase: Is FOP cleared when doing 16-bit protected mode fldenv? */
9397 }
9398 }
9399 else
9400 {
9401 pDstX87->FCW = uPtr.pu16[0*2];
9402 pDstX87->FSW = uPtr.pu16[1*2];
9403 pDstX87->FTW = uPtr.pu16[2*2];
9404 if (IEM_IS_REAL_OR_V86_MODE(pVCpu))
9405 {
9406 pDstX87->FPUIP = uPtr.pu16[3*2] | ((uPtr.pu32[4] & UINT32_C(0x0ffff000)) << 4);
9407 pDstX87->FOP = uPtr.pu32[4] & UINT16_C(0x07ff);
9408 pDstX87->FPUDP = uPtr.pu16[5*2] | ((uPtr.pu32[6] & UINT32_C(0x0ffff000)) << 4);
9409 pDstX87->CS = 0;
9410 pDstX87->Rsrvd1= 0;
9411 pDstX87->DS = 0;
9412 pDstX87->Rsrvd2= 0;
9413 }
9414 else
9415 {
9416 pDstX87->FPUIP = uPtr.pu32[3];
9417 pDstX87->CS = uPtr.pu16[4*2];
9418 pDstX87->Rsrvd1= 0;
9419 pDstX87->FOP = uPtr.pu16[4*2+1];
9420 pDstX87->FPUDP = uPtr.pu32[5];
9421 pDstX87->DS = uPtr.pu16[6*2];
9422 pDstX87->Rsrvd2= 0;
9423 }
9424 }
9425
9426 /* Make adjustments. */
9427 pDstX87->FTW = iemFpuCompressFtw(pDstX87->FTW);
9428#ifdef LOG_ENABLED
9429 uint16_t const fOldFsw = pDstX87->FSW;
9430#endif
9431 pDstX87->FCW &= ~X86_FCW_ZERO_MASK | X86_FCW_IC_MASK; /* Intel 10980xe allows setting the IC bit. Win 3.11 CALC.EXE sets it. */
9432 iemFpuRecalcExceptionStatus(pDstX87);
9433#ifdef LOG_ENABLED
9434 if ((pDstX87->FSW & X86_FSW_ES) ^ (fOldFsw & X86_FSW_ES))
9435 Log11(("iemCImplCommonFpuRestoreEnv: %04x:%08RX64: %s FPU exception (FCW=%#x FSW=%#x -> %#x)\n",
9436 pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, fOldFsw & X86_FSW_ES ? "Supressed" : "Raised",
9437 pDstX87->FCW, fOldFsw, pDstX87->FSW));
9438#endif
9439
9440 /** @todo Testcase: Check if ES and/or B are automatically cleared if no
9441 * exceptions are pending after loading the saved state? */
9442}
9443
9444
9445/**
9446 * Implements 'FNSTENV'.
9447 *
9448 * @param enmEffOpSize The operand size (only REX.W really matters).
9449 * @param iEffSeg The effective segment register for @a GCPtrEffDst.
9450 * @param GCPtrEffDst The address of the image.
9451 */
9452IEM_CIMPL_DEF_3(iemCImpl_fnstenv, IEMMODE, enmEffOpSize, uint8_t, iEffSeg, RTGCPTR, GCPtrEffDst)
9453{
9454 uint8_t bUnmapInfo;
9455 RTPTRUNION uPtr;
9456 VBOXSTRICTRC rcStrict = iemMemMap(pVCpu, &uPtr.pv, &bUnmapInfo, enmEffOpSize == IEMMODE_16BIT ? 14 : 28,
9457 iEffSeg, GCPtrEffDst, IEM_ACCESS_DATA_W | IEM_ACCESS_PARTIAL_WRITE,
9458 enmEffOpSize == IEMMODE_16BIT ? 1 : 3 /** @todo ? */);
9459 if (rcStrict != VINF_SUCCESS)
9460 return rcStrict;
9461
9462 iemCImplCommonFpuStoreEnv(pVCpu, enmEffOpSize, uPtr);
9463
9464 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
9465 if (rcStrict != VINF_SUCCESS)
9466 return rcStrict;
9467
9468 /* Mask all math exceptions. Any possibly pending exceptions will be cleared. */
9469 PX86FXSTATE pFpuCtx = &pVCpu->cpum.GstCtx.XState.x87;
9470 pFpuCtx->FCW |= X86_FCW_XCPT_MASK;
9471#ifdef LOG_ENABLED
9472 uint16_t fOldFsw = pFpuCtx->FSW;
9473#endif
9474 iemFpuRecalcExceptionStatus(pFpuCtx);
9475#ifdef LOG_ENABLED
9476 if ((pFpuCtx->FSW & X86_FSW_ES) ^ (fOldFsw & X86_FSW_ES))
9477 Log11(("fnstenv: %04x:%08RX64: %s FPU exception (FCW=%#x, FSW %#x -> %#x)\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
9478 fOldFsw & X86_FSW_ES ? "Supressed" : "Raised", pFpuCtx->FCW, fOldFsw, pFpuCtx->FSW));
9479#endif
9480
9481 iemHlpUsedFpu(pVCpu);
9482
9483 /* Note: C0, C1, C2 and C3 are documented as undefined, we leave them untouched! */
9484 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
9485}
9486
9487
9488/**
9489 * Implements 'FNSAVE'.
9490 *
9491 * @param enmEffOpSize The operand size.
9492 * @param iEffSeg The effective segment register for @a GCPtrEffDst.
9493 * @param GCPtrEffDst The address of the image.
9494 */
9495IEM_CIMPL_DEF_3(iemCImpl_fnsave, IEMMODE, enmEffOpSize, uint8_t, iEffSeg, RTGCPTR, GCPtrEffDst)
9496{
9497 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_X87);
9498
9499 uint8_t bUnmapInfo;
9500 RTPTRUNION uPtr;
9501 VBOXSTRICTRC rcStrict = iemMemMap(pVCpu, &uPtr.pv, &bUnmapInfo, enmEffOpSize == IEMMODE_16BIT ? 94 : 108,
9502 iEffSeg, GCPtrEffDst, IEM_ACCESS_DATA_W | IEM_ACCESS_PARTIAL_WRITE, 3 /** @todo ? */);
9503 if (rcStrict != VINF_SUCCESS)
9504 return rcStrict;
9505
9506 PX86FXSTATE pFpuCtx = &pVCpu->cpum.GstCtx.XState.x87;
9507 iemCImplCommonFpuStoreEnv(pVCpu, enmEffOpSize, uPtr);
9508 PRTFLOAT80U paRegs = (PRTFLOAT80U)(uPtr.pu8 + (enmEffOpSize == IEMMODE_16BIT ? 14 : 28));
9509 for (uint32_t i = 0; i < RT_ELEMENTS(pFpuCtx->aRegs); i++)
9510 {
9511 paRegs[i].au32[0] = pFpuCtx->aRegs[i].au32[0];
9512 paRegs[i].au32[1] = pFpuCtx->aRegs[i].au32[1];
9513 paRegs[i].au16[4] = pFpuCtx->aRegs[i].au16[4];
9514 }
9515
9516 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
9517 if (rcStrict != VINF_SUCCESS)
9518 return rcStrict;
9519
9520 /* Rotate the stack to account for changed TOS. */
9521 iemFpuRotateStackSetTop(pFpuCtx, 0);
9522
9523 /*
9524 * Re-initialize the FPU context.
9525 */
9526 pFpuCtx->FCW = 0x37f;
9527 pFpuCtx->FSW = 0;
9528 pFpuCtx->FTW = 0x00; /* 0 - empty */
9529 pFpuCtx->FPUDP = 0;
9530 pFpuCtx->DS = 0;
9531 pFpuCtx->Rsrvd2= 0;
9532 pFpuCtx->FPUIP = 0;
9533 pFpuCtx->CS = 0;
9534 pFpuCtx->Rsrvd1= 0;
9535 pFpuCtx->FOP = 0;
9536
9537 iemHlpUsedFpu(pVCpu);
9538 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
9539}
9540
9541
9542
9543/**
9544 * Implements 'FLDENV'.
9545 *
9546 * @param enmEffOpSize The operand size (only REX.W really matters).
9547 * @param iEffSeg The effective segment register for @a GCPtrEffSrc.
9548 * @param GCPtrEffSrc The address of the image.
9549 */
9550IEM_CIMPL_DEF_3(iemCImpl_fldenv, IEMMODE, enmEffOpSize, uint8_t, iEffSeg, RTGCPTR, GCPtrEffSrc)
9551{
9552 uint8_t bUnmapInfo;
9553 RTCPTRUNION uPtr;
9554 VBOXSTRICTRC rcStrict = iemMemMap(pVCpu, (void **)&uPtr.pv, &bUnmapInfo, enmEffOpSize == IEMMODE_16BIT ? 14 : 28,
9555 iEffSeg, GCPtrEffSrc, IEM_ACCESS_DATA_R,
9556 enmEffOpSize == IEMMODE_16BIT ? 1 : 3 /** @todo ?*/);
9557 if (rcStrict != VINF_SUCCESS)
9558 return rcStrict;
9559
9560 iemCImplCommonFpuRestoreEnv(pVCpu, enmEffOpSize, uPtr);
9561
9562 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
9563 if (rcStrict != VINF_SUCCESS)
9564 return rcStrict;
9565
9566 iemHlpUsedFpu(pVCpu);
9567 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
9568}
9569
9570
9571/**
9572 * Implements 'FRSTOR'.
9573 *
9574 * @param enmEffOpSize The operand size.
9575 * @param iEffSeg The effective segment register for @a GCPtrEffSrc.
9576 * @param GCPtrEffSrc The address of the image.
9577 */
9578IEM_CIMPL_DEF_3(iemCImpl_frstor, IEMMODE, enmEffOpSize, uint8_t, iEffSeg, RTGCPTR, GCPtrEffSrc)
9579{
9580 uint8_t bUnmapInfo;
9581 RTCPTRUNION uPtr;
9582 VBOXSTRICTRC rcStrict = iemMemMap(pVCpu, (void **)&uPtr.pv, &bUnmapInfo, enmEffOpSize == IEMMODE_16BIT ? 94 : 108,
9583 iEffSeg, GCPtrEffSrc, IEM_ACCESS_DATA_R, 3 /** @todo ?*/ );
9584 if (rcStrict != VINF_SUCCESS)
9585 return rcStrict;
9586
9587 PX86FXSTATE pFpuCtx = &pVCpu->cpum.GstCtx.XState.x87;
9588 iemCImplCommonFpuRestoreEnv(pVCpu, enmEffOpSize, uPtr);
9589 PCRTFLOAT80U paRegs = (PCRTFLOAT80U)(uPtr.pu8 + (enmEffOpSize == IEMMODE_16BIT ? 14 : 28));
9590 for (uint32_t i = 0; i < RT_ELEMENTS(pFpuCtx->aRegs); i++)
9591 {
9592 pFpuCtx->aRegs[i].au32[0] = paRegs[i].au32[0];
9593 pFpuCtx->aRegs[i].au32[1] = paRegs[i].au32[1];
9594 pFpuCtx->aRegs[i].au32[2] = paRegs[i].au16[4];
9595 pFpuCtx->aRegs[i].au32[3] = 0;
9596 }
9597
9598 rcStrict = iemMemCommitAndUnmap(pVCpu, bUnmapInfo);
9599 if (rcStrict != VINF_SUCCESS)
9600 return rcStrict;
9601
9602 iemHlpUsedFpu(pVCpu);
9603 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
9604}
9605
9606
9607/**
9608 * Implements 'FLDCW'.
9609 *
9610 * @param u16Fcw The new FCW.
9611 */
9612IEM_CIMPL_DEF_1(iemCImpl_fldcw, uint16_t, u16Fcw)
9613{
9614 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_X87);
9615
9616 /** @todo Testcase: Check what happens when trying to load X86_FCW_PC_RSVD. */
9617 /** @todo Testcase: Try see what happens when trying to set undefined bits
9618 * (other than 6 and 7). Currently ignoring them. */
9619 /** @todo Testcase: Test that it raises and loweres the FPU exception bits
9620 * according to FSW. (This is what is currently implemented.) */
9621 PX86FXSTATE pFpuCtx = &pVCpu->cpum.GstCtx.XState.x87;
9622 pFpuCtx->FCW = u16Fcw & (~X86_FCW_ZERO_MASK | X86_FCW_IC_MASK); /* Intel 10980xe allows setting the IC bit. Win 3.11 CALC.EXE sets it. */
9623#ifdef LOG_ENABLED
9624 uint16_t fOldFsw = pFpuCtx->FSW;
9625#endif
9626 iemFpuRecalcExceptionStatus(pFpuCtx);
9627#ifdef LOG_ENABLED
9628 if ((pFpuCtx->FSW & X86_FSW_ES) ^ (fOldFsw & X86_FSW_ES))
9629 Log11(("fldcw: %04x:%08RX64: %s FPU exception (FCW=%#x, FSW %#x -> %#x)\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
9630 fOldFsw & X86_FSW_ES ? "Supressed" : "Raised", pFpuCtx->FCW, fOldFsw, pFpuCtx->FSW));
9631#endif
9632
9633 /* Note: C0, C1, C2 and C3 are documented as undefined, we leave them untouched! */
9634 iemHlpUsedFpu(pVCpu);
9635 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
9636}
9637
9638
9639
9640/**
9641 * Implements the underflow case of fxch.
9642 *
9643 * @param iStReg The other stack register.
9644 * @param uFpuOpcode The FPU opcode (for simplicity).
9645 */
9646IEM_CIMPL_DEF_2(iemCImpl_fxch_underflow, uint8_t, iStReg, uint16_t, uFpuOpcode)
9647{
9648 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_X87);
9649
9650 PX86FXSTATE pFpuCtx = &pVCpu->cpum.GstCtx.XState.x87;
9651 unsigned const iReg1 = X86_FSW_TOP_GET(pFpuCtx->FSW);
9652 unsigned const iReg2 = (iReg1 + iStReg) & X86_FSW_TOP_SMASK;
9653 Assert(!(RT_BIT(iReg1) & pFpuCtx->FTW) || !(RT_BIT(iReg2) & pFpuCtx->FTW));
9654
9655 /** @todo Testcase: fxch underflow. Making assumptions that underflowed
9656 * registers are read as QNaN and then exchanged. This could be
9657 * wrong... */
9658 if (pFpuCtx->FCW & X86_FCW_IM)
9659 {
9660 if (RT_BIT(iReg1) & pFpuCtx->FTW)
9661 {
9662 if (RT_BIT(iReg2) & pFpuCtx->FTW)
9663 iemFpuStoreQNan(&pFpuCtx->aRegs[0].r80);
9664 else
9665 pFpuCtx->aRegs[0].r80 = pFpuCtx->aRegs[iStReg].r80;
9666 iemFpuStoreQNan(&pFpuCtx->aRegs[iStReg].r80);
9667 }
9668 else
9669 {
9670 pFpuCtx->aRegs[iStReg].r80 = pFpuCtx->aRegs[0].r80;
9671 iemFpuStoreQNan(&pFpuCtx->aRegs[0].r80);
9672 }
9673 pFpuCtx->FSW &= ~X86_FSW_C_MASK;
9674 pFpuCtx->FSW |= X86_FSW_C1 | X86_FSW_IE | X86_FSW_SF;
9675 }
9676 else
9677 {
9678 /* raise underflow exception, don't change anything. */
9679 pFpuCtx->FSW &= ~(X86_FSW_TOP_MASK | X86_FSW_XCPT_MASK);
9680 pFpuCtx->FSW |= X86_FSW_C1 | X86_FSW_IE | X86_FSW_SF | X86_FSW_ES | X86_FSW_B;
9681 Log11(("fxch: %04x:%08RX64: Underflow exception (FSW=%#x)\n",
9682 pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pFpuCtx->FSW));
9683 }
9684
9685 iemFpuUpdateOpcodeAndIpWorkerEx(pVCpu, pFpuCtx, uFpuOpcode);
9686 iemHlpUsedFpu(pVCpu);
9687 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
9688}
9689
9690
9691/**
9692 * Implements 'FCOMI', 'FCOMIP', 'FUCOMI', and 'FUCOMIP'.
9693 *
9694 * @param iStReg The other stack register.
9695 * @param fUCmp true for FUCOMI[P], false for FCOMI[P].
9696 * @param uPopAndFpuOpcode Bits 15-0: The FPU opcode.
9697 * Bit 31: Whether we should pop the stack when
9698 * done or not.
9699 */
9700IEM_CIMPL_DEF_3(iemCImpl_fcomi_fucomi, uint8_t, iStReg, bool, fUCmp, uint32_t, uPopAndFpuOpcode)
9701{
9702 Assert(iStReg < 8);
9703 IEM_CTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_X87);
9704
9705 /*
9706 * Raise exceptions.
9707 */
9708 if (pVCpu->cpum.GstCtx.cr0 & (X86_CR0_EM | X86_CR0_TS))
9709 return iemRaiseDeviceNotAvailable(pVCpu);
9710
9711 PX86FXSTATE pFpuCtx = &pVCpu->cpum.GstCtx.XState.x87;
9712 uint16_t u16Fsw = pFpuCtx->FSW;
9713 if (u16Fsw & X86_FSW_ES)
9714 return iemRaiseMathFault(pVCpu);
9715
9716 /*
9717 * Check if any of the register accesses causes #SF + #IA.
9718 */
9719 bool fPop = RT_BOOL(uPopAndFpuOpcode & RT_BIT_32(31));
9720 unsigned const iReg1 = X86_FSW_TOP_GET(u16Fsw);
9721 unsigned const iReg2 = (iReg1 + iStReg) & X86_FSW_TOP_SMASK;
9722 if ((pFpuCtx->FTW & (RT_BIT(iReg1) | RT_BIT(iReg2))) == (RT_BIT(iReg1) | RT_BIT(iReg2)))
9723 {
9724 uint32_t u32Eflags;
9725 if (!fUCmp)
9726 u32Eflags = iemAImpl_fcomi_r80_by_r80(pFpuCtx, &u16Fsw, &pFpuCtx->aRegs[0].r80, &pFpuCtx->aRegs[iStReg].r80);
9727 else
9728 u32Eflags = iemAImpl_fucomi_r80_by_r80(pFpuCtx, &u16Fsw, &pFpuCtx->aRegs[0].r80, &pFpuCtx->aRegs[iStReg].r80);
9729
9730 pFpuCtx->FSW &= ~X86_FSW_C1;
9731 pFpuCtx->FSW |= u16Fsw & ~X86_FSW_TOP_MASK;
9732 if ( !(u16Fsw & X86_FSW_IE)
9733 || (pFpuCtx->FCW & X86_FCW_IM) )
9734 {
9735 pVCpu->cpum.GstCtx.eflags.u &= ~(X86_EFL_OF | X86_EFL_SF | X86_EFL_AF | X86_EFL_ZF | X86_EFL_PF | X86_EFL_CF);
9736 pVCpu->cpum.GstCtx.eflags.u |= u32Eflags & (X86_EFL_ZF | X86_EFL_PF | X86_EFL_CF);
9737 }
9738 }
9739 else if (pFpuCtx->FCW & X86_FCW_IM)
9740 {
9741 /* Masked underflow. */
9742 pFpuCtx->FSW &= ~X86_FSW_C1;
9743 pFpuCtx->FSW |= X86_FSW_IE | X86_FSW_SF;
9744 pVCpu->cpum.GstCtx.eflags.u &= ~(X86_EFL_OF | X86_EFL_SF | X86_EFL_AF | X86_EFL_ZF | X86_EFL_PF | X86_EFL_CF);
9745 pVCpu->cpum.GstCtx.eflags.u |= X86_EFL_ZF | X86_EFL_PF | X86_EFL_CF;
9746 }
9747 else
9748 {
9749 /* Raise underflow - don't touch EFLAGS or TOP. */
9750 pFpuCtx->FSW &= ~X86_FSW_C1;
9751 pFpuCtx->FSW |= X86_FSW_IE | X86_FSW_SF | X86_FSW_ES | X86_FSW_B;
9752 Log11(("fxch: %04x:%08RX64: Raising IE+SF exception (FSW=%#x)\n",
9753 pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pFpuCtx->FSW));
9754 fPop = false;
9755 }
9756
9757 /*
9758 * Pop if necessary.
9759 */
9760 if (fPop)
9761 {
9762 pFpuCtx->FTW &= ~RT_BIT(iReg1);
9763 iemFpuStackIncTop(pVCpu);
9764 }
9765
9766 iemFpuUpdateOpcodeAndIpWorkerEx(pVCpu, pFpuCtx, (uint16_t)uPopAndFpuOpcode);
9767 iemHlpUsedFpu(pVCpu);
9768 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
9769}
9770
9771
9772/**
9773 * Implements 'RDSEED'.
9774 *
9775 * @returns VINF_SUCCESS.
9776 * @param iReg The register.
9777 * @param enmEffOpSize The operand size.
9778 */
9779IEM_CIMPL_DEF_2(iemCImpl_rdseed, uint8_t, iReg, IEMMODE, enmEffOpSize)
9780{
9781#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
9782 /* Nested-guest VMX intercept. */
9783 if ( !IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
9784 || !IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_RDSEED_EXIT))
9785 { /* probable */ }
9786 else
9787 {
9788 Log(("rdseed: Guest intercept -> VM-exit\n"));
9789 IEM_VMX_VMEXIT_INSTR_NEEDS_INFO_RET(pVCpu, VMX_EXIT_RDSEED, VMXINSTRID_RDSEED, cbInstr);
9790 }
9791#endif
9792
9793 uint32_t *pEFlags = &pVCpu->cpum.GstCtx.eflags.uBoth;
9794 switch (enmEffOpSize)
9795 {
9796 case IEMMODE_16BIT:
9797 {
9798 PFNIEMAIMPLRDRANDSEEDU16 pfnImpl = IEM_SELECT_HOST_OR_FALLBACK(fRdSeed,
9799 &iemAImpl_rdseed_u16,
9800 &iemAImpl_rdseed_u16_fallback);
9801 uint16_t *pu16Dst = iemGRegRefU16(pVCpu, iReg);
9802 (pfnImpl)(pu16Dst, pEFlags);
9803 break;
9804 }
9805 case IEMMODE_32BIT:
9806 {
9807 PFNIEMAIMPLRDRANDSEEDU32 pfnImpl = IEM_SELECT_HOST_OR_FALLBACK(fRdSeed,
9808 &iemAImpl_rdseed_u32,
9809 &iemAImpl_rdseed_u32_fallback);
9810 uint32_t *pu32Dst = iemGRegRefU32(pVCpu, iReg);
9811 (pfnImpl)(pu32Dst, pEFlags);
9812 iemGRegStoreU32(pVCpu, iReg, *pu32Dst);
9813 break;
9814 }
9815 case IEMMODE_64BIT:
9816 {
9817 PFNIEMAIMPLRDRANDSEEDU64 pfnImpl = IEM_SELECT_HOST_OR_FALLBACK(fRdSeed,
9818 &iemAImpl_rdseed_u64,
9819 &iemAImpl_rdseed_u64_fallback);
9820 uint64_t *pu64Dst = iemGRegRefU64(pVCpu, iReg);
9821 (pfnImpl)(pu64Dst, pEFlags);
9822 break;
9823 }
9824 IEM_NOT_REACHED_DEFAULT_CASE_RET();
9825 }
9826 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
9827}
9828
9829
9830/**
9831 * Implements 'RDRAND'.
9832 *
9833 * @returns VINF_SUCCESS.
9834 * @param iReg The register.
9835 * @param enmEffOpSize The operand size.
9836 */
9837IEM_CIMPL_DEF_2(iemCImpl_rdrand, uint8_t, iReg, IEMMODE, enmEffOpSize)
9838{
9839#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
9840 /* Nested-guest VMX intercept. */
9841 if ( !IEM_VMX_IS_NON_ROOT_MODE(pVCpu)
9842 || !IEM_VMX_IS_PROCCTLS2_SET(pVCpu, VMX_PROC_CTLS2_RDRAND_EXIT))
9843 { /* probable */ }
9844 else
9845 {
9846 Log(("rdrand: Guest intercept -> VM-exit\n"));
9847 IEM_VMX_VMEXIT_INSTR_NEEDS_INFO_RET(pVCpu, VMX_EXIT_RDRAND, VMXINSTRID_RDRAND, cbInstr);
9848 }
9849#endif
9850
9851 uint32_t *pEFlags = &pVCpu->cpum.GstCtx.eflags.uBoth;
9852 switch (enmEffOpSize)
9853 {
9854 case IEMMODE_16BIT:
9855 {
9856 PFNIEMAIMPLRDRANDSEEDU16 pfnImpl = IEM_SELECT_HOST_OR_FALLBACK(fRdRand, &iemAImpl_rdrand_u16,
9857 &iemAImpl_rdrand_u16_fallback);
9858 uint16_t *pu16Dst = iemGRegRefU16(pVCpu, iReg);
9859 (pfnImpl)(pu16Dst, pEFlags);
9860 break;
9861 }
9862 case IEMMODE_32BIT:
9863 {
9864 PFNIEMAIMPLRDRANDSEEDU32 pfnImpl = IEM_SELECT_HOST_OR_FALLBACK(fRdRand, &iemAImpl_rdrand_u32,
9865 &iemAImpl_rdrand_u32_fallback);
9866 uint32_t *pu32Dst = iemGRegRefU32(pVCpu, iReg);
9867 (pfnImpl)(pu32Dst, pEFlags);
9868 iemGRegStoreU32(pVCpu, iReg, *pu32Dst);
9869 break;
9870 }
9871 case IEMMODE_64BIT:
9872 {
9873 PFNIEMAIMPLRDRANDSEEDU64 pfnImpl = IEM_SELECT_HOST_OR_FALLBACK(fRdRand, &iemAImpl_rdrand_u64,
9874 &iemAImpl_rdrand_u64_fallback);
9875 uint64_t *pu64Dst = iemGRegRefU64(pVCpu, iReg);
9876 (pfnImpl)(pu64Dst, pEFlags);
9877 break;
9878 }
9879 IEM_NOT_REACHED_DEFAULT_CASE_RET();
9880 }
9881 return iemRegAddToRipAndFinishingClearingRF(pVCpu, cbInstr);
9882}
9883
9884/** @} */
9885
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette