VirtualBox

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

Last change on this file since 91684 was 91674, checked in by vboxsync, 3 years ago

SUPDrv: Export RTR0MemObjLockKernelTag too. Minor version bump, require this. bugref:10118

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