VirtualBox

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

Last change on this file since 96166 was 95087, checked in by vboxsync, 3 years ago

SUPDrv: bugref:10209: Added stubs for host FPU begin/end operations.

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