VirtualBox

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

Last change on this file since 4959 was 4959, checked in by vboxsync, 17 years ago

build fix.

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

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