VirtualBox

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

Last change on this file since 55998 was 55988, checked in by vboxsync, 10 years ago

iprt/log.h,SUPDrv: Replaced the 'personal' logging groups with 6 more generic logging levels (7 thru 12) and a 'Warn' level. The 'Warn' level is enabled by 'group.e' together with level 1 logging. Modified the new RTLog[Rel][Get]DefaultInstanceEx functions to only take one 32-bit parameter to minimize call setup time and size. Major support driver version bump. LogAleksey=Log7, LogBird=Log8, LogSunlover=Log9, none of the other personal macros was used. Log*Warning got renamed to Log1*Warning so as to not confuse it with the LogWarn/LogRelWarn macros.

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