VirtualBox

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

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

Make VBOX_WITH_RAW_MODE= link.

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