VirtualBox

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

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

Windows build fixes.

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