VirtualBox

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

Last change on this file since 97441 was 97262, checked in by vboxsync, 2 years ago

VMM: Nested VMX: bugref:10092 Added fetching VM-exit secondary MSR from the support driver. Updated the virtual VMCS with latest VMCS fields (HLAT prefix size, HLAT ptr, secondary VM-exit controls and PCONFIG-exiting bitmap).

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

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