VirtualBox

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

Last change on this file since 97698 was 97694, checked in by vboxsync, 2 years ago

VMM/IEM: Added support for hardware instruction breakpoints (DRx). Corrected some DR6 updating for single stepping. bugref:9898

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