VirtualBox

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

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

Automated rebranding to Oracle copyright/license strings via filemuncher

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

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