VirtualBox

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

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

DBGF,DBGC,++: PVM -> PUVM. Some refactoring and cleanup as well.

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

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