VirtualBox

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

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

csamR3DISInstr: forgot to update the calls to pass DisInfo.

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