VirtualBox

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

Last change on this file since 67954 was 67823, checked in by vboxsync, 7 years ago

Another typo.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use