VirtualBox

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

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

SUP: Make sure SUPR3PageAllocEx returns zero'ed memory. bugref:10094

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 266.0 KB
Line 
1/* $Id: SUPDrv.cpp 93616 2022-02-06 08:03:47Z vboxsync $ */
2/** @file
3 * VBoxDrv - The VirtualBox Support Driver - Common code.
4 */
5
6/*
7 * Copyright (C) 2006-2022 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#define LOG_GROUP LOG_GROUP_SUP_DRV
32#define SUPDRV_AGNOSTIC
33#include "SUPDrvInternal.h"
34#ifndef PAGE_SHIFT
35# include <iprt/param.h>
36#endif
37#include <iprt/asm.h>
38#include <iprt/asm-amd64-x86.h>
39#include <iprt/asm-math.h>
40#include <iprt/cpuset.h>
41#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_WINDOWS)
42# include <iprt/dbg.h>
43#endif
44#include <iprt/handletable.h>
45#include <iprt/mem.h>
46#include <iprt/mp.h>
47#include <iprt/power.h>
48#include <iprt/process.h>
49#include <iprt/semaphore.h>
50#include <iprt/spinlock.h>
51#include <iprt/thread.h>
52#include <iprt/uuid.h>
53#include <iprt/net.h>
54#include <iprt/crc.h>
55#include <iprt/string.h>
56#include <iprt/timer.h>
57#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
58# include <iprt/rand.h>
59# include <iprt/path.h>
60#endif
61#include <iprt/uint128.h>
62#include <iprt/x86.h>
63
64#include <VBox/param.h>
65#include <VBox/log.h>
66#include <VBox/err.h>
67#include <VBox/vmm/hm_vmx.h>
68
69#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
70# include "dtrace/SUPDrv.h"
71#else
72# define VBOXDRV_SESSION_CREATE(pvSession, fUser) do { } while (0)
73# define VBOXDRV_SESSION_CLOSE(pvSession) do { } while (0)
74# define VBOXDRV_IOCTL_ENTRY(pvSession, uIOCtl, pvReqHdr) do { } while (0)
75# define VBOXDRV_IOCTL_RETURN(pvSession, uIOCtl, pvReqHdr, rcRet, rcReq) do { } while (0)
76#endif
77
78#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 = NULL;
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 {
3814 /* Make sure memory mapped into ring-3 is zero initialized if we can: */
3815 if ( ppvR0
3816 && !RTR0MemObjWasZeroInitialized(Mem.MemObj))
3817 {
3818 void *pv = RTR0MemObjAddress(Mem.MemObj);
3819 Assert(pv || !ppvR0);
3820 if (pv)
3821 RT_BZERO(pv, (size_t)cPages * PAGE_SIZE);
3822 }
3823
3824 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0, RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3825 }
3826 else
3827 Mem.MapObjR3 = NIL_RTR0MEMOBJ;
3828 if (RT_SUCCESS(rc))
3829 {
3830 Mem.eType = MEMREF_TYPE_PAGE;
3831 rc = supdrvMemAdd(&Mem, pSession);
3832 if (!rc)
3833 {
3834 if (ppvR3)
3835 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3836 if (ppvR0)
3837 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3838 if (paPages)
3839 {
3840 uint32_t iPage = cPages;
3841 while (iPage-- > 0)
3842 {
3843 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MapObjR3, iPage);
3844 Assert(paPages[iPage] != NIL_RTHCPHYS);
3845 }
3846 }
3847 return VINF_SUCCESS;
3848 }
3849
3850 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3851 AssertRC(rc2);
3852 }
3853
3854 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3855 AssertRC(rc2);
3856 }
3857 return rc;
3858}
3859SUPR0_EXPORT_SYMBOL(SUPR0PageAllocEx);
3860
3861
3862/**
3863 * Maps a chunk of memory previously allocated by SUPR0PageAllocEx into kernel
3864 * space.
3865 *
3866 * @returns IPRT status code.
3867 * @param pSession The session to associated the allocation with.
3868 * @param pvR3 The ring-3 address returned by SUPR0PageAllocEx.
3869 * @param offSub Where to start mapping. Must be page aligned.
3870 * @param cbSub How much to map. Must be page aligned.
3871 * @param fFlags Flags, MBZ.
3872 * @param ppvR0 Where to return the address of the ring-0 mapping on
3873 * success.
3874 */
3875SUPR0DECL(int) SUPR0PageMapKernel(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t offSub, uint32_t cbSub,
3876 uint32_t fFlags, PRTR0PTR ppvR0)
3877{
3878 int rc;
3879 PSUPDRVBUNDLE pBundle;
3880 RTR0MEMOBJ hMemObj = NIL_RTR0MEMOBJ;
3881 LogFlow(("SUPR0PageMapKernel: pSession=%p pvR3=%p offSub=%#x cbSub=%#x\n", pSession, pvR3, offSub, cbSub));
3882
3883 /*
3884 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
3885 */
3886 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3887 AssertPtrNullReturn(ppvR0, VERR_INVALID_POINTER);
3888 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
3889 AssertReturn(!(offSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3890 AssertReturn(!(cbSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3891 AssertReturn(cbSub, VERR_INVALID_PARAMETER);
3892
3893 /*
3894 * Find the memory object.
3895 */
3896 RTSpinlockAcquire(pSession->Spinlock);
3897 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3898 {
3899 if (pBundle->cUsed > 0)
3900 {
3901 unsigned i;
3902 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
3903 {
3904 if ( ( pBundle->aMem[i].eType == MEMREF_TYPE_PAGE
3905 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3906 && pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
3907 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3)
3908 || ( pBundle->aMem[i].eType == MEMREF_TYPE_LOCKED
3909 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3910 && pBundle->aMem[i].MapObjR3 == NIL_RTR0MEMOBJ
3911 && RTR0MemObjAddressR3(pBundle->aMem[i].MemObj) == pvR3))
3912 {
3913 hMemObj = pBundle->aMem[i].MemObj;
3914 break;
3915 }
3916 }
3917 }
3918 }
3919 RTSpinlockRelease(pSession->Spinlock);
3920
3921 rc = VERR_INVALID_PARAMETER;
3922 if (hMemObj != NIL_RTR0MEMOBJ)
3923 {
3924 /*
3925 * Do some further input validations before calling IPRT.
3926 * (Cleanup is done indirectly by telling RTR0MemObjFree to include mappings.)
3927 */
3928 size_t cbMemObj = RTR0MemObjSize(hMemObj);
3929 if ( offSub < cbMemObj
3930 && cbSub <= cbMemObj
3931 && offSub + cbSub <= cbMemObj)
3932 {
3933 RTR0MEMOBJ hMapObj;
3934 rc = RTR0MemObjMapKernelEx(&hMapObj, hMemObj, (void *)-1, 0,
3935 RTMEM_PROT_READ | RTMEM_PROT_WRITE, offSub, cbSub);
3936 if (RT_SUCCESS(rc))
3937 *ppvR0 = RTR0MemObjAddress(hMapObj);
3938 }
3939 else
3940 SUPR0Printf("SUPR0PageMapKernel: cbMemObj=%#x offSub=%#x cbSub=%#x\n", cbMemObj, offSub, cbSub);
3941
3942 }
3943 return rc;
3944}
3945SUPR0_EXPORT_SYMBOL(SUPR0PageMapKernel);
3946
3947
3948/**
3949 * Changes the page level protection of one or more pages previously allocated
3950 * by SUPR0PageAllocEx.
3951 *
3952 * @returns IPRT status code.
3953 * @param pSession The session to associated the allocation with.
3954 * @param pvR3 The ring-3 address returned by SUPR0PageAllocEx.
3955 * NIL_RTR3PTR if the ring-3 mapping should be unaffected.
3956 * @param pvR0 The ring-0 address returned by SUPR0PageAllocEx.
3957 * NIL_RTR0PTR if the ring-0 mapping should be unaffected.
3958 * @param offSub Where to start changing. Must be page aligned.
3959 * @param cbSub How much to change. Must be page aligned.
3960 * @param fProt The new page level protection, see RTMEM_PROT_*.
3961 */
3962SUPR0DECL(int) SUPR0PageProtect(PSUPDRVSESSION pSession, RTR3PTR pvR3, RTR0PTR pvR0, uint32_t offSub, uint32_t cbSub, uint32_t fProt)
3963{
3964 int rc;
3965 PSUPDRVBUNDLE pBundle;
3966 RTR0MEMOBJ hMemObjR0 = NIL_RTR0MEMOBJ;
3967 RTR0MEMOBJ hMemObjR3 = NIL_RTR0MEMOBJ;
3968 LogFlow(("SUPR0PageProtect: pSession=%p pvR3=%p pvR0=%p offSub=%#x cbSub=%#x fProt-%#x\n", pSession, pvR3, pvR0, offSub, cbSub, fProt));
3969
3970 /*
3971 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
3972 */
3973 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3974 AssertReturn(!(fProt & ~(RTMEM_PROT_READ | RTMEM_PROT_WRITE | RTMEM_PROT_EXEC | RTMEM_PROT_NONE)), VERR_INVALID_PARAMETER);
3975 AssertReturn(!(offSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3976 AssertReturn(!(cbSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3977 AssertReturn(cbSub, VERR_INVALID_PARAMETER);
3978
3979 /*
3980 * Find the memory object.
3981 */
3982 RTSpinlockAcquire(pSession->Spinlock);
3983 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3984 {
3985 if (pBundle->cUsed > 0)
3986 {
3987 unsigned i;
3988 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
3989 {
3990 if ( pBundle->aMem[i].eType == MEMREF_TYPE_PAGE
3991 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3992 && ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
3993 || pvR3 == NIL_RTR3PTR)
3994 && ( pvR0 == NIL_RTR0PTR
3995 || RTR0MemObjAddress(pBundle->aMem[i].MemObj) == pvR0)
3996 && ( pvR3 == NIL_RTR3PTR
3997 || RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3))
3998 {
3999 if (pvR0 != NIL_RTR0PTR)
4000 hMemObjR0 = pBundle->aMem[i].MemObj;
4001 if (pvR3 != NIL_RTR3PTR)
4002 hMemObjR3 = pBundle->aMem[i].MapObjR3;
4003 break;
4004 }
4005 }
4006 }
4007 }
4008 RTSpinlockRelease(pSession->Spinlock);
4009
4010 rc = VERR_INVALID_PARAMETER;
4011 if ( hMemObjR0 != NIL_RTR0MEMOBJ
4012 || hMemObjR3 != NIL_RTR0MEMOBJ)
4013 {
4014 /*
4015 * Do some further input validations before calling IPRT.
4016 */
4017 size_t cbMemObj = hMemObjR0 != NIL_RTR0PTR ? RTR0MemObjSize(hMemObjR0) : RTR0MemObjSize(hMemObjR3);
4018 if ( offSub < cbMemObj
4019 && cbSub <= cbMemObj
4020 && offSub + cbSub <= cbMemObj)
4021 {
4022 rc = VINF_SUCCESS;
4023 if (hMemObjR3 != NIL_RTR0PTR)
4024 rc = RTR0MemObjProtect(hMemObjR3, offSub, cbSub, fProt);
4025 if (hMemObjR0 != NIL_RTR0PTR && RT_SUCCESS(rc))
4026 rc = RTR0MemObjProtect(hMemObjR0, offSub, cbSub, fProt);
4027 }
4028 else
4029 SUPR0Printf("SUPR0PageMapKernel: cbMemObj=%#x offSub=%#x cbSub=%#x\n", cbMemObj, offSub, cbSub);
4030
4031 }
4032 return rc;
4033
4034}
4035SUPR0_EXPORT_SYMBOL(SUPR0PageProtect);
4036
4037
4038/**
4039 * Free memory allocated by SUPR0PageAlloc() and SUPR0PageAllocEx().
4040 *
4041 * @returns IPRT status code.
4042 * @param pSession The session owning the allocation.
4043 * @param pvR3 The Ring-3 address returned by SUPR0PageAlloc() or
4044 * SUPR0PageAllocEx().
4045 */
4046SUPR0DECL(int) SUPR0PageFree(PSUPDRVSESSION pSession, RTR3PTR pvR3)
4047{
4048 LogFlow(("SUPR0PageFree: pSession=%p pvR3=%p\n", pSession, (void *)pvR3));
4049 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4050 return supdrvMemRelease(pSession, (RTHCUINTPTR)pvR3, MEMREF_TYPE_PAGE);
4051}
4052SUPR0_EXPORT_SYMBOL(SUPR0PageFree);
4053
4054
4055/**
4056 * Reports a bad context, currenctly that means EFLAGS.AC is 0 instead of 1.
4057 *
4058 * @param pDevExt The device extension.
4059 * @param pszFile The source file where the caller detected the bad
4060 * context.
4061 * @param uLine The line number in @a pszFile.
4062 * @param pszExtra Optional additional message to give further hints.
4063 */
4064void VBOXCALL supdrvBadContext(PSUPDRVDEVEXT pDevExt, const char *pszFile, uint32_t uLine, const char *pszExtra)
4065{
4066 uint32_t cCalls;
4067
4068 /*
4069 * Shorten the filename before displaying the message.
4070 */
4071 for (;;)
4072 {
4073 const char *pszTmp = strchr(pszFile, '/');
4074 if (!pszTmp)
4075 pszTmp = strchr(pszFile, '\\');
4076 if (!pszTmp)
4077 break;
4078 pszFile = pszTmp + 1;
4079 }
4080 if (RT_VALID_PTR(pszExtra) && *pszExtra)
4081 SUPR0Printf("vboxdrv: Bad CPU context error at line %u in %s: %s\n", uLine, pszFile, pszExtra);
4082 else
4083 SUPR0Printf("vboxdrv: Bad CPU context error at line %u in %s!\n", uLine, pszFile);
4084
4085 /*
4086 * Record the incident so that we stand a chance of blocking I/O controls
4087 * before panicing the system.
4088 */
4089 cCalls = ASMAtomicIncU32(&pDevExt->cBadContextCalls);
4090 if (cCalls > UINT32_MAX - _1K)
4091 ASMAtomicWriteU32(&pDevExt->cBadContextCalls, UINT32_MAX - _1K);
4092}
4093
4094
4095/**
4096 * Reports a bad context, currenctly that means EFLAGS.AC is 0 instead of 1.
4097 *
4098 * @param pSession The session of the caller.
4099 * @param pszFile The source file where the caller detected the bad
4100 * context.
4101 * @param uLine The line number in @a pszFile.
4102 * @param pszExtra Optional additional message to give further hints.
4103 */
4104SUPR0DECL(void) SUPR0BadContext(PSUPDRVSESSION pSession, const char *pszFile, uint32_t uLine, const char *pszExtra)
4105{
4106 PSUPDRVDEVEXT pDevExt;
4107
4108 AssertReturnVoid(SUP_IS_SESSION_VALID(pSession));
4109 pDevExt = pSession->pDevExt;
4110
4111 supdrvBadContext(pDevExt, pszFile, uLine, pszExtra);
4112}
4113SUPR0_EXPORT_SYMBOL(SUPR0BadContext);
4114
4115
4116/**
4117 * Gets the paging mode of the current CPU.
4118 *
4119 * @returns Paging mode, SUPPAGEINGMODE_INVALID on error.
4120 */
4121SUPR0DECL(SUPPAGINGMODE) SUPR0GetPagingMode(void)
4122{
4123 SUPPAGINGMODE enmMode;
4124
4125 RTR0UINTREG cr0 = ASMGetCR0();
4126 if ((cr0 & (X86_CR0_PG | X86_CR0_PE)) != (X86_CR0_PG | X86_CR0_PE))
4127 enmMode = SUPPAGINGMODE_INVALID;
4128 else
4129 {
4130 RTR0UINTREG cr4 = ASMGetCR4();
4131 uint32_t fNXEPlusLMA = 0;
4132 if (cr4 & X86_CR4_PAE)
4133 {
4134 uint32_t fExtFeatures = ASMCpuId_EDX(0x80000001);
4135 if (fExtFeatures & (X86_CPUID_EXT_FEATURE_EDX_NX | X86_CPUID_EXT_FEATURE_EDX_LONG_MODE))
4136 {
4137 uint64_t efer = ASMRdMsr(MSR_K6_EFER);
4138 if ((fExtFeatures & X86_CPUID_EXT_FEATURE_EDX_NX) && (efer & MSR_K6_EFER_NXE))
4139 fNXEPlusLMA |= RT_BIT(0);
4140 if ((fExtFeatures & X86_CPUID_EXT_FEATURE_EDX_LONG_MODE) && (efer & MSR_K6_EFER_LMA))
4141 fNXEPlusLMA |= RT_BIT(1);
4142 }
4143 }
4144
4145 switch ((cr4 & (X86_CR4_PAE | X86_CR4_PGE)) | fNXEPlusLMA)
4146 {
4147 case 0:
4148 enmMode = SUPPAGINGMODE_32_BIT;
4149 break;
4150
4151 case X86_CR4_PGE:
4152 enmMode = SUPPAGINGMODE_32_BIT_GLOBAL;
4153 break;
4154
4155 case X86_CR4_PAE:
4156 enmMode = SUPPAGINGMODE_PAE;
4157 break;
4158
4159 case X86_CR4_PAE | RT_BIT(0):
4160 enmMode = SUPPAGINGMODE_PAE_NX;
4161 break;
4162
4163 case X86_CR4_PAE | X86_CR4_PGE:
4164 enmMode = SUPPAGINGMODE_PAE_GLOBAL;
4165 break;
4166
4167 case X86_CR4_PAE | X86_CR4_PGE | RT_BIT(0):
4168 enmMode = SUPPAGINGMODE_PAE_GLOBAL;
4169 break;
4170
4171 case RT_BIT(1) | X86_CR4_PAE:
4172 enmMode = SUPPAGINGMODE_AMD64;
4173 break;
4174
4175 case RT_BIT(1) | X86_CR4_PAE | RT_BIT(0):
4176 enmMode = SUPPAGINGMODE_AMD64_NX;
4177 break;
4178
4179 case RT_BIT(1) | X86_CR4_PAE | X86_CR4_PGE:
4180 enmMode = SUPPAGINGMODE_AMD64_GLOBAL;
4181 break;
4182
4183 case RT_BIT(1) | X86_CR4_PAE | X86_CR4_PGE | RT_BIT(0):
4184 enmMode = SUPPAGINGMODE_AMD64_GLOBAL_NX;
4185 break;
4186
4187 default:
4188 AssertMsgFailed(("Cannot happen! cr4=%#x fNXEPlusLMA=%d\n", cr4, fNXEPlusLMA));
4189 enmMode = SUPPAGINGMODE_INVALID;
4190 break;
4191 }
4192 }
4193 return enmMode;
4194}
4195SUPR0_EXPORT_SYMBOL(SUPR0GetPagingMode);
4196
4197
4198/**
4199 * Change CR4 and take care of the kernel CR4 shadow if applicable.
4200 *
4201 * CR4 shadow handling is required for Linux >= 4.0. Calling this function
4202 * instead of ASMSetCR4() is only necessary for semi-permanent CR4 changes
4203 * for code with interrupts enabled.
4204 *
4205 * @returns the old CR4 value.
4206 *
4207 * @param fOrMask bits to be set in CR4.
4208 * @param fAndMask bits to be cleard in CR4.
4209 *
4210 * @remarks Must be called with preemption/interrupts disabled.
4211 */
4212SUPR0DECL(RTCCUINTREG) SUPR0ChangeCR4(RTCCUINTREG fOrMask, RTCCUINTREG fAndMask)
4213{
4214#ifdef RT_OS_LINUX
4215 return supdrvOSChangeCR4(fOrMask, fAndMask);
4216#else
4217 RTCCUINTREG uOld = ASMGetCR4();
4218 RTCCUINTREG uNew = (uOld & fAndMask) | fOrMask;
4219 if (uNew != uOld)
4220 ASMSetCR4(uNew);
4221 return uOld;
4222#endif
4223}
4224SUPR0_EXPORT_SYMBOL(SUPR0ChangeCR4);
4225
4226
4227/**
4228 * Enables or disabled hardware virtualization extensions using native OS APIs.
4229 *
4230 * @returns VBox status code.
4231 * @retval VINF_SUCCESS on success.
4232 * @retval VERR_NOT_SUPPORTED if not supported by the native OS.
4233 *
4234 * @param fEnable Whether to enable or disable.
4235 */
4236SUPR0DECL(int) SUPR0EnableVTx(bool fEnable)
4237{
4238#ifdef RT_OS_DARWIN
4239 return supdrvOSEnableVTx(fEnable);
4240#else
4241 RT_NOREF1(fEnable);
4242 return VERR_NOT_SUPPORTED;
4243#endif
4244}
4245SUPR0_EXPORT_SYMBOL(SUPR0EnableVTx);
4246
4247
4248/**
4249 * Suspends hardware virtualization extensions using the native OS API.
4250 *
4251 * This is called prior to entering raw-mode context.
4252 *
4253 * @returns @c true if suspended, @c false if not.
4254 */
4255SUPR0DECL(bool) SUPR0SuspendVTxOnCpu(void)
4256{
4257#ifdef RT_OS_DARWIN
4258 return supdrvOSSuspendVTxOnCpu();
4259#else
4260 return false;
4261#endif
4262}
4263SUPR0_EXPORT_SYMBOL(SUPR0SuspendVTxOnCpu);
4264
4265
4266/**
4267 * Resumes hardware virtualization extensions using the native OS API.
4268 *
4269 * This is called after to entering raw-mode context.
4270 *
4271 * @param fSuspended The return value of SUPR0SuspendVTxOnCpu.
4272 */
4273SUPR0DECL(void) SUPR0ResumeVTxOnCpu(bool fSuspended)
4274{
4275#ifdef RT_OS_DARWIN
4276 supdrvOSResumeVTxOnCpu(fSuspended);
4277#else
4278 RT_NOREF1(fSuspended);
4279 Assert(!fSuspended);
4280#endif
4281}
4282SUPR0_EXPORT_SYMBOL(SUPR0ResumeVTxOnCpu);
4283
4284
4285SUPR0DECL(int) SUPR0GetCurrentGdtRw(RTHCUINTPTR *pGdtRw)
4286{
4287#ifdef RT_OS_LINUX
4288 return supdrvOSGetCurrentGdtRw(pGdtRw);
4289#else
4290 NOREF(pGdtRw);
4291 return VERR_NOT_IMPLEMENTED;
4292#endif
4293}
4294SUPR0_EXPORT_SYMBOL(SUPR0GetCurrentGdtRw);
4295
4296
4297/**
4298 * Gets AMD-V and VT-x support for the calling CPU.
4299 *
4300 * @returns VBox status code.
4301 * @param pfCaps Where to store whether VT-x (SUPVTCAPS_VT_X) or AMD-V
4302 * (SUPVTCAPS_AMD_V) is supported.
4303 */
4304SUPR0DECL(int) SUPR0GetVTSupport(uint32_t *pfCaps)
4305{
4306 Assert(pfCaps);
4307 *pfCaps = 0;
4308
4309 /* Check if the CPU even supports CPUID (extremely ancient CPUs). */
4310 if (ASMHasCpuId())
4311 {
4312 /* Check the range of standard CPUID leafs. */
4313 uint32_t uMaxLeaf, uVendorEbx, uVendorEcx, uVendorEdx;
4314 ASMCpuId(0, &uMaxLeaf, &uVendorEbx, &uVendorEcx, &uVendorEdx);
4315 if (RTX86IsValidStdRange(uMaxLeaf))
4316 {
4317 /* Query the standard CPUID leaf. */
4318 uint32_t fFeatEcx, fFeatEdx, uDummy;
4319 ASMCpuId(1, &uDummy, &uDummy, &fFeatEcx, &fFeatEdx);
4320
4321 /* Check if the vendor is Intel (or compatible). */
4322 if ( RTX86IsIntelCpu(uVendorEbx, uVendorEcx, uVendorEdx)
4323 || RTX86IsViaCentaurCpu(uVendorEbx, uVendorEcx, uVendorEdx)
4324 || RTX86IsShanghaiCpu(uVendorEbx, uVendorEcx, uVendorEdx))
4325 {
4326 /* Check VT-x support. In addition, VirtualBox requires MSR and FXSAVE/FXRSTOR to function. */
4327 if ( (fFeatEcx & X86_CPUID_FEATURE_ECX_VMX)
4328 && (fFeatEdx & X86_CPUID_FEATURE_EDX_MSR)
4329 && (fFeatEdx & X86_CPUID_FEATURE_EDX_FXSR))
4330 {
4331 *pfCaps = SUPVTCAPS_VT_X;
4332 return VINF_SUCCESS;
4333 }
4334 return VERR_VMX_NO_VMX;
4335 }
4336
4337 /* Check if the vendor is AMD (or compatible). */
4338 if ( RTX86IsAmdCpu(uVendorEbx, uVendorEcx, uVendorEdx)
4339 || RTX86IsHygonCpu(uVendorEbx, uVendorEcx, uVendorEdx))
4340 {
4341 uint32_t fExtFeatEcx, uExtMaxId;
4342 ASMCpuId(0x80000000, &uExtMaxId, &uDummy, &uDummy, &uDummy);
4343 ASMCpuId(0x80000001, &uDummy, &uDummy, &fExtFeatEcx, &uDummy);
4344
4345 /* Check AMD-V support. In addition, VirtualBox requires MSR and FXSAVE/FXRSTOR to function. */
4346 if ( RTX86IsValidExtRange(uExtMaxId)
4347 && uExtMaxId >= 0x8000000a
4348 && (fExtFeatEcx & X86_CPUID_AMD_FEATURE_ECX_SVM)
4349 && (fFeatEdx & X86_CPUID_FEATURE_EDX_MSR)
4350 && (fFeatEdx & X86_CPUID_FEATURE_EDX_FXSR))
4351 {
4352 *pfCaps = SUPVTCAPS_AMD_V;
4353 return VINF_SUCCESS;
4354 }
4355 return VERR_SVM_NO_SVM;
4356 }
4357 }
4358 }
4359 return VERR_UNSUPPORTED_CPU;
4360}
4361SUPR0_EXPORT_SYMBOL(SUPR0GetVTSupport);
4362
4363
4364/**
4365 * Checks if Intel VT-x feature is usable on this CPU.
4366 *
4367 * @returns VBox status code.
4368 * @param pfIsSmxModeAmbiguous Where to return whether the SMX mode causes
4369 * ambiguity that makes us unsure whether we
4370 * really can use VT-x or not.
4371 *
4372 * @remarks Must be called with preemption disabled.
4373 * The caller is also expected to check that the CPU is an Intel (or
4374 * VIA/Shanghai) CPU -and- that it supports VT-x. Otherwise, this
4375 * function might throw a \#GP fault as it tries to read/write MSRs
4376 * that may not be present!
4377 */
4378SUPR0DECL(int) SUPR0GetVmxUsability(bool *pfIsSmxModeAmbiguous)
4379{
4380 uint64_t fFeatMsr;
4381 bool fMaybeSmxMode;
4382 bool fMsrLocked;
4383 bool fSmxVmxAllowed;
4384 bool fVmxAllowed;
4385 bool fIsSmxModeAmbiguous;
4386 int rc;
4387
4388 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4389
4390 fFeatMsr = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
4391 fMaybeSmxMode = RT_BOOL(ASMGetCR4() & X86_CR4_SMXE);
4392 fMsrLocked = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_LOCK);
4393 fSmxVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
4394 fVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_VMXON);
4395 fIsSmxModeAmbiguous = false;
4396 rc = VERR_INTERNAL_ERROR_5;
4397
4398 /* Check if the LOCK bit is set but excludes the required VMXON bit. */
4399 if (fMsrLocked)
4400 {
4401 if (fVmxAllowed && fSmxVmxAllowed)
4402 rc = VINF_SUCCESS;
4403 else if (!fVmxAllowed && !fSmxVmxAllowed)
4404 rc = VERR_VMX_MSR_ALL_VMX_DISABLED;
4405 else if (!fMaybeSmxMode)
4406 {
4407 if (fVmxAllowed)
4408 rc = VINF_SUCCESS;
4409 else
4410 rc = VERR_VMX_MSR_VMX_DISABLED;
4411 }
4412 else
4413 {
4414 /*
4415 * CR4.SMXE is set but this doesn't mean the CPU is necessarily in SMX mode. We shall assume
4416 * that it is -not- and that it is a stupid BIOS/OS setting CR4.SMXE for no good reason.
4417 * See @bugref{6873}.
4418 */
4419 Assert(fMaybeSmxMode == true);
4420 fIsSmxModeAmbiguous = true;
4421 rc = VINF_SUCCESS;
4422 }
4423 }
4424 else
4425 {
4426 /*
4427 * MSR is not yet locked; we can change it ourselves here. Once the lock bit is set,
4428 * this MSR can no longer be modified.
4429 *
4430 * Set both the VMX and SMX_VMX bits (if supported) as we can't determine SMX mode
4431 * accurately. See @bugref{6873}.
4432 *
4433 * We need to check for SMX hardware support here, before writing the MSR as
4434 * otherwise we will #GP fault on CPUs that do not support it. Callers do not check
4435 * for it.
4436 */
4437 uint32_t fFeaturesECX, uDummy;
4438#ifdef VBOX_STRICT
4439 /* Callers should have verified these at some point. */
4440 uint32_t uMaxId, uVendorEBX, uVendorECX, uVendorEDX;
4441 ASMCpuId(0, &uMaxId, &uVendorEBX, &uVendorECX, &uVendorEDX);
4442 Assert(RTX86IsValidStdRange(uMaxId));
4443 Assert( RTX86IsIntelCpu( uVendorEBX, uVendorECX, uVendorEDX)
4444 || RTX86IsViaCentaurCpu(uVendorEBX, uVendorECX, uVendorEDX)
4445 || RTX86IsShanghaiCpu( uVendorEBX, uVendorECX, uVendorEDX));
4446#endif
4447 ASMCpuId(1, &uDummy, &uDummy, &fFeaturesECX, &uDummy);
4448 bool fSmxVmxHwSupport = false;
4449 if ( (fFeaturesECX & X86_CPUID_FEATURE_ECX_VMX)
4450 && (fFeaturesECX & X86_CPUID_FEATURE_ECX_SMX))
4451 fSmxVmxHwSupport = true;
4452
4453 fFeatMsr |= MSR_IA32_FEATURE_CONTROL_LOCK
4454 | MSR_IA32_FEATURE_CONTROL_VMXON;
4455 if (fSmxVmxHwSupport)
4456 fFeatMsr |= MSR_IA32_FEATURE_CONTROL_SMX_VMXON;
4457
4458 /*
4459 * Commit.
4460 */
4461 ASMWrMsr(MSR_IA32_FEATURE_CONTROL, fFeatMsr);
4462
4463 /*
4464 * Verify.
4465 */
4466 fFeatMsr = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
4467 fMsrLocked = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_LOCK);
4468 if (fMsrLocked)
4469 {
4470 fSmxVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
4471 fVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_VMXON);
4472 if ( fVmxAllowed
4473 && ( !fSmxVmxHwSupport
4474 || fSmxVmxAllowed))
4475 rc = VINF_SUCCESS;
4476 else
4477 rc = !fSmxVmxHwSupport ? VERR_VMX_MSR_VMX_ENABLE_FAILED : VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED;
4478 }
4479 else
4480 rc = VERR_VMX_MSR_LOCKING_FAILED;
4481 }
4482
4483 if (pfIsSmxModeAmbiguous)
4484 *pfIsSmxModeAmbiguous = fIsSmxModeAmbiguous;
4485
4486 return rc;
4487}
4488SUPR0_EXPORT_SYMBOL(SUPR0GetVmxUsability);
4489
4490
4491/**
4492 * Checks if AMD-V SVM feature is usable on this CPU.
4493 *
4494 * @returns VBox status code.
4495 * @param fInitSvm If usable, try to initialize SVM on this CPU.
4496 *
4497 * @remarks Must be called with preemption disabled.
4498 */
4499SUPR0DECL(int) SUPR0GetSvmUsability(bool fInitSvm)
4500{
4501 int rc;
4502 uint64_t fVmCr;
4503 uint64_t fEfer;
4504
4505 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4506 fVmCr = ASMRdMsr(MSR_K8_VM_CR);
4507 if (!(fVmCr & MSR_K8_VM_CR_SVM_DISABLE))
4508 {
4509 rc = VINF_SUCCESS;
4510 if (fInitSvm)
4511 {
4512 /* Turn on SVM in the EFER MSR. */
4513 fEfer = ASMRdMsr(MSR_K6_EFER);
4514 if (fEfer & MSR_K6_EFER_SVME)
4515 rc = VERR_SVM_IN_USE;
4516 else
4517 {
4518 ASMWrMsr(MSR_K6_EFER, fEfer | MSR_K6_EFER_SVME);
4519
4520 /* Paranoia. */
4521 fEfer = ASMRdMsr(MSR_K6_EFER);
4522 if (fEfer & MSR_K6_EFER_SVME)
4523 {
4524 /* Restore previous value. */
4525 ASMWrMsr(MSR_K6_EFER, fEfer & ~MSR_K6_EFER_SVME);
4526 }
4527 else
4528 rc = VERR_SVM_ILLEGAL_EFER_MSR;
4529 }
4530 }
4531 }
4532 else
4533 rc = VERR_SVM_DISABLED;
4534 return rc;
4535}
4536SUPR0_EXPORT_SYMBOL(SUPR0GetSvmUsability);
4537
4538
4539/**
4540 * Queries the AMD-V and VT-x capabilities of the calling CPU.
4541 *
4542 * @returns VBox status code.
4543 * @retval VERR_VMX_NO_VMX
4544 * @retval VERR_VMX_MSR_ALL_VMX_DISABLED
4545 * @retval VERR_VMX_MSR_VMX_DISABLED
4546 * @retval VERR_VMX_MSR_LOCKING_FAILED
4547 * @retval VERR_VMX_MSR_VMX_ENABLE_FAILED
4548 * @retval VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED
4549 * @retval VERR_SVM_NO_SVM
4550 * @retval VERR_SVM_DISABLED
4551 * @retval VERR_UNSUPPORTED_CPU if not identifiable as an AMD, Intel or VIA
4552 * (centaur)/Shanghai CPU.
4553 *
4554 * @param pfCaps Where to store the capabilities.
4555 */
4556int VBOXCALL supdrvQueryVTCapsInternal(uint32_t *pfCaps)
4557{
4558 int rc = VERR_UNSUPPORTED_CPU;
4559 bool fIsSmxModeAmbiguous = false;
4560 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
4561
4562 /*
4563 * Input validation.
4564 */
4565 AssertPtrReturn(pfCaps, VERR_INVALID_POINTER);
4566 *pfCaps = 0;
4567
4568 /* We may modify MSRs and re-read them, disable preemption so we make sure we don't migrate CPUs. */
4569 RTThreadPreemptDisable(&PreemptState);
4570
4571 /* Check if VT-x/AMD-V is supported. */
4572 rc = SUPR0GetVTSupport(pfCaps);
4573 if (RT_SUCCESS(rc))
4574 {
4575 /* Check if VT-x is supported. */
4576 if (*pfCaps & SUPVTCAPS_VT_X)
4577 {
4578 /* Check if VT-x is usable. */
4579 rc = SUPR0GetVmxUsability(&fIsSmxModeAmbiguous);
4580 if (RT_SUCCESS(rc))
4581 {
4582 /* Query some basic VT-x capabilities (mainly required by our GUI). */
4583 VMXCTLSMSR vtCaps;
4584 vtCaps.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS);
4585 if (vtCaps.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
4586 {
4587 vtCaps.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS2);
4588 if (vtCaps.n.allowed1 & VMX_PROC_CTLS2_EPT)
4589 *pfCaps |= SUPVTCAPS_NESTED_PAGING;
4590 if (vtCaps.n.allowed1 & VMX_PROC_CTLS2_UNRESTRICTED_GUEST)
4591 *pfCaps |= SUPVTCAPS_VTX_UNRESTRICTED_GUEST;
4592 if (vtCaps.n.allowed1 & VMX_PROC_CTLS2_VMCS_SHADOWING)
4593 *pfCaps |= SUPVTCAPS_VTX_VMCS_SHADOWING;
4594 }
4595 }
4596 }
4597 /* Check if AMD-V is supported. */
4598 else if (*pfCaps & SUPVTCAPS_AMD_V)
4599 {
4600 /* Check is SVM is usable. */
4601 rc = SUPR0GetSvmUsability(false /* fInitSvm */);
4602 if (RT_SUCCESS(rc))
4603 {
4604 /* Query some basic AMD-V capabilities (mainly required by our GUI). */
4605 uint32_t uDummy, fSvmFeatures;
4606 ASMCpuId(0x8000000a, &uDummy, &uDummy, &uDummy, &fSvmFeatures);
4607 if (fSvmFeatures & X86_CPUID_SVM_FEATURE_EDX_NESTED_PAGING)
4608 *pfCaps |= SUPVTCAPS_NESTED_PAGING;
4609 if (fSvmFeatures & X86_CPUID_SVM_FEATURE_EDX_VIRT_VMSAVE_VMLOAD)
4610 *pfCaps |= SUPVTCAPS_AMDV_VIRT_VMSAVE_VMLOAD;
4611 }
4612 }
4613 }
4614
4615 /* Restore preemption. */
4616 RTThreadPreemptRestore(&PreemptState);
4617
4618 /* After restoring preemption, if we may be in SMX mode, print a warning as it's difficult to debug such problems. */
4619 if (fIsSmxModeAmbiguous)
4620 SUPR0Printf(("WARNING! CR4 hints SMX mode but your CPU is too secretive. Proceeding anyway... We wish you good luck!\n"));
4621
4622 return rc;
4623}
4624
4625
4626/**
4627 * Queries the AMD-V and VT-x capabilities of the calling CPU.
4628 *
4629 * @returns VBox status code.
4630 * @retval VERR_VMX_NO_VMX
4631 * @retval VERR_VMX_MSR_ALL_VMX_DISABLED
4632 * @retval VERR_VMX_MSR_VMX_DISABLED
4633 * @retval VERR_VMX_MSR_LOCKING_FAILED
4634 * @retval VERR_VMX_MSR_VMX_ENABLE_FAILED
4635 * @retval VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED
4636 * @retval VERR_SVM_NO_SVM
4637 * @retval VERR_SVM_DISABLED
4638 * @retval VERR_UNSUPPORTED_CPU if not identifiable as an AMD, Intel or VIA
4639 * (centaur)/Shanghai CPU.
4640 *
4641 * @param pSession The session handle.
4642 * @param pfCaps Where to store the capabilities.
4643 */
4644SUPR0DECL(int) SUPR0QueryVTCaps(PSUPDRVSESSION pSession, uint32_t *pfCaps)
4645{
4646 /*
4647 * Input validation.
4648 */
4649 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4650 AssertPtrReturn(pfCaps, VERR_INVALID_POINTER);
4651
4652 /*
4653 * Call common worker.
4654 */
4655 return supdrvQueryVTCapsInternal(pfCaps);
4656}
4657SUPR0_EXPORT_SYMBOL(SUPR0QueryVTCaps);
4658
4659
4660/**
4661 * Queries the CPU microcode revision.
4662 *
4663 * @returns VBox status code.
4664 * @retval VERR_UNSUPPORTED_CPU if not identifiable as a processor with
4665 * readable microcode rev.
4666 *
4667 * @param puRevision Where to store the microcode revision.
4668 */
4669static int VBOXCALL supdrvQueryUcodeRev(uint32_t *puRevision)
4670{
4671 int rc = VERR_UNSUPPORTED_CPU;
4672 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
4673
4674 /*
4675 * Input validation.
4676 */
4677 AssertPtrReturn(puRevision, VERR_INVALID_POINTER);
4678
4679 *puRevision = 0;
4680
4681 /* Disable preemption so we make sure we don't migrate CPUs, just in case. */
4682 /* NB: We assume that there aren't mismatched microcode revs in the system. */
4683 RTThreadPreemptDisable(&PreemptState);
4684
4685 if (ASMHasCpuId())
4686 {
4687 uint32_t uDummy, uTFMSEAX;
4688 uint32_t uMaxId, uVendorEBX, uVendorECX, uVendorEDX;
4689
4690 ASMCpuId(0, &uMaxId, &uVendorEBX, &uVendorECX, &uVendorEDX);
4691 ASMCpuId(1, &uTFMSEAX, &uDummy, &uDummy, &uDummy);
4692
4693 if (RTX86IsValidStdRange(uMaxId))
4694 {
4695 uint64_t uRevMsr;
4696 if (RTX86IsIntelCpu(uVendorEBX, uVendorECX, uVendorEDX))
4697 {
4698 /* Architectural MSR available on Pentium Pro and later. */
4699 if (RTX86GetCpuFamily(uTFMSEAX) >= 6)
4700 {
4701 /* Revision is in the high dword. */
4702 uRevMsr = ASMRdMsr(MSR_IA32_BIOS_SIGN_ID);
4703 *puRevision = RT_HIDWORD(uRevMsr);
4704 rc = VINF_SUCCESS;
4705 }
4706 }
4707 else if ( RTX86IsAmdCpu(uVendorEBX, uVendorECX, uVendorEDX)
4708 || RTX86IsHygonCpu(uVendorEBX, uVendorECX, uVendorEDX))
4709 {
4710 /* Not well documented, but at least all AMD64 CPUs support this. */
4711 if (RTX86GetCpuFamily(uTFMSEAX) >= 15)
4712 {
4713 /* Revision is in the low dword. */
4714 uRevMsr = ASMRdMsr(MSR_IA32_BIOS_SIGN_ID); /* Same MSR as Intel. */
4715 *puRevision = RT_LODWORD(uRevMsr);
4716 rc = VINF_SUCCESS;
4717 }
4718 }
4719 }
4720 }
4721
4722 RTThreadPreemptRestore(&PreemptState);
4723
4724 return rc;
4725}
4726
4727
4728/**
4729 * Queries the CPU microcode revision.
4730 *
4731 * @returns VBox status code.
4732 * @retval VERR_UNSUPPORTED_CPU if not identifiable as a processor with
4733 * readable microcode rev.
4734 *
4735 * @param pSession The session handle.
4736 * @param puRevision Where to store the microcode revision.
4737 */
4738SUPR0DECL(int) SUPR0QueryUcodeRev(PSUPDRVSESSION pSession, uint32_t *puRevision)
4739{
4740 /*
4741 * Input validation.
4742 */
4743 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4744 AssertPtrReturn(puRevision, VERR_INVALID_POINTER);
4745
4746 /*
4747 * Call common worker.
4748 */
4749 return supdrvQueryUcodeRev(puRevision);
4750}
4751SUPR0_EXPORT_SYMBOL(SUPR0QueryUcodeRev);
4752
4753
4754/**
4755 * Gets hardware-virtualization MSRs of the calling CPU.
4756 *
4757 * @returns VBox status code.
4758 * @param pMsrs Where to store the hardware-virtualization MSRs.
4759 * @param fCaps Hardware virtualization capabilities (SUPVTCAPS_XXX). Pass 0
4760 * to explicitly check for the presence of VT-x/AMD-V before
4761 * querying MSRs.
4762 * @param fForce Force querying of MSRs from the hardware.
4763 */
4764SUPR0DECL(int) SUPR0GetHwvirtMsrs(PSUPHWVIRTMSRS pMsrs, uint32_t fCaps, bool fForce)
4765{
4766 NOREF(fForce);
4767
4768 int rc;
4769 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
4770
4771 /*
4772 * Input validation.
4773 */
4774 AssertPtrReturn(pMsrs, VERR_INVALID_POINTER);
4775
4776 /*
4777 * Disable preemption so we make sure we don't migrate CPUs and because
4778 * we access global data.
4779 */
4780 RTThreadPreemptDisable(&PreemptState);
4781
4782 /*
4783 * Query the MSRs from the hardware.
4784 */
4785 SUPHWVIRTMSRS Msrs;
4786 RT_ZERO(Msrs);
4787
4788 /* If the caller claims VT-x/AMD-V is supported, don't need to recheck it. */
4789 if (!(fCaps & (SUPVTCAPS_VT_X | SUPVTCAPS_AMD_V)))
4790 rc = SUPR0GetVTSupport(&fCaps);
4791 else
4792 rc = VINF_SUCCESS;
4793 if (RT_SUCCESS(rc))
4794 {
4795 if (fCaps & SUPVTCAPS_VT_X)
4796 {
4797 Msrs.u.vmx.u64FeatCtrl = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
4798 Msrs.u.vmx.u64Basic = ASMRdMsr(MSR_IA32_VMX_BASIC);
4799 Msrs.u.vmx.PinCtls.u = ASMRdMsr(MSR_IA32_VMX_PINBASED_CTLS);
4800 Msrs.u.vmx.ProcCtls.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS);
4801 Msrs.u.vmx.ExitCtls.u = ASMRdMsr(MSR_IA32_VMX_EXIT_CTLS);
4802 Msrs.u.vmx.EntryCtls.u = ASMRdMsr(MSR_IA32_VMX_ENTRY_CTLS);
4803 Msrs.u.vmx.u64Misc = ASMRdMsr(MSR_IA32_VMX_MISC);
4804 Msrs.u.vmx.u64Cr0Fixed0 = ASMRdMsr(MSR_IA32_VMX_CR0_FIXED0);
4805 Msrs.u.vmx.u64Cr0Fixed1 = ASMRdMsr(MSR_IA32_VMX_CR0_FIXED1);
4806 Msrs.u.vmx.u64Cr4Fixed0 = ASMRdMsr(MSR_IA32_VMX_CR4_FIXED0);
4807 Msrs.u.vmx.u64Cr4Fixed1 = ASMRdMsr(MSR_IA32_VMX_CR4_FIXED1);
4808 Msrs.u.vmx.u64VmcsEnum = ASMRdMsr(MSR_IA32_VMX_VMCS_ENUM);
4809
4810 if (RT_BF_GET(Msrs.u.vmx.u64Basic, VMX_BF_BASIC_TRUE_CTLS))
4811 {
4812 Msrs.u.vmx.TruePinCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_PINBASED_CTLS);
4813 Msrs.u.vmx.TrueProcCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_PROCBASED_CTLS);
4814 Msrs.u.vmx.TrueEntryCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_ENTRY_CTLS);
4815 Msrs.u.vmx.TrueExitCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_EXIT_CTLS);
4816 }
4817
4818 if (Msrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
4819 {
4820 Msrs.u.vmx.ProcCtls2.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS2);
4821
4822 if (Msrs.u.vmx.ProcCtls2.n.allowed1 & (VMX_PROC_CTLS2_EPT | VMX_PROC_CTLS2_VPID))
4823 Msrs.u.vmx.u64EptVpidCaps = ASMRdMsr(MSR_IA32_VMX_EPT_VPID_CAP);
4824
4825 if (Msrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VMFUNC)
4826 Msrs.u.vmx.u64VmFunc = ASMRdMsr(MSR_IA32_VMX_VMFUNC);
4827 }
4828
4829 if (Msrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TERTIARY_CTLS)
4830 Msrs.u.vmx.u64ProcCtls3 = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS3);
4831 }
4832 else if (fCaps & SUPVTCAPS_AMD_V)
4833 {
4834 Msrs.u.svm.u64MsrHwcr = ASMRdMsr(MSR_K8_HWCR);
4835 Msrs.u.svm.u64MsrSmmAddr = ASMRdMsr(MSR_K7_SMM_ADDR);
4836 Msrs.u.svm.u64MsrSmmMask = ASMRdMsr(MSR_K7_SMM_MASK);
4837 }
4838 else
4839 {
4840 RTThreadPreemptRestore(&PreemptState);
4841 AssertMsgFailedReturn(("SUPR0GetVTSupport returns success but neither VT-x nor AMD-V reported!\n"),
4842 VERR_INTERNAL_ERROR_2);
4843 }
4844
4845 /*
4846 * Copy the MSRs out.
4847 */
4848 memcpy(pMsrs, &Msrs, sizeof(*pMsrs));
4849 }
4850
4851 RTThreadPreemptRestore(&PreemptState);
4852
4853 return rc;
4854}
4855SUPR0_EXPORT_SYMBOL(SUPR0GetHwvirtMsrs);
4856
4857
4858/**
4859 * Register a component factory with the support driver.
4860 *
4861 * This is currently restricted to kernel sessions only.
4862 *
4863 * @returns VBox status code.
4864 * @retval VINF_SUCCESS on success.
4865 * @retval VERR_NO_MEMORY if we're out of memory.
4866 * @retval VERR_ALREADY_EXISTS if the factory has already been registered.
4867 * @retval VERR_ACCESS_DENIED if it isn't a kernel session.
4868 * @retval VERR_INVALID_PARAMETER on invalid parameter.
4869 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
4870 *
4871 * @param pSession The SUPDRV session (must be a ring-0 session).
4872 * @param pFactory Pointer to the component factory registration structure.
4873 *
4874 * @remarks This interface is also available via SUPR0IdcComponentRegisterFactory.
4875 */
4876SUPR0DECL(int) SUPR0ComponentRegisterFactory(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory)
4877{
4878 PSUPDRVFACTORYREG pNewReg;
4879 const char *psz;
4880 int rc;
4881
4882 /*
4883 * Validate parameters.
4884 */
4885 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4886 AssertReturn(pSession->R0Process == NIL_RTR0PROCESS, VERR_ACCESS_DENIED);
4887 AssertPtrReturn(pFactory, VERR_INVALID_POINTER);
4888 AssertPtrReturn(pFactory->pfnQueryFactoryInterface, VERR_INVALID_POINTER);
4889 psz = RTStrEnd(pFactory->szName, sizeof(pFactory->szName));
4890 AssertReturn(psz, VERR_INVALID_PARAMETER);
4891
4892 /*
4893 * Allocate and initialize a new registration structure.
4894 */
4895 pNewReg = (PSUPDRVFACTORYREG)RTMemAlloc(sizeof(SUPDRVFACTORYREG));
4896 if (pNewReg)
4897 {
4898 pNewReg->pNext = NULL;
4899 pNewReg->pFactory = pFactory;
4900 pNewReg->pSession = pSession;
4901 pNewReg->cchName = psz - &pFactory->szName[0];
4902
4903 /*
4904 * Add it to the tail of the list after checking for prior registration.
4905 */
4906 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
4907 if (RT_SUCCESS(rc))
4908 {
4909 PSUPDRVFACTORYREG pPrev = NULL;
4910 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
4911 while (pCur && pCur->pFactory != pFactory)
4912 {
4913 pPrev = pCur;
4914 pCur = pCur->pNext;
4915 }
4916 if (!pCur)
4917 {
4918 if (pPrev)
4919 pPrev->pNext = pNewReg;
4920 else
4921 pSession->pDevExt->pComponentFactoryHead = pNewReg;
4922 rc = VINF_SUCCESS;
4923 }
4924 else
4925 rc = VERR_ALREADY_EXISTS;
4926
4927 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
4928 }
4929
4930 if (RT_FAILURE(rc))
4931 RTMemFree(pNewReg);
4932 }
4933 else
4934 rc = VERR_NO_MEMORY;
4935 return rc;
4936}
4937SUPR0_EXPORT_SYMBOL(SUPR0ComponentRegisterFactory);
4938
4939
4940/**
4941 * Deregister a component factory.
4942 *
4943 * @returns VBox status code.
4944 * @retval VINF_SUCCESS on success.
4945 * @retval VERR_NOT_FOUND if the factory wasn't registered.
4946 * @retval VERR_ACCESS_DENIED if it isn't a kernel session.
4947 * @retval VERR_INVALID_PARAMETER on invalid parameter.
4948 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
4949 *
4950 * @param pSession The SUPDRV session (must be a ring-0 session).
4951 * @param pFactory Pointer to the component factory registration structure
4952 * previously passed SUPR0ComponentRegisterFactory().
4953 *
4954 * @remarks This interface is also available via SUPR0IdcComponentDeregisterFactory.
4955 */
4956SUPR0DECL(int) SUPR0ComponentDeregisterFactory(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory)
4957{
4958 int rc;
4959
4960 /*
4961 * Validate parameters.
4962 */
4963 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4964 AssertReturn(pSession->R0Process == NIL_RTR0PROCESS, VERR_ACCESS_DENIED);
4965 AssertPtrReturn(pFactory, VERR_INVALID_POINTER);
4966
4967 /*
4968 * Take the lock and look for the registration record.
4969 */
4970 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
4971 if (RT_SUCCESS(rc))
4972 {
4973 PSUPDRVFACTORYREG pPrev = NULL;
4974 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
4975 while (pCur && pCur->pFactory != pFactory)
4976 {
4977 pPrev = pCur;
4978 pCur = pCur->pNext;
4979 }
4980 if (pCur)
4981 {
4982 if (!pPrev)
4983 pSession->pDevExt->pComponentFactoryHead = pCur->pNext;
4984 else
4985 pPrev->pNext = pCur->pNext;
4986
4987 pCur->pNext = NULL;
4988 pCur->pFactory = NULL;
4989 pCur->pSession = NULL;
4990 rc = VINF_SUCCESS;
4991 }
4992 else
4993 rc = VERR_NOT_FOUND;
4994
4995 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
4996
4997 RTMemFree(pCur);
4998 }
4999 return rc;
5000}
5001SUPR0_EXPORT_SYMBOL(SUPR0ComponentDeregisterFactory);
5002
5003
5004/**
5005 * Queries a component factory.
5006 *
5007 * @returns VBox status code.
5008 * @retval VERR_INVALID_PARAMETER on invalid parameter.
5009 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
5010 * @retval VERR_SUPDRV_COMPONENT_NOT_FOUND if the component factory wasn't found.
5011 * @retval VERR_SUPDRV_INTERFACE_NOT_SUPPORTED if the interface wasn't supported.
5012 *
5013 * @param pSession The SUPDRV session.
5014 * @param pszName The name of the component factory.
5015 * @param pszInterfaceUuid The UUID of the factory interface (stringified).
5016 * @param ppvFactoryIf Where to store the factory interface.
5017 */
5018SUPR0DECL(int) SUPR0ComponentQueryFactory(PSUPDRVSESSION pSession, const char *pszName, const char *pszInterfaceUuid, void **ppvFactoryIf)
5019{
5020 const char *pszEnd;
5021 size_t cchName;
5022 int rc;
5023
5024 /*
5025 * Validate parameters.
5026 */
5027 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
5028
5029 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
5030 pszEnd = RTStrEnd(pszName, RT_SIZEOFMEMB(SUPDRVFACTORY, szName));
5031 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
5032 cchName = pszEnd - pszName;
5033
5034 AssertPtrReturn(pszInterfaceUuid, VERR_INVALID_POINTER);
5035 pszEnd = RTStrEnd(pszInterfaceUuid, RTUUID_STR_LENGTH);
5036 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
5037
5038 AssertPtrReturn(ppvFactoryIf, VERR_INVALID_POINTER);
5039 *ppvFactoryIf = NULL;
5040
5041 /*
5042 * Take the lock and try all factories by this name.
5043 */
5044 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
5045 if (RT_SUCCESS(rc))
5046 {
5047 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
5048 rc = VERR_SUPDRV_COMPONENT_NOT_FOUND;
5049 while (pCur)
5050 {
5051 if ( pCur->cchName == cchName
5052 && !memcmp(pCur->pFactory->szName, pszName, cchName))
5053 {
5054 void *pvFactory = pCur->pFactory->pfnQueryFactoryInterface(pCur->pFactory, pSession, pszInterfaceUuid);
5055 if (pvFactory)
5056 {
5057 *ppvFactoryIf = pvFactory;
5058 rc = VINF_SUCCESS;
5059 break;
5060 }
5061 rc = VERR_SUPDRV_INTERFACE_NOT_SUPPORTED;
5062 }
5063
5064 /* next */
5065 pCur = pCur->pNext;
5066 }
5067
5068 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
5069 }
5070 return rc;
5071}
5072SUPR0_EXPORT_SYMBOL(SUPR0ComponentQueryFactory);
5073
5074
5075/**
5076 * Adds a memory object to the session.
5077 *
5078 * @returns IPRT status code.
5079 * @param pMem Memory tracking structure containing the
5080 * information to track.
5081 * @param pSession The session.
5082 */
5083static int supdrvMemAdd(PSUPDRVMEMREF pMem, PSUPDRVSESSION pSession)
5084{
5085 PSUPDRVBUNDLE pBundle;
5086
5087 /*
5088 * Find free entry and record the allocation.
5089 */
5090 RTSpinlockAcquire(pSession->Spinlock);
5091 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
5092 {
5093 if (pBundle->cUsed < RT_ELEMENTS(pBundle->aMem))
5094 {
5095 unsigned i;
5096 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
5097 {
5098 if (pBundle->aMem[i].MemObj == NIL_RTR0MEMOBJ)
5099 {
5100 pBundle->cUsed++;
5101 pBundle->aMem[i] = *pMem;
5102 RTSpinlockRelease(pSession->Spinlock);
5103 return VINF_SUCCESS;
5104 }
5105 }
5106 AssertFailed(); /* !!this can't be happening!!! */
5107 }
5108 }
5109 RTSpinlockRelease(pSession->Spinlock);
5110
5111 /*
5112 * Need to allocate a new bundle.
5113 * Insert into the last entry in the bundle.
5114 */
5115 pBundle = (PSUPDRVBUNDLE)RTMemAllocZ(sizeof(*pBundle));
5116 if (!pBundle)
5117 return VERR_NO_MEMORY;
5118
5119 /* take last entry. */
5120 pBundle->cUsed++;
5121 pBundle->aMem[RT_ELEMENTS(pBundle->aMem) - 1] = *pMem;
5122
5123 /* insert into list. */
5124 RTSpinlockAcquire(pSession->Spinlock);
5125 pBundle->pNext = pSession->Bundle.pNext;
5126 pSession->Bundle.pNext = pBundle;
5127 RTSpinlockRelease(pSession->Spinlock);
5128
5129 return VINF_SUCCESS;
5130}
5131
5132
5133/**
5134 * Releases a memory object referenced by pointer and type.
5135 *
5136 * @returns IPRT status code.
5137 * @param pSession Session data.
5138 * @param uPtr Pointer to memory. This is matched against both the R0 and R3 addresses.
5139 * @param eType Memory type.
5140 */
5141static int supdrvMemRelease(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, SUPDRVMEMREFTYPE eType)
5142{
5143 PSUPDRVBUNDLE pBundle;
5144
5145 /*
5146 * Validate input.
5147 */
5148 if (!uPtr)
5149 {
5150 Log(("Illegal address %p\n", (void *)uPtr));
5151 return VERR_INVALID_PARAMETER;
5152 }
5153
5154 /*
5155 * Search for the address.
5156 */
5157 RTSpinlockAcquire(pSession->Spinlock);
5158 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
5159 {
5160 if (pBundle->cUsed > 0)
5161 {
5162 unsigned i;
5163 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
5164 {
5165 if ( pBundle->aMem[i].eType == eType
5166 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
5167 && ( (RTHCUINTPTR)RTR0MemObjAddress(pBundle->aMem[i].MemObj) == uPtr
5168 || ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
5169 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == uPtr))
5170 )
5171 {
5172 /* Make a copy of it and release it outside the spinlock. */
5173 SUPDRVMEMREF Mem = pBundle->aMem[i];
5174 pBundle->aMem[i].eType = MEMREF_TYPE_UNUSED;
5175 pBundle->aMem[i].MemObj = NIL_RTR0MEMOBJ;
5176 pBundle->aMem[i].MapObjR3 = NIL_RTR0MEMOBJ;
5177 RTSpinlockRelease(pSession->Spinlock);
5178
5179 if (Mem.MapObjR3 != NIL_RTR0MEMOBJ)
5180 {
5181 int rc = RTR0MemObjFree(Mem.MapObjR3, false);
5182 AssertRC(rc); /** @todo figure out how to handle this. */
5183 }
5184 if (Mem.MemObj != NIL_RTR0MEMOBJ)
5185 {
5186 int rc = RTR0MemObjFree(Mem.MemObj, true /* fFreeMappings */);
5187 AssertRC(rc); /** @todo figure out how to handle this. */
5188 }
5189 return VINF_SUCCESS;
5190 }
5191 }
5192 }
5193 }
5194 RTSpinlockRelease(pSession->Spinlock);
5195 Log(("Failed to find %p!!! (eType=%d)\n", (void *)uPtr, eType));
5196 return VERR_INVALID_PARAMETER;
5197}
5198
5199
5200/**
5201 * Opens an image. If it's the first time it's opened the call must upload
5202 * the bits using the supdrvIOCtl_LdrLoad() / SUPDRV_IOCTL_LDR_LOAD function.
5203 *
5204 * This is the 1st step of the loading.
5205 *
5206 * @returns IPRT status code.
5207 * @param pDevExt Device globals.
5208 * @param pSession Session data.
5209 * @param pReq The open request.
5210 */
5211static int supdrvIOCtl_LdrOpen(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDROPEN pReq)
5212{
5213 int rc;
5214 PSUPDRVLDRIMAGE pImage;
5215 void *pv;
5216 size_t cchName = strlen(pReq->u.In.szName); /* (caller checked < 32). */
5217 SUPDRV_CHECK_SMAP_SETUP();
5218 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5219 LogFlow(("supdrvIOCtl_LdrOpen: szName=%s cbImageWithEverything=%d\n", pReq->u.In.szName, pReq->u.In.cbImageWithEverything));
5220
5221 /*
5222 * Check if we got an instance of the image already.
5223 */
5224 supdrvLdrLock(pDevExt);
5225 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5226 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
5227 {
5228 if ( pImage->szName[cchName] == '\0'
5229 && !memcmp(pImage->szName, pReq->u.In.szName, cchName))
5230 {
5231 /** @todo Add an _1M (or something) per session reference. */
5232 if (RT_LIKELY(pImage->cImgUsage < UINT32_MAX / 2U))
5233 {
5234 /** @todo check cbImageBits and cbImageWithEverything here, if they differs
5235 * that indicates that the images are different. */
5236 pReq->u.Out.pvImageBase = pImage->pvImage;
5237 pReq->u.Out.fNeedsLoading = pImage->uState == SUP_IOCTL_LDR_OPEN;
5238 pReq->u.Out.fNativeLoader = pImage->fNative;
5239 supdrvLdrAddUsage(pDevExt, pSession, pImage, true /*fRing3Usage*/);
5240 supdrvLdrUnlock(pDevExt);
5241 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5242 return VINF_SUCCESS;
5243 }
5244 supdrvLdrUnlock(pDevExt);
5245 Log(("supdrvIOCtl_LdrOpen: Too many existing references to '%s'!\n", pReq->u.In.szName));
5246 return VERR_TOO_MANY_REFERENCES;
5247 }
5248 }
5249 /* (not found - add it!) */
5250
5251 /* If the loader interface is locked down, make userland fail early */
5252 if (pDevExt->fLdrLockedDown)
5253 {
5254 supdrvLdrUnlock(pDevExt);
5255 Log(("supdrvIOCtl_LdrOpen: Not adding '%s' to image list, loader interface is locked down!\n", pReq->u.In.szName));
5256 return VERR_PERMISSION_DENIED;
5257 }
5258
5259 /* Stop if caller doesn't wish to prepare loading things. */
5260 if (!pReq->u.In.cbImageBits)
5261 {
5262 supdrvLdrUnlock(pDevExt);
5263 Log(("supdrvIOCtl_LdrOpen: Returning VERR_MODULE_NOT_FOUND for '%s'!\n", pReq->u.In.szName));
5264 return VERR_MODULE_NOT_FOUND;
5265 }
5266
5267 /*
5268 * Allocate memory.
5269 */
5270 Assert(cchName < sizeof(pImage->szName));
5271 pv = RTMemAllocZ(sizeof(SUPDRVLDRIMAGE));
5272 if (!pv)
5273 {
5274 supdrvLdrUnlock(pDevExt);
5275 Log(("supdrvIOCtl_LdrOpen: RTMemAllocZ() failed\n"));
5276 return VERR_NO_MEMORY;
5277 }
5278 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5279
5280 /*
5281 * Setup and link in the LDR stuff.
5282 */
5283 pImage = (PSUPDRVLDRIMAGE)pv;
5284 pImage->pvImage = NULL;
5285#ifdef SUPDRV_USE_MEMOBJ_FOR_LDR_IMAGE
5286 pImage->hMemObjImage = NIL_RTR0MEMOBJ;
5287#else
5288 pImage->pvImageAlloc = NULL;
5289#endif
5290 pImage->cbImageWithEverything = pReq->u.In.cbImageWithEverything;
5291 pImage->cbImageBits = pReq->u.In.cbImageBits;
5292 pImage->cSymbols = 0;
5293 pImage->paSymbols = NULL;
5294 pImage->pachStrTab = NULL;
5295 pImage->cbStrTab = 0;
5296 pImage->cSegments = 0;
5297 pImage->paSegments = NULL;
5298 pImage->pfnModuleInit = NULL;
5299 pImage->pfnModuleTerm = NULL;
5300 pImage->pfnServiceReqHandler = NULL;
5301 pImage->uState = SUP_IOCTL_LDR_OPEN;
5302 pImage->cImgUsage = 0; /* Increased by supdrvLdrAddUsage later */
5303 pImage->pDevExt = pDevExt;
5304 pImage->pImageImport = NULL;
5305 pImage->uMagic = SUPDRVLDRIMAGE_MAGIC;
5306 pImage->pWrappedModInfo = NULL;
5307 memcpy(pImage->szName, pReq->u.In.szName, cchName + 1);
5308
5309 /*
5310 * Try load it using the native loader, if that isn't supported, fall back
5311 * on the older method.
5312 */
5313 pImage->fNative = true;
5314 rc = supdrvOSLdrOpen(pDevExt, pImage, pReq->u.In.szFilename);
5315 if (rc == VERR_NOT_SUPPORTED)
5316 {
5317#ifdef SUPDRV_USE_MEMOBJ_FOR_LDR_IMAGE
5318 rc = RTR0MemObjAllocPage(&pImage->hMemObjImage, pImage->cbImageBits, true /*fExecutable*/);
5319 if (RT_SUCCESS(rc))
5320 {
5321 pImage->pvImage = RTR0MemObjAddress(pImage->hMemObjImage);
5322 pImage->fNative = false;
5323 }
5324#else
5325 pImage->pvImageAlloc = RTMemExecAlloc(pImage->cbImageBits + 31);
5326 pImage->pvImage = RT_ALIGN_P(pImage->pvImageAlloc, 32);
5327 pImage->fNative = false;
5328 rc = pImage->pvImageAlloc ? VINF_SUCCESS : VERR_NO_EXEC_MEMORY;
5329#endif
5330 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5331 }
5332 if (RT_SUCCESS(rc))
5333 rc = supdrvLdrAddUsage(pDevExt, pSession, pImage, true /*fRing3Usage*/);
5334 if (RT_FAILURE(rc))
5335 {
5336 supdrvLdrUnlock(pDevExt);
5337 pImage->uMagic = SUPDRVLDRIMAGE_MAGIC_DEAD;
5338 RTMemFree(pImage);
5339 Log(("supdrvIOCtl_LdrOpen(%s): failed - %Rrc\n", pReq->u.In.szName, rc));
5340 return rc;
5341 }
5342 Assert(RT_VALID_PTR(pImage->pvImage) || RT_FAILURE(rc));
5343
5344 /*
5345 * Link it.
5346 */
5347 pImage->pNext = pDevExt->pLdrImages;
5348 pDevExt->pLdrImages = pImage;
5349
5350 pReq->u.Out.pvImageBase = pImage->pvImage;
5351 pReq->u.Out.fNeedsLoading = true;
5352 pReq->u.Out.fNativeLoader = pImage->fNative;
5353 supdrvOSLdrNotifyOpened(pDevExt, pImage, pReq->u.In.szFilename);
5354
5355 supdrvLdrUnlock(pDevExt);
5356 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5357 return VINF_SUCCESS;
5358}
5359
5360
5361/**
5362 * Formats a load error message.
5363 *
5364 * @returns @a rc
5365 * @param rc Return code.
5366 * @param pReq The request.
5367 * @param pszFormat The error message format string.
5368 * @param ... Argument to the format string.
5369 */
5370int VBOXCALL supdrvLdrLoadError(int rc, PSUPLDRLOAD pReq, const char *pszFormat, ...)
5371{
5372 va_list va;
5373 va_start(va, pszFormat);
5374 pReq->u.Out.uErrorMagic = SUPLDRLOAD_ERROR_MAGIC;
5375 RTStrPrintfV(pReq->u.Out.szError, sizeof(pReq->u.Out.szError), pszFormat, va);
5376 va_end(va);
5377 Log(("SUP_IOCTL_LDR_LOAD: %s [rc=%Rrc]\n", pReq->u.Out.szError, rc));
5378 return rc;
5379}
5380
5381
5382/**
5383 * Worker that validates a pointer to an image entrypoint.
5384 *
5385 * Calls supdrvLdrLoadError on error.
5386 *
5387 * @returns IPRT status code.
5388 * @param pDevExt The device globals.
5389 * @param pImage The loader image.
5390 * @param pv The pointer into the image.
5391 * @param fMayBeNull Whether it may be NULL.
5392 * @param pszSymbol The entrypoint name or log name. If the symbol is
5393 * capitalized it signifies a specific symbol, otherwise it
5394 * for logging.
5395 * @param pbImageBits The image bits prepared by ring-3.
5396 * @param pReq The request for passing to supdrvLdrLoadError.
5397 *
5398 * @note Will leave the loader lock on failure!
5399 */
5400static int supdrvLdrValidatePointer(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, void *pv, bool fMayBeNull,
5401 const uint8_t *pbImageBits, const char *pszSymbol, PSUPLDRLOAD pReq)
5402{
5403 if (!fMayBeNull || pv)
5404 {
5405 uint32_t iSeg;
5406
5407 /* Must be within the image bits: */
5408 uintptr_t const uRva = (uintptr_t)pv - (uintptr_t)pImage->pvImage;
5409 if (uRva >= pImage->cbImageBits)
5410 {
5411 supdrvLdrUnlock(pDevExt);
5412 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq,
5413 "Invalid entry point address %p given for %s: RVA %#zx, image size %#zx",
5414 pv, pszSymbol, uRva, pImage->cbImageBits);
5415 }
5416
5417 /* Must be in an executable segment: */
5418 for (iSeg = 0; iSeg < pImage->cSegments; iSeg++)
5419 if (uRva - pImage->paSegments[iSeg].off < (uintptr_t)pImage->paSegments[iSeg].cb)
5420 {
5421 if (pImage->paSegments[iSeg].fProt & SUPLDR_PROT_EXEC)
5422 break;
5423 supdrvLdrUnlock(pDevExt);
5424 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq,
5425 "Bad entry point %p given for %s: not executable (seg #%u: %#RX32 LB %#RX32 prot %#x)",
5426 pv, pszSymbol, iSeg, pImage->paSegments[iSeg].off, pImage->paSegments[iSeg].cb,
5427 pImage->paSegments[iSeg].fProt);
5428 }
5429 if (iSeg >= pImage->cSegments)
5430 {
5431 supdrvLdrUnlock(pDevExt);
5432 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq,
5433 "Bad entry point %p given for %s: no matching segment found (RVA %#zx)!",
5434 pv, pszSymbol, uRva);
5435 }
5436
5437 if (pImage->fNative)
5438 {
5439 /** @todo pass pReq along to the native code. */
5440 int rc = supdrvOSLdrValidatePointer(pDevExt, pImage, pv, pbImageBits, pszSymbol);
5441 if (RT_FAILURE(rc))
5442 {
5443 supdrvLdrUnlock(pDevExt);
5444 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq,
5445 "Bad entry point address %p for %s: rc=%Rrc\n", pv, pszSymbol, rc);
5446 }
5447 }
5448 }
5449 return VINF_SUCCESS;
5450}
5451
5452
5453/**
5454 * Loads the image bits.
5455 *
5456 * This is the 2nd step of the loading.
5457 *
5458 * @returns IPRT status code.
5459 * @param pDevExt Device globals.
5460 * @param pSession Session data.
5461 * @param pReq The request.
5462 */
5463static int supdrvIOCtl_LdrLoad(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRLOAD pReq)
5464{
5465 PSUPDRVLDRUSAGE pUsage;
5466 PSUPDRVLDRIMAGE pImage;
5467 PSUPDRVLDRIMAGE pImageImport;
5468 int rc;
5469 SUPDRV_CHECK_SMAP_SETUP();
5470 LogFlow(("supdrvIOCtl_LdrLoad: pvImageBase=%p cbImageWithEverything=%d\n", pReq->u.In.pvImageBase, pReq->u.In.cbImageWithEverything));
5471 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5472
5473 /*
5474 * Find the ldr image.
5475 */
5476 supdrvLdrLock(pDevExt);
5477 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5478
5479 pUsage = pSession->pLdrUsage;
5480 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
5481 pUsage = pUsage->pNext;
5482 if (!pUsage)
5483 {
5484 supdrvLdrUnlock(pDevExt);
5485 return supdrvLdrLoadError(VERR_INVALID_HANDLE, pReq, "Image not found");
5486 }
5487 pImage = pUsage->pImage;
5488
5489 /*
5490 * Validate input.
5491 */
5492 if ( pImage->cbImageWithEverything != pReq->u.In.cbImageWithEverything
5493 || pImage->cbImageBits != pReq->u.In.cbImageBits)
5494 {
5495 supdrvLdrUnlock(pDevExt);
5496 return supdrvLdrLoadError(VERR_INVALID_HANDLE, pReq, "Image size mismatch found: %u(prep) != %u(load) or %u != %u",
5497 pImage->cbImageWithEverything, pReq->u.In.cbImageWithEverything, pImage->cbImageBits, pReq->u.In.cbImageBits);
5498 }
5499
5500 if (pImage->uState != SUP_IOCTL_LDR_OPEN)
5501 {
5502 unsigned uState = pImage->uState;
5503 supdrvLdrUnlock(pDevExt);
5504 if (uState != SUP_IOCTL_LDR_LOAD)
5505 AssertMsgFailed(("SUP_IOCTL_LDR_LOAD: invalid image state %d (%#x)!\n", uState, uState));
5506 pReq->u.Out.uErrorMagic = 0;
5507 return VERR_ALREADY_LOADED;
5508 }
5509
5510 /* If the loader interface is locked down, don't load new images */
5511 if (pDevExt->fLdrLockedDown)
5512 {
5513 supdrvLdrUnlock(pDevExt);
5514 return supdrvLdrLoadError(VERR_PERMISSION_DENIED, pReq, "Loader is locked down");
5515 }
5516
5517 /*
5518 * If the new image is a dependant of VMMR0.r0, resolve it via the
5519 * caller's usage list and make sure it's in ready state.
5520 */
5521 pImageImport = NULL;
5522 if (pReq->u.In.fFlags & SUPLDRLOAD_F_DEP_VMMR0)
5523 {
5524 PSUPDRVLDRUSAGE pUsageDependency = pSession->pLdrUsage;
5525 while (pUsageDependency && pUsageDependency->pImage->pvImage != pDevExt->pvVMMR0)
5526 pUsageDependency = pUsageDependency->pNext;
5527 if (!pUsageDependency || !pDevExt->pvVMMR0)
5528 {
5529 supdrvLdrUnlock(pDevExt);
5530 return supdrvLdrLoadError(VERR_MODULE_NOT_FOUND, pReq, "VMMR0.r0 not loaded by session");
5531 }
5532 pImageImport = pUsageDependency->pImage;
5533 if (pImageImport->uState != SUP_IOCTL_LDR_LOAD)
5534 {
5535 supdrvLdrUnlock(pDevExt);
5536 return supdrvLdrLoadError(VERR_MODULE_NOT_FOUND, pReq, "VMMR0.r0 is not ready (state %#x)", pImageImport->uState);
5537 }
5538 }
5539
5540 /*
5541 * Copy the segments before we start using supdrvLdrValidatePointer for entrypoint validation.
5542 */
5543 pImage->cSegments = pReq->u.In.cSegments;
5544 {
5545 size_t cbSegments = pImage->cSegments * sizeof(SUPLDRSEG);
5546 pImage->paSegments = (PSUPLDRSEG)RTMemDup(&pReq->u.In.abImage[pReq->u.In.offSegments], cbSegments);
5547 if (pImage->paSegments) /* Align the last segment size to avoid upsetting RTR0MemObjProtect. */ /** @todo relax RTR0MemObjProtect */
5548 pImage->paSegments[pImage->cSegments - 1].cb = RT_ALIGN_32(pImage->paSegments[pImage->cSegments - 1].cb, PAGE_SIZE);
5549 else
5550 {
5551 supdrvLdrUnlock(pDevExt);
5552 return supdrvLdrLoadError(VERR_NO_MEMORY, pReq, "Out of memory for segment table: %#x", cbSegments);
5553 }
5554 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5555 }
5556
5557 /*
5558 * Validate entrypoints.
5559 */
5560 switch (pReq->u.In.eEPType)
5561 {
5562 case SUPLDRLOADEP_NOTHING:
5563 break;
5564
5565 case SUPLDRLOADEP_VMMR0:
5566 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0EntryFast, false, pReq->u.In.abImage, "VMMR0EntryFast", pReq);
5567 if (RT_FAILURE(rc))
5568 return rc;
5569 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0EntryEx, false, pReq->u.In.abImage, "VMMR0EntryEx", pReq);
5570 if (RT_FAILURE(rc))
5571 return rc;
5572
5573 /* Fail here if there is already a VMMR0 module. */
5574 if (pDevExt->pvVMMR0 != NULL)
5575 {
5576 supdrvLdrUnlock(pDevExt);
5577 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq, "There is already a VMMR0 module loaded (%p)", pDevExt->pvVMMR0);
5578 }
5579 break;
5580
5581 case SUPLDRLOADEP_SERVICE:
5582 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.Service.pfnServiceReq, false, pReq->u.In.abImage, "pfnServiceReq", pReq);
5583 if (RT_FAILURE(rc))
5584 return rc;
5585 if ( pReq->u.In.EP.Service.apvReserved[0] != NIL_RTR0PTR
5586 || pReq->u.In.EP.Service.apvReserved[1] != NIL_RTR0PTR
5587 || pReq->u.In.EP.Service.apvReserved[2] != NIL_RTR0PTR)
5588 {
5589 supdrvLdrUnlock(pDevExt);
5590 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq, "apvReserved={%p,%p,%p} MBZ!",
5591 pReq->u.In.EP.Service.apvReserved[0], pReq->u.In.EP.Service.apvReserved[1],
5592 pReq->u.In.EP.Service.apvReserved[2]);
5593 }
5594 break;
5595
5596 default:
5597 supdrvLdrUnlock(pDevExt);
5598 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq, "Invalid eEPType=%d", pReq->u.In.eEPType);
5599 }
5600
5601 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.pfnModuleInit, true, pReq->u.In.abImage, "ModuleInit", pReq);
5602 if (RT_FAILURE(rc))
5603 return rc;
5604 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.pfnModuleTerm, true, pReq->u.In.abImage, "ModuleTerm", pReq);
5605 if (RT_FAILURE(rc))
5606 return rc;
5607 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5608
5609 /*
5610 * Allocate and copy the tables if non-native.
5611 * (No need to do try/except as this is a buffered request.)
5612 */
5613 if (!pImage->fNative)
5614 {
5615 pImage->cbStrTab = pReq->u.In.cbStrTab;
5616 if (pImage->cbStrTab)
5617 {
5618 pImage->pachStrTab = (char *)RTMemDup(&pReq->u.In.abImage[pReq->u.In.offStrTab], pImage->cbStrTab);
5619 if (!pImage->pachStrTab)
5620 rc = supdrvLdrLoadError(VERR_NO_MEMORY, pReq, "Out of memory for string table: %#x", pImage->cbStrTab);
5621 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5622 }
5623
5624 pImage->cSymbols = pReq->u.In.cSymbols;
5625 if (RT_SUCCESS(rc) && pImage->cSymbols)
5626 {
5627 size_t cbSymbols = pImage->cSymbols * sizeof(SUPLDRSYM);
5628 pImage->paSymbols = (PSUPLDRSYM)RTMemDup(&pReq->u.In.abImage[pReq->u.In.offSymbols], cbSymbols);
5629 if (!pImage->paSymbols)
5630 rc = supdrvLdrLoadError(VERR_NO_MEMORY, pReq, "Out of memory for symbol table: %#x", cbSymbols);
5631 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5632 }
5633 }
5634
5635 /*
5636 * Copy the bits and apply permissions / complete native loading.
5637 */
5638 if (RT_SUCCESS(rc))
5639 {
5640 pImage->uState = SUP_IOCTL_LDR_LOAD;
5641 pImage->pfnModuleInit = (PFNR0MODULEINIT)(uintptr_t)pReq->u.In.pfnModuleInit;
5642 pImage->pfnModuleTerm = (PFNR0MODULETERM)(uintptr_t)pReq->u.In.pfnModuleTerm;
5643
5644 if (pImage->fNative)
5645 rc = supdrvOSLdrLoad(pDevExt, pImage, pReq->u.In.abImage, pReq);
5646 else
5647 {
5648#ifdef SUPDRV_USE_MEMOBJ_FOR_LDR_IMAGE
5649 uint32_t i;
5650 memcpy(pImage->pvImage, &pReq->u.In.abImage[0], pImage->cbImageBits);
5651
5652 for (i = 0; i < pImage->cSegments; i++)
5653 {
5654 rc = RTR0MemObjProtect(pImage->hMemObjImage, pImage->paSegments[i].off, pImage->paSegments[i].cb,
5655 pImage->paSegments[i].fProt);
5656 if (RT_SUCCESS(rc))
5657 continue;
5658 if (rc == VERR_NOT_SUPPORTED)
5659 rc = VINF_SUCCESS;
5660 else
5661 rc = supdrvLdrLoadError(rc, pReq, "RTR0MemObjProtect failed on seg#%u %#RX32 LB %#RX32 fProt=%#x",
5662 i, pImage->paSegments[i].off, pImage->paSegments[i].cb, pImage->paSegments[i].fProt);
5663 break;
5664 }
5665#else
5666 memcpy(pImage->pvImage, &pReq->u.In.abImage[0], pImage->cbImageBits);
5667#endif
5668 Log(("vboxdrv: Loaded '%s' at %p\n", pImage->szName, pImage->pvImage));
5669 }
5670 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5671 }
5672
5673 /*
5674 * On success call the module initialization.
5675 */
5676 LogFlow(("supdrvIOCtl_LdrLoad: pfnModuleInit=%p\n", pImage->pfnModuleInit));
5677 if (RT_SUCCESS(rc) && pImage->pfnModuleInit)
5678 {
5679 Log(("supdrvIOCtl_LdrLoad: calling pfnModuleInit=%p\n", pImage->pfnModuleInit));
5680 pDevExt->pLdrInitImage = pImage;
5681 pDevExt->hLdrInitThread = RTThreadNativeSelf();
5682 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5683 rc = pImage->pfnModuleInit(pImage);
5684 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5685 pDevExt->pLdrInitImage = NULL;
5686 pDevExt->hLdrInitThread = NIL_RTNATIVETHREAD;
5687 if (RT_FAILURE(rc))
5688 supdrvLdrLoadError(rc, pReq, "ModuleInit failed: %Rrc", rc);
5689 }
5690 if (RT_SUCCESS(rc))
5691 {
5692 /*
5693 * Publish any standard entry points.
5694 */
5695 switch (pReq->u.In.eEPType)
5696 {
5697 case SUPLDRLOADEP_VMMR0:
5698 Assert(!pDevExt->pvVMMR0);
5699 Assert(!pDevExt->pfnVMMR0EntryFast);
5700 Assert(!pDevExt->pfnVMMR0EntryEx);
5701 ASMAtomicWritePtrVoid(&pDevExt->pvVMMR0, pImage->pvImage);
5702 ASMAtomicWritePtrVoid((void * volatile *)(uintptr_t)&pDevExt->pfnVMMR0EntryFast,
5703 (void *)(uintptr_t) pReq->u.In.EP.VMMR0.pvVMMR0EntryFast);
5704 ASMAtomicWritePtrVoid((void * volatile *)(uintptr_t)&pDevExt->pfnVMMR0EntryEx,
5705 (void *)(uintptr_t) pReq->u.In.EP.VMMR0.pvVMMR0EntryEx);
5706 break;
5707 case SUPLDRLOADEP_SERVICE:
5708 pImage->pfnServiceReqHandler = (PFNSUPR0SERVICEREQHANDLER)(uintptr_t)pReq->u.In.EP.Service.pfnServiceReq;
5709 break;
5710 default:
5711 break;
5712 }
5713
5714 /*
5715 * Increase the usage counter of any imported image.
5716 */
5717 if (pImageImport)
5718 {
5719 pImageImport->cImgUsage++;
5720 if (pImageImport->cImgUsage == 2 && pImageImport->pWrappedModInfo)
5721 supdrvOSLdrRetainWrapperModule(pDevExt, pImageImport);
5722 pImage->pImageImport = pImageImport;
5723 }
5724
5725 /*
5726 * Done!
5727 */
5728 SUPR0Printf("vboxdrv: %RKv %s\n", pImage->pvImage, pImage->szName);
5729 pReq->u.Out.uErrorMagic = 0;
5730 pReq->u.Out.szError[0] = '\0';
5731 }
5732 else
5733 {
5734 /* Inform the tracing component in case ModuleInit registered TPs. */
5735 supdrvTracerModuleUnloading(pDevExt, pImage);
5736
5737 pImage->uState = SUP_IOCTL_LDR_OPEN;
5738 pImage->pfnModuleInit = NULL;
5739 pImage->pfnModuleTerm = NULL;
5740 pImage->pfnServiceReqHandler= NULL;
5741 pImage->cbStrTab = 0;
5742 RTMemFree(pImage->pachStrTab);
5743 pImage->pachStrTab = NULL;
5744 RTMemFree(pImage->paSymbols);
5745 pImage->paSymbols = NULL;
5746 pImage->cSymbols = 0;
5747 }
5748
5749 supdrvLdrUnlock(pDevExt);
5750 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5751 return rc;
5752}
5753
5754
5755/**
5756 * Registers a .r0 module wrapped in a native one and manually loaded.
5757 *
5758 * @returns VINF_SUCCESS or error code (no info statuses).
5759 * @param pDevExt Device globals.
5760 * @param pWrappedModInfo The wrapped module info.
5761 * @param pvNative OS specific information.
5762 * @param phMod Where to store the module handle.
5763 */
5764int VBOXCALL supdrvLdrRegisterWrappedModule(PSUPDRVDEVEXT pDevExt, PCSUPLDRWRAPPEDMODULE pWrappedModInfo,
5765 void *pvNative, void **phMod)
5766{
5767 size_t cchName;
5768 PSUPDRVLDRIMAGE pImage;
5769 PCSUPLDRWRAPMODSYMBOL paSymbols;
5770 uint16_t idx;
5771 const char *pszPrevSymbol;
5772 int rc;
5773 SUPDRV_CHECK_SMAP_SETUP();
5774 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5775
5776 /*
5777 * Validate input.
5778 */
5779 AssertPtrReturn(phMod, VERR_INVALID_POINTER);
5780 *phMod = NULL;
5781 AssertPtrReturn(pDevExt, VERR_INTERNAL_ERROR_2);
5782
5783 AssertPtrReturn(pWrappedModInfo, VERR_INVALID_POINTER);
5784 AssertMsgReturn(pWrappedModInfo->uMagic == SUPLDRWRAPPEDMODULE_MAGIC,
5785 ("uMagic=%#x, expected %#x\n", pWrappedModInfo->uMagic, SUPLDRWRAPPEDMODULE_MAGIC),
5786 VERR_INVALID_MAGIC);
5787 AssertMsgReturn(pWrappedModInfo->uVersion == SUPLDRWRAPPEDMODULE_VERSION,
5788 ("Unsupported uVersion=%#x, current version %#x\n", pWrappedModInfo->uVersion, SUPLDRWRAPPEDMODULE_VERSION),
5789 VERR_VERSION_MISMATCH);
5790 AssertMsgReturn(pWrappedModInfo->uEndMagic == SUPLDRWRAPPEDMODULE_MAGIC,
5791 ("uEndMagic=%#x, expected %#x\n", pWrappedModInfo->uEndMagic, SUPLDRWRAPPEDMODULE_MAGIC),
5792 VERR_INVALID_MAGIC);
5793 AssertMsgReturn(pWrappedModInfo->fFlags <= SUPLDRWRAPPEDMODULE_F_VMMR0, ("Unknown flags in: %#x\n", pWrappedModInfo->fFlags),
5794 VERR_INVALID_FLAGS);
5795
5796 /* szName: */
5797 AssertReturn(RTStrEnd(pWrappedModInfo->szName, sizeof(pWrappedModInfo->szName)) != NULL, VERR_INVALID_NAME);
5798 AssertReturn(supdrvIsLdrModuleNameValid(pWrappedModInfo->szName), VERR_INVALID_NAME);
5799 AssertCompile(sizeof(pImage->szName) == sizeof(pWrappedModInfo->szName));
5800 cchName = strlen(pWrappedModInfo->szName);
5801
5802 /* Image range: */
5803 AssertPtrReturn(pWrappedModInfo->pvImageStart, VERR_INVALID_POINTER);
5804 AssertPtrReturn(pWrappedModInfo->pvImageEnd, VERR_INVALID_POINTER);
5805 AssertReturn((uintptr_t)pWrappedModInfo->pvImageEnd > (uintptr_t)pWrappedModInfo->pvImageStart, VERR_INVALID_PARAMETER);
5806
5807 /* Symbol table: */
5808 AssertMsgReturn(pWrappedModInfo->cSymbols <= _8K, ("Too many symbols: %u, max 8192\n", pWrappedModInfo->cSymbols),
5809 VERR_TOO_MANY_SYMLINKS);
5810 pszPrevSymbol = "\x7f";
5811 paSymbols = pWrappedModInfo->paSymbols;
5812 idx = pWrappedModInfo->cSymbols;
5813 while (idx-- > 0)
5814 {
5815 const char *pszSymbol = paSymbols[idx].pszSymbol;
5816 AssertMsgReturn(RT_VALID_PTR(pszSymbol) && RT_VALID_PTR(paSymbols[idx].pfnValue),
5817 ("paSymbols[%u]: %p/%p\n", idx, pszSymbol, paSymbols[idx].pfnValue),
5818 VERR_INVALID_POINTER);
5819 AssertReturn(*pszSymbol != '\0', VERR_EMPTY_STRING);
5820 AssertMsgReturn(strcmp(pszSymbol, pszPrevSymbol) < 0,
5821 ("symbol table out of order at index %u: '%s' vs '%s'\n", idx, pszSymbol, pszPrevSymbol),
5822 VERR_WRONG_ORDER);
5823 pszPrevSymbol = pszSymbol;
5824 }
5825
5826 /* Standard entry points: */
5827 AssertPtrNullReturn(pWrappedModInfo->pfnModuleInit, VERR_INVALID_POINTER);
5828 AssertPtrNullReturn(pWrappedModInfo->pfnModuleTerm, VERR_INVALID_POINTER);
5829 AssertReturn((uintptr_t)pWrappedModInfo->pfnModuleInit != (uintptr_t)pWrappedModInfo->pfnModuleTerm || pWrappedModInfo->pfnModuleInit == NULL,
5830 VERR_INVALID_PARAMETER);
5831 if (pWrappedModInfo->fFlags & SUPLDRWRAPPEDMODULE_F_VMMR0)
5832 {
5833 AssertReturn(pWrappedModInfo->pfnServiceReqHandler == NULL, VERR_INVALID_PARAMETER);
5834 AssertPtrReturn(pWrappedModInfo->pfnVMMR0EntryFast, VERR_INVALID_POINTER);
5835 AssertPtrReturn(pWrappedModInfo->pfnVMMR0EntryEx, VERR_INVALID_POINTER);
5836 AssertReturn(pWrappedModInfo->pfnVMMR0EntryFast != pWrappedModInfo->pfnVMMR0EntryEx, VERR_INVALID_PARAMETER);
5837 }
5838 else
5839 {
5840 AssertPtrNullReturn(pWrappedModInfo->pfnServiceReqHandler, VERR_INVALID_POINTER);
5841 AssertReturn(pWrappedModInfo->pfnVMMR0EntryFast == NULL, VERR_INVALID_PARAMETER);
5842 AssertReturn(pWrappedModInfo->pfnVMMR0EntryEx == NULL, VERR_INVALID_PARAMETER);
5843 }
5844
5845 /*
5846 * Check if we got an instance of the image already.
5847 */
5848 supdrvLdrLock(pDevExt);
5849 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5850 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
5851 {
5852 if ( pImage->szName[cchName] == '\0'
5853 && !memcmp(pImage->szName, pWrappedModInfo->szName, cchName))
5854 {
5855 supdrvLdrUnlock(pDevExt);
5856 Log(("supdrvLdrRegisterWrappedModule: '%s' already loaded!\n", pWrappedModInfo->szName));
5857 return VERR_ALREADY_LOADED;
5858 }
5859 }
5860 /* (not found - add it!) */
5861
5862 /* If the loader interface is locked down, make userland fail early */
5863 if (pDevExt->fLdrLockedDown)
5864 {
5865 supdrvLdrUnlock(pDevExt);
5866 Log(("supdrvLdrRegisterWrappedModule: Not adding '%s' to image list, loader interface is locked down!\n", pWrappedModInfo->szName));
5867 return VERR_PERMISSION_DENIED;
5868 }
5869
5870 /* Only one VMMR0: */
5871 if ( pDevExt->pvVMMR0 != NULL
5872 && (pWrappedModInfo->fFlags & SUPLDRWRAPPEDMODULE_F_VMMR0))
5873 {
5874 supdrvLdrUnlock(pDevExt);
5875 Log(("supdrvLdrRegisterWrappedModule: Rejecting '%s' as we already got a VMMR0 module!\n", pWrappedModInfo->szName));
5876 return VERR_ALREADY_EXISTS;
5877 }
5878
5879 /*
5880 * Allocate memory.
5881 */
5882 Assert(cchName < sizeof(pImage->szName));
5883 pImage = (PSUPDRVLDRIMAGE)RTMemAllocZ(sizeof(SUPDRVLDRIMAGE));
5884 if (!pImage)
5885 {
5886 supdrvLdrUnlock(pDevExt);
5887 Log(("supdrvLdrRegisterWrappedModule: RTMemAllocZ() failed\n"));
5888 return VERR_NO_MEMORY;
5889 }
5890 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5891
5892 /*
5893 * Setup and link in the LDR stuff.
5894 */
5895 pImage->pvImage = (void *)pWrappedModInfo->pvImageStart;
5896#ifdef SUPDRV_USE_MEMOBJ_FOR_LDR_IMAGE
5897 pImage->hMemObjImage = NIL_RTR0MEMOBJ;
5898#else
5899 pImage->pvImageAlloc = NULL;
5900#endif
5901 pImage->cbImageWithEverything
5902 = pImage->cbImageBits = (uintptr_t)pWrappedModInfo->pvImageEnd - (uintptr_t)pWrappedModInfo->pvImageStart;
5903 pImage->cSymbols = 0;
5904 pImage->paSymbols = NULL;
5905 pImage->pachStrTab = NULL;
5906 pImage->cbStrTab = 0;
5907 pImage->cSegments = 0;
5908 pImage->paSegments = NULL;
5909 pImage->pfnModuleInit = pWrappedModInfo->pfnModuleInit;
5910 pImage->pfnModuleTerm = pWrappedModInfo->pfnModuleTerm;
5911 pImage->pfnServiceReqHandler = NULL; /* Only setting this after module init */
5912 pImage->uState = SUP_IOCTL_LDR_LOAD;
5913 pImage->cImgUsage = 1; /* Held by the wrapper module till unload. */
5914 pImage->pDevExt = pDevExt;
5915 pImage->pImageImport = NULL;
5916 pImage->uMagic = SUPDRVLDRIMAGE_MAGIC;
5917 pImage->pWrappedModInfo = pWrappedModInfo;
5918 pImage->pvWrappedNative = pvNative;
5919 pImage->fNative = true;
5920 memcpy(pImage->szName, pWrappedModInfo->szName, cchName + 1);
5921
5922 /*
5923 * Link it.
5924 */
5925 pImage->pNext = pDevExt->pLdrImages;
5926 pDevExt->pLdrImages = pImage;
5927
5928 /*
5929 * Call module init function if found.
5930 */
5931 rc = VINF_SUCCESS;
5932 if (pImage->pfnModuleInit)
5933 {
5934 Log(("supdrvIOCtl_LdrLoad: calling pfnModuleInit=%p\n", pImage->pfnModuleInit));
5935 pDevExt->pLdrInitImage = pImage;
5936 pDevExt->hLdrInitThread = RTThreadNativeSelf();
5937 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5938 rc = pImage->pfnModuleInit(pImage);
5939 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5940 pDevExt->pLdrInitImage = NULL;
5941 pDevExt->hLdrInitThread = NIL_RTNATIVETHREAD;
5942 }
5943 if (RT_SUCCESS(rc))
5944 {
5945 /*
5946 * Update entry points.
5947 */
5948 if (pWrappedModInfo->fFlags & SUPLDRWRAPPEDMODULE_F_VMMR0)
5949 {
5950 Assert(!pDevExt->pvVMMR0);
5951 Assert(!pDevExt->pfnVMMR0EntryFast);
5952 Assert(!pDevExt->pfnVMMR0EntryEx);
5953 ASMAtomicWritePtrVoid(&pDevExt->pvVMMR0, pImage->pvImage);
5954 ASMAtomicWritePtrVoid((void * volatile *)(uintptr_t)&pDevExt->pfnVMMR0EntryFast,
5955 (void *)(uintptr_t) pWrappedModInfo->pfnVMMR0EntryFast);
5956 ASMAtomicWritePtrVoid((void * volatile *)(uintptr_t)&pDevExt->pfnVMMR0EntryEx,
5957 (void *)(uintptr_t) pWrappedModInfo->pfnVMMR0EntryEx);
5958 }
5959 else
5960 pImage->pfnServiceReqHandler = pWrappedModInfo->pfnServiceReqHandler;
5961#ifdef IN_RING3
5962# error "WTF?"
5963#endif
5964 *phMod = pImage;
5965 }
5966 else
5967 {
5968 /*
5969 * Module init failed - bail, no module term callout.
5970 */
5971 SUPR0Printf("ModuleInit failed for '%s': %Rrc\n", pImage->szName, rc);
5972
5973 pImage->pfnModuleTerm = NULL;
5974 pImage->uState = SUP_IOCTL_LDR_OPEN;
5975 supdrvLdrFree(pDevExt, pImage);
5976 }
5977
5978 supdrvLdrUnlock(pDevExt);
5979 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5980 return VINF_SUCCESS;
5981}
5982
5983
5984/**
5985 * Decrements SUPDRVLDRIMAGE::cImgUsage when two or greater.
5986 *
5987 * @param pDevExt Device globals.
5988 * @param pImage The image.
5989 * @param cReference Number of references being removed.
5990 */
5991DECLINLINE(void) supdrvLdrSubtractUsage(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, uint32_t cReference)
5992{
5993 Assert(cReference > 0);
5994 Assert(pImage->cImgUsage > cReference);
5995 pImage->cImgUsage -= cReference;
5996 if (pImage->cImgUsage == 1 && pImage->pWrappedModInfo)
5997 supdrvOSLdrReleaseWrapperModule(pDevExt, pImage);
5998}
5999
6000
6001/**
6002 * Frees a previously loaded (prep'ed) image.
6003 *
6004 * @returns IPRT status code.
6005 * @param pDevExt Device globals.
6006 * @param pSession Session data.
6007 * @param pReq The request.
6008 */
6009static int supdrvIOCtl_LdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRFREE pReq)
6010{
6011 int rc;
6012 PSUPDRVLDRUSAGE pUsagePrev;
6013 PSUPDRVLDRUSAGE pUsage;
6014 PSUPDRVLDRIMAGE pImage;
6015 LogFlow(("supdrvIOCtl_LdrFree: pvImageBase=%p\n", pReq->u.In.pvImageBase));
6016
6017 /*
6018 * Find the ldr image.
6019 */
6020 supdrvLdrLock(pDevExt);
6021 pUsagePrev = NULL;
6022 pUsage = pSession->pLdrUsage;
6023 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
6024 {
6025 pUsagePrev = pUsage;
6026 pUsage = pUsage->pNext;
6027 }
6028 if (!pUsage)
6029 {
6030 supdrvLdrUnlock(pDevExt);
6031 Log(("SUP_IOCTL_LDR_FREE: couldn't find image!\n"));
6032 return VERR_INVALID_HANDLE;
6033 }
6034 if (pUsage->cRing3Usage == 0)
6035 {
6036 supdrvLdrUnlock(pDevExt);
6037 Log(("SUP_IOCTL_LDR_FREE: No ring-3 reference to the image!\n"));
6038 return VERR_CALLER_NO_REFERENCE;
6039 }
6040
6041 /*
6042 * Check if we can remove anything.
6043 */
6044 rc = VINF_SUCCESS;
6045 pImage = pUsage->pImage;
6046 Log(("SUP_IOCTL_LDR_FREE: pImage=%p %s cImgUsage=%d r3=%d r0=%u\n",
6047 pImage, pImage->szName, pImage->cImgUsage, pUsage->cRing3Usage, pUsage->cRing0Usage));
6048 if (pImage->cImgUsage <= 1 || pUsage->cRing3Usage + pUsage->cRing0Usage <= 1)
6049 {
6050 /*
6051 * Check if there are any objects with destructors in the image, if
6052 * so leave it for the session cleanup routine so we get a chance to
6053 * clean things up in the right order and not leave them all dangling.
6054 */
6055 RTSpinlockAcquire(pDevExt->Spinlock);
6056 if (pImage->cImgUsage <= 1)
6057 {
6058 PSUPDRVOBJ pObj;
6059 for (pObj = pDevExt->pObjs; pObj; pObj = pObj->pNext)
6060 if (RT_UNLIKELY((uintptr_t)pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
6061 {
6062 rc = VERR_DANGLING_OBJECTS;
6063 break;
6064 }
6065 }
6066 else
6067 {
6068 PSUPDRVUSAGE pGenUsage;
6069 for (pGenUsage = pSession->pUsage; pGenUsage; pGenUsage = pGenUsage->pNext)
6070 if (RT_UNLIKELY((uintptr_t)pGenUsage->pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
6071 {
6072 rc = VERR_DANGLING_OBJECTS;
6073 break;
6074 }
6075 }
6076 RTSpinlockRelease(pDevExt->Spinlock);
6077 if (rc == VINF_SUCCESS)
6078 {
6079 /* unlink it */
6080 if (pUsagePrev)
6081 pUsagePrev->pNext = pUsage->pNext;
6082 else
6083 pSession->pLdrUsage = pUsage->pNext;
6084
6085 /* free it */
6086 pUsage->pImage = NULL;
6087 pUsage->pNext = NULL;
6088 RTMemFree(pUsage);
6089
6090 /*
6091 * Dereference the image.
6092 */
6093 if (pImage->cImgUsage <= 1)
6094 supdrvLdrFree(pDevExt, pImage);
6095 else
6096 supdrvLdrSubtractUsage(pDevExt, pImage, 1);
6097 }
6098 else
6099 Log(("supdrvIOCtl_LdrFree: Dangling objects in %p/%s!\n", pImage->pvImage, pImage->szName));
6100 }
6101 else
6102 {
6103 /*
6104 * Dereference both image and usage.
6105 */
6106 pUsage->cRing3Usage--;
6107 supdrvLdrSubtractUsage(pDevExt, pImage, 1);
6108 }
6109
6110 supdrvLdrUnlock(pDevExt);
6111 return rc;
6112}
6113
6114
6115/**
6116 * Deregisters a wrapped .r0 module.
6117 *
6118 * @param pDevExt Device globals.
6119 * @param pWrappedModInfo The wrapped module info.
6120 * @param phMod Where to store the module is stored (NIL'ed on
6121 * success).
6122 */
6123int VBOXCALL supdrvLdrDeregisterWrappedModule(PSUPDRVDEVEXT pDevExt, PCSUPLDRWRAPPEDMODULE pWrappedModInfo, void **phMod)
6124{
6125 PSUPDRVLDRIMAGE pImage;
6126 uint32_t cSleeps;
6127
6128 /*
6129 * Validate input.
6130 */
6131 AssertPtrReturn(pWrappedModInfo, VERR_INVALID_POINTER);
6132 AssertMsgReturn(pWrappedModInfo->uMagic == SUPLDRWRAPPEDMODULE_MAGIC,
6133 ("uMagic=%#x, expected %#x\n", pWrappedModInfo->uMagic, SUPLDRWRAPPEDMODULE_MAGIC),
6134 VERR_INVALID_MAGIC);
6135 AssertMsgReturn(pWrappedModInfo->uEndMagic == SUPLDRWRAPPEDMODULE_MAGIC,
6136 ("uEndMagic=%#x, expected %#x\n", pWrappedModInfo->uEndMagic, SUPLDRWRAPPEDMODULE_MAGIC),
6137 VERR_INVALID_MAGIC);
6138
6139 AssertPtrReturn(phMod, VERR_INVALID_POINTER);
6140 pImage = *(PSUPDRVLDRIMAGE *)phMod;
6141 if (!pImage)
6142 return VINF_SUCCESS;
6143 AssertPtrReturn(pImage, VERR_INVALID_POINTER);
6144 AssertMsgReturn(pImage->uMagic == SUPDRVLDRIMAGE_MAGIC, ("pImage=%p uMagic=%#x\n", pImage, pImage->uMagic),
6145 VERR_INVALID_MAGIC);
6146 AssertMsgReturn(pImage->pvImage == pWrappedModInfo->pvImageStart,
6147 ("pWrappedModInfo(%p)->pvImageStart=%p vs. pImage(=%p)->pvImage=%p\n",
6148 pWrappedModInfo, pWrappedModInfo->pvImageStart, pImage, pImage->pvImage),
6149 VERR_MISMATCH);
6150
6151 AssertPtrReturn(pDevExt, VERR_INVALID_POINTER);
6152
6153 /*
6154 * Try free it, but first we have to wait for its usage count to reach 1 (our).
6155 */
6156 supdrvLdrLock(pDevExt);
6157 for (cSleeps = 0; ; cSleeps++)
6158 {
6159 PSUPDRVLDRIMAGE pCur;
6160
6161 /* Check that the image is in the list. */
6162 for (pCur = pDevExt->pLdrImages; pCur; pCur = pCur->pNext)
6163 if (pCur == pImage)
6164 break;
6165 AssertBreak(pCur == pImage);
6166
6167 /* Anyone still using it? */
6168 if (pImage->cImgUsage <= 1)
6169 break;
6170
6171 /* Someone is using it, wait and check again. */
6172 if (!(cSleeps % 60))
6173 SUPR0Printf("supdrvLdrUnregisterWrappedModule: Still %u users of wrapped image '%s' ...\n",
6174 pImage->cImgUsage, pImage->szName);
6175 supdrvLdrUnlock(pDevExt);
6176 RTThreadSleep(1000);
6177 supdrvLdrLock(pDevExt);
6178 }
6179
6180 /* We're the last 'user', free it. */
6181 supdrvLdrFree(pDevExt, pImage);
6182
6183 supdrvLdrUnlock(pDevExt);
6184
6185 *phMod = NULL;
6186 return VINF_SUCCESS;
6187}
6188
6189
6190/**
6191 * Lock down the image loader interface.
6192 *
6193 * @returns IPRT status code.
6194 * @param pDevExt Device globals.
6195 */
6196static int supdrvIOCtl_LdrLockDown(PSUPDRVDEVEXT pDevExt)
6197{
6198 LogFlow(("supdrvIOCtl_LdrLockDown:\n"));
6199
6200 supdrvLdrLock(pDevExt);
6201 if (!pDevExt->fLdrLockedDown)
6202 {
6203 pDevExt->fLdrLockedDown = true;
6204 Log(("supdrvIOCtl_LdrLockDown: Image loader interface locked down\n"));
6205 }
6206 supdrvLdrUnlock(pDevExt);
6207
6208 return VINF_SUCCESS;
6209}
6210
6211
6212/**
6213 * Worker for getting the address of a symbol in an image.
6214 *
6215 * @returns IPRT status code.
6216 * @param pDevExt Device globals.
6217 * @param pImage The image to search.
6218 * @param pszSymbol The symbol name.
6219 * @param cchSymbol The length of the symbol name.
6220 * @param ppvValue Where to return the symbol
6221 * @note Caller owns the loader lock.
6222 */
6223static int supdrvLdrQuerySymbolWorker(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage,
6224 const char *pszSymbol, size_t cchSymbol, void **ppvValue)
6225{
6226 int rc = VERR_SYMBOL_NOT_FOUND;
6227 if (pImage->fNative && !pImage->pWrappedModInfo)
6228 rc = supdrvOSLdrQuerySymbol(pDevExt, pImage, pszSymbol, cchSymbol, ppvValue);
6229 else if (pImage->fNative && pImage->pWrappedModInfo)
6230 {
6231 PCSUPLDRWRAPMODSYMBOL paSymbols = pImage->pWrappedModInfo->paSymbols;
6232 uint32_t iEnd = pImage->pWrappedModInfo->cSymbols;
6233 uint32_t iStart = 0;
6234 while (iStart < iEnd)
6235 {
6236 uint32_t const i = iStart + (iEnd - iStart) / 2;
6237 int const iDiff = strcmp(paSymbols[i].pszSymbol, pszSymbol);
6238 if (iDiff < 0)
6239 iStart = i + 1;
6240 else if (iDiff > 0)
6241 iEnd = i;
6242 else
6243 {
6244 *ppvValue = (void *)(uintptr_t)paSymbols[i].pfnValue;
6245 rc = VINF_SUCCESS;
6246 break;
6247 }
6248 }
6249#ifdef VBOX_STRICT
6250 if (rc != VINF_SUCCESS)
6251 for (iStart = 0, iEnd = pImage->pWrappedModInfo->cSymbols; iStart < iEnd; iStart++)
6252 Assert(strcmp(paSymbols[iStart].pszSymbol, pszSymbol));
6253#endif
6254 }
6255 else
6256 {
6257 const char *pchStrings = pImage->pachStrTab;
6258 PSUPLDRSYM paSyms = pImage->paSymbols;
6259 uint32_t i;
6260 Assert(!pImage->pWrappedModInfo);
6261 for (i = 0; i < pImage->cSymbols; i++)
6262 {
6263 if ( paSyms[i].offName + cchSymbol + 1 <= pImage->cbStrTab
6264 && !memcmp(pchStrings + paSyms[i].offName, pszSymbol, cchSymbol + 1))
6265 {
6266 /*
6267 * Note! The int32_t is for native loading on solaris where the data
6268 * and text segments are in very different places.
6269 */
6270 *ppvValue = (uint8_t *)pImage->pvImage + (int32_t)paSyms[i].offSymbol;
6271 rc = VINF_SUCCESS;
6272 break;
6273 }
6274 }
6275 }
6276 return rc;
6277}
6278
6279
6280/**
6281 * Queries the address of a symbol in an open image.
6282 *
6283 * @returns IPRT status code.
6284 * @param pDevExt Device globals.
6285 * @param pSession Session data.
6286 * @param pReq The request buffer.
6287 */
6288static int supdrvIOCtl_LdrQuerySymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRGETSYMBOL pReq)
6289{
6290 PSUPDRVLDRIMAGE pImage;
6291 PSUPDRVLDRUSAGE pUsage;
6292 const size_t cchSymbol = strlen(pReq->u.In.szSymbol);
6293 void *pvSymbol = NULL;
6294 int rc;
6295 Log3(("supdrvIOCtl_LdrQuerySymbol: pvImageBase=%p szSymbol=\"%s\"\n", pReq->u.In.pvImageBase, pReq->u.In.szSymbol));
6296
6297 /*
6298 * Find the ldr image.
6299 */
6300 supdrvLdrLock(pDevExt);
6301
6302 pUsage = pSession->pLdrUsage;
6303 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
6304 pUsage = pUsage->pNext;
6305 if (pUsage)
6306 {
6307 pImage = pUsage->pImage;
6308 if (pImage->uState == SUP_IOCTL_LDR_LOAD)
6309 {
6310 /*
6311 * Search the image exports / symbol strings.
6312 */
6313 rc = supdrvLdrQuerySymbolWorker(pDevExt, pImage, pReq->u.In.szSymbol, cchSymbol, &pvSymbol);
6314 }
6315 else
6316 {
6317 Log(("SUP_IOCTL_LDR_GET_SYMBOL: invalid image state %d (%#x)!\n", pImage->uState, pImage->uState));
6318 rc = VERR_WRONG_ORDER;
6319 }
6320 }
6321 else
6322 {
6323 Log(("SUP_IOCTL_LDR_GET_SYMBOL: couldn't find image!\n"));
6324 rc = VERR_INVALID_HANDLE;
6325 }
6326
6327 supdrvLdrUnlock(pDevExt);
6328
6329 pReq->u.Out.pvSymbol = pvSymbol;
6330 return rc;
6331}
6332
6333
6334/**
6335 * Gets the address of a symbol in an open image or the support driver.
6336 *
6337 * @returns VBox status code.
6338 * @param pDevExt Device globals.
6339 * @param pSession Session data.
6340 * @param pReq The request buffer.
6341 */
6342static int supdrvIDC_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVIDCREQGETSYM pReq)
6343{
6344 const char *pszSymbol = pReq->u.In.pszSymbol;
6345 const char *pszModule = pReq->u.In.pszModule;
6346 size_t cchSymbol;
6347 char const *pszEnd;
6348 uint32_t i;
6349 int rc;
6350
6351 /*
6352 * Input validation.
6353 */
6354 AssertPtrReturn(pszSymbol, VERR_INVALID_POINTER);
6355 pszEnd = RTStrEnd(pszSymbol, 512);
6356 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
6357 cchSymbol = pszEnd - pszSymbol;
6358
6359 if (pszModule)
6360 {
6361 AssertPtrReturn(pszModule, VERR_INVALID_POINTER);
6362 pszEnd = RTStrEnd(pszModule, 64);
6363 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
6364 }
6365 Log3(("supdrvIDC_LdrGetSymbol: pszModule=%p:{%s} pszSymbol=%p:{%s}\n", pszModule, pszModule, pszSymbol, pszSymbol));
6366
6367 if ( !pszModule
6368 || !strcmp(pszModule, "SupDrv"))
6369 {
6370 /*
6371 * Search the support driver export table.
6372 */
6373 rc = VERR_SYMBOL_NOT_FOUND;
6374 for (i = 0; i < RT_ELEMENTS(g_aFunctions); i++)
6375 if (!strcmp(g_aFunctions[i].szName, pszSymbol))
6376 {
6377 pReq->u.Out.pfnSymbol = (PFNRT)(uintptr_t)g_aFunctions[i].pfn;
6378 rc = VINF_SUCCESS;
6379 break;
6380 }
6381 }
6382 else
6383 {
6384 /*
6385 * Find the loader image.
6386 */
6387 PSUPDRVLDRIMAGE pImage;
6388
6389 supdrvLdrLock(pDevExt);
6390
6391 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
6392 if (!strcmp(pImage->szName, pszModule))
6393 break;
6394 if (pImage && pImage->uState == SUP_IOCTL_LDR_LOAD)
6395 {
6396 /*
6397 * Search the image exports / symbol strings. Do usage counting on the session.
6398 */
6399 rc = supdrvLdrQuerySymbolWorker(pDevExt, pImage, pszSymbol, cchSymbol, (void **)&pReq->u.Out.pfnSymbol);
6400 if (RT_SUCCESS(rc))
6401 rc = supdrvLdrAddUsage(pDevExt, pSession, pImage, true /*fRing3Usage*/);
6402 }
6403 else
6404 rc = pImage ? VERR_WRONG_ORDER : VERR_MODULE_NOT_FOUND;
6405
6406 supdrvLdrUnlock(pDevExt);
6407 }
6408 return rc;
6409}
6410
6411
6412/**
6413 * Looks up a symbol in g_aFunctions
6414 *
6415 * @returns VINF_SUCCESS on success, VERR_SYMBOL_NOT_FOUND on failure.
6416 * @param pszSymbol The symbol to look up.
6417 * @param puValue Where to return the value.
6418 */
6419int VBOXCALL supdrvLdrGetExportedSymbol(const char *pszSymbol, uintptr_t *puValue)
6420{
6421 uint32_t i;
6422 for (i = 0; i < RT_ELEMENTS(g_aFunctions); i++)
6423 if (!strcmp(g_aFunctions[i].szName, pszSymbol))
6424 {
6425 *puValue = (uintptr_t)g_aFunctions[i].pfn;
6426 return VINF_SUCCESS;
6427 }
6428
6429 if (!strcmp(pszSymbol, "g_SUPGlobalInfoPage"))
6430 {
6431 *puValue = (uintptr_t)g_pSUPGlobalInfoPage;
6432 return VINF_SUCCESS;
6433 }
6434
6435 return VERR_SYMBOL_NOT_FOUND;
6436}
6437
6438
6439/**
6440 * Adds a usage reference in the specified session of an image.
6441 *
6442 * Called while owning the loader semaphore.
6443 *
6444 * @returns VINF_SUCCESS on success and VERR_NO_MEMORY on failure.
6445 * @param pDevExt Pointer to device extension.
6446 * @param pSession Session in question.
6447 * @param pImage Image which the session is using.
6448 * @param fRing3Usage Set if it's ring-3 usage, clear if ring-0.
6449 */
6450static int supdrvLdrAddUsage(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVLDRIMAGE pImage, bool fRing3Usage)
6451{
6452 PSUPDRVLDRUSAGE pUsage;
6453 LogFlow(("supdrvLdrAddUsage: pImage=%p %d\n", pImage, fRing3Usage));
6454
6455 /*
6456 * Referenced it already?
6457 */
6458 pUsage = pSession->pLdrUsage;
6459 while (pUsage)
6460 {
6461 if (pUsage->pImage == pImage)
6462 {
6463 if (fRing3Usage)
6464 pUsage->cRing3Usage++;
6465 else
6466 pUsage->cRing0Usage++;
6467 Assert(pImage->cImgUsage > 1 || !pImage->pWrappedModInfo);
6468 pImage->cImgUsage++;
6469 return VINF_SUCCESS;
6470 }
6471 pUsage = pUsage->pNext;
6472 }
6473
6474 /*
6475 * Allocate new usage record.
6476 */
6477 pUsage = (PSUPDRVLDRUSAGE)RTMemAlloc(sizeof(*pUsage));
6478 AssertReturn(pUsage, VERR_NO_MEMORY);
6479 pUsage->cRing3Usage = fRing3Usage ? 1 : 0;
6480 pUsage->cRing0Usage = fRing3Usage ? 0 : 1;
6481 pUsage->pImage = pImage;
6482 pUsage->pNext = pSession->pLdrUsage;
6483 pSession->pLdrUsage = pUsage;
6484
6485 /*
6486 * Wrapped modules needs to retain a native module reference.
6487 */
6488 pImage->cImgUsage++;
6489 if (pImage->cImgUsage == 2 && pImage->pWrappedModInfo)
6490 supdrvOSLdrRetainWrapperModule(pDevExt, pImage);
6491
6492 return VINF_SUCCESS;
6493}
6494
6495
6496/**
6497 * Frees a load image.
6498 *
6499 * @param pDevExt Pointer to device extension.
6500 * @param pImage Pointer to the image we're gonna free.
6501 * This image must exit!
6502 * @remark The caller MUST own SUPDRVDEVEXT::mtxLdr!
6503 */
6504static void supdrvLdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage)
6505{
6506 unsigned cLoops;
6507 for (cLoops = 0; ; cLoops++)
6508 {
6509 PSUPDRVLDRIMAGE pImagePrev;
6510 PSUPDRVLDRIMAGE pImageImport;
6511 LogFlow(("supdrvLdrFree: pImage=%p %s [loop %u]\n", pImage, pImage->szName, cLoops));
6512 AssertBreak(cLoops < 2);
6513
6514 /*
6515 * Warn if we're releasing images while the image loader interface is
6516 * locked down -- we won't be able to reload them!
6517 */
6518 if (pDevExt->fLdrLockedDown)
6519 Log(("supdrvLdrFree: Warning: unloading '%s' image, while loader interface is locked down!\n", pImage->szName));
6520
6521 /* find it - arg. should've used doubly linked list. */
6522 Assert(pDevExt->pLdrImages);
6523 pImagePrev = NULL;
6524 if (pDevExt->pLdrImages != pImage)
6525 {
6526 pImagePrev = pDevExt->pLdrImages;
6527 while (pImagePrev->pNext != pImage)
6528 pImagePrev = pImagePrev->pNext;
6529 Assert(pImagePrev->pNext == pImage);
6530 }
6531
6532 /* unlink */
6533 if (pImagePrev)
6534 pImagePrev->pNext = pImage->pNext;
6535 else
6536 pDevExt->pLdrImages = pImage->pNext;
6537
6538 /* check if this is VMMR0.r0 unset its entry point pointers. */
6539 if (pDevExt->pvVMMR0 == pImage->pvImage)
6540 {
6541 pDevExt->pvVMMR0 = NULL;
6542 pDevExt->pfnVMMR0EntryFast = NULL;
6543 pDevExt->pfnVMMR0EntryEx = NULL;
6544 }
6545
6546 /* check for objects with destructors in this image. (Shouldn't happen.) */
6547 if (pDevExt->pObjs)
6548 {
6549 unsigned cObjs = 0;
6550 PSUPDRVOBJ pObj;
6551 RTSpinlockAcquire(pDevExt->Spinlock);
6552 for (pObj = pDevExt->pObjs; pObj; pObj = pObj->pNext)
6553 if (RT_UNLIKELY((uintptr_t)pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
6554 {
6555 pObj->pfnDestructor = NULL;
6556 cObjs++;
6557 }
6558 RTSpinlockRelease(pDevExt->Spinlock);
6559 if (cObjs)
6560 OSDBGPRINT(("supdrvLdrFree: Image '%s' has %d dangling objects!\n", pImage->szName, cObjs));
6561 }
6562
6563 /* call termination function if fully loaded. */
6564 if ( pImage->pfnModuleTerm
6565 && pImage->uState == SUP_IOCTL_LDR_LOAD)
6566 {
6567 LogFlow(("supdrvIOCtl_LdrLoad: calling pfnModuleTerm=%p\n", pImage->pfnModuleTerm));
6568 pDevExt->hLdrTermThread = RTThreadNativeSelf();
6569 pImage->pfnModuleTerm(pImage);
6570 pDevExt->hLdrTermThread = NIL_RTNATIVETHREAD;
6571 }
6572
6573 /* Inform the tracing component. */
6574 supdrvTracerModuleUnloading(pDevExt, pImage);
6575
6576 /* Do native unload if appropriate, then inform the native code about the
6577 unloading (mainly for non-native loading case). */
6578 if (pImage->fNative)
6579 supdrvOSLdrUnload(pDevExt, pImage);
6580 supdrvOSLdrNotifyUnloaded(pDevExt, pImage);
6581
6582 /* free the image */
6583 pImage->uMagic = SUPDRVLDRIMAGE_MAGIC_DEAD;
6584 pImage->cImgUsage = 0;
6585 pImage->pDevExt = NULL;
6586 pImage->pNext = NULL;
6587 pImage->uState = SUP_IOCTL_LDR_FREE;
6588#ifdef SUPDRV_USE_MEMOBJ_FOR_LDR_IMAGE
6589 RTR0MemObjFree(pImage->hMemObjImage, true /*fMappings*/);
6590 pImage->hMemObjImage = NIL_RTR0MEMOBJ;
6591#else
6592 RTMemExecFree(pImage->pvImageAlloc, pImage->cbImageBits + 31);
6593 pImage->pvImageAlloc = NULL;
6594#endif
6595 pImage->pvImage = NULL;
6596 RTMemFree(pImage->pachStrTab);
6597 pImage->pachStrTab = NULL;
6598 RTMemFree(pImage->paSymbols);
6599 pImage->paSymbols = NULL;
6600 RTMemFree(pImage->paSegments);
6601 pImage->paSegments = NULL;
6602
6603 pImageImport = pImage->pImageImport;
6604 pImage->pImageImport = NULL;
6605
6606 RTMemFree(pImage);
6607
6608 /*
6609 * Deal with any import image.
6610 */
6611 if (!pImageImport)
6612 break;
6613 if (pImageImport->cImgUsage > 1)
6614 {
6615 supdrvLdrSubtractUsage(pDevExt, pImageImport, 1);
6616 break;
6617 }
6618 pImage = pImageImport;
6619 }
6620}
6621
6622
6623/**
6624 * Acquires the loader lock.
6625 *
6626 * @returns IPRT status code.
6627 * @param pDevExt The device extension.
6628 * @note Not recursive on all platforms yet.
6629 */
6630DECLINLINE(int) supdrvLdrLock(PSUPDRVDEVEXT pDevExt)
6631{
6632#ifdef SUPDRV_USE_MUTEX_FOR_LDR
6633 int rc = RTSemMutexRequest(pDevExt->mtxLdr, RT_INDEFINITE_WAIT);
6634#else
6635 int rc = RTSemFastMutexRequest(pDevExt->mtxLdr);
6636#endif
6637 AssertRC(rc);
6638 return rc;
6639}
6640
6641
6642/**
6643 * Releases the loader lock.
6644 *
6645 * @returns IPRT status code.
6646 * @param pDevExt The device extension.
6647 */
6648DECLINLINE(int) supdrvLdrUnlock(PSUPDRVDEVEXT pDevExt)
6649{
6650#ifdef SUPDRV_USE_MUTEX_FOR_LDR
6651 return RTSemMutexRelease(pDevExt->mtxLdr);
6652#else
6653 return RTSemFastMutexRelease(pDevExt->mtxLdr);
6654#endif
6655}
6656
6657
6658/**
6659 * Acquires the global loader lock.
6660 *
6661 * This can be useful when accessing structures being modified by the ModuleInit
6662 * and ModuleTerm. Use SUPR0LdrUnlock() to unlock.
6663 *
6664 * @returns VBox status code.
6665 * @param pSession The session doing the locking.
6666 *
6667 * @note Cannot be used during ModuleInit or ModuleTerm callbacks.
6668 */
6669SUPR0DECL(int) SUPR0LdrLock(PSUPDRVSESSION pSession)
6670{
6671 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
6672 return supdrvLdrLock(pSession->pDevExt);
6673}
6674SUPR0_EXPORT_SYMBOL(SUPR0LdrLock);
6675
6676
6677/**
6678 * Releases the global loader lock.
6679 *
6680 * Must correspond to a SUPR0LdrLock call!
6681 *
6682 * @returns VBox status code.
6683 * @param pSession The session doing the locking.
6684 *
6685 * @note Cannot be used during ModuleInit or ModuleTerm callbacks.
6686 */
6687SUPR0DECL(int) SUPR0LdrUnlock(PSUPDRVSESSION pSession)
6688{
6689 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
6690 return supdrvLdrUnlock(pSession->pDevExt);
6691}
6692SUPR0_EXPORT_SYMBOL(SUPR0LdrUnlock);
6693
6694
6695/**
6696 * For checking lock ownership in Assert() statements during ModuleInit and
6697 * ModuleTerm.
6698 *
6699 * @returns Whether we own the loader lock or not.
6700 * @param hMod The module in question.
6701 * @param fWantToHear For hosts where it is difficult to know who owns the
6702 * lock, this will be returned instead.
6703 */
6704SUPR0DECL(bool) SUPR0LdrIsLockOwnerByMod(void *hMod, bool fWantToHear)
6705{
6706 PSUPDRVDEVEXT pDevExt;
6707 RTNATIVETHREAD hOwner;
6708
6709 PSUPDRVLDRIMAGE pImage = (PSUPDRVLDRIMAGE)hMod;
6710 AssertPtrReturn(pImage, fWantToHear);
6711 AssertReturn(pImage->uMagic == SUPDRVLDRIMAGE_MAGIC, fWantToHear);
6712
6713 pDevExt = pImage->pDevExt;
6714 AssertPtrReturn(pDevExt, fWantToHear);
6715
6716 /*
6717 * Expecting this to be called at init/term time only, so this will be sufficient.
6718 */
6719 hOwner = pDevExt->hLdrInitThread;
6720 if (hOwner == NIL_RTNATIVETHREAD)
6721 hOwner = pDevExt->hLdrTermThread;
6722 if (hOwner != NIL_RTNATIVETHREAD)
6723 return hOwner == RTThreadNativeSelf();
6724
6725 /*
6726 * Neither of the two semaphore variants currently offers very good
6727 * introspection, so we wing it for now. This API is VBOX_STRICT only.
6728 */
6729#ifdef SUPDRV_USE_MUTEX_FOR_LDR
6730 return RTSemMutexIsOwned(pDevExt->mtxLdr) && fWantToHear;
6731#else
6732 return fWantToHear;
6733#endif
6734}
6735SUPR0_EXPORT_SYMBOL(SUPR0LdrIsLockOwnerByMod);
6736
6737
6738/**
6739 * Locates and retains the given module for ring-0 usage.
6740 *
6741 * @returns VBox status code.
6742 * @param pSession The session to associate the module reference with.
6743 * @param pszName The module name (no path).
6744 * @param phMod Where to return the module handle. The module is
6745 * referenced and a call to SUPR0LdrModRelease() is
6746 * necessary when done with it.
6747 */
6748SUPR0DECL(int) SUPR0LdrModByName(PSUPDRVSESSION pSession, const char *pszName, void **phMod)
6749{
6750 int rc;
6751 size_t cchName;
6752 PSUPDRVDEVEXT pDevExt;
6753
6754 /*
6755 * Validate input.
6756 */
6757 AssertPtrReturn(phMod, VERR_INVALID_POINTER);
6758 *phMod = NULL;
6759 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
6760 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
6761 cchName = strlen(pszName);
6762 AssertReturn(cchName > 0, VERR_EMPTY_STRING);
6763 AssertReturn(cchName < RT_SIZEOFMEMB(SUPDRVLDRIMAGE, szName), VERR_MODULE_NOT_FOUND);
6764
6765 /*
6766 * Do the lookup.
6767 */
6768 pDevExt = pSession->pDevExt;
6769 rc = supdrvLdrLock(pDevExt);
6770 if (RT_SUCCESS(rc))
6771 {
6772 PSUPDRVLDRIMAGE pImage;
6773 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
6774 {
6775 if ( pImage->szName[cchName] == '\0'
6776 && !memcmp(pImage->szName, pszName, cchName))
6777 {
6778 /*
6779 * Check the state and make sure we don't overflow the reference counter before return it.
6780 */
6781 uint32_t uState = pImage->uState;
6782 if (uState == SUP_IOCTL_LDR_LOAD)
6783 {
6784 if (RT_LIKELY(pImage->cImgUsage < UINT32_MAX / 2U))
6785 {
6786 supdrvLdrAddUsage(pDevExt, pSession, pImage, false /*fRing3Usage*/);
6787 *phMod = pImage;
6788 supdrvLdrUnlock(pDevExt);
6789 return VINF_SUCCESS;
6790 }
6791 supdrvLdrUnlock(pDevExt);
6792 Log(("SUPR0LdrModByName: Too many existing references to '%s'!\n", pszName));
6793 return VERR_TOO_MANY_REFERENCES;
6794 }
6795 supdrvLdrUnlock(pDevExt);
6796 Log(("SUPR0LdrModByName: Module '%s' is not in the loaded state (%d)!\n", pszName, uState));
6797 return VERR_INVALID_STATE;
6798 }
6799 }
6800 supdrvLdrUnlock(pDevExt);
6801 Log(("SUPR0LdrModByName: Module '%s' not found!\n", pszName));
6802 rc = VERR_MODULE_NOT_FOUND;
6803 }
6804 return rc;
6805}
6806SUPR0_EXPORT_SYMBOL(SUPR0LdrModByName);
6807
6808
6809/**
6810 * Retains a ring-0 module reference.
6811 *
6812 * Release reference when done by calling SUPR0LdrModRelease().
6813 *
6814 * @returns VBox status code.
6815 * @param pSession The session to reference the module in. A usage
6816 * record is added if needed.
6817 * @param hMod The handle to the module to retain.
6818 */
6819SUPR0DECL(int) SUPR0LdrModRetain(PSUPDRVSESSION pSession, void *hMod)
6820{
6821 PSUPDRVDEVEXT pDevExt;
6822 PSUPDRVLDRIMAGE pImage;
6823 int rc;
6824
6825 /* Validate input a little. */
6826 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
6827 AssertPtrReturn(hMod, VERR_INVALID_HANDLE);
6828 pImage = (PSUPDRVLDRIMAGE)hMod;
6829 AssertReturn(pImage->uMagic == SUPDRVLDRIMAGE_MAGIC, VERR_INVALID_HANDLE);
6830
6831 /* Reference the module: */
6832 pDevExt = pSession->pDevExt;
6833 rc = supdrvLdrLock(pDevExt);
6834 if (RT_SUCCESS(rc))
6835 {
6836 if (pImage->uMagic == SUPDRVLDRIMAGE_MAGIC)
6837 {
6838 if (RT_LIKELY(pImage->cImgUsage < UINT32_MAX / 2U))
6839 rc = supdrvLdrAddUsage(pDevExt, pSession, pImage, false /*fRing3Usage*/);
6840 else
6841 AssertFailedStmt(rc = VERR_TOO_MANY_REFERENCES);
6842 }
6843 else
6844 AssertFailedStmt(rc = VERR_INVALID_HANDLE);
6845 supdrvLdrUnlock(pDevExt);
6846 }
6847 return rc;
6848}
6849SUPR0_EXPORT_SYMBOL(SUPR0LdrModRetain);
6850
6851
6852/**
6853 * Releases a ring-0 module reference retained by SUPR0LdrModByName() or
6854 * SUPR0LdrModRetain().
6855 *
6856 * @returns VBox status code.
6857 * @param pSession The session that the module was retained in.
6858 * @param hMod The module handle. NULL is silently ignored.
6859 */
6860SUPR0DECL(int) SUPR0LdrModRelease(PSUPDRVSESSION pSession, void *hMod)
6861{
6862 PSUPDRVDEVEXT pDevExt;
6863 PSUPDRVLDRIMAGE pImage;
6864 int rc;
6865
6866 /*
6867 * Validate input.
6868 */
6869 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
6870 if (!hMod)
6871 return VINF_SUCCESS;
6872 AssertPtrReturn(hMod, VERR_INVALID_HANDLE);
6873 pImage = (PSUPDRVLDRIMAGE)hMod;
6874 AssertReturn(pImage->uMagic == SUPDRVLDRIMAGE_MAGIC, VERR_INVALID_HANDLE);
6875
6876 /*
6877 * Take the loader lock and revalidate the module:
6878 */
6879 pDevExt = pSession->pDevExt;
6880 rc = supdrvLdrLock(pDevExt);
6881 if (RT_SUCCESS(rc))
6882 {
6883 if (pImage->uMagic == SUPDRVLDRIMAGE_MAGIC)
6884 {
6885 /*
6886 * Find the usage record for the module:
6887 */
6888 PSUPDRVLDRUSAGE pPrevUsage = NULL;
6889 PSUPDRVLDRUSAGE pUsage;
6890
6891 rc = VERR_MODULE_NOT_FOUND;
6892 for (pUsage = pSession->pLdrUsage; pUsage; pUsage = pUsage->pNext)
6893 {
6894 if (pUsage->pImage == pImage)
6895 {
6896 /*
6897 * Drop a ring-0 reference:
6898 */
6899 Assert(pImage->cImgUsage >= pUsage->cRing0Usage + pUsage->cRing3Usage);
6900 if (pUsage->cRing0Usage > 0)
6901 {
6902 if (pImage->cImgUsage > 1)
6903 {
6904 pUsage->cRing0Usage -= 1;
6905 supdrvLdrSubtractUsage(pDevExt, pImage, 1);
6906 rc = VINF_SUCCESS;
6907 }
6908 else
6909 {
6910 Assert(!pImage->pWrappedModInfo /* (The wrapper kmod has the last reference.) */);
6911 supdrvLdrFree(pDevExt, pImage);
6912
6913 if (pPrevUsage)
6914 pPrevUsage->pNext = pUsage->pNext;
6915 else
6916 pSession->pLdrUsage = pUsage->pNext;
6917 pUsage->pNext = NULL;
6918 pUsage->pImage = NULL;
6919 pUsage->cRing0Usage = 0;
6920 pUsage->cRing3Usage = 0;
6921 RTMemFree(pUsage);
6922
6923 rc = VINF_OBJECT_DESTROYED;
6924 }
6925 }
6926 else
6927 AssertFailedStmt(rc = VERR_CALLER_NO_REFERENCE);
6928 break;
6929 }
6930 pPrevUsage = pUsage;
6931 }
6932 }
6933 else
6934 AssertFailedStmt(rc = VERR_INVALID_HANDLE);
6935 supdrvLdrUnlock(pDevExt);
6936 }
6937 return rc;
6938
6939}
6940SUPR0_EXPORT_SYMBOL(SUPR0LdrModRelease);
6941
6942
6943/**
6944 * Implements the service call request.
6945 *
6946 * @returns VBox status code.
6947 * @param pDevExt The device extension.
6948 * @param pSession The calling session.
6949 * @param pReq The request packet, valid.
6950 */
6951static int supdrvIOCtl_CallServiceModule(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPCALLSERVICE pReq)
6952{
6953#if !defined(RT_OS_WINDOWS) || defined(RT_ARCH_AMD64) || defined(DEBUG)
6954 int rc;
6955
6956 /*
6957 * Find the module first in the module referenced by the calling session.
6958 */
6959 rc = supdrvLdrLock(pDevExt);
6960 if (RT_SUCCESS(rc))
6961 {
6962 PFNSUPR0SERVICEREQHANDLER pfnServiceReqHandler = NULL;
6963 PSUPDRVLDRUSAGE pUsage;
6964
6965 for (pUsage = pSession->pLdrUsage; pUsage; pUsage = pUsage->pNext)
6966 if ( pUsage->pImage->pfnServiceReqHandler
6967 && !strcmp(pUsage->pImage->szName, pReq->u.In.szName))
6968 {
6969 pfnServiceReqHandler = pUsage->pImage->pfnServiceReqHandler;
6970 break;
6971 }
6972 supdrvLdrUnlock(pDevExt);
6973
6974 if (pfnServiceReqHandler)
6975 {
6976 /*
6977 * Call it.
6978 */
6979 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_SERVICE_SIZE(0))
6980 rc = pfnServiceReqHandler(pSession, pReq->u.In.uOperation, pReq->u.In.u64Arg, NULL);
6981 else
6982 rc = pfnServiceReqHandler(pSession, pReq->u.In.uOperation, pReq->u.In.u64Arg, (PSUPR0SERVICEREQHDR)&pReq->abReqPkt[0]);
6983 }
6984 else
6985 rc = VERR_SUPDRV_SERVICE_NOT_FOUND;
6986 }
6987
6988 /* log it */
6989 if ( RT_FAILURE(rc)
6990 && rc != VERR_INTERRUPTED
6991 && rc != VERR_TIMEOUT)
6992 Log(("SUP_IOCTL_CALL_SERVICE: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
6993 rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
6994 else
6995 Log4(("SUP_IOCTL_CALL_SERVICE: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
6996 rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
6997 return rc;
6998#else /* RT_OS_WINDOWS && !RT_ARCH_AMD64 && !DEBUG */
6999 RT_NOREF3(pDevExt, pSession, pReq);
7000 return VERR_NOT_IMPLEMENTED;
7001#endif /* RT_OS_WINDOWS && !RT_ARCH_AMD64 && !DEBUG */
7002}
7003
7004
7005/**
7006 * Implements the logger settings request.
7007 *
7008 * @returns VBox status code.
7009 * @param pReq The request.
7010 */
7011static int supdrvIOCtl_LoggerSettings(PSUPLOGGERSETTINGS pReq)
7012{
7013 const char *pszGroup = &pReq->u.In.szStrings[pReq->u.In.offGroups];
7014 const char *pszFlags = &pReq->u.In.szStrings[pReq->u.In.offFlags];
7015 const char *pszDest = &pReq->u.In.szStrings[pReq->u.In.offDestination];
7016 PRTLOGGER pLogger = NULL;
7017 int rc;
7018
7019 /*
7020 * Some further validation.
7021 */
7022 switch (pReq->u.In.fWhat)
7023 {
7024 case SUPLOGGERSETTINGS_WHAT_SETTINGS:
7025 case SUPLOGGERSETTINGS_WHAT_CREATE:
7026 break;
7027
7028 case SUPLOGGERSETTINGS_WHAT_DESTROY:
7029 if (*pszGroup || *pszFlags || *pszDest)
7030 return VERR_INVALID_PARAMETER;
7031 if (pReq->u.In.fWhich == SUPLOGGERSETTINGS_WHICH_RELEASE)
7032 return VERR_ACCESS_DENIED;
7033 break;
7034
7035 default:
7036 return VERR_INTERNAL_ERROR;
7037 }
7038
7039 /*
7040 * Get the logger.
7041 */
7042 switch (pReq->u.In.fWhich)
7043 {
7044 case SUPLOGGERSETTINGS_WHICH_DEBUG:
7045 pLogger = RTLogGetDefaultInstance();
7046 break;
7047
7048 case SUPLOGGERSETTINGS_WHICH_RELEASE:
7049 pLogger = RTLogRelGetDefaultInstance();
7050 break;
7051
7052 default:
7053 return VERR_INTERNAL_ERROR;
7054 }
7055
7056 /*
7057 * Do the job.
7058 */
7059 switch (pReq->u.In.fWhat)
7060 {
7061 case SUPLOGGERSETTINGS_WHAT_SETTINGS:
7062 if (pLogger)
7063 {
7064 rc = RTLogFlags(pLogger, pszFlags);
7065 if (RT_SUCCESS(rc))
7066 rc = RTLogGroupSettings(pLogger, pszGroup);
7067 NOREF(pszDest);
7068 }
7069 else
7070 rc = VERR_NOT_FOUND;
7071 break;
7072
7073 case SUPLOGGERSETTINGS_WHAT_CREATE:
7074 {
7075 if (pLogger)
7076 rc = VERR_ALREADY_EXISTS;
7077 else
7078 {
7079 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
7080
7081 rc = RTLogCreate(&pLogger,
7082 0 /* fFlags */,
7083 pszGroup,
7084 pReq->u.In.fWhich == SUPLOGGERSETTINGS_WHICH_DEBUG
7085 ? "VBOX_LOG"
7086 : "VBOX_RELEASE_LOG",
7087 RT_ELEMENTS(s_apszGroups),
7088 s_apszGroups,
7089 RTLOGDEST_STDOUT | RTLOGDEST_DEBUGGER,
7090 NULL);
7091 if (RT_SUCCESS(rc))
7092 {
7093 rc = RTLogFlags(pLogger, pszFlags);
7094 NOREF(pszDest);
7095 if (RT_SUCCESS(rc))
7096 {
7097 switch (pReq->u.In.fWhich)
7098 {
7099 case SUPLOGGERSETTINGS_WHICH_DEBUG:
7100 pLogger = RTLogSetDefaultInstance(pLogger);
7101 break;
7102 case SUPLOGGERSETTINGS_WHICH_RELEASE:
7103 pLogger = RTLogRelSetDefaultInstance(pLogger);
7104 break;
7105 }
7106 }
7107 RTLogDestroy(pLogger);
7108 }
7109 }
7110 break;
7111 }
7112
7113 case SUPLOGGERSETTINGS_WHAT_DESTROY:
7114 switch (pReq->u.In.fWhich)
7115 {
7116 case SUPLOGGERSETTINGS_WHICH_DEBUG:
7117 pLogger = RTLogSetDefaultInstance(NULL);
7118 break;
7119 case SUPLOGGERSETTINGS_WHICH_RELEASE:
7120 pLogger = RTLogRelSetDefaultInstance(NULL);
7121 break;
7122 }
7123 rc = RTLogDestroy(pLogger);
7124 break;
7125
7126 default:
7127 {
7128 rc = VERR_INTERNAL_ERROR;
7129 break;
7130 }
7131 }
7132
7133 return rc;
7134}
7135
7136
7137/**
7138 * Implements the MSR prober operations.
7139 *
7140 * @returns VBox status code.
7141 * @param pDevExt The device extension.
7142 * @param pReq The request.
7143 */
7144static int supdrvIOCtl_MsrProber(PSUPDRVDEVEXT pDevExt, PSUPMSRPROBER pReq)
7145{
7146#ifdef SUPDRV_WITH_MSR_PROBER
7147 RTCPUID const idCpu = pReq->u.In.idCpu == UINT32_MAX ? NIL_RTCPUID : pReq->u.In.idCpu;
7148 int rc;
7149
7150 switch (pReq->u.In.enmOp)
7151 {
7152 case SUPMSRPROBEROP_READ:
7153 {
7154 uint64_t uValue;
7155 rc = supdrvOSMsrProberRead(pReq->u.In.uMsr, idCpu, &uValue);
7156 if (RT_SUCCESS(rc))
7157 {
7158 pReq->u.Out.uResults.Read.uValue = uValue;
7159 pReq->u.Out.uResults.Read.fGp = false;
7160 }
7161 else if (rc == VERR_ACCESS_DENIED)
7162 {
7163 pReq->u.Out.uResults.Read.uValue = 0;
7164 pReq->u.Out.uResults.Read.fGp = true;
7165 rc = VINF_SUCCESS;
7166 }
7167 break;
7168 }
7169
7170 case SUPMSRPROBEROP_WRITE:
7171 rc = supdrvOSMsrProberWrite(pReq->u.In.uMsr, idCpu, pReq->u.In.uArgs.Write.uToWrite);
7172 if (RT_SUCCESS(rc))
7173 pReq->u.Out.uResults.Write.fGp = false;
7174 else if (rc == VERR_ACCESS_DENIED)
7175 {
7176 pReq->u.Out.uResults.Write.fGp = true;
7177 rc = VINF_SUCCESS;
7178 }
7179 break;
7180
7181 case SUPMSRPROBEROP_MODIFY:
7182 case SUPMSRPROBEROP_MODIFY_FASTER:
7183 rc = supdrvOSMsrProberModify(idCpu, pReq);
7184 break;
7185
7186 default:
7187 return VERR_INVALID_FUNCTION;
7188 }
7189 RT_NOREF1(pDevExt);
7190 return rc;
7191#else
7192 RT_NOREF2(pDevExt, pReq);
7193 return VERR_NOT_IMPLEMENTED;
7194#endif
7195}
7196
7197
7198/**
7199 * Resume built-in keyboard on MacBook Air and Pro hosts.
7200 * If there is no built-in keyboard device, return success anyway.
7201 *
7202 * @returns 0 on Mac OS X platform, VERR_NOT_IMPLEMENTED on the other ones.
7203 */
7204static int supdrvIOCtl_ResumeSuspendedKbds(void)
7205{
7206#if defined(RT_OS_DARWIN)
7207 return supdrvDarwinResumeSuspendedKbds();
7208#else
7209 return VERR_NOT_IMPLEMENTED;
7210#endif
7211}
7212
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