VirtualBox

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

Last change on this file since 62291 was 62291, checked in by vboxsync, 9 years ago

Removed empty internal/pgm.h header file. (That stuff moved into VBox/vmm/pgm.h a long time ago. Internal APIs are using VMM_INT_DECL and similar now.)

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

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