VirtualBox

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

Last change on this file since 57276 was 57229, checked in by vboxsync, 9 years ago

SUPDrv,VMMR0: Added SUPR0BadContext for reporting AC=0 and (on darwin with VBOX_WITH_EFLAGS_AC_SET_IN_VBOXDRV defined) refuse further I/O control calls. That way we'll sit up and pay attention, hopefully. VBOX_WITH_EFLAGS_AC_SET_IN_VBOXDRV is currently enabled for all non-release builds (odd build numbers), and we check EFLAGS.AC at the end of each ioctrl call.

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

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