VirtualBox

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

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

CSAM: 32-bit (gcc) adjustment.

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