VirtualBox

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

Last change on this file since 35348 was 35348, checked in by vboxsync, 14 years ago

VMM reorg: Moving PATM to where the other VMM sources are.

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

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