VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR3/CSAM.cpp@ 41662

Last change on this file since 41662 was 41662, checked in by vboxsync, 12 years ago

DIS,CSAM: Combine the displacement members of OP_PARAMETER into a union to save a little bit of space.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 96.5 KB
Line 
1/* $Id: CSAM.cpp 41662 2012-06-12 08:29:07Z vboxsync $ */
2/** @file
3 * CSAM - Guest OS Code Scanning and Analysis Manager
4 */
5
6/*
7 * Copyright (C) 2006-2007 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/*******************************************************************************
19* Header Files *
20*******************************************************************************/
21#define LOG_GROUP LOG_GROUP_CSAM
22#include <VBox/vmm/cpum.h>
23#include <VBox/vmm/stam.h>
24#include <VBox/vmm/patm.h>
25#include <VBox/vmm/csam.h>
26#include <VBox/vmm/cpumdis.h>
27#include <VBox/vmm/pgm.h>
28#include <VBox/vmm/iom.h>
29#include <VBox/sup.h>
30#include <VBox/vmm/mm.h>
31#include <VBox/vmm/em.h>
32#ifdef VBOX_WITH_REM
33# include <VBox/vmm/rem.h>
34#endif
35#include <VBox/vmm/selm.h>
36#include <VBox/vmm/trpm.h>
37#include <VBox/vmm/cfgm.h>
38#include <VBox/param.h>
39#include <iprt/avl.h>
40#include <iprt/asm.h>
41#include <iprt/thread.h>
42#include "CSAMInternal.h"
43#include <VBox/vmm/vm.h>
44#include <VBox/dbg.h>
45#include <VBox/err.h>
46#include <VBox/vmm/ssm.h>
47#include <VBox/log.h>
48#include <iprt/assert.h>
49#include <iprt/string.h>
50#include <VBox/dis.h>
51#include <VBox/disopcode.h>
52#include "internal/pgm.h"
53
54
55/* Enabled by default */
56#define CSAM_ENABLE
57
58/* Enable to monitor code pages for self-modifying code. */
59#define CSAM_MONITOR_CODE_PAGES
60/* Enable to monitor all scanned pages
61#define CSAM_MONITOR_CSAM_CODE_PAGES */
62/* Enable to scan beyond ret instructions.
63#define CSAM_ANALYSE_BEYOND_RET */
64
65/*******************************************************************************
66* Internal Functions *
67*******************************************************************************/
68static DECLCALLBACK(int) csamr3Save(PVM pVM, PSSMHANDLE pSSM);
69static DECLCALLBACK(int) csamr3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass);
70static DECLCALLBACK(int) CSAMCodePageWriteHandler(PVM pVM, RTGCPTR GCPtr, void *pvPtr, void *pvBuf, size_t cbBuf, PGMACCESSTYPE enmAccessType, void *pvUser);
71static DECLCALLBACK(int) CSAMCodePageInvalidate(PVM pVM, RTGCPTR GCPtr);
72
73bool csamIsCodeScanned(PVM pVM, RTRCPTR pInstr, PCSAMPAGE *pPage);
74int csamR3CheckPageRecord(PVM pVM, RTRCPTR pInstr);
75static PCSAMPAGE csamCreatePageRecord(PVM pVM, RTRCPTR GCPtr, CSAMTAG enmTag, bool fCode32, bool fMonitorInvalidation = false);
76static int csamRemovePageRecord(PVM pVM, RTRCPTR GCPtr);
77static int csamReinit(PVM pVM);
78static void csamMarkCode(PVM pVM, PCSAMPAGE pPage, RTRCPTR pInstr, uint32_t opsize, bool fScanned);
79static int csamAnalyseCodeStream(PVM pVM, RCPTRTYPE(uint8_t *) pInstrGC, RCPTRTYPE(uint8_t *) pCurInstrGC, bool fCode32,
80 PFN_CSAMR3ANALYSE pfnCSAMR3Analyse, void *pUserData, PCSAMP2GLOOKUPREC pCacheRec);
81
82/** @todo Temporary for debugging. */
83static bool fInCSAMCodePageInvalidate = false;
84
85/*******************************************************************************
86* Global Variables *
87*******************************************************************************/
88#ifdef VBOX_WITH_DEBUGGER
89static DECLCALLBACK(int) csamr3CmdOn(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PVM pVM, PCDBGCVAR paArgs, unsigned cArgs);
90static DECLCALLBACK(int) csamr3CmdOff(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PVM pVM, PCDBGCVAR paArgs, unsigned cArgs);
91
92/** Command descriptors. */
93static const DBGCCMD g_aCmds[] =
94{
95 /* pszCmd, cArgsMin, cArgsMax, paArgDesc, cArgDescs, fFlags, pfnHandler pszSyntax, ....pszDescription */
96 { "csamon", 0, 0, NULL, 0, 0, csamr3CmdOn, "", "Enable CSAM code scanning." },
97 { "csamoff", 0, 0, NULL, 0, 0, csamr3CmdOff, "", "Disable CSAM code scanning." },
98};
99#endif
100
101/**
102 * SSM descriptor table for the CSAM structure.
103 */
104static const SSMFIELD g_aCsamFields[] =
105{
106 /** @todo there are more fields that can be ignored here. */
107 SSMFIELD_ENTRY_IGNORE( CSAM, offVM),
108 SSMFIELD_ENTRY_PAD_HC64( CSAM, Alignment0, sizeof(uint32_t)),
109 SSMFIELD_ENTRY_IGN_HCPTR( CSAM, pPageTree),
110 SSMFIELD_ENTRY( CSAM, aDangerousInstr),
111 SSMFIELD_ENTRY( CSAM, cDangerousInstr),
112 SSMFIELD_ENTRY( CSAM, iDangerousInstr),
113 SSMFIELD_ENTRY_RCPTR( CSAM, pPDBitmapGC), /// @todo ignore this?
114 SSMFIELD_ENTRY_RCPTR( CSAM, pPDHCBitmapGC), /// @todo ignore this?
115 SSMFIELD_ENTRY_IGN_HCPTR( CSAM, pPDBitmapHC),
116 SSMFIELD_ENTRY_IGN_HCPTR( CSAM, pPDGCBitmapHC),
117 SSMFIELD_ENTRY_IGN_HCPTR( CSAM, savedstate.pSSM),
118 SSMFIELD_ENTRY( CSAM, savedstate.cPageRecords),
119 SSMFIELD_ENTRY( CSAM, savedstate.cPatchPageRecords),
120 SSMFIELD_ENTRY( CSAM, cDirtyPages),
121 SSMFIELD_ENTRY_RCPTR_ARRAY( CSAM, pvDirtyBasePage),
122 SSMFIELD_ENTRY_RCPTR_ARRAY( CSAM, pvDirtyFaultPage),
123 SSMFIELD_ENTRY( CSAM, cPossibleCodePages),
124 SSMFIELD_ENTRY_RCPTR_ARRAY( CSAM, pvPossibleCodePage),
125 SSMFIELD_ENTRY_RCPTR_ARRAY( CSAM, pvCallInstruction),
126 SSMFIELD_ENTRY( CSAM, iCallInstruction),
127 SSMFIELD_ENTRY( CSAM, fScanningStarted),
128 SSMFIELD_ENTRY( CSAM, fGatesChecked),
129 SSMFIELD_ENTRY_PAD_HC( CSAM, Alignment1, 6, 2),
130 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrTraps),
131 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrPages),
132 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrPagesInv),
133 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrRemovedPages),
134 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrPatchPages),
135 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrPageNPHC),
136 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrPageNPGC),
137 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrFlushes),
138 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrFlushesSkipped),
139 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrKnownPagesHC),
140 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrKnownPagesGC),
141 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrInstr),
142 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrBytesRead),
143 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrOpcodeRead),
144 SSMFIELD_ENTRY_IGNORE( CSAM, StatTime),
145 SSMFIELD_ENTRY_IGNORE( CSAM, StatTimeCheckAddr),
146 SSMFIELD_ENTRY_IGNORE( CSAM, StatTimeAddrConv),
147 SSMFIELD_ENTRY_IGNORE( CSAM, StatTimeFlushPage),
148 SSMFIELD_ENTRY_IGNORE( CSAM, StatTimeDisasm),
149 SSMFIELD_ENTRY_IGNORE( CSAM, StatFlushDirtyPages),
150 SSMFIELD_ENTRY_IGNORE( CSAM, StatCheckGates),
151 SSMFIELD_ENTRY_IGNORE( CSAM, StatCodePageModified),
152 SSMFIELD_ENTRY_IGNORE( CSAM, StatDangerousWrite),
153 SSMFIELD_ENTRY_IGNORE( CSAM, StatInstrCacheHit),
154 SSMFIELD_ENTRY_IGNORE( CSAM, StatInstrCacheMiss),
155 SSMFIELD_ENTRY_IGNORE( CSAM, StatPagePATM),
156 SSMFIELD_ENTRY_IGNORE( CSAM, StatPageCSAM),
157 SSMFIELD_ENTRY_IGNORE( CSAM, StatPageREM),
158 SSMFIELD_ENTRY_IGNORE( CSAM, StatNrUserPages),
159 SSMFIELD_ENTRY_IGNORE( CSAM, StatPageMonitor),
160 SSMFIELD_ENTRY_IGNORE( CSAM, StatPageRemoveREMFlush),
161 SSMFIELD_ENTRY_IGNORE( CSAM, StatBitmapAlloc),
162 SSMFIELD_ENTRY_IGNORE( CSAM, StatScanNextFunction),
163 SSMFIELD_ENTRY_IGNORE( CSAM, StatScanNextFunctionFailed),
164 SSMFIELD_ENTRY_TERM()
165};
166
167/** Fake type to simplify g_aCsamPDBitmapArray construction. */
168typedef struct
169{
170 uint8_t *a[CSAM_PGDIRBMP_CHUNKS];
171} CSAMPDBITMAPARRAY;
172
173/**
174 * SSM descriptor table for the CSAM::pPDBitmapHC array.
175 */
176static SSMFIELD const g_aCsamPDBitmapArray[] =
177{
178 SSMFIELD_ENTRY_HCPTR_NI_ARRAY(CSAMPDBITMAPARRAY, a),
179 SSMFIELD_ENTRY_TERM()
180};
181
182/**
183 * SSM descriptor table for the CSAMPAGEREC structure.
184 */
185static const SSMFIELD g_aCsamPageRecFields[] =
186{
187 SSMFIELD_ENTRY_IGN_HCPTR( CSAMPAGEREC, Core.Key),
188 SSMFIELD_ENTRY_IGN_HCPTR( CSAMPAGEREC, Core.pLeft),
189 SSMFIELD_ENTRY_IGN_HCPTR( CSAMPAGEREC, Core.pRight),
190 SSMFIELD_ENTRY_IGNORE( CSAMPAGEREC, Core.uchHeight),
191 SSMFIELD_ENTRY_PAD_HC_AUTO( 3, 7),
192 SSMFIELD_ENTRY_RCPTR( CSAMPAGEREC, page.pPageGC),
193 SSMFIELD_ENTRY_PAD_HC_AUTO( 0, 4),
194 SSMFIELD_ENTRY_PAD_MSC32_AUTO( 4),
195 SSMFIELD_ENTRY_GCPHYS( CSAMPAGEREC, page.GCPhys),
196 SSMFIELD_ENTRY( CSAMPAGEREC, page.fFlags),
197 SSMFIELD_ENTRY( CSAMPAGEREC, page.uSize),
198 SSMFIELD_ENTRY_PAD_HC_AUTO( 0, 4),
199 SSMFIELD_ENTRY_HCPTR_NI( CSAMPAGEREC, page.pBitmap),
200 SSMFIELD_ENTRY( CSAMPAGEREC, page.fCode32),
201 SSMFIELD_ENTRY( CSAMPAGEREC, page.fMonitorActive),
202 SSMFIELD_ENTRY( CSAMPAGEREC, page.fMonitorInvalidation),
203 SSMFIELD_ENTRY_PAD_HC_AUTO( 1, 1),
204 SSMFIELD_ENTRY( CSAMPAGEREC, page.enmTag),
205 SSMFIELD_ENTRY( CSAMPAGEREC, page.u64Hash),
206 SSMFIELD_ENTRY_TERM()
207};
208
209
210/**
211 * Initializes the CSAM.
212 *
213 * @returns VBox status code.
214 * @param pVM The VM to operate on.
215 */
216VMMR3DECL(int) CSAMR3Init(PVM pVM)
217{
218 int rc;
219
220 LogFlow(("CSAMR3Init\n"));
221
222 /* Allocate bitmap for the page directory. */
223 rc = MMR3HyperAllocOnceNoRel(pVM, CSAM_PGDIRBMP_CHUNKS*sizeof(RTHCPTR), 0, MM_TAG_CSAM, (void **)&pVM->csam.s.pPDBitmapHC);
224 AssertRCReturn(rc, rc);
225 rc = MMR3HyperAllocOnceNoRel(pVM, CSAM_PGDIRBMP_CHUNKS*sizeof(RTRCPTR), 0, MM_TAG_CSAM, (void **)&pVM->csam.s.pPDGCBitmapHC);
226 AssertRCReturn(rc, rc);
227 pVM->csam.s.pPDBitmapGC = MMHyperR3ToRC(pVM, pVM->csam.s.pPDGCBitmapHC);
228 pVM->csam.s.pPDHCBitmapGC = MMHyperR3ToRC(pVM, pVM->csam.s.pPDBitmapHC);
229
230 rc = csamReinit(pVM);
231 AssertRCReturn(rc, rc);
232
233 /*
234 * Register save and load state notifiers.
235 */
236 rc = SSMR3RegisterInternal(pVM, "CSAM", 0, CSAM_SSM_VERSION, sizeof(pVM->csam.s) + PAGE_SIZE*16,
237 NULL, NULL, NULL,
238 NULL, csamr3Save, NULL,
239 NULL, csamr3Load, NULL);
240 AssertRCReturn(rc, rc);
241
242 STAM_REG(pVM, &pVM->csam.s.StatNrTraps, STAMTYPE_COUNTER, "/CSAM/PageTraps", STAMUNIT_OCCURENCES, "The number of CSAM page traps.");
243 STAM_REG(pVM, &pVM->csam.s.StatDangerousWrite, STAMTYPE_COUNTER, "/CSAM/DangerousWrites", STAMUNIT_OCCURENCES, "The number of dangerous writes that cause a context switch.");
244
245 STAM_REG(pVM, &pVM->csam.s.StatNrPageNPHC, STAMTYPE_COUNTER, "/CSAM/HC/PageNotPresent", STAMUNIT_OCCURENCES, "The number of CSAM pages marked not present.");
246 STAM_REG(pVM, &pVM->csam.s.StatNrPageNPGC, STAMTYPE_COUNTER, "/CSAM/GC/PageNotPresent", STAMUNIT_OCCURENCES, "The number of CSAM pages marked not present.");
247 STAM_REG(pVM, &pVM->csam.s.StatNrPages, STAMTYPE_COUNTER, "/CSAM/PageRec/AddedRW", STAMUNIT_OCCURENCES, "The number of CSAM page records (RW monitoring).");
248 STAM_REG(pVM, &pVM->csam.s.StatNrPagesInv, STAMTYPE_COUNTER, "/CSAM/PageRec/AddedRWI", STAMUNIT_OCCURENCES, "The number of CSAM page records (RW & invalidation monitoring).");
249 STAM_REG(pVM, &pVM->csam.s.StatNrRemovedPages, STAMTYPE_COUNTER, "/CSAM/PageRec/Removed", STAMUNIT_OCCURENCES, "The number of removed CSAM page records.");
250 STAM_REG(pVM, &pVM->csam.s.StatPageRemoveREMFlush,STAMTYPE_COUNTER, "/CSAM/PageRec/Removed/REMFlush", STAMUNIT_OCCURENCES, "The number of removed CSAM page records that caused a REM flush.");
251
252 STAM_REG(pVM, &pVM->csam.s.StatNrPatchPages, STAMTYPE_COUNTER, "/CSAM/PageRec/Patch", STAMUNIT_OCCURENCES, "The number of CSAM patch page records.");
253 STAM_REG(pVM, &pVM->csam.s.StatNrUserPages, STAMTYPE_COUNTER, "/CSAM/PageRec/Ignore/User", STAMUNIT_OCCURENCES, "The number of CSAM user page records (ignored).");
254 STAM_REG(pVM, &pVM->csam.s.StatPagePATM, STAMTYPE_COUNTER, "/CSAM/PageRec/Type/PATM", STAMUNIT_OCCURENCES, "The number of PATM page records.");
255 STAM_REG(pVM, &pVM->csam.s.StatPageCSAM, STAMTYPE_COUNTER, "/CSAM/PageRec/Type/CSAM", STAMUNIT_OCCURENCES, "The number of CSAM page records.");
256 STAM_REG(pVM, &pVM->csam.s.StatPageREM, STAMTYPE_COUNTER, "/CSAM/PageRec/Type/REM", STAMUNIT_OCCURENCES, "The number of REM page records.");
257 STAM_REG(pVM, &pVM->csam.s.StatPageMonitor, STAMTYPE_COUNTER, "/CSAM/PageRec/Monitored", STAMUNIT_OCCURENCES, "The number of monitored pages.");
258
259 STAM_REG(pVM, &pVM->csam.s.StatCodePageModified, STAMTYPE_COUNTER, "/CSAM/Monitor/DirtyPage", STAMUNIT_OCCURENCES, "The number of code page modifications.");
260
261 STAM_REG(pVM, &pVM->csam.s.StatNrFlushes, STAMTYPE_COUNTER, "/CSAM/PageFlushes", STAMUNIT_OCCURENCES, "The number of CSAM page flushes.");
262 STAM_REG(pVM, &pVM->csam.s.StatNrFlushesSkipped, STAMTYPE_COUNTER, "/CSAM/PageFlushesSkipped", STAMUNIT_OCCURENCES, "The number of CSAM page flushes that were skipped.");
263 STAM_REG(pVM, &pVM->csam.s.StatNrKnownPagesHC, STAMTYPE_COUNTER, "/CSAM/HC/KnownPageRecords", STAMUNIT_OCCURENCES, "The number of known CSAM page records.");
264 STAM_REG(pVM, &pVM->csam.s.StatNrKnownPagesGC, STAMTYPE_COUNTER, "/CSAM/GC/KnownPageRecords", STAMUNIT_OCCURENCES, "The number of known CSAM page records.");
265 STAM_REG(pVM, &pVM->csam.s.StatNrInstr, STAMTYPE_COUNTER, "/CSAM/ScannedInstr", STAMUNIT_OCCURENCES, "The number of scanned instructions.");
266 STAM_REG(pVM, &pVM->csam.s.StatNrBytesRead, STAMTYPE_COUNTER, "/CSAM/BytesRead", STAMUNIT_OCCURENCES, "The number of bytes read for scanning.");
267 STAM_REG(pVM, &pVM->csam.s.StatNrOpcodeRead, STAMTYPE_COUNTER, "/CSAM/OpcodeBytesRead", STAMUNIT_OCCURENCES, "The number of opcode bytes read by the recompiler.");
268
269 STAM_REG(pVM, &pVM->csam.s.StatBitmapAlloc, STAMTYPE_COUNTER, "/CSAM/Alloc/PageBitmap", STAMUNIT_OCCURENCES, "The number of page bitmap allocations.");
270
271 STAM_REG(pVM, &pVM->csam.s.StatInstrCacheHit, STAMTYPE_COUNTER, "/CSAM/Cache/Hit", STAMUNIT_OCCURENCES, "The number of dangerous instruction cache hits.");
272 STAM_REG(pVM, &pVM->csam.s.StatInstrCacheMiss, STAMTYPE_COUNTER, "/CSAM/Cache/Miss", STAMUNIT_OCCURENCES, "The number of dangerous instruction cache misses.");
273
274 STAM_REG(pVM, &pVM->csam.s.StatScanNextFunction, STAMTYPE_COUNTER, "/CSAM/Function/Scan/Success", STAMUNIT_OCCURENCES, "The number of found functions beyond the ret border.");
275 STAM_REG(pVM, &pVM->csam.s.StatScanNextFunctionFailed, STAMTYPE_COUNTER, "/CSAM/Function/Scan/Failed", STAMUNIT_OCCURENCES, "The number of refused functions beyond the ret border.");
276
277 STAM_REG(pVM, &pVM->csam.s.StatTime, STAMTYPE_PROFILE, "/PROF/CSAM/Scan", STAMUNIT_TICKS_PER_CALL, "Scanning overhead.");
278 STAM_REG(pVM, &pVM->csam.s.StatTimeCheckAddr, STAMTYPE_PROFILE, "/PROF/CSAM/CheckAddr", STAMUNIT_TICKS_PER_CALL, "Address check overhead.");
279 STAM_REG(pVM, &pVM->csam.s.StatTimeAddrConv, STAMTYPE_PROFILE, "/PROF/CSAM/AddrConv", STAMUNIT_TICKS_PER_CALL, "Address conversion overhead.");
280 STAM_REG(pVM, &pVM->csam.s.StatTimeFlushPage, STAMTYPE_PROFILE, "/PROF/CSAM/FlushPage", STAMUNIT_TICKS_PER_CALL, "Page flushing overhead.");
281 STAM_REG(pVM, &pVM->csam.s.StatTimeDisasm, STAMTYPE_PROFILE, "/PROF/CSAM/Disasm", STAMUNIT_TICKS_PER_CALL, "Disassembly overhead.");
282 STAM_REG(pVM, &pVM->csam.s.StatFlushDirtyPages, STAMTYPE_PROFILE, "/PROF/CSAM/FlushDirtyPage", STAMUNIT_TICKS_PER_CALL, "Dirty page flushing overhead.");
283 STAM_REG(pVM, &pVM->csam.s.StatCheckGates, STAMTYPE_PROFILE, "/PROF/CSAM/CheckGates", STAMUNIT_TICKS_PER_CALL, "CSAMR3CheckGates overhead.");
284
285 /*
286 * Check CFGM option and enable/disable CSAM.
287 */
288 bool fEnabled;
289 rc = CFGMR3QueryBool(CFGMR3GetRoot(pVM), "CSAMEnabled", &fEnabled);
290 if (RT_FAILURE(rc))
291#ifdef CSAM_ENABLE
292 fEnabled = true;
293#else
294 fEnabled = false;
295#endif
296 if (fEnabled)
297 CSAMEnableScanning(pVM);
298
299#ifdef VBOX_WITH_DEBUGGER
300 /*
301 * Debugger commands.
302 */
303 static bool fRegisteredCmds = false;
304 if (!fRegisteredCmds)
305 {
306 rc = DBGCRegisterCommands(&g_aCmds[0], RT_ELEMENTS(g_aCmds));
307 if (RT_SUCCESS(rc))
308 fRegisteredCmds = true;
309 }
310#endif
311
312 return VINF_SUCCESS;
313}
314
315/**
316 * (Re)initializes CSAM
317 *
318 * @param pVM The VM.
319 */
320static int csamReinit(PVM pVM)
321{
322 /*
323 * Assert alignment and sizes.
324 */
325 AssertRelease(!(RT_OFFSETOF(VM, csam.s) & 31));
326 AssertRelease(sizeof(pVM->csam.s) <= sizeof(pVM->csam.padding));
327
328 /*
329 * Setup any fixed pointers and offsets.
330 */
331 pVM->csam.s.offVM = RT_OFFSETOF(VM, patm);
332
333 pVM->csam.s.fGatesChecked = false;
334 pVM->csam.s.fScanningStarted = false;
335
336 PVMCPU pVCpu = &pVM->aCpus[0]; /* raw mode implies 1 VPCU */
337 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_CSAM_PENDING_ACTION);
338 pVM->csam.s.cDirtyPages = 0;
339 /* not necessary */
340 memset(pVM->csam.s.pvDirtyBasePage, 0, sizeof(pVM->csam.s.pvDirtyBasePage));
341 memset(pVM->csam.s.pvDirtyFaultPage, 0, sizeof(pVM->csam.s.pvDirtyFaultPage));
342
343 memset(&pVM->csam.s.aDangerousInstr, 0, sizeof(pVM->csam.s.aDangerousInstr));
344 pVM->csam.s.cDangerousInstr = 0;
345 pVM->csam.s.iDangerousInstr = 0;
346
347 memset(pVM->csam.s.pvCallInstruction, 0, sizeof(pVM->csam.s.pvCallInstruction));
348 pVM->csam.s.iCallInstruction = 0;
349
350 /** @note never mess with the pgdir bitmap here! */
351 return VINF_SUCCESS;
352}
353
354/**
355 * Applies relocations to data and code managed by this
356 * component. This function will be called at init and
357 * whenever the VMM need to relocate itself inside the GC.
358 *
359 * The csam will update the addresses used by the switcher.
360 *
361 * @param pVM The VM.
362 * @param offDelta Relocation delta.
363 */
364VMMR3DECL(void) CSAMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
365{
366 if (offDelta)
367 {
368 /* Adjust pgdir and page bitmap pointers. */
369 pVM->csam.s.pPDBitmapGC = MMHyperR3ToRC(pVM, pVM->csam.s.pPDGCBitmapHC);
370 pVM->csam.s.pPDHCBitmapGC = MMHyperR3ToRC(pVM, pVM->csam.s.pPDBitmapHC);
371
372 for(int i=0;i<CSAM_PGDIRBMP_CHUNKS;i++)
373 {
374 if (pVM->csam.s.pPDGCBitmapHC[i])
375 {
376 pVM->csam.s.pPDGCBitmapHC[i] += offDelta;
377 }
378 }
379 }
380 return;
381}
382
383/**
384 * Terminates the csam.
385 *
386 * Termination means cleaning up and freeing all resources,
387 * the VM it self is at this point powered off or suspended.
388 *
389 * @returns VBox status code.
390 * @param pVM The VM to operate on.
391 */
392VMMR3DECL(int) CSAMR3Term(PVM pVM)
393{
394 int rc;
395
396 rc = CSAMR3Reset(pVM);
397 AssertRC(rc);
398
399 /* @todo triggers assertion in MMHyperFree */
400#if 0
401 for(int i=0;i<CSAM_PAGEBMP_CHUNKS;i++)
402 {
403 if (pVM->csam.s.pPDBitmapHC[i])
404 MMHyperFree(pVM, pVM->csam.s.pPDBitmapHC[i]);
405 }
406#endif
407
408 return VINF_SUCCESS;
409}
410
411/**
412 * CSAM reset callback.
413 *
414 * @returns VBox status code.
415 * @param pVM The VM which is reset.
416 */
417VMMR3DECL(int) CSAMR3Reset(PVM pVM)
418{
419 /* Clear page bitmaps. */
420 for(int i=0;i<CSAM_PGDIRBMP_CHUNKS;i++)
421 {
422 if (pVM->csam.s.pPDBitmapHC[i])
423 {
424 Assert((CSAM_PAGE_BITMAP_SIZE& 3) == 0);
425 ASMMemZero32(pVM->csam.s.pPDBitmapHC[i], CSAM_PAGE_BITMAP_SIZE);
426 }
427 }
428
429 /* Remove all CSAM page records. */
430 while(true)
431 {
432 PCSAMPAGEREC pPageRec = (PCSAMPAGEREC)RTAvlPVGetBestFit(&pVM->csam.s.pPageTree, 0, true);
433 if (pPageRec)
434 {
435 csamRemovePageRecord(pVM, pPageRec->page.pPageGC);
436 }
437 else
438 break;
439 }
440 Assert(!pVM->csam.s.pPageTree);
441
442 csamReinit(pVM);
443
444 return VINF_SUCCESS;
445}
446
447
448/**
449 * Callback function for RTAvlPVDoWithAll
450 *
451 * Counts the number of records in the tree
452 *
453 * @returns VBox status code.
454 * @param pNode Current node
455 * @param pcPatches Pointer to patch counter
456 */
457static DECLCALLBACK(int) CountRecord(PAVLPVNODECORE pNode, void *pcPatches)
458{
459 NOREF(pNode);
460 *(uint32_t *)pcPatches = *(uint32_t *)pcPatches + 1;
461 return VINF_SUCCESS;
462}
463
464/**
465 * Callback function for RTAvlPVDoWithAll
466 *
467 * Saves the state of the page record
468 *
469 * @returns VBox status code.
470 * @param pNode Current node
471 * @param pVM1 VM Handle
472 */
473static DECLCALLBACK(int) SavePageState(PAVLPVNODECORE pNode, void *pVM1)
474{
475 PVM pVM = (PVM)pVM1;
476 PCSAMPAGEREC pPage = (PCSAMPAGEREC)pNode;
477 CSAMPAGEREC page = *pPage;
478 PSSMHANDLE pSSM = pVM->csam.s.savedstate.pSSM;
479 int rc;
480
481 /* Save the page record itself */
482 rc = SSMR3PutMem(pSSM, &page, sizeof(page));
483 AssertRCReturn(rc, rc);
484
485 if (page.page.pBitmap)
486 {
487 rc = SSMR3PutMem(pSSM, page.page.pBitmap, CSAM_PAGE_BITMAP_SIZE);
488 AssertRCReturn(rc, rc);
489 }
490
491 return VINF_SUCCESS;
492}
493
494/**
495 * Execute state save operation.
496 *
497 * @returns VBox status code.
498 * @param pVM VM Handle.
499 * @param pSSM SSM operation handle.
500 */
501static DECLCALLBACK(int) csamr3Save(PVM pVM, PSSMHANDLE pSSM)
502{
503 CSAM csamInfo = pVM->csam.s;
504 int rc;
505
506 /*
507 * Count the number of page records in the tree (feeling lazy)
508 */
509 csamInfo.savedstate.cPageRecords = 0;
510 RTAvlPVDoWithAll(&pVM->csam.s.pPageTree, true, CountRecord, &csamInfo.savedstate.cPageRecords);
511
512 /*
513 * Save CSAM structure
514 */
515 pVM->csam.s.savedstate.pSSM = pSSM;
516 rc = SSMR3PutMem(pSSM, &csamInfo, sizeof(csamInfo));
517 AssertRCReturn(rc, rc);
518
519 /* Save pgdir bitmap */
520 rc = SSMR3PutMem(pSSM, csamInfo.pPDBitmapHC, CSAM_PGDIRBMP_CHUNKS*sizeof(RTHCPTR));
521 AssertRCReturn(rc, rc);
522
523 for (unsigned i=0;i<CSAM_PGDIRBMP_CHUNKS;i++)
524 {
525 if(csamInfo.pPDBitmapHC[i])
526 {
527 /* Save the page bitmap. */
528 rc = SSMR3PutMem(pSSM, csamInfo.pPDBitmapHC[i], CSAM_PAGE_BITMAP_SIZE);
529 AssertRCReturn(rc, rc);
530 }
531 }
532
533 /*
534 * Save page records
535 */
536 rc = RTAvlPVDoWithAll(&pVM->csam.s.pPageTree, true, SavePageState, pVM);
537 AssertRCReturn(rc, rc);
538
539 /** @note we don't restore aDangerousInstr; it will be recreated automatically. */
540 return VINF_SUCCESS;
541}
542
543/**
544 * Execute state load operation.
545 *
546 * @returns VBox status code.
547 * @param pVM VM Handle.
548 * @param pSSM SSM operation handle.
549 * @param uVersion Data layout version.
550 * @param uPass The data pass.
551 */
552static DECLCALLBACK(int) csamr3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
553{
554 int rc;
555 CSAM csamInfo;
556
557 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
558 if (uVersion != CSAM_SSM_VERSION)
559 {
560 AssertMsgFailed(("csamR3Load: Invalid version uVersion=%d!\n", uVersion));
561 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
562 }
563
564 pVM->csam.s.savedstate.pSSM = pSSM;
565
566 /*
567 * Restore CSAM structure
568 */
569#if 0
570 rc = SSMR3GetMem(pSSM, &csamInfo, sizeof(csamInfo));
571#else
572 RT_ZERO(csamInfo);
573 rc = SSMR3GetStructEx(pSSM, &csamInfo, sizeof(csamInfo), SSMSTRUCT_FLAGS_MEM_BAND_AID, &g_aCsamFields[0], NULL);
574#endif
575 AssertRCReturn(rc, rc);
576
577 pVM->csam.s.fGatesChecked = csamInfo.fGatesChecked;
578 pVM->csam.s.fScanningStarted = csamInfo.fScanningStarted;
579
580 /* Restore dirty code page info. */
581 pVM->csam.s.cDirtyPages = csamInfo.cDirtyPages;
582 memcpy(pVM->csam.s.pvDirtyBasePage, csamInfo.pvDirtyBasePage, sizeof(pVM->csam.s.pvDirtyBasePage));
583 memcpy(pVM->csam.s.pvDirtyFaultPage, csamInfo.pvDirtyFaultPage, sizeof(pVM->csam.s.pvDirtyFaultPage));
584
585 /* Restore possible code page */
586 pVM->csam.s.cPossibleCodePages = csamInfo.cPossibleCodePages;
587 memcpy(pVM->csam.s.pvPossibleCodePage, csamInfo.pvPossibleCodePage, sizeof(pVM->csam.s.pvPossibleCodePage));
588
589 /* Restore pgdir bitmap (we'll change the pointers next). */
590#if 0
591 rc = SSMR3GetMem(pSSM, pVM->csam.s.pPDBitmapHC, CSAM_PGDIRBMP_CHUNKS*sizeof(RTHCPTR));
592#else
593 rc = SSMR3GetStructEx(pSSM, pVM->csam.s.pPDBitmapHC, sizeof(uint8_t *) * CSAM_PGDIRBMP_CHUNKS,
594 SSMSTRUCT_FLAGS_MEM_BAND_AID, &g_aCsamPDBitmapArray[0], NULL);
595#endif
596 AssertRCReturn(rc, rc);
597
598 /*
599 * Restore page bitmaps
600 */
601 for (unsigned i=0;i<CSAM_PGDIRBMP_CHUNKS;i++)
602 {
603 if(pVM->csam.s.pPDBitmapHC[i])
604 {
605 rc = MMHyperAlloc(pVM, CSAM_PAGE_BITMAP_SIZE, 0, MM_TAG_CSAM, (void **)&pVM->csam.s.pPDBitmapHC[i]);
606 if (RT_FAILURE(rc))
607 {
608 Log(("MMHyperAlloc failed with %Rrc\n", rc));
609 return rc;
610 }
611 /* Convert to GC pointer. */
612 pVM->csam.s.pPDGCBitmapHC[i] = MMHyperR3ToRC(pVM, pVM->csam.s.pPDBitmapHC[i]);
613 Assert(pVM->csam.s.pPDGCBitmapHC[i]);
614
615 /* Restore the bitmap. */
616 rc = SSMR3GetMem(pSSM, pVM->csam.s.pPDBitmapHC[i], CSAM_PAGE_BITMAP_SIZE);
617 AssertRCReturn(rc, rc);
618 }
619 else
620 {
621 Assert(!pVM->csam.s.pPDGCBitmapHC[i]);
622 pVM->csam.s.pPDGCBitmapHC[i] = 0;
623 }
624 }
625
626 /*
627 * Restore page records
628 */
629 for (uint32_t i=0;i<csamInfo.savedstate.cPageRecords + csamInfo.savedstate.cPatchPageRecords;i++)
630 {
631 CSAMPAGEREC page;
632 PCSAMPAGE pPage;
633
634#if 0
635 rc = SSMR3GetMem(pSSM, &page, sizeof(page));
636#else
637 RT_ZERO(page);
638 rc = SSMR3GetStructEx(pSSM, &page, sizeof(page), SSMSTRUCT_FLAGS_MEM_BAND_AID, &g_aCsamPageRecFields[0], NULL);
639#endif
640 AssertRCReturn(rc, rc);
641
642 /*
643 * Recreate the page record
644 */
645 pPage = csamCreatePageRecord(pVM, page.page.pPageGC, page.page.enmTag, page.page.fCode32, page.page.fMonitorInvalidation);
646 AssertReturn(pPage, VERR_NO_MEMORY);
647
648 pPage->GCPhys = page.page.GCPhys;
649 pPage->fFlags = page.page.fFlags;
650 pPage->u64Hash = page.page.u64Hash;
651
652 if (page.page.pBitmap)
653 {
654 rc = SSMR3GetMem(pSSM, pPage->pBitmap, CSAM_PAGE_BITMAP_SIZE);
655 AssertRCReturn(rc, rc);
656 }
657 else
658 {
659 MMR3HeapFree(pPage->pBitmap);
660 pPage->pBitmap = 0;
661 }
662 }
663
664 /* Note: we don't restore aDangerousInstr; it will be recreated automatically. */
665 memset(&pVM->csam.s.aDangerousInstr, 0, sizeof(pVM->csam.s.aDangerousInstr));
666 pVM->csam.s.cDangerousInstr = 0;
667 pVM->csam.s.iDangerousInstr = 0;
668 return VINF_SUCCESS;
669}
670
671/**
672 * Convert guest context address to host context pointer
673 *
674 * @returns VBox status code.
675 * @param pVM The VM to operate on.
676 * @param pCacheRec Address conversion cache record
677 * @param pGCPtr Guest context pointer
678 * @returns Host context pointer or NULL in case of an error
679 *
680 */
681static R3PTRTYPE(void *) CSAMGCVirtToHCVirt(PVM pVM, PCSAMP2GLOOKUPREC pCacheRec, RCPTRTYPE(uint8_t *) pGCPtr)
682{
683 int rc;
684 R3PTRTYPE(void *) pHCPtr;
685 Assert(pVM->cCpus == 1);
686 PVMCPU pVCpu = VMMGetCpu0(pVM);
687
688 STAM_PROFILE_START(&pVM->csam.s.StatTimeAddrConv, a);
689
690 pHCPtr = PATMR3GCPtrToHCPtr(pVM, pGCPtr);
691 if (pHCPtr)
692 return pHCPtr;
693
694 if (pCacheRec->pPageLocStartHC)
695 {
696 uint32_t offset = pGCPtr & PAGE_OFFSET_MASK;
697 if (pCacheRec->pGuestLoc == (pGCPtr & PAGE_BASE_GC_MASK))
698 {
699 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeAddrConv, a);
700 return pCacheRec->pPageLocStartHC + offset;
701 }
702 }
703
704 /* Release previous lock if any. */
705 if (pCacheRec->Lock.pvMap)
706 {
707 PGMPhysReleasePageMappingLock(pVM, &pCacheRec->Lock);
708 pCacheRec->Lock.pvMap = NULL;
709 }
710
711 rc = PGMPhysGCPtr2CCPtrReadOnly(pVCpu, pGCPtr, (const void **)&pHCPtr, &pCacheRec->Lock);
712 if (rc != VINF_SUCCESS)
713 {
714//// AssertMsgRC(rc, ("MMR3PhysGCVirt2HCVirtEx failed for %RRv\n", pGCPtr));
715 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeAddrConv, a);
716 return NULL;
717 }
718
719 pCacheRec->pPageLocStartHC = (R3PTRTYPE(uint8_t*))((RTHCUINTPTR)pHCPtr & PAGE_BASE_HC_MASK);
720 pCacheRec->pGuestLoc = pGCPtr & PAGE_BASE_GC_MASK;
721 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeAddrConv, a);
722 return pHCPtr;
723}
724
725/**
726 * @callback_method_impl{FNDISREADBYTES}
727 */
728static DECLCALLBACK(int) CSAMR3ReadBytes(PDISCPUSTATE pDisState, uint8_t *pbDst, RTUINTPTR uSrcAddr, uint32_t cbToRead)
729{
730 PVM pVM = (PVM)pDisState->apvUserData[0];
731 RTHCUINTPTR pInstrHC = (RTHCUINTPTR)pDisState->apvUserData[1];
732 RTGCUINTPTR32 pInstrGC = pDisState->uInstrAddr;
733 int orgsize = cbToRead;
734 PVMCPU pVCpu = VMMGetCpu0(pVM);
735
736 /* We are not interested in patched instructions, so read the original opcode bytes.
737 Note! single instruction patches (int3) are checked in CSAMR3AnalyseCallback */
738 for (int i = 0; i < orgsize; i++)
739 {
740 int rc = PATMR3QueryOpcode(pVM, (RTRCPTR)uSrcAddr, pbDst);
741 if (RT_FAILURE(rc))
742 break;
743 uSrcAddr++;
744 pbDst++;
745 cbToRead--;
746 }
747 if (cbToRead == 0)
748 return VINF_SUCCESS;
749
750 if (PAGE_ADDRESS(pInstrGC) != PAGE_ADDRESS(uSrcAddr + cbToRead - 1) && !PATMIsPatchGCAddr(pVM, uSrcAddr))
751 return PGMPhysSimpleReadGCPtr(pVCpu, pbDst, uSrcAddr, cbToRead);
752
753 Assert(pInstrHC);
754
755 /* pInstrHC is the base address; adjust according to the GC pointer. */
756 pInstrHC = pInstrHC + (uSrcAddr - pInstrGC);
757
758 memcpy(pbDst, (void *)pInstrHC, cbToRead);
759
760 return VINF_SUCCESS;
761}
762
763DECLINLINE(int) CSAMR3DISInstr(PVM pVM, RTRCPTR InstrGC, uint8_t *InstrHC, DISCPUMODE enmCpuMode,
764 PDISCPUSTATE pCpu, uint32_t *pcbInstr, char *pszOutput)
765{
766 (pCpu)->apvUserData[1] = InstrHC;
767 (pCpu)->apvUserData[2] = (void *)(uintptr_t)InstrGC; Assert(sizeof(InstrGC) <= sizeof(pCpu->apvUserData[0]));
768#ifdef DEBUG
769 return DISInstrEx(InstrGC, 0, enmCpuMode, CSAMR3ReadBytes, pVM, OPTYPE_ALL,
770 pCpu, pcbInstr, pszOutput);
771#else
772 /* We are interested in everything except harmless stuff */
773 return DISInstrEx(InstrGC, 0, enmCpuMode, CSAMR3ReadBytes, pVM, ~(OPTYPE_INVALID | OPTYPE_HARMLESS | OPTYPE_RRM_MASK),
774 pCpu, pcbInstr, pszOutput);
775#endif
776}
777
778/**
779 * Analyses the instructions following the cli for compliance with our heuristics for cli
780 *
781 * @returns VBox status code.
782 * @param pVM The VM to operate on.
783 * @param pCpu CPU disassembly state
784 * @param pInstrGC Guest context pointer to privileged instruction
785 * @param pCurInstrGC Guest context pointer to the current instruction
786 * @param pCacheRec GC to HC cache record
787 * @param pUserData User pointer (callback specific)
788 *
789 */
790static int CSAMR3AnalyseCallback(PVM pVM, DISCPUSTATE *pCpu, RCPTRTYPE(uint8_t *) pInstrGC, RCPTRTYPE(uint8_t *) pCurInstrGC,
791 PCSAMP2GLOOKUPREC pCacheRec, void *pUserData)
792{
793 PCSAMPAGE pPage = (PCSAMPAGE)pUserData;
794 int rc;
795 NOREF(pInstrGC);
796
797 switch (pCpu->pCurInstr->opcode)
798 {
799 case OP_INT:
800 Assert(pCpu->param1.flags & USE_IMMEDIATE8);
801 if (pCpu->param1.parval == 3)
802 {
803 //two byte int 3
804 return VINF_SUCCESS;
805 }
806 break;
807
808 case OP_ILLUD2:
809 /* This appears to be some kind of kernel panic in Linux 2.4; no point to continue. */
810 case OP_RETN:
811 case OP_INT3:
812 case OP_INVALID:
813#if 1
814 /* removing breaks win2k guests? */
815 case OP_IRET:
816#endif
817 return VINF_SUCCESS;
818 }
819
820 // Check for exit points
821 switch (pCpu->pCurInstr->opcode)
822 {
823 /* It's not a good idea to patch pushf instructions:
824 * - increases the chance of conflicts (code jumping to the next instruction)
825 * - better to patch the cli
826 * - code that branches before the cli will likely hit an int 3
827 * - in general doesn't offer any benefits as we don't allow nested patch blocks (IF is always 1)
828 */
829 case OP_PUSHF:
830 case OP_POPF:
831 break;
832
833 case OP_CLI:
834 {
835 uint32_t cbInstr = 0;
836 uint32_t opsize = pCpu->opsize;
837 bool fCode32 = pPage->fCode32;
838
839 Assert(fCode32);
840
841 PATMR3AddHint(pVM, pCurInstrGC, (fCode32) ? PATMFL_CODE32 : 0);
842
843 /* Make sure the instructions that follow the cli have not been encountered before. */
844 while (true)
845 {
846 DISCPUSTATE cpu;
847
848 if (cbInstr + opsize >= SIZEOF_NEARJUMP32)
849 break;
850
851 if (csamIsCodeScanned(pVM, pCurInstrGC + opsize, &pPage) == true)
852 {
853 /* We've scanned the next instruction(s) already. This means we've followed a branch that ended up there before -> dangerous!! */
854 PATMR3DetectConflict(pVM, pCurInstrGC, pCurInstrGC + opsize);
855 break;
856 }
857 pCurInstrGC += opsize;
858 cbInstr += opsize;
859
860 { /* Force pCurInstrHC out of scope after we stop using it (page lock!) */
861 uint8_t *pCurInstrHC = 0;
862 pCurInstrHC = (uint8_t *)CSAMGCVirtToHCVirt(pVM, pCacheRec, pCurInstrGC);
863 if (pCurInstrHC == NULL)
864 {
865 Log(("CSAMGCVirtToHCVirt failed for %RRv\n", pCurInstrGC));
866 break;
867 }
868 Assert(VALID_PTR(pCurInstrHC));
869
870 rc = CSAMR3DISInstr(pVM, pCurInstrGC, pCurInstrHC, (fCode32) ? CPUMODE_32BIT : CPUMODE_16BIT,
871 &cpu, &opsize, NULL);
872 }
873 AssertRC(rc);
874 if (RT_FAILURE(rc))
875 break;
876 }
877 break;
878 }
879
880 case OP_PUSH:
881 if (pCpu->pCurInstr->param1 != OP_PARM_REG_CS)
882 break;
883
884 /* no break */
885 case OP_STR:
886 case OP_LSL:
887 case OP_LAR:
888 case OP_SGDT:
889 case OP_SLDT:
890 case OP_SIDT:
891 case OP_SMSW:
892 case OP_VERW:
893 case OP_VERR:
894 case OP_CPUID:
895 case OP_IRET:
896#ifdef DEBUG
897 switch(pCpu->pCurInstr->opcode)
898 {
899 case OP_STR:
900 Log(("Privileged instruction at %RRv: str!!\n", pCurInstrGC));
901 break;
902 case OP_LSL:
903 Log(("Privileged instruction at %RRv: lsl!!\n", pCurInstrGC));
904 break;
905 case OP_LAR:
906 Log(("Privileged instruction at %RRv: lar!!\n", pCurInstrGC));
907 break;
908 case OP_SGDT:
909 Log(("Privileged instruction at %RRv: sgdt!!\n", pCurInstrGC));
910 break;
911 case OP_SLDT:
912 Log(("Privileged instruction at %RRv: sldt!!\n", pCurInstrGC));
913 break;
914 case OP_SIDT:
915 Log(("Privileged instruction at %RRv: sidt!!\n", pCurInstrGC));
916 break;
917 case OP_SMSW:
918 Log(("Privileged instruction at %RRv: smsw!!\n", pCurInstrGC));
919 break;
920 case OP_VERW:
921 Log(("Privileged instruction at %RRv: verw!!\n", pCurInstrGC));
922 break;
923 case OP_VERR:
924 Log(("Privileged instruction at %RRv: verr!!\n", pCurInstrGC));
925 break;
926 case OP_CPUID:
927 Log(("Privileged instruction at %RRv: cpuid!!\n", pCurInstrGC));
928 break;
929 case OP_PUSH:
930 Log(("Privileged instruction at %RRv: push cs!!\n", pCurInstrGC));
931 break;
932 case OP_IRET:
933 Log(("Privileged instruction at %RRv: iret!!\n", pCurInstrGC));
934 break;
935 }
936#endif
937
938 if (PATMR3HasBeenPatched(pVM, pCurInstrGC) == false)
939 {
940 rc = PATMR3InstallPatch(pVM, pCurInstrGC, (pPage->fCode32) ? PATMFL_CODE32 : 0);
941 if (RT_FAILURE(rc))
942 {
943 Log(("PATMR3InstallPatch failed with %d\n", rc));
944 return VWRN_CONTINUE_ANALYSIS;
945 }
946 }
947 if (pCpu->pCurInstr->opcode == OP_IRET)
948 return VINF_SUCCESS; /* Look no further in this branch. */
949
950 return VWRN_CONTINUE_ANALYSIS;
951
952 case OP_JMP:
953 case OP_CALL:
954 {
955 // return or jump/call through a jump table
956 if (OP_PARM_VTYPE(pCpu->pCurInstr->param1) != OP_PARM_J)
957 {
958#ifdef DEBUG
959 switch(pCpu->pCurInstr->opcode)
960 {
961 case OP_JMP:
962 Log(("Control Flow instruction at %RRv: jmp!!\n", pCurInstrGC));
963 break;
964 case OP_CALL:
965 Log(("Control Flow instruction at %RRv: call!!\n", pCurInstrGC));
966 break;
967 }
968#endif
969 return VWRN_CONTINUE_ANALYSIS;
970 }
971 return VWRN_CONTINUE_ANALYSIS;
972 }
973
974 }
975
976 return VWRN_CONTINUE_ANALYSIS;
977}
978
979#ifdef CSAM_ANALYSE_BEYOND_RET
980/**
981 * Wrapper for csamAnalyseCodeStream for call instructions.
982 *
983 * @returns VBox status code.
984 * @param pVM The VM to operate on.
985 * @param pInstrGC Guest context pointer to privileged instruction
986 * @param pCurInstrGC Guest context pointer to the current instruction
987 * @param fCode32 16 or 32 bits code
988 * @param pfnCSAMR3Analyse Callback for testing the disassembled instruction
989 * @param pUserData User pointer (callback specific)
990 *
991 */
992static int csamAnalyseCallCodeStream(PVM pVM, RCPTRTYPE(uint8_t *) pInstrGC, RCPTRTYPE(uint8_t *) pCurInstrGC, bool fCode32,
993 PFN_CSAMR3ANALYSE pfnCSAMR3Analyse, void *pUserData, PCSAMP2GLOOKUPREC pCacheRec)
994{
995 int rc;
996 CSAMCALLEXITREC CallExitRec;
997 PCSAMCALLEXITREC pOldCallRec;
998 PCSAMPAGE pPage = 0;
999 uint32_t i;
1000
1001 CallExitRec.cInstrAfterRet = 0;
1002
1003 pOldCallRec = pCacheRec->pCallExitRec;
1004 pCacheRec->pCallExitRec = &CallExitRec;
1005
1006 rc = csamAnalyseCodeStream(pVM, pInstrGC, pCurInstrGC, fCode32, pfnCSAMR3Analyse, pUserData, pCacheRec);
1007
1008 for (i=0;i<CallExitRec.cInstrAfterRet;i++)
1009 {
1010 PCSAMPAGE pPage = 0;
1011
1012 pCurInstrGC = CallExitRec.pInstrAfterRetGC[i];
1013
1014 /* Check if we've previously encountered the instruction after the ret. */
1015 if (csamIsCodeScanned(pVM, pCurInstrGC, &pPage) == false)
1016 {
1017 DISCPUSTATE cpu;
1018 uint32_t opsize;
1019 int rc2;
1020#ifdef DEBUG
1021 char szOutput[256];
1022#endif
1023 if (pPage == NULL)
1024 {
1025 /* New address; let's take a look at it. */
1026 pPage = csamCreatePageRecord(pVM, pCurInstrGC, CSAM_TAG_CSAM, fCode32);
1027 if (pPage == NULL)
1028 {
1029 rc = VERR_NO_MEMORY;
1030 goto done;
1031 }
1032 }
1033
1034 /**
1035 * Some generic requirements for recognizing an adjacent function:
1036 * - alignment fillers that consist of:
1037 * - nop
1038 * - lea genregX, [genregX (+ 0)]
1039 * - push ebp after the filler (can extend this later); aligned at at least a 4 byte boundary
1040 */
1041 for (int j = 0; j < 16; j++)
1042 {
1043 uint8_t *pCurInstrHC = (uint8_t *)CSAMGCVirtToHCVirt(pVM, pCacheRec, pCurInstrGC);
1044 if (pCurInstrHC == NULL)
1045 {
1046 Log(("CSAMGCVirtToHCVirt failed for %RRv\n", pCurInstrGC));
1047 goto done;
1048 }
1049 Assert(VALID_PTR(pCurInstrHC));
1050
1051 STAM_PROFILE_START(&pVM->csam.s.StatTimeDisasm, a);
1052#ifdef DEBUG
1053 rc2 = CSAMR3DISInstr(pVM, pCurInstrGC, pCurInstrHC, (fCode32) ? CPUMODE_32BIT : CPUMODE_16BIT,
1054 &cpu, &opsize, szOutput);
1055 if (RT_SUCCESS(rc2)) Log(("CSAM Call Analysis: %s", szOutput));
1056#else
1057 rc2 = CSAMR3DISInstr(pVM, pCurInstrGC, pCurInstrHC, (fCode32) ? CPUMODE_32BIT : CPUMODE_16BIT,
1058 &cpu, &opsize, NULL);
1059#endif
1060 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeDisasm, a);
1061 if (RT_FAILURE(rc2))
1062 {
1063 Log(("Disassembly failed at %RRv with %Rrc (probably page not present) -> return to caller\n", pCurInstrGC, rc2));
1064 goto done;
1065 }
1066
1067 STAM_COUNTER_ADD(&pVM->csam.s.StatNrBytesRead, opsize);
1068
1069 RCPTRTYPE(uint8_t *) addr = 0;
1070 PCSAMPAGE pJmpPage = NULL;
1071
1072 if (PAGE_ADDRESS(pCurInstrGC) != PAGE_ADDRESS(pCurInstrGC + opsize - 1))
1073 {
1074 if (!PGMGstIsPagePresent(pVM, pCurInstrGC + opsize - 1))
1075 {
1076 /// @todo fault in the page
1077 Log(("Page for current instruction %RRv is not present!!\n", pCurInstrGC));
1078 goto done;
1079 }
1080 //all is fine, let's continue
1081 csamR3CheckPageRecord(pVM, pCurInstrGC + opsize - 1);
1082 }
1083
1084 switch (cpu.pCurInstr->opcode)
1085 {
1086 case OP_NOP:
1087 case OP_INT3:
1088 break; /* acceptable */
1089
1090 case OP_LEA:
1091 /* Must be similar to:
1092 *
1093 * lea esi, [esi]
1094 * lea esi, [esi+0]
1095 * Any register is allowed as long as source and destination are identical.
1096 */
1097 if ( cpu.param1.flags != USE_REG_GEN32
1098 || ( cpu.param2.flags != USE_REG_GEN32
1099 && ( !(cpu.param2.flags & USE_REG_GEN32)
1100 || !(cpu.param2.flags & (USE_DISPLACEMENT8|USE_DISPLACEMENT16|USE_DISPLACEMENT32))
1101 || cpu.param2.parval != 0
1102 )
1103 )
1104 || cpu.param1.base.reg_gen32 != cpu.param2.base.reg_gen32
1105 )
1106 {
1107 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunctionFailed);
1108 goto next_function;
1109 }
1110 break;
1111
1112 case OP_PUSH:
1113 {
1114 if ( (pCurInstrGC & 0x3) != 0
1115 || cpu.param1.flags != USE_REG_GEN32
1116 || cpu.param1.base.reg_gen32 != USE_REG_EBP
1117 )
1118 {
1119 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunctionFailed);
1120 goto next_function;
1121 }
1122
1123 if (csamIsCodeScanned(pVM, pCurInstrGC, &pPage) == false)
1124 {
1125 CSAMCALLEXITREC CallExitRec2;
1126 CallExitRec2.cInstrAfterRet = 0;
1127
1128 pCacheRec->pCallExitRec = &CallExitRec2;
1129
1130 /* Analyse the function. */
1131 Log(("Found new function at %RRv\n", pCurInstrGC));
1132 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunction);
1133 csamAnalyseCallCodeStream(pVM, pInstrGC, pCurInstrGC, fCode32, pfnCSAMR3Analyse, pUserData, pCacheRec);
1134 }
1135 goto next_function;
1136 }
1137
1138 case OP_SUB:
1139 {
1140 if ( (pCurInstrGC & 0x3) != 0
1141 || cpu.param1.flags != USE_REG_GEN32
1142 || cpu.param1.base.reg_gen32 != USE_REG_ESP
1143 )
1144 {
1145 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunctionFailed);
1146 goto next_function;
1147 }
1148
1149 if (csamIsCodeScanned(pVM, pCurInstrGC, &pPage) == false)
1150 {
1151 CSAMCALLEXITREC CallExitRec2;
1152 CallExitRec2.cInstrAfterRet = 0;
1153
1154 pCacheRec->pCallExitRec = &CallExitRec2;
1155
1156 /* Analyse the function. */
1157 Log(("Found new function at %RRv\n", pCurInstrGC));
1158 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunction);
1159 csamAnalyseCallCodeStream(pVM, pInstrGC, pCurInstrGC, fCode32, pfnCSAMR3Analyse, pUserData, pCacheRec);
1160 }
1161 goto next_function;
1162 }
1163
1164 default:
1165 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunctionFailed);
1166 goto next_function;
1167 }
1168 /* Mark it as scanned. */
1169 csamMarkCode(pVM, pPage, pCurInstrGC, opsize, true);
1170 pCurInstrGC += opsize;
1171 } /* for at most 16 instructions */
1172next_function:
1173 ; /* MSVC complains otherwise */
1174 }
1175 }
1176done:
1177 pCacheRec->pCallExitRec = pOldCallRec;
1178 return rc;
1179}
1180#else
1181#define csamAnalyseCallCodeStream csamAnalyseCodeStream
1182#endif
1183
1184/**
1185 * Disassembles the code stream until the callback function detects a failure or decides everything is acceptable
1186 *
1187 * @returns VBox status code.
1188 * @param pVM The VM to operate on.
1189 * @param pInstrGC Guest context pointer to privileged instruction
1190 * @param pCurInstrGC Guest context pointer to the current instruction
1191 * @param fCode32 16 or 32 bits code
1192 * @param pfnCSAMR3Analyse Callback for testing the disassembled instruction
1193 * @param pUserData User pointer (callback specific)
1194 *
1195 */
1196static int csamAnalyseCodeStream(PVM pVM, RCPTRTYPE(uint8_t *) pInstrGC, RCPTRTYPE(uint8_t *) pCurInstrGC, bool fCode32,
1197 PFN_CSAMR3ANALYSE pfnCSAMR3Analyse, void *pUserData, PCSAMP2GLOOKUPREC pCacheRec)
1198{
1199 DISCPUSTATE cpu;
1200 PCSAMPAGE pPage = (PCSAMPAGE)pUserData;
1201 int rc = VWRN_CONTINUE_ANALYSIS;
1202 uint32_t opsize;
1203 int rc2;
1204 Assert(pVM->cCpus == 1);
1205 PVMCPU pVCpu = VMMGetCpu0(pVM);
1206
1207#ifdef DEBUG
1208 char szOutput[256];
1209#endif
1210
1211 LogFlow(("csamAnalyseCodeStream: code at %RRv depth=%d\n", pCurInstrGC, pCacheRec->depth));
1212
1213 pVM->csam.s.fScanningStarted = true;
1214
1215 pCacheRec->depth++;
1216 /*
1217 * Limit the call depth. (rather arbitrary upper limit; too low and we won't detect certain
1218 * cpuid instructions in Linux kernels; too high and we waste too much time scanning code)
1219 * (512 is necessary to detect cpuid instructions in Red Hat EL4; see defect 1355)
1220 * @note we are using a lot of stack here. couple of 100k when we go to the full depth (!)
1221 */
1222 if (pCacheRec->depth > 512)
1223 {
1224 LogFlow(("CSAM: maximum calldepth reached for %RRv\n", pCurInstrGC));
1225 pCacheRec->depth--;
1226 return VINF_SUCCESS; //let's not go on forever
1227 }
1228
1229 Assert(!PATMIsPatchGCAddr(pVM, pCurInstrGC));
1230 csamR3CheckPageRecord(pVM, pCurInstrGC);
1231
1232 while(rc == VWRN_CONTINUE_ANALYSIS)
1233 {
1234 if (csamIsCodeScanned(pVM, pCurInstrGC, &pPage) == false)
1235 {
1236 if (pPage == NULL)
1237 {
1238 /* New address; let's take a look at it. */
1239 pPage = csamCreatePageRecord(pVM, pCurInstrGC, CSAM_TAG_CSAM, fCode32);
1240 if (pPage == NULL)
1241 {
1242 rc = VERR_NO_MEMORY;
1243 goto done;
1244 }
1245 }
1246 }
1247 else
1248 {
1249 LogFlow(("Code at %RRv has been scanned before\n", pCurInstrGC));
1250 rc = VINF_SUCCESS;
1251 goto done;
1252 }
1253
1254 { /* Force pCurInstrHC out of scope after we stop using it (page lock!) */
1255 uint8_t *pCurInstrHC = (uint8_t *)CSAMGCVirtToHCVirt(pVM, pCacheRec, pCurInstrGC);
1256 if (pCurInstrHC == NULL)
1257 {
1258 Log(("CSAMGCVirtToHCVirt failed for %RRv\n", pCurInstrGC));
1259 rc = VERR_PATCHING_REFUSED;
1260 goto done;
1261 }
1262 Assert(VALID_PTR(pCurInstrHC));
1263
1264 STAM_PROFILE_START(&pVM->csam.s.StatTimeDisasm, a);
1265#ifdef DEBUG
1266 rc2 = CSAMR3DISInstr(pVM, pCurInstrGC, pCurInstrHC, fCode32 ? CPUMODE_32BIT : CPUMODE_16BIT,
1267 &cpu, &opsize, szOutput);
1268 if (RT_SUCCESS(rc2)) Log(("CSAM Analysis: %s", szOutput));
1269#else
1270 rc2 = CSAMR3DISInstr(pVM, pCurInstrGC, pCurInstrHC, fCode32 ? CPUMODE_32BIT : CPUMODE_16BIT,
1271 &cpu, &opsize, NULL);
1272#endif
1273 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeDisasm, a);
1274 }
1275 if (RT_FAILURE(rc2))
1276 {
1277 Log(("Disassembly failed at %RRv with %Rrc (probably page not present) -> return to caller\n", pCurInstrGC, rc2));
1278 rc = VINF_SUCCESS;
1279 goto done;
1280 }
1281
1282 STAM_COUNTER_ADD(&pVM->csam.s.StatNrBytesRead, opsize);
1283
1284 csamMarkCode(pVM, pPage, pCurInstrGC, opsize, true);
1285
1286 RCPTRTYPE(uint8_t *) addr = 0;
1287 PCSAMPAGE pJmpPage = NULL;
1288
1289 if (PAGE_ADDRESS(pCurInstrGC) != PAGE_ADDRESS(pCurInstrGC + opsize - 1))
1290 {
1291 if (!PGMGstIsPagePresent(pVCpu, pCurInstrGC + opsize - 1))
1292 {
1293 /// @todo fault in the page
1294 Log(("Page for current instruction %RRv is not present!!\n", pCurInstrGC));
1295 rc = VWRN_CONTINUE_ANALYSIS;
1296 goto next_please;
1297 }
1298 //all is fine, let's continue
1299 csamR3CheckPageRecord(pVM, pCurInstrGC + opsize - 1);
1300 }
1301 /*
1302 * If it's harmless, then don't bother checking it (the disasm tables had better be accurate!)
1303 */
1304 if ((cpu.pCurInstr->optype & ~OPTYPE_RRM_MASK) == OPTYPE_HARMLESS)
1305 {
1306 AssertMsg(pfnCSAMR3Analyse(pVM, &cpu, pInstrGC, pCurInstrGC, pCacheRec, (void *)pPage) == VWRN_CONTINUE_ANALYSIS, ("Instruction incorrectly marked harmless?!?!?\n"));
1307 rc = VWRN_CONTINUE_ANALYSIS;
1308 goto next_please;
1309 }
1310
1311#ifdef CSAM_ANALYSE_BEYOND_RET
1312 /* Remember the address of the instruction following the ret in case the parent instruction was a call. */
1313 if ( pCacheRec->pCallExitRec
1314 && cpu.pCurInstr->opcode == OP_RETN
1315 && pCacheRec->pCallExitRec->cInstrAfterRet < CSAM_MAX_CALLEXIT_RET)
1316 {
1317 pCacheRec->pCallExitRec->pInstrAfterRetGC[pCacheRec->pCallExitRec->cInstrAfterRet] = pCurInstrGC + opsize;
1318 pCacheRec->pCallExitRec->cInstrAfterRet++;
1319 }
1320#endif
1321
1322 rc = pfnCSAMR3Analyse(pVM, &cpu, pInstrGC, pCurInstrGC, pCacheRec, (void *)pPage);
1323 if (rc == VINF_SUCCESS)
1324 goto done;
1325
1326 // For our first attempt, we'll handle only simple relative jumps and calls (immediate offset coded in instruction)
1327 if ( ((cpu.pCurInstr->optype & OPTYPE_CONTROLFLOW) && (OP_PARM_VTYPE(cpu.pCurInstr->param1) == OP_PARM_J))
1328 || (cpu.pCurInstr->opcode == OP_CALL && cpu.param1.flags == USE_DISPLACEMENT32)) /* simple indirect call (call dword ptr [address]) */
1329 {
1330 /* We need to parse 'call dword ptr [address]' type of calls to catch cpuid instructions in some recent Linux distributions (e.g. OpenSuse 10.3) */
1331 if ( cpu.pCurInstr->opcode == OP_CALL
1332 && cpu.param1.flags == USE_DISPLACEMENT32)
1333 {
1334 addr = 0;
1335 PGMPhysSimpleReadGCPtr(pVCpu, &addr, (RTRCUINTPTR)cpu.param1.uDisp.i32, sizeof(addr));
1336 }
1337 else
1338 addr = CSAMResolveBranch(&cpu, pCurInstrGC);
1339
1340 if (addr == 0)
1341 {
1342 Log(("We don't support far jumps here!! (%08X)\n", cpu.param1.flags));
1343 rc = VINF_SUCCESS;
1344 break;
1345 }
1346 Assert(!PATMIsPatchGCAddr(pVM, addr));
1347
1348 /* If the target address lies in a patch generated jump, then special action needs to be taken. */
1349 PATMR3DetectConflict(pVM, pCurInstrGC, addr);
1350
1351 /* Same page? */
1352 if (PAGE_ADDRESS(addr) != PAGE_ADDRESS(pCurInstrGC ))
1353 {
1354 if (!PGMGstIsPagePresent(pVCpu, addr))
1355 {
1356 Log(("Page for current instruction %RRv is not present!!\n", addr));
1357 rc = VWRN_CONTINUE_ANALYSIS;
1358 goto next_please;
1359 }
1360
1361 /* All is fine, let's continue. */
1362 csamR3CheckPageRecord(pVM, addr);
1363 }
1364
1365 pJmpPage = NULL;
1366 if (csamIsCodeScanned(pVM, addr, &pJmpPage) == false)
1367 {
1368 if (pJmpPage == NULL)
1369 {
1370 /* New branch target; let's take a look at it. */
1371 pJmpPage = csamCreatePageRecord(pVM, addr, CSAM_TAG_CSAM, fCode32);
1372 if (pJmpPage == NULL)
1373 {
1374 rc = VERR_NO_MEMORY;
1375 goto done;
1376 }
1377 Assert(pPage);
1378 }
1379 if (cpu.pCurInstr->opcode == OP_CALL)
1380 rc = csamAnalyseCallCodeStream(pVM, pInstrGC, addr, fCode32, pfnCSAMR3Analyse, (void *)pJmpPage, pCacheRec);
1381 else
1382 rc = csamAnalyseCodeStream(pVM, pInstrGC, addr, fCode32, pfnCSAMR3Analyse, (void *)pJmpPage, pCacheRec);
1383
1384 if (rc != VINF_SUCCESS) {
1385 goto done;
1386 }
1387 }
1388 if (cpu.pCurInstr->opcode == OP_JMP)
1389 {//unconditional jump; return to caller
1390 rc = VINF_SUCCESS;
1391 goto done;
1392 }
1393
1394 rc = VWRN_CONTINUE_ANALYSIS;
1395 } //if ((cpu.pCurInstr->optype & OPTYPE_CONTROLFLOW) && (OP_PARM_VTYPE(cpu.pCurInstr->param1) == OP_PARM_J))
1396#ifdef CSAM_SCAN_JUMP_TABLE
1397 else
1398 if ( cpu.pCurInstr->opcode == OP_JMP
1399 && (cpu.param1.flags & (USE_DISPLACEMENT32|USE_INDEX|USE_SCALE)) == (USE_DISPLACEMENT32|USE_INDEX|USE_SCALE)
1400 )
1401 {
1402 RTRCPTR pJumpTableGC = (RTRCPTR)cpu.param1.disp32;
1403 uint8_t *pJumpTableHC;
1404 int rc2;
1405
1406 Log(("Jump through jump table\n"));
1407
1408 rc2 = PGMPhysGCPtr2CCPtrReadOnly(pVCpu, pJumpTableGC, (PRTHCPTR)&pJumpTableHC, missing page lock);
1409 if (rc2 == VINF_SUCCESS)
1410 {
1411 for (uint32_t i=0;i<2;i++)
1412 {
1413 uint64_t fFlags;
1414
1415 addr = pJumpTableGC + cpu.param1.scale * i;
1416 /* Same page? */
1417 if (PAGE_ADDRESS(addr) != PAGE_ADDRESS(pJumpTableGC))
1418 break;
1419
1420 addr = *(RTRCPTR *)(pJumpTableHC + cpu.param1.scale * i);
1421
1422 rc2 = PGMGstGetPage(pVCpu, addr, &fFlags, NULL);
1423 if ( rc2 != VINF_SUCCESS
1424 || (fFlags & X86_PTE_US)
1425 || !(fFlags & X86_PTE_P)
1426 )
1427 break;
1428
1429 Log(("Jump to %RRv\n", addr));
1430
1431 pJmpPage = NULL;
1432 if (csamIsCodeScanned(pVM, addr, &pJmpPage) == false)
1433 {
1434 if (pJmpPage == NULL)
1435 {
1436 /* New branch target; let's take a look at it. */
1437 pJmpPage = csamCreatePageRecord(pVM, addr, CSAM_TAG_CSAM, fCode32);
1438 if (pJmpPage == NULL)
1439 {
1440 rc = VERR_NO_MEMORY;
1441 goto done;
1442 }
1443 Assert(pPage);
1444 }
1445 rc = csamAnalyseCodeStream(pVM, pInstrGC, addr, fCode32, pfnCSAMR3Analyse, (void *)pJmpPage, pCacheRec);
1446 if (rc != VINF_SUCCESS) {
1447 goto done;
1448 }
1449 }
1450 }
1451 }
1452 }
1453#endif
1454 if (rc != VWRN_CONTINUE_ANALYSIS) {
1455 break; //done!
1456 }
1457next_please:
1458 if (cpu.pCurInstr->opcode == OP_JMP)
1459 {
1460 rc = VINF_SUCCESS;
1461 goto done;
1462 }
1463 pCurInstrGC += opsize;
1464 }
1465done:
1466 pCacheRec->depth--;
1467 return rc;
1468}
1469
1470
1471/**
1472 * Calculates the 64 bits hash value for the current page
1473 *
1474 * @returns hash value
1475 * @param pVM The VM to operate on.
1476 * @param pInstr Page address
1477 */
1478uint64_t csamR3CalcPageHash(PVM pVM, RTRCPTR pInstr)
1479{
1480 uint64_t hash = 0;
1481 uint32_t val[5];
1482 int rc;
1483 Assert(pVM->cCpus == 1);
1484 PVMCPU pVCpu = VMMGetCpu0(pVM);
1485
1486 Assert((pInstr & PAGE_OFFSET_MASK) == 0);
1487
1488 rc = PGMPhysSimpleReadGCPtr(pVCpu, &val[0], pInstr, sizeof(val[0]));
1489 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
1490 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1491 {
1492 Log(("csamR3CalcPageHash: page %RRv not present!!\n", pInstr));
1493 return ~0ULL;
1494 }
1495
1496 rc = PGMPhysSimpleReadGCPtr(pVCpu, &val[1], pInstr+1024, sizeof(val[0]));
1497 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
1498 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1499 {
1500 Log(("csamR3CalcPageHash: page %RRv not present!!\n", pInstr));
1501 return ~0ULL;
1502 }
1503
1504 rc = PGMPhysSimpleReadGCPtr(pVCpu, &val[2], pInstr+2048, sizeof(val[0]));
1505 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
1506 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1507 {
1508 Log(("csamR3CalcPageHash: page %RRv not present!!\n", pInstr));
1509 return ~0ULL;
1510 }
1511
1512 rc = PGMPhysSimpleReadGCPtr(pVCpu, &val[3], pInstr+3072, sizeof(val[0]));
1513 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
1514 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1515 {
1516 Log(("csamR3CalcPageHash: page %RRv not present!!\n", pInstr));
1517 return ~0ULL;
1518 }
1519
1520 rc = PGMPhysSimpleReadGCPtr(pVCpu, &val[4], pInstr+4092, sizeof(val[0]));
1521 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
1522 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1523 {
1524 Log(("csamR3CalcPageHash: page %RRv not present!!\n", pInstr));
1525 return ~0ULL;
1526 }
1527
1528 // don't want to get division by zero traps
1529 val[2] |= 1;
1530 val[4] |= 1;
1531
1532 hash = (uint64_t)val[0] * (uint64_t)val[1] / (uint64_t)val[2] + (val[3]%val[4]);
1533 return (hash == ~0ULL) ? hash - 1 : hash;
1534}
1535
1536
1537/**
1538 * Notify CSAM of a page flush
1539 *
1540 * @returns VBox status code
1541 * @param pVM The VM to operate on.
1542 * @param addr GC address of the page to flush
1543 * @param fRemovePage Page removal flag
1544 */
1545static int csamFlushPage(PVM pVM, RTRCPTR addr, bool fRemovePage)
1546{
1547 PCSAMPAGEREC pPageRec;
1548 int rc;
1549 RTGCPHYS GCPhys = 0;
1550 uint64_t fFlags = 0;
1551 Assert(pVM->cCpus == 1 || !CSAMIsEnabled(pVM));
1552
1553 if (!CSAMIsEnabled(pVM))
1554 return VINF_SUCCESS;
1555
1556 PVMCPU pVCpu = VMMGetCpu0(pVM);
1557
1558 STAM_PROFILE_START(&pVM->csam.s.StatTimeFlushPage, a);
1559
1560 addr = addr & PAGE_BASE_GC_MASK;
1561
1562 /*
1563 * Note: searching for the page in our tree first is more expensive (skipped flushes are two orders of magnitude more common)
1564 */
1565 if (pVM->csam.s.pPageTree == NULL)
1566 {
1567 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1568 return VWRN_CSAM_PAGE_NOT_FOUND;
1569 }
1570
1571 rc = PGMGstGetPage(pVCpu, addr, &fFlags, &GCPhys);
1572 /* Returned at a very early stage (no paging yet presumably). */
1573 if (rc == VERR_NOT_SUPPORTED)
1574 {
1575 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1576 return rc;
1577 }
1578
1579 if (RT_SUCCESS(rc))
1580 {
1581 if ( (fFlags & X86_PTE_US)
1582 || rc == VERR_PGM_PHYS_PAGE_RESERVED
1583 )
1584 {
1585 /* User page -> not relevant for us. */
1586 STAM_COUNTER_ADD(&pVM->csam.s.StatNrFlushesSkipped, 1);
1587 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1588 return VINF_SUCCESS;
1589 }
1590 }
1591 else
1592 if (rc != VERR_PAGE_NOT_PRESENT && rc != VERR_PAGE_TABLE_NOT_PRESENT)
1593 AssertMsgFailed(("PGMR3GetPage %RRv failed with %Rrc\n", addr, rc));
1594
1595 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)(uintptr_t)addr);
1596 if (pPageRec)
1597 {
1598 if ( GCPhys == pPageRec->page.GCPhys
1599 && (fFlags & X86_PTE_P))
1600 {
1601 STAM_COUNTER_ADD(&pVM->csam.s.StatNrFlushesSkipped, 1);
1602 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1603 return VINF_SUCCESS;
1604 }
1605
1606 Log(("CSAMR3FlushPage: page %RRv has changed -> FLUSH (rc=%Rrc) (Phys: %RGp vs %RGp)\n", addr, rc, GCPhys, pPageRec->page.GCPhys));
1607
1608 STAM_COUNTER_ADD(&pVM->csam.s.StatNrFlushes, 1);
1609
1610 if (fRemovePage)
1611 csamRemovePageRecord(pVM, addr);
1612 else
1613 {
1614 CSAMMarkPage(pVM, addr, false);
1615 pPageRec->page.GCPhys = 0;
1616 pPageRec->page.fFlags = 0;
1617 rc = PGMGstGetPage(pVCpu, addr, &pPageRec->page.fFlags, &pPageRec->page.GCPhys);
1618 if (rc == VINF_SUCCESS)
1619 pPageRec->page.u64Hash = csamR3CalcPageHash(pVM, addr);
1620
1621 if (pPageRec->page.pBitmap == NULL)
1622 {
1623 pPageRec->page.pBitmap = (uint8_t *)MMR3HeapAllocZ(pVM, MM_TAG_CSAM_PATCH, CSAM_PAGE_BITMAP_SIZE);
1624 Assert(pPageRec->page.pBitmap);
1625 if (pPageRec->page.pBitmap == NULL)
1626 return VERR_NO_MEMORY;
1627 }
1628 else
1629 memset(pPageRec->page.pBitmap, 0, CSAM_PAGE_BITMAP_SIZE);
1630 }
1631
1632
1633 /*
1634 * Inform patch manager about the flush; no need to repeat the above check twice.
1635 */
1636 PATMR3FlushPage(pVM, addr);
1637
1638 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1639 return VINF_SUCCESS;
1640 }
1641 else
1642 {
1643 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1644 return VWRN_CSAM_PAGE_NOT_FOUND;
1645 }
1646}
1647
1648/**
1649 * Notify CSAM of a page flush
1650 *
1651 * @returns VBox status code
1652 * @param pVM The VM to operate on.
1653 * @param addr GC address of the page to flush
1654 */
1655VMMR3DECL(int) CSAMR3FlushPage(PVM pVM, RTRCPTR addr)
1656{
1657 return csamFlushPage(pVM, addr, true /* remove page record */);
1658}
1659
1660/**
1661 * Remove a CSAM monitored page. Use with care!
1662 *
1663 * @returns VBox status code
1664 * @param pVM The VM to operate on.
1665 * @param addr GC address of the page to flush
1666 */
1667VMMR3DECL(int) CSAMR3RemovePage(PVM pVM, RTRCPTR addr)
1668{
1669 PCSAMPAGEREC pPageRec;
1670 int rc;
1671
1672 addr = addr & PAGE_BASE_GC_MASK;
1673
1674 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)(uintptr_t)addr);
1675 if (pPageRec)
1676 {
1677 rc = csamRemovePageRecord(pVM, addr);
1678 if (RT_SUCCESS(rc))
1679 PATMR3FlushPage(pVM, addr);
1680 return VINF_SUCCESS;
1681 }
1682 return VWRN_CSAM_PAGE_NOT_FOUND;
1683}
1684
1685/**
1686 * Check a page record in case a page has been changed
1687 *
1688 * @returns VBox status code. (trap handled or not)
1689 * @param pVM The VM to operate on.
1690 * @param pInstrGC GC instruction pointer
1691 */
1692int csamR3CheckPageRecord(PVM pVM, RTRCPTR pInstrGC)
1693{
1694 PCSAMPAGEREC pPageRec;
1695 uint64_t u64hash;
1696
1697 pInstrGC = pInstrGC & PAGE_BASE_GC_MASK;
1698
1699 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)(uintptr_t)pInstrGC);
1700 if (pPageRec)
1701 {
1702 u64hash = csamR3CalcPageHash(pVM, pInstrGC);
1703 if (u64hash != pPageRec->page.u64Hash)
1704 csamFlushPage(pVM, pInstrGC, false /* don't remove page record */);
1705 }
1706 else
1707 return VWRN_CSAM_PAGE_NOT_FOUND;
1708
1709 return VINF_SUCCESS;
1710}
1711
1712/**
1713 * Returns monitor description based on CSAM tag
1714 *
1715 * @return description string
1716 * @param enmTag Owner tag
1717 */
1718const char *csamGetMonitorDescription(CSAMTAG enmTag)
1719{
1720 if (enmTag == CSAM_TAG_PATM)
1721 return "CSAM-PATM self-modifying code monitor handler";
1722 else
1723 if (enmTag == CSAM_TAG_REM)
1724 return "CSAM-REM self-modifying code monitor handler";
1725 Assert(enmTag == CSAM_TAG_CSAM);
1726 return "CSAM self-modifying code monitor handler";
1727}
1728
1729/**
1730 * Adds page record to our lookup tree
1731 *
1732 * @returns CSAMPAGE ptr or NULL if failure
1733 * @param pVM The VM to operate on.
1734 * @param GCPtr Page address
1735 * @param enmTag Owner tag
1736 * @param fCode32 16 or 32 bits code
1737 * @param fMonitorInvalidation Monitor page invalidation flag
1738 */
1739static PCSAMPAGE csamCreatePageRecord(PVM pVM, RTRCPTR GCPtr, CSAMTAG enmTag, bool fCode32, bool fMonitorInvalidation)
1740{
1741 PCSAMPAGEREC pPage;
1742 int rc;
1743 bool ret;
1744 Assert(pVM->cCpus == 1);
1745 PVMCPU pVCpu = VMMGetCpu0(pVM);
1746
1747 Log(("New page record for %RRv\n", GCPtr & PAGE_BASE_GC_MASK));
1748
1749 pPage = (PCSAMPAGEREC)MMR3HeapAllocZ(pVM, MM_TAG_CSAM_PATCH, sizeof(CSAMPAGEREC));
1750 if (pPage == NULL)
1751 {
1752 AssertMsgFailed(("csamCreatePageRecord: Out of memory!!!!\n"));
1753 return NULL;
1754 }
1755 /* Round down to page boundary. */
1756 GCPtr = (GCPtr & PAGE_BASE_GC_MASK);
1757 pPage->Core.Key = (AVLPVKEY)(uintptr_t)GCPtr;
1758 pPage->page.pPageGC = GCPtr;
1759 pPage->page.fCode32 = fCode32;
1760 pPage->page.fMonitorInvalidation = fMonitorInvalidation;
1761 pPage->page.enmTag = enmTag;
1762 pPage->page.fMonitorActive = false;
1763 pPage->page.pBitmap = (uint8_t *)MMR3HeapAllocZ(pVM, MM_TAG_CSAM_PATCH, PAGE_SIZE/sizeof(uint8_t));
1764 rc = PGMGstGetPage(pVCpu, GCPtr, &pPage->page.fFlags, &pPage->page.GCPhys);
1765 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
1766
1767 pPage->page.u64Hash = csamR3CalcPageHash(pVM, GCPtr);
1768 ret = RTAvlPVInsert(&pVM->csam.s.pPageTree, &pPage->Core);
1769 Assert(ret);
1770
1771#ifdef CSAM_MONITOR_CODE_PAGES
1772 AssertRelease(!fInCSAMCodePageInvalidate);
1773
1774 switch (enmTag)
1775 {
1776 case CSAM_TAG_PATM:
1777 case CSAM_TAG_REM:
1778#ifdef CSAM_MONITOR_CSAM_CODE_PAGES
1779 case CSAM_TAG_CSAM:
1780#endif
1781 {
1782 rc = PGMR3HandlerVirtualRegister(pVM, PGMVIRTHANDLERTYPE_WRITE, GCPtr, GCPtr + (PAGE_SIZE - 1) /* inclusive! */,
1783 (fMonitorInvalidation) ? CSAMCodePageInvalidate : 0, CSAMCodePageWriteHandler, "CSAMGCCodePageWriteHandler", 0,
1784 csamGetMonitorDescription(enmTag));
1785 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PGM_HANDLER_VIRTUAL_CONFLICT, ("PGMR3HandlerVirtualRegisterEx %RRv failed with %Rrc\n", GCPtr, rc));
1786 if (RT_FAILURE(rc))
1787 Log(("PGMR3HandlerVirtualRegisterEx for %RRv failed with %Rrc\n", GCPtr, rc));
1788
1789 /* Could fail, because it's already monitored. Don't treat that condition as fatal. */
1790
1791 /* Prefetch it in case it's not there yet. */
1792 rc = PGMPrefetchPage(pVCpu, GCPtr);
1793 AssertRC(rc);
1794
1795 rc = PGMShwMakePageReadonly(pVCpu, GCPtr, 0 /*fFlags*/);
1796 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1797
1798 pPage->page.fMonitorActive = true;
1799 STAM_COUNTER_INC(&pVM->csam.s.StatPageMonitor);
1800 break;
1801 }
1802 default:
1803 break; /* to shut up GCC */
1804 }
1805
1806 Log(("csamCreatePageRecord %RRv GCPhys=%RGp\n", GCPtr, pPage->page.GCPhys));
1807
1808#ifdef VBOX_WITH_STATISTICS
1809 switch (enmTag)
1810 {
1811 case CSAM_TAG_CSAM:
1812 STAM_COUNTER_INC(&pVM->csam.s.StatPageCSAM);
1813 break;
1814 case CSAM_TAG_PATM:
1815 STAM_COUNTER_INC(&pVM->csam.s.StatPagePATM);
1816 break;
1817 case CSAM_TAG_REM:
1818 STAM_COUNTER_INC(&pVM->csam.s.StatPageREM);
1819 break;
1820 default:
1821 break; /* to shut up GCC */
1822 }
1823#endif
1824
1825#endif
1826
1827 STAM_COUNTER_INC(&pVM->csam.s.StatNrPages);
1828 if (fMonitorInvalidation)
1829 STAM_COUNTER_INC(&pVM->csam.s.StatNrPagesInv);
1830
1831 return &pPage->page;
1832}
1833
1834/**
1835 * Monitors a code page (if not already monitored)
1836 *
1837 * @returns VBox status code
1838 * @param pVM The VM to operate on.
1839 * @param pPageAddrGC The page to monitor
1840 * @param enmTag Monitor tag
1841 */
1842VMMR3DECL(int) CSAMR3MonitorPage(PVM pVM, RTRCPTR pPageAddrGC, CSAMTAG enmTag)
1843{
1844 PCSAMPAGEREC pPageRec = NULL;
1845 int rc;
1846 bool fMonitorInvalidation;
1847 Assert(pVM->cCpus == 1);
1848 PVMCPU pVCpu = VMMGetCpu0(pVM);
1849
1850 /* Dirty pages must be handled before calling this function!. */
1851 Assert(!pVM->csam.s.cDirtyPages);
1852
1853 if (pVM->csam.s.fScanningStarted == false)
1854 return VINF_SUCCESS; /* too early */
1855
1856 pPageAddrGC &= PAGE_BASE_GC_MASK;
1857
1858 Log(("CSAMR3MonitorPage %RRv %d\n", pPageAddrGC, enmTag));
1859
1860 /** @todo implicit assumption */
1861 fMonitorInvalidation = (enmTag == CSAM_TAG_PATM);
1862
1863 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)(uintptr_t)pPageAddrGC);
1864 if (pPageRec == NULL)
1865 {
1866 uint64_t fFlags;
1867
1868 rc = PGMGstGetPage(pVCpu, pPageAddrGC, &fFlags, NULL);
1869 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
1870 if ( rc == VINF_SUCCESS
1871 && (fFlags & X86_PTE_US))
1872 {
1873 /* We don't care about user pages. */
1874 STAM_COUNTER_INC(&pVM->csam.s.StatNrUserPages);
1875 return VINF_SUCCESS;
1876 }
1877
1878 csamCreatePageRecord(pVM, pPageAddrGC, enmTag, true /* 32 bits code */, fMonitorInvalidation);
1879
1880 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)(uintptr_t)pPageAddrGC);
1881 Assert(pPageRec);
1882 }
1883 /** @todo reference count */
1884
1885#ifdef CSAM_MONITOR_CSAM_CODE_PAGES
1886 Assert(pPageRec->page.fMonitorActive);
1887#endif
1888
1889#ifdef CSAM_MONITOR_CODE_PAGES
1890 if (!pPageRec->page.fMonitorActive)
1891 {
1892 Log(("CSAMR3MonitorPage: activate monitoring for %RRv\n", pPageAddrGC));
1893
1894 rc = PGMR3HandlerVirtualRegister(pVM, PGMVIRTHANDLERTYPE_WRITE, pPageAddrGC, pPageAddrGC + (PAGE_SIZE - 1) /* inclusive! */,
1895 (fMonitorInvalidation) ? CSAMCodePageInvalidate : 0, CSAMCodePageWriteHandler, "CSAMGCCodePageWriteHandler", 0,
1896 csamGetMonitorDescription(enmTag));
1897 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PGM_HANDLER_VIRTUAL_CONFLICT, ("PGMR3HandlerVirtualRegisterEx %RRv failed with %Rrc\n", pPageAddrGC, rc));
1898 if (RT_FAILURE(rc))
1899 Log(("PGMR3HandlerVirtualRegisterEx for %RRv failed with %Rrc\n", pPageAddrGC, rc));
1900
1901 /* Could fail, because it's already monitored. Don't treat that condition as fatal. */
1902
1903 /* Prefetch it in case it's not there yet. */
1904 rc = PGMPrefetchPage(pVCpu, pPageAddrGC);
1905 AssertRC(rc);
1906
1907 rc = PGMShwMakePageReadonly(pVCpu, pPageAddrGC, 0 /*fFlags*/);
1908 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1909
1910 STAM_COUNTER_INC(&pVM->csam.s.StatPageMonitor);
1911
1912 pPageRec->page.fMonitorActive = true;
1913 pPageRec->page.fMonitorInvalidation = fMonitorInvalidation;
1914 }
1915 else
1916 if ( !pPageRec->page.fMonitorInvalidation
1917 && fMonitorInvalidation)
1918 {
1919 Assert(pPageRec->page.fMonitorActive);
1920 PGMHandlerVirtualChangeInvalidateCallback(pVM, pPageRec->page.pPageGC, CSAMCodePageInvalidate);
1921 pPageRec->page.fMonitorInvalidation = true;
1922 STAM_COUNTER_INC(&pVM->csam.s.StatNrPagesInv);
1923
1924 /* Prefetch it in case it's not there yet. */
1925 rc = PGMPrefetchPage(pVCpu, pPageAddrGC);
1926 AssertRC(rc);
1927
1928 /* Make sure it's readonly. Page invalidation may have modified the attributes. */
1929 rc = PGMShwMakePageReadonly(pVCpu, pPageAddrGC, 0 /*fFlags*/);
1930 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1931 }
1932
1933#if 0 /* def VBOX_STRICT -> very annoying) */
1934 if (pPageRec->page.fMonitorActive)
1935 {
1936 uint64_t fPageShw;
1937 RTHCPHYS GCPhys;
1938 rc = PGMShwGetPage(pVCpu, pPageAddrGC, &fPageShw, &GCPhys);
1939// AssertMsg( (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1940// || !(fPageShw & X86_PTE_RW)
1941// || (pPageRec->page.GCPhys == 0), ("Shadow page flags for %RRv (%RHp) aren't readonly (%RX64)!!\n", pPageAddrGC, GCPhys, fPageShw));
1942 }
1943#endif
1944
1945 if (pPageRec->page.GCPhys == 0)
1946 {
1947 /* Prefetch it in case it's not there yet. */
1948 rc = PGMPrefetchPage(pVCpu, pPageAddrGC);
1949 AssertRC(rc);
1950 /* The page was changed behind our back. It won't be made read-only until the next SyncCR3, so force it here. */
1951 rc = PGMShwMakePageReadonly(pVCpu, pPageAddrGC, 0 /*fFlags*/);
1952 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1953 }
1954#endif /* CSAM_MONITOR_CODE_PAGES */
1955 return VINF_SUCCESS;
1956}
1957
1958/**
1959 * Unmonitors a code page
1960 *
1961 * @returns VBox status code
1962 * @param pVM The VM to operate on.
1963 * @param pPageAddrGC The page to monitor
1964 * @param enmTag Monitor tag
1965 */
1966VMMR3DECL(int) CSAMR3UnmonitorPage(PVM pVM, RTRCPTR pPageAddrGC, CSAMTAG enmTag)
1967{
1968 pPageAddrGC &= PAGE_BASE_GC_MASK;
1969
1970 Log(("CSAMR3UnmonitorPage %RRv %d\n", pPageAddrGC, enmTag));
1971
1972 Assert(enmTag == CSAM_TAG_REM);
1973
1974#ifdef VBOX_STRICT
1975 PCSAMPAGEREC pPageRec;
1976
1977 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)(uintptr_t)pPageAddrGC);
1978 Assert(pPageRec && pPageRec->page.enmTag == enmTag);
1979#endif
1980 return CSAMR3RemovePage(pVM, pPageAddrGC);
1981}
1982
1983/**
1984 * Removes a page record from our lookup tree
1985 *
1986 * @returns VBox status code
1987 * @param pVM The VM to operate on.
1988 * @param GCPtr Page address
1989 */
1990static int csamRemovePageRecord(PVM pVM, RTRCPTR GCPtr)
1991{
1992 PCSAMPAGEREC pPageRec;
1993 Assert(pVM->cCpus == 1);
1994 PVMCPU pVCpu = VMMGetCpu0(pVM);
1995
1996 Log(("csamRemovePageRecord %RRv\n", GCPtr));
1997 pPageRec = (PCSAMPAGEREC)RTAvlPVRemove(&pVM->csam.s.pPageTree, (AVLPVKEY)(uintptr_t)GCPtr);
1998
1999 if (pPageRec)
2000 {
2001 STAM_COUNTER_INC(&pVM->csam.s.StatNrRemovedPages);
2002
2003#ifdef CSAM_MONITOR_CODE_PAGES
2004 if (pPageRec->page.fMonitorActive)
2005 {
2006 /* @todo -> this is expensive (cr3 reload)!!!
2007 * if this happens often, then reuse it instead!!!
2008 */
2009 Assert(!fInCSAMCodePageInvalidate);
2010 STAM_COUNTER_DEC(&pVM->csam.s.StatPageMonitor);
2011 PGMHandlerVirtualDeregister(pVM, GCPtr);
2012 }
2013 if (pPageRec->page.enmTag == CSAM_TAG_PATM)
2014 {
2015 /* Make sure the recompiler flushes its cache as this page is no longer monitored. */
2016 STAM_COUNTER_INC(&pVM->csam.s.StatPageRemoveREMFlush);
2017 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
2018 }
2019#endif
2020
2021#ifdef VBOX_WITH_STATISTICS
2022 switch (pPageRec->page.enmTag)
2023 {
2024 case CSAM_TAG_CSAM:
2025 STAM_COUNTER_DEC(&pVM->csam.s.StatPageCSAM);
2026 break;
2027 case CSAM_TAG_PATM:
2028 STAM_COUNTER_DEC(&pVM->csam.s.StatPagePATM);
2029 break;
2030 case CSAM_TAG_REM:
2031 STAM_COUNTER_DEC(&pVM->csam.s.StatPageREM);
2032 break;
2033 default:
2034 break; /* to shut up GCC */
2035 }
2036#endif
2037
2038 if (pPageRec->page.pBitmap) MMR3HeapFree(pPageRec->page.pBitmap);
2039 MMR3HeapFree(pPageRec);
2040 }
2041 else
2042 AssertFailed();
2043
2044 return VINF_SUCCESS;
2045}
2046
2047/**
2048 * Callback for delayed writes from non-EMT threads
2049 *
2050 * @param pVM VM Handle.
2051 * @param GCPtr The virtual address the guest is writing to. (not correct if it's an alias!)
2052 * @param cbBuf How much it's reading/writing.
2053 */
2054static DECLCALLBACK(void) CSAMDelayedWriteHandler(PVM pVM, RTRCPTR GCPtr, size_t cbBuf)
2055{
2056 int rc = PATMR3PatchWrite(pVM, GCPtr, (uint32_t)cbBuf);
2057 AssertRC(rc);
2058}
2059
2060/**
2061 * \#PF Handler callback for virtual access handler ranges.
2062 *
2063 * Important to realize that a physical page in a range can have aliases, and
2064 * for ALL and WRITE handlers these will also trigger.
2065 *
2066 * @returns VINF_SUCCESS if the handler have carried out the operation.
2067 * @returns VINF_PGM_HANDLER_DO_DEFAULT if the caller should carry out the access operation.
2068 * @param pVM VM Handle.
2069 * @param GCPtr The virtual address the guest is writing to. (not correct if it's an alias!)
2070 * @param pvPtr The HC mapping of that address.
2071 * @param pvBuf What the guest is reading/writing.
2072 * @param cbBuf How much it's reading/writing.
2073 * @param enmAccessType The access type.
2074 * @param pvUser User argument.
2075 */
2076static DECLCALLBACK(int) CSAMCodePageWriteHandler(PVM pVM, RTGCPTR GCPtr, void *pvPtr, void *pvBuf, size_t cbBuf, PGMACCESSTYPE enmAccessType, void *pvUser)
2077{
2078 int rc;
2079
2080 Assert(enmAccessType == PGMACCESSTYPE_WRITE); NOREF(enmAccessType);
2081 Log(("CSAMCodePageWriteHandler: write to %RGv size=%zu\n", GCPtr, cbBuf));
2082 NOREF(pvUser);
2083
2084 if ( PAGE_ADDRESS(pvPtr) == PAGE_ADDRESS((uintptr_t)pvPtr + cbBuf - 1)
2085 && !memcmp(pvPtr, pvBuf, cbBuf))
2086 {
2087 Log(("CSAMCodePageWriteHandler: dummy write -> ignore\n"));
2088 return VINF_PGM_HANDLER_DO_DEFAULT;
2089 }
2090
2091 if (VM_IS_EMT(pVM))
2092 rc = PATMR3PatchWrite(pVM, GCPtr, (uint32_t)cbBuf);
2093 else
2094 {
2095 /* Queue the write instead otherwise we'll get concurrency issues. */
2096 /** @note in theory not correct to let it write the data first before disabling a patch!
2097 * (if it writes the same data as the patch jump and we replace it with obsolete opcodes)
2098 */
2099 Log(("CSAMCodePageWriteHandler: delayed write!\n"));
2100 AssertCompileSize(RTRCPTR, 4);
2101 rc = VMR3ReqCallVoidNoWait(pVM, VMCPUID_ANY, (PFNRT)CSAMDelayedWriteHandler, 3, pVM, (RTRCPTR)GCPtr, cbBuf);
2102 }
2103 AssertRC(rc);
2104
2105 return VINF_PGM_HANDLER_DO_DEFAULT;
2106}
2107
2108/**
2109 * \#PF Handler callback for invalidation of virtual access handler ranges.
2110 *
2111 * @param pVM VM Handle.
2112 * @param GCPtr The virtual address the guest has changed.
2113 */
2114static DECLCALLBACK(int) CSAMCodePageInvalidate(PVM pVM, RTGCPTR GCPtr)
2115{
2116 fInCSAMCodePageInvalidate = true;
2117 LogFlow(("CSAMCodePageInvalidate %RGv\n", GCPtr));
2118 /** @todo We can't remove the page (which unregisters the virtual handler) as we are called from a DoWithAll on the virtual handler tree. Argh. */
2119 csamFlushPage(pVM, GCPtr, false /* don't remove page! */);
2120 fInCSAMCodePageInvalidate = false;
2121 return VINF_SUCCESS;
2122}
2123
2124/**
2125 * Check if the current instruction has already been checked before
2126 *
2127 * @returns VBox status code. (trap handled or not)
2128 * @param pVM The VM to operate on.
2129 * @param pInstr Instruction pointer
2130 * @param pPage CSAM patch structure pointer
2131 */
2132bool csamIsCodeScanned(PVM pVM, RTRCPTR pInstr, PCSAMPAGE *pPage)
2133{
2134 PCSAMPAGEREC pPageRec;
2135 uint32_t offset;
2136
2137 STAM_PROFILE_START(&pVM->csam.s.StatTimeCheckAddr, a);
2138
2139 offset = pInstr & PAGE_OFFSET_MASK;
2140 pInstr = pInstr & PAGE_BASE_GC_MASK;
2141
2142 Assert(pPage);
2143
2144 if (*pPage && (*pPage)->pPageGC == pInstr)
2145 {
2146 if ((*pPage)->pBitmap == NULL || ASMBitTest((*pPage)->pBitmap, offset))
2147 {
2148 STAM_COUNTER_ADD(&pVM->csam.s.StatNrKnownPagesHC, 1);
2149 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
2150 return true;
2151 }
2152 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
2153 return false;
2154 }
2155
2156 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)(uintptr_t)pInstr);
2157 if (pPageRec)
2158 {
2159 if (pPage) *pPage= &pPageRec->page;
2160 if (pPageRec->page.pBitmap == NULL || ASMBitTest(pPageRec->page.pBitmap, offset))
2161 {
2162 STAM_COUNTER_ADD(&pVM->csam.s.StatNrKnownPagesHC, 1);
2163 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
2164 return true;
2165 }
2166 }
2167 else
2168 {
2169 if (pPage) *pPage = NULL;
2170 }
2171 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
2172 return false;
2173}
2174
2175/**
2176 * Mark an instruction in a page as scanned/not scanned
2177 *
2178 * @param pVM The VM to operate on.
2179 * @param pPage Patch structure pointer
2180 * @param pInstr Instruction pointer
2181 * @param opsize Instruction size
2182 * @param fScanned Mark as scanned or not
2183 */
2184static void csamMarkCode(PVM pVM, PCSAMPAGE pPage, RTRCPTR pInstr, uint32_t opsize, bool fScanned)
2185{
2186 LogFlow(("csamMarkCodeAsScanned %RRv opsize=%d\n", pInstr, opsize));
2187 CSAMMarkPage(pVM, pInstr, fScanned);
2188
2189 /** @todo should recreate empty bitmap if !fScanned */
2190 if (pPage->pBitmap == NULL)
2191 return;
2192
2193 if (fScanned)
2194 {
2195 // retn instructions can be scanned more than once
2196 if (ASMBitTest(pPage->pBitmap, pInstr & PAGE_OFFSET_MASK) == 0)
2197 {
2198 pPage->uSize += opsize;
2199 STAM_COUNTER_ADD(&pVM->csam.s.StatNrInstr, 1);
2200 }
2201 if (pPage->uSize >= PAGE_SIZE)
2202 {
2203 Log(("Scanned full page (%RRv) -> free bitmap\n", pInstr & PAGE_BASE_GC_MASK));
2204 MMR3HeapFree(pPage->pBitmap);
2205 pPage->pBitmap = NULL;
2206 }
2207 else
2208 ASMBitSet(pPage->pBitmap, pInstr & PAGE_OFFSET_MASK);
2209 }
2210 else
2211 ASMBitClear(pPage->pBitmap, pInstr & PAGE_OFFSET_MASK);
2212}
2213
2214/**
2215 * Mark an instruction in a page as scanned/not scanned
2216 *
2217 * @returns VBox status code.
2218 * @param pVM The VM to operate on.
2219 * @param pInstr Instruction pointer
2220 * @param opsize Instruction size
2221 * @param fScanned Mark as scanned or not
2222 */
2223VMMR3DECL(int) CSAMR3MarkCode(PVM pVM, RTRCPTR pInstr, uint32_t opsize, bool fScanned)
2224{
2225 PCSAMPAGE pPage = 0;
2226
2227 Assert(!fScanned); /* other case not implemented. */
2228 Assert(!PATMIsPatchGCAddr(pVM, pInstr));
2229
2230 if (csamIsCodeScanned(pVM, pInstr, &pPage) == false)
2231 {
2232 Assert(fScanned == true); /* other case should not be possible */
2233 return VINF_SUCCESS;
2234 }
2235
2236 Log(("CSAMR3MarkCode: %RRv size=%d fScanned=%d\n", pInstr, opsize, fScanned));
2237 csamMarkCode(pVM, pPage, pInstr, opsize, fScanned);
2238 return VINF_SUCCESS;
2239}
2240
2241
2242/**
2243 * Scan and analyse code
2244 *
2245 * @returns VBox status code.
2246 * @param pVM The VM to operate on.
2247 * @param pCtxCore CPU context
2248 * @param pInstrGC Instruction pointer
2249 */
2250VMMR3DECL(int) CSAMR3CheckCodeEx(PVM pVM, PCPUMCTXCORE pCtxCore, RTRCPTR pInstrGC)
2251{
2252 if (EMIsRawRing0Enabled(pVM) == false || PATMIsPatchGCAddr(pVM, pInstrGC) == true)
2253 {
2254 // No use
2255 return VINF_SUCCESS;
2256 }
2257
2258 if (CSAMIsEnabled(pVM))
2259 {
2260 /* Assuming 32 bits code for now. */
2261 Assert(SELMGetCpuModeFromSelector(VMMGetCpu0(pVM), pCtxCore->eflags, pCtxCore->cs, &pCtxCore->csHid) == CPUMODE_32BIT);
2262
2263 pInstrGC = SELMToFlat(pVM, DIS_SELREG_CS, pCtxCore, pInstrGC);
2264 return CSAMR3CheckCode(pVM, pInstrGC);
2265 }
2266 return VINF_SUCCESS;
2267}
2268
2269/**
2270 * Scan and analyse code
2271 *
2272 * @returns VBox status code.
2273 * @param pVM The VM to operate on.
2274 * @param pInstrGC Instruction pointer (0:32 virtual address)
2275 */
2276VMMR3DECL(int) CSAMR3CheckCode(PVM pVM, RTRCPTR pInstrGC)
2277{
2278 int rc;
2279 PCSAMPAGE pPage = NULL;
2280
2281 if ( EMIsRawRing0Enabled(pVM) == false
2282 || PATMIsPatchGCAddr(pVM, pInstrGC) == true)
2283 {
2284 /* Not active. */
2285 return VINF_SUCCESS;
2286 }
2287
2288 if (CSAMIsEnabled(pVM))
2289 {
2290 /* Cache record for CSAMGCVirtToHCVirt */
2291 CSAMP2GLOOKUPREC cacheRec;
2292 RT_ZERO(cacheRec);
2293
2294 STAM_PROFILE_START(&pVM->csam.s.StatTime, a);
2295 rc = csamAnalyseCallCodeStream(pVM, pInstrGC, pInstrGC, true /* 32 bits code */, CSAMR3AnalyseCallback, pPage, &cacheRec);
2296 STAM_PROFILE_STOP(&pVM->csam.s.StatTime, a);
2297 if (cacheRec.Lock.pvMap)
2298 PGMPhysReleasePageMappingLock(pVM, &cacheRec.Lock);
2299
2300 if (rc != VINF_SUCCESS)
2301 {
2302 Log(("csamAnalyseCodeStream failed with %d\n", rc));
2303 return rc;
2304 }
2305 }
2306 return VINF_SUCCESS;
2307}
2308
2309/**
2310 * Flush dirty code pages
2311 *
2312 * @returns VBox status code.
2313 * @param pVM The VM to operate on.
2314 */
2315static int csamR3FlushDirtyPages(PVM pVM)
2316{
2317 Assert(pVM->cCpus == 1);
2318 PVMCPU pVCpu = VMMGetCpu0(pVM);
2319
2320 STAM_PROFILE_START(&pVM->csam.s.StatFlushDirtyPages, a);
2321
2322 for (uint32_t i=0;i<pVM->csam.s.cDirtyPages;i++)
2323 {
2324 int rc;
2325 PCSAMPAGEREC pPageRec;
2326 RTRCPTR GCPtr = pVM->csam.s.pvDirtyBasePage[i];
2327
2328 GCPtr = GCPtr & PAGE_BASE_GC_MASK;
2329
2330#ifdef VBOX_WITH_REM
2331 /* Notify the recompiler that this page has been changed. */
2332 REMR3NotifyCodePageChanged(pVM, pVCpu, GCPtr);
2333#endif
2334
2335 /* Enable write protection again. (use the fault address as it might be an alias) */
2336 rc = PGMShwMakePageReadonly(pVCpu, pVM->csam.s.pvDirtyFaultPage[i], 0 /*fFlags*/);
2337 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
2338
2339 Log(("CSAMR3FlushDirtyPages: flush %RRv (modifypage rc=%Rrc)\n", pVM->csam.s.pvDirtyBasePage[i], rc));
2340
2341 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)(uintptr_t)GCPtr);
2342 if (pPageRec && pPageRec->page.enmTag == CSAM_TAG_REM)
2343 {
2344 uint64_t fFlags;
2345
2346 rc = PGMGstGetPage(pVCpu, GCPtr, &fFlags, NULL);
2347 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
2348 if ( rc == VINF_SUCCESS
2349 && (fFlags & X86_PTE_US))
2350 {
2351 /* We don't care about user pages. */
2352 csamRemovePageRecord(pVM, GCPtr);
2353 STAM_COUNTER_INC(&pVM->csam.s.StatNrUserPages);
2354 }
2355 }
2356 }
2357 pVM->csam.s.cDirtyPages = 0;
2358 STAM_PROFILE_STOP(&pVM->csam.s.StatFlushDirtyPages, a);
2359 return VINF_SUCCESS;
2360}
2361
2362/**
2363 * Flush potential new code pages
2364 *
2365 * @returns VBox status code.
2366 * @param pVM The VM to operate on.
2367 */
2368static int csamR3FlushCodePages(PVM pVM)
2369{
2370 Assert(pVM->cCpus == 1);
2371 PVMCPU pVCpu = VMMGetCpu0(pVM);
2372
2373 for (uint32_t i=0;i<pVM->csam.s.cPossibleCodePages;i++)
2374 {
2375 RTRCPTR GCPtr = pVM->csam.s.pvPossibleCodePage[i];
2376
2377 GCPtr = GCPtr & PAGE_BASE_GC_MASK;
2378
2379 Log(("csamR3FlushCodePages: %RRv\n", GCPtr));
2380 PGMShwMakePageNotPresent(pVCpu, GCPtr, 0 /*fFlags*/);
2381 /* Resync the page to make sure instruction fetch will fault */
2382 CSAMMarkPage(pVM, GCPtr, false);
2383 }
2384 pVM->csam.s.cPossibleCodePages = 0;
2385 return VINF_SUCCESS;
2386}
2387
2388/**
2389 * Perform any pending actions
2390 *
2391 * @returns VBox status code.
2392 * @param pVM The VM to operate on.
2393 * @param pVCpu The VMCPU to operate on.
2394 */
2395VMMR3DECL(int) CSAMR3DoPendingAction(PVM pVM, PVMCPU pVCpu)
2396{
2397 csamR3FlushDirtyPages(pVM);
2398 csamR3FlushCodePages(pVM);
2399
2400 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_CSAM_PENDING_ACTION);
2401 return VINF_SUCCESS;
2402}
2403
2404/**
2405 * Analyse interrupt and trap gates
2406 *
2407 * @returns VBox status code.
2408 * @param pVM The VM to operate on.
2409 * @param iGate Start gate
2410 * @param cGates Number of gates to check
2411 */
2412VMMR3DECL(int) CSAMR3CheckGates(PVM pVM, uint32_t iGate, uint32_t cGates)
2413{
2414 Assert(pVM->cCpus == 1);
2415 PVMCPU pVCpu = VMMGetCpu0(pVM);
2416 uint16_t cbIDT;
2417 RTRCPTR GCPtrIDT = CPUMGetGuestIDTR(pVCpu, &cbIDT);
2418 uint32_t iGateEnd;
2419 uint32_t maxGates;
2420 VBOXIDTE aIDT[256];
2421 PVBOXIDTE pGuestIdte;
2422 int rc;
2423
2424 if (EMIsRawRing0Enabled(pVM) == false)
2425 {
2426 /* Enabling interrupt gates only works when raw ring 0 is enabled. */
2427 //AssertFailed();
2428 return VINF_SUCCESS;
2429 }
2430
2431 /* We only check all gates once during a session */
2432 if ( !pVM->csam.s.fGatesChecked
2433 && cGates != 256)
2434 return VINF_SUCCESS; /* too early */
2435
2436 /* We only check all gates once during a session */
2437 if ( pVM->csam.s.fGatesChecked
2438 && cGates != 1)
2439 return VINF_SUCCESS; /* ignored */
2440
2441 Assert(cGates <= 256);
2442 if (!GCPtrIDT || cGates > 256)
2443 return VERR_INVALID_PARAMETER;
2444
2445 if (cGates != 1)
2446 {
2447 pVM->csam.s.fGatesChecked = true;
2448 for (unsigned i=0;i<RT_ELEMENTS(pVM->csam.s.pvCallInstruction);i++)
2449 {
2450 RTRCPTR pHandler = pVM->csam.s.pvCallInstruction[i];
2451
2452 if (pHandler)
2453 {
2454 PCSAMPAGE pPage = NULL;
2455 CSAMP2GLOOKUPREC cacheRec; /* Cache record for CSAMGCVirtToHCVirt. */
2456 RT_ZERO(cacheRec);
2457
2458 Log(("CSAMCheckGates: checking previous call instruction %RRv\n", pHandler));
2459 STAM_PROFILE_START(&pVM->csam.s.StatTime, a);
2460 rc = csamAnalyseCodeStream(pVM, pHandler, pHandler, true, CSAMR3AnalyseCallback, pPage, &cacheRec);
2461 STAM_PROFILE_STOP(&pVM->csam.s.StatTime, a);
2462 if (cacheRec.Lock.pvMap)
2463 PGMPhysReleasePageMappingLock(pVM, &cacheRec.Lock);
2464
2465 if (rc != VINF_SUCCESS)
2466 {
2467 Log(("CSAMCheckGates: csamAnalyseCodeStream failed with %d\n", rc));
2468 continue;
2469 }
2470 }
2471 }
2472 }
2473
2474 /* Determine valid upper boundary. */
2475 maxGates = (cbIDT+1) / sizeof(VBOXIDTE);
2476 Assert(iGate < maxGates);
2477 if (iGate > maxGates)
2478 return VERR_INVALID_PARAMETER;
2479
2480 if (iGate + cGates > maxGates)
2481 cGates = maxGates - iGate;
2482
2483 GCPtrIDT = GCPtrIDT + iGate * sizeof(VBOXIDTE);
2484 iGateEnd = iGate + cGates;
2485
2486 STAM_PROFILE_START(&pVM->csam.s.StatCheckGates, a);
2487
2488 /*
2489 * Get IDT entries.
2490 */
2491 rc = PGMPhysSimpleReadGCPtr(pVCpu, aIDT, GCPtrIDT, cGates*sizeof(VBOXIDTE));
2492 if (RT_FAILURE(rc))
2493 {
2494 AssertMsgRC(rc, ("Failed to read IDTE! rc=%Rrc\n", rc));
2495 STAM_PROFILE_STOP(&pVM->csam.s.StatCheckGates, a);
2496 return rc;
2497 }
2498 pGuestIdte = &aIDT[0];
2499
2500 for (/*iGate*/; iGate<iGateEnd; iGate++, pGuestIdte++)
2501 {
2502 Assert(TRPMR3GetGuestTrapHandler(pVM, iGate) == TRPM_INVALID_HANDLER);
2503
2504 if ( pGuestIdte->Gen.u1Present
2505 && (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32 || pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_INT_32)
2506 && (pGuestIdte->Gen.u2DPL == 3 || pGuestIdte->Gen.u2DPL == 0)
2507 )
2508 {
2509 RTRCPTR pHandler;
2510 PCSAMPAGE pPage = NULL;
2511 DBGFSELINFO selInfo;
2512 CSAMP2GLOOKUPREC cacheRec; /* Cache record for CSAMGCVirtToHCVirt. */
2513 RT_ZERO(cacheRec);
2514
2515 pHandler = VBOXIDTE_OFFSET(*pGuestIdte);
2516 pHandler = SELMToFlatBySel(pVM, pGuestIdte->Gen.u16SegSel, pHandler);
2517
2518 rc = SELMR3GetSelectorInfo(pVM, pVCpu, pGuestIdte->Gen.u16SegSel, &selInfo);
2519 if ( RT_FAILURE(rc)
2520 || (selInfo.fFlags & (DBGFSELINFO_FLAGS_NOT_PRESENT | DBGFSELINFO_FLAGS_INVALID))
2521 || selInfo.GCPtrBase != 0
2522 || selInfo.cbLimit != ~0U
2523 )
2524 {
2525 /* Refuse to patch a handler whose idt cs selector isn't wide open. */
2526 Log(("CSAMCheckGates: check gate %d failed due to rc %Rrc GCPtrBase=%RRv limit=%x\n", iGate, rc, selInfo.GCPtrBase, selInfo.cbLimit));
2527 continue;
2528 }
2529
2530
2531 if (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32)
2532 {
2533 Log(("CSAMCheckGates: check trap gate %d at %04X:%08X (flat %RRv)\n", iGate, pGuestIdte->Gen.u16SegSel, VBOXIDTE_OFFSET(*pGuestIdte), pHandler));
2534 }
2535 else
2536 {
2537 Log(("CSAMCheckGates: check interrupt gate %d at %04X:%08X (flat %RRv)\n", iGate, pGuestIdte->Gen.u16SegSel, VBOXIDTE_OFFSET(*pGuestIdte), pHandler));
2538 }
2539
2540 STAM_PROFILE_START(&pVM->csam.s.StatTime, b);
2541 rc = csamAnalyseCodeStream(pVM, pHandler, pHandler, true, CSAMR3AnalyseCallback, pPage, &cacheRec);
2542 STAM_PROFILE_STOP(&pVM->csam.s.StatTime, b);
2543 if (cacheRec.Lock.pvMap)
2544 PGMPhysReleasePageMappingLock(pVM, &cacheRec.Lock);
2545
2546 if (rc != VINF_SUCCESS)
2547 {
2548 Log(("CSAMCheckGates: csamAnalyseCodeStream failed with %d\n", rc));
2549 continue;
2550 }
2551 /* OpenBSD guest specific patch test. */
2552 if (iGate >= 0x20)
2553 {
2554 PCPUMCTX pCtx;
2555 DISCPUSTATE cpu;
2556 RTGCUINTPTR32 aOpenBsdPushCSOffset[3] = {0x03, /* OpenBSD 3.7 & 3.8 */
2557 0x2B, /* OpenBSD 4.0 installation ISO */
2558 0x2F}; /* OpenBSD 4.0 after install */
2559
2560 pCtx = CPUMQueryGuestCtxPtr(pVCpu);
2561
2562 for (unsigned i=0;i<RT_ELEMENTS(aOpenBsdPushCSOffset);i++)
2563 {
2564 rc = CPUMR3DisasmInstrCPU(pVM, pVCpu, pCtx, pHandler - aOpenBsdPushCSOffset[i], &cpu, NULL);
2565 if ( rc == VINF_SUCCESS
2566 && cpu.pCurInstr->opcode == OP_PUSH
2567 && cpu.pCurInstr->param1 == OP_PARM_REG_CS)
2568 {
2569 rc = PATMR3InstallPatch(pVM, pHandler - aOpenBsdPushCSOffset[i], PATMFL_CODE32 | PATMFL_GUEST_SPECIFIC);
2570 if (RT_SUCCESS(rc))
2571 Log(("Installed OpenBSD interrupt handler prefix instruction (push cs) patch\n"));
2572 }
2573 }
2574 }
2575
2576 /* Trap gates and certain interrupt gates. */
2577 uint32_t fPatchFlags = PATMFL_CODE32 | PATMFL_IDTHANDLER;
2578
2579 if (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32)
2580 fPatchFlags |= PATMFL_TRAPHANDLER;
2581 else
2582 fPatchFlags |= PATMFL_INTHANDLER;
2583
2584 switch (iGate) {
2585 case 8:
2586 case 10:
2587 case 11:
2588 case 12:
2589 case 13:
2590 case 14:
2591 case 17:
2592 fPatchFlags |= PATMFL_TRAPHANDLER_WITH_ERRORCODE;
2593 break;
2594 default:
2595 /* No error code. */
2596 break;
2597 }
2598
2599 Log(("Installing %s gate handler for 0x%X at %RRv\n", (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32) ? "trap" : "intr", iGate, pHandler));
2600
2601 rc = PATMR3InstallPatch(pVM, pHandler, fPatchFlags);
2602 if (RT_SUCCESS(rc) || rc == VERR_PATM_ALREADY_PATCHED)
2603 {
2604 Log(("Gate handler 0x%X is SAFE!\n", iGate));
2605
2606 RTRCPTR pNewHandlerGC = PATMR3QueryPatchGCPtr(pVM, pHandler);
2607 if (pNewHandlerGC)
2608 {
2609 rc = TRPMR3SetGuestTrapHandler(pVM, iGate, pNewHandlerGC);
2610 if (RT_FAILURE(rc))
2611 Log(("TRPMR3SetGuestTrapHandler %d failed with %Rrc\n", iGate, rc));
2612 }
2613 }
2614 }
2615 } /* for */
2616 STAM_PROFILE_STOP(&pVM->csam.s.StatCheckGates, a);
2617 return VINF_SUCCESS;
2618}
2619
2620/**
2621 * Record previous call instruction addresses
2622 *
2623 * @returns VBox status code.
2624 * @param pVM The VM to operate on.
2625 * @param GCPtrCall Call address
2626 */
2627VMMR3DECL(int) CSAMR3RecordCallAddress(PVM pVM, RTRCPTR GCPtrCall)
2628{
2629 for (unsigned i=0;i<RT_ELEMENTS(pVM->csam.s.pvCallInstruction);i++)
2630 {
2631 if (pVM->csam.s.pvCallInstruction[i] == GCPtrCall)
2632 return VINF_SUCCESS;
2633 }
2634
2635 Log(("CSAMR3RecordCallAddress %RRv\n", GCPtrCall));
2636
2637 pVM->csam.s.pvCallInstruction[pVM->csam.s.iCallInstruction++] = GCPtrCall;
2638 if (pVM->csam.s.iCallInstruction >= RT_ELEMENTS(pVM->csam.s.pvCallInstruction))
2639 pVM->csam.s.iCallInstruction = 0;
2640
2641 return VINF_SUCCESS;
2642}
2643
2644
2645/**
2646 * Query CSAM state (enabled/disabled)
2647 *
2648 * @returns 0 - disabled, 1 - enabled
2649 * @param pVM The VM to operate on.
2650 */
2651VMMR3DECL(int) CSAMR3IsEnabled(PVM pVM)
2652{
2653 return pVM->fCSAMEnabled;
2654}
2655
2656#ifdef VBOX_WITH_DEBUGGER
2657
2658/**
2659 * The '.csamoff' command.
2660 *
2661 * @returns VBox status.
2662 * @param pCmd Pointer to the command descriptor (as registered).
2663 * @param pCmdHlp Pointer to command helper functions.
2664 * @param pVM Pointer to the current VM (if any).
2665 * @param paArgs Pointer to (readonly) array of arguments.
2666 * @param cArgs Number of arguments in the array.
2667 */
2668static DECLCALLBACK(int) csamr3CmdOff(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PVM pVM, PCDBGCVAR paArgs, unsigned cArgs)
2669{
2670 DBGC_CMDHLP_REQ_VM_RET(pCmdHlp, pCmd, pVM);
2671 NOREF(cArgs); NOREF(paArgs);
2672
2673 int rc = CSAMDisableScanning(pVM);
2674 if (RT_FAILURE(rc))
2675 return DBGCCmdHlpFailRc(pCmdHlp, pCmd, rc, "CSAMDisableScanning");
2676 return DBGCCmdHlpPrintf(pCmdHlp, "CSAM Scanning disabled\n");
2677}
2678
2679/**
2680 * The '.csamon' command.
2681 *
2682 * @returns VBox status.
2683 * @param pCmd Pointer to the command descriptor (as registered).
2684 * @param pCmdHlp Pointer to command helper functions.
2685 * @param pVM Pointer to the current VM (if any).
2686 * @param paArgs Pointer to (readonly) array of arguments.
2687 * @param cArgs Number of arguments in the array.
2688 */
2689static DECLCALLBACK(int) csamr3CmdOn(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PVM pVM, PCDBGCVAR paArgs, unsigned cArgs)
2690{
2691 DBGC_CMDHLP_REQ_VM_RET(pCmdHlp, pCmd, pVM);
2692 NOREF(cArgs); NOREF(paArgs);
2693
2694 int rc = CSAMEnableScanning(pVM);
2695 if (RT_FAILURE(rc))
2696 return DBGCCmdHlpFailRc(pCmdHlp, pCmd, rc, "CSAMEnableScanning");
2697 return DBGCCmdHlpPrintf(pCmdHlp, "CSAM Scanning enabled\n");
2698}
2699
2700#endif /* VBOX_WITH_DEBUGGER */
Note: See TracBrowser for help on using the repository browser.

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