VirtualBox

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

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

SUPDrv: Todo.

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

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