VirtualBox

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

Last change on this file since 76223 was 76223, checked in by vboxsync, 6 years ago

SUPDrv: Have a separate function to check for VT-x/AMD-V support, for upcoming changes to HMR0 which will re-use this. No need to duplicate this code in multiple places.

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