VirtualBox

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

Last change on this file since 90774 was 90489, checked in by vboxsync, 4 years ago

SUP: Export RTSemEventIsSignalSafe and RTSemEventMultiIsSignalSafe - IOC version change. bugref:6695

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

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