VirtualBox

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

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

VMMR0,SUPDrv: Need to override RTLogDefaultInstanceEx rather than RTLogGetDefaultInstanceEx for debug logging. bugref:10086

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

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