VirtualBox

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

Last change on this file since 56287 was 56287, checked in by vboxsync, 9 years ago

VMM: Updated (C) year.

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