VirtualBox

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

最後變更 在這個檔案從99983是 99983,由 vboxsync 提交於 22 月 前

VMM/IEM: Removed (finally) the need to call CPUMGetGuestCPL and iemCalcCpuMode for every instruction when executing lots of them. bugref:10369

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

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