VirtualBox

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

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

SUPDrv: Made SUPR0PageAllocEx more palatable for HVCI. bugref:10162

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