VirtualBox

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

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

SUPDrv-darwin.cpp: CR4.VMXE fix after host_vmxon issue.

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

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