VirtualBox

source: vbox/trunk/src/VBox/VMM/PATM/CSAM.cpp@ 30497

Last change on this file since 30497 was 30497, checked in by vboxsync, 15 years ago

Drop more PGMPhysGCPtr2R3Ptr usage

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