VirtualBox

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

Last change on this file since 840 was 760, checked in by vboxsync, 18 years ago

Enhanced detection of changed pages.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 83.4 KB
Line 
1/* $Id: CSAM.cpp 760 2007-02-07 18:29:33Z vboxsync $ */
2/** @file
3 * CSAM - Guest OS Code Scanning and Analysis Manager
4 */
5
6/*
7 * Copyright (C) 2006 InnoTek Systemberatung 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 * If you received this file as part of a commercial VirtualBox
18 * distribution, then only the terms of your commercial VirtualBox
19 * license agreement apply instead of the previous paragraph.
20 */
21
22/*******************************************************************************
23* Header Files *
24*******************************************************************************/
25#define LOG_GROUP LOG_GROUP_CSAM
26#include <VBox/cpum.h>
27#include <VBox/stam.h>
28#include <VBox/patm.h>
29#include <VBox/csam.h>
30#include <VBox/pgm.h>
31#include <VBox/iom.h>
32#include <VBox/sup.h>
33#include <VBox/mm.h>
34#include <VBox/em.h>
35#include <VBox/rem.h>
36#include <VBox/selm.h>
37#include <VBox/trpm.h>
38#include <VBox/cfgm.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/vm.h>
45#include <VBox/dbg.h>
46#include <VBox/err.h>
47#include <VBox/ssm.h>
48#include <VBox/log.h>
49#include <iprt/assert.h>
50#include <iprt/string.h>
51#include <VBox/dis.h>
52#include <VBox/disopcode.h>
53#include <stdlib.h>
54#include <stdio.h>
55
56
57/* Enabled by default */
58#define CSAM_ENABLE
59
60/* Enable to monitor code pages for self-modifying code. */
61#define CSAM_MONITOR_CODE_PAGES
62/* Enable to monitor all scanned pages
63#define CSAM_MONITOR_CSAM_CODE_PAGES */
64
65/*******************************************************************************
66* Internal Functions *
67*******************************************************************************/
68static DECLCALLBACK(int) csamr3Save(PVM pVM, PSSMHANDLE pSSM);
69static DECLCALLBACK(int) csamr3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version);
70static DECLCALLBACK(int) CSAMCodePageWriteHandler(PVM pVM, RTGCPTR GCPtr, void *pvPtr, void *pvBuf, size_t cbBuf, PGMACCESSTYPE enmAccessType, void *pvUser);
71static DECLCALLBACK(int) CSAMCodePageInvalidate(PVM pVM, RTGCPTR GCPtr);
72
73bool csamIsCodeScanned(PVM pVM, RTGCPTR pInstr, PCSAMPAGE *pPage);
74int csamR3CheckPageRecord(PVM pVM, RTGCPTR pInstr);
75static PCSAMPAGE csamCreatePageRecord(PVM pVM, RTGCPTR GCPtr, CSAMTAG enmTag, bool fCode32, bool fMonitorInvalidation = false);
76static int csamRemovePageRecord(PVM pVM, RTGCPTR GCPtr);
77static int csamReinit(PVM pVM);
78static void csamMarkCode(PVM pVM, PCSAMPAGE pPage, RTGCPTR pInstr, uint32_t opsize, bool fScanned);
79static int csamAnalyseCodeStream(PVM pVM, GCPTRTYPE(uint8_t *) pInstrGC, GCPTRTYPE(uint8_t *) pCurInstrGC, bool fCode32,
80 PFN_CSAMR3ANALYSE pfnCSAMR3Analyse, void *pUserData, PCSAMP2GLOOKUPREC pCacheRec);
81
82/** @todo Temporary for debugging. */
83static bool fInCSAMCodePageInvalidate = false;
84
85/*******************************************************************************
86* Global Variables *
87*******************************************************************************/
88#ifdef VBOX_WITH_DEBUGGER
89static DECLCALLBACK(int) csamr3CmdOn(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PVM pVM, PCDBGCVAR paArgs, unsigned cArgs, PDBGCVAR pResult);
90static DECLCALLBACK(int) csamr3CmdOff(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PVM pVM, PCDBGCVAR paArgs, unsigned cArgs, PDBGCVAR pResult);
91
92/** Command descriptors. */
93static const DBGCCMD g_aCmds[] =
94{
95 /* pszCmd, cArgsMin, cArgsMax, paArgDesc, cArgDescs, pResultDesc, fFlags, pfnHandler pszSyntax, ....pszDescription */
96 { "csamon", 0, 0, NULL, 0, NULL, 0, csamr3CmdOn, "", "Enable CSAM code scanning." },
97 { "csamoff", 0, 0, NULL, 0, NULL, 0, csamr3CmdOff, "", "Disable CSAM code scanning." },
98};
99#endif
100
101
102/**
103 * Initializes the CSAM.
104 *
105 * @returns VBox status code.
106 * @param pVM The VM to operate on.
107 */
108CSAMR3DECL(int) CSAMR3Init(PVM pVM)
109{
110 int rc;
111
112 LogFlow(("CSAMR3Init\n"));
113
114 /* Allocate bitmap for the page directory. */
115 rc = MMR3HyperAllocOnceNoRel(pVM, CSAM_PGDIRBMP_CHUNKS*sizeof(RTHCPTR), 0, MM_TAG_CSAM, (void **)&pVM->csam.s.pPDBitmapHC);
116 AssertRCReturn(rc, rc);
117 rc = MMR3HyperAllocOnceNoRel(pVM, CSAM_PGDIRBMP_CHUNKS*sizeof(RTGCPTR), 0, MM_TAG_CSAM, (void **)&pVM->csam.s.pPDGCBitmapHC);
118 AssertRCReturn(rc, rc);
119 pVM->csam.s.pPDBitmapGC = MMHyperHC2GC(pVM, pVM->csam.s.pPDGCBitmapHC);
120 pVM->csam.s.pPDHCBitmapGC = MMHyperHC2GC(pVM, pVM->csam.s.pPDBitmapHC);
121
122 rc = csamReinit(pVM);
123 AssertRCReturn(rc, rc);
124
125 /*
126 * Register save and load state notificators.
127 */
128 rc = SSMR3RegisterInternal(pVM, "CSAM", 0, CSAM_SSM_VERSION, sizeof(pVM->csam.s) + PAGE_SIZE*16,
129 NULL, csamr3Save, NULL,
130 NULL, csamr3Load, NULL);
131 AssertRCReturn(rc, rc);
132
133 STAM_REG(pVM, &pVM->csam.s.StatNrTraps, STAMTYPE_COUNTER, "/CSAM/PageTraps", STAMUNIT_OCCURENCES, "The number of CSAM page traps.");
134 STAM_REG(pVM, &pVM->csam.s.StatDangerousWrite, STAMTYPE_COUNTER, "/CSAM/DangerousWrites", STAMUNIT_OCCURENCES, "The number of dangerous writes that cause a context switch.");
135
136 STAM_REG(pVM, &pVM->csam.s.StatNrPageNPHC, STAMTYPE_COUNTER, "/CSAM/HC/PageNotPresent", STAMUNIT_OCCURENCES, "The number of CSAM pages marked not present.");
137 STAM_REG(pVM, &pVM->csam.s.StatNrPageNPGC, STAMTYPE_COUNTER, "/CSAM/GC/PageNotPresent", STAMUNIT_OCCURENCES, "The number of CSAM pages marked not present.");
138 STAM_REG(pVM, &pVM->csam.s.StatNrPages, STAMTYPE_COUNTER, "/CSAM/PageRec/AddedRW", STAMUNIT_OCCURENCES, "The number of CSAM page records (RW monitoring).");
139 STAM_REG(pVM, &pVM->csam.s.StatNrPagesInv, STAMTYPE_COUNTER, "/CSAM/PageRec/AddedRWI", STAMUNIT_OCCURENCES, "The number of CSAM page records (RW & invalidation monitoring).");
140 STAM_REG(pVM, &pVM->csam.s.StatNrRemovedPages, STAMTYPE_COUNTER, "/CSAM/PageRec/Removed", STAMUNIT_OCCURENCES, "The number of removed CSAM page records.");
141 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.");
142
143 STAM_REG(pVM, &pVM->csam.s.StatNrPatchPages, STAMTYPE_COUNTER, "/CSAM/PageRec/Patch", STAMUNIT_OCCURENCES, "The number of CSAM patch page records.");
144 STAM_REG(pVM, &pVM->csam.s.StatNrUserPages, STAMTYPE_COUNTER, "/CSAM/PageRec/Ignore/User", STAMUNIT_OCCURENCES, "The number of CSAM user page records (ignored).");
145 STAM_REG(pVM, &pVM->csam.s.StatPagePATM, STAMTYPE_COUNTER, "/CSAM/PageRec/Type/PATM", STAMUNIT_OCCURENCES, "The number of PATM page records.");
146 STAM_REG(pVM, &pVM->csam.s.StatPageCSAM, STAMTYPE_COUNTER, "/CSAM/PageRec/Type/CSAM", STAMUNIT_OCCURENCES, "The number of CSAM page records.");
147 STAM_REG(pVM, &pVM->csam.s.StatPageREM, STAMTYPE_COUNTER, "/CSAM/PageRec/Type/REM", STAMUNIT_OCCURENCES, "The number of REM page records.");
148 STAM_REG(pVM, &pVM->csam.s.StatPageMonitor, STAMTYPE_COUNTER, "/CSAM/PageRec/Monitored", STAMUNIT_OCCURENCES, "The number of monitored pages.");
149
150 STAM_REG(pVM, &pVM->csam.s.StatCodePageModified, STAMTYPE_COUNTER, "/CSAM/Monitor/DirtyPage", STAMUNIT_OCCURENCES, "The number of code page modifications.");
151
152 STAM_REG(pVM, &pVM->csam.s.StatNrFlushes, STAMTYPE_COUNTER, "/CSAM/PageFlushes", STAMUNIT_OCCURENCES, "The number of CSAM page flushes.");
153 STAM_REG(pVM, &pVM->csam.s.StatNrFlushesSkipped, STAMTYPE_COUNTER, "/CSAM/PageFlushesSkipped", STAMUNIT_OCCURENCES, "The number of CSAM page flushes that were skipped.");
154 STAM_REG(pVM, &pVM->csam.s.StatNrKnownPagesHC, STAMTYPE_COUNTER, "/CSAM/HC/KnownPageRecords", STAMUNIT_OCCURENCES, "The number of known CSAM page records.");
155 STAM_REG(pVM, &pVM->csam.s.StatNrKnownPagesGC, STAMTYPE_COUNTER, "/CSAM/GC/KnownPageRecords", STAMUNIT_OCCURENCES, "The number of known CSAM page records.");
156 STAM_REG(pVM, &pVM->csam.s.StatNrInstr, STAMTYPE_COUNTER, "/CSAM/ScannedInstr", STAMUNIT_OCCURENCES, "The number of scanned instructions.");
157 STAM_REG(pVM, &pVM->csam.s.StatNrBytesRead, STAMTYPE_COUNTER, "/CSAM/BytesRead", STAMUNIT_OCCURENCES, "The number of bytes read for scanning.");
158 STAM_REG(pVM, &pVM->csam.s.StatNrOpcodeRead, STAMTYPE_COUNTER, "/CSAM/OpcodeBytesRead", STAMUNIT_OCCURENCES, "The number of opcode bytes read by the recompiler.");
159
160 STAM_REG(pVM, &pVM->csam.s.StatBitmapAlloc, STAMTYPE_COUNTER, "/CSAM/Alloc/PageBitmap", STAMUNIT_OCCURENCES, "The number of page bitmap allocations.");
161
162 STAM_REG(pVM, &pVM->csam.s.StatInstrCacheHit, STAMTYPE_COUNTER, "/CSAM/Cache/Hit", STAMUNIT_OCCURENCES, "The number of dangerous instruction cache hits.");
163 STAM_REG(pVM, &pVM->csam.s.StatInstrCacheMiss, STAMTYPE_COUNTER, "/CSAM/Cache/Miss", STAMUNIT_OCCURENCES, "The number of dangerous instruction cache misses.");
164
165 STAM_REG(pVM, &pVM->csam.s.StatScanNextFunction, STAMTYPE_COUNTER, "/CSAM/Function/Scan/Success", STAMUNIT_OCCURENCES, "The number of found functions beyond the ret border.");
166 STAM_REG(pVM, &pVM->csam.s.StatScanNextFunctionFailed, STAMTYPE_COUNTER, "/CSAM/Function/Scan/Failed", STAMUNIT_OCCURENCES, "The number of refused functions beyond the ret border.");
167
168 STAM_REG(pVM, &pVM->csam.s.StatTime, STAMTYPE_PROFILE, "/PROF/CSAM/Scan", STAMUNIT_TICKS_PER_CALL, "Scanning overhead.");
169 STAM_REG(pVM, &pVM->csam.s.StatTimeCheckAddr, STAMTYPE_PROFILE, "/PROF/CSAM/CheckAddr", STAMUNIT_TICKS_PER_CALL, "Address check overhead.");
170 STAM_REG(pVM, &pVM->csam.s.StatTimeAddrConv, STAMTYPE_PROFILE, "/PROF/CSAM/AddrConv", STAMUNIT_TICKS_PER_CALL, "Address conversion overhead.");
171 STAM_REG(pVM, &pVM->csam.s.StatTimeFlushPage, STAMTYPE_PROFILE, "/PROF/CSAM/FlushPage", STAMUNIT_TICKS_PER_CALL, "Page flushing overhead.");
172 STAM_REG(pVM, &pVM->csam.s.StatTimeDisasm, STAMTYPE_PROFILE, "/PROF/CSAM/Disasm", STAMUNIT_TICKS_PER_CALL, "Disassembly overhead.");
173 STAM_REG(pVM, &pVM->csam.s.StatFlushDirtyPages, STAMTYPE_PROFILE, "/PROF/CSAM/FlushDirtyPage", STAMUNIT_TICKS_PER_CALL, "Dirty page flushing overhead.");
174 STAM_REG(pVM, &pVM->csam.s.StatCheckGates, STAMTYPE_PROFILE, "/PROF/CSAM/CheckGates", STAMUNIT_TICKS_PER_CALL, "CSAMR3CheckGates overhead.");
175
176 /*
177 * Check CFGM option and enable/disable CSAM.
178 */
179 bool fEnabled;
180 rc = CFGMR3QueryBool(CFGMR3GetRoot(pVM), "CSAMEnabled", &fEnabled);
181 if (VBOX_FAILURE(rc))
182#ifdef CSAM_ENABLE
183 fEnabled = true;
184#else
185 fEnabled = false;
186#endif
187 if (fEnabled)
188 CSAMEnableScanning(pVM);
189
190#ifdef VBOX_WITH_DEBUGGER
191 /*
192 * Debugger commands.
193 */
194 static bool fRegisteredCmds = false;
195 if (!fRegisteredCmds)
196 {
197 int rc = DBGCRegisterCommands(&g_aCmds[0], ELEMENTS(g_aCmds));
198 if (VBOX_SUCCESS(rc))
199 fRegisteredCmds = true;
200 }
201#endif
202
203 return VINF_SUCCESS;
204}
205
206/**
207 * (Re)initializes CSAM
208 *
209 * @param pVM The VM.
210 */
211static int csamReinit(PVM pVM)
212{
213 /*
214 * Assert alignment and sizes.
215 */
216 AssertRelease(!(RT_OFFSETOF(VM, csam.s) & 31));
217 AssertRelease(sizeof(pVM->csam.s) <= sizeof(pVM->csam.padding));
218
219 /*
220 * Setup any fixed pointers and offsets.
221 */
222 pVM->csam.s.offVM = RT_OFFSETOF(VM, patm);
223
224 pVM->csam.s.fGatesChecked = false;
225 pVM->csam.s.fScanningStarted = false;
226
227 VM_FF_CLEAR(pVM, VM_FF_CSAM_FLUSH_DIRTY_PAGE);
228 pVM->csam.s.cDirtyPages = 0;
229 /* not necessary */
230 memset(pVM->csam.s.pvDirtyBasePage, 0, sizeof(pVM->csam.s.pvDirtyBasePage));
231 memset(pVM->csam.s.pvDirtyFaultPage, 0, sizeof(pVM->csam.s.pvDirtyFaultPage));
232
233 memset(&pVM->csam.s.aDangerousInstr, 0, sizeof(pVM->csam.s.aDangerousInstr));
234 pVM->csam.s.cDangerousInstr = 0;
235 pVM->csam.s.iDangerousInstr = 0;
236
237 /** @note never mess with the pgdir bitmap here! */
238 return VINF_SUCCESS;
239}
240
241/**
242 * Applies relocations to data and code managed by this
243 * component. This function will be called at init and
244 * whenever the VMM need to relocate itself inside the GC.
245 *
246 * The csam will update the addresses used by the switcher.
247 *
248 * @param pVM The VM.
249 * @param offDelta Relocation delta.
250 */
251CSAMR3DECL(void) CSAMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
252{
253 if (offDelta)
254 {
255 /* Adjust pgdir and page bitmap pointers. */
256 pVM->csam.s.pPDBitmapGC = MMHyperHC2GC(pVM, pVM->csam.s.pPDGCBitmapHC);
257 pVM->csam.s.pPDHCBitmapGC = MMHyperHC2GC(pVM, pVM->csam.s.pPDBitmapHC);
258
259 for(int i=0;i<CSAM_PGDIRBMP_CHUNKS;i++)
260 {
261 if (pVM->csam.s.pPDGCBitmapHC[i])
262 {
263 pVM->csam.s.pPDGCBitmapHC[i] += offDelta;
264 }
265 }
266 }
267 return;
268}
269
270/**
271 * Terminates the csam.
272 *
273 * Termination means cleaning up and freeing all resources,
274 * the VM it self is at this point powered off or suspended.
275 *
276 * @returns VBox status code.
277 * @param pVM The VM to operate on.
278 */
279CSAMR3DECL(int) CSAMR3Term(PVM pVM)
280{
281 int rc;
282
283 rc = CSAMR3Reset(pVM);
284 AssertRC(rc);
285
286 /* @todo triggers assertion in MMHyperFree */
287#if 0
288 for(int i=0;i<CSAM_PAGEBMP_CHUNKS;i++)
289 {
290 if (pVM->csam.s.pPDBitmapHC[i])
291 MMHyperFree(pVM, pVM->csam.s.pPDBitmapHC[i]);
292 }
293#endif
294
295 return VINF_SUCCESS;
296}
297
298/**
299 * CSAM reset callback.
300 *
301 * @returns VBox status code.
302 * @param pVM The VM which is reset.
303 */
304CSAMR3DECL(int) CSAMR3Reset(PVM pVM)
305{
306 /* Clear page bitmaps. */
307 for(int i=0;i<CSAM_PGDIRBMP_CHUNKS;i++)
308 {
309 if (pVM->csam.s.pPDBitmapHC[i])
310 {
311 Assert((CSAM_PAGE_BITMAP_SIZE& 3) == 0);
312 ASMMemZero32(pVM->csam.s.pPDBitmapHC[i], CSAM_PAGE_BITMAP_SIZE);
313 }
314 }
315
316 /* Remove all CSAM page records. */
317 while(true)
318 {
319 PCSAMPAGEREC pPageRec = (PCSAMPAGEREC)RTAvlPVGetBestFit(&pVM->csam.s.pPageTree, 0, true);
320 if (pPageRec)
321 {
322 csamRemovePageRecord(pVM, pPageRec->page.pPageGC);
323 }
324 else
325 break;
326 }
327 Assert(!pVM->csam.s.pPageTree);
328
329 csamReinit(pVM);
330
331 return VINF_SUCCESS;
332}
333
334#define CSAM_SUBTRACT_PTR(a, b) *(uintptr_t *)&(a) = (uintptr_t)(a) - (uintptr_t)(b)
335#define CSAM_ADD_PTR(a, b) *(uintptr_t *)&(a) = (uintptr_t)(a) + (uintptr_t)(b)
336
337
338/**
339 * Callback function for RTAvlPVDoWithAll
340 *
341 * Counts the number of records in the tree
342 *
343 * @returns VBox status code.
344 * @param pNode Current node
345 * @param pcPatches Pointer to patch counter
346 */
347static DECLCALLBACK(int) CountRecord(PAVLPVNODECORE pNode, void *pcPatches)
348{
349 *(uint32_t *)pcPatches = *(uint32_t *)pcPatches + 1;
350 return VINF_SUCCESS;
351}
352
353/**
354 * Callback function for RTAvlPVDoWithAll
355 *
356 * Saves the state of the page record
357 *
358 * @returns VBox status code.
359 * @param pNode Current node
360 * @param pVM1 VM Handle
361 */
362static DECLCALLBACK(int) SavePageState(PAVLPVNODECORE pNode, void *pVM1)
363{
364 PVM pVM = (PVM)pVM1;
365 PCSAMPAGEREC pPage = (PCSAMPAGEREC)pNode;
366 CSAMPAGEREC page = *pPage;
367 PSSMHANDLE pSSM = pVM->csam.s.savedstate.pSSM;
368 int rc;
369
370 /* Save the page record itself */
371 rc = SSMR3PutMem(pSSM, &page, sizeof(page));
372 AssertRCReturn(rc, rc);
373
374 if (page.page.pBitmap)
375 {
376 rc = SSMR3PutMem(pSSM, page.page.pBitmap, CSAM_PAGE_BITMAP_SIZE);
377 AssertRCReturn(rc, rc);
378 }
379
380 return VINF_SUCCESS;
381}
382
383/**
384 * Execute state save operation.
385 *
386 * @returns VBox status code.
387 * @param pVM VM Handle.
388 * @param pSSM SSM operation handle.
389 */
390static DECLCALLBACK(int) csamr3Save(PVM pVM, PSSMHANDLE pSSM)
391{
392 CSAM csamInfo = pVM->csam.s;
393 int rc;
394
395 /*
396 * Count the number of page records in the tree (feeling lazy)
397 */
398 csamInfo.savedstate.cPageRecords = 0;
399 RTAvlPVDoWithAll(&pVM->csam.s.pPageTree, true, CountRecord, &csamInfo.savedstate.cPageRecords);
400
401 /*
402 * Save CSAM structure
403 */
404 pVM->csam.s.savedstate.pSSM = pSSM;
405 rc = SSMR3PutMem(pSSM, &csamInfo, sizeof(csamInfo));
406 AssertRCReturn(rc, rc);
407
408 /* Save pgdir bitmap */
409 rc = SSMR3PutMem(pSSM, csamInfo.pPDBitmapHC, CSAM_PGDIRBMP_CHUNKS*sizeof(RTHCPTR));
410 AssertRCReturn(rc, rc);
411
412 for (unsigned i=0;i<CSAM_PGDIRBMP_CHUNKS;i++)
413 {
414 if(csamInfo.pPDBitmapHC[i])
415 {
416 /* Save the page bitmap. */
417 rc = SSMR3PutMem(pSSM, csamInfo.pPDBitmapHC[i], CSAM_PAGE_BITMAP_SIZE);
418 AssertRCReturn(rc, rc);
419 }
420 }
421
422 /*
423 * Save page records
424 */
425 rc = RTAvlPVDoWithAll(&pVM->csam.s.pPageTree, true, SavePageState, pVM);
426 AssertRCReturn(rc, rc);
427
428 /** @note we don't restore aDangerousInstr; it will be recreated automatically. */
429 return VINF_SUCCESS;
430}
431
432/**
433 * Execute state load operation.
434 *
435 * @returns VBox status code.
436 * @param pVM VM Handle.
437 * @param pSSM SSM operation handle.
438 * @param u32Version Data layout version.
439 */
440static DECLCALLBACK(int) csamr3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version)
441{
442 int rc;
443 CSAM csamInfo;
444
445 if (u32Version != CSAM_SSM_VERSION)
446 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
447
448 pVM->csam.s.savedstate.pSSM = pSSM;
449
450 /*
451 * Restore CSAM structure
452 */
453 rc = SSMR3GetMem(pSSM, &csamInfo, sizeof(csamInfo));
454 AssertRCReturn(rc, rc);
455
456 pVM->csam.s.fGatesChecked = csamInfo.fGatesChecked;
457 pVM->csam.s.fScanningStarted = csamInfo.fScanningStarted;
458
459 /* Restore dirty code page info. */
460 pVM->csam.s.cDirtyPages = csamInfo.cDirtyPages;
461 memcpy(pVM->csam.s.pvDirtyBasePage, csamInfo.pvDirtyBasePage, sizeof(pVM->csam.s.pvDirtyBasePage));
462 memcpy(pVM->csam.s.pvDirtyFaultPage, csamInfo.pvDirtyFaultPage, sizeof(pVM->csam.s.pvDirtyFaultPage));
463
464 /* Restore pgdir bitmap (we'll change the pointers next). */
465 rc = SSMR3GetMem(pSSM, pVM->csam.s.pPDBitmapHC, CSAM_PGDIRBMP_CHUNKS*sizeof(RTHCPTR));
466 AssertRCReturn(rc, rc);
467
468 /*
469 * Restore page bitmaps
470 */
471 for (unsigned i=0;i<CSAM_PGDIRBMP_CHUNKS;i++)
472 {
473 if(pVM->csam.s.pPDBitmapHC[i])
474 {
475 rc = MMHyperAlloc(pVM, CSAM_PAGE_BITMAP_SIZE, 0, MM_TAG_CSAM, (void **)&pVM->csam.s.pPDBitmapHC[i]);
476 if (VBOX_FAILURE(rc))
477 {
478 Log(("MMR3HyperAlloc failed with %d\n", rc));
479 return rc;
480 }
481 /* Convert to GC pointer. */
482 pVM->csam.s.pPDGCBitmapHC[i] = MMHyperHC2GC(pVM, pVM->csam.s.pPDBitmapHC[i]);
483 Assert(pVM->csam.s.pPDGCBitmapHC[i]);
484
485 /* Restore the bitmap. */
486 rc = SSMR3GetMem(pSSM, pVM->csam.s.pPDBitmapHC[i], CSAM_PAGE_BITMAP_SIZE);
487 AssertRCReturn(rc, rc);
488 }
489 else
490 {
491 Assert(!pVM->csam.s.pPDGCBitmapHC[i]);
492 pVM->csam.s.pPDGCBitmapHC[i] = 0;
493 }
494 }
495
496 /*
497 * Restore page records
498 */
499 for (uint32_t i=0;i<csamInfo.savedstate.cPageRecords + csamInfo.savedstate.cPatchPageRecords;i++)
500 {
501 CSAMPAGEREC page;
502 PCSAMPAGE pPage;
503
504 rc = SSMR3GetMem(pSSM, &page, sizeof(page));
505 AssertRCReturn(rc, rc);
506
507 /*
508 * Recreate the page record
509 */
510 pPage = csamCreatePageRecord(pVM, page.page.pPageGC, page.page.enmTag, page.page.fCode32, page.page.fMonitorInvalidation);
511 AssertReturn(pPage, VERR_NO_MEMORY);
512
513 pPage->GCPhys = page.page.GCPhys;
514 pPage->fFlags = page.page.fFlags;
515 pPage->u64Hash = page.page.u64Hash;
516
517 if (page.page.pBitmap)
518 {
519 rc = SSMR3GetMem(pSSM, pPage->pBitmap, CSAM_PAGE_BITMAP_SIZE);
520 AssertRCReturn(rc, rc);
521 }
522 else
523 {
524 MMR3HeapFree(pPage->pBitmap);
525 pPage->pBitmap = 0;
526 }
527 }
528
529 /** @note we don't restore aDangerousInstr; it will be recreated automatically. */
530 memset(&pVM->csam.s.aDangerousInstr, 0, sizeof(pVM->csam.s.aDangerousInstr));
531 pVM->csam.s.cDangerousInstr = 0;
532 pVM->csam.s.iDangerousInstr = 0;
533 return VINF_SUCCESS;
534}
535
536/**
537 * Convert guest context address to host context pointer
538 *
539 * @returns VBox status code.
540 * @param pVM The VM to operate on.
541 * @param pCacheRec Address conversion cache record
542 * @param pGCPtr Guest context pointer
543 *
544 * @returns Host context pointer or NULL in case of an error
545 *
546 */
547static HCPTRTYPE(void *) CSAMGCVirtToHCVirt(PVM pVM, PCSAMP2GLOOKUPREC pCacheRec, GCPTRTYPE(uint8_t *)pGCPtr)
548{
549 int rc;
550 HCPTRTYPE(void *)pHCPtr;
551
552 STAM_PROFILE_START(&pVM->csam.s.StatTimeAddrConv, a);
553
554 pHCPtr = PATMR3GCPtrToHCPtr(pVM, pGCPtr);
555 if (pHCPtr) return pHCPtr;
556
557 if (pCacheRec->pPageLocStartHC)
558 {
559 uint32_t offset = pGCPtr & PAGE_OFFSET_MASK;
560 if (pCacheRec->pGuestLoc == (pGCPtr & PAGE_BASE_GC_MASK))
561 {
562 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeAddrConv, a);
563 return pCacheRec->pPageLocStartHC + offset;
564 }
565 }
566
567 rc = PGMPhysGCPtr2HCPtr(pVM, pGCPtr, &pHCPtr);
568 if (rc != VINF_SUCCESS)
569 {
570//// AssertMsgRC(rc, ("MMR3PhysGCVirt2HCVirtEx failed for %VGv\n", pGCPtr));
571 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeAddrConv, a);
572 return NULL;
573 }
574////invalid? Assert(sizeof(HCPTRTYPE(uint8_t*)) == sizeof(uint32_t));
575
576 pCacheRec->pPageLocStartHC = (HCPTRTYPE(uint8_t*))((RTHCUINTPTR)pHCPtr & PAGE_BASE_HC_MASK);
577 pCacheRec->pGuestLoc = pGCPtr & PAGE_BASE_GC_MASK;
578 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeAddrConv, a);
579 return pHCPtr;
580}
581
582/**
583 * Read callback for disassembly function; supports reading bytes that cross a page boundary
584 *
585 * @returns VBox status code.
586 * @param pSrc GC source pointer
587 * @param pDest HC destination pointer
588 * @param size Number of bytes to read
589 * @param dwUserdata Callback specific user data (pCpu)
590 *
591 */
592int32_t CSAMR3ReadBytes(RTHCUINTPTR pSrc, uint8_t *pDest, uint32_t size, RTHCUINTPTR dwUserdata)
593{
594 DISCPUSTATE *pCpu = (DISCPUSTATE *)dwUserdata;
595 PVM pVM = (PVM)pCpu->dwUserData[0];
596 RTHCUINTPTR pInstrHC = pCpu->dwUserData[1];
597 RTGCUINTPTR pInstrGC = pCpu->dwUserData[2];
598 int orgsize = size;
599
600 Assert(sizeof(RTHCUINTPTR) <= sizeof(pCpu->dwUserData[0]));
601 Assert(sizeof(RTGCUINTPTR) <= sizeof(pCpu->dwUserData[0]));
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 bool CSAMR3DISInstr(PVM pVM, DISCPUSTATE *pCpu, RTGCPTR InstrGC, uint8_t *InstrHC, uint32_t *pOpsize, char *pszOutput)
638{
639 (pCpu)->pfnReadBytes = CSAMR3ReadBytes;
640 (pCpu)->dwUserData[0] = (RTHCUINTPTR)pVM;
641 (pCpu)->dwUserData[1] = (RTHCUINTPTR)InstrHC;
642 (pCpu)->dwUserData[2] = (RTHCUINTPTR)InstrGC;
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 bool disret;
718
719 if (cbInstr + opsize >= SIZEOF_NEARJUMP32)
720 break;
721
722 if (csamIsCodeScanned(pVM, pCurInstrGC + opsize, &pPage) == true)
723 {
724 /* We've scanned the next instruction(s) already. This means we've followed a branch that ended up there before -> dangerous!! */
725 PATMR3DetectConflict(pVM, pCurInstrGC, pCurInstrGC + opsize);
726 break;
727 }
728 pCurInstrGC += opsize;
729 cbInstr += opsize;
730
731 pCurInstrHC = (uint8_t *)CSAMGCVirtToHCVirt(pVM, pCacheRec, pCurInstrGC);
732 if (pCurInstrHC == NULL)
733 {
734 Log(("CSAMGCVirtToHCVirt failed for %VGv\n", pCurInstrGC));
735 break;
736 }
737 Assert(VALID_PTR(pCurInstrHC));
738
739 cpu.mode = (pPage->fCode32) ? CPUMODE_32BIT : CPUMODE_16BIT;
740 disret = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, NULL);
741 Assert(disret == true);
742 if (disret == false)
743 break;
744 }
745 break;
746 }
747
748 case OP_PUSH:
749 if (pCpu->pCurInstr->param1 != OP_PARM_REG_CS)
750 break;
751
752 /* no break */
753 case OP_STR:
754 case OP_LSL:
755 case OP_LAR:
756 case OP_SGDT:
757 case OP_SLDT:
758 case OP_SIDT:
759 case OP_SMSW:
760 case OP_VERW:
761 case OP_VERR:
762 case OP_CPUID:
763 case OP_IRET:
764#ifdef DEBUG
765 switch(pCpu->pCurInstr->opcode)
766 {
767 case OP_STR:
768 Log(("Privileged instruction at %VGv: str!!\n", pCurInstrGC));
769 break;
770 case OP_LSL:
771 Log(("Privileged instruction at %VGv: lsl!!\n", pCurInstrGC));
772 break;
773 case OP_LAR:
774 Log(("Privileged instruction at %VGv: lar!!\n", pCurInstrGC));
775 break;
776 case OP_SGDT:
777 Log(("Privileged instruction at %VGv: sgdt!!\n", pCurInstrGC));
778 break;
779 case OP_SLDT:
780 Log(("Privileged instruction at %VGv: sldt!!\n", pCurInstrGC));
781 break;
782 case OP_SIDT:
783 Log(("Privileged instruction at %VGv: sidt!!\n", pCurInstrGC));
784 break;
785 case OP_SMSW:
786 Log(("Privileged instruction at %VGv: smsw!!\n", pCurInstrGC));
787 break;
788 case OP_VERW:
789 Log(("Privileged instruction at %VGv: verw!!\n", pCurInstrGC));
790 break;
791 case OP_VERR:
792 Log(("Privileged instruction at %VGv: verr!!\n", pCurInstrGC));
793 break;
794 case OP_CPUID:
795 Log(("Privileged instruction at %VGv: cpuid!!\n", pCurInstrGC));
796 break;
797 case OP_PUSH:
798 Log(("Privileged instruction at %VGv: push cs!!\n", pCurInstrGC));
799 break;
800 case OP_IRET:
801 Log(("Privileged instruction at %VGv: iret!!\n", pCurInstrGC));
802 break;
803 }
804#endif
805
806 if (PATMR3HasBeenPatched(pVM, pCurInstrGC) == false)
807 {
808 rc = PATMR3InstallPatch(pVM, pCurInstrGC, (pPage->fCode32) ? PATMFL_CODE32 : 0);
809 if (VBOX_FAILURE(rc))
810 {
811 Log(("PATMR3InstallPatch failed with %d\n", rc));
812 return VWRN_CONTINUE_ANALYSIS;
813 }
814 }
815 if (pCpu->pCurInstr->opcode == OP_IRET)
816 return VINF_SUCCESS; /* Look no further in this branch. */
817
818 return VWRN_CONTINUE_ANALYSIS;
819
820 case OP_JMP:
821 case OP_CALL:
822 {
823 // return or jump/call through a jump table
824 if (OP_PARM_VTYPE(pCpu->pCurInstr->param1) != OP_PARM_J)
825 {
826#ifdef DEBUG
827 switch(pCpu->pCurInstr->opcode)
828 {
829 case OP_JMP:
830 Log(("Control Flow instruction at %VGv: jmp!!\n", pCurInstrGC));
831 break;
832 case OP_CALL:
833 Log(("Control Flow instruction at %VGv: call!!\n", pCurInstrGC));
834 break;
835 }
836#endif
837 return VWRN_CONTINUE_ANALYSIS;
838 }
839 return VWRN_CONTINUE_ANALYSIS;
840 }
841
842 }
843
844 return VWRN_CONTINUE_ANALYSIS;
845}
846
847#ifdef CSAM_ANALYSE_BEYOND_RET
848/**
849 * Wrapper for csamAnalyseCodeStream for call instructions.
850 *
851 * @returns VBox status code.
852 * @param pVM The VM to operate on.
853 * @param pInstrGC Guest context pointer to privileged instruction
854 * @param pCurInstrGC Guest context pointer to the current instruction
855 * @param fCode32 16 or 32 bits code
856 * @param pfnCSAMR3Analyse Callback for testing the disassembled instruction
857 * @param pUserData User pointer (callback specific)
858 *
859 */
860static int csamAnalyseCallCodeStream(PVM pVM, GCPTRTYPE(uint8_t *) pInstrGC, GCPTRTYPE(uint8_t *) pCurInstrGC, bool fCode32,
861 PFN_CSAMR3ANALYSE pfnCSAMR3Analyse, void *pUserData, PCSAMP2GLOOKUPREC pCacheRec)
862{
863 int rc;
864 CSAMCALLEXITREC CallExitRec;
865 PCSAMCALLEXITREC pOldCallRec;
866 PCSAMPAGE pPage = 0;
867 uint32_t i;
868
869 CallExitRec.cInstrAfterRet = 0;
870
871 pOldCallRec = pCacheRec->pCallExitRec;
872 pCacheRec->pCallExitRec = &CallExitRec;
873
874 rc = csamAnalyseCodeStream(pVM, pInstrGC, pCurInstrGC, fCode32, pfnCSAMR3Analyse, pUserData, pCacheRec);
875
876 for (i=0;i<CallExitRec.cInstrAfterRet;i++)
877 {
878 PCSAMPAGE pPage = 0;
879
880 pCurInstrGC = CallExitRec.pInstrAfterRetGC[i];
881
882 /* Check if we've previously encountered the instruction after the ret. */
883 if (csamIsCodeScanned(pVM, pCurInstrGC, &pPage) == false)
884 {
885 DISCPUSTATE cpu;
886 uint32_t opsize;
887 uint8_t *pCurInstrHC = 0;
888 bool disret;
889#ifdef DEBUG
890 char szOutput[256];
891#endif
892 if (pPage == NULL)
893 {
894 /* New address; let's take a look at it. */
895 pPage = csamCreatePageRecord(pVM, pCurInstrGC, CSAM_TAG_CSAM, fCode32);
896 if (pPage == NULL)
897 {
898 rc = VERR_NO_MEMORY;
899 goto done;
900 }
901 }
902
903 /**
904 * Some generic requirements for recognizing an adjacent function:
905 * - alignment fillers that consist of:
906 * - nop
907 * - lea genregX, [genregX (+ 0)]
908 * - push ebp after the filler (can extend this later); aligned at at least a 4 byte boundary
909 */
910 for (int j=0;j<16;j++)
911 {
912 pCurInstrHC = (uint8_t *)CSAMGCVirtToHCVirt(pVM, pCacheRec, pCurInstrGC);
913 if (pCurInstrHC == NULL)
914 {
915 Log(("CSAMGCVirtToHCVirt failed for %VGv\n", pCurInstrGC));
916 goto done;
917 }
918 Assert(VALID_PTR(pCurInstrHC));
919
920 cpu.mode = (fCode32) ? CPUMODE_32BIT : CPUMODE_16BIT;
921 STAM_PROFILE_START(&pVM->csam.s.StatTimeDisasm, a);
922#ifdef DEBUG
923 disret = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, szOutput);
924 if (disret == true) Log(("CSAM Call Analysis: %s", szOutput));
925#else
926 disret = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, NULL);
927#endif
928 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeDisasm, a);
929 if (disret == false)
930 {
931 Log(("Disassembly failed at %VGv (probably page not present) -> return to caller\n", pCurInstrGC));
932 goto done;
933 }
934
935 STAM_COUNTER_ADD(&pVM->csam.s.StatNrBytesRead, opsize);
936
937 GCPTRTYPE(uint8_t *) addr = 0;
938 PCSAMPAGE pJmpPage = NULL;
939
940 if (PAGE_ADDRESS(pCurInstrGC) != PAGE_ADDRESS(pCurInstrGC + opsize - 1))
941 {
942 if (!PGMGstIsPagePresent(pVM, pCurInstrGC + opsize - 1))
943 {
944 /// @todo fault in the page
945 Log(("Page for current instruction %VGv is not present!!\n", pCurInstrGC));
946 goto done;
947 }
948 //all is fine, let's continue
949 csamR3CheckPageRecord(pVM, pCurInstrGC + opsize - 1);
950 }
951
952 switch (cpu.pCurInstr->opcode)
953 {
954 case OP_NOP:
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 HCPTRTYPE(uint8_t *)pCurInstrHC = 0;
1071 bool disret;
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 disret = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, szOutput);
1133 if (disret == true) Log(("CSAM Analysis: %s", szOutput));
1134#else
1135 disret = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, NULL);
1136#endif
1137 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeDisasm, a);
1138 if (disret == false)
1139 {
1140 Log(("Disassembly failed at %VGv (probably page not present) -> return to caller\n", pCurInstrGC));
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 * Check a page record in case a page has been changed
1510 *
1511 * @returns VBox status code. (trap handled or not)
1512 * @param pVM The VM to operate on.
1513 * @param pInstrGC GC instruction pointer
1514 */
1515int csamR3CheckPageRecord(PVM pVM, RTGCPTR pInstrGC)
1516{
1517 PCSAMPAGEREC pPageRec;
1518 uint64_t u64hash;
1519
1520 pInstrGC = pInstrGC & PAGE_BASE_GC_MASK;
1521
1522 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)pInstrGC);
1523 if (pPageRec)
1524 {
1525 u64hash = csamR3CalcPageHash(pVM, pInstrGC);
1526 if (u64hash != pPageRec->page.u64Hash)
1527 csamFlushPage(pVM, pInstrGC, false /* don't remove page record */);
1528 }
1529 else
1530 return VWRN_CSAM_PAGE_NOT_FOUND;
1531
1532 return VINF_SUCCESS;
1533}
1534
1535/**
1536 * Returns monitor description based on CSAM tag
1537 *
1538 * @return description string
1539 * @param enmTag Owner tag
1540 */
1541const char *csamGetMonitorDescription(CSAMTAG enmTag)
1542{
1543 if (enmTag == CSAM_TAG_PATM)
1544 return "CSAM-PATM self-modifying code monitor handler";
1545 else
1546 if (enmTag == CSAM_TAG_REM)
1547 return "CSAM-REM self-modifying code monitor handler";
1548 Assert(enmTag == CSAM_TAG_CSAM);
1549 return "CSAM self-modifying code monitor handler";
1550}
1551
1552/**
1553 * Adds page record to our lookup tree
1554 *
1555 * @returns CSAMPAGE ptr or NULL if failure
1556 * @param pVM The VM to operate on.
1557 * @param GCPtr Page address
1558 * @param enmTag Owner tag
1559 * @param fCode32 16 or 32 bits code
1560 * @param fMonitorInvalidation Monitor page invalidation flag
1561 */
1562static PCSAMPAGE csamCreatePageRecord(PVM pVM, RTGCPTR GCPtr, CSAMTAG enmTag, bool fCode32, bool fMonitorInvalidation)
1563{
1564 PCSAMPAGEREC pPage;
1565 int rc;
1566 bool ret;
1567
1568 Log(("New page record for %VGv\n", GCPtr & PAGE_BASE_GC_MASK));
1569
1570 pPage = (PCSAMPAGEREC)MMR3HeapAllocZ(pVM, MM_TAG_CSAM_PATCH, sizeof(CSAMPAGEREC));
1571 if (pPage == NULL)
1572 {
1573 AssertMsgFailed(("csamCreatePageRecord: Out of memory!!!!\n"));
1574 return NULL;
1575 }
1576 /* Round down to page boundary. */
1577 GCPtr = (GCPtr & PAGE_BASE_GC_MASK);
1578 pPage->Core.Key = (AVLPVKEY)GCPtr;
1579 pPage->page.pPageGC = GCPtr;
1580 pPage->page.fCode32 = fCode32;
1581 pPage->page.fMonitorInvalidation = fMonitorInvalidation;
1582 pPage->page.enmTag = enmTag;
1583 pPage->page.fMonitorActive = false;
1584 pPage->page.pBitmap = (uint8_t *)MMR3HeapAllocZ(pVM, MM_TAG_CSAM_PATCH, PAGE_SIZE/sizeof(uint8_t));
1585 rc = PGMGstGetPage(pVM, GCPtr, &pPage->page.fFlags, &pPage->page.GCPhys);
1586 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Vrc\n", rc));
1587
1588 pPage->page.u64Hash = csamR3CalcPageHash(pVM, GCPtr);
1589 ret = RTAvlPVInsert(&pVM->csam.s.pPageTree, &pPage->Core);
1590 Assert(ret);
1591
1592#ifdef CSAM_MONITOR_CODE_PAGES
1593 AssertRelease(!fInCSAMCodePageInvalidate);
1594
1595 switch (enmTag)
1596 {
1597 case CSAM_TAG_PATM:
1598 case CSAM_TAG_REM:
1599#ifdef CSAM_MONITOR_CSAM_CODE_PAGES
1600 case CSAM_TAG_CSAM:
1601#endif
1602 {
1603 int rc = PGMR3HandlerVirtualRegister(pVM, PGMVIRTHANDLERTYPE_WRITE, GCPtr, GCPtr + (PAGE_SIZE - 1) /* inclusive! */,
1604 (fMonitorInvalidation) ? CSAMCodePageInvalidate : 0, CSAMCodePageWriteHandler, "CSAMGCCodePageWriteHandler", 0,
1605 csamGetMonitorDescription(enmTag));
1606 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PGM_HANDLER_VIRTUAL_CONFLICT, ("PGMR3HandlerVirtualRegisterEx %VGv failed with %Vrc\n", GCPtr, rc));
1607 if (VBOX_FAILURE(rc))
1608 Log(("PGMR3HandlerVirtualRegisterEx for %VGv failed with %Vrc\n", GCPtr, rc));
1609
1610 /* Could fail, because it's already monitored. Don't treat that condition as fatal. */
1611
1612 /* Prefetch it in case it's not there yet. */
1613 rc = PGMPrefetchPage(pVM, GCPtr);
1614 AssertRC(rc);
1615
1616 rc = PGMShwModifyPage(pVM, GCPtr, 1, 0, ~(uint64_t)X86_PTE_RW);
1617 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1618
1619 pPage->page.fMonitorActive = true;
1620 STAM_COUNTER_INC(&pVM->csam.s.StatPageMonitor);
1621 break;
1622 }
1623 default:
1624 break; /* to shut up GCC */
1625 }
1626
1627 Log(("csamCreatePageRecord %VGv HCPhys=%VGp\n", GCPtr, pPage->page.GCPhys));
1628
1629#ifdef VBOX_WITH_STATISTICS
1630 switch (enmTag)
1631 {
1632 case CSAM_TAG_CSAM:
1633 STAM_COUNTER_INC(&pVM->csam.s.StatPageCSAM);
1634 break;
1635 case CSAM_TAG_PATM:
1636 STAM_COUNTER_INC(&pVM->csam.s.StatPagePATM);
1637 break;
1638 case CSAM_TAG_REM:
1639 STAM_COUNTER_INC(&pVM->csam.s.StatPageREM);
1640 break;
1641 default:
1642 break; /* to shut up GCC */
1643 }
1644#endif
1645
1646#endif
1647
1648 STAM_COUNTER_INC(&pVM->csam.s.StatNrPages);
1649 if (fMonitorInvalidation)
1650 STAM_COUNTER_INC(&pVM->csam.s.StatNrPagesInv);
1651
1652 return &pPage->page;
1653}
1654
1655/**
1656 * Monitors a code page (if not already monitored)
1657 *
1658 * @returns VBox status code
1659 * @param pVM The VM to operate on.
1660 * @param pPageAddrGC The page to monitor
1661 * @param enmTag Monitor tag
1662 */
1663CSAMR3DECL(int) CSAMR3MonitorPage(PVM pVM, RTGCPTR pPageAddrGC, CSAMTAG enmTag)
1664{
1665 PCSAMPAGEREC pPageRec = NULL;
1666 int rc;
1667 bool fMonitorInvalidation;
1668
1669 /* Dirty pages must be handled before calling this function!. */
1670 Assert(!pVM->csam.s.cDirtyPages);
1671
1672 if (pVM->csam.s.fScanningStarted == false)
1673 return VINF_SUCCESS; /* too early */
1674
1675 pPageAddrGC &= PAGE_BASE_GC_MASK;
1676
1677 Log(("CSAMR3MonitorPage %VGv %d\n", pPageAddrGC, enmTag));
1678
1679 /** @todo implicit assumption */
1680 fMonitorInvalidation = (enmTag == CSAM_TAG_PATM);
1681
1682 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)pPageAddrGC);
1683 if (pPageRec == NULL)
1684 {
1685 uint64_t fFlags;
1686
1687 rc = PGMGstGetPage(pVM, pPageAddrGC, &fFlags, NULL);
1688 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Vrc\n", rc));
1689 if ( rc == VINF_SUCCESS
1690 && (fFlags & X86_PTE_US))
1691 {
1692 /* We don't care about user pages. */
1693 STAM_COUNTER_INC(&pVM->csam.s.StatNrUserPages);
1694 return VINF_SUCCESS;
1695 }
1696
1697 csamCreatePageRecord(pVM, pPageAddrGC, enmTag, true /* 32 bits code */, fMonitorInvalidation);
1698
1699 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)pPageAddrGC);
1700 Assert(pPageRec);
1701 }
1702 /** @todo reference count */
1703
1704#ifdef CSAM_MONITOR_CSAM_CODE_PAGES
1705 Assert(pPageRec->page.fMonitorActive);
1706#endif
1707
1708#ifdef CSAM_MONITOR_CODE_PAGES
1709 if (!pPageRec->page.fMonitorActive)
1710 {
1711 Log(("CSAMR3MonitorPage: activate monitoring for %VGv\n", pPageAddrGC));
1712
1713 rc = PGMR3HandlerVirtualRegister(pVM, PGMVIRTHANDLERTYPE_WRITE, pPageAddrGC, pPageAddrGC + (PAGE_SIZE - 1) /* inclusive! */,
1714 (fMonitorInvalidation) ? CSAMCodePageInvalidate : 0, CSAMCodePageWriteHandler, "CSAMGCCodePageWriteHandler", 0,
1715 csamGetMonitorDescription(enmTag));
1716 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PGM_HANDLER_VIRTUAL_CONFLICT, ("PGMR3HandlerVirtualRegisterEx %VGv failed with %Vrc\n", pPageAddrGC, rc));
1717 if (VBOX_FAILURE(rc))
1718 Log(("PGMR3HandlerVirtualRegisterEx for %VGv failed with %Vrc\n", pPageAddrGC, rc));
1719
1720 /* Could fail, because it's already monitored. Don't treat that condition as fatal. */
1721
1722 /* Prefetch it in case it's not there yet. */
1723 rc = PGMPrefetchPage(pVM, pPageAddrGC);
1724 AssertRC(rc);
1725
1726 rc = PGMShwModifyPage(pVM, pPageAddrGC, 1, 0, ~(uint64_t)X86_PTE_RW);
1727 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1728
1729 STAM_COUNTER_INC(&pVM->csam.s.StatPageMonitor);
1730
1731 pPageRec->page.fMonitorActive = true;
1732 pPageRec->page.fMonitorInvalidation = fMonitorInvalidation;
1733 }
1734 else
1735 if ( !pPageRec->page.fMonitorInvalidation
1736 && fMonitorInvalidation)
1737 {
1738 Assert(pPageRec->page.fMonitorActive);
1739 PGMHandlerVirtualChangeInvalidateCallback(pVM, pPageRec->page.pPageGC, CSAMCodePageInvalidate);
1740 pPageRec->page.fMonitorInvalidation = true;
1741 STAM_COUNTER_INC(&pVM->csam.s.StatNrPagesInv);
1742
1743 /* Prefetch it in case it's not there yet. */
1744 rc = PGMPrefetchPage(pVM, pPageAddrGC);
1745 AssertRC(rc);
1746
1747 /* Make sure it's readonly. Page invalidation may have modified the attributes. */
1748 rc = PGMShwModifyPage(pVM, pPageAddrGC, 1, 0, ~(uint64_t)X86_PTE_RW);
1749 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1750 }
1751
1752#if 0 /* def VBOX_STRICT -> very annoying) */
1753 if (pPageRec->page.fMonitorActive)
1754 {
1755 uint64_t fPageShw;
1756 RTHCPHYS GCPhys;
1757 rc = PGMShwGetPage(pVM, pPageAddrGC, &fPageShw, &GCPhys);
1758// AssertMsg( (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1759// || !(fPageShw & X86_PTE_RW)
1760// || (pPageRec->page.GCPhys == 0), ("Shadow page flags for %VGv (%VHp) aren't readonly (%VX64)!!\n", pPageAddrGC, GCPhys, fPageShw));
1761 }
1762#endif
1763
1764 if (pPageRec->page.GCPhys == 0)
1765 {
1766 /* Prefetch it in case it's not there yet. */
1767 rc = PGMPrefetchPage(pVM, pPageAddrGC);
1768 AssertRC(rc);
1769 /* The page was changed behind our back. It won't be made read-only until the next SyncCR3, so force it here. */
1770 rc = PGMShwModifyPage(pVM, pPageAddrGC, 1, 0, ~(uint64_t)X86_PTE_RW);
1771 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1772 }
1773#endif /* CSAM_MONITOR_CODE_PAGES */
1774 return VINF_SUCCESS;
1775}
1776
1777/**
1778 * Removes a page record from our lookup tree
1779 *
1780 * @returns VBox status code
1781 * @param pVM The VM to operate on.
1782 * @param GCPtr Page address
1783 */
1784static int csamRemovePageRecord(PVM pVM, RTGCPTR GCPtr)
1785{
1786 PCSAMPAGEREC pPageRec;
1787
1788 Log(("csamRemovePageRecord %VGv\n", GCPtr));
1789 pPageRec = (PCSAMPAGEREC)RTAvlPVRemove(&pVM->csam.s.pPageTree, (AVLPVKEY)GCPtr);
1790
1791 if (pPageRec)
1792 {
1793 STAM_COUNTER_INC(&pVM->csam.s.StatNrRemovedPages);
1794
1795#ifdef CSAM_MONITOR_CODE_PAGES
1796 if (pPageRec->page.fMonitorActive)
1797 {
1798 /* @todo -> this is expensive (cr3 reload)!!!
1799 * if this happens often, then reuse it instead!!!
1800 */
1801 Assert(!fInCSAMCodePageInvalidate);
1802 STAM_COUNTER_DEC(&pVM->csam.s.StatPageMonitor);
1803 PGMHandlerVirtualDeregister(pVM, GCPtr);
1804 }
1805 if (pPageRec->page.enmTag == CSAM_TAG_PATM)
1806 {
1807 /* Make sure the recompiler flushes its cache as this page is no longer monitored. */
1808 STAM_COUNTER_INC(&pVM->csam.s.StatPageRemoveREMFlush);
1809 CPUMSetChangedFlags(pVM, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
1810 }
1811#endif
1812
1813#ifdef VBOX_WITH_STATISTICS
1814 switch (pPageRec->page.enmTag)
1815 {
1816 case CSAM_TAG_CSAM:
1817 STAM_COUNTER_DEC(&pVM->csam.s.StatPageCSAM);
1818 break;
1819 case CSAM_TAG_PATM:
1820 STAM_COUNTER_DEC(&pVM->csam.s.StatPagePATM);
1821 break;
1822 case CSAM_TAG_REM:
1823 STAM_COUNTER_DEC(&pVM->csam.s.StatPageREM);
1824 break;
1825 default:
1826 break; /* to shut up GCC */
1827 }
1828#endif
1829
1830 if (pPageRec->page.pBitmap) MMR3HeapFree(pPageRec->page.pBitmap);
1831 MMR3HeapFree(pPageRec);
1832 }
1833 else
1834 AssertFailed();
1835
1836 return VINF_SUCCESS;
1837}
1838
1839/**
1840 * Callback for delayed writes from non-EMT threads
1841 *
1842 * @param pVM VM Handle.
1843 * @param GCPtr The virtual address the guest is writing to. (not correct if it's an alias!)
1844 * @param cbBuf How much it's reading/writing.
1845 */
1846static DECLCALLBACK(void) CSAMDelayedWriteHandler(PVM pVM, RTGCPTR GCPtr, size_t cbBuf)
1847{
1848 int rc = PATMR3PatchWrite(pVM, GCPtr, cbBuf);
1849 AssertRC(rc);
1850}
1851
1852/**
1853 * #PF Handler callback for virtual access handler ranges.
1854 *
1855 * Important to realize that a physical page in a range can have aliases, and
1856 * for ALL and WRITE handlers these will also trigger.
1857 *
1858 * @returns VINF_SUCCESS if the handler have carried out the operation.
1859 * @returns VINF_PGM_HANDLER_DO_DEFAULT if the caller should carry out the access operation.
1860 * @param pVM VM Handle.
1861 * @param GCPtr The virtual address the guest is writing to. (not correct if it's an alias!)
1862 * @param pvPtr The HC mapping of that address.
1863 * @param pvBuf What the guest is reading/writing.
1864 * @param cbBuf How much it's reading/writing.
1865 * @param enmAccessType The access type.
1866 * @param pvUser User argument.
1867 */
1868static DECLCALLBACK(int) CSAMCodePageWriteHandler(PVM pVM, RTGCPTR GCPtr, void *pvPtr, void *pvBuf, size_t cbBuf, PGMACCESSTYPE enmAccessType, void *pvUser)
1869{
1870 int rc;
1871
1872 Assert(enmAccessType == PGMACCESSTYPE_WRITE);
1873 Log(("CSAMCodePageWriteHandler: write to %VGv size=%d\n", GCPtr, cbBuf));
1874
1875 if (VM_IS_EMT(pVM))
1876 {
1877 rc = PATMR3PatchWrite(pVM, GCPtr, cbBuf);
1878 }
1879 else
1880 {
1881 /* Queue the write instead otherwise we'll get concurrency issues. */
1882 /** @note in theory not correct to let it write the data first before disabling a patch!
1883 * (if it writes the same data as the patch jump and we replace it with obsolete opcodes)
1884 */
1885 Log(("CSAMCodePageWriteHandler: delayed write!\n"));
1886 rc = VMR3ReqCallEx(pVM, NULL, 0, VMREQFLAGS_NO_WAIT | VMREQFLAGS_VOID,
1887 (PFNRT)CSAMDelayedWriteHandler, 3, pVM, GCPtr, cbBuf);
1888 }
1889 AssertRC(rc);
1890
1891 return VINF_PGM_HANDLER_DO_DEFAULT;
1892}
1893
1894/**
1895 * #PF Handler callback for invalidation of virtual access handler ranges.
1896 *
1897 * @param pVM VM Handle.
1898 * @param GCPtr The virtual address the guest has changed.
1899 */
1900static DECLCALLBACK(int) CSAMCodePageInvalidate(PVM pVM, RTGCPTR GCPtr)
1901{
1902 fInCSAMCodePageInvalidate = true;
1903 LogFlow(("CSAMCodePageInvalidate %VGv\n", GCPtr));
1904 /** @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. */
1905 csamFlushPage(pVM, GCPtr, false /* don't remove page! */);
1906 fInCSAMCodePageInvalidate = false;
1907 return VINF_SUCCESS;
1908}
1909
1910/**
1911 * Check if the current instruction has already been checked before
1912 *
1913 * @returns VBox status code. (trap handled or not)
1914 * @param pVM The VM to operate on.
1915 * @param pInstr Instruction pointer
1916 * @param pPage CSAM patch structure pointer
1917 */
1918bool csamIsCodeScanned(PVM pVM, RTGCPTR pInstr, PCSAMPAGE *pPage)
1919{
1920 PCSAMPAGEREC pPageRec;
1921 uint32_t offset;
1922
1923 STAM_PROFILE_START(&pVM->csam.s.StatTimeCheckAddr, a);
1924
1925 offset = pInstr & PAGE_OFFSET_MASK;
1926 pInstr = pInstr & PAGE_BASE_GC_MASK;
1927
1928 Assert(pPage);
1929
1930 if (*pPage && (*pPage)->pPageGC == pInstr)
1931 {
1932 if ((*pPage)->pBitmap == NULL || ASMBitTest((*pPage)->pBitmap, offset))
1933 {
1934 STAM_COUNTER_ADD(&pVM->csam.s.StatNrKnownPagesHC, 1);
1935 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
1936 return true;
1937 }
1938 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
1939 return false;
1940 }
1941
1942 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)pInstr);
1943 if (pPageRec)
1944 {
1945 if (pPage) *pPage= &pPageRec->page;
1946 if (pPageRec->page.pBitmap == NULL || ASMBitTest(pPageRec->page.pBitmap, offset))
1947 {
1948 STAM_COUNTER_ADD(&pVM->csam.s.StatNrKnownPagesHC, 1);
1949 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
1950 return true;
1951 }
1952 }
1953 else
1954 {
1955 if (pPage) *pPage = NULL;
1956 }
1957 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
1958 return false;
1959}
1960
1961/**
1962 * Mark an instruction in a page as scanned/not scanned
1963 *
1964 * @param pVM The VM to operate on.
1965 * @param pPage Patch structure pointer
1966 * @param pInstr Instruction pointer
1967 * @param opsize Instruction size
1968 * @param fScanned Mark as scanned or not
1969 */
1970static void csamMarkCode(PVM pVM, PCSAMPAGE pPage, RTGCPTR pInstr, uint32_t opsize, bool fScanned)
1971{
1972 LogFlow(("csamMarkCodeAsScanned %VGv opsize=%d\n", pInstr, opsize));
1973 CSAMMarkPage(pVM, pInstr, fScanned);
1974
1975 /** @todo should recreate empty bitmap if !fScanned */
1976 if (pPage->pBitmap == NULL)
1977 return;
1978
1979 if (fScanned)
1980 {
1981 // retn instructions can be scanned more than once
1982 if (ASMBitTest(pPage->pBitmap, pInstr & PAGE_OFFSET_MASK) == 0)
1983 {
1984 pPage->uSize += opsize;
1985 STAM_COUNTER_ADD(&pVM->csam.s.StatNrInstr, 1);
1986 }
1987 if (pPage->uSize >= PAGE_SIZE)
1988 {
1989 Log(("Scanned full page (%VGv) -> free bitmap\n", pInstr & PAGE_BASE_GC_MASK));
1990 MMR3HeapFree(pPage->pBitmap);
1991 pPage->pBitmap = NULL;
1992 }
1993 else
1994 ASMBitSet(pPage->pBitmap, pInstr & PAGE_OFFSET_MASK);
1995 }
1996 else
1997 ASMBitClear(pPage->pBitmap, pInstr & PAGE_OFFSET_MASK);
1998}
1999
2000/**
2001 * Mark an instruction in a page as scanned/not scanned
2002 *
2003 * @returns VBox status code.
2004 * @param pVM The VM to operate on.
2005 * @param pInstr Instruction pointer
2006 * @param opsize Instruction size
2007 * @param fScanned Mark as scanned or not
2008 */
2009CSAMDECL(int) CSAMR3MarkCode(PVM pVM, RTGCPTR pInstr, uint32_t opsize, bool fScanned)
2010{
2011 PCSAMPAGE pPage = 0;
2012
2013 Assert(!fScanned); /* other case not implemented. */
2014 Assert(!PATMIsPatchGCAddr(pVM, pInstr));
2015
2016 if (csamIsCodeScanned(pVM, pInstr, &pPage) == false)
2017 {
2018 Assert(fScanned == true); /* other case should not be possible */
2019 return VINF_SUCCESS;
2020 }
2021
2022 Log(("CSAMR3MarkCode: %VGv size=%d fScanned=%d\n", pInstr, opsize, fScanned));
2023 csamMarkCode(pVM, pPage, pInstr, opsize, fScanned);
2024 return VINF_SUCCESS;
2025}
2026
2027
2028/**
2029 * Scan and analyse code starting at specified EIP
2030 *
2031 * @returns VBox status code. (trap handled or not)
2032 * @param pVM The VM to operate on.
2033 * @param pEip Instruction pointer
2034 * @param fCode32 16 of 32 bits code
2035 */
2036CSAMR3DECL(int) CSAMR3CheckEIP(PVM pVM, RTGCPTR pEip, bool fCode32)
2037{
2038 int rc;
2039 PCSAMPAGE pPage = NULL;
2040
2041 if (EMIsRawRing0Enabled(pVM) == false || PATMIsPatchGCAddr(pVM, pEip) == true)
2042 {
2043 // No use
2044 return VINF_SUCCESS;
2045 }
2046
2047 if (CSAMIsEnabled(pVM))
2048 {
2049 // Cache record for PATMGCVirtToHCVirt
2050 CSAMP2GLOOKUPREC cacheRec = {0};
2051
2052 //assuming 32 bits code for now
2053 Assert(fCode32);
2054
2055 STAM_PROFILE_START(&pVM->csam.s.StatTime, a);
2056 rc = csamAnalyseCallCodeStream(pVM, pEip, pEip, fCode32, CSAMR3AnalyseCallback, pPage, &cacheRec);
2057 STAM_PROFILE_STOP(&pVM->csam.s.StatTime, a);
2058 if (rc != VINF_SUCCESS)
2059 {
2060 Log(("csamAnalyseCodeStream failed with %d\n", rc));
2061 return rc;
2062 }
2063 else
2064 {
2065 // Log(("CSAMR3CheckEIP: already scanned page at %VGv\n", pEip));
2066 }
2067 }
2068 return VINF_SUCCESS;
2069}
2070
2071/**
2072 * Flush dirty code pages
2073 *
2074 * @returns VBox status code.
2075 * @param pVM The VM to operate on.
2076 */
2077CSAMR3DECL(int) CSAMR3FlushDirtyPages(PVM pVM)
2078{
2079 STAM_PROFILE_START(&pVM->csam.s.StatFlushDirtyPages, a);
2080
2081 for (uint32_t i=0;i<pVM->csam.s.cDirtyPages;i++)
2082 {
2083 int rc;
2084 PCSAMPAGEREC pPageRec;
2085 RTGCPTR GCPtr = pVM->csam.s.pvDirtyBasePage[i];
2086
2087 GCPtr = GCPtr & PAGE_BASE_GC_MASK;
2088
2089 /* Notify the recompiler that this page has been changed. */
2090 REMR3NotifyCodePageChanged(pVM, GCPtr);
2091
2092 /* Enable write protection again. (use the fault address as it might be an alias) */
2093 rc = PGMShwModifyPage(pVM, pVM->csam.s.pvDirtyFaultPage[i], 1, 0, ~(uint64_t)X86_PTE_RW);
2094 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
2095
2096 Log(("CSAMR3FlushDirtyPages: flush %VGv (modifypage rc=%Vrc)\n", pVM->csam.s.pvDirtyBasePage[i], rc));
2097
2098 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)GCPtr);
2099 if (pPageRec && pPageRec->page.enmTag == CSAM_TAG_REM)
2100 {
2101 uint64_t fFlags;
2102
2103 rc = PGMGstGetPage(pVM, GCPtr, &fFlags, NULL);
2104 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Vrc\n", rc));
2105 if ( rc == VINF_SUCCESS
2106 && (fFlags & X86_PTE_US))
2107 {
2108 /* We don't care about user pages. */
2109 csamRemovePageRecord(pVM, GCPtr);
2110 STAM_COUNTER_INC(&pVM->csam.s.StatNrUserPages);
2111 }
2112 }
2113 }
2114 pVM->csam.s.cDirtyPages = 0;
2115 VM_FF_CLEAR(pVM, VM_FF_CSAM_FLUSH_DIRTY_PAGE);
2116 STAM_PROFILE_STOP(&pVM->csam.s.StatFlushDirtyPages, a);
2117 return VINF_SUCCESS;
2118}
2119
2120/**
2121 * Analyse interrupt and trap gates
2122 *
2123 * @returns VBox status code.
2124 * @param pVM The VM to operate on.
2125 * @param iGate Start gate
2126 * @param cGates Number of gates to check
2127 */
2128CSAMR3DECL(int) CSAMR3CheckGates(PVM pVM, uint32_t iGate, uint32_t cGates)
2129{
2130 uint16_t cbIDT;
2131 RTGCPTR GCPtrIDT = CPUMGetGuestIDTR(pVM, &cbIDT);
2132 uint32_t iGateEnd;
2133 uint32_t maxGates;
2134 VBOXIDTE aIDT[256];
2135 PVBOXIDTE pGuestIdte;
2136 int rc;
2137
2138 if (EMIsRawRing0Enabled(pVM) == false)
2139 {
2140 /* Enabling interrupt gates only works when raw ring 0 is enabled. */
2141 //AssertFailed();
2142 return VINF_SUCCESS;
2143 }
2144
2145 /* We only check all gates once during a session */
2146 if ( !pVM->csam.s.fGatesChecked
2147 && cGates != 256)
2148 return VINF_SUCCESS; /* too early */
2149
2150 /* We only check all gates once during a session */
2151 if ( pVM->csam.s.fGatesChecked
2152 && cGates != 1)
2153 return VINF_SUCCESS; /* ignored */
2154
2155 if (cGates != 1)
2156 pVM->csam.s.fGatesChecked = true;
2157
2158 Assert(GCPtrIDT && cGates <= 256);
2159 if (!GCPtrIDT || cGates > 256)
2160 return VERR_INVALID_PARAMETER;
2161
2162 /* Determine valid upper boundary. */
2163 maxGates = (cbIDT+1) / sizeof(VBOXIDTE);
2164 Assert(iGate < maxGates);
2165 if (iGate > maxGates)
2166 return VERR_INVALID_PARAMETER;
2167
2168 if (iGate + cGates > maxGates)
2169 cGates = maxGates - iGate;
2170
2171 GCPtrIDT = GCPtrIDT + iGate * sizeof(VBOXIDTE);
2172 iGateEnd = iGate + cGates;
2173
2174 STAM_PROFILE_START(&pVM->csam.s.StatCheckGates, a);
2175
2176 /*
2177 * Get IDT entries.
2178 */
2179 if (PAGE_ADDRESS(GCPtrIDT) == PAGE_ADDRESS(GCPtrIDT+cGates*sizeof(VBOXIDTE)))
2180 {
2181 /* Just convert the IDT address to a HC pointer. The whole IDT fits in one page. */
2182 rc = PGMPhysGCPtr2HCPtr(pVM, GCPtrIDT, (PRTHCPTR)&pGuestIdte);
2183 if (VBOX_FAILURE(rc))
2184 {
2185 AssertMsgRC(rc, ("Failed to read IDTE! rc=%Vrc\n", rc));
2186 STAM_PROFILE_STOP(&pVM->csam.s.StatCheckGates, a);
2187 return rc;
2188 }
2189 }
2190 else
2191 {
2192 /* Slow method when it crosses a page boundary. */
2193 rc = PGMPhysReadGCPtr(pVM, aIDT, GCPtrIDT, cGates*sizeof(VBOXIDTE));
2194 if (VBOX_FAILURE(rc))
2195 {
2196 AssertMsgRC(rc, ("Failed to read IDTE! rc=%Vrc\n", rc));
2197 STAM_PROFILE_STOP(&pVM->csam.s.StatCheckGates, a);
2198 return rc;
2199 }
2200 pGuestIdte = &aIDT[0];
2201 }
2202
2203 for (/*iGate*/; iGate<iGateEnd; iGate++, pGuestIdte++)
2204 {
2205 Assert(TRPMR3GetGuestTrapHandler(pVM, iGate) == TRPM_INVALID_HANDLER);
2206
2207 if ( pGuestIdte->Gen.u1Present
2208 && (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32 || pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_INT_32)
2209 && (pGuestIdte->Gen.u2DPL == 3 || pGuestIdte->Gen.u2DPL == 0)
2210 )
2211 {
2212 RTGCPTR pHandler;
2213 CSAMP2GLOOKUPREC cacheRec = {0}; /* Cache record for PATMGCVirtToHCVirt. */
2214 PCSAMPAGE pPage = NULL;
2215
2216 pHandler = (pGuestIdte->Gen.u16OffsetHigh << 16) | pGuestIdte->Gen.u16OffsetLow;
2217 pHandler = SELMToFlat(pVM, pGuestIdte->Gen.u16SegSel, 0, pHandler);
2218
2219 if (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32)
2220 {
2221 Log(("CSAMCheckGates: check trap gate %d at %04X:%08X (flat %VGv)\n", iGate, pGuestIdte->Gen.u16SegSel, (pGuestIdte->Gen.u16OffsetHigh << 16) | pGuestIdte->Gen.u16OffsetLow, pHandler));
2222 }
2223 else
2224 {
2225 Log(("CSAMCheckGates: check interrupt gate %d at %04X:%08X (flat %VGv)\n", iGate, pGuestIdte->Gen.u16SegSel, (pGuestIdte->Gen.u16OffsetHigh << 16) | pGuestIdte->Gen.u16OffsetLow, pHandler));
2226 }
2227
2228 STAM_PROFILE_START(&pVM->csam.s.StatTime, a);
2229 rc = csamAnalyseCodeStream(pVM, pHandler, pHandler, true, CSAMR3AnalyseCallback, pPage, &cacheRec);
2230 STAM_PROFILE_STOP(&pVM->csam.s.StatTime, a);
2231 if (rc != VINF_SUCCESS)
2232 {
2233 Log(("CSAMCheckGates: csamAnalyseCodeStream failed with %d\n", rc));
2234 continue;
2235 }
2236 if (iGate >= 0x20)
2237 {
2238 /* OpenBSD guest specific patch test (3.7 & 3.8) */
2239 rc = PATMR3InstallPatch(pVM, pHandler - 3, PATMFL_CODE32 | PATMFL_GUEST_SPECIFIC);
2240 if (VBOX_FAILURE(rc))
2241 /* OpenBSD guest specific patch test (3.9 & 4.0) */
2242 rc = PATMR3InstallPatch(pVM, pHandler - 0x2B, PATMFL_CODE32 | PATMFL_GUEST_SPECIFIC);
2243 if (VBOX_SUCCESS(rc))
2244 Log(("Installed OpenBSD interrupt handler prefix instruction (push cs) patch\n"));
2245 }
2246
2247 /* Trap gates and certain interrupt gates. */
2248 uint32_t fPatchFlags = PATMFL_CODE32 | PATMFL_IDTHANDLER;
2249
2250 if (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32)
2251 fPatchFlags |= PATMFL_TRAPHANDLER;
2252 else
2253 fPatchFlags |= PATMFL_INTHANDLER;
2254
2255 switch (iGate) {
2256 case 8:
2257 case 10:
2258 case 11:
2259 case 12:
2260 case 13:
2261 case 14:
2262 case 17:
2263 fPatchFlags |= PATMFL_TRAPHANDLER_WITH_ERRORCODE;
2264 break;
2265 default:
2266 /* No error code. */
2267 break;
2268 }
2269
2270 Log(("Installing %s gate handler for 0x%X at %VGv\n", (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32) ? "trap" : "intr", iGate, pHandler));
2271
2272 rc = PATMR3InstallPatch(pVM, pHandler, fPatchFlags);
2273 if (VBOX_SUCCESS(rc) || rc == VERR_PATM_ALREADY_PATCHED)
2274 {
2275 Log(("Gate handler 0x%X is SAFE!\n", iGate));
2276
2277 RTGCPTR pNewHandlerGC = PATMR3QueryPatchGCPtr(pVM, pHandler);
2278 if (pNewHandlerGC)
2279 {
2280 rc = TRPMR3SetGuestTrapHandler(pVM, iGate, pNewHandlerGC);
2281 if (VBOX_FAILURE(rc))
2282 Log(("TRPMR3SetGuestTrapHandler %d failed with %Vrc\n", iGate, rc));
2283 }
2284 }
2285 }
2286 } /* for */
2287 STAM_PROFILE_STOP(&pVM->csam.s.StatCheckGates, a);
2288 return VINF_SUCCESS;
2289}
2290
2291/**
2292 * Query CSAM state (enabled/disabled)
2293 *
2294 * @returns 0 - disabled, 1 - enabled
2295 * @param pVM The VM to operate on.
2296 */
2297CSAMR3DECL(int) CSAMR3IsEnabled(PVM pVM)
2298{
2299 return pVM->fCSAMEnabled;
2300}
2301
2302#ifdef VBOX_WITH_DEBUGGER
2303/**
2304 * The '.csamoff' command.
2305 *
2306 * @returns VBox status.
2307 * @param pCmd Pointer to the command descriptor (as registered).
2308 * @param pCmdHlp Pointer to command helper functions.
2309 * @param pVM Pointer to the current VM (if any).
2310 * @param paArgs Pointer to (readonly) array of arguments.
2311 * @param cArgs Number of arguments in the array.
2312 */
2313static DECLCALLBACK(int) csamr3CmdOff(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PVM pVM, PCDBGCVAR paArgs, unsigned cArgs, PDBGCVAR pResult)
2314{
2315 /*
2316 * Validate input.
2317 */
2318 if (!pVM)
2319 return pCmdHlp->pfnPrintf(pCmdHlp, NULL, "error: The command requires VM to be selected.\n");
2320
2321 CSAMDisableScanning(pVM);
2322 return pCmdHlp->pfnPrintf(pCmdHlp, NULL, "CSAM Scanning disabled\n");
2323}
2324
2325/**
2326 * The '.csamon' command.
2327 *
2328 * @returns VBox status.
2329 * @param pCmd Pointer to the command descriptor (as registered).
2330 * @param pCmdHlp Pointer to command helper functions.
2331 * @param pVM Pointer to the current VM (if any).
2332 * @param paArgs Pointer to (readonly) array of arguments.
2333 * @param cArgs Number of arguments in the array.
2334 */
2335static DECLCALLBACK(int) csamr3CmdOn(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PVM pVM, PCDBGCVAR paArgs, unsigned cArgs, PDBGCVAR pResult)
2336{
2337 /*
2338 * Validate input.
2339 */
2340 if (!pVM)
2341 return pCmdHlp->pfnPrintf(pCmdHlp, NULL, "error: The command requires VM to be selected.\n");
2342
2343 CSAMEnableScanning(pVM);
2344 return pCmdHlp->pfnPrintf(pCmdHlp, NULL, "CSAM Scanning enabled\n");
2345}
2346#endif
Note: See TracBrowser for help on using the repository browser.

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