VirtualBox

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

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

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