VirtualBox

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

Last change on this file since 55782 was 55436, checked in by vboxsync, 10 years ago

Reverted bad commit r99781.

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