VirtualBox

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

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

VMM: Stubbed the csam, patm, rem and hm documentation @pages.

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