VirtualBox

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

最後變更 在這個檔案從96407是 96407,由 vboxsync 提交於 3 年 前

scm copyright and license note update

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

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