VirtualBox

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

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

SUPDrv: We should no longer need the exec flag on this type of memory allocation.

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

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