VirtualBox

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

Last change on this file since 61551 was 60603, checked in by vboxsync, 9 years ago

Assorted compile fixes for FreeBSD

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