VirtualBox

source: vbox/trunk/src/VBox/VMM/PATM/CSAM.cpp@ 25273

Last change on this file since 25273 was 25273, checked in by vboxsync, 15 years ago

CSAM.cpp: -Wshadow

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