VirtualBox

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

最後變更 在這個檔案從30493是 30493,由 vboxsync 提交於 15 年 前

Demoted some PGM apis to internal only.

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Id
檔案大小: 96.2 KB
 
1/* $Id: CSAM.cpp 30493 2010-06-29 11:59:47Z 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.alldomusa.eu.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 *
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)
680{
681 int rc;
682 R3PTRTYPE(void *) pHCPtr;
683 Assert(pVM->cCpus == 1);
684 PVMCPU pVCpu = VMMGetCpu0(pVM);
685
686 STAM_PROFILE_START(&pVM->csam.s.StatTimeAddrConv, a);
687
688 pHCPtr = PATMR3GCPtrToHCPtr(pVM, pGCPtr);
689 if (pHCPtr) return pHCPtr;
690
691 if (pCacheRec->pPageLocStartHC)
692 {
693 uint32_t offset = pGCPtr & PAGE_OFFSET_MASK;
694 if (pCacheRec->pGuestLoc == (pGCPtr & PAGE_BASE_GC_MASK))
695 {
696 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeAddrConv, a);
697 return pCacheRec->pPageLocStartHC + offset;
698 }
699 }
700
701 rc = PGMPhysGCPtr2R3Ptr(pVCpu, pGCPtr, &pHCPtr);
702 if (rc != VINF_SUCCESS)
703 {
704//// AssertMsgRC(rc, ("MMR3PhysGCVirt2HCVirtEx failed for %RRv\n", pGCPtr));
705 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeAddrConv, a);
706 return NULL;
707 }
708
709 pCacheRec->pPageLocStartHC = (R3PTRTYPE(uint8_t*))((RTHCUINTPTR)pHCPtr & PAGE_BASE_HC_MASK);
710 pCacheRec->pGuestLoc = pGCPtr & PAGE_BASE_GC_MASK;
711 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeAddrConv, a);
712 return pHCPtr;
713}
714
715/**
716 * Read callback for disassembly function; supports reading bytes that cross a page boundary
717 *
718 * @returns VBox status code.
719 * @param pSrc GC source pointer
720 * @param pDest HC destination pointer
721 * @param size Number of bytes to read
722 * @param dwUserdata Callback specific user data (pCpu)
723 *
724 */
725static DECLCALLBACK(int) CSAMR3ReadBytes(RTUINTPTR pSrc, uint8_t *pDest, unsigned size, void *pvUserdata)
726{
727 DISCPUSTATE *pCpu = (DISCPUSTATE *)pvUserdata;
728 PVM pVM = (PVM)pCpu->apvUserData[0];
729 RTHCUINTPTR pInstrHC = (RTHCUINTPTR)pCpu->apvUserData[1];
730 RTGCUINTPTR32 pInstrGC = (uintptr_t)pCpu->apvUserData[2];
731 int orgsize = size;
732 Assert(pVM->cCpus == 1);
733 PVMCPU pVCpu = VMMGetCpu0(pVM);
734
735 /* We are not interested in patched instructions, so read the original opcode bytes. */
736 /** @note single instruction patches (int3) are checked in CSAMR3AnalyseCallback */
737 for (int i=0;i<orgsize;i++)
738 {
739 int rc = PATMR3QueryOpcode(pVM, (RTRCPTR)pSrc, pDest);
740 if (RT_SUCCESS(rc))
741 {
742 pSrc++;
743 pDest++;
744 size--;
745 }
746 else
747 break;
748 }
749 if (size == 0)
750 return VINF_SUCCESS;
751
752 if (PAGE_ADDRESS(pInstrGC) != PAGE_ADDRESS(pSrc + size - 1) && !PATMIsPatchGCAddr(pVM, pSrc))
753 {
754 return PGMPhysSimpleReadGCPtr(pVCpu, pDest, pSrc, size);
755 }
756 else
757 {
758 Assert(pInstrHC);
759
760 /* pInstrHC is the base address; adjust according to the GC pointer. */
761 pInstrHC = pInstrHC + (pSrc - pInstrGC);
762
763 memcpy(pDest, (void *)pInstrHC, size);
764 }
765
766 return VINF_SUCCESS;
767}
768
769inline int CSAMR3DISInstr(PVM pVM, DISCPUSTATE *pCpu, RTRCPTR InstrGC, uint8_t *InstrHC, uint32_t *pOpsize, char *pszOutput)
770{
771 (pCpu)->pfnReadBytes = CSAMR3ReadBytes;
772 (pCpu)->apvUserData[0] = pVM;
773 (pCpu)->apvUserData[1] = InstrHC;
774 (pCpu)->apvUserData[2] = (void *)InstrGC; Assert(sizeof(InstrGC) <= sizeof(pCpu->apvUserData[0]));
775#ifdef DEBUG
776 return DISInstrEx(pCpu, InstrGC, 0, pOpsize, pszOutput, OPTYPE_ALL);
777#else
778 /* We are interested in everything except harmless stuff */
779 return DISInstrEx(pCpu, InstrGC, 0, pOpsize, pszOutput, ~(OPTYPE_INVALID | OPTYPE_HARMLESS | OPTYPE_RRM_MASK));
780#endif
781}
782
783/**
784 * Analyses the instructions following the cli for compliance with our heuristics for cli
785 *
786 * @returns VBox status code.
787 * @param pVM The VM to operate on.
788 * @param pCpu CPU disassembly state
789 * @param pInstrGC Guest context pointer to privileged instruction
790 * @param pCurInstrGC Guest context pointer to the current instruction
791 * @param pCacheRec GC to HC cache record
792 * @param pUserData User pointer (callback specific)
793 *
794 */
795static int CSAMR3AnalyseCallback(PVM pVM, DISCPUSTATE *pCpu, RCPTRTYPE(uint8_t *) pInstrGC, RCPTRTYPE(uint8_t *) pCurInstrGC,
796 PCSAMP2GLOOKUPREC pCacheRec, void *pUserData)
797{
798 PCSAMPAGE pPage = (PCSAMPAGE)pUserData;
799 int rc;
800
801 switch(pCpu->pCurInstr->opcode)
802 {
803 case OP_INT:
804 Assert(pCpu->param1.flags & USE_IMMEDIATE8);
805 if (pCpu->param1.parval == 3)
806 {
807 //two byte int 3
808 return VINF_SUCCESS;
809 }
810 break;
811
812 case OP_ILLUD2:
813 /* This appears to be some kind of kernel panic in Linux 2.4; no point to continue. */
814 case OP_RETN:
815 case OP_INT3:
816 case OP_INVALID:
817#if 1
818 /* removing breaks win2k guests? */
819 case OP_IRET:
820#endif
821 return VINF_SUCCESS;
822 }
823
824 // Check for exit points
825 switch (pCpu->pCurInstr->opcode)
826 {
827 /* It's not a good idea to patch pushf instructions:
828 * - increases the chance of conflicts (code jumping to the next instruction)
829 * - better to patch the cli
830 * - code that branches before the cli will likely hit an int 3
831 * - in general doesn't offer any benefits as we don't allow nested patch blocks (IF is always 1)
832 */
833 case OP_PUSHF:
834 case OP_POPF:
835 break;
836
837 case OP_CLI:
838 {
839 uint32_t cbInstr = 0;
840 uint32_t opsize = pCpu->opsize;
841 bool fCode32 = pPage->fCode32;
842
843 Assert(fCode32);
844
845 PATMR3AddHint(pVM, pCurInstrGC, (fCode32) ? PATMFL_CODE32 : 0);
846
847 /* Make sure the instructions that follow the cli have not been encountered before. */
848 while (true)
849 {
850 DISCPUSTATE cpu;
851 uint8_t *pCurInstrHC = 0;
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 pCurInstrHC = (uint8_t *)CSAMGCVirtToHCVirt(pVM, pCacheRec, pCurInstrGC);
866 if (pCurInstrHC == NULL)
867 {
868 Log(("CSAMGCVirtToHCVirt failed for %RRv\n", pCurInstrGC));
869 break;
870 }
871 Assert(VALID_PTR(pCurInstrHC));
872
873 cpu.mode = (fCode32) ? CPUMODE_32BIT : CPUMODE_16BIT;
874 rc = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, NULL);
875 AssertRC(rc);
876 if (RT_FAILURE(rc))
877 break;
878 }
879 break;
880 }
881
882 case OP_PUSH:
883 if (pCpu->pCurInstr->param1 != OP_PARM_REG_CS)
884 break;
885
886 /* no break */
887 case OP_STR:
888 case OP_LSL:
889 case OP_LAR:
890 case OP_SGDT:
891 case OP_SLDT:
892 case OP_SIDT:
893 case OP_SMSW:
894 case OP_VERW:
895 case OP_VERR:
896 case OP_CPUID:
897 case OP_IRET:
898#ifdef DEBUG
899 switch(pCpu->pCurInstr->opcode)
900 {
901 case OP_STR:
902 Log(("Privileged instruction at %RRv: str!!\n", pCurInstrGC));
903 break;
904 case OP_LSL:
905 Log(("Privileged instruction at %RRv: lsl!!\n", pCurInstrGC));
906 break;
907 case OP_LAR:
908 Log(("Privileged instruction at %RRv: lar!!\n", pCurInstrGC));
909 break;
910 case OP_SGDT:
911 Log(("Privileged instruction at %RRv: sgdt!!\n", pCurInstrGC));
912 break;
913 case OP_SLDT:
914 Log(("Privileged instruction at %RRv: sldt!!\n", pCurInstrGC));
915 break;
916 case OP_SIDT:
917 Log(("Privileged instruction at %RRv: sidt!!\n", pCurInstrGC));
918 break;
919 case OP_SMSW:
920 Log(("Privileged instruction at %RRv: smsw!!\n", pCurInstrGC));
921 break;
922 case OP_VERW:
923 Log(("Privileged instruction at %RRv: verw!!\n", pCurInstrGC));
924 break;
925 case OP_VERR:
926 Log(("Privileged instruction at %RRv: verr!!\n", pCurInstrGC));
927 break;
928 case OP_CPUID:
929 Log(("Privileged instruction at %RRv: cpuid!!\n", pCurInstrGC));
930 break;
931 case OP_PUSH:
932 Log(("Privileged instruction at %RRv: push cs!!\n", pCurInstrGC));
933 break;
934 case OP_IRET:
935 Log(("Privileged instruction at %RRv: iret!!\n", pCurInstrGC));
936 break;
937 }
938#endif
939
940 if (PATMR3HasBeenPatched(pVM, pCurInstrGC) == false)
941 {
942 rc = PATMR3InstallPatch(pVM, pCurInstrGC, (pPage->fCode32) ? PATMFL_CODE32 : 0);
943 if (RT_FAILURE(rc))
944 {
945 Log(("PATMR3InstallPatch failed with %d\n", rc));
946 return VWRN_CONTINUE_ANALYSIS;
947 }
948 }
949 if (pCpu->pCurInstr->opcode == OP_IRET)
950 return VINF_SUCCESS; /* Look no further in this branch. */
951
952 return VWRN_CONTINUE_ANALYSIS;
953
954 case OP_JMP:
955 case OP_CALL:
956 {
957 // return or jump/call through a jump table
958 if (OP_PARM_VTYPE(pCpu->pCurInstr->param1) != OP_PARM_J)
959 {
960#ifdef DEBUG
961 switch(pCpu->pCurInstr->opcode)
962 {
963 case OP_JMP:
964 Log(("Control Flow instruction at %RRv: jmp!!\n", pCurInstrGC));
965 break;
966 case OP_CALL:
967 Log(("Control Flow instruction at %RRv: call!!\n", pCurInstrGC));
968 break;
969 }
970#endif
971 return VWRN_CONTINUE_ANALYSIS;
972 }
973 return VWRN_CONTINUE_ANALYSIS;
974 }
975
976 }
977
978 return VWRN_CONTINUE_ANALYSIS;
979}
980
981#ifdef CSAM_ANALYSE_BEYOND_RET
982/**
983 * Wrapper for csamAnalyseCodeStream for call instructions.
984 *
985 * @returns VBox status code.
986 * @param pVM The VM to operate on.
987 * @param pInstrGC Guest context pointer to privileged instruction
988 * @param pCurInstrGC Guest context pointer to the current instruction
989 * @param fCode32 16 or 32 bits code
990 * @param pfnCSAMR3Analyse Callback for testing the disassembled instruction
991 * @param pUserData User pointer (callback specific)
992 *
993 */
994static int csamAnalyseCallCodeStream(PVM pVM, RCPTRTYPE(uint8_t *) pInstrGC, RCPTRTYPE(uint8_t *) pCurInstrGC, bool fCode32,
995 PFN_CSAMR3ANALYSE pfnCSAMR3Analyse, void *pUserData, PCSAMP2GLOOKUPREC pCacheRec)
996{
997 int rc;
998 CSAMCALLEXITREC CallExitRec;
999 PCSAMCALLEXITREC pOldCallRec;
1000 PCSAMPAGE pPage = 0;
1001 uint32_t i;
1002
1003 CallExitRec.cInstrAfterRet = 0;
1004
1005 pOldCallRec = pCacheRec->pCallExitRec;
1006 pCacheRec->pCallExitRec = &CallExitRec;
1007
1008 rc = csamAnalyseCodeStream(pVM, pInstrGC, pCurInstrGC, fCode32, pfnCSAMR3Analyse, pUserData, pCacheRec);
1009
1010 for (i=0;i<CallExitRec.cInstrAfterRet;i++)
1011 {
1012 PCSAMPAGE pPage = 0;
1013
1014 pCurInstrGC = CallExitRec.pInstrAfterRetGC[i];
1015
1016 /* Check if we've previously encountered the instruction after the ret. */
1017 if (csamIsCodeScanned(pVM, pCurInstrGC, &pPage) == false)
1018 {
1019 DISCPUSTATE cpu;
1020 uint32_t opsize;
1021 uint8_t *pCurInstrHC = 0;
1022 int rc2;
1023#ifdef DEBUG
1024 char szOutput[256];
1025#endif
1026 if (pPage == NULL)
1027 {
1028 /* New address; let's take a look at it. */
1029 pPage = csamCreatePageRecord(pVM, pCurInstrGC, CSAM_TAG_CSAM, fCode32);
1030 if (pPage == NULL)
1031 {
1032 rc = VERR_NO_MEMORY;
1033 goto done;
1034 }
1035 }
1036
1037 /**
1038 * Some generic requirements for recognizing an adjacent function:
1039 * - alignment fillers that consist of:
1040 * - nop
1041 * - lea genregX, [genregX (+ 0)]
1042 * - push ebp after the filler (can extend this later); aligned at at least a 4 byte boundary
1043 */
1044 for (int j=0;j<16;j++)
1045 {
1046 pCurInstrHC = (uint8_t *)CSAMGCVirtToHCVirt(pVM, pCacheRec, pCurInstrGC);
1047 if (pCurInstrHC == NULL)
1048 {
1049 Log(("CSAMGCVirtToHCVirt failed for %RRv\n", pCurInstrGC));
1050 goto done;
1051 }
1052 Assert(VALID_PTR(pCurInstrHC));
1053
1054 cpu.mode = (fCode32) ? CPUMODE_32BIT : CPUMODE_16BIT;
1055 STAM_PROFILE_START(&pVM->csam.s.StatTimeDisasm, a);
1056#ifdef DEBUG
1057 rc2 = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, szOutput);
1058 if (RT_SUCCESS(rc2)) Log(("CSAM Call Analysis: %s", szOutput));
1059#else
1060 rc2 = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, NULL);
1061#endif
1062 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeDisasm, a);
1063 if (RT_FAILURE(rc2))
1064 {
1065 Log(("Disassembly failed at %RRv with %Rrc (probably page not present) -> return to caller\n", pCurInstrGC, rc2));
1066 goto done;
1067 }
1068
1069 STAM_COUNTER_ADD(&pVM->csam.s.StatNrBytesRead, opsize);
1070
1071 RCPTRTYPE(uint8_t *) addr = 0;
1072 PCSAMPAGE pJmpPage = NULL;
1073
1074 if (PAGE_ADDRESS(pCurInstrGC) != PAGE_ADDRESS(pCurInstrGC + opsize - 1))
1075 {
1076 if (!PGMGstIsPagePresent(pVM, pCurInstrGC + opsize - 1))
1077 {
1078 /// @todo fault in the page
1079 Log(("Page for current instruction %RRv is not present!!\n", pCurInstrGC));
1080 goto done;
1081 }
1082 //all is fine, let's continue
1083 csamR3CheckPageRecord(pVM, pCurInstrGC + opsize - 1);
1084 }
1085
1086 switch (cpu.pCurInstr->opcode)
1087 {
1088 case OP_NOP:
1089 case OP_INT3:
1090 break; /* acceptable */
1091
1092 case OP_LEA:
1093 /* Must be similar to:
1094 *
1095 * lea esi, [esi]
1096 * lea esi, [esi+0]
1097 * Any register is allowed as long as source and destination are identical.
1098 */
1099 if ( cpu.param1.flags != USE_REG_GEN32
1100 || ( cpu.param2.flags != USE_REG_GEN32
1101 && ( !(cpu.param2.flags & USE_REG_GEN32)
1102 || !(cpu.param2.flags & (USE_DISPLACEMENT8|USE_DISPLACEMENT16|USE_DISPLACEMENT32))
1103 || cpu.param2.parval != 0
1104 )
1105 )
1106 || cpu.param1.base.reg_gen32 != cpu.param2.base.reg_gen32
1107 )
1108 {
1109 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunctionFailed);
1110 goto next_function;
1111 }
1112 break;
1113
1114 case OP_PUSH:
1115 {
1116 if ( (pCurInstrGC & 0x3) != 0
1117 || cpu.param1.flags != USE_REG_GEN32
1118 || cpu.param1.base.reg_gen32 != USE_REG_EBP
1119 )
1120 {
1121 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunctionFailed);
1122 goto next_function;
1123 }
1124
1125 if (csamIsCodeScanned(pVM, pCurInstrGC, &pPage) == false)
1126 {
1127 CSAMCALLEXITREC CallExitRec2;
1128 CallExitRec2.cInstrAfterRet = 0;
1129
1130 pCacheRec->pCallExitRec = &CallExitRec2;
1131
1132 /* Analyse the function. */
1133 Log(("Found new function at %RRv\n", pCurInstrGC));
1134 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunction);
1135 csamAnalyseCallCodeStream(pVM, pInstrGC, pCurInstrGC, fCode32, pfnCSAMR3Analyse, pUserData, pCacheRec);
1136 }
1137 goto next_function;
1138 }
1139
1140 case OP_SUB:
1141 {
1142 if ( (pCurInstrGC & 0x3) != 0
1143 || cpu.param1.flags != USE_REG_GEN32
1144 || cpu.param1.base.reg_gen32 != USE_REG_ESP
1145 )
1146 {
1147 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunctionFailed);
1148 goto next_function;
1149 }
1150
1151 if (csamIsCodeScanned(pVM, pCurInstrGC, &pPage) == false)
1152 {
1153 CSAMCALLEXITREC CallExitRec2;
1154 CallExitRec2.cInstrAfterRet = 0;
1155
1156 pCacheRec->pCallExitRec = &CallExitRec2;
1157
1158 /* Analyse the function. */
1159 Log(("Found new function at %RRv\n", pCurInstrGC));
1160 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunction);
1161 csamAnalyseCallCodeStream(pVM, pInstrGC, pCurInstrGC, fCode32, pfnCSAMR3Analyse, pUserData, pCacheRec);
1162 }
1163 goto next_function;
1164 }
1165
1166 default:
1167 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunctionFailed);
1168 goto next_function;
1169 }
1170 /* Mark it as scanned. */
1171 csamMarkCode(pVM, pPage, pCurInstrGC, opsize, true);
1172 pCurInstrGC += opsize;
1173 } /* for at most 16 instructions */
1174next_function:
1175 ; /* MSVC complains otherwise */
1176 }
1177 }
1178done:
1179 pCacheRec->pCallExitRec = pOldCallRec;
1180 return rc;
1181}
1182#else
1183#define csamAnalyseCallCodeStream csamAnalyseCodeStream
1184#endif
1185
1186/**
1187 * Disassembles the code stream until the callback function detects a failure or decides everything is acceptable
1188 *
1189 * @returns VBox status code.
1190 * @param pVM The VM to operate on.
1191 * @param pInstrGC Guest context pointer to privileged instruction
1192 * @param pCurInstrGC Guest context pointer to the current instruction
1193 * @param fCode32 16 or 32 bits code
1194 * @param pfnCSAMR3Analyse Callback for testing the disassembled instruction
1195 * @param pUserData User pointer (callback specific)
1196 *
1197 */
1198static int csamAnalyseCodeStream(PVM pVM, RCPTRTYPE(uint8_t *) pInstrGC, RCPTRTYPE(uint8_t *) pCurInstrGC, bool fCode32,
1199 PFN_CSAMR3ANALYSE pfnCSAMR3Analyse, void *pUserData, PCSAMP2GLOOKUPREC pCacheRec)
1200{
1201 DISCPUSTATE cpu;
1202 PCSAMPAGE pPage = (PCSAMPAGE)pUserData;
1203 int rc = VWRN_CONTINUE_ANALYSIS;
1204 uint32_t opsize;
1205 R3PTRTYPE(uint8_t *) pCurInstrHC = 0;
1206 int rc2;
1207 Assert(pVM->cCpus == 1);
1208 PVMCPU pVCpu = VMMGetCpu0(pVM);
1209
1210#ifdef DEBUG
1211 char szOutput[256];
1212#endif
1213
1214 LogFlow(("csamAnalyseCodeStream: code at %RRv depth=%d\n", pCurInstrGC, pCacheRec->depth));
1215
1216 pVM->csam.s.fScanningStarted = true;
1217
1218 pCacheRec->depth++;
1219 /*
1220 * Limit the call depth. (rather arbitrary upper limit; too low and we won't detect certain
1221 * cpuid instructions in Linux kernels; too high and we waste too much time scanning code)
1222 * (512 is necessary to detect cpuid instructions in Red Hat EL4; see defect 1355)
1223 * @note we are using a lot of stack here. couple of 100k when we go to the full depth (!)
1224 */
1225 if (pCacheRec->depth > 512)
1226 {
1227 LogFlow(("CSAM: maximum calldepth reached for %RRv\n", pCurInstrGC));
1228 pCacheRec->depth--;
1229 return VINF_SUCCESS; //let's not go on forever
1230 }
1231
1232 Assert(!PATMIsPatchGCAddr(pVM, pCurInstrGC));
1233 csamR3CheckPageRecord(pVM, pCurInstrGC);
1234
1235 while(rc == VWRN_CONTINUE_ANALYSIS)
1236 {
1237 if (csamIsCodeScanned(pVM, pCurInstrGC, &pPage) == false)
1238 {
1239 if (pPage == NULL)
1240 {
1241 /* New address; let's take a look at it. */
1242 pPage = csamCreatePageRecord(pVM, pCurInstrGC, CSAM_TAG_CSAM, fCode32);
1243 if (pPage == NULL)
1244 {
1245 rc = VERR_NO_MEMORY;
1246 goto done;
1247 }
1248 }
1249 }
1250 else
1251 {
1252 LogFlow(("Code at %RRv has been scanned before\n", pCurInstrGC));
1253 rc = VINF_SUCCESS;
1254 goto done;
1255 }
1256
1257 pCurInstrHC = (uint8_t *)CSAMGCVirtToHCVirt(pVM, pCacheRec, pCurInstrGC);
1258 if (pCurInstrHC == NULL)
1259 {
1260 Log(("CSAMGCVirtToHCVirt failed for %RRv\n", pCurInstrGC));
1261 rc = VERR_PATCHING_REFUSED;
1262 goto done;
1263 }
1264 Assert(VALID_PTR(pCurInstrHC));
1265
1266 cpu.mode = (fCode32) ? CPUMODE_32BIT : CPUMODE_16BIT;
1267 STAM_PROFILE_START(&pVM->csam.s.StatTimeDisasm, a);
1268#ifdef DEBUG
1269 rc2 = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, szOutput);
1270 if (RT_SUCCESS(rc2)) Log(("CSAM Analysis: %s", szOutput));
1271#else
1272 rc2 = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, NULL);
1273#endif
1274 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeDisasm, a);
1275 if (RT_FAILURE(rc2))
1276 {
1277 Log(("Disassembly failed at %RRv with %Rrc (probably page not present) -> return to caller\n", pCurInstrGC, rc2));
1278 rc = VINF_SUCCESS;
1279 goto done;
1280 }
1281
1282 STAM_COUNTER_ADD(&pVM->csam.s.StatNrBytesRead, opsize);
1283
1284 csamMarkCode(pVM, pPage, pCurInstrGC, opsize, true);
1285
1286 RCPTRTYPE(uint8_t *) addr = 0;
1287 PCSAMPAGE pJmpPage = NULL;
1288
1289 if (PAGE_ADDRESS(pCurInstrGC) != PAGE_ADDRESS(pCurInstrGC + opsize - 1))
1290 {
1291 if (!PGMGstIsPagePresent(pVCpu, pCurInstrGC + opsize - 1))
1292 {
1293 /// @todo fault in the page
1294 Log(("Page for current instruction %RRv is not present!!\n", pCurInstrGC));
1295 rc = VWRN_CONTINUE_ANALYSIS;
1296 goto next_please;
1297 }
1298 //all is fine, let's continue
1299 csamR3CheckPageRecord(pVM, pCurInstrGC + opsize - 1);
1300 }
1301 /*
1302 * If it's harmless, then don't bother checking it (the disasm tables had better be accurate!)
1303 */
1304 if ((cpu.pCurInstr->optype & ~OPTYPE_RRM_MASK) == OPTYPE_HARMLESS)
1305 {
1306 AssertMsg(pfnCSAMR3Analyse(pVM, &cpu, pInstrGC, pCurInstrGC, pCacheRec, (void *)pPage) == VWRN_CONTINUE_ANALYSIS, ("Instruction incorrectly marked harmless?!?!?\n"));
1307 rc = VWRN_CONTINUE_ANALYSIS;
1308 goto next_please;
1309 }
1310
1311#ifdef CSAM_ANALYSE_BEYOND_RET
1312 /* Remember the address of the instruction following the ret in case the parent instruction was a call. */
1313 if ( pCacheRec->pCallExitRec
1314 && cpu.pCurInstr->opcode == OP_RETN
1315 && pCacheRec->pCallExitRec->cInstrAfterRet < CSAM_MAX_CALLEXIT_RET)
1316 {
1317 pCacheRec->pCallExitRec->pInstrAfterRetGC[pCacheRec->pCallExitRec->cInstrAfterRet] = pCurInstrGC + opsize;
1318 pCacheRec->pCallExitRec->cInstrAfterRet++;
1319 }
1320#endif
1321
1322 rc = pfnCSAMR3Analyse(pVM, &cpu, pInstrGC, pCurInstrGC, pCacheRec, (void *)pPage);
1323 if (rc == VINF_SUCCESS)
1324 goto done;
1325
1326 // For our first attempt, we'll handle only simple relative jumps and calls (immediate offset coded in instruction)
1327 if ( ((cpu.pCurInstr->optype & OPTYPE_CONTROLFLOW) && (OP_PARM_VTYPE(cpu.pCurInstr->param1) == OP_PARM_J))
1328 || (cpu.pCurInstr->opcode == OP_CALL && cpu.param1.flags == USE_DISPLACEMENT32)) /* simple indirect call (call dword ptr [address]) */
1329 {
1330 /* We need to parse 'call dword ptr [address]' type of calls to catch cpuid instructions in some recent Linux distributions (e.g. OpenSuse 10.3) */
1331 if ( cpu.pCurInstr->opcode == OP_CALL
1332 && cpu.param1.flags == USE_DISPLACEMENT32)
1333 {
1334 addr = 0;
1335 PGMPhysSimpleReadGCPtr(pVCpu, &addr, (RTRCUINTPTR)cpu.param1.disp32, sizeof(addr));
1336 }
1337 else
1338 addr = CSAMResolveBranch(&cpu, pCurInstrGC);
1339
1340 if (addr == 0)
1341 {
1342 Log(("We don't support far jumps here!! (%08X)\n", cpu.param1.flags));
1343 rc = VINF_SUCCESS;
1344 break;
1345 }
1346 Assert(!PATMIsPatchGCAddr(pVM, addr));
1347
1348 /* If the target address lies in a patch generated jump, then special action needs to be taken. */
1349 PATMR3DetectConflict(pVM, pCurInstrGC, addr);
1350
1351 /* Same page? */
1352 if (PAGE_ADDRESS(addr) != PAGE_ADDRESS(pCurInstrGC ))
1353 {
1354 if (!PGMGstIsPagePresent(pVCpu, addr))
1355 {
1356 Log(("Page for current instruction %RRv is not present!!\n", addr));
1357 rc = VWRN_CONTINUE_ANALYSIS;
1358 goto next_please;
1359 }
1360
1361 /* All is fine, let's continue. */
1362 csamR3CheckPageRecord(pVM, addr);
1363 }
1364
1365 pJmpPage = NULL;
1366 if (csamIsCodeScanned(pVM, addr, &pJmpPage) == false)
1367 {
1368 if (pJmpPage == NULL)
1369 {
1370 /* New branch target; let's take a look at it. */
1371 pJmpPage = csamCreatePageRecord(pVM, addr, CSAM_TAG_CSAM, fCode32);
1372 if (pJmpPage == NULL)
1373 {
1374 rc = VERR_NO_MEMORY;
1375 goto done;
1376 }
1377 Assert(pPage);
1378 }
1379 if (cpu.pCurInstr->opcode == OP_CALL)
1380 rc = csamAnalyseCallCodeStream(pVM, pInstrGC, addr, fCode32, pfnCSAMR3Analyse, (void *)pJmpPage, pCacheRec);
1381 else
1382 rc = csamAnalyseCodeStream(pVM, pInstrGC, addr, fCode32, pfnCSAMR3Analyse, (void *)pJmpPage, pCacheRec);
1383
1384 if (rc != VINF_SUCCESS) {
1385 goto done;
1386 }
1387 }
1388 if (cpu.pCurInstr->opcode == OP_JMP)
1389 {//unconditional jump; return to caller
1390 rc = VINF_SUCCESS;
1391 goto done;
1392 }
1393
1394 rc = VWRN_CONTINUE_ANALYSIS;
1395 } //if ((cpu.pCurInstr->optype & OPTYPE_CONTROLFLOW) && (OP_PARM_VTYPE(cpu.pCurInstr->param1) == OP_PARM_J))
1396#ifdef CSAM_SCAN_JUMP_TABLE
1397 else
1398 if ( cpu.pCurInstr->opcode == OP_JMP
1399 && (cpu.param1.flags & (USE_DISPLACEMENT32|USE_INDEX|USE_SCALE)) == (USE_DISPLACEMENT32|USE_INDEX|USE_SCALE)
1400 )
1401 {
1402 RTRCPTR pJumpTableGC = (RTRCPTR)cpu.param1.disp32;
1403 uint8_t *pJumpTableHC;
1404 int rc2;
1405
1406 Log(("Jump through jump table\n"));
1407
1408 rc2 = PGMPhysGCPtr2R3Ptr(pVCpu, pJumpTableGC, (PRTHCPTR)&pJumpTableHC);
1409 if (rc2 == VINF_SUCCESS)
1410 {
1411 for (uint32_t i=0;i<2;i++)
1412 {
1413 uint64_t fFlags;
1414
1415 addr = pJumpTableGC + cpu.param1.scale * i;
1416 /* Same page? */
1417 if (PAGE_ADDRESS(addr) != PAGE_ADDRESS(pJumpTableGC))
1418 break;
1419
1420 addr = *(RTRCPTR *)(pJumpTableHC + cpu.param1.scale * i);
1421
1422 rc2 = PGMGstGetPage(pVCpu, addr, &fFlags, NULL);
1423 if ( rc2 != VINF_SUCCESS
1424 || (fFlags & X86_PTE_US)
1425 || !(fFlags & X86_PTE_P)
1426 )
1427 break;
1428
1429 Log(("Jump to %RRv\n", addr));
1430
1431 pJmpPage = NULL;
1432 if (csamIsCodeScanned(pVM, addr, &pJmpPage) == false)
1433 {
1434 if (pJmpPage == NULL)
1435 {
1436 /* New branch target; let's take a look at it. */
1437 pJmpPage = csamCreatePageRecord(pVM, addr, CSAM_TAG_CSAM, fCode32);
1438 if (pJmpPage == NULL)
1439 {
1440 rc = VERR_NO_MEMORY;
1441 goto done;
1442 }
1443 Assert(pPage);
1444 }
1445 rc = csamAnalyseCodeStream(pVM, pInstrGC, addr, fCode32, pfnCSAMR3Analyse, (void *)pJmpPage, pCacheRec);
1446 if (rc != VINF_SUCCESS) {
1447 goto done;
1448 }
1449 }
1450 }
1451 }
1452 }
1453#endif
1454 if (rc != VWRN_CONTINUE_ANALYSIS) {
1455 break; //done!
1456 }
1457next_please:
1458 if (cpu.pCurInstr->opcode == OP_JMP)
1459 {
1460 rc = VINF_SUCCESS;
1461 goto done;
1462 }
1463 pCurInstrGC += opsize;
1464 }
1465done:
1466 pCacheRec->depth--;
1467 return rc;
1468}
1469
1470
1471/**
1472 * Calculates the 64 bits hash value for the current page
1473 *
1474 * @returns hash value
1475 * @param pVM The VM to operate on.
1476 * @param pInstr Page address
1477 */
1478uint64_t csamR3CalcPageHash(PVM pVM, RTRCPTR pInstr)
1479{
1480 uint64_t hash = 0;
1481 uint32_t val[5];
1482 int rc;
1483 Assert(pVM->cCpus == 1);
1484 PVMCPU pVCpu = VMMGetCpu0(pVM);
1485
1486 Assert((pInstr & PAGE_OFFSET_MASK) == 0);
1487
1488 rc = PGMPhysSimpleReadGCPtr(pVCpu, &val[0], pInstr, sizeof(val[0]));
1489 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
1490 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1491 {
1492 Log(("csamR3CalcPageHash: page %RRv not present!!\n", pInstr));
1493 return ~0ULL;
1494 }
1495
1496 rc = PGMPhysSimpleReadGCPtr(pVCpu, &val[1], pInstr+1024, sizeof(val[0]));
1497 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
1498 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1499 {
1500 Log(("csamR3CalcPageHash: page %RRv not present!!\n", pInstr));
1501 return ~0ULL;
1502 }
1503
1504 rc = PGMPhysSimpleReadGCPtr(pVCpu, &val[2], pInstr+2048, sizeof(val[0]));
1505 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
1506 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1507 {
1508 Log(("csamR3CalcPageHash: page %RRv not present!!\n", pInstr));
1509 return ~0ULL;
1510 }
1511
1512 rc = PGMPhysSimpleReadGCPtr(pVCpu, &val[3], pInstr+3072, sizeof(val[0]));
1513 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
1514 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1515 {
1516 Log(("csamR3CalcPageHash: page %RRv not present!!\n", pInstr));
1517 return ~0ULL;
1518 }
1519
1520 rc = PGMPhysSimpleReadGCPtr(pVCpu, &val[4], pInstr+4092, sizeof(val[0]));
1521 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
1522 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1523 {
1524 Log(("csamR3CalcPageHash: page %RRv not present!!\n", pInstr));
1525 return ~0ULL;
1526 }
1527
1528 // don't want to get division by zero traps
1529 val[2] |= 1;
1530 val[4] |= 1;
1531
1532 hash = (uint64_t)val[0] * (uint64_t)val[1] / (uint64_t)val[2] + (val[3]%val[4]);
1533 return (hash == ~0ULL) ? hash - 1 : hash;
1534}
1535
1536
1537/**
1538 * Notify CSAM of a page flush
1539 *
1540 * @returns VBox status code
1541 * @param pVM The VM to operate on.
1542 * @param addr GC address of the page to flush
1543 * @param fRemovePage Page removal flag
1544 */
1545static int csamFlushPage(PVM pVM, RTRCPTR addr, bool fRemovePage)
1546{
1547 PCSAMPAGEREC pPageRec;
1548 int rc;
1549 RTGCPHYS GCPhys = 0;
1550 uint64_t fFlags = 0;
1551 Assert(pVM->cCpus == 1 || !CSAMIsEnabled(pVM));
1552
1553 if (!CSAMIsEnabled(pVM))
1554 return VINF_SUCCESS;
1555
1556 PVMCPU pVCpu = VMMGetCpu0(pVM);
1557
1558 STAM_PROFILE_START(&pVM->csam.s.StatTimeFlushPage, a);
1559
1560 addr = addr & PAGE_BASE_GC_MASK;
1561
1562 /*
1563 * Note: searching for the page in our tree first is more expensive (skipped flushes are two orders of magnitude more common)
1564 */
1565 if (pVM->csam.s.pPageTree == NULL)
1566 {
1567 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1568 return VWRN_CSAM_PAGE_NOT_FOUND;
1569 }
1570
1571 rc = PGMGstGetPage(pVCpu, addr, &fFlags, &GCPhys);
1572 /* Returned at a very early stage (no paging yet presumably). */
1573 if (rc == VERR_NOT_SUPPORTED)
1574 {
1575 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1576 return rc;
1577 }
1578
1579 if (RT_SUCCESS(rc))
1580 {
1581 if ( (fFlags & X86_PTE_US)
1582 || rc == VERR_PGM_PHYS_PAGE_RESERVED
1583 )
1584 {
1585 /* User page -> not relevant for us. */
1586 STAM_COUNTER_ADD(&pVM->csam.s.StatNrFlushesSkipped, 1);
1587 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1588 return VINF_SUCCESS;
1589 }
1590 }
1591 else
1592 if (rc != VERR_PAGE_NOT_PRESENT && rc != VERR_PAGE_TABLE_NOT_PRESENT)
1593 AssertMsgFailed(("PGMR3GetPage %RRv failed with %Rrc\n", addr, rc));
1594
1595 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)addr);
1596 if (pPageRec)
1597 {
1598 if ( GCPhys == pPageRec->page.GCPhys
1599 && (fFlags & X86_PTE_P))
1600 {
1601 STAM_COUNTER_ADD(&pVM->csam.s.StatNrFlushesSkipped, 1);
1602 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1603 return VINF_SUCCESS;
1604 }
1605
1606 Log(("CSAMR3FlushPage: page %RRv has changed -> FLUSH (rc=%Rrc) (Phys: %RGp vs %RGp)\n", addr, rc, GCPhys, pPageRec->page.GCPhys));
1607
1608 STAM_COUNTER_ADD(&pVM->csam.s.StatNrFlushes, 1);
1609
1610 if (fRemovePage)
1611 csamRemovePageRecord(pVM, addr);
1612 else
1613 {
1614 CSAMMarkPage(pVM, addr, false);
1615 pPageRec->page.GCPhys = 0;
1616 pPageRec->page.fFlags = 0;
1617 rc = PGMGstGetPage(pVCpu, addr, &pPageRec->page.fFlags, &pPageRec->page.GCPhys);
1618 if (rc == VINF_SUCCESS)
1619 pPageRec->page.u64Hash = csamR3CalcPageHash(pVM, addr);
1620
1621 if (pPageRec->page.pBitmap == NULL)
1622 {
1623 pPageRec->page.pBitmap = (uint8_t *)MMR3HeapAllocZ(pVM, MM_TAG_CSAM_PATCH, CSAM_PAGE_BITMAP_SIZE);
1624 Assert(pPageRec->page.pBitmap);
1625 if (pPageRec->page.pBitmap == NULL)
1626 return VERR_NO_MEMORY;
1627 }
1628 else
1629 memset(pPageRec->page.pBitmap, 0, CSAM_PAGE_BITMAP_SIZE);
1630 }
1631
1632
1633 /*
1634 * Inform patch manager about the flush; no need to repeat the above check twice.
1635 */
1636 PATMR3FlushPage(pVM, addr);
1637
1638 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1639 return VINF_SUCCESS;
1640 }
1641 else
1642 {
1643 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1644 return VWRN_CSAM_PAGE_NOT_FOUND;
1645 }
1646}
1647
1648/**
1649 * Notify CSAM of a page flush
1650 *
1651 * @returns VBox status code
1652 * @param pVM The VM to operate on.
1653 * @param addr GC address of the page to flush
1654 */
1655VMMR3DECL(int) CSAMR3FlushPage(PVM pVM, RTRCPTR addr)
1656{
1657 return csamFlushPage(pVM, addr, true /* remove page record */);
1658}
1659
1660/**
1661 * Remove a CSAM monitored page. Use with care!
1662 *
1663 * @returns VBox status code
1664 * @param pVM The VM to operate on.
1665 * @param addr GC address of the page to flush
1666 */
1667VMMR3DECL(int) CSAMR3RemovePage(PVM pVM, RTRCPTR addr)
1668{
1669 PCSAMPAGEREC pPageRec;
1670 int rc;
1671
1672 addr = addr & PAGE_BASE_GC_MASK;
1673
1674 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)addr);
1675 if (pPageRec)
1676 {
1677 rc = csamRemovePageRecord(pVM, addr);
1678 if (RT_SUCCESS(rc))
1679 PATMR3FlushPage(pVM, addr);
1680 return VINF_SUCCESS;
1681 }
1682 return VWRN_CSAM_PAGE_NOT_FOUND;
1683}
1684
1685/**
1686 * Check a page record in case a page has been changed
1687 *
1688 * @returns VBox status code. (trap handled or not)
1689 * @param pVM The VM to operate on.
1690 * @param pInstrGC GC instruction pointer
1691 */
1692int csamR3CheckPageRecord(PVM pVM, RTRCPTR pInstrGC)
1693{
1694 PCSAMPAGEREC pPageRec;
1695 uint64_t u64hash;
1696
1697 pInstrGC = pInstrGC & PAGE_BASE_GC_MASK;
1698
1699 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)pInstrGC);
1700 if (pPageRec)
1701 {
1702 u64hash = csamR3CalcPageHash(pVM, pInstrGC);
1703 if (u64hash != pPageRec->page.u64Hash)
1704 csamFlushPage(pVM, pInstrGC, false /* don't remove page record */);
1705 }
1706 else
1707 return VWRN_CSAM_PAGE_NOT_FOUND;
1708
1709 return VINF_SUCCESS;
1710}
1711
1712/**
1713 * Returns monitor description based on CSAM tag
1714 *
1715 * @return description string
1716 * @param enmTag Owner tag
1717 */
1718const char *csamGetMonitorDescription(CSAMTAG enmTag)
1719{
1720 if (enmTag == CSAM_TAG_PATM)
1721 return "CSAM-PATM self-modifying code monitor handler";
1722 else
1723 if (enmTag == CSAM_TAG_REM)
1724 return "CSAM-REM self-modifying code monitor handler";
1725 Assert(enmTag == CSAM_TAG_CSAM);
1726 return "CSAM self-modifying code monitor handler";
1727}
1728
1729/**
1730 * Adds page record to our lookup tree
1731 *
1732 * @returns CSAMPAGE ptr or NULL if failure
1733 * @param pVM The VM to operate on.
1734 * @param GCPtr Page address
1735 * @param enmTag Owner tag
1736 * @param fCode32 16 or 32 bits code
1737 * @param fMonitorInvalidation Monitor page invalidation flag
1738 */
1739static PCSAMPAGE csamCreatePageRecord(PVM pVM, RTRCPTR GCPtr, CSAMTAG enmTag, bool fCode32, bool fMonitorInvalidation)
1740{
1741 PCSAMPAGEREC pPage;
1742 int rc;
1743 bool ret;
1744 Assert(pVM->cCpus == 1);
1745 PVMCPU pVCpu = VMMGetCpu0(pVM);
1746
1747 Log(("New page record for %RRv\n", GCPtr & PAGE_BASE_GC_MASK));
1748
1749 pPage = (PCSAMPAGEREC)MMR3HeapAllocZ(pVM, MM_TAG_CSAM_PATCH, sizeof(CSAMPAGEREC));
1750 if (pPage == NULL)
1751 {
1752 AssertMsgFailed(("csamCreatePageRecord: Out of memory!!!!\n"));
1753 return NULL;
1754 }
1755 /* Round down to page boundary. */
1756 GCPtr = (GCPtr & PAGE_BASE_GC_MASK);
1757 pPage->Core.Key = (AVLPVKEY)GCPtr;
1758 pPage->page.pPageGC = GCPtr;
1759 pPage->page.fCode32 = fCode32;
1760 pPage->page.fMonitorInvalidation = fMonitorInvalidation;
1761 pPage->page.enmTag = enmTag;
1762 pPage->page.fMonitorActive = false;
1763 pPage->page.pBitmap = (uint8_t *)MMR3HeapAllocZ(pVM, MM_TAG_CSAM_PATCH, PAGE_SIZE/sizeof(uint8_t));
1764 rc = PGMGstGetPage(pVCpu, GCPtr, &pPage->page.fFlags, &pPage->page.GCPhys);
1765 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
1766
1767 pPage->page.u64Hash = csamR3CalcPageHash(pVM, GCPtr);
1768 ret = RTAvlPVInsert(&pVM->csam.s.pPageTree, &pPage->Core);
1769 Assert(ret);
1770
1771#ifdef CSAM_MONITOR_CODE_PAGES
1772 AssertRelease(!fInCSAMCodePageInvalidate);
1773
1774 switch (enmTag)
1775 {
1776 case CSAM_TAG_PATM:
1777 case CSAM_TAG_REM:
1778#ifdef CSAM_MONITOR_CSAM_CODE_PAGES
1779 case CSAM_TAG_CSAM:
1780#endif
1781 {
1782 rc = PGMR3HandlerVirtualRegister(pVM, PGMVIRTHANDLERTYPE_WRITE, GCPtr, GCPtr + (PAGE_SIZE - 1) /* inclusive! */,
1783 (fMonitorInvalidation) ? CSAMCodePageInvalidate : 0, CSAMCodePageWriteHandler, "CSAMGCCodePageWriteHandler", 0,
1784 csamGetMonitorDescription(enmTag));
1785 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PGM_HANDLER_VIRTUAL_CONFLICT, ("PGMR3HandlerVirtualRegisterEx %RRv failed with %Rrc\n", GCPtr, rc));
1786 if (RT_FAILURE(rc))
1787 Log(("PGMR3HandlerVirtualRegisterEx for %RRv failed with %Rrc\n", GCPtr, rc));
1788
1789 /* Could fail, because it's already monitored. Don't treat that condition as fatal. */
1790
1791 /* Prefetch it in case it's not there yet. */
1792 rc = PGMPrefetchPage(pVCpu, GCPtr);
1793 AssertRC(rc);
1794
1795 rc = PGMShwMakePageReadonly(pVCpu, GCPtr, 0 /*fFlags*/);
1796 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1797
1798 pPage->page.fMonitorActive = true;
1799 STAM_COUNTER_INC(&pVM->csam.s.StatPageMonitor);
1800 break;
1801 }
1802 default:
1803 break; /* to shut up GCC */
1804 }
1805
1806 Log(("csamCreatePageRecord %RRv GCPhys=%RGp\n", GCPtr, pPage->page.GCPhys));
1807
1808#ifdef VBOX_WITH_STATISTICS
1809 switch (enmTag)
1810 {
1811 case CSAM_TAG_CSAM:
1812 STAM_COUNTER_INC(&pVM->csam.s.StatPageCSAM);
1813 break;
1814 case CSAM_TAG_PATM:
1815 STAM_COUNTER_INC(&pVM->csam.s.StatPagePATM);
1816 break;
1817 case CSAM_TAG_REM:
1818 STAM_COUNTER_INC(&pVM->csam.s.StatPageREM);
1819 break;
1820 default:
1821 break; /* to shut up GCC */
1822 }
1823#endif
1824
1825#endif
1826
1827 STAM_COUNTER_INC(&pVM->csam.s.StatNrPages);
1828 if (fMonitorInvalidation)
1829 STAM_COUNTER_INC(&pVM->csam.s.StatNrPagesInv);
1830
1831 return &pPage->page;
1832}
1833
1834/**
1835 * Monitors a code page (if not already monitored)
1836 *
1837 * @returns VBox status code
1838 * @param pVM The VM to operate on.
1839 * @param pPageAddrGC The page to monitor
1840 * @param enmTag Monitor tag
1841 */
1842VMMR3DECL(int) CSAMR3MonitorPage(PVM pVM, RTRCPTR pPageAddrGC, CSAMTAG enmTag)
1843{
1844 PCSAMPAGEREC pPageRec = NULL;
1845 int rc;
1846 bool fMonitorInvalidation;
1847 Assert(pVM->cCpus == 1);
1848 PVMCPU pVCpu = VMMGetCpu0(pVM);
1849
1850 /* Dirty pages must be handled before calling this function!. */
1851 Assert(!pVM->csam.s.cDirtyPages);
1852
1853 if (pVM->csam.s.fScanningStarted == false)
1854 return VINF_SUCCESS; /* too early */
1855
1856 pPageAddrGC &= PAGE_BASE_GC_MASK;
1857
1858 Log(("CSAMR3MonitorPage %RRv %d\n", pPageAddrGC, enmTag));
1859
1860 /** @todo implicit assumption */
1861 fMonitorInvalidation = (enmTag == CSAM_TAG_PATM);
1862
1863 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)pPageAddrGC);
1864 if (pPageRec == NULL)
1865 {
1866 uint64_t fFlags;
1867
1868 rc = PGMGstGetPage(pVCpu, pPageAddrGC, &fFlags, NULL);
1869 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
1870 if ( rc == VINF_SUCCESS
1871 && (fFlags & X86_PTE_US))
1872 {
1873 /* We don't care about user pages. */
1874 STAM_COUNTER_INC(&pVM->csam.s.StatNrUserPages);
1875 return VINF_SUCCESS;
1876 }
1877
1878 csamCreatePageRecord(pVM, pPageAddrGC, enmTag, true /* 32 bits code */, fMonitorInvalidation);
1879
1880 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)pPageAddrGC);
1881 Assert(pPageRec);
1882 }
1883 /** @todo reference count */
1884
1885#ifdef CSAM_MONITOR_CSAM_CODE_PAGES
1886 Assert(pPageRec->page.fMonitorActive);
1887#endif
1888
1889#ifdef CSAM_MONITOR_CODE_PAGES
1890 if (!pPageRec->page.fMonitorActive)
1891 {
1892 Log(("CSAMR3MonitorPage: activate monitoring for %RRv\n", pPageAddrGC));
1893
1894 rc = PGMR3HandlerVirtualRegister(pVM, PGMVIRTHANDLERTYPE_WRITE, pPageAddrGC, pPageAddrGC + (PAGE_SIZE - 1) /* inclusive! */,
1895 (fMonitorInvalidation) ? CSAMCodePageInvalidate : 0, CSAMCodePageWriteHandler, "CSAMGCCodePageWriteHandler", 0,
1896 csamGetMonitorDescription(enmTag));
1897 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PGM_HANDLER_VIRTUAL_CONFLICT, ("PGMR3HandlerVirtualRegisterEx %RRv failed with %Rrc\n", pPageAddrGC, rc));
1898 if (RT_FAILURE(rc))
1899 Log(("PGMR3HandlerVirtualRegisterEx for %RRv failed with %Rrc\n", pPageAddrGC, rc));
1900
1901 /* Could fail, because it's already monitored. Don't treat that condition as fatal. */
1902
1903 /* Prefetch it in case it's not there yet. */
1904 rc = PGMPrefetchPage(pVCpu, pPageAddrGC);
1905 AssertRC(rc);
1906
1907 rc = PGMShwMakePageReadonly(pVCpu, pPageAddrGC, 0 /*fFlags*/);
1908 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1909
1910 STAM_COUNTER_INC(&pVM->csam.s.StatPageMonitor);
1911
1912 pPageRec->page.fMonitorActive = true;
1913 pPageRec->page.fMonitorInvalidation = fMonitorInvalidation;
1914 }
1915 else
1916 if ( !pPageRec->page.fMonitorInvalidation
1917 && fMonitorInvalidation)
1918 {
1919 Assert(pPageRec->page.fMonitorActive);
1920 PGMHandlerVirtualChangeInvalidateCallback(pVM, pPageRec->page.pPageGC, CSAMCodePageInvalidate);
1921 pPageRec->page.fMonitorInvalidation = true;
1922 STAM_COUNTER_INC(&pVM->csam.s.StatNrPagesInv);
1923
1924 /* Prefetch it in case it's not there yet. */
1925 rc = PGMPrefetchPage(pVCpu, pPageAddrGC);
1926 AssertRC(rc);
1927
1928 /* Make sure it's readonly. Page invalidation may have modified the attributes. */
1929 rc = PGMShwMakePageReadonly(pVCpu, pPageAddrGC, 0 /*fFlags*/);
1930 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1931 }
1932
1933#if 0 /* def VBOX_STRICT -> very annoying) */
1934 if (pPageRec->page.fMonitorActive)
1935 {
1936 uint64_t fPageShw;
1937 RTHCPHYS GCPhys;
1938 rc = PGMShwGetPage(pVCpu, pPageAddrGC, &fPageShw, &GCPhys);
1939// AssertMsg( (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1940// || !(fPageShw & X86_PTE_RW)
1941// || (pPageRec->page.GCPhys == 0), ("Shadow page flags for %RRv (%RHp) aren't readonly (%RX64)!!\n", pPageAddrGC, GCPhys, fPageShw));
1942 }
1943#endif
1944
1945 if (pPageRec->page.GCPhys == 0)
1946 {
1947 /* Prefetch it in case it's not there yet. */
1948 rc = PGMPrefetchPage(pVCpu, pPageAddrGC);
1949 AssertRC(rc);
1950 /* The page was changed behind our back. It won't be made read-only until the next SyncCR3, so force it here. */
1951 rc = PGMShwMakePageReadonly(pVCpu, pPageAddrGC, 0 /*fFlags*/);
1952 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1953 }
1954#endif /* CSAM_MONITOR_CODE_PAGES */
1955 return VINF_SUCCESS;
1956}
1957
1958/**
1959 * Unmonitors a code page
1960 *
1961 * @returns VBox status code
1962 * @param pVM The VM to operate on.
1963 * @param pPageAddrGC The page to monitor
1964 * @param enmTag Monitor tag
1965 */
1966VMMR3DECL(int) CSAMR3UnmonitorPage(PVM pVM, RTRCPTR pPageAddrGC, CSAMTAG enmTag)
1967{
1968 pPageAddrGC &= PAGE_BASE_GC_MASK;
1969
1970 Log(("CSAMR3UnmonitorPage %RRv %d\n", pPageAddrGC, enmTag));
1971
1972 Assert(enmTag == CSAM_TAG_REM);
1973
1974#ifdef VBOX_STRICT
1975 PCSAMPAGEREC pPageRec;
1976
1977 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)pPageAddrGC);
1978 Assert(pPageRec && pPageRec->page.enmTag == enmTag);
1979#endif
1980 return CSAMR3RemovePage(pVM, pPageAddrGC);
1981}
1982
1983/**
1984 * Removes a page record from our lookup tree
1985 *
1986 * @returns VBox status code
1987 * @param pVM The VM to operate on.
1988 * @param GCPtr Page address
1989 */
1990static int csamRemovePageRecord(PVM pVM, RTRCPTR GCPtr)
1991{
1992 PCSAMPAGEREC pPageRec;
1993 Assert(pVM->cCpus == 1);
1994 PVMCPU pVCpu = VMMGetCpu0(pVM);
1995
1996 Log(("csamRemovePageRecord %RRv\n", GCPtr));
1997 pPageRec = (PCSAMPAGEREC)RTAvlPVRemove(&pVM->csam.s.pPageTree, (AVLPVKEY)GCPtr);
1998
1999 if (pPageRec)
2000 {
2001 STAM_COUNTER_INC(&pVM->csam.s.StatNrRemovedPages);
2002
2003#ifdef CSAM_MONITOR_CODE_PAGES
2004 if (pPageRec->page.fMonitorActive)
2005 {
2006 /* @todo -> this is expensive (cr3 reload)!!!
2007 * if this happens often, then reuse it instead!!!
2008 */
2009 Assert(!fInCSAMCodePageInvalidate);
2010 STAM_COUNTER_DEC(&pVM->csam.s.StatPageMonitor);
2011 PGMHandlerVirtualDeregister(pVM, GCPtr);
2012 }
2013 if (pPageRec->page.enmTag == CSAM_TAG_PATM)
2014 {
2015 /* Make sure the recompiler flushes its cache as this page is no longer monitored. */
2016 STAM_COUNTER_INC(&pVM->csam.s.StatPageRemoveREMFlush);
2017 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
2018 }
2019#endif
2020
2021#ifdef VBOX_WITH_STATISTICS
2022 switch (pPageRec->page.enmTag)
2023 {
2024 case CSAM_TAG_CSAM:
2025 STAM_COUNTER_DEC(&pVM->csam.s.StatPageCSAM);
2026 break;
2027 case CSAM_TAG_PATM:
2028 STAM_COUNTER_DEC(&pVM->csam.s.StatPagePATM);
2029 break;
2030 case CSAM_TAG_REM:
2031 STAM_COUNTER_DEC(&pVM->csam.s.StatPageREM);
2032 break;
2033 default:
2034 break; /* to shut up GCC */
2035 }
2036#endif
2037
2038 if (pPageRec->page.pBitmap) MMR3HeapFree(pPageRec->page.pBitmap);
2039 MMR3HeapFree(pPageRec);
2040 }
2041 else
2042 AssertFailed();
2043
2044 return VINF_SUCCESS;
2045}
2046
2047/**
2048 * Callback for delayed writes from non-EMT threads
2049 *
2050 * @param pVM VM Handle.
2051 * @param GCPtr The virtual address the guest is writing to. (not correct if it's an alias!)
2052 * @param cbBuf How much it's reading/writing.
2053 */
2054static DECLCALLBACK(void) CSAMDelayedWriteHandler(PVM pVM, RTRCPTR GCPtr, size_t cbBuf)
2055{
2056 int rc = PATMR3PatchWrite(pVM, GCPtr, (uint32_t)cbBuf);
2057 AssertRC(rc);
2058}
2059
2060/**
2061 * \#PF Handler callback for virtual access handler ranges.
2062 *
2063 * Important to realize that a physical page in a range can have aliases, and
2064 * for ALL and WRITE handlers these will also trigger.
2065 *
2066 * @returns VINF_SUCCESS if the handler have carried out the operation.
2067 * @returns VINF_PGM_HANDLER_DO_DEFAULT if the caller should carry out the access operation.
2068 * @param pVM VM Handle.
2069 * @param GCPtr The virtual address the guest is writing to. (not correct if it's an alias!)
2070 * @param pvPtr The HC mapping of that address.
2071 * @param pvBuf What the guest is reading/writing.
2072 * @param cbBuf How much it's reading/writing.
2073 * @param enmAccessType The access type.
2074 * @param pvUser User argument.
2075 */
2076static DECLCALLBACK(int) CSAMCodePageWriteHandler(PVM pVM, RTGCPTR GCPtr, void *pvPtr, void *pvBuf, size_t cbBuf, PGMACCESSTYPE enmAccessType, void *pvUser)
2077{
2078 int rc;
2079
2080 Assert(enmAccessType == PGMACCESSTYPE_WRITE);
2081 Log(("CSAMCodePageWriteHandler: write to %RGv size=%zu\n", GCPtr, cbBuf));
2082
2083 if ( PAGE_ADDRESS(pvPtr) == PAGE_ADDRESS((uintptr_t)pvPtr + cbBuf - 1)
2084 && !memcmp(pvPtr, pvBuf, cbBuf))
2085 {
2086 Log(("CSAMCodePageWriteHandler: dummy write -> ignore\n"));
2087 return VINF_PGM_HANDLER_DO_DEFAULT;
2088 }
2089
2090 if (VM_IS_EMT(pVM))
2091 {
2092 rc = PATMR3PatchWrite(pVM, GCPtr, (uint32_t)cbBuf);
2093 }
2094 else
2095 {
2096 /* Queue the write instead otherwise we'll get concurrency issues. */
2097 /** @note in theory not correct to let it write the data first before disabling a patch!
2098 * (if it writes the same data as the patch jump and we replace it with obsolete opcodes)
2099 */
2100 Log(("CSAMCodePageWriteHandler: delayed write!\n"));
2101 AssertCompileSize(RTRCPTR, 4);
2102 rc = VMR3ReqCallVoidNoWait(pVM, VMCPUID_ANY, (PFNRT)CSAMDelayedWriteHandler, 3, pVM, (RTRCPTR)GCPtr, cbBuf);
2103 }
2104 AssertRC(rc);
2105
2106 return VINF_PGM_HANDLER_DO_DEFAULT;
2107}
2108
2109/**
2110 * \#PF Handler callback for invalidation of virtual access handler ranges.
2111 *
2112 * @param pVM VM Handle.
2113 * @param GCPtr The virtual address the guest has changed.
2114 */
2115static DECLCALLBACK(int) CSAMCodePageInvalidate(PVM pVM, RTGCPTR GCPtr)
2116{
2117 fInCSAMCodePageInvalidate = true;
2118 LogFlow(("CSAMCodePageInvalidate %RGv\n", GCPtr));
2119 /** @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. */
2120 csamFlushPage(pVM, GCPtr, false /* don't remove page! */);
2121 fInCSAMCodePageInvalidate = false;
2122 return VINF_SUCCESS;
2123}
2124
2125/**
2126 * Check if the current instruction has already been checked before
2127 *
2128 * @returns VBox status code. (trap handled or not)
2129 * @param pVM The VM to operate on.
2130 * @param pInstr Instruction pointer
2131 * @param pPage CSAM patch structure pointer
2132 */
2133bool csamIsCodeScanned(PVM pVM, RTRCPTR pInstr, PCSAMPAGE *pPage)
2134{
2135 PCSAMPAGEREC pPageRec;
2136 uint32_t offset;
2137
2138 STAM_PROFILE_START(&pVM->csam.s.StatTimeCheckAddr, a);
2139
2140 offset = pInstr & PAGE_OFFSET_MASK;
2141 pInstr = pInstr & PAGE_BASE_GC_MASK;
2142
2143 Assert(pPage);
2144
2145 if (*pPage && (*pPage)->pPageGC == pInstr)
2146 {
2147 if ((*pPage)->pBitmap == NULL || ASMBitTest((*pPage)->pBitmap, offset))
2148 {
2149 STAM_COUNTER_ADD(&pVM->csam.s.StatNrKnownPagesHC, 1);
2150 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
2151 return true;
2152 }
2153 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
2154 return false;
2155 }
2156
2157 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)pInstr);
2158 if (pPageRec)
2159 {
2160 if (pPage) *pPage= &pPageRec->page;
2161 if (pPageRec->page.pBitmap == NULL || ASMBitTest(pPageRec->page.pBitmap, offset))
2162 {
2163 STAM_COUNTER_ADD(&pVM->csam.s.StatNrKnownPagesHC, 1);
2164 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
2165 return true;
2166 }
2167 }
2168 else
2169 {
2170 if (pPage) *pPage = NULL;
2171 }
2172 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
2173 return false;
2174}
2175
2176/**
2177 * Mark an instruction in a page as scanned/not scanned
2178 *
2179 * @param pVM The VM to operate on.
2180 * @param pPage Patch structure pointer
2181 * @param pInstr Instruction pointer
2182 * @param opsize Instruction size
2183 * @param fScanned Mark as scanned or not
2184 */
2185static void csamMarkCode(PVM pVM, PCSAMPAGE pPage, RTRCPTR pInstr, uint32_t opsize, bool fScanned)
2186{
2187 LogFlow(("csamMarkCodeAsScanned %RRv opsize=%d\n", pInstr, opsize));
2188 CSAMMarkPage(pVM, pInstr, fScanned);
2189
2190 /** @todo should recreate empty bitmap if !fScanned */
2191 if (pPage->pBitmap == NULL)
2192 return;
2193
2194 if (fScanned)
2195 {
2196 // retn instructions can be scanned more than once
2197 if (ASMBitTest(pPage->pBitmap, pInstr & PAGE_OFFSET_MASK) == 0)
2198 {
2199 pPage->uSize += opsize;
2200 STAM_COUNTER_ADD(&pVM->csam.s.StatNrInstr, 1);
2201 }
2202 if (pPage->uSize >= PAGE_SIZE)
2203 {
2204 Log(("Scanned full page (%RRv) -> free bitmap\n", pInstr & PAGE_BASE_GC_MASK));
2205 MMR3HeapFree(pPage->pBitmap);
2206 pPage->pBitmap = NULL;
2207 }
2208 else
2209 ASMBitSet(pPage->pBitmap, pInstr & PAGE_OFFSET_MASK);
2210 }
2211 else
2212 ASMBitClear(pPage->pBitmap, pInstr & PAGE_OFFSET_MASK);
2213}
2214
2215/**
2216 * Mark an instruction in a page as scanned/not scanned
2217 *
2218 * @returns VBox status code.
2219 * @param pVM The VM to operate on.
2220 * @param pInstr Instruction pointer
2221 * @param opsize Instruction size
2222 * @param fScanned Mark as scanned or not
2223 */
2224VMMR3DECL(int) CSAMR3MarkCode(PVM pVM, RTRCPTR pInstr, uint32_t opsize, bool fScanned)
2225{
2226 PCSAMPAGE pPage = 0;
2227
2228 Assert(!fScanned); /* other case not implemented. */
2229 Assert(!PATMIsPatchGCAddr(pVM, pInstr));
2230
2231 if (csamIsCodeScanned(pVM, pInstr, &pPage) == false)
2232 {
2233 Assert(fScanned == true); /* other case should not be possible */
2234 return VINF_SUCCESS;
2235 }
2236
2237 Log(("CSAMR3MarkCode: %RRv size=%d fScanned=%d\n", pInstr, opsize, fScanned));
2238 csamMarkCode(pVM, pPage, pInstr, opsize, fScanned);
2239 return VINF_SUCCESS;
2240}
2241
2242
2243/**
2244 * Scan and analyse code
2245 *
2246 * @returns VBox status code.
2247 * @param pVM The VM to operate on.
2248 * @param pCtxCore CPU context
2249 * @param pInstrGC Instruction pointer
2250 */
2251VMMR3DECL(int) CSAMR3CheckCodeEx(PVM pVM, PCPUMCTXCORE pCtxCore, RTRCPTR pInstrGC)
2252{
2253 if (EMIsRawRing0Enabled(pVM) == false || PATMIsPatchGCAddr(pVM, pInstrGC) == true)
2254 {
2255 // No use
2256 return VINF_SUCCESS;
2257 }
2258
2259 if (CSAMIsEnabled(pVM))
2260 {
2261 /* Assuming 32 bits code for now. */
2262 Assert(SELMGetCpuModeFromSelector(pVM, pCtxCore->eflags, pCtxCore->cs, &pCtxCore->csHid) == CPUMODE_32BIT);
2263
2264 pInstrGC = SELMToFlat(pVM, DIS_SELREG_CS, pCtxCore, pInstrGC);
2265 return CSAMR3CheckCode(pVM, pInstrGC);
2266 }
2267 return VINF_SUCCESS;
2268}
2269
2270/**
2271 * Scan and analyse code
2272 *
2273 * @returns VBox status code.
2274 * @param pVM The VM to operate on.
2275 * @param pInstrGC Instruction pointer (0:32 virtual address)
2276 */
2277VMMR3DECL(int) CSAMR3CheckCode(PVM pVM, RTRCPTR pInstrGC)
2278{
2279 int rc;
2280 PCSAMPAGE pPage = NULL;
2281
2282 if (EMIsRawRing0Enabled(pVM) == false || PATMIsPatchGCAddr(pVM, pInstrGC) == true)
2283 {
2284 // No use
2285 return VINF_SUCCESS;
2286 }
2287
2288 if (CSAMIsEnabled(pVM))
2289 {
2290 // Cache record for PATMGCVirtToHCVirt
2291 CSAMP2GLOOKUPREC cacheRec;
2292 RT_ZERO(cacheRec);
2293
2294 STAM_PROFILE_START(&pVM->csam.s.StatTime, a);
2295 rc = csamAnalyseCallCodeStream(pVM, pInstrGC, pInstrGC, true /* 32 bits code */, CSAMR3AnalyseCallback, pPage, &cacheRec);
2296 STAM_PROFILE_STOP(&pVM->csam.s.StatTime, a);
2297 if (rc != VINF_SUCCESS)
2298 {
2299 Log(("csamAnalyseCodeStream failed with %d\n", rc));
2300 return rc;
2301 }
2302 }
2303 return VINF_SUCCESS;
2304}
2305
2306/**
2307 * Flush dirty code pages
2308 *
2309 * @returns VBox status code.
2310 * @param pVM The VM to operate on.
2311 */
2312static int csamR3FlushDirtyPages(PVM pVM)
2313{
2314 Assert(pVM->cCpus == 1);
2315 PVMCPU pVCpu = VMMGetCpu0(pVM);
2316
2317 STAM_PROFILE_START(&pVM->csam.s.StatFlushDirtyPages, a);
2318
2319 for (uint32_t i=0;i<pVM->csam.s.cDirtyPages;i++)
2320 {
2321 int rc;
2322 PCSAMPAGEREC pPageRec;
2323 RTRCPTR GCPtr = pVM->csam.s.pvDirtyBasePage[i];
2324
2325 GCPtr = GCPtr & PAGE_BASE_GC_MASK;
2326
2327 /* Notify the recompiler that this page has been changed. */
2328 REMR3NotifyCodePageChanged(pVM, pVCpu, GCPtr);
2329
2330 /* Enable write protection again. (use the fault address as it might be an alias) */
2331 rc = PGMShwMakePageReadonly(pVCpu, pVM->csam.s.pvDirtyFaultPage[i], 0 /*fFlags*/);
2332 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
2333
2334 Log(("CSAMR3FlushDirtyPages: flush %RRv (modifypage rc=%Rrc)\n", pVM->csam.s.pvDirtyBasePage[i], rc));
2335
2336 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)GCPtr);
2337 if (pPageRec && pPageRec->page.enmTag == CSAM_TAG_REM)
2338 {
2339 uint64_t fFlags;
2340
2341 rc = PGMGstGetPage(pVCpu, GCPtr, &fFlags, NULL);
2342 AssertMsg(RT_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Rrc\n", rc));
2343 if ( rc == VINF_SUCCESS
2344 && (fFlags & X86_PTE_US))
2345 {
2346 /* We don't care about user pages. */
2347 csamRemovePageRecord(pVM, GCPtr);
2348 STAM_COUNTER_INC(&pVM->csam.s.StatNrUserPages);
2349 }
2350 }
2351 }
2352 pVM->csam.s.cDirtyPages = 0;
2353 STAM_PROFILE_STOP(&pVM->csam.s.StatFlushDirtyPages, a);
2354 return VINF_SUCCESS;
2355}
2356
2357/**
2358 * Flush potential new code pages
2359 *
2360 * @returns VBox status code.
2361 * @param pVM The VM to operate on.
2362 */
2363static int csamR3FlushCodePages(PVM pVM)
2364{
2365 Assert(pVM->cCpus == 1);
2366 PVMCPU pVCpu = VMMGetCpu0(pVM);
2367
2368 for (uint32_t i=0;i<pVM->csam.s.cPossibleCodePages;i++)
2369 {
2370 RTRCPTR GCPtr = pVM->csam.s.pvPossibleCodePage[i];
2371
2372 GCPtr = GCPtr & PAGE_BASE_GC_MASK;
2373
2374 Log(("csamR3FlushCodePages: %RRv\n", GCPtr));
2375 PGMShwMakePageNotPresent(pVCpu, GCPtr, 0 /*fFlags*/);
2376 /* Resync the page to make sure instruction fetch will fault */
2377 CSAMMarkPage(pVM, GCPtr, false);
2378 }
2379 pVM->csam.s.cPossibleCodePages = 0;
2380 return VINF_SUCCESS;
2381}
2382
2383/**
2384 * Perform any pending actions
2385 *
2386 * @returns VBox status code.
2387 * @param pVM The VM to operate on.
2388 * @param pVCpu The VMCPU to operate on.
2389 */
2390VMMR3DECL(int) CSAMR3DoPendingAction(PVM pVM, PVMCPU pVCpu)
2391{
2392 csamR3FlushDirtyPages(pVM);
2393 csamR3FlushCodePages(pVM);
2394
2395 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_CSAM_PENDING_ACTION);
2396 return VINF_SUCCESS;
2397}
2398
2399/**
2400 * Analyse interrupt and trap gates
2401 *
2402 * @returns VBox status code.
2403 * @param pVM The VM to operate on.
2404 * @param iGate Start gate
2405 * @param cGates Number of gates to check
2406 */
2407VMMR3DECL(int) CSAMR3CheckGates(PVM pVM, uint32_t iGate, uint32_t cGates)
2408{
2409 Assert(pVM->cCpus == 1);
2410 PVMCPU pVCpu = VMMGetCpu0(pVM);
2411 uint16_t cbIDT;
2412 RTRCPTR GCPtrIDT = CPUMGetGuestIDTR(pVCpu, &cbIDT);
2413 uint32_t iGateEnd;
2414 uint32_t maxGates;
2415 VBOXIDTE aIDT[256];
2416 PVBOXIDTE pGuestIdte;
2417 int rc;
2418
2419 if (EMIsRawRing0Enabled(pVM) == false)
2420 {
2421 /* Enabling interrupt gates only works when raw ring 0 is enabled. */
2422 //AssertFailed();
2423 return VINF_SUCCESS;
2424 }
2425
2426 /* We only check all gates once during a session */
2427 if ( !pVM->csam.s.fGatesChecked
2428 && cGates != 256)
2429 return VINF_SUCCESS; /* too early */
2430
2431 /* We only check all gates once during a session */
2432 if ( pVM->csam.s.fGatesChecked
2433 && cGates != 1)
2434 return VINF_SUCCESS; /* ignored */
2435
2436 Assert(cGates <= 256);
2437 if (!GCPtrIDT || cGates > 256)
2438 return VERR_INVALID_PARAMETER;
2439
2440 if (cGates != 1)
2441 {
2442 pVM->csam.s.fGatesChecked = true;
2443 for (unsigned i=0;i<RT_ELEMENTS(pVM->csam.s.pvCallInstruction);i++)
2444 {
2445 RTRCPTR pHandler = pVM->csam.s.pvCallInstruction[i];
2446
2447 if (pHandler)
2448 {
2449 PCSAMPAGE pPage = NULL;
2450 CSAMP2GLOOKUPREC cacheRec; /* Cache record for PATMGCVirtToHCVirt. */
2451 RT_ZERO(cacheRec);
2452
2453 Log(("CSAMCheckGates: checking previous call instruction %RRv\n", pHandler));
2454 STAM_PROFILE_START(&pVM->csam.s.StatTime, a);
2455 rc = csamAnalyseCodeStream(pVM, pHandler, pHandler, true, CSAMR3AnalyseCallback, pPage, &cacheRec);
2456 STAM_PROFILE_STOP(&pVM->csam.s.StatTime, a);
2457 if (rc != VINF_SUCCESS)
2458 {
2459 Log(("CSAMCheckGates: csamAnalyseCodeStream failed with %d\n", rc));
2460 continue;
2461 }
2462 }
2463 }
2464 }
2465
2466 /* Determine valid upper boundary. */
2467 maxGates = (cbIDT+1) / sizeof(VBOXIDTE);
2468 Assert(iGate < maxGates);
2469 if (iGate > maxGates)
2470 return VERR_INVALID_PARAMETER;
2471
2472 if (iGate + cGates > maxGates)
2473 cGates = maxGates - iGate;
2474
2475 GCPtrIDT = GCPtrIDT + iGate * sizeof(VBOXIDTE);
2476 iGateEnd = iGate + cGates;
2477
2478 STAM_PROFILE_START(&pVM->csam.s.StatCheckGates, a);
2479
2480 /*
2481 * Get IDT entries.
2482 */
2483 if (PAGE_ADDRESS(GCPtrIDT) == PAGE_ADDRESS(GCPtrIDT+cGates*sizeof(VBOXIDTE)))
2484 {
2485 /* Just convert the IDT address to a R3 pointer. The whole IDT fits in one page. */
2486 rc = PGMPhysGCPtr2R3Ptr(pVCpu, GCPtrIDT, (PRTR3PTR)&pGuestIdte);
2487 if (RT_FAILURE(rc))
2488 {
2489 AssertMsgRC(rc, ("Failed to read IDTE! rc=%Rrc\n", rc));
2490 STAM_PROFILE_STOP(&pVM->csam.s.StatCheckGates, a);
2491 return rc;
2492 }
2493 }
2494 else
2495 {
2496 /* Slow method when it crosses a page boundary. */
2497 rc = PGMPhysSimpleReadGCPtr(pVCpu, aIDT, GCPtrIDT, cGates*sizeof(VBOXIDTE));
2498 if (RT_FAILURE(rc))
2499 {
2500 AssertMsgRC(rc, ("Failed to read IDTE! rc=%Rrc\n", rc));
2501 STAM_PROFILE_STOP(&pVM->csam.s.StatCheckGates, a);
2502 return rc;
2503 }
2504 pGuestIdte = &aIDT[0];
2505 }
2506
2507 for (/*iGate*/; iGate<iGateEnd; iGate++, pGuestIdte++)
2508 {
2509 Assert(TRPMR3GetGuestTrapHandler(pVM, iGate) == TRPM_INVALID_HANDLER);
2510
2511 if ( pGuestIdte->Gen.u1Present
2512 && (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32 || pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_INT_32)
2513 && (pGuestIdte->Gen.u2DPL == 3 || pGuestIdte->Gen.u2DPL == 0)
2514 )
2515 {
2516 RTRCPTR pHandler;
2517 PCSAMPAGE pPage = NULL;
2518 DBGFSELINFO selInfo;
2519 CSAMP2GLOOKUPREC cacheRec; /* Cache record for PATMGCVirtToHCVirt. */
2520 RT_ZERO(cacheRec);
2521
2522 pHandler = VBOXIDTE_OFFSET(*pGuestIdte);
2523 pHandler = SELMToFlatBySel(pVM, pGuestIdte->Gen.u16SegSel, pHandler);
2524
2525 rc = SELMR3GetSelectorInfo(pVM, pVCpu, pGuestIdte->Gen.u16SegSel, &selInfo);
2526 if ( RT_FAILURE(rc)
2527 || (selInfo.fFlags & (DBGFSELINFO_FLAGS_NOT_PRESENT | DBGFSELINFO_FLAGS_INVALID))
2528 || selInfo.GCPtrBase != 0
2529 || selInfo.cbLimit != ~0U
2530 )
2531 {
2532 /* Refuse to patch a handler whose idt cs selector isn't wide open. */
2533 Log(("CSAMCheckGates: check gate %d failed due to rc %Rrc GCPtrBase=%RRv limit=%x\n", iGate, rc, selInfo.GCPtrBase, selInfo.cbLimit));
2534 continue;
2535 }
2536
2537
2538 if (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32)
2539 {
2540 Log(("CSAMCheckGates: check trap gate %d at %04X:%08X (flat %RRv)\n", iGate, pGuestIdte->Gen.u16SegSel, VBOXIDTE_OFFSET(*pGuestIdte), pHandler));
2541 }
2542 else
2543 {
2544 Log(("CSAMCheckGates: check interrupt gate %d at %04X:%08X (flat %RRv)\n", iGate, pGuestIdte->Gen.u16SegSel, VBOXIDTE_OFFSET(*pGuestIdte), pHandler));
2545 }
2546
2547 STAM_PROFILE_START(&pVM->csam.s.StatTime, b);
2548 rc = csamAnalyseCodeStream(pVM, pHandler, pHandler, true, CSAMR3AnalyseCallback, pPage, &cacheRec);
2549 STAM_PROFILE_STOP(&pVM->csam.s.StatTime, b);
2550 if (rc != VINF_SUCCESS)
2551 {
2552 Log(("CSAMCheckGates: csamAnalyseCodeStream failed with %d\n", rc));
2553 continue;
2554 }
2555 /* OpenBSD guest specific patch test. */
2556 if (iGate >= 0x20)
2557 {
2558 PCPUMCTX pCtx;
2559 DISCPUSTATE cpu;
2560 RTGCUINTPTR32 aOpenBsdPushCSOffset[3] = {0x03, /* OpenBSD 3.7 & 3.8 */
2561 0x2B, /* OpenBSD 4.0 installation ISO */
2562 0x2F}; /* OpenBSD 4.0 after install */
2563
2564 pCtx = CPUMQueryGuestCtxPtr(pVCpu);
2565
2566 for (unsigned i=0;i<RT_ELEMENTS(aOpenBsdPushCSOffset);i++)
2567 {
2568 rc = CPUMR3DisasmInstrCPU(pVM, pVCpu, pCtx, pHandler - aOpenBsdPushCSOffset[i], &cpu, NULL);
2569 if ( rc == VINF_SUCCESS
2570 && cpu.pCurInstr->opcode == OP_PUSH
2571 && cpu.pCurInstr->param1 == OP_PARM_REG_CS)
2572 {
2573 rc = PATMR3InstallPatch(pVM, pHandler - aOpenBsdPushCSOffset[i], PATMFL_CODE32 | PATMFL_GUEST_SPECIFIC);
2574 if (RT_SUCCESS(rc))
2575 Log(("Installed OpenBSD interrupt handler prefix instruction (push cs) patch\n"));
2576 }
2577 }
2578 }
2579
2580 /* Trap gates and certain interrupt gates. */
2581 uint32_t fPatchFlags = PATMFL_CODE32 | PATMFL_IDTHANDLER;
2582
2583 if (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32)
2584 fPatchFlags |= PATMFL_TRAPHANDLER;
2585 else
2586 fPatchFlags |= PATMFL_INTHANDLER;
2587
2588 switch (iGate) {
2589 case 8:
2590 case 10:
2591 case 11:
2592 case 12:
2593 case 13:
2594 case 14:
2595 case 17:
2596 fPatchFlags |= PATMFL_TRAPHANDLER_WITH_ERRORCODE;
2597 break;
2598 default:
2599 /* No error code. */
2600 break;
2601 }
2602
2603 Log(("Installing %s gate handler for 0x%X at %RRv\n", (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32) ? "trap" : "intr", iGate, pHandler));
2604
2605 rc = PATMR3InstallPatch(pVM, pHandler, fPatchFlags);
2606 if (RT_SUCCESS(rc) || rc == VERR_PATM_ALREADY_PATCHED)
2607 {
2608 Log(("Gate handler 0x%X is SAFE!\n", iGate));
2609
2610 RTRCPTR pNewHandlerGC = PATMR3QueryPatchGCPtr(pVM, pHandler);
2611 if (pNewHandlerGC)
2612 {
2613 rc = TRPMR3SetGuestTrapHandler(pVM, iGate, pNewHandlerGC);
2614 if (RT_FAILURE(rc))
2615 Log(("TRPMR3SetGuestTrapHandler %d failed with %Rrc\n", iGate, rc));
2616 }
2617 }
2618 }
2619 } /* for */
2620 STAM_PROFILE_STOP(&pVM->csam.s.StatCheckGates, a);
2621 return VINF_SUCCESS;
2622}
2623
2624/**
2625 * Record previous call instruction addresses
2626 *
2627 * @returns VBox status code.
2628 * @param pVM The VM to operate on.
2629 * @param GCPtrCall Call address
2630 */
2631VMMR3DECL(int) CSAMR3RecordCallAddress(PVM pVM, RTRCPTR GCPtrCall)
2632{
2633 for (unsigned i=0;i<RT_ELEMENTS(pVM->csam.s.pvCallInstruction);i++)
2634 {
2635 if (pVM->csam.s.pvCallInstruction[i] == GCPtrCall)
2636 return VINF_SUCCESS;
2637 }
2638
2639 Log(("CSAMR3RecordCallAddress %RRv\n", GCPtrCall));
2640
2641 pVM->csam.s.pvCallInstruction[pVM->csam.s.iCallInstruction++] = GCPtrCall;
2642 if (pVM->csam.s.iCallInstruction >= RT_ELEMENTS(pVM->csam.s.pvCallInstruction))
2643 pVM->csam.s.iCallInstruction = 0;
2644
2645 return VINF_SUCCESS;
2646}
2647
2648
2649/**
2650 * Query CSAM state (enabled/disabled)
2651 *
2652 * @returns 0 - disabled, 1 - enabled
2653 * @param pVM The VM to operate on.
2654 */
2655VMMR3DECL(int) CSAMR3IsEnabled(PVM pVM)
2656{
2657 return pVM->fCSAMEnabled;
2658}
2659
2660#ifdef VBOX_WITH_DEBUGGER
2661/**
2662 * The '.csamoff' command.
2663 *
2664 * @returns VBox status.
2665 * @param pCmd Pointer to the command descriptor (as registered).
2666 * @param pCmdHlp Pointer to command helper functions.
2667 * @param pVM Pointer to the current VM (if any).
2668 * @param paArgs Pointer to (readonly) array of arguments.
2669 * @param cArgs Number of arguments in the array.
2670 */
2671static DECLCALLBACK(int) csamr3CmdOff(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PVM pVM, PCDBGCVAR paArgs, unsigned cArgs, PDBGCVAR pResult)
2672{
2673 /*
2674 * Validate input.
2675 */
2676 if (!pVM)
2677 return pCmdHlp->pfnPrintf(pCmdHlp, NULL, "error: The command requires VM to be selected.\n");
2678
2679 CSAMDisableScanning(pVM);
2680 return pCmdHlp->pfnPrintf(pCmdHlp, NULL, "CSAM Scanning disabled\n");
2681}
2682
2683/**
2684 * The '.csamon' command.
2685 *
2686 * @returns VBox status.
2687 * @param pCmd Pointer to the command descriptor (as registered).
2688 * @param pCmdHlp Pointer to command helper functions.
2689 * @param pVM Pointer to the current VM (if any).
2690 * @param paArgs Pointer to (readonly) array of arguments.
2691 * @param cArgs Number of arguments in the array.
2692 */
2693static DECLCALLBACK(int) csamr3CmdOn(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PVM pVM, PCDBGCVAR paArgs, unsigned cArgs, PDBGCVAR pResult)
2694{
2695 /*
2696 * Validate input.
2697 */
2698 if (!pVM)
2699 return pCmdHlp->pfnPrintf(pCmdHlp, NULL, "error: The command requires VM to be selected.\n");
2700
2701 CSAMEnableScanning(pVM);
2702 return pCmdHlp->pfnPrintf(pCmdHlp, NULL, "CSAM Scanning enabled\n");
2703}
2704#endif
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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