VirtualBox

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

Last change on this file since 100184 was 100108, checked in by vboxsync, 12 months ago

*: Fix build issues when setting VBOX_WITH_WARNINGS_AS_ERRORS=1 on darwin.arm64 and make it a default, bugref:10469

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

© 2023 Oracle
ContactPrivacy policyTerms of Use