VirtualBox

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

Last change on this file since 54335 was 54331, checked in by vboxsync, 10 years ago

SUPDrv.c -> SUPDrv.cpp; SUPDrvSem.c -> SUPDrvSem.cpp

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