VirtualBox

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

Last change on this file since 60273 was 60241, checked in by vboxsync, 9 years ago

usblib.h,SUPDrv: Added missing RTStrPurgeEncoding to SUPDrv so VBoxUSB/whatever can use it on darwin and solaris.

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