VirtualBox

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

Last change on this file since 41791 was 41791, checked in by vboxsync, 12 years ago

DIS,CSAM: Drop pvUser2.

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