VirtualBox

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

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

Biggest check-in ever. New source code headers for all (C) innotek files.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 87.0 KB
Line 
1/* $Id: CSAM.cpp 4071 2007-08-07 17:07:59Z 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 HCPTRTYPE(void *) CSAMGCVirtToHCVirt(PVM pVM, PCSAMP2GLOOKUPREC pCacheRec, GCPTRTYPE(uint8_t *) pGCPtr)
551{
552 int rc;
553 HCPTRTYPE(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(HCPTRTYPE(uint8_t*)) == sizeof(uint32_t));
578
579 pCacheRec->pPageLocStartHC = (HCPTRTYPE(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 */
595int32_t CSAMR3ReadBytes(RTHCUINTPTR pSrc, uint8_t *pDest, uint32_t size, RTHCUINTPTR dwUserdata)
596{
597 DISCPUSTATE *pCpu = (DISCPUSTATE *)dwUserdata;
598 PVM pVM = (PVM)pCpu->dwUserData[0];
599 RTHCUINTPTR pInstrHC = pCpu->dwUserData[1];
600 RTGCUINTPTR pInstrGC = pCpu->dwUserData[2];
601 int orgsize = size;
602
603 Assert(sizeof(RTHCUINTPTR) <= sizeof(pCpu->dwUserData[0]));
604 Assert(sizeof(RTGCUINTPTR) <= sizeof(pCpu->dwUserData[0]));
605
606 /* We are not interested in patched instructions, so read the original opcode bytes. */
607 /** @note single instruction patches (int3) are checked in CSAMR3AnalyseCallback */
608 for (int i=0;i<orgsize;i++)
609 {
610 int rc = PATMR3QueryOpcode(pVM, (RTGCPTR)pSrc, pDest);
611 if (VBOX_SUCCESS(rc))
612 {
613 pSrc++;
614 pDest++;
615 size--;
616 }
617 else
618 break;
619 }
620 if (size == 0)
621 return VINF_SUCCESS;
622
623 if (PAGE_ADDRESS(pInstrGC) != PAGE_ADDRESS(pSrc + size - 1) && !PATMIsPatchGCAddr(pVM, pSrc))
624 {
625 return PGMPhysReadGCPtr(pVM, pDest, pSrc, size);
626 }
627 else
628 {
629 Assert(pInstrHC);
630
631 /* pInstrHC is the base address; adjust according to the GC pointer. */
632 pInstrHC = pInstrHC + (pSrc - pInstrGC);
633
634 memcpy(pDest, (void *)pInstrHC, size);
635 }
636
637 return VINF_SUCCESS;
638}
639
640inline bool CSAMR3DISInstr(PVM pVM, DISCPUSTATE *pCpu, RTGCPTR InstrGC, uint8_t *InstrHC, uint32_t *pOpsize, char *pszOutput)
641{
642 (pCpu)->pfnReadBytes = CSAMR3ReadBytes;
643 (pCpu)->dwUserData[0] = (RTHCUINTPTR)pVM;
644 (pCpu)->dwUserData[1] = (RTHCUINTPTR)InstrHC;
645 (pCpu)->dwUserData[2] = (RTHCUINTPTR)InstrGC;
646#ifdef DEBUG
647 return DISInstrEx(pCpu, InstrGC, 0, pOpsize, pszOutput, OPTYPE_ALL);
648#else
649 /* We are interested in everything except harmless stuff */
650 return DISInstrEx(pCpu, InstrGC, 0, pOpsize, pszOutput, ~(OPTYPE_INVALID | OPTYPE_HARMLESS | OPTYPE_RRM_MASK));
651#endif
652}
653
654/**
655 * Analyses the instructions following the cli for compliance with our heuristics for cli
656 *
657 * @returns VBox status code.
658 * @param pVM The VM to operate on.
659 * @param pCpu CPU disassembly state
660 * @param pInstrGC Guest context pointer to privileged instruction
661 * @param pCurInstrGC Guest context pointer to the current instruction
662 * @param pCacheRec GC to HC cache record
663 * @param pUserData User pointer (callback specific)
664 *
665 */
666static int CSAMR3AnalyseCallback(PVM pVM, DISCPUSTATE *pCpu, GCPTRTYPE(uint8_t *) pInstrGC, GCPTRTYPE(uint8_t *) pCurInstrGC,
667 PCSAMP2GLOOKUPREC pCacheRec, void *pUserData)
668{
669 PCSAMPAGE pPage = (PCSAMPAGE)pUserData;
670 int rc;
671
672 switch(pCpu->pCurInstr->opcode)
673 {
674 case OP_INT:
675 Assert(pCpu->param1.flags & USE_IMMEDIATE8);
676 if (pCpu->param1.parval == 3)
677 {
678 //two byte int 3
679 return VINF_SUCCESS;
680 }
681 break;
682
683 case OP_ILLUD2:
684 /* This appears to be some kind of kernel panic in Linux 2.4; no point to continue. */
685 case OP_RETN:
686 case OP_INT3:
687 case OP_INVALID:
688#if 1
689 /* removing breaks win2k guests? */
690 case OP_IRET:
691#endif
692 return VINF_SUCCESS;
693 }
694
695 // Check for exit points
696 switch (pCpu->pCurInstr->opcode)
697 {
698 /* It's not a good idea to patch pushf instructions:
699 * - increases the chance of conflicts (code jumping to the next instruction)
700 * - better to patch the cli
701 * - code that branches before the cli will likely hit an int 3
702 * - in general doesn't offer any benefits as we don't allow nested patch blocks (IF is always 1)
703 */
704 case OP_PUSHF:
705 case OP_POPF:
706 break;
707
708 case OP_CLI:
709 {
710 uint32_t cbInstr = 0;
711 uint32_t opsize = pCpu->opsize;
712
713 PATMR3AddHint(pVM, pCurInstrGC, (pPage->fCode32) ? PATMFL_CODE32 : 0);
714
715 /* Make sure the instructions that follow the cli have not been encountered before. */
716 while (true)
717 {
718 DISCPUSTATE cpu;
719 uint8_t *pCurInstrHC = 0;
720 bool disret;
721
722 if (cbInstr + opsize >= SIZEOF_NEARJUMP32)
723 break;
724
725 if (csamIsCodeScanned(pVM, pCurInstrGC + opsize, &pPage) == true)
726 {
727 /* We've scanned the next instruction(s) already. This means we've followed a branch that ended up there before -> dangerous!! */
728 PATMR3DetectConflict(pVM, pCurInstrGC, pCurInstrGC + opsize);
729 break;
730 }
731 pCurInstrGC += opsize;
732 cbInstr += opsize;
733
734 pCurInstrHC = (uint8_t *)CSAMGCVirtToHCVirt(pVM, pCacheRec, pCurInstrGC);
735 if (pCurInstrHC == NULL)
736 {
737 Log(("CSAMGCVirtToHCVirt failed for %VGv\n", pCurInstrGC));
738 break;
739 }
740 Assert(VALID_PTR(pCurInstrHC));
741
742 cpu.mode = (pPage->fCode32) ? CPUMODE_32BIT : CPUMODE_16BIT;
743 disret = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, NULL);
744 Assert(disret == true);
745 if (disret == false)
746 break;
747 }
748 break;
749 }
750
751 case OP_PUSH:
752 if (pCpu->pCurInstr->param1 != OP_PARM_REG_CS)
753 break;
754
755 /* no break */
756 case OP_STR:
757 case OP_LSL:
758 case OP_LAR:
759 case OP_SGDT:
760 case OP_SLDT:
761 case OP_SIDT:
762 case OP_SMSW:
763 case OP_VERW:
764 case OP_VERR:
765 case OP_CPUID:
766 case OP_IRET:
767#ifdef DEBUG
768 switch(pCpu->pCurInstr->opcode)
769 {
770 case OP_STR:
771 Log(("Privileged instruction at %VGv: str!!\n", pCurInstrGC));
772 break;
773 case OP_LSL:
774 Log(("Privileged instruction at %VGv: lsl!!\n", pCurInstrGC));
775 break;
776 case OP_LAR:
777 Log(("Privileged instruction at %VGv: lar!!\n", pCurInstrGC));
778 break;
779 case OP_SGDT:
780 Log(("Privileged instruction at %VGv: sgdt!!\n", pCurInstrGC));
781 break;
782 case OP_SLDT:
783 Log(("Privileged instruction at %VGv: sldt!!\n", pCurInstrGC));
784 break;
785 case OP_SIDT:
786 Log(("Privileged instruction at %VGv: sidt!!\n", pCurInstrGC));
787 break;
788 case OP_SMSW:
789 Log(("Privileged instruction at %VGv: smsw!!\n", pCurInstrGC));
790 break;
791 case OP_VERW:
792 Log(("Privileged instruction at %VGv: verw!!\n", pCurInstrGC));
793 break;
794 case OP_VERR:
795 Log(("Privileged instruction at %VGv: verr!!\n", pCurInstrGC));
796 break;
797 case OP_CPUID:
798 Log(("Privileged instruction at %VGv: cpuid!!\n", pCurInstrGC));
799 break;
800 case OP_PUSH:
801 Log(("Privileged instruction at %VGv: push cs!!\n", pCurInstrGC));
802 break;
803 case OP_IRET:
804 Log(("Privileged instruction at %VGv: iret!!\n", pCurInstrGC));
805 break;
806 }
807#endif
808
809 if (PATMR3HasBeenPatched(pVM, pCurInstrGC) == false)
810 {
811 rc = PATMR3InstallPatch(pVM, pCurInstrGC, (pPage->fCode32) ? PATMFL_CODE32 : 0);
812 if (VBOX_FAILURE(rc))
813 {
814 Log(("PATMR3InstallPatch failed with %d\n", rc));
815 return VWRN_CONTINUE_ANALYSIS;
816 }
817 }
818 if (pCpu->pCurInstr->opcode == OP_IRET)
819 return VINF_SUCCESS; /* Look no further in this branch. */
820
821 return VWRN_CONTINUE_ANALYSIS;
822
823 case OP_JMP:
824 case OP_CALL:
825 {
826 // return or jump/call through a jump table
827 if (OP_PARM_VTYPE(pCpu->pCurInstr->param1) != OP_PARM_J)
828 {
829#ifdef DEBUG
830 switch(pCpu->pCurInstr->opcode)
831 {
832 case OP_JMP:
833 Log(("Control Flow instruction at %VGv: jmp!!\n", pCurInstrGC));
834 break;
835 case OP_CALL:
836 Log(("Control Flow instruction at %VGv: call!!\n", pCurInstrGC));
837 break;
838 }
839#endif
840 return VWRN_CONTINUE_ANALYSIS;
841 }
842 return VWRN_CONTINUE_ANALYSIS;
843 }
844
845 }
846
847 return VWRN_CONTINUE_ANALYSIS;
848}
849
850#ifdef CSAM_ANALYSE_BEYOND_RET
851/**
852 * Wrapper for csamAnalyseCodeStream for call instructions.
853 *
854 * @returns VBox status code.
855 * @param pVM The VM to operate on.
856 * @param pInstrGC Guest context pointer to privileged instruction
857 * @param pCurInstrGC Guest context pointer to the current instruction
858 * @param fCode32 16 or 32 bits code
859 * @param pfnCSAMR3Analyse Callback for testing the disassembled instruction
860 * @param pUserData User pointer (callback specific)
861 *
862 */
863static int csamAnalyseCallCodeStream(PVM pVM, GCPTRTYPE(uint8_t *) pInstrGC, GCPTRTYPE(uint8_t *) pCurInstrGC, bool fCode32,
864 PFN_CSAMR3ANALYSE pfnCSAMR3Analyse, void *pUserData, PCSAMP2GLOOKUPREC pCacheRec)
865{
866 int rc;
867 CSAMCALLEXITREC CallExitRec;
868 PCSAMCALLEXITREC pOldCallRec;
869 PCSAMPAGE pPage = 0;
870 uint32_t i;
871
872 CallExitRec.cInstrAfterRet = 0;
873
874 pOldCallRec = pCacheRec->pCallExitRec;
875 pCacheRec->pCallExitRec = &CallExitRec;
876
877 rc = csamAnalyseCodeStream(pVM, pInstrGC, pCurInstrGC, fCode32, pfnCSAMR3Analyse, pUserData, pCacheRec);
878
879 for (i=0;i<CallExitRec.cInstrAfterRet;i++)
880 {
881 PCSAMPAGE pPage = 0;
882
883 pCurInstrGC = CallExitRec.pInstrAfterRetGC[i];
884
885 /* Check if we've previously encountered the instruction after the ret. */
886 if (csamIsCodeScanned(pVM, pCurInstrGC, &pPage) == false)
887 {
888 DISCPUSTATE cpu;
889 uint32_t opsize;
890 uint8_t *pCurInstrHC = 0;
891 bool disret;
892#ifdef DEBUG
893 char szOutput[256];
894#endif
895 if (pPage == NULL)
896 {
897 /* New address; let's take a look at it. */
898 pPage = csamCreatePageRecord(pVM, pCurInstrGC, CSAM_TAG_CSAM, fCode32);
899 if (pPage == NULL)
900 {
901 rc = VERR_NO_MEMORY;
902 goto done;
903 }
904 }
905
906 /**
907 * Some generic requirements for recognizing an adjacent function:
908 * - alignment fillers that consist of:
909 * - nop
910 * - lea genregX, [genregX (+ 0)]
911 * - push ebp after the filler (can extend this later); aligned at at least a 4 byte boundary
912 */
913 for (int j=0;j<16;j++)
914 {
915 pCurInstrHC = (uint8_t *)CSAMGCVirtToHCVirt(pVM, pCacheRec, pCurInstrGC);
916 if (pCurInstrHC == NULL)
917 {
918 Log(("CSAMGCVirtToHCVirt failed for %VGv\n", pCurInstrGC));
919 goto done;
920 }
921 Assert(VALID_PTR(pCurInstrHC));
922
923 cpu.mode = (fCode32) ? CPUMODE_32BIT : CPUMODE_16BIT;
924 STAM_PROFILE_START(&pVM->csam.s.StatTimeDisasm, a);
925#ifdef DEBUG
926 disret = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, szOutput);
927 if (disret == true) Log(("CSAM Call Analysis: %s", szOutput));
928#else
929 disret = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, NULL);
930#endif
931 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeDisasm, a);
932 if (disret == false)
933 {
934 Log(("Disassembly failed at %VGv (probably page not present) -> return to caller\n", pCurInstrGC));
935 goto done;
936 }
937
938 STAM_COUNTER_ADD(&pVM->csam.s.StatNrBytesRead, opsize);
939
940 GCPTRTYPE(uint8_t *) addr = 0;
941 PCSAMPAGE pJmpPage = NULL;
942
943 if (PAGE_ADDRESS(pCurInstrGC) != PAGE_ADDRESS(pCurInstrGC + opsize - 1))
944 {
945 if (!PGMGstIsPagePresent(pVM, pCurInstrGC + opsize - 1))
946 {
947 /// @todo fault in the page
948 Log(("Page for current instruction %VGv is not present!!\n", pCurInstrGC));
949 goto done;
950 }
951 //all is fine, let's continue
952 csamR3CheckPageRecord(pVM, pCurInstrGC + opsize - 1);
953 }
954
955 switch (cpu.pCurInstr->opcode)
956 {
957 case OP_NOP:
958 case OP_INT3:
959 break; /* acceptable */
960
961 case OP_LEA:
962 /* Must be similar to:
963 *
964 * lea esi, [esi]
965 * lea esi, [esi+0]
966 * Any register is allowed as long as source and destination are identical.
967 */
968 if ( cpu.param1.flags != USE_REG_GEN32
969 || ( cpu.param2.flags != USE_REG_GEN32
970 && ( !(cpu.param2.flags & USE_REG_GEN32)
971 || !(cpu.param2.flags & (USE_DISPLACEMENT8|USE_DISPLACEMENT16|USE_DISPLACEMENT32))
972 || cpu.param2.parval != 0
973 )
974 )
975 || cpu.param1.base.reg_gen32 != cpu.param2.base.reg_gen32
976 )
977 {
978 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunctionFailed);
979 goto next_function;
980 }
981 break;
982
983 case OP_PUSH:
984 {
985 if ( (pCurInstrGC & 0x3) != 0
986 || cpu.param1.flags != USE_REG_GEN32
987 || cpu.param1.base.reg_gen32 != USE_REG_EBP
988 )
989 {
990 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunctionFailed);
991 goto next_function;
992 }
993
994 if (csamIsCodeScanned(pVM, pCurInstrGC, &pPage) == false)
995 {
996 CSAMCALLEXITREC CallExitRec2;
997 CallExitRec2.cInstrAfterRet = 0;
998
999 pCacheRec->pCallExitRec = &CallExitRec2;
1000
1001 /* Analyse the function. */
1002 Log(("Found new function at %VGv\n", pCurInstrGC));
1003 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunction);
1004 csamAnalyseCallCodeStream(pVM, pInstrGC, pCurInstrGC, fCode32, pfnCSAMR3Analyse, pUserData, pCacheRec);
1005 }
1006 goto next_function;
1007 }
1008
1009 case OP_SUB:
1010 {
1011 if ( (pCurInstrGC & 0x3) != 0
1012 || cpu.param1.flags != USE_REG_GEN32
1013 || cpu.param1.base.reg_gen32 != USE_REG_ESP
1014 )
1015 {
1016 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunctionFailed);
1017 goto next_function;
1018 }
1019
1020 if (csamIsCodeScanned(pVM, pCurInstrGC, &pPage) == false)
1021 {
1022 CSAMCALLEXITREC CallExitRec2;
1023 CallExitRec2.cInstrAfterRet = 0;
1024
1025 pCacheRec->pCallExitRec = &CallExitRec2;
1026
1027 /* Analyse the function. */
1028 Log(("Found new function at %VGv\n", pCurInstrGC));
1029 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunction);
1030 csamAnalyseCallCodeStream(pVM, pInstrGC, pCurInstrGC, fCode32, pfnCSAMR3Analyse, pUserData, pCacheRec);
1031 }
1032 goto next_function;
1033 }
1034
1035 default:
1036 STAM_COUNTER_INC(&pVM->csam.s.StatScanNextFunctionFailed);
1037 goto next_function;
1038 }
1039 /* Mark it as scanned. */
1040 csamMarkCode(pVM, pPage, pCurInstrGC, opsize, true);
1041 pCurInstrGC += opsize;
1042 } /* for at most 16 instructions */
1043next_function:
1044 ; /* MSVC complains otherwise */
1045 }
1046 }
1047done:
1048 pCacheRec->pCallExitRec = pOldCallRec;
1049 return rc;
1050}
1051#else
1052#define csamAnalyseCallCodeStream csamAnalyseCodeStream
1053#endif
1054
1055/**
1056 * Disassembles the code stream until the callback function detects a failure or decides everything is acceptable
1057 *
1058 * @returns VBox status code.
1059 * @param pVM The VM to operate on.
1060 * @param pInstrGC Guest context pointer to privileged instruction
1061 * @param pCurInstrGC Guest context pointer to the current instruction
1062 * @param fCode32 16 or 32 bits code
1063 * @param pfnCSAMR3Analyse Callback for testing the disassembled instruction
1064 * @param pUserData User pointer (callback specific)
1065 *
1066 */
1067static int csamAnalyseCodeStream(PVM pVM, GCPTRTYPE(uint8_t *) pInstrGC, GCPTRTYPE(uint8_t *) pCurInstrGC, bool fCode32,
1068 PFN_CSAMR3ANALYSE pfnCSAMR3Analyse, void *pUserData, PCSAMP2GLOOKUPREC pCacheRec)
1069{
1070 DISCPUSTATE cpu;
1071 PCSAMPAGE pPage = (PCSAMPAGE)pUserData;
1072 int rc = VWRN_CONTINUE_ANALYSIS;
1073 uint32_t opsize;
1074 HCPTRTYPE(uint8_t *) pCurInstrHC = 0;
1075 bool disret;
1076
1077#ifdef DEBUG
1078 char szOutput[256];
1079#endif
1080
1081 LogFlow(("csamAnalyseCodeStream: code at %VGv depth=%d\n", pCurInstrGC, pCacheRec->depth));
1082
1083 pVM->csam.s.fScanningStarted = true;
1084
1085 pCacheRec->depth++;
1086 /*
1087 * Limit the call depth. (rather arbitrary upper limit; too low and we won't detect certain
1088 * cpuid instructions in Linux kernels; too high and we waste too much time scanning code)
1089 * (512 is necessary to detect cpuid instructions in Red Hat EL4; see defect 1355)
1090 * @note we are using a lot of stack here. couple of 100k when we go to the full depth (!)
1091 */
1092 if (pCacheRec->depth > 512)
1093 {
1094 LogFlow(("CSAM: maximum calldepth reached for %VGv\n", pCurInstrGC));
1095 pCacheRec->depth--;
1096 return VINF_SUCCESS; //let's not go on forever
1097 }
1098
1099 Assert(!PATMIsPatchGCAddr(pVM, pCurInstrGC));
1100 csamR3CheckPageRecord(pVM, pCurInstrGC);
1101
1102 while(rc == VWRN_CONTINUE_ANALYSIS)
1103 {
1104 if (csamIsCodeScanned(pVM, pCurInstrGC, &pPage) == false)
1105 {
1106 if (pPage == NULL)
1107 {
1108 /* New address; let's take a look at it. */
1109 pPage = csamCreatePageRecord(pVM, pCurInstrGC, CSAM_TAG_CSAM, fCode32);
1110 if (pPage == NULL)
1111 {
1112 rc = VERR_NO_MEMORY;
1113 goto done;
1114 }
1115 }
1116 }
1117 else
1118 {
1119 LogFlow(("Code at %VGv has been scanned before\n", pCurInstrGC));
1120 rc = VINF_SUCCESS;
1121 goto done;
1122 }
1123
1124 pCurInstrHC = (uint8_t *)CSAMGCVirtToHCVirt(pVM, pCacheRec, pCurInstrGC);
1125 if (pCurInstrHC == NULL)
1126 {
1127 Log(("CSAMGCVirtToHCVirt failed for %VGv\n", pCurInstrGC));
1128 rc = VERR_PATCHING_REFUSED;
1129 goto done;
1130 }
1131 Assert(VALID_PTR(pCurInstrHC));
1132
1133 cpu.mode = (fCode32) ? CPUMODE_32BIT : CPUMODE_16BIT;
1134 STAM_PROFILE_START(&pVM->csam.s.StatTimeDisasm, a);
1135#ifdef DEBUG
1136 disret = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, szOutput);
1137 if (disret == true) Log(("CSAM Analysis: %s", szOutput));
1138#else
1139 disret = CSAMR3DISInstr(pVM, &cpu, pCurInstrGC, pCurInstrHC, &opsize, NULL);
1140#endif
1141 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeDisasm, a);
1142 if (disret == false)
1143 {
1144 Log(("Disassembly failed at %VGv (probably page not present) -> return to caller\n", pCurInstrGC));
1145 rc = VINF_SUCCESS;
1146 goto done;
1147 }
1148
1149 STAM_COUNTER_ADD(&pVM->csam.s.StatNrBytesRead, opsize);
1150
1151 csamMarkCode(pVM, pPage, pCurInstrGC, opsize, true);
1152
1153 GCPTRTYPE(uint8_t *) addr = 0;
1154 PCSAMPAGE pJmpPage = NULL;
1155
1156 if (PAGE_ADDRESS(pCurInstrGC) != PAGE_ADDRESS(pCurInstrGC + opsize - 1))
1157 {
1158 if (!PGMGstIsPagePresent(pVM, pCurInstrGC + opsize - 1))
1159 {
1160 /// @todo fault in the page
1161 Log(("Page for current instruction %VGv is not present!!\n", pCurInstrGC));
1162 rc = VWRN_CONTINUE_ANALYSIS;
1163 goto next_please;
1164 }
1165 //all is fine, let's continue
1166 csamR3CheckPageRecord(pVM, pCurInstrGC + opsize - 1);
1167 }
1168 /*
1169 * If it's harmless, then don't bother checking it (the disasm tables had better be accurate!)
1170 */
1171 if ((cpu.pCurInstr->optype & ~OPTYPE_RRM_MASK) == OPTYPE_HARMLESS)
1172 {
1173 AssertMsg(pfnCSAMR3Analyse(pVM, &cpu, pInstrGC, pCurInstrGC, pCacheRec, (void *)pPage) == VWRN_CONTINUE_ANALYSIS, ("Instruction incorrectly marked harmless?!?!?\n"));
1174 rc = VWRN_CONTINUE_ANALYSIS;
1175 goto next_please;
1176 }
1177
1178#ifdef CSAM_ANALYSE_BEYOND_RET
1179 /* Remember the address of the instruction following the ret in case the parent instruction was a call. */
1180 if ( pCacheRec->pCallExitRec
1181 && cpu.pCurInstr->opcode == OP_RETN
1182 && pCacheRec->pCallExitRec->cInstrAfterRet < CSAM_MAX_CALLEXIT_RET)
1183 {
1184 pCacheRec->pCallExitRec->pInstrAfterRetGC[pCacheRec->pCallExitRec->cInstrAfterRet] = pCurInstrGC + opsize;
1185 pCacheRec->pCallExitRec->cInstrAfterRet++;
1186 }
1187#endif
1188
1189 rc = pfnCSAMR3Analyse(pVM, &cpu, pInstrGC, pCurInstrGC, pCacheRec, (void *)pPage);
1190 if (rc == VINF_SUCCESS)
1191 goto done;
1192
1193 // For our first attempt, we'll handle only simple relative jumps and calls (immediate offset coded in instruction)
1194 if ((cpu.pCurInstr->optype & OPTYPE_CONTROLFLOW) && (OP_PARM_VTYPE(cpu.pCurInstr->param1) == OP_PARM_J))
1195 {
1196 addr = CSAMResolveBranch(&cpu, pCurInstrGC);
1197 if (addr == 0)
1198 {
1199 Log(("We don't support far jumps here!! (%08X)\n", cpu.param1.flags));
1200 rc = VINF_SUCCESS;
1201 break;
1202 }
1203 Assert(!PATMIsPatchGCAddr(pVM, addr));
1204
1205 /* If the target address lies in a patch generated jump, then special action needs to be taken. */
1206 PATMR3DetectConflict(pVM, pCurInstrGC, addr);
1207
1208 /* Same page? */
1209 if (PAGE_ADDRESS(addr) != PAGE_ADDRESS(pCurInstrGC ))
1210 {
1211 if (!PGMGstIsPagePresent(pVM, addr))
1212 {
1213 Log(("Page for current instruction %VGv is not present!!\n", addr));
1214 rc = VWRN_CONTINUE_ANALYSIS;
1215 goto next_please;
1216 }
1217
1218 /* All is fine, let's continue. */
1219 csamR3CheckPageRecord(pVM, addr);
1220 }
1221
1222 pJmpPage = NULL;
1223 if (csamIsCodeScanned(pVM, addr, &pJmpPage) == false)
1224 {
1225 if (pJmpPage == NULL)
1226 {
1227 /* New branch target; let's take a look at it. */
1228 pJmpPage = csamCreatePageRecord(pVM, addr, CSAM_TAG_CSAM, fCode32);
1229 if (pJmpPage == NULL)
1230 {
1231 rc = VERR_NO_MEMORY;
1232 goto done;
1233 }
1234 Assert(pPage);
1235 }
1236 if (cpu.pCurInstr->opcode == OP_CALL)
1237 rc = csamAnalyseCallCodeStream(pVM, pInstrGC, addr, fCode32, pfnCSAMR3Analyse, (void *)pJmpPage, pCacheRec);
1238 else
1239 rc = csamAnalyseCodeStream(pVM, pInstrGC, addr, fCode32, pfnCSAMR3Analyse, (void *)pJmpPage, pCacheRec);
1240
1241 if (rc != VINF_SUCCESS) {
1242 goto done;
1243 }
1244 }
1245 if (cpu.pCurInstr->opcode == OP_JMP)
1246 {//unconditional jump; return to caller
1247 rc = VINF_SUCCESS;
1248 goto done;
1249 }
1250
1251 rc = VWRN_CONTINUE_ANALYSIS;
1252 } //if ((cpu.pCurInstr->optype & OPTYPE_CONTROLFLOW) && (OP_PARM_VTYPE(cpu.pCurInstr->param1) == OP_PARM_J))
1253#ifdef CSAM_SCAN_JUMP_TABLE
1254 else
1255 if ( cpu.pCurInstr->opcode == OP_JMP
1256 && (cpu.param1.flags & (USE_DISPLACEMENT32|USE_INDEX|USE_SCALE)) == (USE_DISPLACEMENT32|USE_INDEX|USE_SCALE)
1257 )
1258 {
1259 RTGCPTR pJumpTableGC = (RTGCPTR)cpu.param1.disp32;
1260 uint8_t *pJumpTableHC;
1261 int rc2;
1262
1263 Log(("Jump through jump table\n"));
1264
1265 rc2 = PGMPhysGCPtr2HCPtr(pVM, pJumpTableGC, (PRTHCPTR)&pJumpTableHC);
1266 if (rc2 == VINF_SUCCESS)
1267 {
1268 for (uint32_t i=0;i<2;i++)
1269 {
1270 uint64_t fFlags;
1271
1272 addr = pJumpTableGC + cpu.param1.scale * i;
1273 /* Same page? */
1274 if (PAGE_ADDRESS(addr) != PAGE_ADDRESS(pJumpTableGC))
1275 break;
1276
1277 addr = *(RTGCPTR *)(pJumpTableHC + cpu.param1.scale * i);
1278
1279 rc2 = PGMGstGetPage(pVM, addr, &fFlags, NULL);
1280 if ( rc2 != VINF_SUCCESS
1281 || (fFlags & X86_PTE_US)
1282 || !(fFlags & X86_PTE_P)
1283 )
1284 break;
1285
1286 Log(("Jump to %VGv\n", addr));
1287
1288 pJmpPage = NULL;
1289 if (csamIsCodeScanned(pVM, addr, &pJmpPage) == false)
1290 {
1291 if (pJmpPage == NULL)
1292 {
1293 /* New branch target; let's take a look at it. */
1294 pJmpPage = csamCreatePageRecord(pVM, addr, CSAM_TAG_CSAM, fCode32);
1295 if (pJmpPage == NULL)
1296 {
1297 rc = VERR_NO_MEMORY;
1298 goto done;
1299 }
1300 Assert(pPage);
1301 }
1302 rc = csamAnalyseCodeStream(pVM, pInstrGC, addr, fCode32, pfnCSAMR3Analyse, (void *)pJmpPage, pCacheRec);
1303 if (rc != VINF_SUCCESS) {
1304 goto done;
1305 }
1306 }
1307 }
1308 }
1309 }
1310#endif
1311 if (rc != VWRN_CONTINUE_ANALYSIS) {
1312 break; //done!
1313 }
1314next_please:
1315 if (cpu.pCurInstr->opcode == OP_JMP)
1316 {
1317 rc = VINF_SUCCESS;
1318 goto done;
1319 }
1320 pCurInstrGC += opsize;
1321 }
1322done:
1323 pCacheRec->depth--;
1324 return rc;
1325}
1326
1327
1328/**
1329 * Calculates the 64 bits hash value for the current page
1330 *
1331 * @returns hash value
1332 * @param pVM The VM to operate on.
1333 * @param pInstr Page address
1334 */
1335uint64_t csamR3CalcPageHash(PVM pVM, RTGCPTR pInstr)
1336{
1337 uint64_t hash = 0;
1338 uint32_t val[5];
1339 int rc;
1340
1341 Assert((pInstr & PAGE_OFFSET_MASK) == 0);
1342
1343 rc = PGMPhysReadGCPtr(pVM, &val[0], pInstr, sizeof(val[0]));
1344 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Vrc\n", rc));
1345 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1346 {
1347 Log(("csamR3CalcPageHash: page %VGv not present!!\n", pInstr));
1348 return ~0ULL;
1349 }
1350
1351 rc = PGMPhysReadGCPtr(pVM, &val[1], pInstr+1024, sizeof(val[0]));
1352 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Vrc\n", rc));
1353 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1354 {
1355 Log(("csamR3CalcPageHash: page %VGv not present!!\n", pInstr));
1356 return ~0ULL;
1357 }
1358
1359 rc = PGMPhysReadGCPtr(pVM, &val[2], pInstr+2048, sizeof(val[0]));
1360 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Vrc\n", rc));
1361 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1362 {
1363 Log(("csamR3CalcPageHash: page %VGv not present!!\n", pInstr));
1364 return ~0ULL;
1365 }
1366
1367 rc = PGMPhysReadGCPtr(pVM, &val[3], pInstr+3072, sizeof(val[0]));
1368 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Vrc\n", rc));
1369 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1370 {
1371 Log(("csamR3CalcPageHash: page %VGv not present!!\n", pInstr));
1372 return ~0ULL;
1373 }
1374
1375 rc = PGMPhysReadGCPtr(pVM, &val[4], pInstr+4092, sizeof(val[0]));
1376 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Vrc\n", rc));
1377 if (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1378 {
1379 Log(("csamR3CalcPageHash: page %VGv not present!!\n", pInstr));
1380 return ~0ULL;
1381 }
1382
1383 // don't want to get division by zero traps
1384 val[2] |= 1;
1385 val[4] |= 1;
1386
1387 hash = (uint64_t)val[0] * (uint64_t)val[1] / (uint64_t)val[2] + (val[3]%val[4]);
1388 return (hash == ~0ULL) ? hash - 1 : hash;
1389}
1390
1391
1392/**
1393 * Notify CSAM of a page flush
1394 *
1395 * @returns VBox status code
1396 * @param pVM The VM to operate on.
1397 * @param addr GC address of the page to flush
1398 * @param fRemovePage Page removal flag
1399 */
1400static int csamFlushPage(PVM pVM, RTGCPTR addr, bool fRemovePage)
1401{
1402 PCSAMPAGEREC pPageRec;
1403 int rc;
1404 RTGCPHYS GCPhys = 0;
1405 uint64_t fFlags = 0;
1406
1407 if (!CSAMIsEnabled(pVM))
1408 return VINF_SUCCESS;
1409
1410 STAM_PROFILE_START(&pVM->csam.s.StatTimeFlushPage, a);
1411
1412 addr = addr & PAGE_BASE_GC_MASK;
1413
1414 /*
1415 * Note: searching for the page in our tree first is more expensive (skipped flushes are two orders of magnitude more common)
1416 */
1417 if (pVM->csam.s.pPageTree == NULL)
1418 {
1419 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1420 return VWRN_CSAM_PAGE_NOT_FOUND;
1421 }
1422
1423 rc = PGMGstGetPage(pVM, addr, &fFlags, &GCPhys);
1424 /* Returned at a very early stage (no paging yet presumably). */
1425 if (rc == VERR_NOT_SUPPORTED)
1426 {
1427 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1428 return rc;
1429 }
1430
1431 if (VBOX_SUCCESS(rc))
1432 {
1433 if ( (fFlags & X86_PTE_US)
1434 || rc == VERR_PGM_PHYS_PAGE_RESERVED
1435 )
1436 {
1437 /* User page -> not relevant for us. */
1438 STAM_COUNTER_ADD(&pVM->csam.s.StatNrFlushesSkipped, 1);
1439 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1440 return VINF_SUCCESS;
1441 }
1442 }
1443 else
1444 if (rc != VERR_PAGE_NOT_PRESENT && rc != VERR_PAGE_TABLE_NOT_PRESENT)
1445 AssertMsgFailed(("PGMR3GetPage %VGv failed with %Vrc\n", addr, rc));
1446
1447 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)addr);
1448 if (pPageRec)
1449 {
1450 if ( GCPhys == pPageRec->page.GCPhys
1451 && (fFlags & X86_PTE_P))
1452 {
1453 STAM_COUNTER_ADD(&pVM->csam.s.StatNrFlushesSkipped, 1);
1454 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1455 return VINF_SUCCESS;
1456 }
1457
1458 Log(("CSAMR3FlushPage: page %VGv has changed -> FLUSH (rc=%Vrc) (Phys: %VGp vs %VGp)\n", addr, rc, GCPhys, pPageRec->page.GCPhys));
1459
1460 STAM_COUNTER_ADD(&pVM->csam.s.StatNrFlushes, 1);
1461
1462 if (fRemovePage)
1463 csamRemovePageRecord(pVM, addr);
1464 else
1465 {
1466 CSAMMarkPage(pVM, addr, false);
1467 pPageRec->page.GCPhys = 0;
1468 pPageRec->page.fFlags = 0;
1469 rc = PGMGstGetPage(pVM, addr, &pPageRec->page.fFlags, &pPageRec->page.GCPhys);
1470 if (rc == VINF_SUCCESS)
1471 pPageRec->page.u64Hash = csamR3CalcPageHash(pVM, addr);
1472
1473 if (pPageRec->page.pBitmap == NULL)
1474 {
1475 pPageRec->page.pBitmap = (uint8_t *)MMR3HeapAllocZ(pVM, MM_TAG_CSAM_PATCH, CSAM_PAGE_BITMAP_SIZE);
1476 Assert(pPageRec->page.pBitmap);
1477 if (pPageRec->page.pBitmap == NULL)
1478 return VERR_NO_MEMORY;
1479 }
1480 else
1481 memset(pPageRec->page.pBitmap, 0, CSAM_PAGE_BITMAP_SIZE);
1482 }
1483
1484
1485 /*
1486 * Inform patch manager about the flush; no need to repeat the above check twice.
1487 */
1488 PATMR3FlushPage(pVM, addr);
1489
1490 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1491 return VINF_SUCCESS;
1492 }
1493 else
1494 {
1495 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeFlushPage, a);
1496 return VWRN_CSAM_PAGE_NOT_FOUND;
1497 }
1498}
1499
1500/**
1501 * Notify CSAM of a page flush
1502 *
1503 * @returns VBox status code
1504 * @param pVM The VM to operate on.
1505 * @param addr GC address of the page to flush
1506 */
1507CSAMR3DECL(int) CSAMR3FlushPage(PVM pVM, RTGCPTR addr)
1508{
1509 return csamFlushPage(pVM, addr, true /* remove page record */);
1510}
1511
1512/**
1513 * Remove a CSAM monitored page. Use with care!
1514 *
1515 * @returns VBox status code
1516 * @param pVM The VM to operate on.
1517 * @param addr GC address of the page to flush
1518 */
1519CSAMR3DECL(int) CSAMR3RemovePage(PVM pVM, RTGCPTR addr)
1520{
1521 PCSAMPAGEREC pPageRec;
1522 int rc;
1523
1524 addr = addr & PAGE_BASE_GC_MASK;
1525
1526 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)addr);
1527 if (pPageRec)
1528 {
1529 rc = csamRemovePageRecord(pVM, addr);
1530 if (VBOX_SUCCESS(rc))
1531 PATMR3FlushPage(pVM, addr);
1532 return VINF_SUCCESS;
1533 }
1534 return VWRN_CSAM_PAGE_NOT_FOUND;
1535}
1536
1537/**
1538 * Check a page record in case a page has been changed
1539 *
1540 * @returns VBox status code. (trap handled or not)
1541 * @param pVM The VM to operate on.
1542 * @param pInstrGC GC instruction pointer
1543 */
1544int csamR3CheckPageRecord(PVM pVM, RTGCPTR pInstrGC)
1545{
1546 PCSAMPAGEREC pPageRec;
1547 uint64_t u64hash;
1548
1549 pInstrGC = pInstrGC & PAGE_BASE_GC_MASK;
1550
1551 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)pInstrGC);
1552 if (pPageRec)
1553 {
1554 u64hash = csamR3CalcPageHash(pVM, pInstrGC);
1555 if (u64hash != pPageRec->page.u64Hash)
1556 csamFlushPage(pVM, pInstrGC, false /* don't remove page record */);
1557 }
1558 else
1559 return VWRN_CSAM_PAGE_NOT_FOUND;
1560
1561 return VINF_SUCCESS;
1562}
1563
1564/**
1565 * Returns monitor description based on CSAM tag
1566 *
1567 * @return description string
1568 * @param enmTag Owner tag
1569 */
1570const char *csamGetMonitorDescription(CSAMTAG enmTag)
1571{
1572 if (enmTag == CSAM_TAG_PATM)
1573 return "CSAM-PATM self-modifying code monitor handler";
1574 else
1575 if (enmTag == CSAM_TAG_REM)
1576 return "CSAM-REM self-modifying code monitor handler";
1577 Assert(enmTag == CSAM_TAG_CSAM);
1578 return "CSAM self-modifying code monitor handler";
1579}
1580
1581/**
1582 * Adds page record to our lookup tree
1583 *
1584 * @returns CSAMPAGE ptr or NULL if failure
1585 * @param pVM The VM to operate on.
1586 * @param GCPtr Page address
1587 * @param enmTag Owner tag
1588 * @param fCode32 16 or 32 bits code
1589 * @param fMonitorInvalidation Monitor page invalidation flag
1590 */
1591static PCSAMPAGE csamCreatePageRecord(PVM pVM, RTGCPTR GCPtr, CSAMTAG enmTag, bool fCode32, bool fMonitorInvalidation)
1592{
1593 PCSAMPAGEREC pPage;
1594 int rc;
1595 bool ret;
1596
1597 Log(("New page record for %VGv\n", GCPtr & PAGE_BASE_GC_MASK));
1598
1599 pPage = (PCSAMPAGEREC)MMR3HeapAllocZ(pVM, MM_TAG_CSAM_PATCH, sizeof(CSAMPAGEREC));
1600 if (pPage == NULL)
1601 {
1602 AssertMsgFailed(("csamCreatePageRecord: Out of memory!!!!\n"));
1603 return NULL;
1604 }
1605 /* Round down to page boundary. */
1606 GCPtr = (GCPtr & PAGE_BASE_GC_MASK);
1607 pPage->Core.Key = (AVLPVKEY)GCPtr;
1608 pPage->page.pPageGC = GCPtr;
1609 pPage->page.fCode32 = fCode32;
1610 pPage->page.fMonitorInvalidation = fMonitorInvalidation;
1611 pPage->page.enmTag = enmTag;
1612 pPage->page.fMonitorActive = false;
1613 pPage->page.pBitmap = (uint8_t *)MMR3HeapAllocZ(pVM, MM_TAG_CSAM_PATCH, PAGE_SIZE/sizeof(uint8_t));
1614 rc = PGMGstGetPage(pVM, GCPtr, &pPage->page.fFlags, &pPage->page.GCPhys);
1615 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Vrc\n", rc));
1616
1617 pPage->page.u64Hash = csamR3CalcPageHash(pVM, GCPtr);
1618 ret = RTAvlPVInsert(&pVM->csam.s.pPageTree, &pPage->Core);
1619 Assert(ret);
1620
1621#ifdef CSAM_MONITOR_CODE_PAGES
1622 AssertRelease(!fInCSAMCodePageInvalidate);
1623
1624 switch (enmTag)
1625 {
1626 case CSAM_TAG_PATM:
1627 case CSAM_TAG_REM:
1628#ifdef CSAM_MONITOR_CSAM_CODE_PAGES
1629 case CSAM_TAG_CSAM:
1630#endif
1631 {
1632 int rc = PGMR3HandlerVirtualRegister(pVM, PGMVIRTHANDLERTYPE_WRITE, GCPtr, GCPtr + (PAGE_SIZE - 1) /* inclusive! */,
1633 (fMonitorInvalidation) ? CSAMCodePageInvalidate : 0, CSAMCodePageWriteHandler, "CSAMGCCodePageWriteHandler", 0,
1634 csamGetMonitorDescription(enmTag));
1635 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PGM_HANDLER_VIRTUAL_CONFLICT, ("PGMR3HandlerVirtualRegisterEx %VGv failed with %Vrc\n", GCPtr, rc));
1636 if (VBOX_FAILURE(rc))
1637 Log(("PGMR3HandlerVirtualRegisterEx for %VGv failed with %Vrc\n", GCPtr, rc));
1638
1639 /* Could fail, because it's already monitored. Don't treat that condition as fatal. */
1640
1641 /* Prefetch it in case it's not there yet. */
1642 rc = PGMPrefetchPage(pVM, GCPtr);
1643 AssertRC(rc);
1644
1645 rc = PGMShwModifyPage(pVM, GCPtr, 1, 0, ~(uint64_t)X86_PTE_RW);
1646 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1647
1648 pPage->page.fMonitorActive = true;
1649 STAM_COUNTER_INC(&pVM->csam.s.StatPageMonitor);
1650 break;
1651 }
1652 default:
1653 break; /* to shut up GCC */
1654 }
1655
1656 Log(("csamCreatePageRecord %VGv HCPhys=%VGp\n", GCPtr, pPage->page.GCPhys));
1657
1658#ifdef VBOX_WITH_STATISTICS
1659 switch (enmTag)
1660 {
1661 case CSAM_TAG_CSAM:
1662 STAM_COUNTER_INC(&pVM->csam.s.StatPageCSAM);
1663 break;
1664 case CSAM_TAG_PATM:
1665 STAM_COUNTER_INC(&pVM->csam.s.StatPagePATM);
1666 break;
1667 case CSAM_TAG_REM:
1668 STAM_COUNTER_INC(&pVM->csam.s.StatPageREM);
1669 break;
1670 default:
1671 break; /* to shut up GCC */
1672 }
1673#endif
1674
1675#endif
1676
1677 STAM_COUNTER_INC(&pVM->csam.s.StatNrPages);
1678 if (fMonitorInvalidation)
1679 STAM_COUNTER_INC(&pVM->csam.s.StatNrPagesInv);
1680
1681 return &pPage->page;
1682}
1683
1684/**
1685 * Monitors a code page (if not already monitored)
1686 *
1687 * @returns VBox status code
1688 * @param pVM The VM to operate on.
1689 * @param pPageAddrGC The page to monitor
1690 * @param enmTag Monitor tag
1691 */
1692CSAMR3DECL(int) CSAMR3MonitorPage(PVM pVM, RTGCPTR pPageAddrGC, CSAMTAG enmTag)
1693{
1694 PCSAMPAGEREC pPageRec = NULL;
1695 int rc;
1696 bool fMonitorInvalidation;
1697
1698 /* Dirty pages must be handled before calling this function!. */
1699 Assert(!pVM->csam.s.cDirtyPages);
1700
1701 if (pVM->csam.s.fScanningStarted == false)
1702 return VINF_SUCCESS; /* too early */
1703
1704 pPageAddrGC &= PAGE_BASE_GC_MASK;
1705
1706 Log(("CSAMR3MonitorPage %VGv %d\n", pPageAddrGC, enmTag));
1707
1708 /** @todo implicit assumption */
1709 fMonitorInvalidation = (enmTag == CSAM_TAG_PATM);
1710
1711 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)pPageAddrGC);
1712 if (pPageRec == NULL)
1713 {
1714 uint64_t fFlags;
1715
1716 rc = PGMGstGetPage(pVM, pPageAddrGC, &fFlags, NULL);
1717 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Vrc\n", rc));
1718 if ( rc == VINF_SUCCESS
1719 && (fFlags & X86_PTE_US))
1720 {
1721 /* We don't care about user pages. */
1722 STAM_COUNTER_INC(&pVM->csam.s.StatNrUserPages);
1723 return VINF_SUCCESS;
1724 }
1725
1726 csamCreatePageRecord(pVM, pPageAddrGC, enmTag, true /* 32 bits code */, fMonitorInvalidation);
1727
1728 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)pPageAddrGC);
1729 Assert(pPageRec);
1730 }
1731 /** @todo reference count */
1732
1733#ifdef CSAM_MONITOR_CSAM_CODE_PAGES
1734 Assert(pPageRec->page.fMonitorActive);
1735#endif
1736
1737#ifdef CSAM_MONITOR_CODE_PAGES
1738 if (!pPageRec->page.fMonitorActive)
1739 {
1740 Log(("CSAMR3MonitorPage: activate monitoring for %VGv\n", pPageAddrGC));
1741
1742 rc = PGMR3HandlerVirtualRegister(pVM, PGMVIRTHANDLERTYPE_WRITE, pPageAddrGC, pPageAddrGC + (PAGE_SIZE - 1) /* inclusive! */,
1743 (fMonitorInvalidation) ? CSAMCodePageInvalidate : 0, CSAMCodePageWriteHandler, "CSAMGCCodePageWriteHandler", 0,
1744 csamGetMonitorDescription(enmTag));
1745 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PGM_HANDLER_VIRTUAL_CONFLICT, ("PGMR3HandlerVirtualRegisterEx %VGv failed with %Vrc\n", pPageAddrGC, rc));
1746 if (VBOX_FAILURE(rc))
1747 Log(("PGMR3HandlerVirtualRegisterEx for %VGv failed with %Vrc\n", pPageAddrGC, rc));
1748
1749 /* Could fail, because it's already monitored. Don't treat that condition as fatal. */
1750
1751 /* Prefetch it in case it's not there yet. */
1752 rc = PGMPrefetchPage(pVM, pPageAddrGC);
1753 AssertRC(rc);
1754
1755 rc = PGMShwModifyPage(pVM, pPageAddrGC, 1, 0, ~(uint64_t)X86_PTE_RW);
1756 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1757
1758 STAM_COUNTER_INC(&pVM->csam.s.StatPageMonitor);
1759
1760 pPageRec->page.fMonitorActive = true;
1761 pPageRec->page.fMonitorInvalidation = fMonitorInvalidation;
1762 }
1763 else
1764 if ( !pPageRec->page.fMonitorInvalidation
1765 && fMonitorInvalidation)
1766 {
1767 Assert(pPageRec->page.fMonitorActive);
1768 PGMHandlerVirtualChangeInvalidateCallback(pVM, pPageRec->page.pPageGC, CSAMCodePageInvalidate);
1769 pPageRec->page.fMonitorInvalidation = true;
1770 STAM_COUNTER_INC(&pVM->csam.s.StatNrPagesInv);
1771
1772 /* Prefetch it in case it's not there yet. */
1773 rc = PGMPrefetchPage(pVM, pPageAddrGC);
1774 AssertRC(rc);
1775
1776 /* Make sure it's readonly. Page invalidation may have modified the attributes. */
1777 rc = PGMShwModifyPage(pVM, pPageAddrGC, 1, 0, ~(uint64_t)X86_PTE_RW);
1778 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1779 }
1780
1781#if 0 /* def VBOX_STRICT -> very annoying) */
1782 if (pPageRec->page.fMonitorActive)
1783 {
1784 uint64_t fPageShw;
1785 RTHCPHYS GCPhys;
1786 rc = PGMShwGetPage(pVM, pPageAddrGC, &fPageShw, &GCPhys);
1787// AssertMsg( (rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT)
1788// || !(fPageShw & X86_PTE_RW)
1789// || (pPageRec->page.GCPhys == 0), ("Shadow page flags for %VGv (%VHp) aren't readonly (%VX64)!!\n", pPageAddrGC, GCPhys, fPageShw));
1790 }
1791#endif
1792
1793 if (pPageRec->page.GCPhys == 0)
1794 {
1795 /* Prefetch it in case it's not there yet. */
1796 rc = PGMPrefetchPage(pVM, pPageAddrGC);
1797 AssertRC(rc);
1798 /* The page was changed behind our back. It won't be made read-only until the next SyncCR3, so force it here. */
1799 rc = PGMShwModifyPage(pVM, pPageAddrGC, 1, 0, ~(uint64_t)X86_PTE_RW);
1800 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
1801 }
1802#endif /* CSAM_MONITOR_CODE_PAGES */
1803 return VINF_SUCCESS;
1804}
1805
1806/**
1807 * Removes a page record from our lookup tree
1808 *
1809 * @returns VBox status code
1810 * @param pVM The VM to operate on.
1811 * @param GCPtr Page address
1812 */
1813static int csamRemovePageRecord(PVM pVM, RTGCPTR GCPtr)
1814{
1815 PCSAMPAGEREC pPageRec;
1816
1817 Log(("csamRemovePageRecord %VGv\n", GCPtr));
1818 pPageRec = (PCSAMPAGEREC)RTAvlPVRemove(&pVM->csam.s.pPageTree, (AVLPVKEY)GCPtr);
1819
1820 if (pPageRec)
1821 {
1822 STAM_COUNTER_INC(&pVM->csam.s.StatNrRemovedPages);
1823
1824#ifdef CSAM_MONITOR_CODE_PAGES
1825 if (pPageRec->page.fMonitorActive)
1826 {
1827 /* @todo -> this is expensive (cr3 reload)!!!
1828 * if this happens often, then reuse it instead!!!
1829 */
1830 Assert(!fInCSAMCodePageInvalidate);
1831 STAM_COUNTER_DEC(&pVM->csam.s.StatPageMonitor);
1832 PGMHandlerVirtualDeregister(pVM, GCPtr);
1833 }
1834 if (pPageRec->page.enmTag == CSAM_TAG_PATM)
1835 {
1836 /* Make sure the recompiler flushes its cache as this page is no longer monitored. */
1837 STAM_COUNTER_INC(&pVM->csam.s.StatPageRemoveREMFlush);
1838 CPUMSetChangedFlags(pVM, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
1839 }
1840#endif
1841
1842#ifdef VBOX_WITH_STATISTICS
1843 switch (pPageRec->page.enmTag)
1844 {
1845 case CSAM_TAG_CSAM:
1846 STAM_COUNTER_DEC(&pVM->csam.s.StatPageCSAM);
1847 break;
1848 case CSAM_TAG_PATM:
1849 STAM_COUNTER_DEC(&pVM->csam.s.StatPagePATM);
1850 break;
1851 case CSAM_TAG_REM:
1852 STAM_COUNTER_DEC(&pVM->csam.s.StatPageREM);
1853 break;
1854 default:
1855 break; /* to shut up GCC */
1856 }
1857#endif
1858
1859 if (pPageRec->page.pBitmap) MMR3HeapFree(pPageRec->page.pBitmap);
1860 MMR3HeapFree(pPageRec);
1861 }
1862 else
1863 AssertFailed();
1864
1865 return VINF_SUCCESS;
1866}
1867
1868/**
1869 * Callback for delayed writes from non-EMT threads
1870 *
1871 * @param pVM VM Handle.
1872 * @param GCPtr The virtual address the guest is writing to. (not correct if it's an alias!)
1873 * @param cbBuf How much it's reading/writing.
1874 */
1875static DECLCALLBACK(void) CSAMDelayedWriteHandler(PVM pVM, RTGCPTR GCPtr, size_t cbBuf)
1876{
1877 int rc = PATMR3PatchWrite(pVM, GCPtr, cbBuf);
1878 AssertRC(rc);
1879}
1880
1881/**
1882 * #PF Handler callback for virtual access handler ranges.
1883 *
1884 * Important to realize that a physical page in a range can have aliases, and
1885 * for ALL and WRITE handlers these will also trigger.
1886 *
1887 * @returns VINF_SUCCESS if the handler have carried out the operation.
1888 * @returns VINF_PGM_HANDLER_DO_DEFAULT if the caller should carry out the access operation.
1889 * @param pVM VM Handle.
1890 * @param GCPtr The virtual address the guest is writing to. (not correct if it's an alias!)
1891 * @param pvPtr The HC mapping of that address.
1892 * @param pvBuf What the guest is reading/writing.
1893 * @param cbBuf How much it's reading/writing.
1894 * @param enmAccessType The access type.
1895 * @param pvUser User argument.
1896 */
1897static DECLCALLBACK(int) CSAMCodePageWriteHandler(PVM pVM, RTGCPTR GCPtr, void *pvPtr, void *pvBuf, size_t cbBuf, PGMACCESSTYPE enmAccessType, void *pvUser)
1898{
1899 int rc;
1900
1901 Assert(enmAccessType == PGMACCESSTYPE_WRITE);
1902 Log(("CSAMCodePageWriteHandler: write to %VGv size=%d\n", GCPtr, cbBuf));
1903
1904 if (VM_IS_EMT(pVM))
1905 {
1906 rc = PATMR3PatchWrite(pVM, GCPtr, cbBuf);
1907 }
1908 else
1909 {
1910 /* Queue the write instead otherwise we'll get concurrency issues. */
1911 /** @note in theory not correct to let it write the data first before disabling a patch!
1912 * (if it writes the same data as the patch jump and we replace it with obsolete opcodes)
1913 */
1914 Log(("CSAMCodePageWriteHandler: delayed write!\n"));
1915 rc = VMR3ReqCallEx(pVM, NULL, 0, VMREQFLAGS_NO_WAIT | VMREQFLAGS_VOID,
1916 (PFNRT)CSAMDelayedWriteHandler, 3, pVM, GCPtr, cbBuf);
1917 }
1918 AssertRC(rc);
1919
1920 return VINF_PGM_HANDLER_DO_DEFAULT;
1921}
1922
1923/**
1924 * #PF Handler callback for invalidation of virtual access handler ranges.
1925 *
1926 * @param pVM VM Handle.
1927 * @param GCPtr The virtual address the guest has changed.
1928 */
1929static DECLCALLBACK(int) CSAMCodePageInvalidate(PVM pVM, RTGCPTR GCPtr)
1930{
1931 fInCSAMCodePageInvalidate = true;
1932 LogFlow(("CSAMCodePageInvalidate %VGv\n", GCPtr));
1933 /** @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. */
1934 csamFlushPage(pVM, GCPtr, false /* don't remove page! */);
1935 fInCSAMCodePageInvalidate = false;
1936 return VINF_SUCCESS;
1937}
1938
1939/**
1940 * Check if the current instruction has already been checked before
1941 *
1942 * @returns VBox status code. (trap handled or not)
1943 * @param pVM The VM to operate on.
1944 * @param pInstr Instruction pointer
1945 * @param pPage CSAM patch structure pointer
1946 */
1947bool csamIsCodeScanned(PVM pVM, RTGCPTR pInstr, PCSAMPAGE *pPage)
1948{
1949 PCSAMPAGEREC pPageRec;
1950 uint32_t offset;
1951
1952 STAM_PROFILE_START(&pVM->csam.s.StatTimeCheckAddr, a);
1953
1954 offset = pInstr & PAGE_OFFSET_MASK;
1955 pInstr = pInstr & PAGE_BASE_GC_MASK;
1956
1957 Assert(pPage);
1958
1959 if (*pPage && (*pPage)->pPageGC == pInstr)
1960 {
1961 if ((*pPage)->pBitmap == NULL || ASMBitTest((*pPage)->pBitmap, offset))
1962 {
1963 STAM_COUNTER_ADD(&pVM->csam.s.StatNrKnownPagesHC, 1);
1964 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
1965 return true;
1966 }
1967 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
1968 return false;
1969 }
1970
1971 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)pInstr);
1972 if (pPageRec)
1973 {
1974 if (pPage) *pPage= &pPageRec->page;
1975 if (pPageRec->page.pBitmap == NULL || ASMBitTest(pPageRec->page.pBitmap, offset))
1976 {
1977 STAM_COUNTER_ADD(&pVM->csam.s.StatNrKnownPagesHC, 1);
1978 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
1979 return true;
1980 }
1981 }
1982 else
1983 {
1984 if (pPage) *pPage = NULL;
1985 }
1986 STAM_PROFILE_STOP(&pVM->csam.s.StatTimeCheckAddr, a);
1987 return false;
1988}
1989
1990/**
1991 * Mark an instruction in a page as scanned/not scanned
1992 *
1993 * @param pVM The VM to operate on.
1994 * @param pPage Patch structure pointer
1995 * @param pInstr Instruction pointer
1996 * @param opsize Instruction size
1997 * @param fScanned Mark as scanned or not
1998 */
1999static void csamMarkCode(PVM pVM, PCSAMPAGE pPage, RTGCPTR pInstr, uint32_t opsize, bool fScanned)
2000{
2001 LogFlow(("csamMarkCodeAsScanned %VGv opsize=%d\n", pInstr, opsize));
2002 CSAMMarkPage(pVM, pInstr, fScanned);
2003
2004 /** @todo should recreate empty bitmap if !fScanned */
2005 if (pPage->pBitmap == NULL)
2006 return;
2007
2008 if (fScanned)
2009 {
2010 // retn instructions can be scanned more than once
2011 if (ASMBitTest(pPage->pBitmap, pInstr & PAGE_OFFSET_MASK) == 0)
2012 {
2013 pPage->uSize += opsize;
2014 STAM_COUNTER_ADD(&pVM->csam.s.StatNrInstr, 1);
2015 }
2016 if (pPage->uSize >= PAGE_SIZE)
2017 {
2018 Log(("Scanned full page (%VGv) -> free bitmap\n", pInstr & PAGE_BASE_GC_MASK));
2019 MMR3HeapFree(pPage->pBitmap);
2020 pPage->pBitmap = NULL;
2021 }
2022 else
2023 ASMBitSet(pPage->pBitmap, pInstr & PAGE_OFFSET_MASK);
2024 }
2025 else
2026 ASMBitClear(pPage->pBitmap, pInstr & PAGE_OFFSET_MASK);
2027}
2028
2029/**
2030 * Mark an instruction in a page as scanned/not scanned
2031 *
2032 * @returns VBox status code.
2033 * @param pVM The VM to operate on.
2034 * @param pInstr Instruction pointer
2035 * @param opsize Instruction size
2036 * @param fScanned Mark as scanned or not
2037 */
2038CSAMR3DECL(int) CSAMR3MarkCode(PVM pVM, RTGCPTR pInstr, uint32_t opsize, bool fScanned)
2039{
2040 PCSAMPAGE pPage = 0;
2041
2042 Assert(!fScanned); /* other case not implemented. */
2043 Assert(!PATMIsPatchGCAddr(pVM, pInstr));
2044
2045 if (csamIsCodeScanned(pVM, pInstr, &pPage) == false)
2046 {
2047 Assert(fScanned == true); /* other case should not be possible */
2048 return VINF_SUCCESS;
2049 }
2050
2051 Log(("CSAMR3MarkCode: %VGv size=%d fScanned=%d\n", pInstr, opsize, fScanned));
2052 csamMarkCode(pVM, pPage, pInstr, opsize, fScanned);
2053 return VINF_SUCCESS;
2054}
2055
2056
2057/**
2058 * Scan and analyse code
2059 *
2060 * @returns VBox status code.
2061 * @param pVM The VM to operate on.
2062 * @param Sel selector
2063 * @param pHiddenSel The hidden selector register.
2064 * @param pInstrGC Instruction pointer
2065 */
2066CSAMR3DECL(int) CSAMR3CheckCodeEx(PVM pVM, RTSEL Sel, CPUMSELREGHID *pHiddenSel, RTGCPTR pInstrGC)
2067{
2068 if (EMIsRawRing0Enabled(pVM) == false || PATMIsPatchGCAddr(pVM, pInstrGC) == true)
2069 {
2070 // No use
2071 return VINF_SUCCESS;
2072 }
2073
2074 if (CSAMIsEnabled(pVM))
2075 {
2076 X86EFLAGS fakeflags;
2077
2078 /* we're not in v86 mode here */
2079 fakeflags.u32 = 0;
2080
2081 bool fCode32 = SELMIsSelector32Bit(pVM, fakeflags, Sel, pHiddenSel);
2082
2083 //assuming 32 bits code for now
2084 Assert(fCode32); NOREF(fCode32);
2085
2086 pInstrGC = SELMToFlat(pVM, fakeflags, Sel, pHiddenSel, pInstrGC);
2087
2088 return CSAMR3CheckCode(pVM, pInstrGC);
2089 }
2090 return VINF_SUCCESS;
2091}
2092
2093/**
2094 * Scan and analyse code
2095 *
2096 * @returns VBox status code.
2097 * @param pVM The VM to operate on.
2098 * @param pInstrGC Instruction pointer (0:32 virtual address)
2099 */
2100CSAMR3DECL(int) CSAMR3CheckCode(PVM pVM, RTGCPTR pInstrGC)
2101{
2102 int rc;
2103 PCSAMPAGE pPage = NULL;
2104
2105 if (EMIsRawRing0Enabled(pVM) == false || PATMIsPatchGCAddr(pVM, pInstrGC) == true)
2106 {
2107 // No use
2108 return VINF_SUCCESS;
2109 }
2110
2111 if (CSAMIsEnabled(pVM))
2112 {
2113 // Cache record for PATMGCVirtToHCVirt
2114 CSAMP2GLOOKUPREC cacheRec = {0};
2115
2116 STAM_PROFILE_START(&pVM->csam.s.StatTime, a);
2117 rc = csamAnalyseCallCodeStream(pVM, pInstrGC, pInstrGC, true /* 32 bits code */, CSAMR3AnalyseCallback, pPage, &cacheRec);
2118 STAM_PROFILE_STOP(&pVM->csam.s.StatTime, a);
2119 if (rc != VINF_SUCCESS)
2120 {
2121 Log(("csamAnalyseCodeStream failed with %d\n", rc));
2122 return rc;
2123 }
2124 }
2125 return VINF_SUCCESS;
2126}
2127
2128/**
2129 * Flush dirty code pages
2130 *
2131 * @returns VBox status code.
2132 * @param pVM The VM to operate on.
2133 */
2134static int csamR3FlushDirtyPages(PVM pVM)
2135{
2136 STAM_PROFILE_START(&pVM->csam.s.StatFlushDirtyPages, a);
2137
2138 for (uint32_t i=0;i<pVM->csam.s.cDirtyPages;i++)
2139 {
2140 int rc;
2141 PCSAMPAGEREC pPageRec;
2142 RTGCPTR GCPtr = pVM->csam.s.pvDirtyBasePage[i];
2143
2144 GCPtr = GCPtr & PAGE_BASE_GC_MASK;
2145
2146 /* Notify the recompiler that this page has been changed. */
2147 REMR3NotifyCodePageChanged(pVM, GCPtr);
2148
2149 /* Enable write protection again. (use the fault address as it might be an alias) */
2150 rc = PGMShwModifyPage(pVM, pVM->csam.s.pvDirtyFaultPage[i], 1, 0, ~(uint64_t)X86_PTE_RW);
2151 Assert(rc == VINF_SUCCESS || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT);
2152
2153 Log(("CSAMR3FlushDirtyPages: flush %VGv (modifypage rc=%Vrc)\n", pVM->csam.s.pvDirtyBasePage[i], rc));
2154
2155 pPageRec = (PCSAMPAGEREC)RTAvlPVGet(&pVM->csam.s.pPageTree, (AVLPVKEY)GCPtr);
2156 if (pPageRec && pPageRec->page.enmTag == CSAM_TAG_REM)
2157 {
2158 uint64_t fFlags;
2159
2160 rc = PGMGstGetPage(pVM, GCPtr, &fFlags, NULL);
2161 AssertMsg(VBOX_SUCCESS(rc) || rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc = %Vrc\n", rc));
2162 if ( rc == VINF_SUCCESS
2163 && (fFlags & X86_PTE_US))
2164 {
2165 /* We don't care about user pages. */
2166 csamRemovePageRecord(pVM, GCPtr);
2167 STAM_COUNTER_INC(&pVM->csam.s.StatNrUserPages);
2168 }
2169 }
2170 }
2171 pVM->csam.s.cDirtyPages = 0;
2172 STAM_PROFILE_STOP(&pVM->csam.s.StatFlushDirtyPages, a);
2173 return VINF_SUCCESS;
2174}
2175
2176/**
2177 * Flush potential new code pages
2178 *
2179 * @returns VBox status code.
2180 * @param pVM The VM to operate on.
2181 */
2182static int csamR3FlushCodePages(PVM pVM)
2183{
2184 for (uint32_t i=0;i<pVM->csam.s.cPossibleCodePages;i++)
2185 {
2186 RTGCPTR GCPtr = pVM->csam.s.pvPossibleCodePage[i];
2187
2188 GCPtr = GCPtr & PAGE_BASE_GC_MASK;
2189
2190 Log(("csamR3FlushCodePages: %VGv\n", GCPtr));
2191 PGMShwSetPage(pVM, GCPtr, 1, 0);
2192 /* Resync the page to make sure instruction fetch will fault */
2193 CSAMMarkPage(pVM, GCPtr, false);
2194 }
2195 pVM->csam.s.cPossibleCodePages = 0;
2196 return VINF_SUCCESS;
2197}
2198
2199/**
2200 * Perform any pending actions
2201 *
2202 * @returns VBox status code.
2203 * @param pVM The VM to operate on.
2204 */
2205CSAMR3DECL(int) CSAMR3DoPendingAction(PVM pVM)
2206{
2207 csamR3FlushDirtyPages(pVM);
2208 csamR3FlushCodePages(pVM);
2209
2210 VM_FF_CLEAR(pVM, VM_FF_CSAM_PENDING_ACTION);
2211 return VINF_SUCCESS;
2212}
2213
2214/**
2215 * Analyse interrupt and trap gates
2216 *
2217 * @returns VBox status code.
2218 * @param pVM The VM to operate on.
2219 * @param iGate Start gate
2220 * @param cGates Number of gates to check
2221 */
2222CSAMR3DECL(int) CSAMR3CheckGates(PVM pVM, uint32_t iGate, uint32_t cGates)
2223{
2224 uint16_t cbIDT;
2225 RTGCPTR GCPtrIDT = CPUMGetGuestIDTR(pVM, &cbIDT);
2226 uint32_t iGateEnd;
2227 uint32_t maxGates;
2228 VBOXIDTE aIDT[256];
2229 PVBOXIDTE pGuestIdte;
2230 int rc;
2231
2232 if (EMIsRawRing0Enabled(pVM) == false)
2233 {
2234 /* Enabling interrupt gates only works when raw ring 0 is enabled. */
2235 //AssertFailed();
2236 return VINF_SUCCESS;
2237 }
2238
2239 /* We only check all gates once during a session */
2240 if ( !pVM->csam.s.fGatesChecked
2241 && cGates != 256)
2242 return VINF_SUCCESS; /* too early */
2243
2244 /* We only check all gates once during a session */
2245 if ( pVM->csam.s.fGatesChecked
2246 && cGates != 1)
2247 return VINF_SUCCESS; /* ignored */
2248
2249 Assert(cGates <= 256);
2250 if (!GCPtrIDT || cGates > 256)
2251 return VERR_INVALID_PARAMETER;
2252
2253 if (cGates != 1)
2254 pVM->csam.s.fGatesChecked = true;
2255
2256 /* Determine valid upper boundary. */
2257 maxGates = (cbIDT+1) / sizeof(VBOXIDTE);
2258 Assert(iGate < maxGates);
2259 if (iGate > maxGates)
2260 return VERR_INVALID_PARAMETER;
2261
2262 if (iGate + cGates > maxGates)
2263 cGates = maxGates - iGate;
2264
2265 GCPtrIDT = GCPtrIDT + iGate * sizeof(VBOXIDTE);
2266 iGateEnd = iGate + cGates;
2267
2268 STAM_PROFILE_START(&pVM->csam.s.StatCheckGates, a);
2269
2270 /*
2271 * Get IDT entries.
2272 */
2273 if (PAGE_ADDRESS(GCPtrIDT) == PAGE_ADDRESS(GCPtrIDT+cGates*sizeof(VBOXIDTE)))
2274 {
2275 /* Just convert the IDT address to a HC pointer. The whole IDT fits in one page. */
2276 rc = PGMPhysGCPtr2HCPtr(pVM, GCPtrIDT, (PRTHCPTR)&pGuestIdte);
2277 if (VBOX_FAILURE(rc))
2278 {
2279 AssertMsgRC(rc, ("Failed to read IDTE! rc=%Vrc\n", rc));
2280 STAM_PROFILE_STOP(&pVM->csam.s.StatCheckGates, a);
2281 return rc;
2282 }
2283 }
2284 else
2285 {
2286 /* Slow method when it crosses a page boundary. */
2287 rc = PGMPhysReadGCPtr(pVM, aIDT, GCPtrIDT, cGates*sizeof(VBOXIDTE));
2288 if (VBOX_FAILURE(rc))
2289 {
2290 AssertMsgRC(rc, ("Failed to read IDTE! rc=%Vrc\n", rc));
2291 STAM_PROFILE_STOP(&pVM->csam.s.StatCheckGates, a);
2292 return rc;
2293 }
2294 pGuestIdte = &aIDT[0];
2295 }
2296
2297 for (/*iGate*/; iGate<iGateEnd; iGate++, pGuestIdte++)
2298 {
2299 Assert(TRPMR3GetGuestTrapHandler(pVM, iGate) == TRPM_INVALID_HANDLER);
2300
2301 if ( pGuestIdte->Gen.u1Present
2302 && (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32 || pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_INT_32)
2303 && (pGuestIdte->Gen.u2DPL == 3 || pGuestIdte->Gen.u2DPL == 0)
2304 )
2305 {
2306 RTGCPTR pHandler;
2307 CSAMP2GLOOKUPREC cacheRec = {0}; /* Cache record for PATMGCVirtToHCVirt. */
2308 PCSAMPAGE pPage = NULL;
2309 X86EFLAGS fakeflags;
2310 SELMSELINFO selInfo;
2311
2312 /* we're not in v86 mode here */
2313 fakeflags.u32 = 0;
2314
2315 pHandler = (pGuestIdte->Gen.u16OffsetHigh << 16) | pGuestIdte->Gen.u16OffsetLow;
2316 pHandler = SELMToFlat(pVM, fakeflags, pGuestIdte->Gen.u16SegSel, 0, pHandler);
2317
2318 rc = SELMR3GetSelectorInfo(pVM, pGuestIdte->Gen.u16SegSel, &selInfo);
2319 if ( VBOX_FAILURE(rc)
2320 || selInfo.GCPtrBase != 0
2321 || selInfo.cbLimit != ~0U
2322 )
2323 {
2324 /* Refuse to patch a handler whose idt cs selector isn't wide open. */
2325 Log(("CSAMCheckGates: check gate %d failed due to rc %Vrc GCPtrBase=%VGv limit=%x\n", iGate, rc, selInfo.GCPtrBase, selInfo.cbLimit));
2326 continue;
2327 }
2328
2329
2330 if (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32)
2331 {
2332 Log(("CSAMCheckGates: check trap gate %d at %04X:%08X (flat %VGv)\n", iGate, pGuestIdte->Gen.u16SegSel, (pGuestIdte->Gen.u16OffsetHigh << 16) | pGuestIdte->Gen.u16OffsetLow, pHandler));
2333 }
2334 else
2335 {
2336 Log(("CSAMCheckGates: check interrupt gate %d at %04X:%08X (flat %VGv)\n", iGate, pGuestIdte->Gen.u16SegSel, (pGuestIdte->Gen.u16OffsetHigh << 16) | pGuestIdte->Gen.u16OffsetLow, pHandler));
2337 }
2338
2339 STAM_PROFILE_START(&pVM->csam.s.StatTime, a);
2340 rc = csamAnalyseCodeStream(pVM, pHandler, pHandler, true, CSAMR3AnalyseCallback, pPage, &cacheRec);
2341 STAM_PROFILE_STOP(&pVM->csam.s.StatTime, a);
2342 if (rc != VINF_SUCCESS)
2343 {
2344 Log(("CSAMCheckGates: csamAnalyseCodeStream failed with %d\n", rc));
2345 continue;
2346 }
2347 /* OpenBSD guest specific patch test. */
2348 if (iGate >= 0x20)
2349 {
2350 PCPUMCTX pCtx;
2351 DISCPUSTATE cpu;
2352 RTGCUINTPTR aOpenBsdPushCSOffset[3] = {0x03, /* OpenBSD 3.7 & 3.8 */
2353 0x2B, /* OpenBSD 4.0 installation ISO */
2354 0x2F}; /* OpenBSD 4.0 after install */
2355
2356 rc = CPUMQueryGuestCtxPtr(pVM, &pCtx);
2357 AssertRC(rc); /* can't fail */
2358
2359 for (unsigned i=0;i<ELEMENTS(aOpenBsdPushCSOffset);i++)
2360 {
2361 rc = CPUMR3DisasmInstrCPU(pVM, pCtx, pHandler - aOpenBsdPushCSOffset[i], &cpu, NULL);
2362 if ( rc == VINF_SUCCESS
2363 && cpu.pCurInstr->opcode == OP_PUSH
2364 && cpu.pCurInstr->param1 == OP_PARM_REG_CS)
2365 {
2366 rc = PATMR3InstallPatch(pVM, pHandler - aOpenBsdPushCSOffset[i], PATMFL_CODE32 | PATMFL_GUEST_SPECIFIC);
2367 if (VBOX_SUCCESS(rc))
2368 Log(("Installed OpenBSD interrupt handler prefix instruction (push cs) patch\n"));
2369 }
2370 }
2371 }
2372
2373 /* Trap gates and certain interrupt gates. */
2374 uint32_t fPatchFlags = PATMFL_CODE32 | PATMFL_IDTHANDLER;
2375
2376 if (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32)
2377 fPatchFlags |= PATMFL_TRAPHANDLER;
2378 else
2379 fPatchFlags |= PATMFL_INTHANDLER;
2380
2381 switch (iGate) {
2382 case 8:
2383 case 10:
2384 case 11:
2385 case 12:
2386 case 13:
2387 case 14:
2388 case 17:
2389 fPatchFlags |= PATMFL_TRAPHANDLER_WITH_ERRORCODE;
2390 break;
2391 default:
2392 /* No error code. */
2393 break;
2394 }
2395
2396 Log(("Installing %s gate handler for 0x%X at %VGv\n", (pGuestIdte->Gen.u5Type2 == VBOX_IDTE_TYPE2_TRAP_32) ? "trap" : "intr", iGate, pHandler));
2397
2398 rc = PATMR3InstallPatch(pVM, pHandler, fPatchFlags);
2399 if (VBOX_SUCCESS(rc) || rc == VERR_PATM_ALREADY_PATCHED)
2400 {
2401 Log(("Gate handler 0x%X is SAFE!\n", iGate));
2402
2403 RTGCPTR pNewHandlerGC = PATMR3QueryPatchGCPtr(pVM, pHandler);
2404 if (pNewHandlerGC)
2405 {
2406 rc = TRPMR3SetGuestTrapHandler(pVM, iGate, pNewHandlerGC);
2407 if (VBOX_FAILURE(rc))
2408 Log(("TRPMR3SetGuestTrapHandler %d failed with %Vrc\n", iGate, rc));
2409 }
2410 }
2411 }
2412 } /* for */
2413 STAM_PROFILE_STOP(&pVM->csam.s.StatCheckGates, a);
2414 return VINF_SUCCESS;
2415}
2416
2417/**
2418 * Query CSAM state (enabled/disabled)
2419 *
2420 * @returns 0 - disabled, 1 - enabled
2421 * @param pVM The VM to operate on.
2422 */
2423CSAMR3DECL(int) CSAMR3IsEnabled(PVM pVM)
2424{
2425 return pVM->fCSAMEnabled;
2426}
2427
2428#ifdef VBOX_WITH_DEBUGGER
2429/**
2430 * The '.csamoff' command.
2431 *
2432 * @returns VBox status.
2433 * @param pCmd Pointer to the command descriptor (as registered).
2434 * @param pCmdHlp Pointer to command helper functions.
2435 * @param pVM Pointer to the current VM (if any).
2436 * @param paArgs Pointer to (readonly) array of arguments.
2437 * @param cArgs Number of arguments in the array.
2438 */
2439static DECLCALLBACK(int) csamr3CmdOff(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PVM pVM, PCDBGCVAR paArgs, unsigned cArgs, PDBGCVAR pResult)
2440{
2441 /*
2442 * Validate input.
2443 */
2444 if (!pVM)
2445 return pCmdHlp->pfnPrintf(pCmdHlp, NULL, "error: The command requires VM to be selected.\n");
2446
2447 CSAMDisableScanning(pVM);
2448 return pCmdHlp->pfnPrintf(pCmdHlp, NULL, "CSAM Scanning disabled\n");
2449}
2450
2451/**
2452 * The '.csamon' command.
2453 *
2454 * @returns VBox status.
2455 * @param pCmd Pointer to the command descriptor (as registered).
2456 * @param pCmdHlp Pointer to command helper functions.
2457 * @param pVM Pointer to the current VM (if any).
2458 * @param paArgs Pointer to (readonly) array of arguments.
2459 * @param cArgs Number of arguments in the array.
2460 */
2461static DECLCALLBACK(int) csamr3CmdOn(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PVM pVM, PCDBGCVAR paArgs, unsigned cArgs, PDBGCVAR pResult)
2462{
2463 /*
2464 * Validate input.
2465 */
2466 if (!pVM)
2467 return pCmdHlp->pfnPrintf(pCmdHlp, NULL, "error: The command requires VM to be selected.\n");
2468
2469 CSAMEnableScanning(pVM);
2470 return pCmdHlp->pfnPrintf(pCmdHlp, NULL, "CSAM Scanning enabled\n");
2471}
2472#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