VirtualBox

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

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

SUPDrv,VMM/NEM/win: Abstracted kernel I/O control work in SUPDrv, currently only implemented & needed on windows. Made first I/O control call to VID from ring-0. bugref:9044

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

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