VirtualBox

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

Last change on this file since 81304 was 81304, checked in by vboxsync, 6 years ago

SUPDrv: Added reporting of VT-x's VMCS shadowing CPU feature as part of SUPR0QueryVTCaps.

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

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