VirtualBox

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

Last change on this file since 107044 was 106640, checked in by vboxsync, 5 weeks ago

SUPDrv: Some tiny fixes and cleanup. jiraref:VBP-1253

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