VirtualBox

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

Last change on this file since 56284 was 56270, checked in by vboxsync, 10 years ago

nit.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 207.5 KB
Line 
1/* $Id: SUPDrv.cpp 56270 2015-06-08 09:44:20Z 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 */
3763SUPR0DECL(int) SUPR0GetVmxUsability(bool *pfIsSmxModeAmbiguous)
3764{
3765 uint64_t u64FeatMsr;
3766 bool fMaybeSmxMode;
3767 bool fMsrLocked;
3768 bool fSmxVmxAllowed;
3769 bool fVmxAllowed;
3770 bool fIsSmxModeAmbiguous;
3771 int rc;
3772
3773 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3774
3775 u64FeatMsr = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
3776 fMaybeSmxMode = RT_BOOL(ASMGetCR4() & X86_CR4_SMXE);
3777 fMsrLocked = RT_BOOL(u64FeatMsr & MSR_IA32_FEATURE_CONTROL_LOCK);
3778 fSmxVmxAllowed = RT_BOOL(u64FeatMsr & MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
3779 fVmxAllowed = RT_BOOL(u64FeatMsr & MSR_IA32_FEATURE_CONTROL_VMXON);
3780 fIsSmxModeAmbiguous = false;
3781 rc = VERR_INTERNAL_ERROR_5;
3782
3783 /* Check if the LOCK bit is set but excludes the required VMXON bit. */
3784 if (fMsrLocked)
3785 {
3786 if (fVmxAllowed && fSmxVmxAllowed)
3787 rc = VINF_SUCCESS;
3788 else if (!fVmxAllowed && !fSmxVmxAllowed)
3789 rc = VERR_VMX_MSR_ALL_VMXON_DISABLED;
3790 else if (!fMaybeSmxMode)
3791 {
3792 if (fVmxAllowed)
3793 rc = VINF_SUCCESS;
3794 else
3795 rc = VERR_VMX_MSR_VMXON_DISABLED;
3796 }
3797 else
3798 {
3799 /*
3800 * CR4.SMXE is set but this doesn't mean the CPU is necessarily in SMX mode. We shall assume
3801 * that it is -not- and that it is a stupid BIOS/OS setting CR4.SMXE for no good reason.
3802 * See @bugref{6873}.
3803 */
3804 Assert(fMaybeSmxMode == true);
3805 fIsSmxModeAmbiguous = true;
3806 rc = VINF_SUCCESS;
3807 }
3808 }
3809 else
3810 {
3811 /*
3812 * MSR is not yet locked; we can change it ourselves here. Once the lock bit is set,
3813 * this MSR can no longer be modified.
3814 *
3815 * Set both the VMXON and SMX_VMXON bits (if supported) as we can't determine SMX mode
3816 * accurately. See @bugref{6873}.
3817 *
3818 * The reason we are being paranoid here and (re)checking is that we don't assume all callers
3819 * of this function to check it like SUPR0QueryVTCaps() currently does. If we get something
3820 * wrong here, we can throw a #GP and panic the box. This isn't a performance critical path.
3821 */
3822 uint32_t fFeaturesECX, uDummy;
3823 uint32_t uMaxId, uVendorEBX, uVendorECX, uVendorEDX;
3824 ASMCpuId(0, &uMaxId, &uVendorEBX, &uVendorECX, &uVendorEDX);
3825 ASMCpuId(1, &uDummy, &uDummy, &fFeaturesECX, &uDummy);
3826 if ( ASMIsValidStdRange(uMaxId)
3827 && ( ASMIsIntelCpuEx( uVendorEBX, uVendorECX, uVendorEDX)
3828 || ASMIsViaCentaurCpuEx(uVendorEBX, uVendorECX, uVendorEDX)))
3829 {
3830 bool fSmxVmxHwSupport = false;
3831 if ( (fFeaturesECX & X86_CPUID_FEATURE_ECX_VMX)
3832 && (fFeaturesECX & X86_CPUID_FEATURE_ECX_SMX))
3833 fSmxVmxHwSupport = true;
3834
3835 u64FeatMsr |= MSR_IA32_FEATURE_CONTROL_LOCK
3836 | MSR_IA32_FEATURE_CONTROL_VMXON;
3837 if (fSmxVmxHwSupport)
3838 u64FeatMsr |= MSR_IA32_FEATURE_CONTROL_SMX_VMXON;
3839
3840 /* Commit. */
3841 ASMWrMsr(MSR_IA32_FEATURE_CONTROL, u64FeatMsr);
3842
3843 /* Verify. */
3844 u64FeatMsr = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
3845 fMsrLocked = RT_BOOL(u64FeatMsr & MSR_IA32_FEATURE_CONTROL_LOCK);
3846 fSmxVmxAllowed = fMsrLocked && RT_BOOL(u64FeatMsr & MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
3847 fVmxAllowed = fMsrLocked && RT_BOOL(u64FeatMsr & MSR_IA32_FEATURE_CONTROL_VMXON);
3848 if ( fVmxAllowed
3849 && ( !fSmxVmxHwSupport
3850 || fSmxVmxAllowed))
3851 rc = VINF_SUCCESS;
3852 else
3853 rc = VERR_VMX_MSR_LOCKING_FAILED;
3854 }
3855 else
3856 rc = VERR_VMX_IPE_5;
3857 }
3858
3859 if (pfIsSmxModeAmbiguous)
3860 *pfIsSmxModeAmbiguous = fIsSmxModeAmbiguous;
3861
3862 return rc;
3863}
3864
3865
3866/**
3867 * Checks if AMD-V SVM feature is usable on this CPU.
3868 *
3869 * @returns VBox status code.
3870 * @param fInitSvm If usable, try to initialize SVM on this CPU.
3871 *
3872 * @remarks Must be called with preemption disabled.
3873 */
3874SUPR0DECL(int) SUPR0GetSvmUsability(bool fInitSvm)
3875{
3876 int rc;
3877 uint64_t fVmCr;
3878 uint64_t fEfer;
3879
3880 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3881 fVmCr = ASMRdMsr(MSR_K8_VM_CR);
3882 if (!(fVmCr & MSR_K8_VM_CR_SVM_DISABLE))
3883 {
3884 rc = VINF_SUCCESS;
3885 if (fInitSvm)
3886 {
3887 /* Turn on SVM in the EFER MSR. */
3888 fEfer = ASMRdMsr(MSR_K6_EFER);
3889 if (fEfer & MSR_K6_EFER_SVME)
3890 rc = VERR_SVM_IN_USE;
3891 else
3892 {
3893 ASMWrMsr(MSR_K6_EFER, fEfer | MSR_K6_EFER_SVME);
3894
3895 /* Paranoia. */
3896 fEfer = ASMRdMsr(MSR_K6_EFER);
3897 if (fEfer & MSR_K6_EFER_SVME)
3898 {
3899 /* Restore previous value. */
3900 ASMWrMsr(MSR_K6_EFER, fEfer & ~MSR_K6_EFER_SVME);
3901 }
3902 else
3903 rc = VERR_SVM_ILLEGAL_EFER_MSR;
3904 }
3905 }
3906 }
3907 else
3908 rc = VERR_SVM_DISABLED;
3909 return rc;
3910}
3911
3912
3913/**
3914 * Queries the AMD-V and VT-x capabilities of the calling CPU.
3915 *
3916 * @returns VBox status code.
3917 * @retval VERR_VMX_NO_VMX
3918 * @retval VERR_VMX_MSR_ALL_VMXON_DISABLED
3919 * @retval VERR_VMX_MSR_VMXON_DISABLED
3920 * @retval VERR_VMX_MSR_LOCKING_FAILED
3921 * @retval VERR_SVM_NO_SVM
3922 * @retval VERR_SVM_DISABLED
3923 * @retval VERR_UNSUPPORTED_CPU if not identifiable as an AMD, Intel or VIA
3924 * (centaur) CPU.
3925 *
3926 * @param pSession The session handle.
3927 * @param pfCaps Where to store the capabilities.
3928 */
3929SUPR0DECL(int) SUPR0QueryVTCaps(PSUPDRVSESSION pSession, uint32_t *pfCaps)
3930{
3931 int rc = VERR_UNSUPPORTED_CPU;
3932 bool fIsSmxModeAmbiguous = false;
3933 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
3934
3935 /*
3936 * Input validation.
3937 */
3938 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3939 AssertPtrReturn(pfCaps, VERR_INVALID_POINTER);
3940
3941 *pfCaps = 0;
3942 /* We may modify MSRs and re-read them, disable preemption so we make sure we don't migrate CPUs. */
3943 RTThreadPreemptDisable(&PreemptState);
3944 if (ASMHasCpuId())
3945 {
3946 uint32_t fFeaturesECX, fFeaturesEDX, uDummy;
3947 uint32_t uMaxId, uVendorEBX, uVendorECX, uVendorEDX;
3948
3949 ASMCpuId(0, &uMaxId, &uVendorEBX, &uVendorECX, &uVendorEDX);
3950 ASMCpuId(1, &uDummy, &uDummy, &fFeaturesECX, &fFeaturesEDX);
3951
3952 if ( ASMIsValidStdRange(uMaxId)
3953 && ( ASMIsIntelCpuEx( uVendorEBX, uVendorECX, uVendorEDX)
3954 || ASMIsViaCentaurCpuEx(uVendorEBX, uVendorECX, uVendorEDX) )
3955 )
3956 {
3957 if ( (fFeaturesECX & X86_CPUID_FEATURE_ECX_VMX)
3958 && (fFeaturesEDX & X86_CPUID_FEATURE_EDX_MSR)
3959 && (fFeaturesEDX & X86_CPUID_FEATURE_EDX_FXSR)
3960 )
3961 {
3962 rc = SUPR0GetVmxUsability(&fIsSmxModeAmbiguous);
3963 if (rc == VINF_SUCCESS)
3964 {
3965 VMXCAPABILITY vtCaps;
3966
3967 *pfCaps |= SUPVTCAPS_VT_X;
3968
3969 vtCaps.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS);
3970 if (vtCaps.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL)
3971 {
3972 vtCaps.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS2);
3973 if (vtCaps.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_EPT)
3974 *pfCaps |= SUPVTCAPS_NESTED_PAGING;
3975 if (vtCaps.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_UNRESTRICTED_GUEST)
3976 *pfCaps |= SUPVTCAPS_VTX_UNRESTRICTED_GUEST;
3977 }
3978 }
3979 }
3980 else
3981 rc = VERR_VMX_NO_VMX;
3982 }
3983 else if ( ASMIsAmdCpuEx(uVendorEBX, uVendorECX, uVendorEDX)
3984 && ASMIsValidStdRange(uMaxId))
3985 {
3986 uint32_t fExtFeaturesEcx, uExtMaxId;
3987 ASMCpuId(0x80000000, &uExtMaxId, &uDummy, &uDummy, &uDummy);
3988 ASMCpuId(0x80000001, &uDummy, &uDummy, &fExtFeaturesEcx, &uDummy);
3989
3990 /* Check if SVM is available. */
3991 if ( ASMIsValidExtRange(uExtMaxId)
3992 && uExtMaxId >= 0x8000000a
3993 && (fExtFeaturesEcx & X86_CPUID_AMD_FEATURE_ECX_SVM)
3994 && (fFeaturesEDX & X86_CPUID_FEATURE_EDX_MSR)
3995 && (fFeaturesEDX & X86_CPUID_FEATURE_EDX_FXSR)
3996 )
3997 {
3998 rc = SUPR0GetSvmUsability(false /* fInitSvm */);
3999 if (RT_SUCCESS(rc))
4000 {
4001 uint32_t fSvmFeatures;
4002 *pfCaps |= SUPVTCAPS_AMD_V;
4003
4004 /* Query AMD-V features. */
4005 ASMCpuId(0x8000000a, &uDummy, &uDummy, &uDummy, &fSvmFeatures);
4006 if (fSvmFeatures & AMD_CPUID_SVM_FEATURE_EDX_NESTED_PAGING)
4007 *pfCaps |= SUPVTCAPS_NESTED_PAGING;
4008 }
4009 }
4010 else
4011 rc = VERR_SVM_NO_SVM;
4012 }
4013 }
4014
4015 RTThreadPreemptRestore(&PreemptState);
4016 if (fIsSmxModeAmbiguous)
4017 SUPR0Printf(("WARNING! CR4 hints SMX mode but your CPU is too secretive. Proceeding anyway... We wish you good luck!\n"));
4018 return rc;
4019}
4020
4021
4022/**
4023 * Register a component factory with the support driver.
4024 *
4025 * This is currently restricted to kernel sessions only.
4026 *
4027 * @returns VBox status code.
4028 * @retval VINF_SUCCESS on success.
4029 * @retval VERR_NO_MEMORY if we're out of memory.
4030 * @retval VERR_ALREADY_EXISTS if the factory has already been registered.
4031 * @retval VERR_ACCESS_DENIED if it isn't a kernel session.
4032 * @retval VERR_INVALID_PARAMETER on invalid parameter.
4033 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
4034 *
4035 * @param pSession The SUPDRV session (must be a ring-0 session).
4036 * @param pFactory Pointer to the component factory registration structure.
4037 *
4038 * @remarks This interface is also available via SUPR0IdcComponentRegisterFactory.
4039 */
4040SUPR0DECL(int) SUPR0ComponentRegisterFactory(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory)
4041{
4042 PSUPDRVFACTORYREG pNewReg;
4043 const char *psz;
4044 int rc;
4045
4046 /*
4047 * Validate parameters.
4048 */
4049 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4050 AssertReturn(pSession->R0Process == NIL_RTR0PROCESS, VERR_ACCESS_DENIED);
4051 AssertPtrReturn(pFactory, VERR_INVALID_POINTER);
4052 AssertPtrReturn(pFactory->pfnQueryFactoryInterface, VERR_INVALID_POINTER);
4053 psz = RTStrEnd(pFactory->szName, sizeof(pFactory->szName));
4054 AssertReturn(psz, VERR_INVALID_PARAMETER);
4055
4056 /*
4057 * Allocate and initialize a new registration structure.
4058 */
4059 pNewReg = (PSUPDRVFACTORYREG)RTMemAlloc(sizeof(SUPDRVFACTORYREG));
4060 if (pNewReg)
4061 {
4062 pNewReg->pNext = NULL;
4063 pNewReg->pFactory = pFactory;
4064 pNewReg->pSession = pSession;
4065 pNewReg->cchName = psz - &pFactory->szName[0];
4066
4067 /*
4068 * Add it to the tail of the list after checking for prior registration.
4069 */
4070 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
4071 if (RT_SUCCESS(rc))
4072 {
4073 PSUPDRVFACTORYREG pPrev = NULL;
4074 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
4075 while (pCur && pCur->pFactory != pFactory)
4076 {
4077 pPrev = pCur;
4078 pCur = pCur->pNext;
4079 }
4080 if (!pCur)
4081 {
4082 if (pPrev)
4083 pPrev->pNext = pNewReg;
4084 else
4085 pSession->pDevExt->pComponentFactoryHead = pNewReg;
4086 rc = VINF_SUCCESS;
4087 }
4088 else
4089 rc = VERR_ALREADY_EXISTS;
4090
4091 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
4092 }
4093
4094 if (RT_FAILURE(rc))
4095 RTMemFree(pNewReg);
4096 }
4097 else
4098 rc = VERR_NO_MEMORY;
4099 return rc;
4100}
4101
4102
4103/**
4104 * Deregister a component factory.
4105 *
4106 * @returns VBox status code.
4107 * @retval VINF_SUCCESS on success.
4108 * @retval VERR_NOT_FOUND if the factory wasn't registered.
4109 * @retval VERR_ACCESS_DENIED if it isn't a kernel session.
4110 * @retval VERR_INVALID_PARAMETER on invalid parameter.
4111 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
4112 *
4113 * @param pSession The SUPDRV session (must be a ring-0 session).
4114 * @param pFactory Pointer to the component factory registration structure
4115 * previously passed SUPR0ComponentRegisterFactory().
4116 *
4117 * @remarks This interface is also available via SUPR0IdcComponentDeregisterFactory.
4118 */
4119SUPR0DECL(int) SUPR0ComponentDeregisterFactory(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory)
4120{
4121 int rc;
4122
4123 /*
4124 * Validate parameters.
4125 */
4126 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4127 AssertReturn(pSession->R0Process == NIL_RTR0PROCESS, VERR_ACCESS_DENIED);
4128 AssertPtrReturn(pFactory, VERR_INVALID_POINTER);
4129
4130 /*
4131 * Take the lock and look for the registration record.
4132 */
4133 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
4134 if (RT_SUCCESS(rc))
4135 {
4136 PSUPDRVFACTORYREG pPrev = NULL;
4137 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
4138 while (pCur && pCur->pFactory != pFactory)
4139 {
4140 pPrev = pCur;
4141 pCur = pCur->pNext;
4142 }
4143 if (pCur)
4144 {
4145 if (!pPrev)
4146 pSession->pDevExt->pComponentFactoryHead = pCur->pNext;
4147 else
4148 pPrev->pNext = pCur->pNext;
4149
4150 pCur->pNext = NULL;
4151 pCur->pFactory = NULL;
4152 pCur->pSession = NULL;
4153 rc = VINF_SUCCESS;
4154 }
4155 else
4156 rc = VERR_NOT_FOUND;
4157
4158 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
4159
4160 RTMemFree(pCur);
4161 }
4162 return rc;
4163}
4164
4165
4166/**
4167 * Queries a component factory.
4168 *
4169 * @returns VBox status code.
4170 * @retval VERR_INVALID_PARAMETER on invalid parameter.
4171 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
4172 * @retval VERR_SUPDRV_COMPONENT_NOT_FOUND if the component factory wasn't found.
4173 * @retval VERR_SUPDRV_INTERFACE_NOT_SUPPORTED if the interface wasn't supported.
4174 *
4175 * @param pSession The SUPDRV session.
4176 * @param pszName The name of the component factory.
4177 * @param pszInterfaceUuid The UUID of the factory interface (stringified).
4178 * @param ppvFactoryIf Where to store the factory interface.
4179 */
4180SUPR0DECL(int) SUPR0ComponentQueryFactory(PSUPDRVSESSION pSession, const char *pszName, const char *pszInterfaceUuid, void **ppvFactoryIf)
4181{
4182 const char *pszEnd;
4183 size_t cchName;
4184 int rc;
4185
4186 /*
4187 * Validate parameters.
4188 */
4189 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4190
4191 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
4192 pszEnd = RTStrEnd(pszName, RT_SIZEOFMEMB(SUPDRVFACTORY, szName));
4193 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
4194 cchName = pszEnd - pszName;
4195
4196 AssertPtrReturn(pszInterfaceUuid, VERR_INVALID_POINTER);
4197 pszEnd = RTStrEnd(pszInterfaceUuid, RTUUID_STR_LENGTH);
4198 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
4199
4200 AssertPtrReturn(ppvFactoryIf, VERR_INVALID_POINTER);
4201 *ppvFactoryIf = NULL;
4202
4203 /*
4204 * Take the lock and try all factories by this name.
4205 */
4206 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
4207 if (RT_SUCCESS(rc))
4208 {
4209 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
4210 rc = VERR_SUPDRV_COMPONENT_NOT_FOUND;
4211 while (pCur)
4212 {
4213 if ( pCur->cchName == cchName
4214 && !memcmp(pCur->pFactory->szName, pszName, cchName))
4215 {
4216 void *pvFactory = pCur->pFactory->pfnQueryFactoryInterface(pCur->pFactory, pSession, pszInterfaceUuid);
4217 if (pvFactory)
4218 {
4219 *ppvFactoryIf = pvFactory;
4220 rc = VINF_SUCCESS;
4221 break;
4222 }
4223 rc = VERR_SUPDRV_INTERFACE_NOT_SUPPORTED;
4224 }
4225
4226 /* next */
4227 pCur = pCur->pNext;
4228 }
4229
4230 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
4231 }
4232 return rc;
4233}
4234
4235
4236/**
4237 * Adds a memory object to the session.
4238 *
4239 * @returns IPRT status code.
4240 * @param pMem Memory tracking structure containing the
4241 * information to track.
4242 * @param pSession The session.
4243 */
4244static int supdrvMemAdd(PSUPDRVMEMREF pMem, PSUPDRVSESSION pSession)
4245{
4246 PSUPDRVBUNDLE pBundle;
4247
4248 /*
4249 * Find free entry and record the allocation.
4250 */
4251 RTSpinlockAcquire(pSession->Spinlock);
4252 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
4253 {
4254 if (pBundle->cUsed < RT_ELEMENTS(pBundle->aMem))
4255 {
4256 unsigned i;
4257 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
4258 {
4259 if (pBundle->aMem[i].MemObj == NIL_RTR0MEMOBJ)
4260 {
4261 pBundle->cUsed++;
4262 pBundle->aMem[i] = *pMem;
4263 RTSpinlockRelease(pSession->Spinlock);
4264 return VINF_SUCCESS;
4265 }
4266 }
4267 AssertFailed(); /* !!this can't be happening!!! */
4268 }
4269 }
4270 RTSpinlockRelease(pSession->Spinlock);
4271
4272 /*
4273 * Need to allocate a new bundle.
4274 * Insert into the last entry in the bundle.
4275 */
4276 pBundle = (PSUPDRVBUNDLE)RTMemAllocZ(sizeof(*pBundle));
4277 if (!pBundle)
4278 return VERR_NO_MEMORY;
4279
4280 /* take last entry. */
4281 pBundle->cUsed++;
4282 pBundle->aMem[RT_ELEMENTS(pBundle->aMem) - 1] = *pMem;
4283
4284 /* insert into list. */
4285 RTSpinlockAcquire(pSession->Spinlock);
4286 pBundle->pNext = pSession->Bundle.pNext;
4287 pSession->Bundle.pNext = pBundle;
4288 RTSpinlockRelease(pSession->Spinlock);
4289
4290 return VINF_SUCCESS;
4291}
4292
4293
4294/**
4295 * Releases a memory object referenced by pointer and type.
4296 *
4297 * @returns IPRT status code.
4298 * @param pSession Session data.
4299 * @param uPtr Pointer to memory. This is matched against both the R0 and R3 addresses.
4300 * @param eType Memory type.
4301 */
4302static int supdrvMemRelease(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, SUPDRVMEMREFTYPE eType)
4303{
4304 PSUPDRVBUNDLE pBundle;
4305
4306 /*
4307 * Validate input.
4308 */
4309 if (!uPtr)
4310 {
4311 Log(("Illegal address %p\n", (void *)uPtr));
4312 return VERR_INVALID_PARAMETER;
4313 }
4314
4315 /*
4316 * Search for the address.
4317 */
4318 RTSpinlockAcquire(pSession->Spinlock);
4319 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
4320 {
4321 if (pBundle->cUsed > 0)
4322 {
4323 unsigned i;
4324 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
4325 {
4326 if ( pBundle->aMem[i].eType == eType
4327 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
4328 && ( (RTHCUINTPTR)RTR0MemObjAddress(pBundle->aMem[i].MemObj) == uPtr
4329 || ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
4330 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == uPtr))
4331 )
4332 {
4333 /* Make a copy of it and release it outside the spinlock. */
4334 SUPDRVMEMREF Mem = pBundle->aMem[i];
4335 pBundle->aMem[i].eType = MEMREF_TYPE_UNUSED;
4336 pBundle->aMem[i].MemObj = NIL_RTR0MEMOBJ;
4337 pBundle->aMem[i].MapObjR3 = NIL_RTR0MEMOBJ;
4338 RTSpinlockRelease(pSession->Spinlock);
4339
4340 if (Mem.MapObjR3 != NIL_RTR0MEMOBJ)
4341 {
4342 int rc = RTR0MemObjFree(Mem.MapObjR3, false);
4343 AssertRC(rc); /** @todo figure out how to handle this. */
4344 }
4345 if (Mem.MemObj != NIL_RTR0MEMOBJ)
4346 {
4347 int rc = RTR0MemObjFree(Mem.MemObj, true /* fFreeMappings */);
4348 AssertRC(rc); /** @todo figure out how to handle this. */
4349 }
4350 return VINF_SUCCESS;
4351 }
4352 }
4353 }
4354 }
4355 RTSpinlockRelease(pSession->Spinlock);
4356 Log(("Failed to find %p!!! (eType=%d)\n", (void *)uPtr, eType));
4357 return VERR_INVALID_PARAMETER;
4358}
4359
4360
4361/**
4362 * Opens an image. If it's the first time it's opened the call must upload
4363 * the bits using the supdrvIOCtl_LdrLoad() / SUPDRV_IOCTL_LDR_LOAD function.
4364 *
4365 * This is the 1st step of the loading.
4366 *
4367 * @returns IPRT status code.
4368 * @param pDevExt Device globals.
4369 * @param pSession Session data.
4370 * @param pReq The open request.
4371 */
4372static int supdrvIOCtl_LdrOpen(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDROPEN pReq)
4373{
4374 int rc;
4375 PSUPDRVLDRIMAGE pImage;
4376 void *pv;
4377 size_t cchName = strlen(pReq->u.In.szName); /* (caller checked < 32). */
4378 LogFlow(("supdrvIOCtl_LdrOpen: szName=%s cbImageWithTabs=%d\n", pReq->u.In.szName, pReq->u.In.cbImageWithTabs));
4379
4380 /*
4381 * Check if we got an instance of the image already.
4382 */
4383 supdrvLdrLock(pDevExt);
4384 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
4385 {
4386 if ( pImage->szName[cchName] == '\0'
4387 && !memcmp(pImage->szName, pReq->u.In.szName, cchName))
4388 {
4389 if (RT_LIKELY(pImage->cUsage < UINT32_MAX / 2U))
4390 {
4391 /** @todo check cbImageBits and cbImageWithTabs here, if they differs that indicates that the images are different. */
4392 pImage->cUsage++;
4393 pReq->u.Out.pvImageBase = pImage->pvImage;
4394 pReq->u.Out.fNeedsLoading = pImage->uState == SUP_IOCTL_LDR_OPEN;
4395 pReq->u.Out.fNativeLoader = pImage->fNative;
4396 supdrvLdrAddUsage(pSession, pImage);
4397 supdrvLdrUnlock(pDevExt);
4398 return VINF_SUCCESS;
4399 }
4400 supdrvLdrUnlock(pDevExt);
4401 Log(("supdrvIOCtl_LdrOpen: To many existing references to '%s'!\n", pReq->u.In.szName));
4402 return VERR_INTERNAL_ERROR_3; /** @todo add VERR_TOO_MANY_REFERENCES */
4403 }
4404 }
4405 /* (not found - add it!) */
4406
4407 /* If the loader interface is locked down, make userland fail early */
4408 if (pDevExt->fLdrLockedDown)
4409 {
4410 supdrvLdrUnlock(pDevExt);
4411 Log(("supdrvIOCtl_LdrOpen: Not adding '%s' to image list, loader interface is locked down!\n", pReq->u.In.szName));
4412 return VERR_PERMISSION_DENIED;
4413 }
4414
4415 /*
4416 * Allocate memory.
4417 */
4418 Assert(cchName < sizeof(pImage->szName));
4419 pv = RTMemAlloc(sizeof(SUPDRVLDRIMAGE));
4420 if (!pv)
4421 {
4422 supdrvLdrUnlock(pDevExt);
4423 Log(("supdrvIOCtl_LdrOpen: RTMemAlloc() failed\n"));
4424 return /*VERR_NO_MEMORY*/ VERR_INTERNAL_ERROR_2;
4425 }
4426
4427 /*
4428 * Setup and link in the LDR stuff.
4429 */
4430 pImage = (PSUPDRVLDRIMAGE)pv;
4431 pImage->pvImage = NULL;
4432 pImage->pvImageAlloc = NULL;
4433 pImage->cbImageWithTabs = pReq->u.In.cbImageWithTabs;
4434 pImage->cbImageBits = pReq->u.In.cbImageBits;
4435 pImage->cSymbols = 0;
4436 pImage->paSymbols = NULL;
4437 pImage->pachStrTab = NULL;
4438 pImage->cbStrTab = 0;
4439 pImage->pfnModuleInit = NULL;
4440 pImage->pfnModuleTerm = NULL;
4441 pImage->pfnServiceReqHandler = NULL;
4442 pImage->uState = SUP_IOCTL_LDR_OPEN;
4443 pImage->cUsage = 1;
4444 pImage->pDevExt = pDevExt;
4445 memcpy(pImage->szName, pReq->u.In.szName, cchName + 1);
4446
4447 /*
4448 * Try load it using the native loader, if that isn't supported, fall back
4449 * on the older method.
4450 */
4451 pImage->fNative = true;
4452 rc = supdrvOSLdrOpen(pDevExt, pImage, pReq->u.In.szFilename);
4453 if (rc == VERR_NOT_SUPPORTED)
4454 {
4455 pImage->pvImageAlloc = RTMemExecAlloc(pImage->cbImageBits + 31);
4456 pImage->pvImage = RT_ALIGN_P(pImage->pvImageAlloc, 32);
4457 pImage->fNative = false;
4458 rc = pImage->pvImageAlloc ? VINF_SUCCESS : VERR_NO_EXEC_MEMORY;
4459 }
4460 if (RT_FAILURE(rc))
4461 {
4462 supdrvLdrUnlock(pDevExt);
4463 RTMemFree(pImage);
4464 Log(("supdrvIOCtl_LdrOpen(%s): failed - %Rrc\n", pReq->u.In.szName, rc));
4465 return rc;
4466 }
4467 Assert(VALID_PTR(pImage->pvImage) || RT_FAILURE(rc));
4468
4469 /*
4470 * Link it.
4471 */
4472 pImage->pNext = pDevExt->pLdrImages;
4473 pDevExt->pLdrImages = pImage;
4474
4475 supdrvLdrAddUsage(pSession, pImage);
4476
4477 pReq->u.Out.pvImageBase = pImage->pvImage;
4478 pReq->u.Out.fNeedsLoading = true;
4479 pReq->u.Out.fNativeLoader = pImage->fNative;
4480 supdrvOSLdrNotifyOpened(pDevExt, pImage);
4481
4482 supdrvLdrUnlock(pDevExt);
4483 return VINF_SUCCESS;
4484}
4485
4486
4487/**
4488 * Worker that validates a pointer to an image entrypoint.
4489 *
4490 * @returns IPRT status code.
4491 * @param pDevExt The device globals.
4492 * @param pImage The loader image.
4493 * @param pv The pointer into the image.
4494 * @param fMayBeNull Whether it may be NULL.
4495 * @param pszWhat What is this entrypoint? (for logging)
4496 * @param pbImageBits The image bits prepared by ring-3.
4497 *
4498 * @remarks Will leave the lock on failure.
4499 */
4500static int supdrvLdrValidatePointer(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, void *pv,
4501 bool fMayBeNull, const uint8_t *pbImageBits, const char *pszWhat)
4502{
4503 if (!fMayBeNull || pv)
4504 {
4505 if ((uintptr_t)pv - (uintptr_t)pImage->pvImage >= pImage->cbImageBits)
4506 {
4507 supdrvLdrUnlock(pDevExt);
4508 Log(("Out of range (%p LB %#x): %s=%p\n", pImage->pvImage, pImage->cbImageBits, pszWhat, pv));
4509 return VERR_INVALID_PARAMETER;
4510 }
4511
4512 if (pImage->fNative)
4513 {
4514 int rc = supdrvOSLdrValidatePointer(pDevExt, pImage, pv, pbImageBits);
4515 if (RT_FAILURE(rc))
4516 {
4517 supdrvLdrUnlock(pDevExt);
4518 Log(("Bad entry point address: %s=%p (rc=%Rrc)\n", pszWhat, pv, rc));
4519 return rc;
4520 }
4521 }
4522 }
4523 return VINF_SUCCESS;
4524}
4525
4526
4527/**
4528 * Loads the image bits.
4529 *
4530 * This is the 2nd step of the loading.
4531 *
4532 * @returns IPRT status code.
4533 * @param pDevExt Device globals.
4534 * @param pSession Session data.
4535 * @param pReq The request.
4536 */
4537static int supdrvIOCtl_LdrLoad(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRLOAD pReq)
4538{
4539 PSUPDRVLDRUSAGE pUsage;
4540 PSUPDRVLDRIMAGE pImage;
4541 int rc;
4542 LogFlow(("supdrvIOCtl_LdrLoad: pvImageBase=%p cbImageWithBits=%d\n", pReq->u.In.pvImageBase, pReq->u.In.cbImageWithTabs));
4543
4544 /*
4545 * Find the ldr image.
4546 */
4547 supdrvLdrLock(pDevExt);
4548 pUsage = pSession->pLdrUsage;
4549 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
4550 pUsage = pUsage->pNext;
4551 if (!pUsage)
4552 {
4553 supdrvLdrUnlock(pDevExt);
4554 Log(("SUP_IOCTL_LDR_LOAD: couldn't find image!\n"));
4555 return VERR_INVALID_HANDLE;
4556 }
4557 pImage = pUsage->pImage;
4558
4559 /*
4560 * Validate input.
4561 */
4562 if ( pImage->cbImageWithTabs != pReq->u.In.cbImageWithTabs
4563 || pImage->cbImageBits != pReq->u.In.cbImageBits)
4564 {
4565 supdrvLdrUnlock(pDevExt);
4566 Log(("SUP_IOCTL_LDR_LOAD: image size mismatch!! %d(prep) != %d(load) or %d != %d\n",
4567 pImage->cbImageWithTabs, pReq->u.In.cbImageWithTabs, pImage->cbImageBits, pReq->u.In.cbImageBits));
4568 return VERR_INVALID_HANDLE;
4569 }
4570
4571 if (pImage->uState != SUP_IOCTL_LDR_OPEN)
4572 {
4573 unsigned uState = pImage->uState;
4574 supdrvLdrUnlock(pDevExt);
4575 if (uState != SUP_IOCTL_LDR_LOAD)
4576 AssertMsgFailed(("SUP_IOCTL_LDR_LOAD: invalid image state %d (%#x)!\n", uState, uState));
4577 return VERR_ALREADY_LOADED;
4578 }
4579
4580 /* If the loader interface is locked down, don't load new images */
4581 if (pDevExt->fLdrLockedDown)
4582 {
4583 supdrvLdrUnlock(pDevExt);
4584 Log(("SUP_IOCTL_LDR_LOAD: Not loading '%s' image bits, loader interface is locked down!\n", pImage->szName));
4585 return VERR_PERMISSION_DENIED;
4586 }
4587
4588 switch (pReq->u.In.eEPType)
4589 {
4590 case SUPLDRLOADEP_NOTHING:
4591 break;
4592
4593 case SUPLDRLOADEP_VMMR0:
4594 rc = supdrvLdrValidatePointer( pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0, false, pReq->u.In.abImage, "pvVMMR0");
4595 if (RT_SUCCESS(rc))
4596 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0EntryInt, false, pReq->u.In.abImage, "pvVMMR0EntryInt");
4597 if (RT_SUCCESS(rc))
4598 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0EntryFast, false, pReq->u.In.abImage, "pvVMMR0EntryFast");
4599 if (RT_SUCCESS(rc))
4600 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0EntryEx, false, pReq->u.In.abImage, "pvVMMR0EntryEx");
4601 if (RT_FAILURE(rc))
4602 return rc;
4603 break;
4604
4605 case SUPLDRLOADEP_SERVICE:
4606 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.Service.pfnServiceReq, false, pReq->u.In.abImage, "pfnServiceReq");
4607 if (RT_FAILURE(rc))
4608 return rc;
4609 if ( pReq->u.In.EP.Service.apvReserved[0] != NIL_RTR0PTR
4610 || pReq->u.In.EP.Service.apvReserved[1] != NIL_RTR0PTR
4611 || pReq->u.In.EP.Service.apvReserved[2] != NIL_RTR0PTR)
4612 {
4613 supdrvLdrUnlock(pDevExt);
4614 Log(("Out of range (%p LB %#x): apvReserved={%p,%p,%p} MBZ!\n",
4615 pImage->pvImage, pReq->u.In.cbImageWithTabs,
4616 pReq->u.In.EP.Service.apvReserved[0],
4617 pReq->u.In.EP.Service.apvReserved[1],
4618 pReq->u.In.EP.Service.apvReserved[2]));
4619 return VERR_INVALID_PARAMETER;
4620 }
4621 break;
4622
4623 default:
4624 supdrvLdrUnlock(pDevExt);
4625 Log(("Invalid eEPType=%d\n", pReq->u.In.eEPType));
4626 return VERR_INVALID_PARAMETER;
4627 }
4628
4629 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.pfnModuleInit, true, pReq->u.In.abImage, "pfnModuleInit");
4630 if (RT_FAILURE(rc))
4631 return rc;
4632 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.pfnModuleTerm, true, pReq->u.In.abImage, "pfnModuleTerm");
4633 if (RT_FAILURE(rc))
4634 return rc;
4635
4636 /*
4637 * Allocate and copy the tables.
4638 * (No need to do try/except as this is a buffered request.)
4639 */
4640 pImage->cbStrTab = pReq->u.In.cbStrTab;
4641 if (pImage->cbStrTab)
4642 {
4643 pImage->pachStrTab = (char *)RTMemAlloc(pImage->cbStrTab);
4644 if (pImage->pachStrTab)
4645 memcpy(pImage->pachStrTab, &pReq->u.In.abImage[pReq->u.In.offStrTab], pImage->cbStrTab);
4646 else
4647 rc = /*VERR_NO_MEMORY*/ VERR_INTERNAL_ERROR_3;
4648 }
4649
4650 pImage->cSymbols = pReq->u.In.cSymbols;
4651 if (RT_SUCCESS(rc) && pImage->cSymbols)
4652 {
4653 size_t cbSymbols = pImage->cSymbols * sizeof(SUPLDRSYM);
4654 pImage->paSymbols = (PSUPLDRSYM)RTMemAlloc(cbSymbols);
4655 if (pImage->paSymbols)
4656 memcpy(pImage->paSymbols, &pReq->u.In.abImage[pReq->u.In.offSymbols], cbSymbols);
4657 else
4658 rc = /*VERR_NO_MEMORY*/ VERR_INTERNAL_ERROR_4;
4659 }
4660
4661 /*
4662 * Copy the bits / complete native loading.
4663 */
4664 if (RT_SUCCESS(rc))
4665 {
4666 pImage->uState = SUP_IOCTL_LDR_LOAD;
4667 pImage->pfnModuleInit = (PFNR0MODULEINIT)pReq->u.In.pfnModuleInit;
4668 pImage->pfnModuleTerm = (PFNR0MODULETERM)pReq->u.In.pfnModuleTerm;
4669
4670 if (pImage->fNative)
4671 rc = supdrvOSLdrLoad(pDevExt, pImage, pReq->u.In.abImage, pReq);
4672 else
4673 {
4674 memcpy(pImage->pvImage, &pReq->u.In.abImage[0], pImage->cbImageBits);
4675 Log(("vboxdrv: Loaded '%s' at %p\n", pImage->szName, pImage->pvImage));
4676 }
4677 }
4678
4679 /*
4680 * Update any entry points.
4681 */
4682 if (RT_SUCCESS(rc))
4683 {
4684 switch (pReq->u.In.eEPType)
4685 {
4686 default:
4687 case SUPLDRLOADEP_NOTHING:
4688 rc = VINF_SUCCESS;
4689 break;
4690 case SUPLDRLOADEP_VMMR0:
4691 rc = supdrvLdrSetVMMR0EPs(pDevExt, pReq->u.In.EP.VMMR0.pvVMMR0, pReq->u.In.EP.VMMR0.pvVMMR0EntryInt,
4692 pReq->u.In.EP.VMMR0.pvVMMR0EntryFast, pReq->u.In.EP.VMMR0.pvVMMR0EntryEx);
4693 break;
4694 case SUPLDRLOADEP_SERVICE:
4695 pImage->pfnServiceReqHandler = (PFNSUPR0SERVICEREQHANDLER)pReq->u.In.EP.Service.pfnServiceReq;
4696 rc = VINF_SUCCESS;
4697 break;
4698 }
4699 }
4700
4701 /*
4702 * On success call the module initialization.
4703 */
4704 LogFlow(("supdrvIOCtl_LdrLoad: pfnModuleInit=%p\n", pImage->pfnModuleInit));
4705 if (RT_SUCCESS(rc) && pImage->pfnModuleInit)
4706 {
4707 Log(("supdrvIOCtl_LdrLoad: calling pfnModuleInit=%p\n", pImage->pfnModuleInit));
4708 pDevExt->pLdrInitImage = pImage;
4709 pDevExt->hLdrInitThread = RTThreadNativeSelf();
4710 rc = pImage->pfnModuleInit(pImage);
4711 pDevExt->pLdrInitImage = NULL;
4712 pDevExt->hLdrInitThread = NIL_RTNATIVETHREAD;
4713 if (RT_FAILURE(rc) && pDevExt->pvVMMR0 == pImage->pvImage)
4714 supdrvLdrUnsetVMMR0EPs(pDevExt);
4715 }
4716 SUPR0Printf("vboxdrv: %p %s\n", pImage->pvImage, pImage->szName);
4717
4718 if (RT_FAILURE(rc))
4719 {
4720 /* Inform the tracing component in case ModuleInit registered TPs. */
4721 supdrvTracerModuleUnloading(pDevExt, pImage);
4722
4723 pImage->uState = SUP_IOCTL_LDR_OPEN;
4724 pImage->pfnModuleInit = NULL;
4725 pImage->pfnModuleTerm = NULL;
4726 pImage->pfnServiceReqHandler= NULL;
4727 pImage->cbStrTab = 0;
4728 RTMemFree(pImage->pachStrTab);
4729 pImage->pachStrTab = NULL;
4730 RTMemFree(pImage->paSymbols);
4731 pImage->paSymbols = NULL;
4732 pImage->cSymbols = 0;
4733 }
4734
4735 supdrvLdrUnlock(pDevExt);
4736 return rc;
4737}
4738
4739
4740/**
4741 * Frees a previously loaded (prep'ed) image.
4742 *
4743 * @returns IPRT status code.
4744 * @param pDevExt Device globals.
4745 * @param pSession Session data.
4746 * @param pReq The request.
4747 */
4748static int supdrvIOCtl_LdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRFREE pReq)
4749{
4750 int rc;
4751 PSUPDRVLDRUSAGE pUsagePrev;
4752 PSUPDRVLDRUSAGE pUsage;
4753 PSUPDRVLDRIMAGE pImage;
4754 LogFlow(("supdrvIOCtl_LdrFree: pvImageBase=%p\n", pReq->u.In.pvImageBase));
4755
4756 /*
4757 * Find the ldr image.
4758 */
4759 supdrvLdrLock(pDevExt);
4760 pUsagePrev = NULL;
4761 pUsage = pSession->pLdrUsage;
4762 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
4763 {
4764 pUsagePrev = pUsage;
4765 pUsage = pUsage->pNext;
4766 }
4767 if (!pUsage)
4768 {
4769 supdrvLdrUnlock(pDevExt);
4770 Log(("SUP_IOCTL_LDR_FREE: couldn't find image!\n"));
4771 return VERR_INVALID_HANDLE;
4772 }
4773
4774 /*
4775 * Check if we can remove anything.
4776 */
4777 rc = VINF_SUCCESS;
4778 pImage = pUsage->pImage;
4779 if (pImage->cUsage <= 1 || pUsage->cUsage <= 1)
4780 {
4781 /*
4782 * Check if there are any objects with destructors in the image, if
4783 * so leave it for the session cleanup routine so we get a chance to
4784 * clean things up in the right order and not leave them all dangling.
4785 */
4786 RTSpinlockAcquire(pDevExt->Spinlock);
4787 if (pImage->cUsage <= 1)
4788 {
4789 PSUPDRVOBJ pObj;
4790 for (pObj = pDevExt->pObjs; pObj; pObj = pObj->pNext)
4791 if (RT_UNLIKELY((uintptr_t)pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
4792 {
4793 rc = VERR_DANGLING_OBJECTS;
4794 break;
4795 }
4796 }
4797 else
4798 {
4799 PSUPDRVUSAGE pGenUsage;
4800 for (pGenUsage = pSession->pUsage; pGenUsage; pGenUsage = pGenUsage->pNext)
4801 if (RT_UNLIKELY((uintptr_t)pGenUsage->pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
4802 {
4803 rc = VERR_DANGLING_OBJECTS;
4804 break;
4805 }
4806 }
4807 RTSpinlockRelease(pDevExt->Spinlock);
4808 if (rc == VINF_SUCCESS)
4809 {
4810 /* unlink it */
4811 if (pUsagePrev)
4812 pUsagePrev->pNext = pUsage->pNext;
4813 else
4814 pSession->pLdrUsage = pUsage->pNext;
4815
4816 /* free it */
4817 pUsage->pImage = NULL;
4818 pUsage->pNext = NULL;
4819 RTMemFree(pUsage);
4820
4821 /*
4822 * Dereference the image.
4823 */
4824 if (pImage->cUsage <= 1)
4825 supdrvLdrFree(pDevExt, pImage);
4826 else
4827 pImage->cUsage--;
4828 }
4829 else
4830 {
4831 Log(("supdrvIOCtl_LdrFree: Dangling objects in %p/%s!\n", pImage->pvImage, pImage->szName));
4832 rc = VINF_SUCCESS; /** @todo BRANCH-2.1: remove this after branching. */
4833 }
4834 }
4835 else
4836 {
4837 /*
4838 * Dereference both image and usage.
4839 */
4840 pImage->cUsage--;
4841 pUsage->cUsage--;
4842 }
4843
4844 supdrvLdrUnlock(pDevExt);
4845 return rc;
4846}
4847
4848
4849/**
4850 * Lock down the image loader interface.
4851 *
4852 * @returns IPRT status code.
4853 * @param pDevExt Device globals.
4854 */
4855static int supdrvIOCtl_LdrLockDown(PSUPDRVDEVEXT pDevExt)
4856{
4857 LogFlow(("supdrvIOCtl_LdrLockDown:\n"));
4858
4859 supdrvLdrLock(pDevExt);
4860 if (!pDevExt->fLdrLockedDown)
4861 {
4862 pDevExt->fLdrLockedDown = true;
4863 Log(("supdrvIOCtl_LdrLockDown: Image loader interface locked down\n"));
4864 }
4865 supdrvLdrUnlock(pDevExt);
4866
4867 return VINF_SUCCESS;
4868}
4869
4870
4871/**
4872 * Gets the address of a symbol in an open image.
4873 *
4874 * @returns IPRT status code.
4875 * @param pDevExt Device globals.
4876 * @param pSession Session data.
4877 * @param pReq The request buffer.
4878 */
4879static int supdrvIOCtl_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRGETSYMBOL pReq)
4880{
4881 PSUPDRVLDRIMAGE pImage;
4882 PSUPDRVLDRUSAGE pUsage;
4883 uint32_t i;
4884 PSUPLDRSYM paSyms;
4885 const char *pchStrings;
4886 const size_t cbSymbol = strlen(pReq->u.In.szSymbol) + 1;
4887 void *pvSymbol = NULL;
4888 int rc = VERR_GENERAL_FAILURE;
4889 Log3(("supdrvIOCtl_LdrGetSymbol: pvImageBase=%p szSymbol=\"%s\"\n", pReq->u.In.pvImageBase, pReq->u.In.szSymbol));
4890
4891 /*
4892 * Find the ldr image.
4893 */
4894 supdrvLdrLock(pDevExt);
4895 pUsage = pSession->pLdrUsage;
4896 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
4897 pUsage = pUsage->pNext;
4898 if (!pUsage)
4899 {
4900 supdrvLdrUnlock(pDevExt);
4901 Log(("SUP_IOCTL_LDR_GET_SYMBOL: couldn't find image!\n"));
4902 return VERR_INVALID_HANDLE;
4903 }
4904 pImage = pUsage->pImage;
4905 if (pImage->uState != SUP_IOCTL_LDR_LOAD)
4906 {
4907 unsigned uState = pImage->uState;
4908 supdrvLdrUnlock(pDevExt);
4909 Log(("SUP_IOCTL_LDR_GET_SYMBOL: invalid image state %d (%#x)!\n", uState, uState)); NOREF(uState);
4910 return VERR_ALREADY_LOADED;
4911 }
4912
4913 /*
4914 * Search the symbol strings.
4915 *
4916 * Note! The int32_t is for native loading on solaris where the data
4917 * and text segments are in very different places.
4918 */
4919 pchStrings = pImage->pachStrTab;
4920 paSyms = pImage->paSymbols;
4921 for (i = 0; i < pImage->cSymbols; i++)
4922 {
4923 if ( paSyms[i].offName + cbSymbol <= pImage->cbStrTab
4924 && !memcmp(pchStrings + paSyms[i].offName, pReq->u.In.szSymbol, cbSymbol))
4925 {
4926 pvSymbol = (uint8_t *)pImage->pvImage + (int32_t)paSyms[i].offSymbol;
4927 rc = VINF_SUCCESS;
4928 break;
4929 }
4930 }
4931 supdrvLdrUnlock(pDevExt);
4932 pReq->u.Out.pvSymbol = pvSymbol;
4933 return rc;
4934}
4935
4936
4937/**
4938 * Gets the address of a symbol in an open image or the support driver.
4939 *
4940 * @returns VINF_SUCCESS on success.
4941 * @returns
4942 * @param pDevExt Device globals.
4943 * @param pSession Session data.
4944 * @param pReq The request buffer.
4945 */
4946static int supdrvIDC_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVIDCREQGETSYM pReq)
4947{
4948 int rc = VINF_SUCCESS;
4949 const char *pszSymbol = pReq->u.In.pszSymbol;
4950 const char *pszModule = pReq->u.In.pszModule;
4951 size_t cbSymbol;
4952 char const *pszEnd;
4953 uint32_t i;
4954
4955 /*
4956 * Input validation.
4957 */
4958 AssertPtrReturn(pszSymbol, VERR_INVALID_POINTER);
4959 pszEnd = RTStrEnd(pszSymbol, 512);
4960 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
4961 cbSymbol = pszEnd - pszSymbol + 1;
4962
4963 if (pszModule)
4964 {
4965 AssertPtrReturn(pszModule, VERR_INVALID_POINTER);
4966 pszEnd = RTStrEnd(pszModule, 64);
4967 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
4968 }
4969 Log3(("supdrvIDC_LdrGetSymbol: pszModule=%p:{%s} pszSymbol=%p:{%s}\n", pszModule, pszModule, pszSymbol, pszSymbol));
4970
4971
4972 if ( !pszModule
4973 || !strcmp(pszModule, "SupDrv"))
4974 {
4975 /*
4976 * Search the support driver export table.
4977 */
4978 for (i = 0; i < RT_ELEMENTS(g_aFunctions); i++)
4979 if (!strcmp(g_aFunctions[i].szName, pszSymbol))
4980 {
4981 pReq->u.Out.pfnSymbol = (PFNRT)g_aFunctions[i].pfn;
4982 break;
4983 }
4984 }
4985 else
4986 {
4987 /*
4988 * Find the loader image.
4989 */
4990 PSUPDRVLDRIMAGE pImage;
4991
4992 supdrvLdrLock(pDevExt);
4993
4994 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
4995 if (!strcmp(pImage->szName, pszModule))
4996 break;
4997 if (pImage && pImage->uState == SUP_IOCTL_LDR_LOAD)
4998 {
4999 /*
5000 * Search the symbol strings.
5001 */
5002 const char *pchStrings = pImage->pachStrTab;
5003 PCSUPLDRSYM paSyms = pImage->paSymbols;
5004 for (i = 0; i < pImage->cSymbols; i++)
5005 {
5006 if ( paSyms[i].offName + cbSymbol <= pImage->cbStrTab
5007 && !memcmp(pchStrings + paSyms[i].offName, pszSymbol, cbSymbol))
5008 {
5009 /*
5010 * Found it! Calc the symbol address and add a reference to the module.
5011 */
5012 pReq->u.Out.pfnSymbol = (PFNRT)((uint8_t *)pImage->pvImage + (int32_t)paSyms[i].offSymbol);
5013 rc = supdrvLdrAddUsage(pSession, pImage);
5014 break;
5015 }
5016 }
5017 }
5018 else
5019 rc = pImage ? VERR_WRONG_ORDER : VERR_MODULE_NOT_FOUND;
5020
5021 supdrvLdrUnlock(pDevExt);
5022 }
5023 return rc;
5024}
5025
5026
5027/**
5028 * Updates the VMMR0 entry point pointers.
5029 *
5030 * @returns IPRT status code.
5031 * @param pDevExt Device globals.
5032 * @param pSession Session data.
5033 * @param pVMMR0 VMMR0 image handle.
5034 * @param pvVMMR0EntryInt VMMR0EntryInt address.
5035 * @param pvVMMR0EntryFast VMMR0EntryFast address.
5036 * @param pvVMMR0EntryEx VMMR0EntryEx address.
5037 * @remark Caller must own the loader mutex.
5038 */
5039static int supdrvLdrSetVMMR0EPs(PSUPDRVDEVEXT pDevExt, void *pvVMMR0, void *pvVMMR0EntryInt, void *pvVMMR0EntryFast, void *pvVMMR0EntryEx)
5040{
5041 int rc = VINF_SUCCESS;
5042 LogFlow(("supdrvLdrSetR0EP pvVMMR0=%p pvVMMR0EntryInt=%p\n", pvVMMR0, pvVMMR0EntryInt));
5043
5044
5045 /*
5046 * Check if not yet set.
5047 */
5048 if (!pDevExt->pvVMMR0)
5049 {
5050 pDevExt->pvVMMR0 = pvVMMR0;
5051 *(void **)&pDevExt->pfnVMMR0EntryInt = pvVMMR0EntryInt;
5052 *(void **)&pDevExt->pfnVMMR0EntryFast = pvVMMR0EntryFast;
5053 *(void **)&pDevExt->pfnVMMR0EntryEx = pvVMMR0EntryEx;
5054 ASMCompilerBarrier(); /* the above isn't nice, so be careful... */
5055 }
5056 else
5057 {
5058 /*
5059 * Return failure or success depending on whether the values match or not.
5060 */
5061 if ( pDevExt->pvVMMR0 != pvVMMR0
5062 || (void *)pDevExt->pfnVMMR0EntryInt != pvVMMR0EntryInt
5063 || (void *)pDevExt->pfnVMMR0EntryFast != pvVMMR0EntryFast
5064 || (void *)pDevExt->pfnVMMR0EntryEx != pvVMMR0EntryEx)
5065 {
5066 AssertMsgFailed(("SUP_IOCTL_LDR_SETR0EP: Already set pointing to a different module!\n"));
5067 rc = VERR_INVALID_PARAMETER;
5068 }
5069 }
5070 return rc;
5071}
5072
5073
5074/**
5075 * Unsets the VMMR0 entry point installed by supdrvLdrSetR0EP.
5076 *
5077 * @param pDevExt Device globals.
5078 */
5079static void supdrvLdrUnsetVMMR0EPs(PSUPDRVDEVEXT pDevExt)
5080{
5081 pDevExt->pvVMMR0 = NULL;
5082 pDevExt->pfnVMMR0EntryInt = NULL;
5083 pDevExt->pfnVMMR0EntryFast = NULL;
5084 pDevExt->pfnVMMR0EntryEx = NULL;
5085}
5086
5087
5088/**
5089 * Adds a usage reference in the specified session of an image.
5090 *
5091 * Called while owning the loader semaphore.
5092 *
5093 * @returns VINF_SUCCESS on success and VERR_NO_MEMORY on failure.
5094 * @param pSession Session in question.
5095 * @param pImage Image which the session is using.
5096 */
5097static int supdrvLdrAddUsage(PSUPDRVSESSION pSession, PSUPDRVLDRIMAGE pImage)
5098{
5099 PSUPDRVLDRUSAGE pUsage;
5100 LogFlow(("supdrvLdrAddUsage: pImage=%p\n", pImage));
5101
5102 /*
5103 * Referenced it already?
5104 */
5105 pUsage = pSession->pLdrUsage;
5106 while (pUsage)
5107 {
5108 if (pUsage->pImage == pImage)
5109 {
5110 pUsage->cUsage++;
5111 return VINF_SUCCESS;
5112 }
5113 pUsage = pUsage->pNext;
5114 }
5115
5116 /*
5117 * Allocate new usage record.
5118 */
5119 pUsage = (PSUPDRVLDRUSAGE)RTMemAlloc(sizeof(*pUsage));
5120 AssertReturn(pUsage, /*VERR_NO_MEMORY*/ VERR_INTERNAL_ERROR_5);
5121 pUsage->cUsage = 1;
5122 pUsage->pImage = pImage;
5123 pUsage->pNext = pSession->pLdrUsage;
5124 pSession->pLdrUsage = pUsage;
5125 return VINF_SUCCESS;
5126}
5127
5128
5129/**
5130 * Frees a load image.
5131 *
5132 * @param pDevExt Pointer to device extension.
5133 * @param pImage Pointer to the image we're gonna free.
5134 * This image must exit!
5135 * @remark The caller MUST own SUPDRVDEVEXT::mtxLdr!
5136 */
5137static void supdrvLdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage)
5138{
5139 PSUPDRVLDRIMAGE pImagePrev;
5140 LogFlow(("supdrvLdrFree: pImage=%p\n", pImage));
5141
5142 /*
5143 * Warn if we're releasing images while the image loader interface is
5144 * locked down -- we won't be able to reload them!
5145 */
5146 if (pDevExt->fLdrLockedDown)
5147 Log(("supdrvLdrFree: Warning: unloading '%s' image, while loader interface is locked down!\n", pImage->szName));
5148
5149 /* find it - arg. should've used doubly linked list. */
5150 Assert(pDevExt->pLdrImages);
5151 pImagePrev = NULL;
5152 if (pDevExt->pLdrImages != pImage)
5153 {
5154 pImagePrev = pDevExt->pLdrImages;
5155 while (pImagePrev->pNext != pImage)
5156 pImagePrev = pImagePrev->pNext;
5157 Assert(pImagePrev->pNext == pImage);
5158 }
5159
5160 /* unlink */
5161 if (pImagePrev)
5162 pImagePrev->pNext = pImage->pNext;
5163 else
5164 pDevExt->pLdrImages = pImage->pNext;
5165
5166 /* check if this is VMMR0.r0 unset its entry point pointers. */
5167 if (pDevExt->pvVMMR0 == pImage->pvImage)
5168 supdrvLdrUnsetVMMR0EPs(pDevExt);
5169
5170 /* check for objects with destructors in this image. (Shouldn't happen.) */
5171 if (pDevExt->pObjs)
5172 {
5173 unsigned cObjs = 0;
5174 PSUPDRVOBJ pObj;
5175 RTSpinlockAcquire(pDevExt->Spinlock);
5176 for (pObj = pDevExt->pObjs; pObj; pObj = pObj->pNext)
5177 if (RT_UNLIKELY((uintptr_t)pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
5178 {
5179 pObj->pfnDestructor = NULL;
5180 cObjs++;
5181 }
5182 RTSpinlockRelease(pDevExt->Spinlock);
5183 if (cObjs)
5184 OSDBGPRINT(("supdrvLdrFree: Image '%s' has %d dangling objects!\n", pImage->szName, cObjs));
5185 }
5186
5187 /* call termination function if fully loaded. */
5188 if ( pImage->pfnModuleTerm
5189 && pImage->uState == SUP_IOCTL_LDR_LOAD)
5190 {
5191 LogFlow(("supdrvIOCtl_LdrLoad: calling pfnModuleTerm=%p\n", pImage->pfnModuleTerm));
5192 pImage->pfnModuleTerm(pImage);
5193 }
5194
5195 /* Inform the tracing component. */
5196 supdrvTracerModuleUnloading(pDevExt, pImage);
5197
5198 /* do native unload if appropriate. */
5199 if (pImage->fNative)
5200 supdrvOSLdrUnload(pDevExt, pImage);
5201
5202 /* free the image */
5203 pImage->cUsage = 0;
5204 pImage->pDevExt = NULL;
5205 pImage->pNext = NULL;
5206 pImage->uState = SUP_IOCTL_LDR_FREE;
5207 RTMemExecFree(pImage->pvImageAlloc, pImage->cbImageBits + 31);
5208 pImage->pvImageAlloc = NULL;
5209 RTMemFree(pImage->pachStrTab);
5210 pImage->pachStrTab = NULL;
5211 RTMemFree(pImage->paSymbols);
5212 pImage->paSymbols = NULL;
5213 RTMemFree(pImage);
5214}
5215
5216
5217/**
5218 * Acquires the loader lock.
5219 *
5220 * @returns IPRT status code.
5221 * @param pDevExt The device extension.
5222 */
5223DECLINLINE(int) supdrvLdrLock(PSUPDRVDEVEXT pDevExt)
5224{
5225#ifdef SUPDRV_USE_MUTEX_FOR_LDR
5226 int rc = RTSemMutexRequest(pDevExt->mtxLdr, RT_INDEFINITE_WAIT);
5227#else
5228 int rc = RTSemFastMutexRequest(pDevExt->mtxLdr);
5229#endif
5230 AssertRC(rc);
5231 return rc;
5232}
5233
5234
5235/**
5236 * Releases the loader lock.
5237 *
5238 * @returns IPRT status code.
5239 * @param pDevExt The device extension.
5240 */
5241DECLINLINE(int) supdrvLdrUnlock(PSUPDRVDEVEXT pDevExt)
5242{
5243#ifdef SUPDRV_USE_MUTEX_FOR_LDR
5244 return RTSemMutexRelease(pDevExt->mtxLdr);
5245#else
5246 return RTSemFastMutexRelease(pDevExt->mtxLdr);
5247#endif
5248}
5249
5250
5251/**
5252 * Implements the service call request.
5253 *
5254 * @returns VBox status code.
5255 * @param pDevExt The device extension.
5256 * @param pSession The calling session.
5257 * @param pReq The request packet, valid.
5258 */
5259static int supdrvIOCtl_CallServiceModule(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPCALLSERVICE pReq)
5260{
5261#if !defined(RT_OS_WINDOWS) || defined(RT_ARCH_AMD64) || defined(DEBUG)
5262 int rc;
5263
5264 /*
5265 * Find the module first in the module referenced by the calling session.
5266 */
5267 rc = supdrvLdrLock(pDevExt);
5268 if (RT_SUCCESS(rc))
5269 {
5270 PFNSUPR0SERVICEREQHANDLER pfnServiceReqHandler = NULL;
5271 PSUPDRVLDRUSAGE pUsage;
5272
5273 for (pUsage = pSession->pLdrUsage; pUsage; pUsage = pUsage->pNext)
5274 if ( pUsage->pImage->pfnServiceReqHandler
5275 && !strcmp(pUsage->pImage->szName, pReq->u.In.szName))
5276 {
5277 pfnServiceReqHandler = pUsage->pImage->pfnServiceReqHandler;
5278 break;
5279 }
5280 supdrvLdrUnlock(pDevExt);
5281
5282 if (pfnServiceReqHandler)
5283 {
5284 /*
5285 * Call it.
5286 */
5287 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_SERVICE_SIZE(0))
5288 rc = pfnServiceReqHandler(pSession, pReq->u.In.uOperation, pReq->u.In.u64Arg, NULL);
5289 else
5290 rc = pfnServiceReqHandler(pSession, pReq->u.In.uOperation, pReq->u.In.u64Arg, (PSUPR0SERVICEREQHDR)&pReq->abReqPkt[0]);
5291 }
5292 else
5293 rc = VERR_SUPDRV_SERVICE_NOT_FOUND;
5294 }
5295
5296 /* log it */
5297 if ( RT_FAILURE(rc)
5298 && rc != VERR_INTERRUPTED
5299 && rc != VERR_TIMEOUT)
5300 Log(("SUP_IOCTL_CALL_SERVICE: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
5301 rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
5302 else
5303 Log4(("SUP_IOCTL_CALL_SERVICE: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
5304 rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
5305 return rc;
5306#else /* RT_OS_WINDOWS && !RT_ARCH_AMD64 && !DEBUG */
5307 return VERR_NOT_IMPLEMENTED;
5308#endif /* RT_OS_WINDOWS && !RT_ARCH_AMD64 && !DEBUG */
5309}
5310
5311
5312/**
5313 * Implements the logger settings request.
5314 *
5315 * @returns VBox status code.
5316 * @param pDevExt The device extension.
5317 * @param pSession The caller's session.
5318 * @param pReq The request.
5319 */
5320static int supdrvIOCtl_LoggerSettings(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLOGGERSETTINGS pReq)
5321{
5322 const char *pszGroup = &pReq->u.In.szStrings[pReq->u.In.offGroups];
5323 const char *pszFlags = &pReq->u.In.szStrings[pReq->u.In.offFlags];
5324 const char *pszDest = &pReq->u.In.szStrings[pReq->u.In.offDestination];
5325 PRTLOGGER pLogger = NULL;
5326 int rc;
5327
5328 /*
5329 * Some further validation.
5330 */
5331 switch (pReq->u.In.fWhat)
5332 {
5333 case SUPLOGGERSETTINGS_WHAT_SETTINGS:
5334 case SUPLOGGERSETTINGS_WHAT_CREATE:
5335 break;
5336
5337 case SUPLOGGERSETTINGS_WHAT_DESTROY:
5338 if (*pszGroup || *pszFlags || *pszDest)
5339 return VERR_INVALID_PARAMETER;
5340 if (pReq->u.In.fWhich == SUPLOGGERSETTINGS_WHICH_RELEASE)
5341 return VERR_ACCESS_DENIED;
5342 break;
5343
5344 default:
5345 return VERR_INTERNAL_ERROR;
5346 }
5347
5348 /*
5349 * Get the logger.
5350 */
5351 switch (pReq->u.In.fWhich)
5352 {
5353 case SUPLOGGERSETTINGS_WHICH_DEBUG:
5354 pLogger = RTLogGetDefaultInstance();
5355 break;
5356
5357 case SUPLOGGERSETTINGS_WHICH_RELEASE:
5358 pLogger = RTLogRelGetDefaultInstance();
5359 break;
5360
5361 default:
5362 return VERR_INTERNAL_ERROR;
5363 }
5364
5365 /*
5366 * Do the job.
5367 */
5368 switch (pReq->u.In.fWhat)
5369 {
5370 case SUPLOGGERSETTINGS_WHAT_SETTINGS:
5371 if (pLogger)
5372 {
5373 rc = RTLogFlags(pLogger, pszFlags);
5374 if (RT_SUCCESS(rc))
5375 rc = RTLogGroupSettings(pLogger, pszGroup);
5376 NOREF(pszDest);
5377 }
5378 else
5379 rc = VERR_NOT_FOUND;
5380 break;
5381
5382 case SUPLOGGERSETTINGS_WHAT_CREATE:
5383 {
5384 if (pLogger)
5385 rc = VERR_ALREADY_EXISTS;
5386 else
5387 {
5388 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
5389
5390 rc = RTLogCreate(&pLogger,
5391 0 /* fFlags */,
5392 pszGroup,
5393 pReq->u.In.fWhich == SUPLOGGERSETTINGS_WHICH_DEBUG
5394 ? "VBOX_LOG"
5395 : "VBOX_RELEASE_LOG",
5396 RT_ELEMENTS(s_apszGroups),
5397 s_apszGroups,
5398 RTLOGDEST_STDOUT | RTLOGDEST_DEBUGGER,
5399 NULL);
5400 if (RT_SUCCESS(rc))
5401 {
5402 rc = RTLogFlags(pLogger, pszFlags);
5403 NOREF(pszDest);
5404 if (RT_SUCCESS(rc))
5405 {
5406 switch (pReq->u.In.fWhich)
5407 {
5408 case SUPLOGGERSETTINGS_WHICH_DEBUG:
5409 pLogger = RTLogSetDefaultInstance(pLogger);
5410 break;
5411 case SUPLOGGERSETTINGS_WHICH_RELEASE:
5412 pLogger = RTLogRelSetDefaultInstance(pLogger);
5413 break;
5414 }
5415 }
5416 RTLogDestroy(pLogger);
5417 }
5418 }
5419 break;
5420 }
5421
5422 case SUPLOGGERSETTINGS_WHAT_DESTROY:
5423 switch (pReq->u.In.fWhich)
5424 {
5425 case SUPLOGGERSETTINGS_WHICH_DEBUG:
5426 pLogger = RTLogSetDefaultInstance(NULL);
5427 break;
5428 case SUPLOGGERSETTINGS_WHICH_RELEASE:
5429 pLogger = RTLogRelSetDefaultInstance(NULL);
5430 break;
5431 }
5432 rc = RTLogDestroy(pLogger);
5433 break;
5434
5435 default:
5436 {
5437 rc = VERR_INTERNAL_ERROR;
5438 break;
5439 }
5440 }
5441
5442 return rc;
5443}
5444
5445
5446/**
5447 * Implements the MSR prober operations.
5448 *
5449 * @returns VBox status code.
5450 * @param pDevExt The device extension.
5451 * @param pReq The request.
5452 */
5453static int supdrvIOCtl_MsrProber(PSUPDRVDEVEXT pDevExt, PSUPMSRPROBER pReq)
5454{
5455#ifdef SUPDRV_WITH_MSR_PROBER
5456 RTCPUID const idCpu = pReq->u.In.idCpu == UINT32_MAX ? NIL_RTCPUID : pReq->u.In.idCpu;
5457 int rc;
5458
5459 switch (pReq->u.In.enmOp)
5460 {
5461 case SUPMSRPROBEROP_READ:
5462 {
5463 uint64_t uValue;
5464 rc = supdrvOSMsrProberRead(pReq->u.In.uMsr, idCpu, &uValue);
5465 if (RT_SUCCESS(rc))
5466 {
5467 pReq->u.Out.uResults.Read.uValue = uValue;
5468 pReq->u.Out.uResults.Read.fGp = false;
5469 }
5470 else if (rc == VERR_ACCESS_DENIED)
5471 {
5472 pReq->u.Out.uResults.Read.uValue = 0;
5473 pReq->u.Out.uResults.Read.fGp = true;
5474 rc = VINF_SUCCESS;
5475 }
5476 break;
5477 }
5478
5479 case SUPMSRPROBEROP_WRITE:
5480 rc = supdrvOSMsrProberWrite(pReq->u.In.uMsr, idCpu, pReq->u.In.uArgs.Write.uToWrite);
5481 if (RT_SUCCESS(rc))
5482 pReq->u.Out.uResults.Write.fGp = false;
5483 else if (rc == VERR_ACCESS_DENIED)
5484 {
5485 pReq->u.Out.uResults.Write.fGp = true;
5486 rc = VINF_SUCCESS;
5487 }
5488 break;
5489
5490 case SUPMSRPROBEROP_MODIFY:
5491 case SUPMSRPROBEROP_MODIFY_FASTER:
5492 rc = supdrvOSMsrProberModify(idCpu, pReq);
5493 break;
5494
5495 default:
5496 return VERR_INVALID_FUNCTION;
5497 }
5498 return rc;
5499#else
5500 return VERR_NOT_IMPLEMENTED;
5501#endif
5502}
5503
5504
5505/**
5506 * Resume built-in keyboard on MacBook Air and Pro hosts.
5507 * If there is no built-in keyboard device, return success anyway.
5508 *
5509 * @returns 0 on Mac OS X platform, VERR_NOT_IMPLEMENTED on the other ones.
5510 */
5511static int supdrvIOCtl_ResumeSuspendedKbds(void)
5512{
5513#if defined(RT_OS_DARWIN)
5514 return supdrvDarwinResumeSuspendedKbds();
5515#else
5516 return VERR_NOT_IMPLEMENTED;
5517#endif
5518}
5519
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