VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/Support/SUPDrv.cpp@ 71198

Last change on this file since 71198 was 71198, checked in by vboxsync, 7 years ago

SUPDrv,VMMR0: Prepped for extending the fast I/O control interface a bit for NEM; SUPDRV version increment. bugref:9044

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 229.2 KB
Line 
1/* $Id: SUPDrv.cpp 71198 2018-03-05 10:59:17Z vboxsync $ */
2/** @file
3 * VBoxDrv - The VirtualBox Support Driver - Common code.
4 */
5
6/*
7 * Copyright (C) 2006-2017 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#define LOG_GROUP LOG_GROUP_SUP_DRV
32#define SUPDRV_AGNOSTIC
33#include "SUPDrvInternal.h"
34#ifndef PAGE_SHIFT
35# include <iprt/param.h>
36#endif
37#include <iprt/asm.h>
38#include <iprt/asm-amd64-x86.h>
39#include <iprt/asm-math.h>
40#include <iprt/cpuset.h>
41#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_WINDOWS)
42# include <iprt/dbg.h>
43#endif
44#include <iprt/handletable.h>
45#include <iprt/mem.h>
46#include <iprt/mp.h>
47#include <iprt/power.h>
48#include <iprt/process.h>
49#include <iprt/semaphore.h>
50#include <iprt/spinlock.h>
51#include <iprt/thread.h>
52#include <iprt/uuid.h>
53#include <iprt/net.h>
54#include <iprt/crc.h>
55#include <iprt/string.h>
56#include <iprt/timer.h>
57#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
58# include <iprt/rand.h>
59# include <iprt/path.h>
60#endif
61#include <iprt/uint128.h>
62#include <iprt/x86.h>
63
64#include <VBox/param.h>
65#include <VBox/log.h>
66#include <VBox/err.h>
67#include <VBox/vmm/hm_vmx.h>
68
69#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
70# include "dtrace/SUPDrv.h"
71#else
72# define VBOXDRV_SESSION_CREATE(pvSession, fUser) do { } while (0)
73# define VBOXDRV_SESSION_CLOSE(pvSession) do { } while (0)
74# define VBOXDRV_IOCTL_ENTRY(pvSession, uIOCtl, pvReqHdr) do { } while (0)
75# define VBOXDRV_IOCTL_RETURN(pvSession, uIOCtl, pvReqHdr, rcRet, rcReq) do { } while (0)
76#endif
77
78/*
79 * Logging assignments:
80 * Log - useful stuff, like failures.
81 * LogFlow - program flow, except the really noisy bits.
82 * Log2 - Cleanup.
83 * Log3 - Loader flow noise.
84 * Log4 - Call VMMR0 flow noise.
85 * Log5 - Native yet-to-be-defined noise.
86 * Log6 - Native ioctl flow noise.
87 *
88 * Logging requires BUILD_TYPE=debug and possibly changes to the logger
89 * instantiation in log-vbox.c(pp).
90 */
91
92
93/*********************************************************************************************************************************
94* Defined Constants And Macros *
95*********************************************************************************************************************************/
96/** @def VBOX_SVN_REV
97 * The makefile should define this if it can. */
98#ifndef VBOX_SVN_REV
99# define VBOX_SVN_REV 0
100#endif
101
102/** @ SUPDRV_CHECK_SMAP_SETUP
103 * SMAP check setup. */
104/** @def SUPDRV_CHECK_SMAP_CHECK
105 * Checks that the AC flag is set if SMAP is enabled. If AC is not set, it
106 * will be logged and @a a_BadExpr is executed. */
107#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX)
108# define SUPDRV_CHECK_SMAP_SETUP() uint32_t const fKernelFeatures = SUPR0GetKernelFeatures()
109# define SUPDRV_CHECK_SMAP_CHECK(a_pDevExt, a_BadExpr) \
110 do { \
111 if (fKernelFeatures & SUPKERNELFEATURES_SMAP) \
112 { \
113 RTCCUINTREG fEfl = ASMGetFlags(); \
114 if (RT_LIKELY(fEfl & X86_EFL_AC)) \
115 { /* likely */ } \
116 else \
117 { \
118 supdrvBadContext(a_pDevExt, "SUPDrv.cpp", __LINE__, "EFLAGS.AC is 0!"); \
119 a_BadExpr; \
120 } \
121 } \
122 } while (0)
123#else
124# define SUPDRV_CHECK_SMAP_SETUP() uint32_t const fKernelFeatures = 0
125# define SUPDRV_CHECK_SMAP_CHECK(a_pDevExt, a_BadExpr) NOREF(fKernelFeatures)
126#endif
127
128
129/*********************************************************************************************************************************
130* Internal Functions *
131*********************************************************************************************************************************/
132static DECLCALLBACK(int) supdrvSessionObjHandleRetain(RTHANDLETABLE hHandleTable, void *pvObj, void *pvCtx, void *pvUser);
133static DECLCALLBACK(void) supdrvSessionObjHandleDelete(RTHANDLETABLE hHandleTable, uint32_t h, void *pvObj, void *pvCtx, void *pvUser);
134static int supdrvMemAdd(PSUPDRVMEMREF pMem, PSUPDRVSESSION pSession);
135static int supdrvMemRelease(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, SUPDRVMEMREFTYPE eType);
136static int supdrvIOCtl_LdrOpen(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDROPEN pReq);
137static int supdrvIOCtl_LdrLoad(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRLOAD pReq);
138static int supdrvIOCtl_LdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRFREE pReq);
139static int supdrvIOCtl_LdrLockDown(PSUPDRVDEVEXT pDevExt);
140static int supdrvIOCtl_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRGETSYMBOL pReq);
141static int supdrvIDC_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVIDCREQGETSYM pReq);
142static int supdrvLdrSetVMMR0EPs(PSUPDRVDEVEXT pDevExt, void *pvVMMR0, void *pvVMMR0EntryFast, void *pvVMMR0EntryEx);
143static void supdrvLdrUnsetVMMR0EPs(PSUPDRVDEVEXT pDevExt);
144static int supdrvLdrAddUsage(PSUPDRVSESSION pSession, PSUPDRVLDRIMAGE pImage);
145static void supdrvLdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage);
146DECLINLINE(int) supdrvLdrLock(PSUPDRVDEVEXT pDevExt);
147DECLINLINE(int) supdrvLdrUnlock(PSUPDRVDEVEXT pDevExt);
148static int supdrvIOCtl_CallServiceModule(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPCALLSERVICE pReq);
149static int supdrvIOCtl_LoggerSettings(PSUPLOGGERSETTINGS pReq);
150static int supdrvIOCtl_MsrProber(PSUPDRVDEVEXT pDevExt, PSUPMSRPROBER pReq);
151static int supdrvIOCtl_ResumeSuspendedKbds(void);
152
153
154/*********************************************************************************************************************************
155* Global Variables *
156*********************************************************************************************************************************/
157/**
158 * Array of the R0 SUP API.
159 *
160 * While making changes to these exports, make sure to update the IOC
161 * minor version (SUPDRV_IOC_VERSION).
162 *
163 * @remarks This array is processed by SUPR0-def-pe.sed and SUPR0-def-lx.sed to
164 * produce definition files from which import libraries are generated.
165 * Take care when commenting things and especially with \#ifdef'ing.
166 */
167static SUPFUNC g_aFunctions[] =
168{
169/* SED: START */
170 /* name function */
171 /* Entries with absolute addresses determined at runtime, fixup
172 code makes ugly ASSUMPTIONS about the order here: */
173 { "SUPR0AbsIs64bit", (void *)0 },
174 { "SUPR0Abs64bitKernelCS", (void *)0 },
175 { "SUPR0Abs64bitKernelSS", (void *)0 },
176 { "SUPR0Abs64bitKernelDS", (void *)0 },
177 { "SUPR0AbsKernelCS", (void *)0 },
178 { "SUPR0AbsKernelSS", (void *)0 },
179 { "SUPR0AbsKernelDS", (void *)0 },
180 { "SUPR0AbsKernelES", (void *)0 },
181 { "SUPR0AbsKernelFS", (void *)0 },
182 { "SUPR0AbsKernelGS", (void *)0 },
183 /* Normal function pointers: */
184 { "g_pSUPGlobalInfoPage", (void *)&g_pSUPGlobalInfoPage }, /* SED: DATA */
185 { "SUPGetGIP", (void *)(uintptr_t)SUPGetGIP },
186 { "SUPReadTscWithDelta", (void *)(uintptr_t)SUPReadTscWithDelta },
187 { "SUPGetTscDeltaSlow", (void *)(uintptr_t)SUPGetTscDeltaSlow },
188 { "SUPGetCpuHzFromGipForAsyncMode", (void *)(uintptr_t)SUPGetCpuHzFromGipForAsyncMode },
189 { "SUPIsTscFreqCompatible", (void *)(uintptr_t)SUPIsTscFreqCompatible },
190 { "SUPIsTscFreqCompatibleEx", (void *)(uintptr_t)SUPIsTscFreqCompatibleEx },
191 { "SUPR0BadContext", (void *)(uintptr_t)SUPR0BadContext },
192 { "SUPR0ComponentDeregisterFactory", (void *)(uintptr_t)SUPR0ComponentDeregisterFactory },
193 { "SUPR0ComponentQueryFactory", (void *)(uintptr_t)SUPR0ComponentQueryFactory },
194 { "SUPR0ComponentRegisterFactory", (void *)(uintptr_t)SUPR0ComponentRegisterFactory },
195 { "SUPR0ContAlloc", (void *)(uintptr_t)SUPR0ContAlloc },
196 { "SUPR0ContFree", (void *)(uintptr_t)SUPR0ContFree },
197 { "SUPR0ChangeCR4", (void *)(uintptr_t)SUPR0ChangeCR4 },
198 { "SUPR0EnableVTx", (void *)(uintptr_t)SUPR0EnableVTx },
199 { "SUPR0SuspendVTxOnCpu", (void *)(uintptr_t)SUPR0SuspendVTxOnCpu },
200 { "SUPR0ResumeVTxOnCpu", (void *)(uintptr_t)SUPR0ResumeVTxOnCpu },
201 { "SUPR0GetCurrentGdtRw", (void *)(uintptr_t)SUPR0GetCurrentGdtRw },
202 { "SUPR0GetKernelFeatures", (void *)(uintptr_t)SUPR0GetKernelFeatures },
203 { "SUPR0GetPagingMode", (void *)(uintptr_t)SUPR0GetPagingMode },
204 { "SUPR0GetSvmUsability", (void *)(uintptr_t)SUPR0GetSvmUsability },
205 { "SUPR0GetVmxUsability", (void *)(uintptr_t)SUPR0GetVmxUsability },
206 { "SUPR0GetRawModeUsability", (void *)(uintptr_t)SUPR0GetRawModeUsability },
207 { "SUPR0LockMem", (void *)(uintptr_t)SUPR0LockMem },
208 { "SUPR0LowAlloc", (void *)(uintptr_t)SUPR0LowAlloc },
209 { "SUPR0LowFree", (void *)(uintptr_t)SUPR0LowFree },
210 { "SUPR0MemAlloc", (void *)(uintptr_t)SUPR0MemAlloc },
211 { "SUPR0MemFree", (void *)(uintptr_t)SUPR0MemFree },
212 { "SUPR0MemGetPhys", (void *)(uintptr_t)SUPR0MemGetPhys },
213 { "SUPR0ObjAddRef", (void *)(uintptr_t)SUPR0ObjAddRef },
214 { "SUPR0ObjAddRefEx", (void *)(uintptr_t)SUPR0ObjAddRefEx },
215 { "SUPR0ObjRegister", (void *)(uintptr_t)SUPR0ObjRegister },
216 { "SUPR0ObjRelease", (void *)(uintptr_t)SUPR0ObjRelease },
217 { "SUPR0ObjVerifyAccess", (void *)(uintptr_t)SUPR0ObjVerifyAccess },
218 { "SUPR0PageAllocEx", (void *)(uintptr_t)SUPR0PageAllocEx },
219 { "SUPR0PageFree", (void *)(uintptr_t)SUPR0PageFree },
220 { "SUPR0Printf", (void *)(uintptr_t)SUPR0Printf },
221 { "SUPR0GetSessionGVM", (void *)(uintptr_t)SUPR0GetSessionGVM },
222 { "SUPR0GetSessionVM", (void *)(uintptr_t)SUPR0GetSessionVM },
223 { "SUPR0SetSessionVM", (void *)(uintptr_t)SUPR0SetSessionVM },
224 { "SUPR0TscDeltaMeasureBySetIndex", (void *)(uintptr_t)SUPR0TscDeltaMeasureBySetIndex },
225 { "SUPR0TracerDeregisterDrv", (void *)(uintptr_t)SUPR0TracerDeregisterDrv },
226 { "SUPR0TracerDeregisterImpl", (void *)(uintptr_t)SUPR0TracerDeregisterImpl },
227 { "SUPR0TracerFireProbe", (void *)(uintptr_t)SUPR0TracerFireProbe },
228 { "SUPR0TracerRegisterDrv", (void *)(uintptr_t)SUPR0TracerRegisterDrv },
229 { "SUPR0TracerRegisterImpl", (void *)(uintptr_t)SUPR0TracerRegisterImpl },
230 { "SUPR0TracerRegisterModule", (void *)(uintptr_t)SUPR0TracerRegisterModule },
231 { "SUPR0TracerUmodProbeFire", (void *)(uintptr_t)SUPR0TracerUmodProbeFire },
232 { "SUPR0UnlockMem", (void *)(uintptr_t)SUPR0UnlockMem },
233#ifdef RT_OS_WINDOWS
234 { "SUPR0IoCtlSetupForHandle", (void *)(uintptr_t)SUPR0IoCtlSetupForHandle }, /* only-windows */
235 { "SUPR0IoCtlPerform", (void *)(uintptr_t)SUPR0IoCtlPerform }, /* only-windows */
236 { "SUPR0IoCtlCleanup", (void *)(uintptr_t)SUPR0IoCtlCleanup }, /* only-windows */
237#endif
238 { "SUPSemEventClose", (void *)(uintptr_t)SUPSemEventClose },
239 { "SUPSemEventCreate", (void *)(uintptr_t)SUPSemEventCreate },
240 { "SUPSemEventGetResolution", (void *)(uintptr_t)SUPSemEventGetResolution },
241 { "SUPSemEventMultiClose", (void *)(uintptr_t)SUPSemEventMultiClose },
242 { "SUPSemEventMultiCreate", (void *)(uintptr_t)SUPSemEventMultiCreate },
243 { "SUPSemEventMultiGetResolution", (void *)(uintptr_t)SUPSemEventMultiGetResolution },
244 { "SUPSemEventMultiReset", (void *)(uintptr_t)SUPSemEventMultiReset },
245 { "SUPSemEventMultiSignal", (void *)(uintptr_t)SUPSemEventMultiSignal },
246 { "SUPSemEventMultiWait", (void *)(uintptr_t)SUPSemEventMultiWait },
247 { "SUPSemEventMultiWaitNoResume", (void *)(uintptr_t)SUPSemEventMultiWaitNoResume },
248 { "SUPSemEventMultiWaitNsAbsIntr", (void *)(uintptr_t)SUPSemEventMultiWaitNsAbsIntr },
249 { "SUPSemEventMultiWaitNsRelIntr", (void *)(uintptr_t)SUPSemEventMultiWaitNsRelIntr },
250 { "SUPSemEventSignal", (void *)(uintptr_t)SUPSemEventSignal },
251 { "SUPSemEventWait", (void *)(uintptr_t)SUPSemEventWait },
252 { "SUPSemEventWaitNoResume", (void *)(uintptr_t)SUPSemEventWaitNoResume },
253 { "SUPSemEventWaitNsAbsIntr", (void *)(uintptr_t)SUPSemEventWaitNsAbsIntr },
254 { "SUPSemEventWaitNsRelIntr", (void *)(uintptr_t)SUPSemEventWaitNsRelIntr },
255
256 { "RTAssertAreQuiet", (void *)(uintptr_t)RTAssertAreQuiet },
257 { "RTAssertMayPanic", (void *)(uintptr_t)RTAssertMayPanic },
258 { "RTAssertMsg1", (void *)(uintptr_t)RTAssertMsg1 },
259 { "RTAssertMsg2AddV", (void *)(uintptr_t)RTAssertMsg2AddV },
260 { "RTAssertMsg2V", (void *)(uintptr_t)RTAssertMsg2V },
261 { "RTAssertSetMayPanic", (void *)(uintptr_t)RTAssertSetMayPanic },
262 { "RTAssertSetQuiet", (void *)(uintptr_t)RTAssertSetQuiet },
263 { "RTCrc32", (void *)(uintptr_t)RTCrc32 },
264 { "RTCrc32Finish", (void *)(uintptr_t)RTCrc32Finish },
265 { "RTCrc32Process", (void *)(uintptr_t)RTCrc32Process },
266 { "RTCrc32Start", (void *)(uintptr_t)RTCrc32Start },
267 { "RTErrConvertFromErrno", (void *)(uintptr_t)RTErrConvertFromErrno },
268 { "RTErrConvertToErrno", (void *)(uintptr_t)RTErrConvertToErrno },
269 { "RTHandleTableAllocWithCtx", (void *)(uintptr_t)RTHandleTableAllocWithCtx },
270 { "RTHandleTableCreate", (void *)(uintptr_t)RTHandleTableCreate },
271 { "RTHandleTableCreateEx", (void *)(uintptr_t)RTHandleTableCreateEx },
272 { "RTHandleTableDestroy", (void *)(uintptr_t)RTHandleTableDestroy },
273 { "RTHandleTableFreeWithCtx", (void *)(uintptr_t)RTHandleTableFreeWithCtx },
274 { "RTHandleTableLookupWithCtx", (void *)(uintptr_t)RTHandleTableLookupWithCtx },
275 { "RTLogDefaultInstance", (void *)(uintptr_t)RTLogDefaultInstance },
276 { "RTLogDefaultInstanceEx", (void *)(uintptr_t)RTLogDefaultInstanceEx },
277 { "RTLogGetDefaultInstance", (void *)(uintptr_t)RTLogGetDefaultInstance },
278 { "RTLogGetDefaultInstanceEx", (void *)(uintptr_t)RTLogGetDefaultInstanceEx },
279 { "RTLogLoggerExV", (void *)(uintptr_t)RTLogLoggerExV },
280 { "RTLogPrintfV", (void *)(uintptr_t)RTLogPrintfV },
281 { "RTLogRelGetDefaultInstance", (void *)(uintptr_t)RTLogRelGetDefaultInstance },
282 { "RTLogRelGetDefaultInstanceEx", (void *)(uintptr_t)RTLogRelGetDefaultInstanceEx },
283 { "RTLogSetDefaultInstanceThread", (void *)(uintptr_t)RTLogSetDefaultInstanceThread },
284 { "RTMemAllocExTag", (void *)(uintptr_t)RTMemAllocExTag },
285 { "RTMemAllocTag", (void *)(uintptr_t)RTMemAllocTag },
286 { "RTMemAllocVarTag", (void *)(uintptr_t)RTMemAllocVarTag },
287 { "RTMemAllocZTag", (void *)(uintptr_t)RTMemAllocZTag },
288 { "RTMemAllocZVarTag", (void *)(uintptr_t)RTMemAllocZVarTag },
289 { "RTMemDupExTag", (void *)(uintptr_t)RTMemDupExTag },
290 { "RTMemDupTag", (void *)(uintptr_t)RTMemDupTag },
291 { "RTMemFree", (void *)(uintptr_t)RTMemFree },
292 { "RTMemFreeEx", (void *)(uintptr_t)RTMemFreeEx },
293 { "RTMemReallocTag", (void *)(uintptr_t)RTMemReallocTag },
294 { "RTMpCpuId", (void *)(uintptr_t)RTMpCpuId },
295 { "RTMpCpuIdFromSetIndex", (void *)(uintptr_t)RTMpCpuIdFromSetIndex },
296 { "RTMpCpuIdToSetIndex", (void *)(uintptr_t)RTMpCpuIdToSetIndex },
297 { "RTMpCurSetIndex", (void *)(uintptr_t)RTMpCurSetIndex },
298 { "RTMpCurSetIndexAndId", (void *)(uintptr_t)RTMpCurSetIndexAndId },
299 { "RTMpGetArraySize", (void *)(uintptr_t)RTMpGetArraySize },
300 { "RTMpGetCount", (void *)(uintptr_t)RTMpGetCount },
301 { "RTMpGetMaxCpuId", (void *)(uintptr_t)RTMpGetMaxCpuId },
302 { "RTMpGetOnlineCount", (void *)(uintptr_t)RTMpGetOnlineCount },
303 { "RTMpGetOnlineSet", (void *)(uintptr_t)RTMpGetOnlineSet },
304 { "RTMpGetSet", (void *)(uintptr_t)RTMpGetSet },
305 { "RTMpIsCpuOnline", (void *)(uintptr_t)RTMpIsCpuOnline },
306 { "RTMpIsCpuPossible", (void *)(uintptr_t)RTMpIsCpuPossible },
307 { "RTMpIsCpuWorkPending", (void *)(uintptr_t)RTMpIsCpuWorkPending },
308 { "RTMpNotificationDeregister", (void *)(uintptr_t)RTMpNotificationDeregister },
309 { "RTMpNotificationRegister", (void *)(uintptr_t)RTMpNotificationRegister },
310 { "RTMpOnAll", (void *)(uintptr_t)RTMpOnAll },
311 { "RTMpOnOthers", (void *)(uintptr_t)RTMpOnOthers },
312 { "RTMpOnSpecific", (void *)(uintptr_t)RTMpOnSpecific },
313 { "RTMpPokeCpu", (void *)(uintptr_t)RTMpPokeCpu },
314 { "RTNetIPv4AddDataChecksum", (void *)(uintptr_t)RTNetIPv4AddDataChecksum },
315 { "RTNetIPv4AddTCPChecksum", (void *)(uintptr_t)RTNetIPv4AddTCPChecksum },
316 { "RTNetIPv4AddUDPChecksum", (void *)(uintptr_t)RTNetIPv4AddUDPChecksum },
317 { "RTNetIPv4FinalizeChecksum", (void *)(uintptr_t)RTNetIPv4FinalizeChecksum },
318 { "RTNetIPv4HdrChecksum", (void *)(uintptr_t)RTNetIPv4HdrChecksum },
319 { "RTNetIPv4IsDHCPValid", (void *)(uintptr_t)RTNetIPv4IsDHCPValid },
320 { "RTNetIPv4IsHdrValid", (void *)(uintptr_t)RTNetIPv4IsHdrValid },
321 { "RTNetIPv4IsTCPSizeValid", (void *)(uintptr_t)RTNetIPv4IsTCPSizeValid },
322 { "RTNetIPv4IsTCPValid", (void *)(uintptr_t)RTNetIPv4IsTCPValid },
323 { "RTNetIPv4IsUDPSizeValid", (void *)(uintptr_t)RTNetIPv4IsUDPSizeValid },
324 { "RTNetIPv4IsUDPValid", (void *)(uintptr_t)RTNetIPv4IsUDPValid },
325 { "RTNetIPv4PseudoChecksum", (void *)(uintptr_t)RTNetIPv4PseudoChecksum },
326 { "RTNetIPv4PseudoChecksumBits", (void *)(uintptr_t)RTNetIPv4PseudoChecksumBits },
327 { "RTNetIPv4TCPChecksum", (void *)(uintptr_t)RTNetIPv4TCPChecksum },
328 { "RTNetIPv4UDPChecksum", (void *)(uintptr_t)RTNetIPv4UDPChecksum },
329 { "RTNetIPv6PseudoChecksum", (void *)(uintptr_t)RTNetIPv6PseudoChecksum },
330 { "RTNetIPv6PseudoChecksumBits", (void *)(uintptr_t)RTNetIPv6PseudoChecksumBits },
331 { "RTNetIPv6PseudoChecksumEx", (void *)(uintptr_t)RTNetIPv6PseudoChecksumEx },
332 { "RTNetTCPChecksum", (void *)(uintptr_t)RTNetTCPChecksum },
333 { "RTNetUDPChecksum", (void *)(uintptr_t)RTNetUDPChecksum },
334 { "RTPowerNotificationDeregister", (void *)(uintptr_t)RTPowerNotificationDeregister },
335 { "RTPowerNotificationRegister", (void *)(uintptr_t)RTPowerNotificationRegister },
336 { "RTProcSelf", (void *)(uintptr_t)RTProcSelf },
337 { "RTR0AssertPanicSystem", (void *)(uintptr_t)RTR0AssertPanicSystem },
338#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_WINDOWS)
339 { "RTR0DbgKrnlInfoOpen", (void *)(uintptr_t)RTR0DbgKrnlInfoOpen }, /* only-darwin, only-solaris, only-windows */
340 { "RTR0DbgKrnlInfoQueryMember", (void *)(uintptr_t)RTR0DbgKrnlInfoQueryMember }, /* only-darwin, only-solaris, only-windows */
341# if defined(RT_OS_SOLARIS)
342 { "RTR0DbgKrnlInfoQuerySize", (void *)(uintptr_t)RTR0DbgKrnlInfoQuerySize }, /* only-solaris */
343# endif
344 { "RTR0DbgKrnlInfoQuerySymbol", (void *)(uintptr_t)RTR0DbgKrnlInfoQuerySymbol }, /* only-darwin, only-solaris, only-windows */
345 { "RTR0DbgKrnlInfoRelease", (void *)(uintptr_t)RTR0DbgKrnlInfoRelease }, /* only-darwin, only-solaris, only-windows */
346 { "RTR0DbgKrnlInfoRetain", (void *)(uintptr_t)RTR0DbgKrnlInfoRetain }, /* only-darwin, only-solaris, only-windows */
347#endif
348 { "RTR0MemAreKrnlAndUsrDifferent", (void *)(uintptr_t)RTR0MemAreKrnlAndUsrDifferent },
349 { "RTR0MemKernelIsValidAddr", (void *)(uintptr_t)RTR0MemKernelIsValidAddr },
350 { "RTR0MemKernelCopyFrom", (void *)(uintptr_t)RTR0MemKernelCopyFrom },
351 { "RTR0MemKernelCopyTo", (void *)(uintptr_t)RTR0MemKernelCopyTo },
352 { "RTR0MemObjAddress", (void *)(uintptr_t)RTR0MemObjAddress },
353 { "RTR0MemObjAddressR3", (void *)(uintptr_t)RTR0MemObjAddressR3 },
354 { "RTR0MemObjAllocContTag", (void *)(uintptr_t)RTR0MemObjAllocContTag },
355 { "RTR0MemObjAllocLowTag", (void *)(uintptr_t)RTR0MemObjAllocLowTag },
356 { "RTR0MemObjAllocPageTag", (void *)(uintptr_t)RTR0MemObjAllocPageTag },
357 { "RTR0MemObjAllocPhysExTag", (void *)(uintptr_t)RTR0MemObjAllocPhysExTag },
358 { "RTR0MemObjAllocPhysNCTag", (void *)(uintptr_t)RTR0MemObjAllocPhysNCTag },
359 { "RTR0MemObjAllocPhysTag", (void *)(uintptr_t)RTR0MemObjAllocPhysTag },
360 { "RTR0MemObjEnterPhysTag", (void *)(uintptr_t)RTR0MemObjEnterPhysTag },
361 { "RTR0MemObjFree", (void *)(uintptr_t)RTR0MemObjFree },
362 { "RTR0MemObjGetPagePhysAddr", (void *)(uintptr_t)RTR0MemObjGetPagePhysAddr },
363 { "RTR0MemObjIsMapping", (void *)(uintptr_t)RTR0MemObjIsMapping },
364 { "RTR0MemObjLockUserTag", (void *)(uintptr_t)RTR0MemObjLockUserTag },
365 { "RTR0MemObjMapKernelExTag", (void *)(uintptr_t)RTR0MemObjMapKernelExTag },
366 { "RTR0MemObjMapKernelTag", (void *)(uintptr_t)RTR0MemObjMapKernelTag },
367 { "RTR0MemObjMapUserTag", (void *)(uintptr_t)RTR0MemObjMapUserTag },
368 { "RTR0MemObjProtect", (void *)(uintptr_t)RTR0MemObjProtect },
369 { "RTR0MemObjSize", (void *)(uintptr_t)RTR0MemObjSize },
370 { "RTR0MemUserCopyFrom", (void *)(uintptr_t)RTR0MemUserCopyFrom },
371 { "RTR0MemUserCopyTo", (void *)(uintptr_t)RTR0MemUserCopyTo },
372 { "RTR0MemUserIsValidAddr", (void *)(uintptr_t)RTR0MemUserIsValidAddr },
373 { "RTR0ProcHandleSelf", (void *)(uintptr_t)RTR0ProcHandleSelf },
374 { "RTSemEventCreate", (void *)(uintptr_t)RTSemEventCreate },
375 { "RTSemEventDestroy", (void *)(uintptr_t)RTSemEventDestroy },
376 { "RTSemEventGetResolution", (void *)(uintptr_t)RTSemEventGetResolution },
377 { "RTSemEventMultiCreate", (void *)(uintptr_t)RTSemEventMultiCreate },
378 { "RTSemEventMultiDestroy", (void *)(uintptr_t)RTSemEventMultiDestroy },
379 { "RTSemEventMultiGetResolution", (void *)(uintptr_t)RTSemEventMultiGetResolution },
380 { "RTSemEventMultiReset", (void *)(uintptr_t)RTSemEventMultiReset },
381 { "RTSemEventMultiSignal", (void *)(uintptr_t)RTSemEventMultiSignal },
382 { "RTSemEventMultiWait", (void *)(uintptr_t)RTSemEventMultiWait },
383 { "RTSemEventMultiWaitEx", (void *)(uintptr_t)RTSemEventMultiWaitEx },
384 { "RTSemEventMultiWaitExDebug", (void *)(uintptr_t)RTSemEventMultiWaitExDebug },
385 { "RTSemEventMultiWaitNoResume", (void *)(uintptr_t)RTSemEventMultiWaitNoResume },
386 { "RTSemEventSignal", (void *)(uintptr_t)RTSemEventSignal },
387 { "RTSemEventWait", (void *)(uintptr_t)RTSemEventWait },
388 { "RTSemEventWaitEx", (void *)(uintptr_t)RTSemEventWaitEx },
389 { "RTSemEventWaitExDebug", (void *)(uintptr_t)RTSemEventWaitExDebug },
390 { "RTSemEventWaitNoResume", (void *)(uintptr_t)RTSemEventWaitNoResume },
391 { "RTSemFastMutexCreate", (void *)(uintptr_t)RTSemFastMutexCreate },
392 { "RTSemFastMutexDestroy", (void *)(uintptr_t)RTSemFastMutexDestroy },
393 { "RTSemFastMutexRelease", (void *)(uintptr_t)RTSemFastMutexRelease },
394 { "RTSemFastMutexRequest", (void *)(uintptr_t)RTSemFastMutexRequest },
395 { "RTSemMutexCreate", (void *)(uintptr_t)RTSemMutexCreate },
396 { "RTSemMutexDestroy", (void *)(uintptr_t)RTSemMutexDestroy },
397 { "RTSemMutexRelease", (void *)(uintptr_t)RTSemMutexRelease },
398 { "RTSemMutexRequest", (void *)(uintptr_t)RTSemMutexRequest },
399 { "RTSemMutexRequestDebug", (void *)(uintptr_t)RTSemMutexRequestDebug },
400 { "RTSemMutexRequestNoResume", (void *)(uintptr_t)RTSemMutexRequestNoResume },
401 { "RTSemMutexRequestNoResumeDebug", (void *)(uintptr_t)RTSemMutexRequestNoResumeDebug },
402 { "RTSpinlockAcquire", (void *)(uintptr_t)RTSpinlockAcquire },
403 { "RTSpinlockCreate", (void *)(uintptr_t)RTSpinlockCreate },
404 { "RTSpinlockDestroy", (void *)(uintptr_t)RTSpinlockDestroy },
405 { "RTSpinlockRelease", (void *)(uintptr_t)RTSpinlockRelease },
406 { "RTStrCopy", (void *)(uintptr_t)RTStrCopy },
407 { "RTStrDupTag", (void *)(uintptr_t)RTStrDupTag },
408 { "RTStrFormat", (void *)(uintptr_t)RTStrFormat },
409 { "RTStrFormatNumber", (void *)(uintptr_t)RTStrFormatNumber },
410 { "RTStrFormatTypeDeregister", (void *)(uintptr_t)RTStrFormatTypeDeregister },
411 { "RTStrFormatTypeRegister", (void *)(uintptr_t)RTStrFormatTypeRegister },
412 { "RTStrFormatTypeSetUser", (void *)(uintptr_t)RTStrFormatTypeSetUser },
413 { "RTStrFormatV", (void *)(uintptr_t)RTStrFormatV },
414 { "RTStrFree", (void *)(uintptr_t)RTStrFree },
415 { "RTStrNCmp", (void *)(uintptr_t)RTStrNCmp },
416 { "RTStrPrintf", (void *)(uintptr_t)RTStrPrintf },
417 { "RTStrPrintfEx", (void *)(uintptr_t)RTStrPrintfEx },
418 { "RTStrPrintfExV", (void *)(uintptr_t)RTStrPrintfExV },
419 { "RTStrPrintfV", (void *)(uintptr_t)RTStrPrintfV },
420 { "RTThreadCreate", (void *)(uintptr_t)RTThreadCreate },
421 { "RTThreadCtxHookIsEnabled", (void *)(uintptr_t)RTThreadCtxHookIsEnabled },
422 { "RTThreadCtxHookCreate", (void *)(uintptr_t)RTThreadCtxHookCreate },
423 { "RTThreadCtxHookDestroy", (void *)(uintptr_t)RTThreadCtxHookDestroy },
424 { "RTThreadCtxHookDisable", (void *)(uintptr_t)RTThreadCtxHookDisable },
425 { "RTThreadCtxHookEnable", (void *)(uintptr_t)RTThreadCtxHookEnable },
426 { "RTThreadGetName", (void *)(uintptr_t)RTThreadGetName },
427 { "RTThreadGetNative", (void *)(uintptr_t)RTThreadGetNative },
428 { "RTThreadGetType", (void *)(uintptr_t)RTThreadGetType },
429 { "RTThreadIsInInterrupt", (void *)(uintptr_t)RTThreadIsInInterrupt },
430 { "RTThreadNativeSelf", (void *)(uintptr_t)RTThreadNativeSelf },
431 { "RTThreadPreemptDisable", (void *)(uintptr_t)RTThreadPreemptDisable },
432 { "RTThreadPreemptIsEnabled", (void *)(uintptr_t)RTThreadPreemptIsEnabled },
433 { "RTThreadPreemptIsPending", (void *)(uintptr_t)RTThreadPreemptIsPending },
434 { "RTThreadPreemptIsPendingTrusty", (void *)(uintptr_t)RTThreadPreemptIsPendingTrusty },
435 { "RTThreadPreemptIsPossible", (void *)(uintptr_t)RTThreadPreemptIsPossible },
436 { "RTThreadPreemptRestore", (void *)(uintptr_t)RTThreadPreemptRestore },
437 { "RTThreadSelf", (void *)(uintptr_t)RTThreadSelf },
438 { "RTThreadSelfName", (void *)(uintptr_t)RTThreadSelfName },
439 { "RTThreadSleep", (void *)(uintptr_t)RTThreadSleep },
440 { "RTThreadUserReset", (void *)(uintptr_t)RTThreadUserReset },
441 { "RTThreadUserSignal", (void *)(uintptr_t)RTThreadUserSignal },
442 { "RTThreadUserWait", (void *)(uintptr_t)RTThreadUserWait },
443 { "RTThreadUserWaitNoResume", (void *)(uintptr_t)RTThreadUserWaitNoResume },
444 { "RTThreadWait", (void *)(uintptr_t)RTThreadWait },
445 { "RTThreadWaitNoResume", (void *)(uintptr_t)RTThreadWaitNoResume },
446 { "RTThreadYield", (void *)(uintptr_t)RTThreadYield },
447 { "RTTimeMilliTS", (void *)(uintptr_t)RTTimeMilliTS },
448 { "RTTimeNanoTS", (void *)(uintptr_t)RTTimeNanoTS },
449 { "RTTimeNow", (void *)(uintptr_t)RTTimeNow },
450 { "RTTimerCanDoHighResolution", (void *)(uintptr_t)RTTimerCanDoHighResolution },
451 { "RTTimerChangeInterval", (void *)(uintptr_t)RTTimerChangeInterval },
452 { "RTTimerCreate", (void *)(uintptr_t)RTTimerCreate },
453 { "RTTimerCreateEx", (void *)(uintptr_t)RTTimerCreateEx },
454 { "RTTimerDestroy", (void *)(uintptr_t)RTTimerDestroy },
455 { "RTTimerGetSystemGranularity", (void *)(uintptr_t)RTTimerGetSystemGranularity },
456 { "RTTimerReleaseSystemGranularity", (void *)(uintptr_t)RTTimerReleaseSystemGranularity },
457 { "RTTimerRequestSystemGranularity", (void *)(uintptr_t)RTTimerRequestSystemGranularity },
458 { "RTTimerStart", (void *)(uintptr_t)RTTimerStart },
459 { "RTTimerStop", (void *)(uintptr_t)RTTimerStop },
460 { "RTTimeSystemMilliTS", (void *)(uintptr_t)RTTimeSystemMilliTS },
461 { "RTTimeSystemNanoTS", (void *)(uintptr_t)RTTimeSystemNanoTS },
462 { "RTUuidCompare", (void *)(uintptr_t)RTUuidCompare },
463 { "RTUuidCompareStr", (void *)(uintptr_t)RTUuidCompareStr },
464 { "RTUuidFromStr", (void *)(uintptr_t)RTUuidFromStr },
465/* SED: END */
466};
467
468#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
469/**
470 * Drag in the rest of IRPT since we share it with the
471 * rest of the kernel modules on darwin.
472 */
473PFNRT g_apfnVBoxDrvIPRTDeps[] =
474{
475 /* VBoxNetAdp */
476 (PFNRT)RTRandBytes,
477 /* VBoxUSB */
478 (PFNRT)RTPathStripFilename,
479 (PFNRT)RTHandleTableAlloc,
480#if !defined(RT_OS_FREEBSD)
481 (PFNRT)RTStrPurgeEncoding,
482#endif
483 NULL
484};
485#endif /* RT_OS_DARWIN || RT_OS_SOLARIS || RT_OS_SOLARIS */
486
487
488/**
489 * Initializes the device extentsion structure.
490 *
491 * @returns IPRT status code.
492 * @param pDevExt The device extension to initialize.
493 * @param cbSession The size of the session structure. The size of
494 * SUPDRVSESSION may be smaller when SUPDRV_AGNOSTIC is
495 * defined because we're skipping the OS specific members
496 * then.
497 */
498int VBOXCALL supdrvInitDevExt(PSUPDRVDEVEXT pDevExt, size_t cbSession)
499{
500 int rc;
501
502#ifdef SUPDRV_WITH_RELEASE_LOGGER
503 /*
504 * Create the release log.
505 */
506 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
507 PRTLOGGER pRelLogger;
508 rc = RTLogCreate(&pRelLogger, 0 /* fFlags */, "all",
509 "VBOX_RELEASE_LOG", RT_ELEMENTS(s_apszGroups), s_apszGroups, RTLOGDEST_STDOUT | RTLOGDEST_DEBUGGER, NULL);
510 if (RT_SUCCESS(rc))
511 RTLogRelSetDefaultInstance(pRelLogger);
512 /** @todo Add native hook for getting logger config parameters and setting
513 * them. On linux we should use the module parameter stuff... */
514#endif
515
516 /*
517 * Initialize it.
518 */
519 memset(pDevExt, 0, sizeof(*pDevExt)); /* Does not wipe OS specific tail section of the structure. */
520 pDevExt->Spinlock = NIL_RTSPINLOCK;
521 pDevExt->hGipSpinlock = NIL_RTSPINLOCK;
522 pDevExt->hSessionHashTabSpinlock = NIL_RTSPINLOCK;
523#ifdef SUPDRV_USE_MUTEX_FOR_LDR
524 pDevExt->mtxLdr = NIL_RTSEMMUTEX;
525#else
526 pDevExt->mtxLdr = NIL_RTSEMFASTMUTEX;
527#endif
528#ifdef SUPDRV_USE_MUTEX_FOR_GIP
529 pDevExt->mtxGip = NIL_RTSEMMUTEX;
530 pDevExt->mtxTscDelta = NIL_RTSEMMUTEX;
531#else
532 pDevExt->mtxGip = NIL_RTSEMFASTMUTEX;
533 pDevExt->mtxTscDelta = NIL_RTSEMFASTMUTEX;
534#endif
535
536 rc = RTSpinlockCreate(&pDevExt->Spinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "SUPDrvDevExt");
537 if (RT_SUCCESS(rc))
538 rc = RTSpinlockCreate(&pDevExt->hGipSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "SUPDrvGip");
539 if (RT_SUCCESS(rc))
540 rc = RTSpinlockCreate(&pDevExt->hSessionHashTabSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "SUPDrvSession");
541
542 if (RT_SUCCESS(rc))
543#ifdef SUPDRV_USE_MUTEX_FOR_LDR
544 rc = RTSemMutexCreate(&pDevExt->mtxLdr);
545#else
546 rc = RTSemFastMutexCreate(&pDevExt->mtxLdr);
547#endif
548 if (RT_SUCCESS(rc))
549#ifdef SUPDRV_USE_MUTEX_FOR_GIP
550 rc = RTSemMutexCreate(&pDevExt->mtxTscDelta);
551#else
552 rc = RTSemFastMutexCreate(&pDevExt->mtxTscDelta);
553#endif
554 if (RT_SUCCESS(rc))
555 {
556 rc = RTSemFastMutexCreate(&pDevExt->mtxComponentFactory);
557 if (RT_SUCCESS(rc))
558 {
559#ifdef SUPDRV_USE_MUTEX_FOR_GIP
560 rc = RTSemMutexCreate(&pDevExt->mtxGip);
561#else
562 rc = RTSemFastMutexCreate(&pDevExt->mtxGip);
563#endif
564 if (RT_SUCCESS(rc))
565 {
566 rc = supdrvGipCreate(pDevExt);
567 if (RT_SUCCESS(rc))
568 {
569 rc = supdrvTracerInit(pDevExt);
570 if (RT_SUCCESS(rc))
571 {
572 pDevExt->pLdrInitImage = NULL;
573 pDevExt->hLdrInitThread = NIL_RTNATIVETHREAD;
574 pDevExt->u32Cookie = BIRD; /** @todo make this random? */
575 pDevExt->cbSession = (uint32_t)cbSession;
576
577 /*
578 * Fixup the absolute symbols.
579 *
580 * Because of the table indexing assumptions we'll have a little #ifdef orgy
581 * here rather than distributing this to OS specific files. At least for now.
582 */
583#ifdef RT_OS_DARWIN
584# if ARCH_BITS == 32
585 if (SUPR0GetPagingMode() >= SUPPAGINGMODE_AMD64)
586 {
587 g_aFunctions[0].pfn = (void *)1; /* SUPR0AbsIs64bit */
588 g_aFunctions[1].pfn = (void *)0x80; /* SUPR0Abs64bitKernelCS - KERNEL64_CS, seg.h */
589 g_aFunctions[2].pfn = (void *)0x88; /* SUPR0Abs64bitKernelSS - KERNEL64_SS, seg.h */
590 g_aFunctions[3].pfn = (void *)0x88; /* SUPR0Abs64bitKernelDS - KERNEL64_SS, seg.h */
591 }
592 else
593 g_aFunctions[0].pfn = g_aFunctions[1].pfn = g_aFunctions[2].pfn = g_aFunctions[3].pfn = (void *)0;
594 g_aFunctions[4].pfn = (void *)0x08; /* SUPR0AbsKernelCS - KERNEL_CS, seg.h */
595 g_aFunctions[5].pfn = (void *)0x10; /* SUPR0AbsKernelSS - KERNEL_DS, seg.h */
596 g_aFunctions[6].pfn = (void *)0x10; /* SUPR0AbsKernelDS - KERNEL_DS, seg.h */
597 g_aFunctions[7].pfn = (void *)0x10; /* SUPR0AbsKernelES - KERNEL_DS, seg.h */
598 g_aFunctions[8].pfn = (void *)0x10; /* SUPR0AbsKernelFS - KERNEL_DS, seg.h */
599 g_aFunctions[9].pfn = (void *)0x48; /* SUPR0AbsKernelGS - CPU_DATA_GS, seg.h */
600# else /* 64-bit darwin: */
601 g_aFunctions[0].pfn = (void *)1; /* SUPR0AbsIs64bit */
602 g_aFunctions[1].pfn = (void *)(uintptr_t)ASMGetCS(); /* SUPR0Abs64bitKernelCS */
603 g_aFunctions[2].pfn = (void *)(uintptr_t)ASMGetSS(); /* SUPR0Abs64bitKernelSS */
604 g_aFunctions[3].pfn = (void *)0; /* SUPR0Abs64bitKernelDS */
605 g_aFunctions[4].pfn = (void *)(uintptr_t)ASMGetCS(); /* SUPR0AbsKernelCS */
606 g_aFunctions[5].pfn = (void *)(uintptr_t)ASMGetSS(); /* SUPR0AbsKernelSS */
607 g_aFunctions[6].pfn = (void *)0; /* SUPR0AbsKernelDS */
608 g_aFunctions[7].pfn = (void *)0; /* SUPR0AbsKernelES */
609 g_aFunctions[8].pfn = (void *)0; /* SUPR0AbsKernelFS */
610 g_aFunctions[9].pfn = (void *)0; /* SUPR0AbsKernelGS */
611
612# endif
613#else /* !RT_OS_DARWIN */
614# if ARCH_BITS == 64
615 g_aFunctions[0].pfn = (void *)1; /* SUPR0AbsIs64bit */
616 g_aFunctions[1].pfn = (void *)(uintptr_t)ASMGetCS(); /* SUPR0Abs64bitKernelCS */
617 g_aFunctions[2].pfn = (void *)(uintptr_t)ASMGetSS(); /* SUPR0Abs64bitKernelSS */
618 g_aFunctions[3].pfn = (void *)(uintptr_t)ASMGetDS(); /* SUPR0Abs64bitKernelDS */
619# else
620 g_aFunctions[0].pfn = g_aFunctions[1].pfn = g_aFunctions[2].pfn = g_aFunctions[3].pfn = (void *)0;
621# endif
622 g_aFunctions[4].pfn = (void *)(uintptr_t)ASMGetCS(); /* SUPR0AbsKernelCS */
623 g_aFunctions[5].pfn = (void *)(uintptr_t)ASMGetSS(); /* SUPR0AbsKernelSS */
624 g_aFunctions[6].pfn = (void *)(uintptr_t)ASMGetDS(); /* SUPR0AbsKernelDS */
625 g_aFunctions[7].pfn = (void *)(uintptr_t)ASMGetES(); /* SUPR0AbsKernelES */
626 g_aFunctions[8].pfn = (void *)(uintptr_t)ASMGetFS(); /* SUPR0AbsKernelFS */
627 g_aFunctions[9].pfn = (void *)(uintptr_t)ASMGetGS(); /* SUPR0AbsKernelGS */
628#endif /* !RT_OS_DARWIN */
629 return VINF_SUCCESS;
630 }
631
632 supdrvGipDestroy(pDevExt);
633 }
634
635#ifdef SUPDRV_USE_MUTEX_FOR_GIP
636 RTSemMutexDestroy(pDevExt->mtxGip);
637 pDevExt->mtxGip = NIL_RTSEMMUTEX;
638#else
639 RTSemFastMutexDestroy(pDevExt->mtxGip);
640 pDevExt->mtxGip = NIL_RTSEMFASTMUTEX;
641#endif
642 }
643 RTSemFastMutexDestroy(pDevExt->mtxComponentFactory);
644 pDevExt->mtxComponentFactory = NIL_RTSEMFASTMUTEX;
645 }
646 }
647
648#ifdef SUPDRV_USE_MUTEX_FOR_GIP
649 RTSemMutexDestroy(pDevExt->mtxTscDelta);
650 pDevExt->mtxTscDelta = NIL_RTSEMMUTEX;
651#else
652 RTSemFastMutexDestroy(pDevExt->mtxTscDelta);
653 pDevExt->mtxTscDelta = NIL_RTSEMFASTMUTEX;
654#endif
655#ifdef SUPDRV_USE_MUTEX_FOR_LDR
656 RTSemMutexDestroy(pDevExt->mtxLdr);
657 pDevExt->mtxLdr = NIL_RTSEMMUTEX;
658#else
659 RTSemFastMutexDestroy(pDevExt->mtxLdr);
660 pDevExt->mtxLdr = NIL_RTSEMFASTMUTEX;
661#endif
662 RTSpinlockDestroy(pDevExt->Spinlock);
663 pDevExt->Spinlock = NIL_RTSPINLOCK;
664 RTSpinlockDestroy(pDevExt->hGipSpinlock);
665 pDevExt->hGipSpinlock = NIL_RTSPINLOCK;
666 RTSpinlockDestroy(pDevExt->hSessionHashTabSpinlock);
667 pDevExt->hSessionHashTabSpinlock = NIL_RTSPINLOCK;
668
669#ifdef SUPDRV_WITH_RELEASE_LOGGER
670 RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
671 RTLogDestroy(RTLogSetDefaultInstance(NULL));
672#endif
673
674 return rc;
675}
676
677
678/**
679 * Delete the device extension (e.g. cleanup members).
680 *
681 * @param pDevExt The device extension to delete.
682 */
683void VBOXCALL supdrvDeleteDevExt(PSUPDRVDEVEXT pDevExt)
684{
685 PSUPDRVOBJ pObj;
686 PSUPDRVUSAGE pUsage;
687
688 /*
689 * Kill mutexes and spinlocks.
690 */
691#ifdef SUPDRV_USE_MUTEX_FOR_GIP
692 RTSemMutexDestroy(pDevExt->mtxGip);
693 pDevExt->mtxGip = NIL_RTSEMMUTEX;
694 RTSemMutexDestroy(pDevExt->mtxTscDelta);
695 pDevExt->mtxTscDelta = NIL_RTSEMMUTEX;
696#else
697 RTSemFastMutexDestroy(pDevExt->mtxGip);
698 pDevExt->mtxGip = NIL_RTSEMFASTMUTEX;
699 RTSemFastMutexDestroy(pDevExt->mtxTscDelta);
700 pDevExt->mtxTscDelta = NIL_RTSEMFASTMUTEX;
701#endif
702#ifdef SUPDRV_USE_MUTEX_FOR_LDR
703 RTSemMutexDestroy(pDevExt->mtxLdr);
704 pDevExt->mtxLdr = NIL_RTSEMMUTEX;
705#else
706 RTSemFastMutexDestroy(pDevExt->mtxLdr);
707 pDevExt->mtxLdr = NIL_RTSEMFASTMUTEX;
708#endif
709 RTSpinlockDestroy(pDevExt->Spinlock);
710 pDevExt->Spinlock = NIL_RTSPINLOCK;
711 RTSemFastMutexDestroy(pDevExt->mtxComponentFactory);
712 pDevExt->mtxComponentFactory = NIL_RTSEMFASTMUTEX;
713 RTSpinlockDestroy(pDevExt->hSessionHashTabSpinlock);
714 pDevExt->hSessionHashTabSpinlock = NIL_RTSPINLOCK;
715
716 /*
717 * Free lists.
718 */
719 /* objects. */
720 pObj = pDevExt->pObjs;
721 Assert(!pObj); /* (can trigger on forced unloads) */
722 pDevExt->pObjs = NULL;
723 while (pObj)
724 {
725 void *pvFree = pObj;
726 pObj = pObj->pNext;
727 RTMemFree(pvFree);
728 }
729
730 /* usage records. */
731 pUsage = pDevExt->pUsageFree;
732 pDevExt->pUsageFree = NULL;
733 while (pUsage)
734 {
735 void *pvFree = pUsage;
736 pUsage = pUsage->pNext;
737 RTMemFree(pvFree);
738 }
739
740 /* kill the GIP. */
741 supdrvGipDestroy(pDevExt);
742 RTSpinlockDestroy(pDevExt->hGipSpinlock);
743 pDevExt->hGipSpinlock = NIL_RTSPINLOCK;
744
745 supdrvTracerTerm(pDevExt);
746
747#ifdef SUPDRV_WITH_RELEASE_LOGGER
748 /* destroy the loggers. */
749 RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
750 RTLogDestroy(RTLogSetDefaultInstance(NULL));
751#endif
752}
753
754
755/**
756 * Create session.
757 *
758 * @returns IPRT status code.
759 * @param pDevExt Device extension.
760 * @param fUser Flag indicating whether this is a user or kernel
761 * session.
762 * @param fUnrestricted Unrestricted access (system) or restricted access
763 * (user)?
764 * @param ppSession Where to store the pointer to the session data.
765 */
766int VBOXCALL supdrvCreateSession(PSUPDRVDEVEXT pDevExt, bool fUser, bool fUnrestricted, PSUPDRVSESSION *ppSession)
767{
768 int rc;
769 PSUPDRVSESSION pSession;
770
771 if (!SUP_IS_DEVEXT_VALID(pDevExt))
772 return VERR_INVALID_PARAMETER;
773
774 /*
775 * Allocate memory for the session data.
776 */
777 pSession = *ppSession = (PSUPDRVSESSION)RTMemAllocZ(pDevExt->cbSession);
778 if (pSession)
779 {
780 /* Initialize session data. */
781 rc = RTSpinlockCreate(&pSession->Spinlock, RTSPINLOCK_FLAGS_INTERRUPT_UNSAFE, "SUPDrvSession");
782 if (!rc)
783 {
784 rc = RTHandleTableCreateEx(&pSession->hHandleTable,
785 RTHANDLETABLE_FLAGS_LOCKED_IRQ_SAFE | RTHANDLETABLE_FLAGS_CONTEXT,
786 1 /*uBase*/, 32768 /*cMax*/, supdrvSessionObjHandleRetain, pSession);
787 if (RT_SUCCESS(rc))
788 {
789 Assert(pSession->Spinlock != NIL_RTSPINLOCK);
790 pSession->pDevExt = pDevExt;
791 pSession->u32Cookie = BIRD_INV;
792 pSession->fUnrestricted = fUnrestricted;
793 /*pSession->fInHashTable = false; */
794 pSession->cRefs = 1;
795 /*pSession->pCommonNextHash = NULL;
796 pSession->ppOsSessionPtr = NULL; */
797 if (fUser)
798 {
799 pSession->Process = RTProcSelf();
800 pSession->R0Process = RTR0ProcHandleSelf();
801 }
802 else
803 {
804 pSession->Process = NIL_RTPROCESS;
805 pSession->R0Process = NIL_RTR0PROCESS;
806 }
807 /*pSession->pLdrUsage = NULL;
808 pSession->pVM = NULL;
809 pSession->pUsage = NULL;
810 pSession->pGip = NULL;
811 pSession->fGipReferenced = false;
812 pSession->Bundle.cUsed = 0; */
813 pSession->Uid = NIL_RTUID;
814 pSession->Gid = NIL_RTGID;
815 /*pSession->uTracerData = 0;*/
816 pSession->hTracerCaller = NIL_RTNATIVETHREAD;
817 RTListInit(&pSession->TpProviders);
818 /*pSession->cTpProviders = 0;*/
819 /*pSession->cTpProbesFiring = 0;*/
820 RTListInit(&pSession->TpUmods);
821 /*RT_ZERO(pSession->apTpLookupTable);*/
822
823 VBOXDRV_SESSION_CREATE(pSession, fUser);
824 LogFlow(("Created session %p initial cookie=%#x\n", pSession, pSession->u32Cookie));
825 return VINF_SUCCESS;
826 }
827
828 RTSpinlockDestroy(pSession->Spinlock);
829 }
830 RTMemFree(pSession);
831 *ppSession = NULL;
832 Log(("Failed to create spinlock, rc=%d!\n", rc));
833 }
834 else
835 rc = VERR_NO_MEMORY;
836
837 return rc;
838}
839
840
841/**
842 * Cleans up the session in the context of the process to which it belongs, the
843 * caller will free the session and the session spinlock.
844 *
845 * This should normally occur when the session is closed or as the process
846 * exits. Careful reference counting in the OS specfic code makes sure that
847 * there cannot be any races between process/handle cleanup callbacks and
848 * threads doing I/O control calls.
849 *
850 * @param pDevExt The device extension.
851 * @param pSession Session data.
852 */
853static void supdrvCleanupSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
854{
855 int rc;
856 PSUPDRVBUNDLE pBundle;
857 LogFlow(("supdrvCleanupSession: pSession=%p\n", pSession));
858
859 Assert(!pSession->fInHashTable);
860 Assert(!pSession->ppOsSessionPtr);
861 AssertLogRelMsg(pSession->R0Process == RTR0ProcHandleSelf() || pSession->R0Process == NIL_RTR0PROCESS,
862 ("R0Process=%p cur=%p; curpid=%u\n",
863 pSession->R0Process, RTR0ProcHandleSelf(), RTProcSelf()));
864
865 /*
866 * Remove logger instances related to this session.
867 */
868 RTLogSetDefaultInstanceThread(NULL, (uintptr_t)pSession);
869
870 /*
871 * Destroy the handle table.
872 */
873 rc = RTHandleTableDestroy(pSession->hHandleTable, supdrvSessionObjHandleDelete, pSession);
874 AssertRC(rc);
875 pSession->hHandleTable = NIL_RTHANDLETABLE;
876
877 /*
878 * Release object references made in this session.
879 * In theory there should be noone racing us in this session.
880 */
881 Log2(("release objects - start\n"));
882 if (pSession->pUsage)
883 {
884 PSUPDRVUSAGE pUsage;
885 RTSpinlockAcquire(pDevExt->Spinlock);
886
887 while ((pUsage = pSession->pUsage) != NULL)
888 {
889 PSUPDRVOBJ pObj = pUsage->pObj;
890 pSession->pUsage = pUsage->pNext;
891
892 AssertMsg(pUsage->cUsage >= 1 && pObj->cUsage >= pUsage->cUsage, ("glob %d; sess %d\n", pObj->cUsage, pUsage->cUsage));
893 if (pUsage->cUsage < pObj->cUsage)
894 {
895 pObj->cUsage -= pUsage->cUsage;
896 RTSpinlockRelease(pDevExt->Spinlock);
897 }
898 else
899 {
900 /* Destroy the object and free the record. */
901 if (pDevExt->pObjs == pObj)
902 pDevExt->pObjs = pObj->pNext;
903 else
904 {
905 PSUPDRVOBJ pObjPrev;
906 for (pObjPrev = pDevExt->pObjs; pObjPrev; pObjPrev = pObjPrev->pNext)
907 if (pObjPrev->pNext == pObj)
908 {
909 pObjPrev->pNext = pObj->pNext;
910 break;
911 }
912 Assert(pObjPrev);
913 }
914 RTSpinlockRelease(pDevExt->Spinlock);
915
916 Log(("supdrvCleanupSession: destroying %p/%d (%p/%p) cpid=%RTproc pid=%RTproc dtor=%p\n",
917 pObj, pObj->enmType, pObj->pvUser1, pObj->pvUser2, pObj->CreatorProcess, RTProcSelf(), pObj->pfnDestructor));
918 if (pObj->pfnDestructor)
919 pObj->pfnDestructor(pObj, pObj->pvUser1, pObj->pvUser2);
920 RTMemFree(pObj);
921 }
922
923 /* free it and continue. */
924 RTMemFree(pUsage);
925
926 RTSpinlockAcquire(pDevExt->Spinlock);
927 }
928
929 RTSpinlockRelease(pDevExt->Spinlock);
930 AssertMsg(!pSession->pUsage, ("Some buster reregistered an object during desturction!\n"));
931 }
932 Log2(("release objects - done\n"));
933
934 /*
935 * Make sure the associated VM pointers are NULL.
936 */
937 if (pSession->pSessionGVM || pSession->pSessionVM || pSession->pFastIoCtrlVM)
938 {
939 SUPR0Printf("supdrvCleanupSession: VM not disassociated! pSessionGVM=%p pSessionVM=%p pFastIoCtrlVM=%p\n",
940 pSession->pSessionGVM, pSession->pSessionVM, pSession->pFastIoCtrlVM);
941 pSession->pSessionGVM = NULL;
942 pSession->pSessionVM = NULL;
943 pSession->pFastIoCtrlVM = NULL;
944 }
945
946 /*
947 * Do tracer cleanups related to this session.
948 */
949 Log2(("release tracer stuff - start\n"));
950 supdrvTracerCleanupSession(pDevExt, pSession);
951 Log2(("release tracer stuff - end\n"));
952
953 /*
954 * Release memory allocated in the session.
955 *
956 * We do not serialize this as we assume that the application will
957 * not allocated memory while closing the file handle object.
958 */
959 Log2(("freeing memory:\n"));
960 pBundle = &pSession->Bundle;
961 while (pBundle)
962 {
963 PSUPDRVBUNDLE pToFree;
964 unsigned i;
965
966 /*
967 * Check and unlock all entries in the bundle.
968 */
969 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
970 {
971 if (pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ)
972 {
973 Log2(("eType=%d pvR0=%p pvR3=%p cb=%ld\n", pBundle->aMem[i].eType, RTR0MemObjAddress(pBundle->aMem[i].MemObj),
974 (void *)RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3), (long)RTR0MemObjSize(pBundle->aMem[i].MemObj)));
975 if (pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ)
976 {
977 rc = RTR0MemObjFree(pBundle->aMem[i].MapObjR3, false);
978 AssertRC(rc); /** @todo figure out how to handle this. */
979 pBundle->aMem[i].MapObjR3 = NIL_RTR0MEMOBJ;
980 }
981 rc = RTR0MemObjFree(pBundle->aMem[i].MemObj, true /* fFreeMappings */);
982 AssertRC(rc); /** @todo figure out how to handle this. */
983 pBundle->aMem[i].MemObj = NIL_RTR0MEMOBJ;
984 pBundle->aMem[i].eType = MEMREF_TYPE_UNUSED;
985 }
986 }
987
988 /*
989 * Advance and free previous bundle.
990 */
991 pToFree = pBundle;
992 pBundle = pBundle->pNext;
993
994 pToFree->pNext = NULL;
995 pToFree->cUsed = 0;
996 if (pToFree != &pSession->Bundle)
997 RTMemFree(pToFree);
998 }
999 Log2(("freeing memory - done\n"));
1000
1001 /*
1002 * Deregister component factories.
1003 */
1004 RTSemFastMutexRequest(pDevExt->mtxComponentFactory);
1005 Log2(("deregistering component factories:\n"));
1006 if (pDevExt->pComponentFactoryHead)
1007 {
1008 PSUPDRVFACTORYREG pPrev = NULL;
1009 PSUPDRVFACTORYREG pCur = pDevExt->pComponentFactoryHead;
1010 while (pCur)
1011 {
1012 if (pCur->pSession == pSession)
1013 {
1014 /* unlink it */
1015 PSUPDRVFACTORYREG pNext = pCur->pNext;
1016 if (pPrev)
1017 pPrev->pNext = pNext;
1018 else
1019 pDevExt->pComponentFactoryHead = pNext;
1020
1021 /* free it */
1022 pCur->pNext = NULL;
1023 pCur->pSession = NULL;
1024 pCur->pFactory = NULL;
1025 RTMemFree(pCur);
1026
1027 /* next */
1028 pCur = pNext;
1029 }
1030 else
1031 {
1032 /* next */
1033 pPrev = pCur;
1034 pCur = pCur->pNext;
1035 }
1036 }
1037 }
1038 RTSemFastMutexRelease(pDevExt->mtxComponentFactory);
1039 Log2(("deregistering component factories - done\n"));
1040
1041 /*
1042 * Loaded images needs to be dereferenced and possibly freed up.
1043 */
1044 supdrvLdrLock(pDevExt);
1045 Log2(("freeing images:\n"));
1046 if (pSession->pLdrUsage)
1047 {
1048 PSUPDRVLDRUSAGE pUsage = pSession->pLdrUsage;
1049 pSession->pLdrUsage = NULL;
1050 while (pUsage)
1051 {
1052 void *pvFree = pUsage;
1053 PSUPDRVLDRIMAGE pImage = pUsage->pImage;
1054 if (pImage->cUsage > pUsage->cUsage)
1055 pImage->cUsage -= pUsage->cUsage;
1056 else
1057 supdrvLdrFree(pDevExt, pImage);
1058 pUsage->pImage = NULL;
1059 pUsage = pUsage->pNext;
1060 RTMemFree(pvFree);
1061 }
1062 }
1063 supdrvLdrUnlock(pDevExt);
1064 Log2(("freeing images - done\n"));
1065
1066 /*
1067 * Unmap the GIP.
1068 */
1069 Log2(("umapping GIP:\n"));
1070 if (pSession->GipMapObjR3 != NIL_RTR0MEMOBJ)
1071 {
1072 SUPR0GipUnmap(pSession);
1073 pSession->fGipReferenced = 0;
1074 }
1075 Log2(("umapping GIP - done\n"));
1076}
1077
1078
1079/**
1080 * Common code for freeing a session when the reference count reaches zero.
1081 *
1082 * @param pDevExt Device extension.
1083 * @param pSession Session data.
1084 * This data will be freed by this routine.
1085 */
1086static void supdrvDestroySession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
1087{
1088 VBOXDRV_SESSION_CLOSE(pSession);
1089
1090 /*
1091 * Cleanup the session first.
1092 */
1093 supdrvCleanupSession(pDevExt, pSession);
1094 supdrvOSCleanupSession(pDevExt, pSession);
1095
1096 /*
1097 * Free the rest of the session stuff.
1098 */
1099 RTSpinlockDestroy(pSession->Spinlock);
1100 pSession->Spinlock = NIL_RTSPINLOCK;
1101 pSession->pDevExt = NULL;
1102 RTMemFree(pSession);
1103 LogFlow(("supdrvDestroySession: returns\n"));
1104}
1105
1106
1107/**
1108 * Inserts the session into the global hash table.
1109 *
1110 * @retval VINF_SUCCESS on success.
1111 * @retval VERR_WRONG_ORDER if the session was already inserted (asserted).
1112 * @retval VERR_INVALID_PARAMETER if the session handle is invalid or a ring-0
1113 * session (asserted).
1114 * @retval VERR_DUPLICATE if there is already a session for that pid.
1115 *
1116 * @param pDevExt The device extension.
1117 * @param pSession The session.
1118 * @param ppOsSessionPtr Pointer to the OS session pointer, if any is
1119 * available and used. This will set to point to the
1120 * session while under the protection of the session
1121 * hash table spinlock. It will also be kept in
1122 * PSUPDRVSESSION::ppOsSessionPtr for lookup and
1123 * cleanup use.
1124 * @param pvUser Argument for supdrvOSSessionHashTabInserted.
1125 */
1126int VBOXCALL supdrvSessionHashTabInsert(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVSESSION *ppOsSessionPtr,
1127 void *pvUser)
1128{
1129 PSUPDRVSESSION pCur;
1130 unsigned iHash;
1131
1132 /*
1133 * Validate input.
1134 */
1135 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1136 AssertReturn(pSession->R0Process != NIL_RTR0PROCESS, VERR_INVALID_PARAMETER);
1137
1138 /*
1139 * Calculate the hash table index and acquire the spinlock.
1140 */
1141 iHash = SUPDRV_SESSION_HASH(pSession->Process);
1142
1143 RTSpinlockAcquire(pDevExt->hSessionHashTabSpinlock);
1144
1145 /*
1146 * If there are a collisions, we need to carefully check if we got a
1147 * duplicate. There can only be one open session per process.
1148 */
1149 pCur = pDevExt->apSessionHashTab[iHash];
1150 if (pCur)
1151 {
1152 while (pCur && pCur->Process != pSession->Process)
1153 pCur = pCur->pCommonNextHash;
1154
1155 if (pCur)
1156 {
1157 RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
1158 if (pCur == pSession)
1159 {
1160 Assert(pSession->fInHashTable);
1161 AssertFailed();
1162 return VERR_WRONG_ORDER;
1163 }
1164 Assert(!pSession->fInHashTable);
1165 if (pCur->R0Process == pSession->R0Process)
1166 return VERR_RESOURCE_IN_USE;
1167 return VERR_DUPLICATE;
1168 }
1169 }
1170 Assert(!pSession->fInHashTable);
1171 Assert(!pSession->ppOsSessionPtr);
1172
1173 /*
1174 * Insert it, doing a callout to the OS specific code in case it has
1175 * anything it wishes to do while we're holding the spinlock.
1176 */
1177 pSession->pCommonNextHash = pDevExt->apSessionHashTab[iHash];
1178 pDevExt->apSessionHashTab[iHash] = pSession;
1179 pSession->fInHashTable = true;
1180 ASMAtomicIncS32(&pDevExt->cSessions);
1181
1182 pSession->ppOsSessionPtr = ppOsSessionPtr;
1183 if (ppOsSessionPtr)
1184 ASMAtomicWritePtr(ppOsSessionPtr, pSession);
1185
1186 supdrvOSSessionHashTabInserted(pDevExt, pSession, pvUser);
1187
1188 /*
1189 * Retain a reference for the pointer in the session table.
1190 */
1191 ASMAtomicIncU32(&pSession->cRefs);
1192
1193 RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
1194 return VINF_SUCCESS;
1195}
1196
1197
1198/**
1199 * Removes the session from the global hash table.
1200 *
1201 * @retval VINF_SUCCESS on success.
1202 * @retval VERR_NOT_FOUND if the session was already removed (asserted).
1203 * @retval VERR_INVALID_PARAMETER if the session handle is invalid or a ring-0
1204 * session (asserted).
1205 *
1206 * @param pDevExt The device extension.
1207 * @param pSession The session. The caller is expected to have a reference
1208 * to this so it won't croak on us when we release the hash
1209 * table reference.
1210 * @param pvUser OS specific context value for the
1211 * supdrvOSSessionHashTabInserted callback.
1212 */
1213int VBOXCALL supdrvSessionHashTabRemove(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
1214{
1215 PSUPDRVSESSION pCur;
1216 unsigned iHash;
1217 int32_t cRefs;
1218
1219 /*
1220 * Validate input.
1221 */
1222 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1223 AssertReturn(pSession->R0Process != NIL_RTR0PROCESS, VERR_INVALID_PARAMETER);
1224
1225 /*
1226 * Calculate the hash table index and acquire the spinlock.
1227 */
1228 iHash = SUPDRV_SESSION_HASH(pSession->Process);
1229
1230 RTSpinlockAcquire(pDevExt->hSessionHashTabSpinlock);
1231
1232 /*
1233 * Unlink it.
1234 */
1235 pCur = pDevExt->apSessionHashTab[iHash];
1236 if (pCur == pSession)
1237 pDevExt->apSessionHashTab[iHash] = pSession->pCommonNextHash;
1238 else
1239 {
1240 PSUPDRVSESSION pPrev = pCur;
1241 while (pCur && pCur != pSession)
1242 {
1243 pPrev = pCur;
1244 pCur = pCur->pCommonNextHash;
1245 }
1246 if (pCur)
1247 pPrev->pCommonNextHash = pCur->pCommonNextHash;
1248 else
1249 {
1250 Assert(!pSession->fInHashTable);
1251 RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
1252 return VERR_NOT_FOUND;
1253 }
1254 }
1255
1256 pSession->pCommonNextHash = NULL;
1257 pSession->fInHashTable = false;
1258
1259 ASMAtomicDecS32(&pDevExt->cSessions);
1260
1261 /*
1262 * Clear OS specific session pointer if available and do the OS callback.
1263 */
1264 if (pSession->ppOsSessionPtr)
1265 {
1266 ASMAtomicCmpXchgPtr(pSession->ppOsSessionPtr, NULL, pSession);
1267 pSession->ppOsSessionPtr = NULL;
1268 }
1269
1270 supdrvOSSessionHashTabRemoved(pDevExt, pSession, pvUser);
1271
1272 RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
1273
1274 /*
1275 * Drop the reference the hash table had to the session. This shouldn't
1276 * be the last reference!
1277 */
1278 cRefs = ASMAtomicDecU32(&pSession->cRefs);
1279 Assert(cRefs > 0 && cRefs < _1M);
1280 if (cRefs == 0)
1281 supdrvDestroySession(pDevExt, pSession);
1282
1283 return VINF_SUCCESS;
1284}
1285
1286
1287/**
1288 * Looks up the session for the current process in the global hash table or in
1289 * OS specific pointer.
1290 *
1291 * @returns Pointer to the session with a reference that the caller must
1292 * release. If no valid session was found, NULL is returned.
1293 *
1294 * @param pDevExt The device extension.
1295 * @param Process The process ID.
1296 * @param R0Process The ring-0 process handle.
1297 * @param ppOsSessionPtr The OS session pointer if available. If not NULL,
1298 * this is used instead of the hash table. For
1299 * additional safety it must then be equal to the
1300 * SUPDRVSESSION::ppOsSessionPtr member.
1301 * This can be NULL even if the OS has a session
1302 * pointer.
1303 */
1304PSUPDRVSESSION VBOXCALL supdrvSessionHashTabLookup(PSUPDRVDEVEXT pDevExt, RTPROCESS Process, RTR0PROCESS R0Process,
1305 PSUPDRVSESSION *ppOsSessionPtr)
1306{
1307 PSUPDRVSESSION pCur;
1308 unsigned iHash;
1309
1310 /*
1311 * Validate input.
1312 */
1313 AssertReturn(R0Process != NIL_RTR0PROCESS, NULL);
1314
1315 /*
1316 * Calculate the hash table index and acquire the spinlock.
1317 */
1318 iHash = SUPDRV_SESSION_HASH(Process);
1319
1320 RTSpinlockAcquire(pDevExt->hSessionHashTabSpinlock);
1321
1322 /*
1323 * If an OS session pointer is provided, always use it.
1324 */
1325 if (ppOsSessionPtr)
1326 {
1327 pCur = *ppOsSessionPtr;
1328 if ( pCur
1329 && ( pCur->ppOsSessionPtr != ppOsSessionPtr
1330 || pCur->Process != Process
1331 || pCur->R0Process != R0Process) )
1332 pCur = NULL;
1333 }
1334 else
1335 {
1336 /*
1337 * Otherwise, do the hash table lookup.
1338 */
1339 pCur = pDevExt->apSessionHashTab[iHash];
1340 while ( pCur
1341 && ( pCur->Process != Process
1342 || pCur->R0Process != R0Process) )
1343 pCur = pCur->pCommonNextHash;
1344 }
1345
1346 /*
1347 * Retain the session.
1348 */
1349 if (pCur)
1350 {
1351 uint32_t cRefs = ASMAtomicIncU32(&pCur->cRefs);
1352 NOREF(cRefs);
1353 Assert(cRefs > 1 && cRefs < _1M);
1354 }
1355
1356 RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
1357
1358 return pCur;
1359}
1360
1361
1362/**
1363 * Retain a session to make sure it doesn't go away while it is in use.
1364 *
1365 * @returns New reference count on success, UINT32_MAX on failure.
1366 * @param pSession Session data.
1367 */
1368uint32_t VBOXCALL supdrvSessionRetain(PSUPDRVSESSION pSession)
1369{
1370 uint32_t cRefs;
1371 AssertPtrReturn(pSession, UINT32_MAX);
1372 AssertReturn(SUP_IS_SESSION_VALID(pSession), UINT32_MAX);
1373
1374 cRefs = ASMAtomicIncU32(&pSession->cRefs);
1375 AssertMsg(cRefs > 1 && cRefs < _1M, ("%#x %p\n", cRefs, pSession));
1376 return cRefs;
1377}
1378
1379
1380/**
1381 * Releases a given session.
1382 *
1383 * @returns New reference count on success (0 if closed), UINT32_MAX on failure.
1384 * @param pSession Session data.
1385 */
1386uint32_t VBOXCALL supdrvSessionRelease(PSUPDRVSESSION pSession)
1387{
1388 uint32_t cRefs;
1389 AssertPtrReturn(pSession, UINT32_MAX);
1390 AssertReturn(SUP_IS_SESSION_VALID(pSession), UINT32_MAX);
1391
1392 cRefs = ASMAtomicDecU32(&pSession->cRefs);
1393 AssertMsg(cRefs < _1M, ("%#x %p\n", cRefs, pSession));
1394 if (cRefs == 0)
1395 supdrvDestroySession(pSession->pDevExt, pSession);
1396 return cRefs;
1397}
1398
1399
1400/**
1401 * RTHandleTableDestroy callback used by supdrvCleanupSession.
1402 *
1403 * @returns IPRT status code, see SUPR0ObjAddRef.
1404 * @param hHandleTable The handle table handle. Ignored.
1405 * @param pvObj The object pointer.
1406 * @param pvCtx Context, the handle type. Ignored.
1407 * @param pvUser Session pointer.
1408 */
1409static DECLCALLBACK(int) supdrvSessionObjHandleRetain(RTHANDLETABLE hHandleTable, void *pvObj, void *pvCtx, void *pvUser)
1410{
1411 NOREF(pvCtx);
1412 NOREF(hHandleTable);
1413 return SUPR0ObjAddRefEx(pvObj, (PSUPDRVSESSION)pvUser, true /*fNoBlocking*/);
1414}
1415
1416
1417/**
1418 * RTHandleTableDestroy callback used by supdrvCleanupSession.
1419 *
1420 * @param hHandleTable The handle table handle. Ignored.
1421 * @param h The handle value. Ignored.
1422 * @param pvObj The object pointer.
1423 * @param pvCtx Context, the handle type. Ignored.
1424 * @param pvUser Session pointer.
1425 */
1426static DECLCALLBACK(void) supdrvSessionObjHandleDelete(RTHANDLETABLE hHandleTable, uint32_t h, void *pvObj, void *pvCtx, void *pvUser)
1427{
1428 NOREF(pvCtx);
1429 NOREF(h);
1430 NOREF(hHandleTable);
1431 SUPR0ObjRelease(pvObj, (PSUPDRVSESSION)pvUser);
1432}
1433
1434
1435/**
1436 * Fast path I/O Control worker.
1437 *
1438 * @returns VBox status code that should be passed down to ring-3 unchanged.
1439 * @param uOperation SUP_VMMR0_DO_XXX (not the I/O control number!).
1440 * @param idCpu VMCPU id.
1441 * @param pDevExt Device extention.
1442 * @param pSession Session data.
1443 */
1444int VBOXCALL supdrvIOCtlFast(uintptr_t uOperation, VMCPUID idCpu, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
1445{
1446 /*
1447 * Validate input and check that the VM has a session.
1448 */
1449 if (RT_LIKELY(RT_VALID_PTR(pSession)))
1450 {
1451 PVM pVM = pSession->pSessionVM;
1452 PGVM pGVM = pSession->pSessionGVM;
1453 if (RT_LIKELY( pGVM != NULL
1454 && pVM != NULL
1455 && pVM == pSession->pFastIoCtrlVM))
1456 {
1457 if (RT_LIKELY(pDevExt->pfnVMMR0EntryFast))
1458 {
1459 /*
1460 * Make the call.
1461 */
1462 pDevExt->pfnVMMR0EntryFast(pGVM, pVM, idCpu, uOperation);
1463 return VINF_SUCCESS;
1464 }
1465
1466 SUPR0Printf("supdrvIOCtlFast: pfnVMMR0EntryFast is NULL\n");
1467 }
1468 else
1469 SUPR0Printf("supdrvIOCtlFast: Misconfig session: pGVM=%p pVM=%p pFastIoCtrlVM=%p\n",
1470 pGVM, pVM, pSession->pFastIoCtrlVM);
1471 }
1472 else
1473 SUPR0Printf("supdrvIOCtlFast: Bad session pointer %p\n", pSession);
1474 return VERR_INTERNAL_ERROR;
1475}
1476
1477
1478/**
1479 * Helper for supdrvIOCtl used to validate module names passed to SUP_IOCTL_LDR_OPEN.
1480 *
1481 * Check if pszStr contains any character of pszChars. We would use strpbrk
1482 * here if this function would be contained in the RedHat kABI white list, see
1483 * http://www.kerneldrivers.org/RHEL5.
1484 *
1485 * @returns true if fine, false if not.
1486 * @param pszName The module name to check.
1487 */
1488static bool supdrvIsLdrModuleNameValid(const char *pszName)
1489{
1490 int chCur;
1491 while ((chCur = *pszName++) != '\0')
1492 {
1493 static const char s_szInvalidChars[] = ";:()[]{}/\\|&*%#@!~`\"'";
1494 unsigned offInv = RT_ELEMENTS(s_szInvalidChars);
1495 while (offInv-- > 0)
1496 if (s_szInvalidChars[offInv] == chCur)
1497 return false;
1498 }
1499 return true;
1500}
1501
1502
1503
1504/**
1505 * I/O Control inner worker (tracing reasons).
1506 *
1507 * @returns IPRT status code.
1508 * @retval VERR_INVALID_PARAMETER if the request is invalid.
1509 *
1510 * @param uIOCtl Function number.
1511 * @param pDevExt Device extention.
1512 * @param pSession Session data.
1513 * @param pReqHdr The request header.
1514 */
1515static int supdrvIOCtlInnerUnrestricted(uintptr_t uIOCtl, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPREQHDR pReqHdr)
1516{
1517 /*
1518 * Validation macros
1519 */
1520#define REQ_CHECK_SIZES_EX(Name, cbInExpect, cbOutExpect) \
1521 do { \
1522 if (RT_UNLIKELY(pReqHdr->cbIn != (cbInExpect) || pReqHdr->cbOut != (cbOutExpect))) \
1523 { \
1524 OSDBGPRINT(( #Name ": Invalid input/output sizes. cbIn=%ld expected %ld. cbOut=%ld expected %ld.\n", \
1525 (long)pReqHdr->cbIn, (long)(cbInExpect), (long)pReqHdr->cbOut, (long)(cbOutExpect))); \
1526 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
1527 } \
1528 } while (0)
1529
1530#define REQ_CHECK_SIZES(Name) REQ_CHECK_SIZES_EX(Name, Name ## _SIZE_IN, Name ## _SIZE_OUT)
1531
1532#define REQ_CHECK_SIZE_IN(Name, cbInExpect) \
1533 do { \
1534 if (RT_UNLIKELY(pReqHdr->cbIn != (cbInExpect))) \
1535 { \
1536 OSDBGPRINT(( #Name ": Invalid input/output sizes. cbIn=%ld expected %ld.\n", \
1537 (long)pReqHdr->cbIn, (long)(cbInExpect))); \
1538 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
1539 } \
1540 } while (0)
1541
1542#define REQ_CHECK_SIZE_OUT(Name, cbOutExpect) \
1543 do { \
1544 if (RT_UNLIKELY(pReqHdr->cbOut != (cbOutExpect))) \
1545 { \
1546 OSDBGPRINT(( #Name ": Invalid input/output sizes. cbOut=%ld expected %ld.\n", \
1547 (long)pReqHdr->cbOut, (long)(cbOutExpect))); \
1548 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
1549 } \
1550 } while (0)
1551
1552#define REQ_CHECK_EXPR(Name, expr) \
1553 do { \
1554 if (RT_UNLIKELY(!(expr))) \
1555 { \
1556 OSDBGPRINT(( #Name ": %s\n", #expr)); \
1557 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
1558 } \
1559 } while (0)
1560
1561#define REQ_CHECK_EXPR_FMT(expr, fmt) \
1562 do { \
1563 if (RT_UNLIKELY(!(expr))) \
1564 { \
1565 OSDBGPRINT( fmt ); \
1566 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
1567 } \
1568 } while (0)
1569
1570 /*
1571 * The switch.
1572 */
1573 switch (SUP_CTL_CODE_NO_SIZE(uIOCtl))
1574 {
1575 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_COOKIE):
1576 {
1577 PSUPCOOKIE pReq = (PSUPCOOKIE)pReqHdr;
1578 REQ_CHECK_SIZES(SUP_IOCTL_COOKIE);
1579 if (strncmp(pReq->u.In.szMagic, SUPCOOKIE_MAGIC, sizeof(pReq->u.In.szMagic)))
1580 {
1581 OSDBGPRINT(("SUP_IOCTL_COOKIE: invalid magic %.16s\n", pReq->u.In.szMagic));
1582 pReq->Hdr.rc = VERR_INVALID_MAGIC;
1583 return 0;
1584 }
1585
1586#if 0
1587 /*
1588 * Call out to the OS specific code and let it do permission checks on the
1589 * client process.
1590 */
1591 if (!supdrvOSValidateClientProcess(pDevExt, pSession))
1592 {
1593 pReq->u.Out.u32Cookie = 0xffffffff;
1594 pReq->u.Out.u32SessionCookie = 0xffffffff;
1595 pReq->u.Out.u32SessionVersion = 0xffffffff;
1596 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
1597 pReq->u.Out.pSession = NULL;
1598 pReq->u.Out.cFunctions = 0;
1599 pReq->Hdr.rc = VERR_PERMISSION_DENIED;
1600 return 0;
1601 }
1602#endif
1603
1604 /*
1605 * Match the version.
1606 * The current logic is very simple, match the major interface version.
1607 */
1608 if ( pReq->u.In.u32MinVersion > SUPDRV_IOC_VERSION
1609 || (pReq->u.In.u32MinVersion & 0xffff0000) != (SUPDRV_IOC_VERSION & 0xffff0000))
1610 {
1611 OSDBGPRINT(("SUP_IOCTL_COOKIE: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
1612 pReq->u.In.u32ReqVersion, pReq->u.In.u32MinVersion, SUPDRV_IOC_VERSION));
1613 pReq->u.Out.u32Cookie = 0xffffffff;
1614 pReq->u.Out.u32SessionCookie = 0xffffffff;
1615 pReq->u.Out.u32SessionVersion = 0xffffffff;
1616 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
1617 pReq->u.Out.pSession = NULL;
1618 pReq->u.Out.cFunctions = 0;
1619 pReq->Hdr.rc = VERR_VERSION_MISMATCH;
1620 return 0;
1621 }
1622
1623 /*
1624 * Fill in return data and be gone.
1625 * N.B. The first one to change SUPDRV_IOC_VERSION shall makes sure that
1626 * u32SessionVersion <= u32ReqVersion!
1627 */
1628 /** @todo Somehow validate the client and negotiate a secure cookie... */
1629 pReq->u.Out.u32Cookie = pDevExt->u32Cookie;
1630 pReq->u.Out.u32SessionCookie = pSession->u32Cookie;
1631 pReq->u.Out.u32SessionVersion = SUPDRV_IOC_VERSION;
1632 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
1633 pReq->u.Out.pSession = pSession;
1634 pReq->u.Out.cFunctions = sizeof(g_aFunctions) / sizeof(g_aFunctions[0]);
1635 pReq->Hdr.rc = VINF_SUCCESS;
1636 return 0;
1637 }
1638
1639 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_QUERY_FUNCS(0)):
1640 {
1641 /* validate */
1642 PSUPQUERYFUNCS pReq = (PSUPQUERYFUNCS)pReqHdr;
1643 REQ_CHECK_SIZES_EX(SUP_IOCTL_QUERY_FUNCS, SUP_IOCTL_QUERY_FUNCS_SIZE_IN, SUP_IOCTL_QUERY_FUNCS_SIZE_OUT(RT_ELEMENTS(g_aFunctions)));
1644
1645 /* execute */
1646 pReq->u.Out.cFunctions = RT_ELEMENTS(g_aFunctions);
1647 memcpy(&pReq->u.Out.aFunctions[0], g_aFunctions, sizeof(g_aFunctions));
1648 pReq->Hdr.rc = VINF_SUCCESS;
1649 return 0;
1650 }
1651
1652 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_LOCK):
1653 {
1654 /* validate */
1655 PSUPPAGELOCK pReq = (PSUPPAGELOCK)pReqHdr;
1656 REQ_CHECK_SIZE_IN(SUP_IOCTL_PAGE_LOCK, SUP_IOCTL_PAGE_LOCK_SIZE_IN);
1657 REQ_CHECK_SIZE_OUT(SUP_IOCTL_PAGE_LOCK, SUP_IOCTL_PAGE_LOCK_SIZE_OUT(pReq->u.In.cPages));
1658 REQ_CHECK_EXPR(SUP_IOCTL_PAGE_LOCK, pReq->u.In.cPages > 0);
1659 REQ_CHECK_EXPR(SUP_IOCTL_PAGE_LOCK, pReq->u.In.pvR3 >= PAGE_SIZE);
1660
1661 /* execute */
1662 pReq->Hdr.rc = SUPR0LockMem(pSession, pReq->u.In.pvR3, pReq->u.In.cPages, &pReq->u.Out.aPages[0]);
1663 if (RT_FAILURE(pReq->Hdr.rc))
1664 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
1665 return 0;
1666 }
1667
1668 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_UNLOCK):
1669 {
1670 /* validate */
1671 PSUPPAGEUNLOCK pReq = (PSUPPAGEUNLOCK)pReqHdr;
1672 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_UNLOCK);
1673
1674 /* execute */
1675 pReq->Hdr.rc = SUPR0UnlockMem(pSession, pReq->u.In.pvR3);
1676 return 0;
1677 }
1678
1679 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CONT_ALLOC):
1680 {
1681 /* validate */
1682 PSUPCONTALLOC pReq = (PSUPCONTALLOC)pReqHdr;
1683 REQ_CHECK_SIZES(SUP_IOCTL_CONT_ALLOC);
1684
1685 /* execute */
1686 pReq->Hdr.rc = SUPR0ContAlloc(pSession, pReq->u.In.cPages, &pReq->u.Out.pvR0, &pReq->u.Out.pvR3, &pReq->u.Out.HCPhys);
1687 if (RT_FAILURE(pReq->Hdr.rc))
1688 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
1689 return 0;
1690 }
1691
1692 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CONT_FREE):
1693 {
1694 /* validate */
1695 PSUPCONTFREE pReq = (PSUPCONTFREE)pReqHdr;
1696 REQ_CHECK_SIZES(SUP_IOCTL_CONT_FREE);
1697
1698 /* execute */
1699 pReq->Hdr.rc = SUPR0ContFree(pSession, (RTHCUINTPTR)pReq->u.In.pvR3);
1700 return 0;
1701 }
1702
1703 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_OPEN):
1704 {
1705 /* validate */
1706 PSUPLDROPEN pReq = (PSUPLDROPEN)pReqHdr;
1707 REQ_CHECK_SIZES(SUP_IOCTL_LDR_OPEN);
1708 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.cbImageWithTabs > 0);
1709 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.cbImageWithTabs < 16*_1M);
1710 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.cbImageBits > 0);
1711 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.cbImageBits > 0);
1712 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.cbImageBits < pReq->u.In.cbImageWithTabs);
1713 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.szName[0]);
1714 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, RTStrEnd(pReq->u.In.szName, sizeof(pReq->u.In.szName)));
1715 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, supdrvIsLdrModuleNameValid(pReq->u.In.szName));
1716 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, RTStrEnd(pReq->u.In.szFilename, sizeof(pReq->u.In.szFilename)));
1717
1718 /* execute */
1719 pReq->Hdr.rc = supdrvIOCtl_LdrOpen(pDevExt, pSession, pReq);
1720 return 0;
1721 }
1722
1723 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_LOAD):
1724 {
1725 /* validate */
1726 PSUPLDRLOAD pReq = (PSUPLDRLOAD)pReqHdr;
1727 REQ_CHECK_EXPR(Name, pReq->Hdr.cbIn >= SUP_IOCTL_LDR_LOAD_SIZE_IN(32));
1728 REQ_CHECK_SIZES_EX(SUP_IOCTL_LDR_LOAD, SUP_IOCTL_LDR_LOAD_SIZE_IN(pReq->u.In.cbImageWithTabs), SUP_IOCTL_LDR_LOAD_SIZE_OUT);
1729 REQ_CHECK_EXPR(SUP_IOCTL_LDR_LOAD, pReq->u.In.cSymbols <= 16384);
1730 REQ_CHECK_EXPR_FMT( !pReq->u.In.cSymbols
1731 || ( pReq->u.In.offSymbols < pReq->u.In.cbImageWithTabs
1732 && pReq->u.In.offSymbols + pReq->u.In.cSymbols * sizeof(SUPLDRSYM) <= pReq->u.In.cbImageWithTabs),
1733 ("SUP_IOCTL_LDR_LOAD: offSymbols=%#lx cSymbols=%#lx cbImageWithTabs=%#lx\n", (long)pReq->u.In.offSymbols,
1734 (long)pReq->u.In.cSymbols, (long)pReq->u.In.cbImageWithTabs));
1735 REQ_CHECK_EXPR_FMT( !pReq->u.In.cbStrTab
1736 || ( pReq->u.In.offStrTab < pReq->u.In.cbImageWithTabs
1737 && pReq->u.In.offStrTab + pReq->u.In.cbStrTab <= pReq->u.In.cbImageWithTabs
1738 && pReq->u.In.cbStrTab <= pReq->u.In.cbImageWithTabs),
1739 ("SUP_IOCTL_LDR_LOAD: offStrTab=%#lx cbStrTab=%#lx cbImageWithTabs=%#lx\n", (long)pReq->u.In.offStrTab,
1740 (long)pReq->u.In.cbStrTab, (long)pReq->u.In.cbImageWithTabs));
1741
1742 if (pReq->u.In.cSymbols)
1743 {
1744 uint32_t i;
1745 PSUPLDRSYM paSyms = (PSUPLDRSYM)&pReq->u.In.abImage[pReq->u.In.offSymbols];
1746 for (i = 0; i < pReq->u.In.cSymbols; i++)
1747 {
1748 REQ_CHECK_EXPR_FMT(paSyms[i].offSymbol < pReq->u.In.cbImageWithTabs,
1749 ("SUP_IOCTL_LDR_LOAD: sym #%ld: symb off %#lx (max=%#lx)\n", (long)i, (long)paSyms[i].offSymbol, (long)pReq->u.In.cbImageWithTabs));
1750 REQ_CHECK_EXPR_FMT(paSyms[i].offName < pReq->u.In.cbStrTab,
1751 ("SUP_IOCTL_LDR_LOAD: sym #%ld: name off %#lx (max=%#lx)\n", (long)i, (long)paSyms[i].offName, (long)pReq->u.In.cbImageWithTabs));
1752 REQ_CHECK_EXPR_FMT(RTStrEnd((char const *)&pReq->u.In.abImage[pReq->u.In.offStrTab + paSyms[i].offName],
1753 pReq->u.In.cbStrTab - paSyms[i].offName),
1754 ("SUP_IOCTL_LDR_LOAD: sym #%ld: unterminated name! (%#lx / %#lx)\n", (long)i, (long)paSyms[i].offName, (long)pReq->u.In.cbImageWithTabs));
1755 }
1756 }
1757
1758 /* execute */
1759 pReq->Hdr.rc = supdrvIOCtl_LdrLoad(pDevExt, pSession, pReq);
1760 return 0;
1761 }
1762
1763 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_FREE):
1764 {
1765 /* validate */
1766 PSUPLDRFREE pReq = (PSUPLDRFREE)pReqHdr;
1767 REQ_CHECK_SIZES(SUP_IOCTL_LDR_FREE);
1768
1769 /* execute */
1770 pReq->Hdr.rc = supdrvIOCtl_LdrFree(pDevExt, pSession, pReq);
1771 return 0;
1772 }
1773
1774 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_LOCK_DOWN):
1775 {
1776 /* validate */
1777 REQ_CHECK_SIZES(SUP_IOCTL_LDR_LOCK_DOWN);
1778
1779 /* execute */
1780 pReqHdr->rc = supdrvIOCtl_LdrLockDown(pDevExt);
1781 return 0;
1782 }
1783
1784 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_GET_SYMBOL):
1785 {
1786 /* validate */
1787 PSUPLDRGETSYMBOL pReq = (PSUPLDRGETSYMBOL)pReqHdr;
1788 REQ_CHECK_SIZES(SUP_IOCTL_LDR_GET_SYMBOL);
1789 REQ_CHECK_EXPR(SUP_IOCTL_LDR_GET_SYMBOL, RTStrEnd(pReq->u.In.szSymbol, sizeof(pReq->u.In.szSymbol)));
1790
1791 /* execute */
1792 pReq->Hdr.rc = supdrvIOCtl_LdrGetSymbol(pDevExt, pSession, pReq);
1793 return 0;
1794 }
1795
1796 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CALL_VMMR0_NO_SIZE()):
1797 {
1798 /* validate */
1799 PSUPCALLVMMR0 pReq = (PSUPCALLVMMR0)pReqHdr;
1800 Log4(("SUP_IOCTL_CALL_VMMR0: op=%u in=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1801 pReq->u.In.uOperation, pReq->Hdr.cbIn, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1802
1803 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_VMMR0_SIZE(0))
1804 {
1805 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_VMMR0, SUP_IOCTL_CALL_VMMR0_SIZE_IN(0), SUP_IOCTL_CALL_VMMR0_SIZE_OUT(0));
1806
1807 /* execute */
1808 if (RT_LIKELY(pDevExt->pfnVMMR0EntryEx))
1809 {
1810 if (pReq->u.In.pVMR0 == NULL)
1811 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(NULL, NULL, pReq->u.In.idCpu,
1812 pReq->u.In.uOperation, NULL, pReq->u.In.u64Arg, pSession);
1813 else if (pReq->u.In.pVMR0 == pSession->pSessionVM)
1814 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(pSession->pSessionGVM, pSession->pSessionVM, pReq->u.In.idCpu,
1815 pReq->u.In.uOperation, NULL, pReq->u.In.u64Arg, pSession);
1816 else
1817 pReq->Hdr.rc = VERR_INVALID_VM_HANDLE;
1818 }
1819 else
1820 pReq->Hdr.rc = VERR_WRONG_ORDER;
1821 }
1822 else
1823 {
1824 PSUPVMMR0REQHDR pVMMReq = (PSUPVMMR0REQHDR)&pReq->abReqPkt[0];
1825 REQ_CHECK_EXPR_FMT(pReq->Hdr.cbIn >= SUP_IOCTL_CALL_VMMR0_SIZE(sizeof(SUPVMMR0REQHDR)),
1826 ("SUP_IOCTL_CALL_VMMR0: cbIn=%#x < %#lx\n", pReq->Hdr.cbIn, SUP_IOCTL_CALL_VMMR0_SIZE(sizeof(SUPVMMR0REQHDR))));
1827 REQ_CHECK_EXPR(SUP_IOCTL_CALL_VMMR0, pVMMReq->u32Magic == SUPVMMR0REQHDR_MAGIC);
1828 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_VMMR0, SUP_IOCTL_CALL_VMMR0_SIZE_IN(pVMMReq->cbReq), SUP_IOCTL_CALL_VMMR0_SIZE_OUT(pVMMReq->cbReq));
1829
1830 /* execute */
1831 if (RT_LIKELY(pDevExt->pfnVMMR0EntryEx))
1832 {
1833 if (pReq->u.In.pVMR0 == NULL)
1834 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(NULL, NULL, pReq->u.In.idCpu,
1835 pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg, pSession);
1836 else if (pReq->u.In.pVMR0 == pSession->pSessionVM)
1837 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(pSession->pSessionGVM, pSession->pSessionVM, pReq->u.In.idCpu,
1838 pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg, pSession);
1839 else
1840 pReq->Hdr.rc = VERR_INVALID_VM_HANDLE;
1841 }
1842 else
1843 pReq->Hdr.rc = VERR_WRONG_ORDER;
1844 }
1845
1846 if ( RT_FAILURE(pReq->Hdr.rc)
1847 && pReq->Hdr.rc != VERR_INTERRUPTED
1848 && pReq->Hdr.rc != VERR_TIMEOUT)
1849 Log(("SUP_IOCTL_CALL_VMMR0: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1850 pReq->Hdr.rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1851 else
1852 Log4(("SUP_IOCTL_CALL_VMMR0: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1853 pReq->Hdr.rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1854 return 0;
1855 }
1856
1857 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CALL_VMMR0_BIG):
1858 {
1859 /* validate */
1860 PSUPCALLVMMR0 pReq = (PSUPCALLVMMR0)pReqHdr;
1861 PSUPVMMR0REQHDR pVMMReq;
1862 Log4(("SUP_IOCTL_CALL_VMMR0_BIG: op=%u in=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1863 pReq->u.In.uOperation, pReq->Hdr.cbIn, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1864
1865 pVMMReq = (PSUPVMMR0REQHDR)&pReq->abReqPkt[0];
1866 REQ_CHECK_EXPR_FMT(pReq->Hdr.cbIn >= SUP_IOCTL_CALL_VMMR0_BIG_SIZE(sizeof(SUPVMMR0REQHDR)),
1867 ("SUP_IOCTL_CALL_VMMR0_BIG: cbIn=%#x < %#lx\n", pReq->Hdr.cbIn, SUP_IOCTL_CALL_VMMR0_BIG_SIZE(sizeof(SUPVMMR0REQHDR))));
1868 REQ_CHECK_EXPR(SUP_IOCTL_CALL_VMMR0_BIG, pVMMReq->u32Magic == SUPVMMR0REQHDR_MAGIC);
1869 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_VMMR0_BIG, SUP_IOCTL_CALL_VMMR0_BIG_SIZE_IN(pVMMReq->cbReq), SUP_IOCTL_CALL_VMMR0_BIG_SIZE_OUT(pVMMReq->cbReq));
1870
1871 /* execute */
1872 if (RT_LIKELY(pDevExt->pfnVMMR0EntryEx))
1873 {
1874 if (pReq->u.In.pVMR0 == NULL)
1875 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(NULL, NULL, pReq->u.In.idCpu, pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg, pSession);
1876 else if (pReq->u.In.pVMR0 == pSession->pSessionVM)
1877 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(pSession->pSessionGVM, pSession->pSessionVM, pReq->u.In.idCpu,
1878 pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg, pSession);
1879 else
1880 pReq->Hdr.rc = VERR_INVALID_VM_HANDLE;
1881 }
1882 else
1883 pReq->Hdr.rc = VERR_WRONG_ORDER;
1884
1885 if ( RT_FAILURE(pReq->Hdr.rc)
1886 && pReq->Hdr.rc != VERR_INTERRUPTED
1887 && pReq->Hdr.rc != VERR_TIMEOUT)
1888 Log(("SUP_IOCTL_CALL_VMMR0_BIG: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1889 pReq->Hdr.rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1890 else
1891 Log4(("SUP_IOCTL_CALL_VMMR0_BIG: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1892 pReq->Hdr.rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1893 return 0;
1894 }
1895
1896 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GET_PAGING_MODE):
1897 {
1898 /* validate */
1899 PSUPGETPAGINGMODE pReq = (PSUPGETPAGINGMODE)pReqHdr;
1900 REQ_CHECK_SIZES(SUP_IOCTL_GET_PAGING_MODE);
1901
1902 /* execute */
1903 pReq->Hdr.rc = VINF_SUCCESS;
1904 pReq->u.Out.enmMode = SUPR0GetPagingMode();
1905 return 0;
1906 }
1907
1908 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LOW_ALLOC):
1909 {
1910 /* validate */
1911 PSUPLOWALLOC pReq = (PSUPLOWALLOC)pReqHdr;
1912 REQ_CHECK_EXPR(SUP_IOCTL_LOW_ALLOC, pReq->Hdr.cbIn <= SUP_IOCTL_LOW_ALLOC_SIZE_IN);
1913 REQ_CHECK_SIZES_EX(SUP_IOCTL_LOW_ALLOC, SUP_IOCTL_LOW_ALLOC_SIZE_IN, SUP_IOCTL_LOW_ALLOC_SIZE_OUT(pReq->u.In.cPages));
1914
1915 /* execute */
1916 pReq->Hdr.rc = SUPR0LowAlloc(pSession, pReq->u.In.cPages, &pReq->u.Out.pvR0, &pReq->u.Out.pvR3, &pReq->u.Out.aPages[0]);
1917 if (RT_FAILURE(pReq->Hdr.rc))
1918 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
1919 return 0;
1920 }
1921
1922 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LOW_FREE):
1923 {
1924 /* validate */
1925 PSUPLOWFREE pReq = (PSUPLOWFREE)pReqHdr;
1926 REQ_CHECK_SIZES(SUP_IOCTL_LOW_FREE);
1927
1928 /* execute */
1929 pReq->Hdr.rc = SUPR0LowFree(pSession, (RTHCUINTPTR)pReq->u.In.pvR3);
1930 return 0;
1931 }
1932
1933 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GIP_MAP):
1934 {
1935 /* validate */
1936 PSUPGIPMAP pReq = (PSUPGIPMAP)pReqHdr;
1937 REQ_CHECK_SIZES(SUP_IOCTL_GIP_MAP);
1938
1939 /* execute */
1940 pReq->Hdr.rc = SUPR0GipMap(pSession, &pReq->u.Out.pGipR3, &pReq->u.Out.HCPhysGip);
1941 if (RT_SUCCESS(pReq->Hdr.rc))
1942 pReq->u.Out.pGipR0 = pDevExt->pGip;
1943 return 0;
1944 }
1945
1946 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GIP_UNMAP):
1947 {
1948 /* validate */
1949 PSUPGIPUNMAP pReq = (PSUPGIPUNMAP)pReqHdr;
1950 REQ_CHECK_SIZES(SUP_IOCTL_GIP_UNMAP);
1951
1952 /* execute */
1953 pReq->Hdr.rc = SUPR0GipUnmap(pSession);
1954 return 0;
1955 }
1956
1957 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_SET_VM_FOR_FAST):
1958 {
1959 /* validate */
1960 PSUPSETVMFORFAST pReq = (PSUPSETVMFORFAST)pReqHdr;
1961 REQ_CHECK_SIZES(SUP_IOCTL_SET_VM_FOR_FAST);
1962 REQ_CHECK_EXPR_FMT( !pReq->u.In.pVMR0
1963 || ( VALID_PTR(pReq->u.In.pVMR0)
1964 && !((uintptr_t)pReq->u.In.pVMR0 & (PAGE_SIZE - 1))),
1965 ("SUP_IOCTL_SET_VM_FOR_FAST: pVMR0=%p!\n", pReq->u.In.pVMR0));
1966
1967 /* execute */
1968 RTSpinlockAcquire(pDevExt->Spinlock);
1969 if (pSession->pSessionVM == pReq->u.In.pVMR0)
1970 {
1971 if (pSession->pFastIoCtrlVM == NULL)
1972 {
1973 pSession->pFastIoCtrlVM = pSession->pSessionVM;
1974 RTSpinlockRelease(pDevExt->Spinlock);
1975 pReq->Hdr.rc = VINF_SUCCESS;
1976 }
1977 else
1978 {
1979 RTSpinlockRelease(pDevExt->Spinlock);
1980 OSDBGPRINT(("SUP_IOCTL_SET_VM_FOR_FAST: pSession->pFastIoCtrlVM=%p! (pVMR0=%p)\n",
1981 pSession->pFastIoCtrlVM, pReq->u.In.pVMR0));
1982 pReq->Hdr.rc = VERR_ALREADY_EXISTS;
1983 }
1984 }
1985 else
1986 {
1987 RTSpinlockRelease(pDevExt->Spinlock);
1988 OSDBGPRINT(("SUP_IOCTL_SET_VM_FOR_FAST: pSession->pSessionVM=%p vs pVMR0=%p)\n",
1989 pSession->pSessionVM, pReq->u.In.pVMR0));
1990 pReq->Hdr.rc = pSession->pSessionVM ? VERR_ACCESS_DENIED : VERR_WRONG_ORDER;
1991 }
1992 return 0;
1993 }
1994
1995 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_ALLOC_EX):
1996 {
1997 /* validate */
1998 PSUPPAGEALLOCEX pReq = (PSUPPAGEALLOCEX)pReqHdr;
1999 REQ_CHECK_EXPR(SUP_IOCTL_PAGE_ALLOC_EX, pReq->Hdr.cbIn <= SUP_IOCTL_PAGE_ALLOC_EX_SIZE_IN);
2000 REQ_CHECK_SIZES_EX(SUP_IOCTL_PAGE_ALLOC_EX, SUP_IOCTL_PAGE_ALLOC_EX_SIZE_IN, SUP_IOCTL_PAGE_ALLOC_EX_SIZE_OUT(pReq->u.In.cPages));
2001 REQ_CHECK_EXPR_FMT(pReq->u.In.fKernelMapping || pReq->u.In.fUserMapping,
2002 ("SUP_IOCTL_PAGE_ALLOC_EX: No mapping requested!\n"));
2003 REQ_CHECK_EXPR_FMT(pReq->u.In.fUserMapping,
2004 ("SUP_IOCTL_PAGE_ALLOC_EX: Must have user mapping!\n"));
2005 REQ_CHECK_EXPR_FMT(!pReq->u.In.fReserved0 && !pReq->u.In.fReserved1,
2006 ("SUP_IOCTL_PAGE_ALLOC_EX: fReserved0=%d fReserved1=%d\n", pReq->u.In.fReserved0, pReq->u.In.fReserved1));
2007
2008 /* execute */
2009 pReq->Hdr.rc = SUPR0PageAllocEx(pSession, pReq->u.In.cPages, 0 /* fFlags */,
2010 pReq->u.In.fUserMapping ? &pReq->u.Out.pvR3 : NULL,
2011 pReq->u.In.fKernelMapping ? &pReq->u.Out.pvR0 : NULL,
2012 &pReq->u.Out.aPages[0]);
2013 if (RT_FAILURE(pReq->Hdr.rc))
2014 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2015 return 0;
2016 }
2017
2018 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_MAP_KERNEL):
2019 {
2020 /* validate */
2021 PSUPPAGEMAPKERNEL pReq = (PSUPPAGEMAPKERNEL)pReqHdr;
2022 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_MAP_KERNEL);
2023 REQ_CHECK_EXPR_FMT(!pReq->u.In.fFlags, ("SUP_IOCTL_PAGE_MAP_KERNEL: fFlags=%#x! MBZ\n", pReq->u.In.fFlags));
2024 REQ_CHECK_EXPR_FMT(!(pReq->u.In.offSub & PAGE_OFFSET_MASK), ("SUP_IOCTL_PAGE_MAP_KERNEL: offSub=%#x\n", pReq->u.In.offSub));
2025 REQ_CHECK_EXPR_FMT(pReq->u.In.cbSub && !(pReq->u.In.cbSub & PAGE_OFFSET_MASK),
2026 ("SUP_IOCTL_PAGE_MAP_KERNEL: cbSub=%#x\n", pReq->u.In.cbSub));
2027
2028 /* execute */
2029 pReq->Hdr.rc = SUPR0PageMapKernel(pSession, pReq->u.In.pvR3, pReq->u.In.offSub, pReq->u.In.cbSub,
2030 pReq->u.In.fFlags, &pReq->u.Out.pvR0);
2031 if (RT_FAILURE(pReq->Hdr.rc))
2032 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2033 return 0;
2034 }
2035
2036 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_PROTECT):
2037 {
2038 /* validate */
2039 PSUPPAGEPROTECT pReq = (PSUPPAGEPROTECT)pReqHdr;
2040 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_PROTECT);
2041 REQ_CHECK_EXPR_FMT(!(pReq->u.In.fProt & ~(RTMEM_PROT_READ | RTMEM_PROT_WRITE | RTMEM_PROT_EXEC | RTMEM_PROT_NONE)),
2042 ("SUP_IOCTL_PAGE_PROTECT: fProt=%#x!\n", pReq->u.In.fProt));
2043 REQ_CHECK_EXPR_FMT(!(pReq->u.In.offSub & PAGE_OFFSET_MASK), ("SUP_IOCTL_PAGE_PROTECT: offSub=%#x\n", pReq->u.In.offSub));
2044 REQ_CHECK_EXPR_FMT(pReq->u.In.cbSub && !(pReq->u.In.cbSub & PAGE_OFFSET_MASK),
2045 ("SUP_IOCTL_PAGE_PROTECT: cbSub=%#x\n", pReq->u.In.cbSub));
2046
2047 /* execute */
2048 pReq->Hdr.rc = SUPR0PageProtect(pSession, pReq->u.In.pvR3, pReq->u.In.pvR0, pReq->u.In.offSub, pReq->u.In.cbSub, pReq->u.In.fProt);
2049 return 0;
2050 }
2051
2052 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_FREE):
2053 {
2054 /* validate */
2055 PSUPPAGEFREE pReq = (PSUPPAGEFREE)pReqHdr;
2056 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_FREE);
2057
2058 /* execute */
2059 pReq->Hdr.rc = SUPR0PageFree(pSession, pReq->u.In.pvR3);
2060 return 0;
2061 }
2062
2063 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CALL_SERVICE_NO_SIZE()):
2064 {
2065 /* validate */
2066 PSUPCALLSERVICE pReq = (PSUPCALLSERVICE)pReqHdr;
2067 Log4(("SUP_IOCTL_CALL_SERVICE: op=%u in=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
2068 pReq->u.In.uOperation, pReq->Hdr.cbIn, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
2069
2070 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_SERVICE_SIZE(0))
2071 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_SERVICE, SUP_IOCTL_CALL_SERVICE_SIZE_IN(0), SUP_IOCTL_CALL_SERVICE_SIZE_OUT(0));
2072 else
2073 {
2074 PSUPR0SERVICEREQHDR pSrvReq = (PSUPR0SERVICEREQHDR)&pReq->abReqPkt[0];
2075 REQ_CHECK_EXPR_FMT(pReq->Hdr.cbIn >= SUP_IOCTL_CALL_SERVICE_SIZE(sizeof(SUPR0SERVICEREQHDR)),
2076 ("SUP_IOCTL_CALL_SERVICE: cbIn=%#x < %#lx\n", pReq->Hdr.cbIn, SUP_IOCTL_CALL_SERVICE_SIZE(sizeof(SUPR0SERVICEREQHDR))));
2077 REQ_CHECK_EXPR(SUP_IOCTL_CALL_SERVICE, pSrvReq->u32Magic == SUPR0SERVICEREQHDR_MAGIC);
2078 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_SERVICE, SUP_IOCTL_CALL_SERVICE_SIZE_IN(pSrvReq->cbReq), SUP_IOCTL_CALL_SERVICE_SIZE_OUT(pSrvReq->cbReq));
2079 }
2080 REQ_CHECK_EXPR(SUP_IOCTL_CALL_SERVICE, RTStrEnd(pReq->u.In.szName, sizeof(pReq->u.In.szName)));
2081
2082 /* execute */
2083 pReq->Hdr.rc = supdrvIOCtl_CallServiceModule(pDevExt, pSession, pReq);
2084 return 0;
2085 }
2086
2087 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LOGGER_SETTINGS_NO_SIZE()):
2088 {
2089 /* validate */
2090 PSUPLOGGERSETTINGS pReq = (PSUPLOGGERSETTINGS)pReqHdr;
2091 size_t cbStrTab;
2092 REQ_CHECK_SIZE_OUT(SUP_IOCTL_LOGGER_SETTINGS, SUP_IOCTL_LOGGER_SETTINGS_SIZE_OUT);
2093 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->Hdr.cbIn >= SUP_IOCTL_LOGGER_SETTINGS_SIZE_IN(1));
2094 cbStrTab = pReq->Hdr.cbIn - SUP_IOCTL_LOGGER_SETTINGS_SIZE_IN(0);
2095 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.offGroups < cbStrTab);
2096 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.offFlags < cbStrTab);
2097 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.offDestination < cbStrTab);
2098 REQ_CHECK_EXPR_FMT(pReq->u.In.szStrings[cbStrTab - 1] == '\0',
2099 ("SUP_IOCTL_LOGGER_SETTINGS: cbIn=%#x cbStrTab=%#zx LastChar=%d\n",
2100 pReq->Hdr.cbIn, cbStrTab, pReq->u.In.szStrings[cbStrTab - 1]));
2101 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.fWhich <= SUPLOGGERSETTINGS_WHICH_RELEASE);
2102 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.fWhat <= SUPLOGGERSETTINGS_WHAT_DESTROY);
2103
2104 /* execute */
2105 pReq->Hdr.rc = supdrvIOCtl_LoggerSettings(pReq);
2106 return 0;
2107 }
2108
2109 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_SEM_OP2):
2110 {
2111 /* validate */
2112 PSUPSEMOP2 pReq = (PSUPSEMOP2)pReqHdr;
2113 REQ_CHECK_SIZES_EX(SUP_IOCTL_SEM_OP2, SUP_IOCTL_SEM_OP2_SIZE_IN, SUP_IOCTL_SEM_OP2_SIZE_OUT);
2114 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP2, pReq->u.In.uReserved == 0);
2115
2116 /* execute */
2117 switch (pReq->u.In.uType)
2118 {
2119 case SUP_SEM_TYPE_EVENT:
2120 {
2121 SUPSEMEVENT hEvent = (SUPSEMEVENT)(uintptr_t)pReq->u.In.hSem;
2122 switch (pReq->u.In.uOp)
2123 {
2124 case SUPSEMOP2_WAIT_MS_REL:
2125 pReq->Hdr.rc = SUPSemEventWaitNoResume(pSession, hEvent, pReq->u.In.uArg.cRelMsTimeout);
2126 break;
2127 case SUPSEMOP2_WAIT_NS_ABS:
2128 pReq->Hdr.rc = SUPSemEventWaitNsAbsIntr(pSession, hEvent, pReq->u.In.uArg.uAbsNsTimeout);
2129 break;
2130 case SUPSEMOP2_WAIT_NS_REL:
2131 pReq->Hdr.rc = SUPSemEventWaitNsRelIntr(pSession, hEvent, pReq->u.In.uArg.cRelNsTimeout);
2132 break;
2133 case SUPSEMOP2_SIGNAL:
2134 pReq->Hdr.rc = SUPSemEventSignal(pSession, hEvent);
2135 break;
2136 case SUPSEMOP2_CLOSE:
2137 pReq->Hdr.rc = SUPSemEventClose(pSession, hEvent);
2138 break;
2139 case SUPSEMOP2_RESET:
2140 default:
2141 pReq->Hdr.rc = VERR_INVALID_FUNCTION;
2142 break;
2143 }
2144 break;
2145 }
2146
2147 case SUP_SEM_TYPE_EVENT_MULTI:
2148 {
2149 SUPSEMEVENTMULTI hEventMulti = (SUPSEMEVENTMULTI)(uintptr_t)pReq->u.In.hSem;
2150 switch (pReq->u.In.uOp)
2151 {
2152 case SUPSEMOP2_WAIT_MS_REL:
2153 pReq->Hdr.rc = SUPSemEventMultiWaitNoResume(pSession, hEventMulti, pReq->u.In.uArg.cRelMsTimeout);
2154 break;
2155 case SUPSEMOP2_WAIT_NS_ABS:
2156 pReq->Hdr.rc = SUPSemEventMultiWaitNsAbsIntr(pSession, hEventMulti, pReq->u.In.uArg.uAbsNsTimeout);
2157 break;
2158 case SUPSEMOP2_WAIT_NS_REL:
2159 pReq->Hdr.rc = SUPSemEventMultiWaitNsRelIntr(pSession, hEventMulti, pReq->u.In.uArg.cRelNsTimeout);
2160 break;
2161 case SUPSEMOP2_SIGNAL:
2162 pReq->Hdr.rc = SUPSemEventMultiSignal(pSession, hEventMulti);
2163 break;
2164 case SUPSEMOP2_CLOSE:
2165 pReq->Hdr.rc = SUPSemEventMultiClose(pSession, hEventMulti);
2166 break;
2167 case SUPSEMOP2_RESET:
2168 pReq->Hdr.rc = SUPSemEventMultiReset(pSession, hEventMulti);
2169 break;
2170 default:
2171 pReq->Hdr.rc = VERR_INVALID_FUNCTION;
2172 break;
2173 }
2174 break;
2175 }
2176
2177 default:
2178 pReq->Hdr.rc = VERR_INVALID_PARAMETER;
2179 break;
2180 }
2181 return 0;
2182 }
2183
2184 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_SEM_OP3):
2185 {
2186 /* validate */
2187 PSUPSEMOP3 pReq = (PSUPSEMOP3)pReqHdr;
2188 REQ_CHECK_SIZES_EX(SUP_IOCTL_SEM_OP3, SUP_IOCTL_SEM_OP3_SIZE_IN, SUP_IOCTL_SEM_OP3_SIZE_OUT);
2189 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, pReq->u.In.u32Reserved == 0 && pReq->u.In.u64Reserved == 0);
2190
2191 /* execute */
2192 switch (pReq->u.In.uType)
2193 {
2194 case SUP_SEM_TYPE_EVENT:
2195 {
2196 SUPSEMEVENT hEvent = (SUPSEMEVENT)(uintptr_t)pReq->u.In.hSem;
2197 switch (pReq->u.In.uOp)
2198 {
2199 case SUPSEMOP3_CREATE:
2200 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, hEvent == NIL_SUPSEMEVENT);
2201 pReq->Hdr.rc = SUPSemEventCreate(pSession, &hEvent);
2202 pReq->u.Out.hSem = (uint32_t)(uintptr_t)hEvent;
2203 break;
2204 case SUPSEMOP3_GET_RESOLUTION:
2205 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, hEvent == NIL_SUPSEMEVENT);
2206 pReq->Hdr.rc = VINF_SUCCESS;
2207 pReq->Hdr.cbOut = sizeof(*pReq);
2208 pReq->u.Out.cNsResolution = SUPSemEventGetResolution(pSession);
2209 break;
2210 default:
2211 pReq->Hdr.rc = VERR_INVALID_FUNCTION;
2212 break;
2213 }
2214 break;
2215 }
2216
2217 case SUP_SEM_TYPE_EVENT_MULTI:
2218 {
2219 SUPSEMEVENTMULTI hEventMulti = (SUPSEMEVENTMULTI)(uintptr_t)pReq->u.In.hSem;
2220 switch (pReq->u.In.uOp)
2221 {
2222 case SUPSEMOP3_CREATE:
2223 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, hEventMulti == NIL_SUPSEMEVENTMULTI);
2224 pReq->Hdr.rc = SUPSemEventMultiCreate(pSession, &hEventMulti);
2225 pReq->u.Out.hSem = (uint32_t)(uintptr_t)hEventMulti;
2226 break;
2227 case SUPSEMOP3_GET_RESOLUTION:
2228 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, hEventMulti == NIL_SUPSEMEVENTMULTI);
2229 pReq->Hdr.rc = VINF_SUCCESS;
2230 pReq->u.Out.cNsResolution = SUPSemEventMultiGetResolution(pSession);
2231 break;
2232 default:
2233 pReq->Hdr.rc = VERR_INVALID_FUNCTION;
2234 break;
2235 }
2236 break;
2237 }
2238
2239 default:
2240 pReq->Hdr.rc = VERR_INVALID_PARAMETER;
2241 break;
2242 }
2243 return 0;
2244 }
2245
2246 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_VT_CAPS):
2247 {
2248 /* validate */
2249 PSUPVTCAPS pReq = (PSUPVTCAPS)pReqHdr;
2250 REQ_CHECK_SIZES(SUP_IOCTL_VT_CAPS);
2251
2252 /* execute */
2253 pReq->Hdr.rc = SUPR0QueryVTCaps(pSession, &pReq->u.Out.fCaps);
2254 if (RT_FAILURE(pReq->Hdr.rc))
2255 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2256 return 0;
2257 }
2258
2259 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_OPEN):
2260 {
2261 /* validate */
2262 PSUPTRACEROPEN pReq = (PSUPTRACEROPEN)pReqHdr;
2263 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_OPEN);
2264
2265 /* execute */
2266 pReq->Hdr.rc = supdrvIOCtl_TracerOpen(pDevExt, pSession, pReq->u.In.uCookie, pReq->u.In.uArg);
2267 return 0;
2268 }
2269
2270 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_CLOSE):
2271 {
2272 /* validate */
2273 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_CLOSE);
2274
2275 /* execute */
2276 pReqHdr->rc = supdrvIOCtl_TracerClose(pDevExt, pSession);
2277 return 0;
2278 }
2279
2280 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_IOCTL):
2281 {
2282 /* validate */
2283 PSUPTRACERIOCTL pReq = (PSUPTRACERIOCTL)pReqHdr;
2284 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_IOCTL);
2285
2286 /* execute */
2287 pReqHdr->rc = supdrvIOCtl_TracerIOCtl(pDevExt, pSession, pReq->u.In.uCmd, pReq->u.In.uArg, &pReq->u.Out.iRetVal);
2288 return 0;
2289 }
2290
2291 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_UMOD_REG):
2292 {
2293 /* validate */
2294 PSUPTRACERUMODREG pReq = (PSUPTRACERUMODREG)pReqHdr;
2295 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_UMOD_REG);
2296 if (!RTStrEnd(pReq->u.In.szName, sizeof(pReq->u.In.szName)))
2297 return VERR_INVALID_PARAMETER;
2298
2299 /* execute */
2300 pReqHdr->rc = supdrvIOCtl_TracerUmodRegister(pDevExt, pSession,
2301 pReq->u.In.R3PtrVtgHdr, pReq->u.In.uVtgHdrAddr,
2302 pReq->u.In.R3PtrStrTab, pReq->u.In.cbStrTab,
2303 pReq->u.In.szName, pReq->u.In.fFlags);
2304 return 0;
2305 }
2306
2307 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_UMOD_DEREG):
2308 {
2309 /* validate */
2310 PSUPTRACERUMODDEREG pReq = (PSUPTRACERUMODDEREG)pReqHdr;
2311 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_UMOD_DEREG);
2312
2313 /* execute */
2314 pReqHdr->rc = supdrvIOCtl_TracerUmodDeregister(pDevExt, pSession, pReq->u.In.pVtgHdr);
2315 return 0;
2316 }
2317
2318 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_UMOD_FIRE_PROBE):
2319 {
2320 /* validate */
2321 PSUPTRACERUMODFIREPROBE pReq = (PSUPTRACERUMODFIREPROBE)pReqHdr;
2322 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_UMOD_FIRE_PROBE);
2323
2324 supdrvIOCtl_TracerUmodProbeFire(pDevExt, pSession, &pReq->u.In);
2325 pReqHdr->rc = VINF_SUCCESS;
2326 return 0;
2327 }
2328
2329 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_MSR_PROBER):
2330 {
2331 /* validate */
2332 PSUPMSRPROBER pReq = (PSUPMSRPROBER)pReqHdr;
2333 REQ_CHECK_SIZES(SUP_IOCTL_MSR_PROBER);
2334 REQ_CHECK_EXPR(SUP_IOCTL_MSR_PROBER,
2335 pReq->u.In.enmOp > SUPMSRPROBEROP_INVALID && pReq->u.In.enmOp < SUPMSRPROBEROP_END);
2336
2337 pReqHdr->rc = supdrvIOCtl_MsrProber(pDevExt, pReq);
2338 return 0;
2339 }
2340
2341 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_RESUME_SUSPENDED_KBDS):
2342 {
2343 /* validate */
2344 REQ_CHECK_SIZES(SUP_IOCTL_RESUME_SUSPENDED_KBDS);
2345
2346 pReqHdr->rc = supdrvIOCtl_ResumeSuspendedKbds();
2347 return 0;
2348 }
2349
2350 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TSC_DELTA_MEASURE):
2351 {
2352 /* validate */
2353 PSUPTSCDELTAMEASURE pReq = (PSUPTSCDELTAMEASURE)pReqHdr;
2354 REQ_CHECK_SIZES(SUP_IOCTL_TSC_DELTA_MEASURE);
2355
2356 pReqHdr->rc = supdrvIOCtl_TscDeltaMeasure(pDevExt, pSession, pReq);
2357 return 0;
2358 }
2359
2360 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TSC_READ):
2361 {
2362 /* validate */
2363 PSUPTSCREAD pReq = (PSUPTSCREAD)pReqHdr;
2364 REQ_CHECK_SIZES(SUP_IOCTL_TSC_READ);
2365
2366 pReqHdr->rc = supdrvIOCtl_TscRead(pDevExt, pSession, pReq);
2367 return 0;
2368 }
2369
2370 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GIP_SET_FLAGS):
2371 {
2372 /* validate */
2373 PSUPGIPSETFLAGS pReq = (PSUPGIPSETFLAGS)pReqHdr;
2374 REQ_CHECK_SIZES(SUP_IOCTL_GIP_SET_FLAGS);
2375
2376 pReqHdr->rc = supdrvIOCtl_GipSetFlags(pDevExt, pSession, pReq->u.In.fOrMask, pReq->u.In.fAndMask);
2377 return 0;
2378 }
2379
2380 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_UCODE_REV):
2381 {
2382 /* validate */
2383 PSUPUCODEREV pReq = (PSUPUCODEREV)pReqHdr;
2384 REQ_CHECK_SIZES(SUP_IOCTL_UCODE_REV);
2385
2386 /* execute */
2387 pReq->Hdr.rc = SUPR0QueryUcodeRev(pSession, &pReq->u.Out.MicrocodeRev);
2388 if (RT_FAILURE(pReq->Hdr.rc))
2389 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2390 return 0;
2391 }
2392
2393 default:
2394 Log(("Unknown IOCTL %#lx\n", (long)uIOCtl));
2395 break;
2396 }
2397 return VERR_GENERAL_FAILURE;
2398}
2399
2400
2401/**
2402 * I/O Control inner worker for the restricted operations.
2403 *
2404 * @returns IPRT status code.
2405 * @retval VERR_INVALID_PARAMETER if the request is invalid.
2406 *
2407 * @param uIOCtl Function number.
2408 * @param pDevExt Device extention.
2409 * @param pSession Session data.
2410 * @param pReqHdr The request header.
2411 */
2412static int supdrvIOCtlInnerRestricted(uintptr_t uIOCtl, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPREQHDR pReqHdr)
2413{
2414 /*
2415 * The switch.
2416 */
2417 switch (SUP_CTL_CODE_NO_SIZE(uIOCtl))
2418 {
2419 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_COOKIE):
2420 {
2421 PSUPCOOKIE pReq = (PSUPCOOKIE)pReqHdr;
2422 REQ_CHECK_SIZES(SUP_IOCTL_COOKIE);
2423 if (strncmp(pReq->u.In.szMagic, SUPCOOKIE_MAGIC, sizeof(pReq->u.In.szMagic)))
2424 {
2425 OSDBGPRINT(("SUP_IOCTL_COOKIE: invalid magic %.16s\n", pReq->u.In.szMagic));
2426 pReq->Hdr.rc = VERR_INVALID_MAGIC;
2427 return 0;
2428 }
2429
2430 /*
2431 * Match the version.
2432 * The current logic is very simple, match the major interface version.
2433 */
2434 if ( pReq->u.In.u32MinVersion > SUPDRV_IOC_VERSION
2435 || (pReq->u.In.u32MinVersion & 0xffff0000) != (SUPDRV_IOC_VERSION & 0xffff0000))
2436 {
2437 OSDBGPRINT(("SUP_IOCTL_COOKIE: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
2438 pReq->u.In.u32ReqVersion, pReq->u.In.u32MinVersion, SUPDRV_IOC_VERSION));
2439 pReq->u.Out.u32Cookie = 0xffffffff;
2440 pReq->u.Out.u32SessionCookie = 0xffffffff;
2441 pReq->u.Out.u32SessionVersion = 0xffffffff;
2442 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
2443 pReq->u.Out.pSession = NULL;
2444 pReq->u.Out.cFunctions = 0;
2445 pReq->Hdr.rc = VERR_VERSION_MISMATCH;
2446 return 0;
2447 }
2448
2449 /*
2450 * Fill in return data and be gone.
2451 * N.B. The first one to change SUPDRV_IOC_VERSION shall makes sure that
2452 * u32SessionVersion <= u32ReqVersion!
2453 */
2454 /** @todo Somehow validate the client and negotiate a secure cookie... */
2455 pReq->u.Out.u32Cookie = pDevExt->u32Cookie;
2456 pReq->u.Out.u32SessionCookie = pSession->u32Cookie;
2457 pReq->u.Out.u32SessionVersion = SUPDRV_IOC_VERSION;
2458 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
2459 pReq->u.Out.pSession = pSession;
2460 pReq->u.Out.cFunctions = 0;
2461 pReq->Hdr.rc = VINF_SUCCESS;
2462 return 0;
2463 }
2464
2465 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_VT_CAPS):
2466 {
2467 /* validate */
2468 PSUPVTCAPS pReq = (PSUPVTCAPS)pReqHdr;
2469 REQ_CHECK_SIZES(SUP_IOCTL_VT_CAPS);
2470
2471 /* execute */
2472 pReq->Hdr.rc = SUPR0QueryVTCaps(pSession, &pReq->u.Out.fCaps);
2473 if (RT_FAILURE(pReq->Hdr.rc))
2474 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2475 return 0;
2476 }
2477
2478 default:
2479 Log(("Unknown IOCTL %#lx\n", (long)uIOCtl));
2480 break;
2481 }
2482 return VERR_GENERAL_FAILURE;
2483}
2484
2485
2486/**
2487 * I/O Control worker.
2488 *
2489 * @returns IPRT status code.
2490 * @retval VERR_INVALID_PARAMETER if the request is invalid.
2491 *
2492 * @param uIOCtl Function number.
2493 * @param pDevExt Device extention.
2494 * @param pSession Session data.
2495 * @param pReqHdr The request header.
2496 * @param cbReq The size of the request buffer.
2497 */
2498int VBOXCALL supdrvIOCtl(uintptr_t uIOCtl, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPREQHDR pReqHdr, size_t cbReq)
2499{
2500 int rc;
2501 VBOXDRV_IOCTL_ENTRY(pSession, uIOCtl, pReqHdr);
2502
2503 /*
2504 * Validate the request.
2505 */
2506 if (RT_UNLIKELY(cbReq < sizeof(*pReqHdr)))
2507 {
2508 OSDBGPRINT(("vboxdrv: Bad ioctl request size; cbReq=%#lx\n", (long)cbReq));
2509 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2510 return VERR_INVALID_PARAMETER;
2511 }
2512 if (RT_UNLIKELY( (pReqHdr->fFlags & SUPREQHDR_FLAGS_MAGIC_MASK) != SUPREQHDR_FLAGS_MAGIC
2513 || pReqHdr->cbIn < sizeof(*pReqHdr)
2514 || pReqHdr->cbIn > cbReq
2515 || pReqHdr->cbOut < sizeof(*pReqHdr)
2516 || pReqHdr->cbOut > cbReq))
2517 {
2518 OSDBGPRINT(("vboxdrv: Bad ioctl request header; cbIn=%#lx cbOut=%#lx fFlags=%#lx\n",
2519 (long)pReqHdr->cbIn, (long)pReqHdr->cbOut, (long)pReqHdr->fFlags));
2520 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2521 return VERR_INVALID_PARAMETER;
2522 }
2523 if (RT_UNLIKELY(!RT_VALID_PTR(pSession)))
2524 {
2525 OSDBGPRINT(("vboxdrv: Invalid pSession value %p (ioctl=%p)\n", pSession, (void *)uIOCtl));
2526 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2527 return VERR_INVALID_PARAMETER;
2528 }
2529 if (RT_UNLIKELY(uIOCtl == SUP_IOCTL_COOKIE))
2530 {
2531 if (pReqHdr->u32Cookie != SUPCOOKIE_INITIAL_COOKIE)
2532 {
2533 OSDBGPRINT(("SUP_IOCTL_COOKIE: bad cookie %#lx\n", (long)pReqHdr->u32Cookie));
2534 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2535 return VERR_INVALID_PARAMETER;
2536 }
2537 }
2538 else if (RT_UNLIKELY( pReqHdr->u32Cookie != pDevExt->u32Cookie
2539 || pReqHdr->u32SessionCookie != pSession->u32Cookie))
2540 {
2541 OSDBGPRINT(("vboxdrv: bad cookie %#lx / %#lx.\n", (long)pReqHdr->u32Cookie, (long)pReqHdr->u32SessionCookie));
2542 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2543 return VERR_INVALID_PARAMETER;
2544 }
2545
2546 /*
2547 * Hand it to an inner function to avoid lots of unnecessary return tracepoints.
2548 */
2549 if (pSession->fUnrestricted)
2550 rc = supdrvIOCtlInnerUnrestricted(uIOCtl, pDevExt, pSession, pReqHdr);
2551 else
2552 rc = supdrvIOCtlInnerRestricted(uIOCtl, pDevExt, pSession, pReqHdr);
2553
2554 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, pReqHdr->rc, rc);
2555 return rc;
2556}
2557
2558
2559/**
2560 * Inter-Driver Communication (IDC) worker.
2561 *
2562 * @returns VBox status code.
2563 * @retval VINF_SUCCESS on success.
2564 * @retval VERR_INVALID_PARAMETER if the request is invalid.
2565 * @retval VERR_NOT_SUPPORTED if the request isn't supported.
2566 *
2567 * @param uReq The request (function) code.
2568 * @param pDevExt Device extention.
2569 * @param pSession Session data.
2570 * @param pReqHdr The request header.
2571 */
2572int VBOXCALL supdrvIDC(uintptr_t uReq, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVIDCREQHDR pReqHdr)
2573{
2574 /*
2575 * The OS specific code has already validated the pSession
2576 * pointer, and the request size being greater or equal to
2577 * size of the header.
2578 *
2579 * So, just check that pSession is a kernel context session.
2580 */
2581 if (RT_UNLIKELY( pSession
2582 && pSession->R0Process != NIL_RTR0PROCESS))
2583 return VERR_INVALID_PARAMETER;
2584
2585/*
2586 * Validation macro.
2587 */
2588#define REQ_CHECK_IDC_SIZE(Name, cbExpect) \
2589 do { \
2590 if (RT_UNLIKELY(pReqHdr->cb != (cbExpect))) \
2591 { \
2592 OSDBGPRINT(( #Name ": Invalid input/output sizes. cb=%ld expected %ld.\n", \
2593 (long)pReqHdr->cb, (long)(cbExpect))); \
2594 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
2595 } \
2596 } while (0)
2597
2598 switch (uReq)
2599 {
2600 case SUPDRV_IDC_REQ_CONNECT:
2601 {
2602 PSUPDRVIDCREQCONNECT pReq = (PSUPDRVIDCREQCONNECT)pReqHdr;
2603 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_CONNECT, sizeof(*pReq));
2604
2605 /*
2606 * Validate the cookie and other input.
2607 */
2608 if (pReq->Hdr.pSession != NULL)
2609 {
2610 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: Hdr.pSession=%p expected NULL!\n", pReq->Hdr.pSession));
2611 return pReqHdr->rc = VERR_INVALID_PARAMETER;
2612 }
2613 if (pReq->u.In.u32MagicCookie != SUPDRVIDCREQ_CONNECT_MAGIC_COOKIE)
2614 {
2615 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: u32MagicCookie=%#x expected %#x!\n",
2616 (unsigned)pReq->u.In.u32MagicCookie, (unsigned)SUPDRVIDCREQ_CONNECT_MAGIC_COOKIE));
2617 return pReqHdr->rc = VERR_INVALID_PARAMETER;
2618 }
2619 if ( pReq->u.In.uMinVersion > pReq->u.In.uReqVersion
2620 || (pReq->u.In.uMinVersion & UINT32_C(0xffff0000)) != (pReq->u.In.uReqVersion & UINT32_C(0xffff0000)))
2621 {
2622 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: uMinVersion=%#x uMaxVersion=%#x doesn't match!\n",
2623 pReq->u.In.uMinVersion, pReq->u.In.uReqVersion));
2624 return pReqHdr->rc = VERR_INVALID_PARAMETER;
2625 }
2626 if (pSession != NULL)
2627 {
2628 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: pSession=%p expected NULL!\n", pSession));
2629 return pReqHdr->rc = VERR_INVALID_PARAMETER;
2630 }
2631
2632 /*
2633 * Match the version.
2634 * The current logic is very simple, match the major interface version.
2635 */
2636 if ( pReq->u.In.uMinVersion > SUPDRV_IDC_VERSION
2637 || (pReq->u.In.uMinVersion & 0xffff0000) != (SUPDRV_IDC_VERSION & 0xffff0000))
2638 {
2639 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
2640 pReq->u.In.uReqVersion, pReq->u.In.uMinVersion, (unsigned)SUPDRV_IDC_VERSION));
2641 pReq->u.Out.pSession = NULL;
2642 pReq->u.Out.uSessionVersion = 0xffffffff;
2643 pReq->u.Out.uDriverVersion = SUPDRV_IDC_VERSION;
2644 pReq->u.Out.uDriverRevision = VBOX_SVN_REV;
2645 pReq->Hdr.rc = VERR_VERSION_MISMATCH;
2646 return VINF_SUCCESS;
2647 }
2648
2649 pReq->u.Out.pSession = NULL;
2650 pReq->u.Out.uSessionVersion = SUPDRV_IDC_VERSION;
2651 pReq->u.Out.uDriverVersion = SUPDRV_IDC_VERSION;
2652 pReq->u.Out.uDriverRevision = VBOX_SVN_REV;
2653
2654 pReq->Hdr.rc = supdrvCreateSession(pDevExt, false /* fUser */, true /*fUnrestricted*/, &pSession);
2655 if (RT_FAILURE(pReq->Hdr.rc))
2656 {
2657 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: failed to create session, rc=%d\n", pReq->Hdr.rc));
2658 return VINF_SUCCESS;
2659 }
2660
2661 pReq->u.Out.pSession = pSession;
2662 pReq->Hdr.pSession = pSession;
2663
2664 return VINF_SUCCESS;
2665 }
2666
2667 case SUPDRV_IDC_REQ_DISCONNECT:
2668 {
2669 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_DISCONNECT, sizeof(*pReqHdr));
2670
2671 supdrvSessionRelease(pSession);
2672 return pReqHdr->rc = VINF_SUCCESS;
2673 }
2674
2675 case SUPDRV_IDC_REQ_GET_SYMBOL:
2676 {
2677 PSUPDRVIDCREQGETSYM pReq = (PSUPDRVIDCREQGETSYM)pReqHdr;
2678 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_GET_SYMBOL, sizeof(*pReq));
2679
2680 pReq->Hdr.rc = supdrvIDC_LdrGetSymbol(pDevExt, pSession, pReq);
2681 return VINF_SUCCESS;
2682 }
2683
2684 case SUPDRV_IDC_REQ_COMPONENT_REGISTER_FACTORY:
2685 {
2686 PSUPDRVIDCREQCOMPREGFACTORY pReq = (PSUPDRVIDCREQCOMPREGFACTORY)pReqHdr;
2687 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_COMPONENT_REGISTER_FACTORY, sizeof(*pReq));
2688
2689 pReq->Hdr.rc = SUPR0ComponentRegisterFactory(pSession, pReq->u.In.pFactory);
2690 return VINF_SUCCESS;
2691 }
2692
2693 case SUPDRV_IDC_REQ_COMPONENT_DEREGISTER_FACTORY:
2694 {
2695 PSUPDRVIDCREQCOMPDEREGFACTORY pReq = (PSUPDRVIDCREQCOMPDEREGFACTORY)pReqHdr;
2696 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_COMPONENT_DEREGISTER_FACTORY, sizeof(*pReq));
2697
2698 pReq->Hdr.rc = SUPR0ComponentDeregisterFactory(pSession, pReq->u.In.pFactory);
2699 return VINF_SUCCESS;
2700 }
2701
2702 default:
2703 Log(("Unknown IDC %#lx\n", (long)uReq));
2704 break;
2705 }
2706
2707#undef REQ_CHECK_IDC_SIZE
2708 return VERR_NOT_SUPPORTED;
2709}
2710
2711
2712/**
2713 * Register a object for reference counting.
2714 * The object is registered with one reference in the specified session.
2715 *
2716 * @returns Unique identifier on success (pointer).
2717 * All future reference must use this identifier.
2718 * @returns NULL on failure.
2719 * @param pSession The caller's session.
2720 * @param enmType The object type.
2721 * @param pfnDestructor The destructore function which will be called when the reference count reaches 0.
2722 * @param pvUser1 The first user argument.
2723 * @param pvUser2 The second user argument.
2724 */
2725SUPR0DECL(void *) SUPR0ObjRegister(PSUPDRVSESSION pSession, SUPDRVOBJTYPE enmType, PFNSUPDRVDESTRUCTOR pfnDestructor, void *pvUser1, void *pvUser2)
2726{
2727 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
2728 PSUPDRVOBJ pObj;
2729 PSUPDRVUSAGE pUsage;
2730
2731 /*
2732 * Validate the input.
2733 */
2734 AssertReturn(SUP_IS_SESSION_VALID(pSession), NULL);
2735 AssertReturn(enmType > SUPDRVOBJTYPE_INVALID && enmType < SUPDRVOBJTYPE_END, NULL);
2736 AssertPtrReturn(pfnDestructor, NULL);
2737
2738 /*
2739 * Allocate and initialize the object.
2740 */
2741 pObj = (PSUPDRVOBJ)RTMemAlloc(sizeof(*pObj));
2742 if (!pObj)
2743 return NULL;
2744 pObj->u32Magic = SUPDRVOBJ_MAGIC;
2745 pObj->enmType = enmType;
2746 pObj->pNext = NULL;
2747 pObj->cUsage = 1;
2748 pObj->pfnDestructor = pfnDestructor;
2749 pObj->pvUser1 = pvUser1;
2750 pObj->pvUser2 = pvUser2;
2751 pObj->CreatorUid = pSession->Uid;
2752 pObj->CreatorGid = pSession->Gid;
2753 pObj->CreatorProcess= pSession->Process;
2754 supdrvOSObjInitCreator(pObj, pSession);
2755
2756 /*
2757 * Allocate the usage record.
2758 * (We keep freed usage records around to simplify SUPR0ObjAddRefEx().)
2759 */
2760 RTSpinlockAcquire(pDevExt->Spinlock);
2761
2762 pUsage = pDevExt->pUsageFree;
2763 if (pUsage)
2764 pDevExt->pUsageFree = pUsage->pNext;
2765 else
2766 {
2767 RTSpinlockRelease(pDevExt->Spinlock);
2768 pUsage = (PSUPDRVUSAGE)RTMemAlloc(sizeof(*pUsage));
2769 if (!pUsage)
2770 {
2771 RTMemFree(pObj);
2772 return NULL;
2773 }
2774 RTSpinlockAcquire(pDevExt->Spinlock);
2775 }
2776
2777 /*
2778 * Insert the object and create the session usage record.
2779 */
2780 /* The object. */
2781 pObj->pNext = pDevExt->pObjs;
2782 pDevExt->pObjs = pObj;
2783
2784 /* The session record. */
2785 pUsage->cUsage = 1;
2786 pUsage->pObj = pObj;
2787 pUsage->pNext = pSession->pUsage;
2788 /* Log2(("SUPR0ObjRegister: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext)); */
2789 pSession->pUsage = pUsage;
2790
2791 RTSpinlockRelease(pDevExt->Spinlock);
2792
2793 Log(("SUPR0ObjRegister: returns %p (pvUser1=%p, pvUser=%p)\n", pObj, pvUser1, pvUser2));
2794 return pObj;
2795}
2796
2797
2798/**
2799 * Increment the reference counter for the object associating the reference
2800 * with the specified session.
2801 *
2802 * @returns IPRT status code.
2803 * @param pvObj The identifier returned by SUPR0ObjRegister().
2804 * @param pSession The session which is referencing the object.
2805 *
2806 * @remarks The caller should not own any spinlocks and must carefully protect
2807 * itself against potential race with the destructor so freed memory
2808 * isn't accessed here.
2809 */
2810SUPR0DECL(int) SUPR0ObjAddRef(void *pvObj, PSUPDRVSESSION pSession)
2811{
2812 return SUPR0ObjAddRefEx(pvObj, pSession, false /* fNoBlocking */);
2813}
2814
2815
2816/**
2817 * Increment the reference counter for the object associating the reference
2818 * with the specified session.
2819 *
2820 * @returns IPRT status code.
2821 * @retval VERR_TRY_AGAIN if fNoBlocking was set and a new usage record
2822 * couldn't be allocated. (If you see this you're not doing the right
2823 * thing and it won't ever work reliably.)
2824 *
2825 * @param pvObj The identifier returned by SUPR0ObjRegister().
2826 * @param pSession The session which is referencing the object.
2827 * @param fNoBlocking Set if it's not OK to block. Never try to make the
2828 * first reference to an object in a session with this
2829 * argument set.
2830 *
2831 * @remarks The caller should not own any spinlocks and must carefully protect
2832 * itself against potential race with the destructor so freed memory
2833 * isn't accessed here.
2834 */
2835SUPR0DECL(int) SUPR0ObjAddRefEx(void *pvObj, PSUPDRVSESSION pSession, bool fNoBlocking)
2836{
2837 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
2838 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
2839 int rc = VINF_SUCCESS;
2840 PSUPDRVUSAGE pUsagePre;
2841 PSUPDRVUSAGE pUsage;
2842
2843 /*
2844 * Validate the input.
2845 * Be ready for the destruction race (someone might be stuck in the
2846 * destructor waiting a lock we own).
2847 */
2848 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2849 AssertPtrReturn(pObj, VERR_INVALID_POINTER);
2850 AssertMsgReturn(pObj->u32Magic == SUPDRVOBJ_MAGIC || pObj->u32Magic == SUPDRVOBJ_MAGIC_DEAD,
2851 ("Invalid pvObj=%p magic=%#x (expected %#x or %#x)\n", pvObj, pObj->u32Magic, SUPDRVOBJ_MAGIC, SUPDRVOBJ_MAGIC_DEAD),
2852 VERR_INVALID_PARAMETER);
2853
2854 RTSpinlockAcquire(pDevExt->Spinlock);
2855
2856 if (RT_UNLIKELY(pObj->u32Magic != SUPDRVOBJ_MAGIC))
2857 {
2858 RTSpinlockRelease(pDevExt->Spinlock);
2859
2860 AssertMsgFailed(("pvObj=%p magic=%#x\n", pvObj, pObj->u32Magic));
2861 return VERR_WRONG_ORDER;
2862 }
2863
2864 /*
2865 * Preallocate the usage record if we can.
2866 */
2867 pUsagePre = pDevExt->pUsageFree;
2868 if (pUsagePre)
2869 pDevExt->pUsageFree = pUsagePre->pNext;
2870 else if (!fNoBlocking)
2871 {
2872 RTSpinlockRelease(pDevExt->Spinlock);
2873 pUsagePre = (PSUPDRVUSAGE)RTMemAlloc(sizeof(*pUsagePre));
2874 if (!pUsagePre)
2875 return VERR_NO_MEMORY;
2876
2877 RTSpinlockAcquire(pDevExt->Spinlock);
2878 if (RT_UNLIKELY(pObj->u32Magic != SUPDRVOBJ_MAGIC))
2879 {
2880 RTSpinlockRelease(pDevExt->Spinlock);
2881
2882 AssertMsgFailed(("pvObj=%p magic=%#x\n", pvObj, pObj->u32Magic));
2883 return VERR_WRONG_ORDER;
2884 }
2885 }
2886
2887 /*
2888 * Reference the object.
2889 */
2890 pObj->cUsage++;
2891
2892 /*
2893 * Look for the session record.
2894 */
2895 for (pUsage = pSession->pUsage; pUsage; pUsage = pUsage->pNext)
2896 {
2897 /*Log(("SUPR0AddRef: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext));*/
2898 if (pUsage->pObj == pObj)
2899 break;
2900 }
2901 if (pUsage)
2902 pUsage->cUsage++;
2903 else if (pUsagePre)
2904 {
2905 /* create a new session record. */
2906 pUsagePre->cUsage = 1;
2907 pUsagePre->pObj = pObj;
2908 pUsagePre->pNext = pSession->pUsage;
2909 pSession->pUsage = pUsagePre;
2910 /*Log(("SUPR0AddRef: pUsagePre=%p:{.pObj=%p, .pNext=%p}\n", pUsagePre, pUsagePre->pObj, pUsagePre->pNext));*/
2911
2912 pUsagePre = NULL;
2913 }
2914 else
2915 {
2916 pObj->cUsage--;
2917 rc = VERR_TRY_AGAIN;
2918 }
2919
2920 /*
2921 * Put any unused usage record into the free list..
2922 */
2923 if (pUsagePre)
2924 {
2925 pUsagePre->pNext = pDevExt->pUsageFree;
2926 pDevExt->pUsageFree = pUsagePre;
2927 }
2928
2929 RTSpinlockRelease(pDevExt->Spinlock);
2930
2931 return rc;
2932}
2933
2934
2935/**
2936 * Decrement / destroy a reference counter record for an object.
2937 *
2938 * The object is uniquely identified by pfnDestructor+pvUser1+pvUser2.
2939 *
2940 * @returns IPRT status code.
2941 * @retval VINF_SUCCESS if not destroyed.
2942 * @retval VINF_OBJECT_DESTROYED if it's destroyed by this release call.
2943 * @retval VERR_INVALID_PARAMETER if the object isn't valid. Will assert in
2944 * string builds.
2945 *
2946 * @param pvObj The identifier returned by SUPR0ObjRegister().
2947 * @param pSession The session which is referencing the object.
2948 */
2949SUPR0DECL(int) SUPR0ObjRelease(void *pvObj, PSUPDRVSESSION pSession)
2950{
2951 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
2952 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
2953 int rc = VERR_INVALID_PARAMETER;
2954 PSUPDRVUSAGE pUsage;
2955 PSUPDRVUSAGE pUsagePrev;
2956
2957 /*
2958 * Validate the input.
2959 */
2960 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2961 AssertMsgReturn(VALID_PTR(pObj)&& pObj->u32Magic == SUPDRVOBJ_MAGIC,
2962 ("Invalid pvObj=%p magic=%#x (expected %#x)\n", pvObj, pObj ? pObj->u32Magic : 0, SUPDRVOBJ_MAGIC),
2963 VERR_INVALID_PARAMETER);
2964
2965 /*
2966 * Acquire the spinlock and look for the usage record.
2967 */
2968 RTSpinlockAcquire(pDevExt->Spinlock);
2969
2970 for (pUsagePrev = NULL, pUsage = pSession->pUsage;
2971 pUsage;
2972 pUsagePrev = pUsage, pUsage = pUsage->pNext)
2973 {
2974 /*Log2(("SUPR0ObjRelease: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext));*/
2975 if (pUsage->pObj == pObj)
2976 {
2977 rc = VINF_SUCCESS;
2978 AssertMsg(pUsage->cUsage >= 1 && pObj->cUsage >= pUsage->cUsage, ("glob %d; sess %d\n", pObj->cUsage, pUsage->cUsage));
2979 if (pUsage->cUsage > 1)
2980 {
2981 pObj->cUsage--;
2982 pUsage->cUsage--;
2983 }
2984 else
2985 {
2986 /*
2987 * Free the session record.
2988 */
2989 if (pUsagePrev)
2990 pUsagePrev->pNext = pUsage->pNext;
2991 else
2992 pSession->pUsage = pUsage->pNext;
2993 pUsage->pNext = pDevExt->pUsageFree;
2994 pDevExt->pUsageFree = pUsage;
2995
2996 /* What about the object? */
2997 if (pObj->cUsage > 1)
2998 pObj->cUsage--;
2999 else
3000 {
3001 /*
3002 * Object is to be destroyed, unlink it.
3003 */
3004 pObj->u32Magic = SUPDRVOBJ_MAGIC_DEAD;
3005 rc = VINF_OBJECT_DESTROYED;
3006 if (pDevExt->pObjs == pObj)
3007 pDevExt->pObjs = pObj->pNext;
3008 else
3009 {
3010 PSUPDRVOBJ pObjPrev;
3011 for (pObjPrev = pDevExt->pObjs; pObjPrev; pObjPrev = pObjPrev->pNext)
3012 if (pObjPrev->pNext == pObj)
3013 {
3014 pObjPrev->pNext = pObj->pNext;
3015 break;
3016 }
3017 Assert(pObjPrev);
3018 }
3019 }
3020 }
3021 break;
3022 }
3023 }
3024
3025 RTSpinlockRelease(pDevExt->Spinlock);
3026
3027 /*
3028 * Call the destructor and free the object if required.
3029 */
3030 if (rc == VINF_OBJECT_DESTROYED)
3031 {
3032 Log(("SUPR0ObjRelease: destroying %p/%d (%p/%p) cpid=%RTproc pid=%RTproc dtor=%p\n",
3033 pObj, pObj->enmType, pObj->pvUser1, pObj->pvUser2, pObj->CreatorProcess, RTProcSelf(), pObj->pfnDestructor));
3034 if (pObj->pfnDestructor)
3035 pObj->pfnDestructor(pObj, pObj->pvUser1, pObj->pvUser2);
3036 RTMemFree(pObj);
3037 }
3038
3039 AssertMsg(pUsage, ("pvObj=%p\n", pvObj));
3040 return rc;
3041}
3042
3043
3044/**
3045 * Verifies that the current process can access the specified object.
3046 *
3047 * @returns The following IPRT status code:
3048 * @retval VINF_SUCCESS if access was granted.
3049 * @retval VERR_PERMISSION_DENIED if denied access.
3050 * @retval VERR_INVALID_PARAMETER if invalid parameter.
3051 *
3052 * @param pvObj The identifier returned by SUPR0ObjRegister().
3053 * @param pSession The session which wishes to access the object.
3054 * @param pszObjName Object string name. This is optional and depends on the object type.
3055 *
3056 * @remark The caller is responsible for making sure the object isn't removed while
3057 * we're inside this function. If uncertain about this, just call AddRef before calling us.
3058 */
3059SUPR0DECL(int) SUPR0ObjVerifyAccess(void *pvObj, PSUPDRVSESSION pSession, const char *pszObjName)
3060{
3061 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
3062 int rc;
3063
3064 /*
3065 * Validate the input.
3066 */
3067 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3068 AssertMsgReturn(VALID_PTR(pObj) && pObj->u32Magic == SUPDRVOBJ_MAGIC,
3069 ("Invalid pvObj=%p magic=%#x (exepcted %#x)\n", pvObj, pObj ? pObj->u32Magic : 0, SUPDRVOBJ_MAGIC),
3070 VERR_INVALID_PARAMETER);
3071
3072 /*
3073 * Check access. (returns true if a decision has been made.)
3074 */
3075 rc = VERR_INTERNAL_ERROR;
3076 if (supdrvOSObjCanAccess(pObj, pSession, pszObjName, &rc))
3077 return rc;
3078
3079 /*
3080 * Default policy is to allow the user to access his own
3081 * stuff but nothing else.
3082 */
3083 if (pObj->CreatorUid == pSession->Uid)
3084 return VINF_SUCCESS;
3085 return VERR_PERMISSION_DENIED;
3086}
3087
3088
3089/**
3090 * API for the VMMR0 module to get the SUPDRVSESSION::pSessionVM member.
3091 *
3092 * @returns The associated VM pointer.
3093 * @param pSession The session of the current thread.
3094 */
3095SUPR0DECL(PVM) SUPR0GetSessionVM(PSUPDRVSESSION pSession)
3096{
3097 AssertReturn(SUP_IS_SESSION_VALID(pSession), NULL);
3098 return pSession->pSessionVM;
3099}
3100
3101
3102/**
3103 * API for the VMMR0 module to get the SUPDRVSESSION::pSessionGVM member.
3104 *
3105 * @returns The associated GVM pointer.
3106 * @param pSession The session of the current thread.
3107 */
3108SUPR0DECL(PGVM) SUPR0GetSessionGVM(PSUPDRVSESSION pSession)
3109{
3110 AssertReturn(SUP_IS_SESSION_VALID(pSession), NULL);
3111 return pSession->pSessionGVM;
3112}
3113
3114
3115/**
3116 * API for the VMMR0 module to work the SUPDRVSESSION::pSessionVM member.
3117 *
3118 * This will fail if there is already a VM associated with the session and pVM
3119 * isn't NULL.
3120 *
3121 * @retval VINF_SUCCESS
3122 * @retval VERR_ALREADY_EXISTS if there already is a VM associated with the
3123 * session.
3124 * @retval VERR_INVALID_PARAMETER if only one of the parameters are NULL or if
3125 * the session is invalid.
3126 *
3127 * @param pSession The session of the current thread.
3128 * @param pGVM The GVM to associate with the session. Pass NULL to
3129 * dissassociate.
3130 * @param pVM The VM to associate with the session. Pass NULL to
3131 * dissassociate.
3132 */
3133SUPR0DECL(int) SUPR0SetSessionVM(PSUPDRVSESSION pSession, PGVM pGVM, PVM pVM)
3134{
3135 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3136 AssertReturn((pGVM != NULL) == (pVM != NULL), VERR_INVALID_PARAMETER);
3137
3138 RTSpinlockAcquire(pSession->pDevExt->Spinlock);
3139 if (pGVM)
3140 {
3141 if (!pSession->pSessionGVM)
3142 {
3143 pSession->pSessionGVM = pGVM;
3144 pSession->pSessionVM = pVM;
3145 pSession->pFastIoCtrlVM = NULL;
3146 }
3147 else
3148 {
3149 RTSpinlockRelease(pSession->pDevExt->Spinlock);
3150 SUPR0Printf("SUPR0SetSessionVM: Unable to associated GVM/VM %p/%p with session %p as it has %p/%p already!\n",
3151 pGVM, pVM, pSession, pSession->pSessionGVM, pSession->pSessionVM);
3152 return VERR_ALREADY_EXISTS;
3153 }
3154 }
3155 else
3156 {
3157 pSession->pSessionGVM = NULL;
3158 pSession->pSessionVM = NULL;
3159 pSession->pFastIoCtrlVM = NULL;
3160 }
3161 RTSpinlockRelease(pSession->pDevExt->Spinlock);
3162 return VINF_SUCCESS;
3163}
3164
3165
3166/**
3167 * Lock pages.
3168 *
3169 * @returns IPRT status code.
3170 * @param pSession Session to which the locked memory should be associated.
3171 * @param pvR3 Start of the memory range to lock.
3172 * This must be page aligned.
3173 * @param cPages Number of pages to lock.
3174 * @param paPages Where to put the physical addresses of locked memory.
3175 */
3176SUPR0DECL(int) SUPR0LockMem(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t cPages, PRTHCPHYS paPages)
3177{
3178 int rc;
3179 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3180 const size_t cb = (size_t)cPages << PAGE_SHIFT;
3181 LogFlow(("SUPR0LockMem: pSession=%p pvR3=%p cPages=%d paPages=%p\n", pSession, (void *)pvR3, cPages, paPages));
3182
3183 /*
3184 * Verify input.
3185 */
3186 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3187 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
3188 if ( RT_ALIGN_R3PT(pvR3, PAGE_SIZE, RTR3PTR) != pvR3
3189 || !pvR3)
3190 {
3191 Log(("pvR3 (%p) must be page aligned and not NULL!\n", (void *)pvR3));
3192 return VERR_INVALID_PARAMETER;
3193 }
3194
3195 /*
3196 * Let IPRT do the job.
3197 */
3198 Mem.eType = MEMREF_TYPE_LOCKED;
3199 rc = RTR0MemObjLockUser(&Mem.MemObj, pvR3, cb, RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
3200 if (RT_SUCCESS(rc))
3201 {
3202 uint32_t iPage = cPages;
3203 AssertMsg(RTR0MemObjAddressR3(Mem.MemObj) == pvR3, ("%p == %p\n", RTR0MemObjAddressR3(Mem.MemObj), pvR3));
3204 AssertMsg(RTR0MemObjSize(Mem.MemObj) == cb, ("%x == %x\n", RTR0MemObjSize(Mem.MemObj), cb));
3205
3206 while (iPage-- > 0)
3207 {
3208 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MemObj, iPage);
3209 if (RT_UNLIKELY(paPages[iPage] == NIL_RTCCPHYS))
3210 {
3211 AssertMsgFailed(("iPage=%d\n", iPage));
3212 rc = VERR_INTERNAL_ERROR;
3213 break;
3214 }
3215 }
3216 if (RT_SUCCESS(rc))
3217 rc = supdrvMemAdd(&Mem, pSession);
3218 if (RT_FAILURE(rc))
3219 {
3220 int rc2 = RTR0MemObjFree(Mem.MemObj, false);
3221 AssertRC(rc2);
3222 }
3223 }
3224
3225 return rc;
3226}
3227
3228
3229/**
3230 * Unlocks the memory pointed to by pv.
3231 *
3232 * @returns IPRT status code.
3233 * @param pSession Session to which the memory was locked.
3234 * @param pvR3 Memory to unlock.
3235 */
3236SUPR0DECL(int) SUPR0UnlockMem(PSUPDRVSESSION pSession, RTR3PTR pvR3)
3237{
3238 LogFlow(("SUPR0UnlockMem: pSession=%p pvR3=%p\n", pSession, (void *)pvR3));
3239 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3240 return supdrvMemRelease(pSession, (RTHCUINTPTR)pvR3, MEMREF_TYPE_LOCKED);
3241}
3242
3243
3244/**
3245 * Allocates a chunk of page aligned memory with contiguous and fixed physical
3246 * backing.
3247 *
3248 * @returns IPRT status code.
3249 * @param pSession Session data.
3250 * @param cPages Number of pages to allocate.
3251 * @param ppvR0 Where to put the address of Ring-0 mapping the allocated memory.
3252 * @param ppvR3 Where to put the address of Ring-3 mapping the allocated memory.
3253 * @param pHCPhys Where to put the physical address of allocated memory.
3254 */
3255SUPR0DECL(int) SUPR0ContAlloc(PSUPDRVSESSION pSession, uint32_t cPages, PRTR0PTR ppvR0, PRTR3PTR ppvR3, PRTHCPHYS pHCPhys)
3256{
3257 int rc;
3258 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3259 LogFlow(("SUPR0ContAlloc: pSession=%p cPages=%d ppvR0=%p ppvR3=%p pHCPhys=%p\n", pSession, cPages, ppvR0, ppvR3, pHCPhys));
3260
3261 /*
3262 * Validate input.
3263 */
3264 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3265 if (!ppvR3 || !ppvR0 || !pHCPhys)
3266 {
3267 Log(("Null pointer. All of these should be set: pSession=%p ppvR0=%p ppvR3=%p pHCPhys=%p\n",
3268 pSession, ppvR0, ppvR3, pHCPhys));
3269 return VERR_INVALID_PARAMETER;
3270
3271 }
3272 if (cPages < 1 || cPages >= 256)
3273 {
3274 Log(("Illegal request cPages=%d, must be greater than 0 and smaller than 256.\n", cPages));
3275 return VERR_PAGE_COUNT_OUT_OF_RANGE;
3276 }
3277
3278 /*
3279 * Let IPRT do the job.
3280 */
3281 rc = RTR0MemObjAllocCont(&Mem.MemObj, cPages << PAGE_SHIFT, true /* executable R0 mapping */);
3282 if (RT_SUCCESS(rc))
3283 {
3284 int rc2;
3285 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
3286 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3287 if (RT_SUCCESS(rc))
3288 {
3289 Mem.eType = MEMREF_TYPE_CONT;
3290 rc = supdrvMemAdd(&Mem, pSession);
3291 if (!rc)
3292 {
3293 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3294 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3295 *pHCPhys = RTR0MemObjGetPagePhysAddr(Mem.MemObj, 0);
3296 return 0;
3297 }
3298
3299 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3300 AssertRC(rc2);
3301 }
3302 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3303 AssertRC(rc2);
3304 }
3305
3306 return rc;
3307}
3308
3309
3310/**
3311 * Frees memory allocated using SUPR0ContAlloc().
3312 *
3313 * @returns IPRT status code.
3314 * @param pSession The session to which the memory was allocated.
3315 * @param uPtr Pointer to the memory (ring-3 or ring-0).
3316 */
3317SUPR0DECL(int) SUPR0ContFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
3318{
3319 LogFlow(("SUPR0ContFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
3320 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3321 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_CONT);
3322}
3323
3324
3325/**
3326 * Allocates a chunk of page aligned memory with fixed physical backing below 4GB.
3327 *
3328 * The memory isn't zeroed.
3329 *
3330 * @returns IPRT status code.
3331 * @param pSession Session data.
3332 * @param cPages Number of pages to allocate.
3333 * @param ppvR0 Where to put the address of Ring-0 mapping of the allocated memory.
3334 * @param ppvR3 Where to put the address of Ring-3 mapping of the allocated memory.
3335 * @param paPages Where to put the physical addresses of allocated memory.
3336 */
3337SUPR0DECL(int) SUPR0LowAlloc(PSUPDRVSESSION pSession, uint32_t cPages, PRTR0PTR ppvR0, PRTR3PTR ppvR3, PRTHCPHYS paPages)
3338{
3339 unsigned iPage;
3340 int rc;
3341 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3342 LogFlow(("SUPR0LowAlloc: pSession=%p cPages=%d ppvR3=%p ppvR0=%p paPages=%p\n", pSession, cPages, ppvR3, ppvR0, paPages));
3343
3344 /*
3345 * Validate input.
3346 */
3347 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3348 if (!ppvR3 || !ppvR0 || !paPages)
3349 {
3350 Log(("Null pointer. All of these should be set: pSession=%p ppvR3=%p ppvR0=%p paPages=%p\n",
3351 pSession, ppvR3, ppvR0, paPages));
3352 return VERR_INVALID_PARAMETER;
3353
3354 }
3355 if (cPages < 1 || cPages >= 256)
3356 {
3357 Log(("Illegal request cPages=%d, must be greater than 0 and smaller than 256.\n", cPages));
3358 return VERR_PAGE_COUNT_OUT_OF_RANGE;
3359 }
3360
3361 /*
3362 * Let IPRT do the work.
3363 */
3364 rc = RTR0MemObjAllocLow(&Mem.MemObj, cPages << PAGE_SHIFT, true /* executable ring-0 mapping */);
3365 if (RT_SUCCESS(rc))
3366 {
3367 int rc2;
3368 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
3369 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3370 if (RT_SUCCESS(rc))
3371 {
3372 Mem.eType = MEMREF_TYPE_LOW;
3373 rc = supdrvMemAdd(&Mem, pSession);
3374 if (!rc)
3375 {
3376 for (iPage = 0; iPage < cPages; iPage++)
3377 {
3378 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MemObj, iPage);
3379 AssertMsg(!(paPages[iPage] & (PAGE_SIZE - 1)), ("iPage=%d Phys=%RHp\n", paPages[iPage]));
3380 }
3381 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3382 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3383 return 0;
3384 }
3385
3386 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3387 AssertRC(rc2);
3388 }
3389
3390 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3391 AssertRC(rc2);
3392 }
3393
3394 return rc;
3395}
3396
3397
3398/**
3399 * Frees memory allocated using SUPR0LowAlloc().
3400 *
3401 * @returns IPRT status code.
3402 * @param pSession The session to which the memory was allocated.
3403 * @param uPtr Pointer to the memory (ring-3 or ring-0).
3404 */
3405SUPR0DECL(int) SUPR0LowFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
3406{
3407 LogFlow(("SUPR0LowFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
3408 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3409 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_LOW);
3410}
3411
3412
3413
3414/**
3415 * Allocates a chunk of memory with both R0 and R3 mappings.
3416 * The memory is fixed and it's possible to query the physical addresses using SUPR0MemGetPhys().
3417 *
3418 * @returns IPRT status code.
3419 * @param pSession The session to associated the allocation with.
3420 * @param cb Number of bytes to allocate.
3421 * @param ppvR0 Where to store the address of the Ring-0 mapping.
3422 * @param ppvR3 Where to store the address of the Ring-3 mapping.
3423 */
3424SUPR0DECL(int) SUPR0MemAlloc(PSUPDRVSESSION pSession, uint32_t cb, PRTR0PTR ppvR0, PRTR3PTR ppvR3)
3425{
3426 int rc;
3427 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3428 LogFlow(("SUPR0MemAlloc: pSession=%p cb=%d ppvR0=%p ppvR3=%p\n", pSession, cb, ppvR0, ppvR3));
3429
3430 /*
3431 * Validate input.
3432 */
3433 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3434 AssertPtrReturn(ppvR0, VERR_INVALID_POINTER);
3435 AssertPtrReturn(ppvR3, VERR_INVALID_POINTER);
3436 if (cb < 1 || cb >= _4M)
3437 {
3438 Log(("Illegal request cb=%u; must be greater than 0 and smaller than 4MB.\n", cb));
3439 return VERR_INVALID_PARAMETER;
3440 }
3441
3442 /*
3443 * Let IPRT do the work.
3444 */
3445 rc = RTR0MemObjAllocPage(&Mem.MemObj, cb, true /* executable ring-0 mapping */);
3446 if (RT_SUCCESS(rc))
3447 {
3448 int rc2;
3449 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
3450 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3451 if (RT_SUCCESS(rc))
3452 {
3453 Mem.eType = MEMREF_TYPE_MEM;
3454 rc = supdrvMemAdd(&Mem, pSession);
3455 if (!rc)
3456 {
3457 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3458 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3459 return VINF_SUCCESS;
3460 }
3461
3462 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3463 AssertRC(rc2);
3464 }
3465
3466 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3467 AssertRC(rc2);
3468 }
3469
3470 return rc;
3471}
3472
3473
3474/**
3475 * Get the physical addresses of memory allocated using SUPR0MemAlloc().
3476 *
3477 * @returns IPRT status code.
3478 * @param pSession The session to which the memory was allocated.
3479 * @param uPtr The Ring-0 or Ring-3 address returned by SUPR0MemAlloc().
3480 * @param paPages Where to store the physical addresses.
3481 */
3482SUPR0DECL(int) SUPR0MemGetPhys(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, PSUPPAGE paPages) /** @todo switch this bugger to RTHCPHYS */
3483{
3484 PSUPDRVBUNDLE pBundle;
3485 LogFlow(("SUPR0MemGetPhys: pSession=%p uPtr=%p paPages=%p\n", pSession, (void *)uPtr, paPages));
3486
3487 /*
3488 * Validate input.
3489 */
3490 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3491 AssertPtrReturn(paPages, VERR_INVALID_POINTER);
3492 AssertReturn(uPtr, VERR_INVALID_PARAMETER);
3493
3494 /*
3495 * Search for the address.
3496 */
3497 RTSpinlockAcquire(pSession->Spinlock);
3498 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3499 {
3500 if (pBundle->cUsed > 0)
3501 {
3502 unsigned i;
3503 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
3504 {
3505 if ( pBundle->aMem[i].eType == MEMREF_TYPE_MEM
3506 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3507 && ( (RTHCUINTPTR)RTR0MemObjAddress(pBundle->aMem[i].MemObj) == uPtr
3508 || ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
3509 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == uPtr)
3510 )
3511 )
3512 {
3513 const size_t cPages = RTR0MemObjSize(pBundle->aMem[i].MemObj) >> PAGE_SHIFT;
3514 size_t iPage;
3515 for (iPage = 0; iPage < cPages; iPage++)
3516 {
3517 paPages[iPage].Phys = RTR0MemObjGetPagePhysAddr(pBundle->aMem[i].MemObj, iPage);
3518 paPages[iPage].uReserved = 0;
3519 }
3520 RTSpinlockRelease(pSession->Spinlock);
3521 return VINF_SUCCESS;
3522 }
3523 }
3524 }
3525 }
3526 RTSpinlockRelease(pSession->Spinlock);
3527 Log(("Failed to find %p!!!\n", (void *)uPtr));
3528 return VERR_INVALID_PARAMETER;
3529}
3530
3531
3532/**
3533 * Free memory allocated by SUPR0MemAlloc().
3534 *
3535 * @returns IPRT status code.
3536 * @param pSession The session owning the allocation.
3537 * @param uPtr The Ring-0 or Ring-3 address returned by SUPR0MemAlloc().
3538 */
3539SUPR0DECL(int) SUPR0MemFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
3540{
3541 LogFlow(("SUPR0MemFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
3542 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3543 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_MEM);
3544}
3545
3546
3547/**
3548 * Allocates a chunk of memory with a kernel or/and a user mode mapping.
3549 *
3550 * The memory is fixed and it's possible to query the physical addresses using
3551 * SUPR0MemGetPhys().
3552 *
3553 * @returns IPRT status code.
3554 * @param pSession The session to associated the allocation with.
3555 * @param cPages The number of pages to allocate.
3556 * @param fFlags Flags, reserved for the future. Must be zero.
3557 * @param ppvR3 Where to store the address of the Ring-3 mapping.
3558 * NULL if no ring-3 mapping.
3559 * @param ppvR0 Where to store the address of the Ring-0 mapping.
3560 * NULL if no ring-0 mapping.
3561 * @param paPages Where to store the addresses of the pages. Optional.
3562 */
3563SUPR0DECL(int) SUPR0PageAllocEx(PSUPDRVSESSION pSession, uint32_t cPages, uint32_t fFlags, PRTR3PTR ppvR3, PRTR0PTR ppvR0, PRTHCPHYS paPages)
3564{
3565 int rc;
3566 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3567 LogFlow(("SUPR0PageAlloc: pSession=%p cb=%d ppvR3=%p\n", pSession, cPages, ppvR3));
3568
3569 /*
3570 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
3571 */
3572 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3573 AssertPtrNullReturn(ppvR3, VERR_INVALID_POINTER);
3574 AssertPtrNullReturn(ppvR0, VERR_INVALID_POINTER);
3575 AssertReturn(ppvR3 || ppvR0, VERR_INVALID_PARAMETER);
3576 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
3577 if (cPages < 1 || cPages > VBOX_MAX_ALLOC_PAGE_COUNT)
3578 {
3579 Log(("SUPR0PageAlloc: Illegal request cb=%u; must be greater than 0 and smaller than %uMB (VBOX_MAX_ALLOC_PAGE_COUNT pages).\n", cPages, VBOX_MAX_ALLOC_PAGE_COUNT * (_1M / _4K)));
3580 return VERR_PAGE_COUNT_OUT_OF_RANGE;
3581 }
3582
3583 /*
3584 * Let IPRT do the work.
3585 */
3586 if (ppvR0)
3587 rc = RTR0MemObjAllocPage(&Mem.MemObj, (size_t)cPages * PAGE_SIZE, true /* fExecutable */);
3588 else
3589 rc = RTR0MemObjAllocPhysNC(&Mem.MemObj, (size_t)cPages * PAGE_SIZE, NIL_RTHCPHYS);
3590 if (RT_SUCCESS(rc))
3591 {
3592 int rc2;
3593 if (ppvR3)
3594 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
3595 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3596 else
3597 Mem.MapObjR3 = NIL_RTR0MEMOBJ;
3598 if (RT_SUCCESS(rc))
3599 {
3600 Mem.eType = MEMREF_TYPE_PAGE;
3601 rc = supdrvMemAdd(&Mem, pSession);
3602 if (!rc)
3603 {
3604 if (ppvR3)
3605 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3606 if (ppvR0)
3607 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3608 if (paPages)
3609 {
3610 uint32_t iPage = cPages;
3611 while (iPage-- > 0)
3612 {
3613 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MapObjR3, iPage);
3614 Assert(paPages[iPage] != NIL_RTHCPHYS);
3615 }
3616 }
3617 return VINF_SUCCESS;
3618 }
3619
3620 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3621 AssertRC(rc2);
3622 }
3623
3624 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3625 AssertRC(rc2);
3626 }
3627 return rc;
3628}
3629
3630
3631/**
3632 * Maps a chunk of memory previously allocated by SUPR0PageAllocEx into kernel
3633 * space.
3634 *
3635 * @returns IPRT status code.
3636 * @param pSession The session to associated the allocation with.
3637 * @param pvR3 The ring-3 address returned by SUPR0PageAllocEx.
3638 * @param offSub Where to start mapping. Must be page aligned.
3639 * @param cbSub How much to map. Must be page aligned.
3640 * @param fFlags Flags, MBZ.
3641 * @param ppvR0 Where to return the address of the ring-0 mapping on
3642 * success.
3643 */
3644SUPR0DECL(int) SUPR0PageMapKernel(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t offSub, uint32_t cbSub,
3645 uint32_t fFlags, PRTR0PTR ppvR0)
3646{
3647 int rc;
3648 PSUPDRVBUNDLE pBundle;
3649 RTR0MEMOBJ hMemObj = NIL_RTR0MEMOBJ;
3650 LogFlow(("SUPR0PageMapKernel: pSession=%p pvR3=%p offSub=%#x cbSub=%#x\n", pSession, pvR3, offSub, cbSub));
3651
3652 /*
3653 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
3654 */
3655 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3656 AssertPtrNullReturn(ppvR0, VERR_INVALID_POINTER);
3657 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
3658 AssertReturn(!(offSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3659 AssertReturn(!(cbSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3660 AssertReturn(cbSub, VERR_INVALID_PARAMETER);
3661
3662 /*
3663 * Find the memory object.
3664 */
3665 RTSpinlockAcquire(pSession->Spinlock);
3666 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3667 {
3668 if (pBundle->cUsed > 0)
3669 {
3670 unsigned i;
3671 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
3672 {
3673 if ( ( pBundle->aMem[i].eType == MEMREF_TYPE_PAGE
3674 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3675 && pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
3676 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3)
3677 || ( pBundle->aMem[i].eType == MEMREF_TYPE_LOCKED
3678 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3679 && pBundle->aMem[i].MapObjR3 == NIL_RTR0MEMOBJ
3680 && RTR0MemObjAddressR3(pBundle->aMem[i].MemObj) == pvR3))
3681 {
3682 hMemObj = pBundle->aMem[i].MemObj;
3683 break;
3684 }
3685 }
3686 }
3687 }
3688 RTSpinlockRelease(pSession->Spinlock);
3689
3690 rc = VERR_INVALID_PARAMETER;
3691 if (hMemObj != NIL_RTR0MEMOBJ)
3692 {
3693 /*
3694 * Do some further input validations before calling IPRT.
3695 * (Cleanup is done indirectly by telling RTR0MemObjFree to include mappings.)
3696 */
3697 size_t cbMemObj = RTR0MemObjSize(hMemObj);
3698 if ( offSub < cbMemObj
3699 && cbSub <= cbMemObj
3700 && offSub + cbSub <= cbMemObj)
3701 {
3702 RTR0MEMOBJ hMapObj;
3703 rc = RTR0MemObjMapKernelEx(&hMapObj, hMemObj, (void *)-1, 0,
3704 RTMEM_PROT_READ | RTMEM_PROT_WRITE, offSub, cbSub);
3705 if (RT_SUCCESS(rc))
3706 *ppvR0 = RTR0MemObjAddress(hMapObj);
3707 }
3708 else
3709 SUPR0Printf("SUPR0PageMapKernel: cbMemObj=%#x offSub=%#x cbSub=%#x\n", cbMemObj, offSub, cbSub);
3710
3711 }
3712 return rc;
3713}
3714
3715
3716/**
3717 * Changes the page level protection of one or more pages previously allocated
3718 * by SUPR0PageAllocEx.
3719 *
3720 * @returns IPRT status code.
3721 * @param pSession The session to associated the allocation with.
3722 * @param pvR3 The ring-3 address returned by SUPR0PageAllocEx.
3723 * NIL_RTR3PTR if the ring-3 mapping should be unaffected.
3724 * @param pvR0 The ring-0 address returned by SUPR0PageAllocEx.
3725 * NIL_RTR0PTR if the ring-0 mapping should be unaffected.
3726 * @param offSub Where to start changing. Must be page aligned.
3727 * @param cbSub How much to change. Must be page aligned.
3728 * @param fProt The new page level protection, see RTMEM_PROT_*.
3729 */
3730SUPR0DECL(int) SUPR0PageProtect(PSUPDRVSESSION pSession, RTR3PTR pvR3, RTR0PTR pvR0, uint32_t offSub, uint32_t cbSub, uint32_t fProt)
3731{
3732 int rc;
3733 PSUPDRVBUNDLE pBundle;
3734 RTR0MEMOBJ hMemObjR0 = NIL_RTR0MEMOBJ;
3735 RTR0MEMOBJ hMemObjR3 = NIL_RTR0MEMOBJ;
3736 LogFlow(("SUPR0PageProtect: pSession=%p pvR3=%p pvR0=%p offSub=%#x cbSub=%#x fProt-%#x\n", pSession, pvR3, pvR0, offSub, cbSub, fProt));
3737
3738 /*
3739 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
3740 */
3741 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3742 AssertReturn(!(fProt & ~(RTMEM_PROT_READ | RTMEM_PROT_WRITE | RTMEM_PROT_EXEC | RTMEM_PROT_NONE)), VERR_INVALID_PARAMETER);
3743 AssertReturn(!(offSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3744 AssertReturn(!(cbSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3745 AssertReturn(cbSub, VERR_INVALID_PARAMETER);
3746
3747 /*
3748 * Find the memory object.
3749 */
3750 RTSpinlockAcquire(pSession->Spinlock);
3751 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3752 {
3753 if (pBundle->cUsed > 0)
3754 {
3755 unsigned i;
3756 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
3757 {
3758 if ( pBundle->aMem[i].eType == MEMREF_TYPE_PAGE
3759 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3760 && ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
3761 || pvR3 == NIL_RTR3PTR)
3762 && ( pvR0 == NIL_RTR0PTR
3763 || RTR0MemObjAddress(pBundle->aMem[i].MemObj) == pvR0)
3764 && ( pvR3 == NIL_RTR3PTR
3765 || RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3))
3766 {
3767 if (pvR0 != NIL_RTR0PTR)
3768 hMemObjR0 = pBundle->aMem[i].MemObj;
3769 if (pvR3 != NIL_RTR3PTR)
3770 hMemObjR3 = pBundle->aMem[i].MapObjR3;
3771 break;
3772 }
3773 }
3774 }
3775 }
3776 RTSpinlockRelease(pSession->Spinlock);
3777
3778 rc = VERR_INVALID_PARAMETER;
3779 if ( hMemObjR0 != NIL_RTR0MEMOBJ
3780 || hMemObjR3 != NIL_RTR0MEMOBJ)
3781 {
3782 /*
3783 * Do some further input validations before calling IPRT.
3784 */
3785 size_t cbMemObj = hMemObjR0 != NIL_RTR0PTR ? RTR0MemObjSize(hMemObjR0) : RTR0MemObjSize(hMemObjR3);
3786 if ( offSub < cbMemObj
3787 && cbSub <= cbMemObj
3788 && offSub + cbSub <= cbMemObj)
3789 {
3790 rc = VINF_SUCCESS;
3791 if (hMemObjR3 != NIL_RTR0PTR)
3792 rc = RTR0MemObjProtect(hMemObjR3, offSub, cbSub, fProt);
3793 if (hMemObjR0 != NIL_RTR0PTR && RT_SUCCESS(rc))
3794 rc = RTR0MemObjProtect(hMemObjR0, offSub, cbSub, fProt);
3795 }
3796 else
3797 SUPR0Printf("SUPR0PageMapKernel: cbMemObj=%#x offSub=%#x cbSub=%#x\n", cbMemObj, offSub, cbSub);
3798
3799 }
3800 return rc;
3801
3802}
3803
3804
3805/**
3806 * Free memory allocated by SUPR0PageAlloc() and SUPR0PageAllocEx().
3807 *
3808 * @returns IPRT status code.
3809 * @param pSession The session owning the allocation.
3810 * @param pvR3 The Ring-3 address returned by SUPR0PageAlloc() or
3811 * SUPR0PageAllocEx().
3812 */
3813SUPR0DECL(int) SUPR0PageFree(PSUPDRVSESSION pSession, RTR3PTR pvR3)
3814{
3815 LogFlow(("SUPR0PageFree: pSession=%p pvR3=%p\n", pSession, (void *)pvR3));
3816 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3817 return supdrvMemRelease(pSession, (RTHCUINTPTR)pvR3, MEMREF_TYPE_PAGE);
3818}
3819
3820
3821/**
3822 * Reports a bad context, currenctly that means EFLAGS.AC is 0 instead of 1.
3823 *
3824 * @param pDevExt The device extension.
3825 * @param pszFile The source file where the caller detected the bad
3826 * context.
3827 * @param uLine The line number in @a pszFile.
3828 * @param pszExtra Optional additional message to give further hints.
3829 */
3830void VBOXCALL supdrvBadContext(PSUPDRVDEVEXT pDevExt, const char *pszFile, uint32_t uLine, const char *pszExtra)
3831{
3832 uint32_t cCalls;
3833
3834 /*
3835 * Shorten the filename before displaying the message.
3836 */
3837 for (;;)
3838 {
3839 const char *pszTmp = strchr(pszFile, '/');
3840 if (!pszTmp)
3841 pszTmp = strchr(pszFile, '\\');
3842 if (!pszTmp)
3843 break;
3844 pszFile = pszTmp + 1;
3845 }
3846 if (RT_VALID_PTR(pszExtra) && *pszExtra)
3847 SUPR0Printf("vboxdrv: Bad CPU context error at line %u in %s: %s\n", uLine, pszFile, pszExtra);
3848 else
3849 SUPR0Printf("vboxdrv: Bad CPU context error at line %u in %s!\n", uLine, pszFile);
3850
3851 /*
3852 * Record the incident so that we stand a chance of blocking I/O controls
3853 * before panicing the system.
3854 */
3855 cCalls = ASMAtomicIncU32(&pDevExt->cBadContextCalls);
3856 if (cCalls > UINT32_MAX - _1K)
3857 ASMAtomicWriteU32(&pDevExt->cBadContextCalls, UINT32_MAX - _1K);
3858}
3859
3860
3861/**
3862 * Reports a bad context, currenctly that means EFLAGS.AC is 0 instead of 1.
3863 *
3864 * @param pSession The session of the caller.
3865 * @param pszFile The source file where the caller detected the bad
3866 * context.
3867 * @param uLine The line number in @a pszFile.
3868 * @param pszExtra Optional additional message to give further hints.
3869 */
3870SUPR0DECL(void) SUPR0BadContext(PSUPDRVSESSION pSession, const char *pszFile, uint32_t uLine, const char *pszExtra)
3871{
3872 PSUPDRVDEVEXT pDevExt;
3873
3874 AssertReturnVoid(SUP_IS_SESSION_VALID(pSession));
3875 pDevExt = pSession->pDevExt;
3876
3877 supdrvBadContext(pDevExt, pszFile, uLine, pszExtra);
3878}
3879
3880
3881/**
3882 * Gets the paging mode of the current CPU.
3883 *
3884 * @returns Paging mode, SUPPAGEINGMODE_INVALID on error.
3885 */
3886SUPR0DECL(SUPPAGINGMODE) SUPR0GetPagingMode(void)
3887{
3888 SUPPAGINGMODE enmMode;
3889
3890 RTR0UINTREG cr0 = ASMGetCR0();
3891 if ((cr0 & (X86_CR0_PG | X86_CR0_PE)) != (X86_CR0_PG | X86_CR0_PE))
3892 enmMode = SUPPAGINGMODE_INVALID;
3893 else
3894 {
3895 RTR0UINTREG cr4 = ASMGetCR4();
3896 uint32_t fNXEPlusLMA = 0;
3897 if (cr4 & X86_CR4_PAE)
3898 {
3899 uint32_t fExtFeatures = ASMCpuId_EDX(0x80000001);
3900 if (fExtFeatures & (X86_CPUID_EXT_FEATURE_EDX_NX | X86_CPUID_EXT_FEATURE_EDX_LONG_MODE))
3901 {
3902 uint64_t efer = ASMRdMsr(MSR_K6_EFER);
3903 if ((fExtFeatures & X86_CPUID_EXT_FEATURE_EDX_NX) && (efer & MSR_K6_EFER_NXE))
3904 fNXEPlusLMA |= RT_BIT(0);
3905 if ((fExtFeatures & X86_CPUID_EXT_FEATURE_EDX_LONG_MODE) && (efer & MSR_K6_EFER_LMA))
3906 fNXEPlusLMA |= RT_BIT(1);
3907 }
3908 }
3909
3910 switch ((cr4 & (X86_CR4_PAE | X86_CR4_PGE)) | fNXEPlusLMA)
3911 {
3912 case 0:
3913 enmMode = SUPPAGINGMODE_32_BIT;
3914 break;
3915
3916 case X86_CR4_PGE:
3917 enmMode = SUPPAGINGMODE_32_BIT_GLOBAL;
3918 break;
3919
3920 case X86_CR4_PAE:
3921 enmMode = SUPPAGINGMODE_PAE;
3922 break;
3923
3924 case X86_CR4_PAE | RT_BIT(0):
3925 enmMode = SUPPAGINGMODE_PAE_NX;
3926 break;
3927
3928 case X86_CR4_PAE | X86_CR4_PGE:
3929 enmMode = SUPPAGINGMODE_PAE_GLOBAL;
3930 break;
3931
3932 case X86_CR4_PAE | X86_CR4_PGE | RT_BIT(0):
3933 enmMode = SUPPAGINGMODE_PAE_GLOBAL;
3934 break;
3935
3936 case RT_BIT(1) | X86_CR4_PAE:
3937 enmMode = SUPPAGINGMODE_AMD64;
3938 break;
3939
3940 case RT_BIT(1) | X86_CR4_PAE | RT_BIT(0):
3941 enmMode = SUPPAGINGMODE_AMD64_NX;
3942 break;
3943
3944 case RT_BIT(1) | X86_CR4_PAE | X86_CR4_PGE:
3945 enmMode = SUPPAGINGMODE_AMD64_GLOBAL;
3946 break;
3947
3948 case RT_BIT(1) | X86_CR4_PAE | X86_CR4_PGE | RT_BIT(0):
3949 enmMode = SUPPAGINGMODE_AMD64_GLOBAL_NX;
3950 break;
3951
3952 default:
3953 AssertMsgFailed(("Cannot happen! cr4=%#x fNXEPlusLMA=%d\n", cr4, fNXEPlusLMA));
3954 enmMode = SUPPAGINGMODE_INVALID;
3955 break;
3956 }
3957 }
3958 return enmMode;
3959}
3960
3961
3962/**
3963 * Change CR4 and take care of the kernel CR4 shadow if applicable.
3964 *
3965 * CR4 shadow handling is required for Linux >= 4.0. Calling this function
3966 * instead of ASMSetCR4() is only necessary for semi-permanent CR4 changes
3967 * for code with interrupts enabled.
3968 *
3969 * @returns the old CR4 value.
3970 *
3971 * @param fOrMask bits to be set in CR4.
3972 * @param fAndMask bits to be cleard in CR4.
3973 *
3974 * @remarks Must be called with preemption/interrupts disabled.
3975 */
3976SUPR0DECL(RTCCUINTREG) SUPR0ChangeCR4(RTCCUINTREG fOrMask, RTCCUINTREG fAndMask)
3977{
3978#ifdef RT_OS_LINUX
3979 return supdrvOSChangeCR4(fOrMask, fAndMask);
3980#else
3981 RTCCUINTREG uOld = ASMGetCR4();
3982 RTCCUINTREG uNew = (uOld & fAndMask) | fOrMask;
3983 if (uNew != uOld)
3984 ASMSetCR4(uNew);
3985 return uOld;
3986#endif
3987}
3988
3989
3990/**
3991 * Enables or disabled hardware virtualization extensions using native OS APIs.
3992 *
3993 * @returns VBox status code.
3994 * @retval VINF_SUCCESS on success.
3995 * @retval VERR_NOT_SUPPORTED if not supported by the native OS.
3996 *
3997 * @param fEnable Whether to enable or disable.
3998 */
3999SUPR0DECL(int) SUPR0EnableVTx(bool fEnable)
4000{
4001#ifdef RT_OS_DARWIN
4002 return supdrvOSEnableVTx(fEnable);
4003#else
4004 RT_NOREF1(fEnable);
4005 return VERR_NOT_SUPPORTED;
4006#endif
4007}
4008
4009
4010/**
4011 * Suspends hardware virtualization extensions using the native OS API.
4012 *
4013 * This is called prior to entering raw-mode context.
4014 *
4015 * @returns @c true if suspended, @c false if not.
4016 */
4017SUPR0DECL(bool) SUPR0SuspendVTxOnCpu(void)
4018{
4019#ifdef RT_OS_DARWIN
4020 return supdrvOSSuspendVTxOnCpu();
4021#else
4022 return false;
4023#endif
4024}
4025
4026
4027/**
4028 * Resumes hardware virtualization extensions using the native OS API.
4029 *
4030 * This is called after to entering raw-mode context.
4031 *
4032 * @param fSuspended The return value of SUPR0SuspendVTxOnCpu.
4033 */
4034SUPR0DECL(void) SUPR0ResumeVTxOnCpu(bool fSuspended)
4035{
4036#ifdef RT_OS_DARWIN
4037 supdrvOSResumeVTxOnCpu(fSuspended);
4038#else
4039 RT_NOREF1(fSuspended);
4040 Assert(!fSuspended);
4041#endif
4042}
4043
4044
4045SUPR0DECL(int) SUPR0GetCurrentGdtRw(RTHCUINTPTR *pGdtRw)
4046{
4047#ifdef RT_OS_LINUX
4048 return supdrvOSGetCurrentGdtRw(pGdtRw);
4049#else
4050 NOREF(pGdtRw);
4051 return VERR_NOT_IMPLEMENTED;
4052#endif
4053}
4054
4055
4056/**
4057 * Checks if raw-mode is usable on this system.
4058 *
4059 * The reasons why raw-mode isn't safe to use are host specific. For example on
4060 * Windows the Hyper-V root partition may perhapse not allow important bits in
4061 * CR4 to be changed, which would make it impossible to do a world switch.
4062 *
4063 * @returns VBox status code.
4064 */
4065SUPR0DECL(int) SUPR0GetRawModeUsability(void)
4066{
4067#ifdef RT_OS_WINDOWS
4068 return supdrvOSGetRawModeUsability();
4069#else
4070 return VINF_SUCCESS;
4071#endif
4072}
4073
4074
4075
4076/**
4077 * Checks if Intel VT-x feature is usable on this CPU.
4078 *
4079 * @returns VBox status code.
4080 * @param pfIsSmxModeAmbiguous Where to return whether the SMX mode causes
4081 * ambiguity that makes us unsure whether we
4082 * really can use VT-x or not.
4083 *
4084 * @remarks Must be called with preemption disabled.
4085 * The caller is also expected to check that the CPU is an Intel (or
4086 * VIA) CPU -and- that it supports VT-x. Otherwise, this function
4087 * might throw a \#GP fault as it tries to read/write MSRs that may not
4088 * be present!
4089 */
4090SUPR0DECL(int) SUPR0GetVmxUsability(bool *pfIsSmxModeAmbiguous)
4091{
4092 uint64_t fFeatMsr;
4093 bool fMaybeSmxMode;
4094 bool fMsrLocked;
4095 bool fSmxVmxAllowed;
4096 bool fVmxAllowed;
4097 bool fIsSmxModeAmbiguous;
4098 int rc;
4099
4100 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4101
4102 fFeatMsr = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
4103 fMaybeSmxMode = RT_BOOL(ASMGetCR4() & X86_CR4_SMXE);
4104 fMsrLocked = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_LOCK);
4105 fSmxVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
4106 fVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_VMXON);
4107 fIsSmxModeAmbiguous = false;
4108 rc = VERR_INTERNAL_ERROR_5;
4109
4110 /* Check if the LOCK bit is set but excludes the required VMXON bit. */
4111 if (fMsrLocked)
4112 {
4113 if (fVmxAllowed && fSmxVmxAllowed)
4114 rc = VINF_SUCCESS;
4115 else if (!fVmxAllowed && !fSmxVmxAllowed)
4116 rc = VERR_VMX_MSR_ALL_VMX_DISABLED;
4117 else if (!fMaybeSmxMode)
4118 {
4119 if (fVmxAllowed)
4120 rc = VINF_SUCCESS;
4121 else
4122 rc = VERR_VMX_MSR_VMX_DISABLED;
4123 }
4124 else
4125 {
4126 /*
4127 * CR4.SMXE is set but this doesn't mean the CPU is necessarily in SMX mode. We shall assume
4128 * that it is -not- and that it is a stupid BIOS/OS setting CR4.SMXE for no good reason.
4129 * See @bugref{6873}.
4130 */
4131 Assert(fMaybeSmxMode == true);
4132 fIsSmxModeAmbiguous = true;
4133 rc = VINF_SUCCESS;
4134 }
4135 }
4136 else
4137 {
4138 /*
4139 * MSR is not yet locked; we can change it ourselves here. Once the lock bit is set,
4140 * this MSR can no longer be modified.
4141 *
4142 * Set both the VMX and SMX_VMX bits (if supported) as we can't determine SMX mode
4143 * accurately. See @bugref{6873}.
4144 *
4145 * We need to check for SMX hardware support here, before writing the MSR as
4146 * otherwise we will #GP fault on CPUs that do not support it. Callers do not check
4147 * for it.
4148 */
4149 uint32_t fFeaturesECX, uDummy;
4150#ifdef VBOX_STRICT
4151 /* Callers should have verified these at some point. */
4152 uint32_t uMaxId, uVendorEBX, uVendorECX, uVendorEDX;
4153 ASMCpuId(0, &uMaxId, &uVendorEBX, &uVendorECX, &uVendorEDX);
4154 Assert(ASMIsValidStdRange(uMaxId));
4155 Assert( ASMIsIntelCpuEx( uVendorEBX, uVendorECX, uVendorEDX)
4156 || ASMIsViaCentaurCpuEx(uVendorEBX, uVendorECX, uVendorEDX));
4157#endif
4158 ASMCpuId(1, &uDummy, &uDummy, &fFeaturesECX, &uDummy);
4159 bool fSmxVmxHwSupport = false;
4160 if ( (fFeaturesECX & X86_CPUID_FEATURE_ECX_VMX)
4161 && (fFeaturesECX & X86_CPUID_FEATURE_ECX_SMX))
4162 fSmxVmxHwSupport = true;
4163
4164 fFeatMsr |= MSR_IA32_FEATURE_CONTROL_LOCK
4165 | MSR_IA32_FEATURE_CONTROL_VMXON;
4166 if (fSmxVmxHwSupport)
4167 fFeatMsr |= MSR_IA32_FEATURE_CONTROL_SMX_VMXON;
4168
4169 /*
4170 * Commit.
4171 */
4172 ASMWrMsr(MSR_IA32_FEATURE_CONTROL, fFeatMsr);
4173
4174 /*
4175 * Verify.
4176 */
4177 fFeatMsr = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
4178 fMsrLocked = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_LOCK);
4179 if (fMsrLocked)
4180 {
4181 fSmxVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
4182 fVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_VMXON);
4183 if ( fVmxAllowed
4184 && ( !fSmxVmxHwSupport
4185 || fSmxVmxAllowed))
4186 rc = VINF_SUCCESS;
4187 else
4188 rc = !fSmxVmxHwSupport ? VERR_VMX_MSR_VMX_ENABLE_FAILED : VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED;
4189 }
4190 else
4191 rc = VERR_VMX_MSR_LOCKING_FAILED;
4192 }
4193
4194 if (pfIsSmxModeAmbiguous)
4195 *pfIsSmxModeAmbiguous = fIsSmxModeAmbiguous;
4196
4197 return rc;
4198}
4199
4200
4201/**
4202 * Checks if AMD-V SVM feature is usable on this CPU.
4203 *
4204 * @returns VBox status code.
4205 * @param fInitSvm If usable, try to initialize SVM on this CPU.
4206 *
4207 * @remarks Must be called with preemption disabled.
4208 */
4209SUPR0DECL(int) SUPR0GetSvmUsability(bool fInitSvm)
4210{
4211 int rc;
4212 uint64_t fVmCr;
4213 uint64_t fEfer;
4214
4215 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4216 fVmCr = ASMRdMsr(MSR_K8_VM_CR);
4217 if (!(fVmCr & MSR_K8_VM_CR_SVM_DISABLE))
4218 {
4219 rc = VINF_SUCCESS;
4220 if (fInitSvm)
4221 {
4222 /* Turn on SVM in the EFER MSR. */
4223 fEfer = ASMRdMsr(MSR_K6_EFER);
4224 if (fEfer & MSR_K6_EFER_SVME)
4225 rc = VERR_SVM_IN_USE;
4226 else
4227 {
4228 ASMWrMsr(MSR_K6_EFER, fEfer | MSR_K6_EFER_SVME);
4229
4230 /* Paranoia. */
4231 fEfer = ASMRdMsr(MSR_K6_EFER);
4232 if (fEfer & MSR_K6_EFER_SVME)
4233 {
4234 /* Restore previous value. */
4235 ASMWrMsr(MSR_K6_EFER, fEfer & ~MSR_K6_EFER_SVME);
4236 }
4237 else
4238 rc = VERR_SVM_ILLEGAL_EFER_MSR;
4239 }
4240 }
4241 }
4242 else
4243 rc = VERR_SVM_DISABLED;
4244 return rc;
4245}
4246
4247
4248/**
4249 * Queries the AMD-V and VT-x capabilities of the calling CPU.
4250 *
4251 * @returns VBox status code.
4252 * @retval VERR_VMX_NO_VMX
4253 * @retval VERR_VMX_MSR_ALL_VMX_DISABLED
4254 * @retval VERR_VMX_MSR_VMX_DISABLED
4255 * @retval VERR_VMX_MSR_LOCKING_FAILED
4256 * @retval VERR_VMX_MSR_VMX_ENABLE_FAILED
4257 * @retval VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED
4258 * @retval VERR_SVM_NO_SVM
4259 * @retval VERR_SVM_DISABLED
4260 * @retval VERR_UNSUPPORTED_CPU if not identifiable as an AMD, Intel or VIA
4261 * (centaur) CPU.
4262 *
4263 * @param pfCaps Where to store the capabilities.
4264 */
4265int VBOXCALL supdrvQueryVTCapsInternal(uint32_t *pfCaps)
4266{
4267 int rc = VERR_UNSUPPORTED_CPU;
4268 bool fIsSmxModeAmbiguous = false;
4269 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
4270
4271 /*
4272 * Input validation.
4273 */
4274 AssertPtrReturn(pfCaps, VERR_INVALID_POINTER);
4275
4276 *pfCaps = 0;
4277 /* We may modify MSRs and re-read them, disable preemption so we make sure we don't migrate CPUs. */
4278 RTThreadPreemptDisable(&PreemptState);
4279 if (ASMHasCpuId())
4280 {
4281 uint32_t fFeaturesECX, fFeaturesEDX, uDummy;
4282 uint32_t uMaxId, uVendorEBX, uVendorECX, uVendorEDX;
4283
4284 ASMCpuId(0, &uMaxId, &uVendorEBX, &uVendorECX, &uVendorEDX);
4285 ASMCpuId(1, &uDummy, &uDummy, &fFeaturesECX, &fFeaturesEDX);
4286
4287 if ( ASMIsValidStdRange(uMaxId)
4288 && ( ASMIsIntelCpuEx( uVendorEBX, uVendorECX, uVendorEDX)
4289 || ASMIsViaCentaurCpuEx(uVendorEBX, uVendorECX, uVendorEDX) )
4290 )
4291 {
4292 if ( (fFeaturesECX & X86_CPUID_FEATURE_ECX_VMX)
4293 && (fFeaturesEDX & X86_CPUID_FEATURE_EDX_MSR)
4294 && (fFeaturesEDX & X86_CPUID_FEATURE_EDX_FXSR)
4295 )
4296 {
4297 rc = SUPR0GetVmxUsability(&fIsSmxModeAmbiguous);
4298 if (rc == VINF_SUCCESS)
4299 {
4300 VMXCAPABILITY vtCaps;
4301
4302 *pfCaps |= SUPVTCAPS_VT_X;
4303
4304 vtCaps.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS);
4305 if (vtCaps.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL)
4306 {
4307 vtCaps.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS2);
4308 if (vtCaps.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_EPT)
4309 *pfCaps |= SUPVTCAPS_NESTED_PAGING;
4310 if (vtCaps.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_UNRESTRICTED_GUEST)
4311 *pfCaps |= SUPVTCAPS_VTX_UNRESTRICTED_GUEST;
4312 }
4313 }
4314 }
4315 else
4316 rc = VERR_VMX_NO_VMX;
4317 }
4318 else if ( ASMIsAmdCpuEx(uVendorEBX, uVendorECX, uVendorEDX)
4319 && ASMIsValidStdRange(uMaxId))
4320 {
4321 uint32_t fExtFeaturesEcx, uExtMaxId;
4322 ASMCpuId(0x80000000, &uExtMaxId, &uDummy, &uDummy, &uDummy);
4323 ASMCpuId(0x80000001, &uDummy, &uDummy, &fExtFeaturesEcx, &uDummy);
4324
4325 /* Check if SVM is available. */
4326 if ( ASMIsValidExtRange(uExtMaxId)
4327 && uExtMaxId >= 0x8000000a
4328 && (fExtFeaturesEcx & X86_CPUID_AMD_FEATURE_ECX_SVM)
4329 && (fFeaturesEDX & X86_CPUID_FEATURE_EDX_MSR)
4330 && (fFeaturesEDX & X86_CPUID_FEATURE_EDX_FXSR)
4331 )
4332 {
4333 rc = SUPR0GetSvmUsability(false /* fInitSvm */);
4334 if (RT_SUCCESS(rc))
4335 {
4336 uint32_t fSvmFeatures;
4337 *pfCaps |= SUPVTCAPS_AMD_V;
4338
4339 /* Query AMD-V features. */
4340 ASMCpuId(0x8000000a, &uDummy, &uDummy, &uDummy, &fSvmFeatures);
4341 if (fSvmFeatures & X86_CPUID_SVM_FEATURE_EDX_NESTED_PAGING)
4342 *pfCaps |= SUPVTCAPS_NESTED_PAGING;
4343 }
4344 }
4345 else
4346 rc = VERR_SVM_NO_SVM;
4347 }
4348 }
4349
4350 RTThreadPreemptRestore(&PreemptState);
4351 if (fIsSmxModeAmbiguous)
4352 SUPR0Printf(("WARNING! CR4 hints SMX mode but your CPU is too secretive. Proceeding anyway... We wish you good luck!\n"));
4353 return rc;
4354}
4355
4356/**
4357 * Queries the AMD-V and VT-x capabilities of the calling CPU.
4358 *
4359 * @returns VBox status code.
4360 * @retval VERR_VMX_NO_VMX
4361 * @retval VERR_VMX_MSR_ALL_VMX_DISABLED
4362 * @retval VERR_VMX_MSR_VMX_DISABLED
4363 * @retval VERR_VMX_MSR_LOCKING_FAILED
4364 * @retval VERR_VMX_MSR_VMX_ENABLE_FAILED
4365 * @retval VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED
4366 * @retval VERR_SVM_NO_SVM
4367 * @retval VERR_SVM_DISABLED
4368 * @retval VERR_UNSUPPORTED_CPU if not identifiable as an AMD, Intel or VIA
4369 * (centaur) CPU.
4370 *
4371 * @param pSession The session handle.
4372 * @param pfCaps Where to store the capabilities.
4373 */
4374SUPR0DECL(int) SUPR0QueryVTCaps(PSUPDRVSESSION pSession, uint32_t *pfCaps)
4375{
4376 /*
4377 * Input validation.
4378 */
4379 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4380 AssertPtrReturn(pfCaps, VERR_INVALID_POINTER);
4381
4382 /*
4383 * Call common worker.
4384 */
4385 return supdrvQueryVTCapsInternal(pfCaps);
4386}
4387
4388
4389/**
4390 * Queries the CPU microcode revision.
4391 *
4392 * @returns VBox status code.
4393 * @retval VERR_UNSUPPORTED_CPU if not identifiable as a processor with
4394 * readable microcode rev.
4395 *
4396 * @param puRevision Where to store the microcode revision.
4397 */
4398int VBOXCALL supdrvQueryUcodeRev(uint32_t *puRevision)
4399{
4400 int rc = VERR_UNSUPPORTED_CPU;
4401 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
4402
4403 /*
4404 * Input validation.
4405 */
4406 AssertPtrReturn(puRevision, VERR_INVALID_POINTER);
4407
4408 *puRevision = 0;
4409
4410 /* Disable preemption so we make sure we don't migrate CPUs, just in case. */
4411 /* NB: We assume that there aren't mismatched microcode revs in the system. */
4412 RTThreadPreemptDisable(&PreemptState);
4413
4414 if (ASMHasCpuId())
4415 {
4416 uint32_t uDummy, uTFMSEAX;
4417 uint32_t uMaxId, uVendorEBX, uVendorECX, uVendorEDX;
4418
4419 ASMCpuId(0, &uMaxId, &uVendorEBX, &uVendorECX, &uVendorEDX);
4420 ASMCpuId(1, &uTFMSEAX, &uDummy, &uDummy, &uDummy);
4421
4422 if (ASMIsValidStdRange(uMaxId))
4423 {
4424 uint64_t uRevMsr;
4425 if (ASMIsIntelCpuEx(uVendorEBX, uVendorECX, uVendorEDX))
4426 {
4427 /* Architectural MSR available on Pentium Pro and later. */
4428 if (ASMGetCpuFamily(uTFMSEAX) >= 6)
4429 {
4430 /* Revision is in the high dword. */
4431 uRevMsr = ASMRdMsr(MSR_IA32_BIOS_SIGN_ID);
4432 *puRevision = RT_HIDWORD(uRevMsr);
4433 rc = VINF_SUCCESS;
4434 }
4435 }
4436 else if (ASMIsAmdCpuEx(uVendorEBX, uVendorECX, uVendorEDX))
4437 {
4438 /* Not well documented, but at least all AMD64 CPUs support this. */
4439 if (ASMGetCpuFamily(uTFMSEAX) >= 15)
4440 {
4441 /* Revision is in the low dword. */
4442 uRevMsr = ASMRdMsr(MSR_IA32_BIOS_SIGN_ID); /* Same MSR as Intel. */
4443 *puRevision = RT_LODWORD(uRevMsr);
4444 rc = VINF_SUCCESS;
4445 }
4446 }
4447 }
4448 }
4449
4450 RTThreadPreemptRestore(&PreemptState);
4451
4452 return rc;
4453}
4454
4455/**
4456 * Queries the CPU microcode revision.
4457 *
4458 * @returns VBox status code.
4459 * @retval VERR_UNSUPPORTED_CPU if not identifiable as a processor with
4460 * readable microcode rev.
4461 *
4462 * @param pSession The session handle.
4463 * @param puRevision Where to store the microcode revision.
4464 */
4465SUPR0DECL(int) SUPR0QueryUcodeRev(PSUPDRVSESSION pSession, uint32_t *puRevision)
4466{
4467 /*
4468 * Input validation.
4469 */
4470 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4471 AssertPtrReturn(puRevision, VERR_INVALID_POINTER);
4472
4473 /*
4474 * Call common worker.
4475 */
4476 return supdrvQueryUcodeRev(puRevision);
4477}
4478
4479
4480/**
4481 * Register a component factory with the support driver.
4482 *
4483 * This is currently restricted to kernel sessions only.
4484 *
4485 * @returns VBox status code.
4486 * @retval VINF_SUCCESS on success.
4487 * @retval VERR_NO_MEMORY if we're out of memory.
4488 * @retval VERR_ALREADY_EXISTS if the factory has already been registered.
4489 * @retval VERR_ACCESS_DENIED if it isn't a kernel session.
4490 * @retval VERR_INVALID_PARAMETER on invalid parameter.
4491 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
4492 *
4493 * @param pSession The SUPDRV session (must be a ring-0 session).
4494 * @param pFactory Pointer to the component factory registration structure.
4495 *
4496 * @remarks This interface is also available via SUPR0IdcComponentRegisterFactory.
4497 */
4498SUPR0DECL(int) SUPR0ComponentRegisterFactory(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory)
4499{
4500 PSUPDRVFACTORYREG pNewReg;
4501 const char *psz;
4502 int rc;
4503
4504 /*
4505 * Validate parameters.
4506 */
4507 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4508 AssertReturn(pSession->R0Process == NIL_RTR0PROCESS, VERR_ACCESS_DENIED);
4509 AssertPtrReturn(pFactory, VERR_INVALID_POINTER);
4510 AssertPtrReturn(pFactory->pfnQueryFactoryInterface, VERR_INVALID_POINTER);
4511 psz = RTStrEnd(pFactory->szName, sizeof(pFactory->szName));
4512 AssertReturn(psz, VERR_INVALID_PARAMETER);
4513
4514 /*
4515 * Allocate and initialize a new registration structure.
4516 */
4517 pNewReg = (PSUPDRVFACTORYREG)RTMemAlloc(sizeof(SUPDRVFACTORYREG));
4518 if (pNewReg)
4519 {
4520 pNewReg->pNext = NULL;
4521 pNewReg->pFactory = pFactory;
4522 pNewReg->pSession = pSession;
4523 pNewReg->cchName = psz - &pFactory->szName[0];
4524
4525 /*
4526 * Add it to the tail of the list after checking for prior registration.
4527 */
4528 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
4529 if (RT_SUCCESS(rc))
4530 {
4531 PSUPDRVFACTORYREG pPrev = NULL;
4532 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
4533 while (pCur && pCur->pFactory != pFactory)
4534 {
4535 pPrev = pCur;
4536 pCur = pCur->pNext;
4537 }
4538 if (!pCur)
4539 {
4540 if (pPrev)
4541 pPrev->pNext = pNewReg;
4542 else
4543 pSession->pDevExt->pComponentFactoryHead = pNewReg;
4544 rc = VINF_SUCCESS;
4545 }
4546 else
4547 rc = VERR_ALREADY_EXISTS;
4548
4549 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
4550 }
4551
4552 if (RT_FAILURE(rc))
4553 RTMemFree(pNewReg);
4554 }
4555 else
4556 rc = VERR_NO_MEMORY;
4557 return rc;
4558}
4559
4560
4561/**
4562 * Deregister a component factory.
4563 *
4564 * @returns VBox status code.
4565 * @retval VINF_SUCCESS on success.
4566 * @retval VERR_NOT_FOUND if the factory wasn't registered.
4567 * @retval VERR_ACCESS_DENIED if it isn't a kernel session.
4568 * @retval VERR_INVALID_PARAMETER on invalid parameter.
4569 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
4570 *
4571 * @param pSession The SUPDRV session (must be a ring-0 session).
4572 * @param pFactory Pointer to the component factory registration structure
4573 * previously passed SUPR0ComponentRegisterFactory().
4574 *
4575 * @remarks This interface is also available via SUPR0IdcComponentDeregisterFactory.
4576 */
4577SUPR0DECL(int) SUPR0ComponentDeregisterFactory(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory)
4578{
4579 int rc;
4580
4581 /*
4582 * Validate parameters.
4583 */
4584 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4585 AssertReturn(pSession->R0Process == NIL_RTR0PROCESS, VERR_ACCESS_DENIED);
4586 AssertPtrReturn(pFactory, VERR_INVALID_POINTER);
4587
4588 /*
4589 * Take the lock and look for the registration record.
4590 */
4591 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
4592 if (RT_SUCCESS(rc))
4593 {
4594 PSUPDRVFACTORYREG pPrev = NULL;
4595 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
4596 while (pCur && pCur->pFactory != pFactory)
4597 {
4598 pPrev = pCur;
4599 pCur = pCur->pNext;
4600 }
4601 if (pCur)
4602 {
4603 if (!pPrev)
4604 pSession->pDevExt->pComponentFactoryHead = pCur->pNext;
4605 else
4606 pPrev->pNext = pCur->pNext;
4607
4608 pCur->pNext = NULL;
4609 pCur->pFactory = NULL;
4610 pCur->pSession = NULL;
4611 rc = VINF_SUCCESS;
4612 }
4613 else
4614 rc = VERR_NOT_FOUND;
4615
4616 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
4617
4618 RTMemFree(pCur);
4619 }
4620 return rc;
4621}
4622
4623
4624/**
4625 * Queries a component factory.
4626 *
4627 * @returns VBox status code.
4628 * @retval VERR_INVALID_PARAMETER on invalid parameter.
4629 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
4630 * @retval VERR_SUPDRV_COMPONENT_NOT_FOUND if the component factory wasn't found.
4631 * @retval VERR_SUPDRV_INTERFACE_NOT_SUPPORTED if the interface wasn't supported.
4632 *
4633 * @param pSession The SUPDRV session.
4634 * @param pszName The name of the component factory.
4635 * @param pszInterfaceUuid The UUID of the factory interface (stringified).
4636 * @param ppvFactoryIf Where to store the factory interface.
4637 */
4638SUPR0DECL(int) SUPR0ComponentQueryFactory(PSUPDRVSESSION pSession, const char *pszName, const char *pszInterfaceUuid, void **ppvFactoryIf)
4639{
4640 const char *pszEnd;
4641 size_t cchName;
4642 int rc;
4643
4644 /*
4645 * Validate parameters.
4646 */
4647 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4648
4649 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
4650 pszEnd = RTStrEnd(pszName, RT_SIZEOFMEMB(SUPDRVFACTORY, szName));
4651 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
4652 cchName = pszEnd - pszName;
4653
4654 AssertPtrReturn(pszInterfaceUuid, VERR_INVALID_POINTER);
4655 pszEnd = RTStrEnd(pszInterfaceUuid, RTUUID_STR_LENGTH);
4656 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
4657
4658 AssertPtrReturn(ppvFactoryIf, VERR_INVALID_POINTER);
4659 *ppvFactoryIf = NULL;
4660
4661 /*
4662 * Take the lock and try all factories by this name.
4663 */
4664 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
4665 if (RT_SUCCESS(rc))
4666 {
4667 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
4668 rc = VERR_SUPDRV_COMPONENT_NOT_FOUND;
4669 while (pCur)
4670 {
4671 if ( pCur->cchName == cchName
4672 && !memcmp(pCur->pFactory->szName, pszName, cchName))
4673 {
4674 void *pvFactory = pCur->pFactory->pfnQueryFactoryInterface(pCur->pFactory, pSession, pszInterfaceUuid);
4675 if (pvFactory)
4676 {
4677 *ppvFactoryIf = pvFactory;
4678 rc = VINF_SUCCESS;
4679 break;
4680 }
4681 rc = VERR_SUPDRV_INTERFACE_NOT_SUPPORTED;
4682 }
4683
4684 /* next */
4685 pCur = pCur->pNext;
4686 }
4687
4688 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
4689 }
4690 return rc;
4691}
4692
4693
4694/**
4695 * Adds a memory object to the session.
4696 *
4697 * @returns IPRT status code.
4698 * @param pMem Memory tracking structure containing the
4699 * information to track.
4700 * @param pSession The session.
4701 */
4702static int supdrvMemAdd(PSUPDRVMEMREF pMem, PSUPDRVSESSION pSession)
4703{
4704 PSUPDRVBUNDLE pBundle;
4705
4706 /*
4707 * Find free entry and record the allocation.
4708 */
4709 RTSpinlockAcquire(pSession->Spinlock);
4710 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
4711 {
4712 if (pBundle->cUsed < RT_ELEMENTS(pBundle->aMem))
4713 {
4714 unsigned i;
4715 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
4716 {
4717 if (pBundle->aMem[i].MemObj == NIL_RTR0MEMOBJ)
4718 {
4719 pBundle->cUsed++;
4720 pBundle->aMem[i] = *pMem;
4721 RTSpinlockRelease(pSession->Spinlock);
4722 return VINF_SUCCESS;
4723 }
4724 }
4725 AssertFailed(); /* !!this can't be happening!!! */
4726 }
4727 }
4728 RTSpinlockRelease(pSession->Spinlock);
4729
4730 /*
4731 * Need to allocate a new bundle.
4732 * Insert into the last entry in the bundle.
4733 */
4734 pBundle = (PSUPDRVBUNDLE)RTMemAllocZ(sizeof(*pBundle));
4735 if (!pBundle)
4736 return VERR_NO_MEMORY;
4737
4738 /* take last entry. */
4739 pBundle->cUsed++;
4740 pBundle->aMem[RT_ELEMENTS(pBundle->aMem) - 1] = *pMem;
4741
4742 /* insert into list. */
4743 RTSpinlockAcquire(pSession->Spinlock);
4744 pBundle->pNext = pSession->Bundle.pNext;
4745 pSession->Bundle.pNext = pBundle;
4746 RTSpinlockRelease(pSession->Spinlock);
4747
4748 return VINF_SUCCESS;
4749}
4750
4751
4752/**
4753 * Releases a memory object referenced by pointer and type.
4754 *
4755 * @returns IPRT status code.
4756 * @param pSession Session data.
4757 * @param uPtr Pointer to memory. This is matched against both the R0 and R3 addresses.
4758 * @param eType Memory type.
4759 */
4760static int supdrvMemRelease(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, SUPDRVMEMREFTYPE eType)
4761{
4762 PSUPDRVBUNDLE pBundle;
4763
4764 /*
4765 * Validate input.
4766 */
4767 if (!uPtr)
4768 {
4769 Log(("Illegal address %p\n", (void *)uPtr));
4770 return VERR_INVALID_PARAMETER;
4771 }
4772
4773 /*
4774 * Search for the address.
4775 */
4776 RTSpinlockAcquire(pSession->Spinlock);
4777 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
4778 {
4779 if (pBundle->cUsed > 0)
4780 {
4781 unsigned i;
4782 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
4783 {
4784 if ( pBundle->aMem[i].eType == eType
4785 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
4786 && ( (RTHCUINTPTR)RTR0MemObjAddress(pBundle->aMem[i].MemObj) == uPtr
4787 || ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
4788 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == uPtr))
4789 )
4790 {
4791 /* Make a copy of it and release it outside the spinlock. */
4792 SUPDRVMEMREF Mem = pBundle->aMem[i];
4793 pBundle->aMem[i].eType = MEMREF_TYPE_UNUSED;
4794 pBundle->aMem[i].MemObj = NIL_RTR0MEMOBJ;
4795 pBundle->aMem[i].MapObjR3 = NIL_RTR0MEMOBJ;
4796 RTSpinlockRelease(pSession->Spinlock);
4797
4798 if (Mem.MapObjR3 != NIL_RTR0MEMOBJ)
4799 {
4800 int rc = RTR0MemObjFree(Mem.MapObjR3, false);
4801 AssertRC(rc); /** @todo figure out how to handle this. */
4802 }
4803 if (Mem.MemObj != NIL_RTR0MEMOBJ)
4804 {
4805 int rc = RTR0MemObjFree(Mem.MemObj, true /* fFreeMappings */);
4806 AssertRC(rc); /** @todo figure out how to handle this. */
4807 }
4808 return VINF_SUCCESS;
4809 }
4810 }
4811 }
4812 }
4813 RTSpinlockRelease(pSession->Spinlock);
4814 Log(("Failed to find %p!!! (eType=%d)\n", (void *)uPtr, eType));
4815 return VERR_INVALID_PARAMETER;
4816}
4817
4818
4819/**
4820 * Opens an image. If it's the first time it's opened the call must upload
4821 * the bits using the supdrvIOCtl_LdrLoad() / SUPDRV_IOCTL_LDR_LOAD function.
4822 *
4823 * This is the 1st step of the loading.
4824 *
4825 * @returns IPRT status code.
4826 * @param pDevExt Device globals.
4827 * @param pSession Session data.
4828 * @param pReq The open request.
4829 */
4830static int supdrvIOCtl_LdrOpen(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDROPEN pReq)
4831{
4832 int rc;
4833 PSUPDRVLDRIMAGE pImage;
4834 void *pv;
4835 size_t cchName = strlen(pReq->u.In.szName); /* (caller checked < 32). */
4836 SUPDRV_CHECK_SMAP_SETUP();
4837 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
4838 LogFlow(("supdrvIOCtl_LdrOpen: szName=%s cbImageWithTabs=%d\n", pReq->u.In.szName, pReq->u.In.cbImageWithTabs));
4839
4840 /*
4841 * Check if we got an instance of the image already.
4842 */
4843 supdrvLdrLock(pDevExt);
4844 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
4845 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
4846 {
4847 if ( pImage->szName[cchName] == '\0'
4848 && !memcmp(pImage->szName, pReq->u.In.szName, cchName))
4849 {
4850 if (RT_LIKELY(pImage->cUsage < UINT32_MAX / 2U))
4851 {
4852 /** @todo check cbImageBits and cbImageWithTabs here, if they differs that indicates that the images are different. */
4853 pImage->cUsage++;
4854 pReq->u.Out.pvImageBase = pImage->pvImage;
4855 pReq->u.Out.fNeedsLoading = pImage->uState == SUP_IOCTL_LDR_OPEN;
4856 pReq->u.Out.fNativeLoader = pImage->fNative;
4857 supdrvLdrAddUsage(pSession, pImage);
4858 supdrvLdrUnlock(pDevExt);
4859 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
4860 return VINF_SUCCESS;
4861 }
4862 supdrvLdrUnlock(pDevExt);
4863 Log(("supdrvIOCtl_LdrOpen: To many existing references to '%s'!\n", pReq->u.In.szName));
4864 return VERR_INTERNAL_ERROR_3; /** @todo add VERR_TOO_MANY_REFERENCES */
4865 }
4866 }
4867 /* (not found - add it!) */
4868
4869 /* If the loader interface is locked down, make userland fail early */
4870 if (pDevExt->fLdrLockedDown)
4871 {
4872 supdrvLdrUnlock(pDevExt);
4873 Log(("supdrvIOCtl_LdrOpen: Not adding '%s' to image list, loader interface is locked down!\n", pReq->u.In.szName));
4874 return VERR_PERMISSION_DENIED;
4875 }
4876
4877 /*
4878 * Allocate memory.
4879 */
4880 Assert(cchName < sizeof(pImage->szName));
4881 pv = RTMemAlloc(sizeof(SUPDRVLDRIMAGE));
4882 if (!pv)
4883 {
4884 supdrvLdrUnlock(pDevExt);
4885 Log(("supdrvIOCtl_LdrOpen: RTMemAlloc() failed\n"));
4886 return /*VERR_NO_MEMORY*/ VERR_INTERNAL_ERROR_2;
4887 }
4888 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
4889
4890 /*
4891 * Setup and link in the LDR stuff.
4892 */
4893 pImage = (PSUPDRVLDRIMAGE)pv;
4894 pImage->pvImage = NULL;
4895 pImage->pvImageAlloc = NULL;
4896 pImage->cbImageWithTabs = pReq->u.In.cbImageWithTabs;
4897 pImage->cbImageBits = pReq->u.In.cbImageBits;
4898 pImage->cSymbols = 0;
4899 pImage->paSymbols = NULL;
4900 pImage->pachStrTab = NULL;
4901 pImage->cbStrTab = 0;
4902 pImage->pfnModuleInit = NULL;
4903 pImage->pfnModuleTerm = NULL;
4904 pImage->pfnServiceReqHandler = NULL;
4905 pImage->uState = SUP_IOCTL_LDR_OPEN;
4906 pImage->cUsage = 1;
4907 pImage->pDevExt = pDevExt;
4908 memcpy(pImage->szName, pReq->u.In.szName, cchName + 1);
4909
4910 /*
4911 * Try load it using the native loader, if that isn't supported, fall back
4912 * on the older method.
4913 */
4914 pImage->fNative = true;
4915 rc = supdrvOSLdrOpen(pDevExt, pImage, pReq->u.In.szFilename);
4916 if (rc == VERR_NOT_SUPPORTED)
4917 {
4918 pImage->pvImageAlloc = RTMemExecAlloc(pImage->cbImageBits + 31);
4919 pImage->pvImage = RT_ALIGN_P(pImage->pvImageAlloc, 32);
4920 pImage->fNative = false;
4921 rc = pImage->pvImageAlloc ? VINF_SUCCESS : VERR_NO_EXEC_MEMORY;
4922 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
4923 }
4924 if (RT_FAILURE(rc))
4925 {
4926 supdrvLdrUnlock(pDevExt);
4927 RTMemFree(pImage);
4928 Log(("supdrvIOCtl_LdrOpen(%s): failed - %Rrc\n", pReq->u.In.szName, rc));
4929 return rc;
4930 }
4931 Assert(VALID_PTR(pImage->pvImage) || RT_FAILURE(rc));
4932
4933 /*
4934 * Link it.
4935 */
4936 pImage->pNext = pDevExt->pLdrImages;
4937 pDevExt->pLdrImages = pImage;
4938
4939 supdrvLdrAddUsage(pSession, pImage);
4940
4941 pReq->u.Out.pvImageBase = pImage->pvImage;
4942 pReq->u.Out.fNeedsLoading = true;
4943 pReq->u.Out.fNativeLoader = pImage->fNative;
4944 supdrvOSLdrNotifyOpened(pDevExt, pImage, pReq->u.In.szFilename);
4945
4946 supdrvLdrUnlock(pDevExt);
4947 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
4948 return VINF_SUCCESS;
4949}
4950
4951
4952/**
4953 * Worker that validates a pointer to an image entrypoint.
4954 *
4955 * @returns IPRT status code.
4956 * @param pDevExt The device globals.
4957 * @param pImage The loader image.
4958 * @param pv The pointer into the image.
4959 * @param fMayBeNull Whether it may be NULL.
4960 * @param pszWhat What is this entrypoint? (for logging)
4961 * @param pbImageBits The image bits prepared by ring-3.
4962 *
4963 * @remarks Will leave the lock on failure.
4964 */
4965static int supdrvLdrValidatePointer(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, void *pv,
4966 bool fMayBeNull, const uint8_t *pbImageBits, const char *pszWhat)
4967{
4968 if (!fMayBeNull || pv)
4969 {
4970 if ((uintptr_t)pv - (uintptr_t)pImage->pvImage >= pImage->cbImageBits)
4971 {
4972 supdrvLdrUnlock(pDevExt);
4973 Log(("Out of range (%p LB %#x): %s=%p\n", pImage->pvImage, pImage->cbImageBits, pszWhat, pv));
4974 return VERR_INVALID_PARAMETER;
4975 }
4976
4977 if (pImage->fNative)
4978 {
4979 int rc = supdrvOSLdrValidatePointer(pDevExt, pImage, pv, pbImageBits);
4980 if (RT_FAILURE(rc))
4981 {
4982 supdrvLdrUnlock(pDevExt);
4983 Log(("Bad entry point address: %s=%p (rc=%Rrc)\n", pszWhat, pv, rc)); NOREF(pszWhat);
4984 return rc;
4985 }
4986 }
4987 }
4988 return VINF_SUCCESS;
4989}
4990
4991
4992/**
4993 * Formats a load error message.
4994 *
4995 * @returns @a rc
4996 * @param rc Return code.
4997 * @param pReq The request.
4998 * @param pszFormat The error message format string.
4999 * @param ... Argument to the format string.
5000 */
5001int VBOXCALL supdrvLdrLoadError(int rc, PSUPLDRLOAD pReq, const char *pszFormat, ...)
5002{
5003 va_list va;
5004 va_start(va, pszFormat);
5005 pReq->u.Out.uErrorMagic = SUPLDRLOAD_ERROR_MAGIC;
5006 RTStrPrintfV(pReq->u.Out.szError, sizeof(pReq->u.Out.szError), pszFormat, va);
5007 va_end(va);
5008 Log(("SUP_IOCTL_LDR_LOAD: %s [rc=%Rrc]\n", pReq->u.Out.szError, rc));
5009 return rc;
5010}
5011
5012
5013/**
5014 * Loads the image bits.
5015 *
5016 * This is the 2nd step of the loading.
5017 *
5018 * @returns IPRT status code.
5019 * @param pDevExt Device globals.
5020 * @param pSession Session data.
5021 * @param pReq The request.
5022 */
5023static int supdrvIOCtl_LdrLoad(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRLOAD pReq)
5024{
5025 PSUPDRVLDRUSAGE pUsage;
5026 PSUPDRVLDRIMAGE pImage;
5027 int rc;
5028 SUPDRV_CHECK_SMAP_SETUP();
5029 LogFlow(("supdrvIOCtl_LdrLoad: pvImageBase=%p cbImageWithBits=%d\n", pReq->u.In.pvImageBase, pReq->u.In.cbImageWithTabs));
5030 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5031
5032 /*
5033 * Find the ldr image.
5034 */
5035 supdrvLdrLock(pDevExt);
5036 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5037
5038 pUsage = pSession->pLdrUsage;
5039 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
5040 pUsage = pUsage->pNext;
5041 if (!pUsage)
5042 {
5043 supdrvLdrUnlock(pDevExt);
5044 return supdrvLdrLoadError(VERR_INVALID_HANDLE, pReq, "Image not found");
5045 }
5046 pImage = pUsage->pImage;
5047
5048 /*
5049 * Validate input.
5050 */
5051 if ( pImage->cbImageWithTabs != pReq->u.In.cbImageWithTabs
5052 || pImage->cbImageBits != pReq->u.In.cbImageBits)
5053 {
5054 supdrvLdrUnlock(pDevExt);
5055 return supdrvLdrLoadError(VERR_INVALID_HANDLE, pReq, "Image size mismatch found: %d(prep) != %d(load) or %d != %d",
5056 pImage->cbImageWithTabs, pReq->u.In.cbImageWithTabs, pImage->cbImageBits, pReq->u.In.cbImageBits);
5057 }
5058
5059 if (pImage->uState != SUP_IOCTL_LDR_OPEN)
5060 {
5061 unsigned uState = pImage->uState;
5062 supdrvLdrUnlock(pDevExt);
5063 if (uState != SUP_IOCTL_LDR_LOAD)
5064 AssertMsgFailed(("SUP_IOCTL_LDR_LOAD: invalid image state %d (%#x)!\n", uState, uState));
5065 pReq->u.Out.uErrorMagic = 0;
5066 return VERR_ALREADY_LOADED;
5067 }
5068
5069 /* If the loader interface is locked down, don't load new images */
5070 if (pDevExt->fLdrLockedDown)
5071 {
5072 supdrvLdrUnlock(pDevExt);
5073 return supdrvLdrLoadError(VERR_PERMISSION_DENIED, pReq, "Loader is locked down");
5074 }
5075
5076 switch (pReq->u.In.eEPType)
5077 {
5078 case SUPLDRLOADEP_NOTHING:
5079 break;
5080
5081 case SUPLDRLOADEP_VMMR0:
5082 rc = supdrvLdrValidatePointer( pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0, false, pReq->u.In.abImage, "pvVMMR0");
5083 if (RT_SUCCESS(rc))
5084 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0EntryFast, false, pReq->u.In.abImage, "pvVMMR0EntryFast");
5085 if (RT_SUCCESS(rc))
5086 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0EntryEx, false, pReq->u.In.abImage, "pvVMMR0EntryEx");
5087 if (RT_FAILURE(rc))
5088 return supdrvLdrLoadError(rc, pReq, "Invalid VMMR0 pointer");
5089 break;
5090
5091 case SUPLDRLOADEP_SERVICE:
5092 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.Service.pfnServiceReq, false, pReq->u.In.abImage, "pfnServiceReq");
5093 if (RT_FAILURE(rc))
5094 return supdrvLdrLoadError(rc, pReq, "Invalid pfnServiceReq pointer: %p", pReq->u.In.EP.Service.pfnServiceReq);
5095 if ( pReq->u.In.EP.Service.apvReserved[0] != NIL_RTR0PTR
5096 || pReq->u.In.EP.Service.apvReserved[1] != NIL_RTR0PTR
5097 || pReq->u.In.EP.Service.apvReserved[2] != NIL_RTR0PTR)
5098 {
5099 supdrvLdrUnlock(pDevExt);
5100 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq,
5101 "Out of range (%p LB %#x): apvReserved={%p,%p,%p} MBZ!",
5102 pImage->pvImage, pReq->u.In.cbImageWithTabs,
5103 pReq->u.In.EP.Service.apvReserved[0],
5104 pReq->u.In.EP.Service.apvReserved[1],
5105 pReq->u.In.EP.Service.apvReserved[2]);
5106 }
5107 break;
5108
5109 default:
5110 supdrvLdrUnlock(pDevExt);
5111 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq, "Invalid eEPType=%d", pReq->u.In.eEPType);
5112 }
5113
5114 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.pfnModuleInit, true, pReq->u.In.abImage, "pfnModuleInit");
5115 if (RT_FAILURE(rc))
5116 return supdrvLdrLoadError(rc, pReq, "Invalid pfnModuleInit pointer: %p", pReq->u.In.pfnModuleInit);
5117 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.pfnModuleTerm, true, pReq->u.In.abImage, "pfnModuleTerm");
5118 if (RT_FAILURE(rc))
5119 return supdrvLdrLoadError(rc, pReq, "Invalid pfnModuleTerm pointer: %p", pReq->u.In.pfnModuleTerm);
5120 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5121
5122 /*
5123 * Allocate and copy the tables.
5124 * (No need to do try/except as this is a buffered request.)
5125 */
5126 pImage->cbStrTab = pReq->u.In.cbStrTab;
5127 if (pImage->cbStrTab)
5128 {
5129 pImage->pachStrTab = (char *)RTMemAlloc(pImage->cbStrTab);
5130 if (pImage->pachStrTab)
5131 memcpy(pImage->pachStrTab, &pReq->u.In.abImage[pReq->u.In.offStrTab], pImage->cbStrTab);
5132 else
5133 rc = supdrvLdrLoadError(VERR_NO_MEMORY, pReq, "Out of memory for string table: %#x", pImage->cbStrTab);
5134 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5135 }
5136
5137 pImage->cSymbols = pReq->u.In.cSymbols;
5138 if (RT_SUCCESS(rc) && pImage->cSymbols)
5139 {
5140 size_t cbSymbols = pImage->cSymbols * sizeof(SUPLDRSYM);
5141 pImage->paSymbols = (PSUPLDRSYM)RTMemAlloc(cbSymbols);
5142 if (pImage->paSymbols)
5143 memcpy(pImage->paSymbols, &pReq->u.In.abImage[pReq->u.In.offSymbols], cbSymbols);
5144 else
5145 rc = supdrvLdrLoadError(VERR_NO_MEMORY, pReq, "Out of memory for symbol table: %#x", cbSymbols);
5146 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5147 }
5148
5149 /*
5150 * Copy the bits / complete native loading.
5151 */
5152 if (RT_SUCCESS(rc))
5153 {
5154 pImage->uState = SUP_IOCTL_LDR_LOAD;
5155 pImage->pfnModuleInit = (PFNR0MODULEINIT)(uintptr_t)pReq->u.In.pfnModuleInit;
5156 pImage->pfnModuleTerm = (PFNR0MODULETERM)(uintptr_t)pReq->u.In.pfnModuleTerm;
5157
5158 if (pImage->fNative)
5159 rc = supdrvOSLdrLoad(pDevExt, pImage, pReq->u.In.abImage, pReq);
5160 else
5161 {
5162 memcpy(pImage->pvImage, &pReq->u.In.abImage[0], pImage->cbImageBits);
5163 Log(("vboxdrv: Loaded '%s' at %p\n", pImage->szName, pImage->pvImage));
5164 }
5165 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5166 }
5167
5168 /*
5169 * Update any entry points.
5170 */
5171 if (RT_SUCCESS(rc))
5172 {
5173 switch (pReq->u.In.eEPType)
5174 {
5175 default:
5176 case SUPLDRLOADEP_NOTHING:
5177 rc = VINF_SUCCESS;
5178 break;
5179 case SUPLDRLOADEP_VMMR0:
5180 rc = supdrvLdrSetVMMR0EPs(pDevExt, pReq->u.In.EP.VMMR0.pvVMMR0,
5181 pReq->u.In.EP.VMMR0.pvVMMR0EntryFast, pReq->u.In.EP.VMMR0.pvVMMR0EntryEx);
5182 break;
5183 case SUPLDRLOADEP_SERVICE:
5184 pImage->pfnServiceReqHandler = (PFNSUPR0SERVICEREQHANDLER)(uintptr_t)pReq->u.In.EP.Service.pfnServiceReq;
5185 rc = VINF_SUCCESS;
5186 break;
5187 }
5188 }
5189
5190 /*
5191 * On success call the module initialization.
5192 */
5193 LogFlow(("supdrvIOCtl_LdrLoad: pfnModuleInit=%p\n", pImage->pfnModuleInit));
5194 if (RT_SUCCESS(rc) && pImage->pfnModuleInit)
5195 {
5196 Log(("supdrvIOCtl_LdrLoad: calling pfnModuleInit=%p\n", pImage->pfnModuleInit));
5197 pDevExt->pLdrInitImage = pImage;
5198 pDevExt->hLdrInitThread = RTThreadNativeSelf();
5199 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5200 rc = pImage->pfnModuleInit(pImage);
5201 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5202 pDevExt->pLdrInitImage = NULL;
5203 pDevExt->hLdrInitThread = NIL_RTNATIVETHREAD;
5204 if (RT_FAILURE(rc))
5205 {
5206 if (pDevExt->pvVMMR0 == pImage->pvImage)
5207 supdrvLdrUnsetVMMR0EPs(pDevExt);
5208 supdrvLdrLoadError(rc, pReq, "ModuleInit failed: %Rrc", rc);
5209 }
5210 }
5211 if (RT_SUCCESS(rc))
5212 {
5213 SUPR0Printf("vboxdrv: %RKv %s\n", pImage->pvImage, pImage->szName);
5214 pReq->u.Out.uErrorMagic = 0;
5215 pReq->u.Out.szError[0] = '\0';
5216 }
5217 else
5218 {
5219 /* Inform the tracing component in case ModuleInit registered TPs. */
5220 supdrvTracerModuleUnloading(pDevExt, pImage);
5221
5222 pImage->uState = SUP_IOCTL_LDR_OPEN;
5223 pImage->pfnModuleInit = NULL;
5224 pImage->pfnModuleTerm = NULL;
5225 pImage->pfnServiceReqHandler= NULL;
5226 pImage->cbStrTab = 0;
5227 RTMemFree(pImage->pachStrTab);
5228 pImage->pachStrTab = NULL;
5229 RTMemFree(pImage->paSymbols);
5230 pImage->paSymbols = NULL;
5231 pImage->cSymbols = 0;
5232 }
5233
5234 supdrvLdrUnlock(pDevExt);
5235 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5236 return rc;
5237}
5238
5239
5240/**
5241 * Frees a previously loaded (prep'ed) image.
5242 *
5243 * @returns IPRT status code.
5244 * @param pDevExt Device globals.
5245 * @param pSession Session data.
5246 * @param pReq The request.
5247 */
5248static int supdrvIOCtl_LdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRFREE pReq)
5249{
5250 int rc;
5251 PSUPDRVLDRUSAGE pUsagePrev;
5252 PSUPDRVLDRUSAGE pUsage;
5253 PSUPDRVLDRIMAGE pImage;
5254 LogFlow(("supdrvIOCtl_LdrFree: pvImageBase=%p\n", pReq->u.In.pvImageBase));
5255
5256 /*
5257 * Find the ldr image.
5258 */
5259 supdrvLdrLock(pDevExt);
5260 pUsagePrev = NULL;
5261 pUsage = pSession->pLdrUsage;
5262 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
5263 {
5264 pUsagePrev = pUsage;
5265 pUsage = pUsage->pNext;
5266 }
5267 if (!pUsage)
5268 {
5269 supdrvLdrUnlock(pDevExt);
5270 Log(("SUP_IOCTL_LDR_FREE: couldn't find image!\n"));
5271 return VERR_INVALID_HANDLE;
5272 }
5273
5274 /*
5275 * Check if we can remove anything.
5276 */
5277 rc = VINF_SUCCESS;
5278 pImage = pUsage->pImage;
5279 if (pImage->cUsage <= 1 || pUsage->cUsage <= 1)
5280 {
5281 /*
5282 * Check if there are any objects with destructors in the image, if
5283 * so leave it for the session cleanup routine so we get a chance to
5284 * clean things up in the right order and not leave them all dangling.
5285 */
5286 RTSpinlockAcquire(pDevExt->Spinlock);
5287 if (pImage->cUsage <= 1)
5288 {
5289 PSUPDRVOBJ pObj;
5290 for (pObj = pDevExt->pObjs; pObj; pObj = pObj->pNext)
5291 if (RT_UNLIKELY((uintptr_t)pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
5292 {
5293 rc = VERR_DANGLING_OBJECTS;
5294 break;
5295 }
5296 }
5297 else
5298 {
5299 PSUPDRVUSAGE pGenUsage;
5300 for (pGenUsage = pSession->pUsage; pGenUsage; pGenUsage = pGenUsage->pNext)
5301 if (RT_UNLIKELY((uintptr_t)pGenUsage->pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
5302 {
5303 rc = VERR_DANGLING_OBJECTS;
5304 break;
5305 }
5306 }
5307 RTSpinlockRelease(pDevExt->Spinlock);
5308 if (rc == VINF_SUCCESS)
5309 {
5310 /* unlink it */
5311 if (pUsagePrev)
5312 pUsagePrev->pNext = pUsage->pNext;
5313 else
5314 pSession->pLdrUsage = pUsage->pNext;
5315
5316 /* free it */
5317 pUsage->pImage = NULL;
5318 pUsage->pNext = NULL;
5319 RTMemFree(pUsage);
5320
5321 /*
5322 * Dereference the image.
5323 */
5324 if (pImage->cUsage <= 1)
5325 supdrvLdrFree(pDevExt, pImage);
5326 else
5327 pImage->cUsage--;
5328 }
5329 else
5330 {
5331 Log(("supdrvIOCtl_LdrFree: Dangling objects in %p/%s!\n", pImage->pvImage, pImage->szName));
5332 rc = VINF_SUCCESS; /** @todo BRANCH-2.1: remove this after branching. */
5333 }
5334 }
5335 else
5336 {
5337 /*
5338 * Dereference both image and usage.
5339 */
5340 pImage->cUsage--;
5341 pUsage->cUsage--;
5342 }
5343
5344 supdrvLdrUnlock(pDevExt);
5345 return rc;
5346}
5347
5348
5349/**
5350 * Lock down the image loader interface.
5351 *
5352 * @returns IPRT status code.
5353 * @param pDevExt Device globals.
5354 */
5355static int supdrvIOCtl_LdrLockDown(PSUPDRVDEVEXT pDevExt)
5356{
5357 LogFlow(("supdrvIOCtl_LdrLockDown:\n"));
5358
5359 supdrvLdrLock(pDevExt);
5360 if (!pDevExt->fLdrLockedDown)
5361 {
5362 pDevExt->fLdrLockedDown = true;
5363 Log(("supdrvIOCtl_LdrLockDown: Image loader interface locked down\n"));
5364 }
5365 supdrvLdrUnlock(pDevExt);
5366
5367 return VINF_SUCCESS;
5368}
5369
5370
5371/**
5372 * Gets the address of a symbol in an open image.
5373 *
5374 * @returns IPRT status code.
5375 * @param pDevExt Device globals.
5376 * @param pSession Session data.
5377 * @param pReq The request buffer.
5378 */
5379static int supdrvIOCtl_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRGETSYMBOL pReq)
5380{
5381 PSUPDRVLDRIMAGE pImage;
5382 PSUPDRVLDRUSAGE pUsage;
5383 uint32_t i;
5384 PSUPLDRSYM paSyms;
5385 const char *pchStrings;
5386 const size_t cbSymbol = strlen(pReq->u.In.szSymbol) + 1;
5387 void *pvSymbol = NULL;
5388 int rc = VERR_SYMBOL_NOT_FOUND;
5389 Log3(("supdrvIOCtl_LdrGetSymbol: pvImageBase=%p szSymbol=\"%s\"\n", pReq->u.In.pvImageBase, pReq->u.In.szSymbol));
5390
5391 /*
5392 * Find the ldr image.
5393 */
5394 supdrvLdrLock(pDevExt);
5395 pUsage = pSession->pLdrUsage;
5396 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
5397 pUsage = pUsage->pNext;
5398 if (!pUsage)
5399 {
5400 supdrvLdrUnlock(pDevExt);
5401 Log(("SUP_IOCTL_LDR_GET_SYMBOL: couldn't find image!\n"));
5402 return VERR_INVALID_HANDLE;
5403 }
5404 pImage = pUsage->pImage;
5405 if (pImage->uState != SUP_IOCTL_LDR_LOAD)
5406 {
5407 unsigned uState = pImage->uState;
5408 supdrvLdrUnlock(pDevExt);
5409 Log(("SUP_IOCTL_LDR_GET_SYMBOL: invalid image state %d (%#x)!\n", uState, uState)); NOREF(uState);
5410 return VERR_ALREADY_LOADED;
5411 }
5412
5413 /*
5414 * Search the symbol strings.
5415 *
5416 * Note! The int32_t is for native loading on solaris where the data
5417 * and text segments are in very different places.
5418 */
5419 pchStrings = pImage->pachStrTab;
5420 paSyms = pImage->paSymbols;
5421 for (i = 0; i < pImage->cSymbols; i++)
5422 {
5423 if ( paSyms[i].offName + cbSymbol <= pImage->cbStrTab
5424 && !memcmp(pchStrings + paSyms[i].offName, pReq->u.In.szSymbol, cbSymbol))
5425 {
5426 pvSymbol = (uint8_t *)pImage->pvImage + (int32_t)paSyms[i].offSymbol;
5427 rc = VINF_SUCCESS;
5428 break;
5429 }
5430 }
5431 supdrvLdrUnlock(pDevExt);
5432 pReq->u.Out.pvSymbol = pvSymbol;
5433 return rc;
5434}
5435
5436
5437/**
5438 * Gets the address of a symbol in an open image or the support driver.
5439 *
5440 * @returns VINF_SUCCESS on success.
5441 * @returns
5442 * @param pDevExt Device globals.
5443 * @param pSession Session data.
5444 * @param pReq The request buffer.
5445 */
5446static int supdrvIDC_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVIDCREQGETSYM pReq)
5447{
5448 int rc = VINF_SUCCESS;
5449 const char *pszSymbol = pReq->u.In.pszSymbol;
5450 const char *pszModule = pReq->u.In.pszModule;
5451 size_t cbSymbol;
5452 char const *pszEnd;
5453 uint32_t i;
5454
5455 /*
5456 * Input validation.
5457 */
5458 AssertPtrReturn(pszSymbol, VERR_INVALID_POINTER);
5459 pszEnd = RTStrEnd(pszSymbol, 512);
5460 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
5461 cbSymbol = pszEnd - pszSymbol + 1;
5462
5463 if (pszModule)
5464 {
5465 AssertPtrReturn(pszModule, VERR_INVALID_POINTER);
5466 pszEnd = RTStrEnd(pszModule, 64);
5467 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
5468 }
5469 Log3(("supdrvIDC_LdrGetSymbol: pszModule=%p:{%s} pszSymbol=%p:{%s}\n", pszModule, pszModule, pszSymbol, pszSymbol));
5470
5471
5472 if ( !pszModule
5473 || !strcmp(pszModule, "SupDrv"))
5474 {
5475 /*
5476 * Search the support driver export table.
5477 */
5478 for (i = 0; i < RT_ELEMENTS(g_aFunctions); i++)
5479 if (!strcmp(g_aFunctions[i].szName, pszSymbol))
5480 {
5481 pReq->u.Out.pfnSymbol = (PFNRT)(uintptr_t)g_aFunctions[i].pfn;
5482 break;
5483 }
5484 }
5485 else
5486 {
5487 /*
5488 * Find the loader image.
5489 */
5490 PSUPDRVLDRIMAGE pImage;
5491
5492 supdrvLdrLock(pDevExt);
5493
5494 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
5495 if (!strcmp(pImage->szName, pszModule))
5496 break;
5497 if (pImage && pImage->uState == SUP_IOCTL_LDR_LOAD)
5498 {
5499 /*
5500 * Search the symbol strings.
5501 */
5502 const char *pchStrings = pImage->pachStrTab;
5503 PCSUPLDRSYM paSyms = pImage->paSymbols;
5504 for (i = 0; i < pImage->cSymbols; i++)
5505 {
5506 if ( paSyms[i].offName + cbSymbol <= pImage->cbStrTab
5507 && !memcmp(pchStrings + paSyms[i].offName, pszSymbol, cbSymbol))
5508 {
5509 /*
5510 * Found it! Calc the symbol address and add a reference to the module.
5511 */
5512 pReq->u.Out.pfnSymbol = (PFNRT)((uintptr_t)pImage->pvImage + (int32_t)paSyms[i].offSymbol);
5513 rc = supdrvLdrAddUsage(pSession, pImage);
5514 break;
5515 }
5516 }
5517 }
5518 else
5519 rc = pImage ? VERR_WRONG_ORDER : VERR_MODULE_NOT_FOUND;
5520
5521 supdrvLdrUnlock(pDevExt);
5522 }
5523 return rc;
5524}
5525
5526
5527/**
5528 * Updates the VMMR0 entry point pointers.
5529 *
5530 * @returns IPRT status code.
5531 * @param pDevExt Device globals.
5532 * @param pvVMMR0 VMMR0 image handle.
5533 * @param pvVMMR0EntryFast VMMR0EntryFast address.
5534 * @param pvVMMR0EntryEx VMMR0EntryEx address.
5535 * @remark Caller must own the loader mutex.
5536 */
5537static int supdrvLdrSetVMMR0EPs(PSUPDRVDEVEXT pDevExt, void *pvVMMR0, void *pvVMMR0EntryFast, void *pvVMMR0EntryEx)
5538{
5539 int rc = VINF_SUCCESS;
5540 LogFlow(("supdrvLdrSetR0EP pvVMMR0=%p pvVMMR0EntryFast=%p\n", pvVMMR0, pvVMMR0EntryFast));
5541
5542
5543 /*
5544 * Check if not yet set.
5545 */
5546 if (!pDevExt->pvVMMR0)
5547 {
5548 pDevExt->pvVMMR0 = pvVMMR0;
5549 *(void **)&pDevExt->pfnVMMR0EntryFast = pvVMMR0EntryFast;
5550 *(void **)&pDevExt->pfnVMMR0EntryEx = pvVMMR0EntryEx;
5551 ASMCompilerBarrier(); /* the above isn't nice, so be careful... */
5552 }
5553 else
5554 {
5555 /*
5556 * Return failure or success depending on whether the values match or not.
5557 */
5558 if ( pDevExt->pvVMMR0 != pvVMMR0
5559 || (uintptr_t)pDevExt->pfnVMMR0EntryFast != (uintptr_t)pvVMMR0EntryFast
5560 || (uintptr_t)pDevExt->pfnVMMR0EntryEx != (uintptr_t)pvVMMR0EntryEx)
5561 {
5562 AssertMsgFailed(("SUP_IOCTL_LDR_SETR0EP: Already set pointing to a different module!\n"));
5563 rc = VERR_INVALID_PARAMETER;
5564 }
5565 }
5566 return rc;
5567}
5568
5569
5570/**
5571 * Unsets the VMMR0 entry point installed by supdrvLdrSetR0EP.
5572 *
5573 * @param pDevExt Device globals.
5574 */
5575static void supdrvLdrUnsetVMMR0EPs(PSUPDRVDEVEXT pDevExt)
5576{
5577 pDevExt->pvVMMR0 = NULL;
5578 pDevExt->pfnVMMR0EntryFast = NULL;
5579 pDevExt->pfnVMMR0EntryEx = NULL;
5580}
5581
5582
5583/**
5584 * Adds a usage reference in the specified session of an image.
5585 *
5586 * Called while owning the loader semaphore.
5587 *
5588 * @returns VINF_SUCCESS on success and VERR_NO_MEMORY on failure.
5589 * @param pSession Session in question.
5590 * @param pImage Image which the session is using.
5591 */
5592static int supdrvLdrAddUsage(PSUPDRVSESSION pSession, PSUPDRVLDRIMAGE pImage)
5593{
5594 PSUPDRVLDRUSAGE pUsage;
5595 LogFlow(("supdrvLdrAddUsage: pImage=%p\n", pImage));
5596
5597 /*
5598 * Referenced it already?
5599 */
5600 pUsage = pSession->pLdrUsage;
5601 while (pUsage)
5602 {
5603 if (pUsage->pImage == pImage)
5604 {
5605 pUsage->cUsage++;
5606 return VINF_SUCCESS;
5607 }
5608 pUsage = pUsage->pNext;
5609 }
5610
5611 /*
5612 * Allocate new usage record.
5613 */
5614 pUsage = (PSUPDRVLDRUSAGE)RTMemAlloc(sizeof(*pUsage));
5615 AssertReturn(pUsage, /*VERR_NO_MEMORY*/ VERR_INTERNAL_ERROR_5);
5616 pUsage->cUsage = 1;
5617 pUsage->pImage = pImage;
5618 pUsage->pNext = pSession->pLdrUsage;
5619 pSession->pLdrUsage = pUsage;
5620 return VINF_SUCCESS;
5621}
5622
5623
5624/**
5625 * Frees a load image.
5626 *
5627 * @param pDevExt Pointer to device extension.
5628 * @param pImage Pointer to the image we're gonna free.
5629 * This image must exit!
5630 * @remark The caller MUST own SUPDRVDEVEXT::mtxLdr!
5631 */
5632static void supdrvLdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage)
5633{
5634 PSUPDRVLDRIMAGE pImagePrev;
5635 LogFlow(("supdrvLdrFree: pImage=%p\n", pImage));
5636
5637 /*
5638 * Warn if we're releasing images while the image loader interface is
5639 * locked down -- we won't be able to reload them!
5640 */
5641 if (pDevExt->fLdrLockedDown)
5642 Log(("supdrvLdrFree: Warning: unloading '%s' image, while loader interface is locked down!\n", pImage->szName));
5643
5644 /* find it - arg. should've used doubly linked list. */
5645 Assert(pDevExt->pLdrImages);
5646 pImagePrev = NULL;
5647 if (pDevExt->pLdrImages != pImage)
5648 {
5649 pImagePrev = pDevExt->pLdrImages;
5650 while (pImagePrev->pNext != pImage)
5651 pImagePrev = pImagePrev->pNext;
5652 Assert(pImagePrev->pNext == pImage);
5653 }
5654
5655 /* unlink */
5656 if (pImagePrev)
5657 pImagePrev->pNext = pImage->pNext;
5658 else
5659 pDevExt->pLdrImages = pImage->pNext;
5660
5661 /* check if this is VMMR0.r0 unset its entry point pointers. */
5662 if (pDevExt->pvVMMR0 == pImage->pvImage)
5663 supdrvLdrUnsetVMMR0EPs(pDevExt);
5664
5665 /* check for objects with destructors in this image. (Shouldn't happen.) */
5666 if (pDevExt->pObjs)
5667 {
5668 unsigned cObjs = 0;
5669 PSUPDRVOBJ pObj;
5670 RTSpinlockAcquire(pDevExt->Spinlock);
5671 for (pObj = pDevExt->pObjs; pObj; pObj = pObj->pNext)
5672 if (RT_UNLIKELY((uintptr_t)pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
5673 {
5674 pObj->pfnDestructor = NULL;
5675 cObjs++;
5676 }
5677 RTSpinlockRelease(pDevExt->Spinlock);
5678 if (cObjs)
5679 OSDBGPRINT(("supdrvLdrFree: Image '%s' has %d dangling objects!\n", pImage->szName, cObjs));
5680 }
5681
5682 /* call termination function if fully loaded. */
5683 if ( pImage->pfnModuleTerm
5684 && pImage->uState == SUP_IOCTL_LDR_LOAD)
5685 {
5686 LogFlow(("supdrvIOCtl_LdrLoad: calling pfnModuleTerm=%p\n", pImage->pfnModuleTerm));
5687 pImage->pfnModuleTerm(pImage);
5688 }
5689
5690 /* Inform the tracing component. */
5691 supdrvTracerModuleUnloading(pDevExt, pImage);
5692
5693 /* Do native unload if appropriate, then inform the native code about the
5694 unloading (mainly for non-native loading case). */
5695 if (pImage->fNative)
5696 supdrvOSLdrUnload(pDevExt, pImage);
5697 supdrvOSLdrNotifyUnloaded(pDevExt, pImage);
5698
5699 /* free the image */
5700 pImage->cUsage = 0;
5701 pImage->pDevExt = NULL;
5702 pImage->pNext = NULL;
5703 pImage->uState = SUP_IOCTL_LDR_FREE;
5704 RTMemExecFree(pImage->pvImageAlloc, pImage->cbImageBits + 31);
5705 pImage->pvImageAlloc = NULL;
5706 RTMemFree(pImage->pachStrTab);
5707 pImage->pachStrTab = NULL;
5708 RTMemFree(pImage->paSymbols);
5709 pImage->paSymbols = NULL;
5710 RTMemFree(pImage);
5711}
5712
5713
5714/**
5715 * Acquires the loader lock.
5716 *
5717 * @returns IPRT status code.
5718 * @param pDevExt The device extension.
5719 */
5720DECLINLINE(int) supdrvLdrLock(PSUPDRVDEVEXT pDevExt)
5721{
5722#ifdef SUPDRV_USE_MUTEX_FOR_LDR
5723 int rc = RTSemMutexRequest(pDevExt->mtxLdr, RT_INDEFINITE_WAIT);
5724#else
5725 int rc = RTSemFastMutexRequest(pDevExt->mtxLdr);
5726#endif
5727 AssertRC(rc);
5728 return rc;
5729}
5730
5731
5732/**
5733 * Releases the loader lock.
5734 *
5735 * @returns IPRT status code.
5736 * @param pDevExt The device extension.
5737 */
5738DECLINLINE(int) supdrvLdrUnlock(PSUPDRVDEVEXT pDevExt)
5739{
5740#ifdef SUPDRV_USE_MUTEX_FOR_LDR
5741 return RTSemMutexRelease(pDevExt->mtxLdr);
5742#else
5743 return RTSemFastMutexRelease(pDevExt->mtxLdr);
5744#endif
5745}
5746
5747
5748/**
5749 * Implements the service call request.
5750 *
5751 * @returns VBox status code.
5752 * @param pDevExt The device extension.
5753 * @param pSession The calling session.
5754 * @param pReq The request packet, valid.
5755 */
5756static int supdrvIOCtl_CallServiceModule(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPCALLSERVICE pReq)
5757{
5758#if !defined(RT_OS_WINDOWS) || defined(RT_ARCH_AMD64) || defined(DEBUG)
5759 int rc;
5760
5761 /*
5762 * Find the module first in the module referenced by the calling session.
5763 */
5764 rc = supdrvLdrLock(pDevExt);
5765 if (RT_SUCCESS(rc))
5766 {
5767 PFNSUPR0SERVICEREQHANDLER pfnServiceReqHandler = NULL;
5768 PSUPDRVLDRUSAGE pUsage;
5769
5770 for (pUsage = pSession->pLdrUsage; pUsage; pUsage = pUsage->pNext)
5771 if ( pUsage->pImage->pfnServiceReqHandler
5772 && !strcmp(pUsage->pImage->szName, pReq->u.In.szName))
5773 {
5774 pfnServiceReqHandler = pUsage->pImage->pfnServiceReqHandler;
5775 break;
5776 }
5777 supdrvLdrUnlock(pDevExt);
5778
5779 if (pfnServiceReqHandler)
5780 {
5781 /*
5782 * Call it.
5783 */
5784 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_SERVICE_SIZE(0))
5785 rc = pfnServiceReqHandler(pSession, pReq->u.In.uOperation, pReq->u.In.u64Arg, NULL);
5786 else
5787 rc = pfnServiceReqHandler(pSession, pReq->u.In.uOperation, pReq->u.In.u64Arg, (PSUPR0SERVICEREQHDR)&pReq->abReqPkt[0]);
5788 }
5789 else
5790 rc = VERR_SUPDRV_SERVICE_NOT_FOUND;
5791 }
5792
5793 /* log it */
5794 if ( RT_FAILURE(rc)
5795 && rc != VERR_INTERRUPTED
5796 && rc != VERR_TIMEOUT)
5797 Log(("SUP_IOCTL_CALL_SERVICE: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
5798 rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
5799 else
5800 Log4(("SUP_IOCTL_CALL_SERVICE: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
5801 rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
5802 return rc;
5803#else /* RT_OS_WINDOWS && !RT_ARCH_AMD64 && !DEBUG */
5804 RT_NOREF3(pDevExt, pSession, pReq);
5805 return VERR_NOT_IMPLEMENTED;
5806#endif /* RT_OS_WINDOWS && !RT_ARCH_AMD64 && !DEBUG */
5807}
5808
5809
5810/**
5811 * Implements the logger settings request.
5812 *
5813 * @returns VBox status code.
5814 * @param pReq The request.
5815 */
5816static int supdrvIOCtl_LoggerSettings(PSUPLOGGERSETTINGS pReq)
5817{
5818 const char *pszGroup = &pReq->u.In.szStrings[pReq->u.In.offGroups];
5819 const char *pszFlags = &pReq->u.In.szStrings[pReq->u.In.offFlags];
5820 const char *pszDest = &pReq->u.In.szStrings[pReq->u.In.offDestination];
5821 PRTLOGGER pLogger = NULL;
5822 int rc;
5823
5824 /*
5825 * Some further validation.
5826 */
5827 switch (pReq->u.In.fWhat)
5828 {
5829 case SUPLOGGERSETTINGS_WHAT_SETTINGS:
5830 case SUPLOGGERSETTINGS_WHAT_CREATE:
5831 break;
5832
5833 case SUPLOGGERSETTINGS_WHAT_DESTROY:
5834 if (*pszGroup || *pszFlags || *pszDest)
5835 return VERR_INVALID_PARAMETER;
5836 if (pReq->u.In.fWhich == SUPLOGGERSETTINGS_WHICH_RELEASE)
5837 return VERR_ACCESS_DENIED;
5838 break;
5839
5840 default:
5841 return VERR_INTERNAL_ERROR;
5842 }
5843
5844 /*
5845 * Get the logger.
5846 */
5847 switch (pReq->u.In.fWhich)
5848 {
5849 case SUPLOGGERSETTINGS_WHICH_DEBUG:
5850 pLogger = RTLogGetDefaultInstance();
5851 break;
5852
5853 case SUPLOGGERSETTINGS_WHICH_RELEASE:
5854 pLogger = RTLogRelGetDefaultInstance();
5855 break;
5856
5857 default:
5858 return VERR_INTERNAL_ERROR;
5859 }
5860
5861 /*
5862 * Do the job.
5863 */
5864 switch (pReq->u.In.fWhat)
5865 {
5866 case SUPLOGGERSETTINGS_WHAT_SETTINGS:
5867 if (pLogger)
5868 {
5869 rc = RTLogFlags(pLogger, pszFlags);
5870 if (RT_SUCCESS(rc))
5871 rc = RTLogGroupSettings(pLogger, pszGroup);
5872 NOREF(pszDest);
5873 }
5874 else
5875 rc = VERR_NOT_FOUND;
5876 break;
5877
5878 case SUPLOGGERSETTINGS_WHAT_CREATE:
5879 {
5880 if (pLogger)
5881 rc = VERR_ALREADY_EXISTS;
5882 else
5883 {
5884 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
5885
5886 rc = RTLogCreate(&pLogger,
5887 0 /* fFlags */,
5888 pszGroup,
5889 pReq->u.In.fWhich == SUPLOGGERSETTINGS_WHICH_DEBUG
5890 ? "VBOX_LOG"
5891 : "VBOX_RELEASE_LOG",
5892 RT_ELEMENTS(s_apszGroups),
5893 s_apszGroups,
5894 RTLOGDEST_STDOUT | RTLOGDEST_DEBUGGER,
5895 NULL);
5896 if (RT_SUCCESS(rc))
5897 {
5898 rc = RTLogFlags(pLogger, pszFlags);
5899 NOREF(pszDest);
5900 if (RT_SUCCESS(rc))
5901 {
5902 switch (pReq->u.In.fWhich)
5903 {
5904 case SUPLOGGERSETTINGS_WHICH_DEBUG:
5905 pLogger = RTLogSetDefaultInstance(pLogger);
5906 break;
5907 case SUPLOGGERSETTINGS_WHICH_RELEASE:
5908 pLogger = RTLogRelSetDefaultInstance(pLogger);
5909 break;
5910 }
5911 }
5912 RTLogDestroy(pLogger);
5913 }
5914 }
5915 break;
5916 }
5917
5918 case SUPLOGGERSETTINGS_WHAT_DESTROY:
5919 switch (pReq->u.In.fWhich)
5920 {
5921 case SUPLOGGERSETTINGS_WHICH_DEBUG:
5922 pLogger = RTLogSetDefaultInstance(NULL);
5923 break;
5924 case SUPLOGGERSETTINGS_WHICH_RELEASE:
5925 pLogger = RTLogRelSetDefaultInstance(NULL);
5926 break;
5927 }
5928 rc = RTLogDestroy(pLogger);
5929 break;
5930
5931 default:
5932 {
5933 rc = VERR_INTERNAL_ERROR;
5934 break;
5935 }
5936 }
5937
5938 return rc;
5939}
5940
5941
5942/**
5943 * Implements the MSR prober operations.
5944 *
5945 * @returns VBox status code.
5946 * @param pDevExt The device extension.
5947 * @param pReq The request.
5948 */
5949static int supdrvIOCtl_MsrProber(PSUPDRVDEVEXT pDevExt, PSUPMSRPROBER pReq)
5950{
5951#ifdef SUPDRV_WITH_MSR_PROBER
5952 RTCPUID const idCpu = pReq->u.In.idCpu == UINT32_MAX ? NIL_RTCPUID : pReq->u.In.idCpu;
5953 int rc;
5954
5955 switch (pReq->u.In.enmOp)
5956 {
5957 case SUPMSRPROBEROP_READ:
5958 {
5959 uint64_t uValue;
5960 rc = supdrvOSMsrProberRead(pReq->u.In.uMsr, idCpu, &uValue);
5961 if (RT_SUCCESS(rc))
5962 {
5963 pReq->u.Out.uResults.Read.uValue = uValue;
5964 pReq->u.Out.uResults.Read.fGp = false;
5965 }
5966 else if (rc == VERR_ACCESS_DENIED)
5967 {
5968 pReq->u.Out.uResults.Read.uValue = 0;
5969 pReq->u.Out.uResults.Read.fGp = true;
5970 rc = VINF_SUCCESS;
5971 }
5972 break;
5973 }
5974
5975 case SUPMSRPROBEROP_WRITE:
5976 rc = supdrvOSMsrProberWrite(pReq->u.In.uMsr, idCpu, pReq->u.In.uArgs.Write.uToWrite);
5977 if (RT_SUCCESS(rc))
5978 pReq->u.Out.uResults.Write.fGp = false;
5979 else if (rc == VERR_ACCESS_DENIED)
5980 {
5981 pReq->u.Out.uResults.Write.fGp = true;
5982 rc = VINF_SUCCESS;
5983 }
5984 break;
5985
5986 case SUPMSRPROBEROP_MODIFY:
5987 case SUPMSRPROBEROP_MODIFY_FASTER:
5988 rc = supdrvOSMsrProberModify(idCpu, pReq);
5989 break;
5990
5991 default:
5992 return VERR_INVALID_FUNCTION;
5993 }
5994 RT_NOREF1(pDevExt);
5995 return rc;
5996#else
5997 RT_NOREF2(pDevExt, pReq);
5998 return VERR_NOT_IMPLEMENTED;
5999#endif
6000}
6001
6002
6003/**
6004 * Resume built-in keyboard on MacBook Air and Pro hosts.
6005 * If there is no built-in keyboard device, return success anyway.
6006 *
6007 * @returns 0 on Mac OS X platform, VERR_NOT_IMPLEMENTED on the other ones.
6008 */
6009static int supdrvIOCtl_ResumeSuspendedKbds(void)
6010{
6011#if defined(RT_OS_DARWIN)
6012 return supdrvDarwinResumeSuspendedKbds();
6013#else
6014 return VERR_NOT_IMPLEMENTED;
6015#endif
6016}
6017
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