VirtualBox

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

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

DISInstr* -> DISInstrToStr + cbOutput argument.

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