VirtualBox

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

Last change on this file since 57112 was 57090, checked in by vboxsync, 10 years ago

SUP: Moved SUPIsTscFreqCompatible(Ex) to SUPLibAll.cpp and made it not inlined.

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

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