VirtualBox

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

Last change on this file since 106159 was 106061, checked in by vboxsync, 2 months ago

Copyright year updates by scm.

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