VirtualBox

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

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

VMM,SUPDrv: Started on some session/VMMR0 nits. I/O control interface version bump (sorry).

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

© 2023 Oracle
ContactPrivacy policyTerms of Use