VirtualBox

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

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

Linux: Host Drivers: SUPDrv: make sure that module builds if CONFIG_FORTIFY_SOURCE not enabled, ​​bugref:10209.

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