VirtualBox

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

Last change on this file since 99735 was 99421, checked in by vboxsync, 20 months ago

SUPDrv: Move SUPDRV_MEMCPY to SUPDrvInternal.h and try explain why and when to use. bugref:10209 ticketref:21410

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