VirtualBox

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

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

Corrections

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

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