VirtualBox

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

Last change on this file since 101358 was 101358, checked in by vboxsync, 8 months ago

Linux: vboxdrv: Replace SUPDRV_UNFORTIFIED_MEMCPY with RT_BCOPY_UNFORTIFIED, bugref:10209.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 265.9 KB
Line 
1/* $Id: SUPDrv.cpp 101358 2023-10-05 15:24:57Z 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( 5, RTR0MemObjAllocContTag),
457 SUPEXP_STK_BACK( 5, RTR0MemObjAllocLargeTag),
458 SUPEXP_STK_BACK( 4, RTR0MemObjAllocLowTag),
459 SUPEXP_STK_BACK( 4, RTR0MemObjAllocPageTag),
460 SUPEXP_STK_BACK( 5, RTR0MemObjAllocPhysExTag),
461 SUPEXP_STK_BACK( 4, RTR0MemObjAllocPhysNCTag),
462 SUPEXP_STK_BACK( 4, RTR0MemObjAllocPhysTag),
463 SUPEXP_STK_BACK( 5, RTR0MemObjEnterPhysTag),
464 SUPEXP_STK_BACK( 2, RTR0MemObjFree),
465 SUPEXP_STK_BACK( 2, RTR0MemObjGetPagePhysAddr),
466 SUPEXP_STK_OKAY( 1, RTR0MemObjIsMapping),
467 SUPEXP_STK_BACK( 6, RTR0MemObjLockUserTag),
468 SUPEXP_STK_BACK( 5, RTR0MemObjLockKernelTag),
469 SUPEXP_STK_BACK( 8, RTR0MemObjMapKernelExTag),
470 SUPEXP_STK_BACK( 6, RTR0MemObjMapKernelTag),
471 SUPEXP_STK_BACK( 9, RTR0MemObjMapUserExTag),
472 SUPEXP_STK_BACK( 7, RTR0MemObjMapUserTag),
473 SUPEXP_STK_BACK( 4, RTR0MemObjProtect),
474 SUPEXP_STK_OKAY( 1, RTR0MemObjSize),
475 SUPEXP_STK_OKAY( 1, RTR0MemObjWasZeroInitialized),
476 SUPEXP_STK_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 RT_BCOPY_UNFORTIFIED(&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 /** @todo Is the 4GiB requirement actually necessray? */
3507 rc = RTR0MemObjAllocCont(&Mem.MemObj, cPages << PAGE_SHIFT, _4G-1 /*PhysHighest*/, true /* executable R0 mapping */);
3508 if (RT_SUCCESS(rc))
3509 {
3510 int rc2;
3511 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
3512 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3513 if (RT_SUCCESS(rc))
3514 {
3515 Mem.eType = MEMREF_TYPE_CONT;
3516 rc = supdrvMemAdd(&Mem, pSession);
3517 if (!rc)
3518 {
3519 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3520 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3521 *pHCPhys = RTR0MemObjGetPagePhysAddr(Mem.MemObj, 0);
3522 return 0;
3523 }
3524
3525 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3526 AssertRC(rc2);
3527 }
3528 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3529 AssertRC(rc2);
3530 }
3531
3532 return rc;
3533}
3534SUPR0_EXPORT_SYMBOL(SUPR0ContAlloc);
3535
3536
3537/**
3538 * Frees memory allocated using SUPR0ContAlloc().
3539 *
3540 * @returns IPRT status code.
3541 * @param pSession The session to which the memory was allocated.
3542 * @param uPtr Pointer to the memory (ring-3 or ring-0).
3543 */
3544SUPR0DECL(int) SUPR0ContFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
3545{
3546 LogFlow(("SUPR0ContFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
3547 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3548 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_CONT);
3549}
3550SUPR0_EXPORT_SYMBOL(SUPR0ContFree);
3551
3552
3553/**
3554 * Allocates a chunk of page aligned memory with fixed physical backing below 4GB.
3555 *
3556 * The memory isn't zeroed.
3557 *
3558 * @returns IPRT status code.
3559 * @param pSession Session data.
3560 * @param cPages Number of pages to allocate.
3561 * @param ppvR0 Where to put the address of Ring-0 mapping of the allocated memory.
3562 * @param ppvR3 Where to put the address of Ring-3 mapping of the allocated memory.
3563 * @param paPages Where to put the physical addresses of allocated memory.
3564 */
3565SUPR0DECL(int) SUPR0LowAlloc(PSUPDRVSESSION pSession, uint32_t cPages, PRTR0PTR ppvR0, PRTR3PTR ppvR3, PRTHCPHYS paPages)
3566{
3567 unsigned iPage;
3568 int rc;
3569 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3570 LogFlow(("SUPR0LowAlloc: pSession=%p cPages=%d ppvR3=%p ppvR0=%p paPages=%p\n", pSession, cPages, ppvR3, ppvR0, paPages));
3571
3572 /*
3573 * Validate input.
3574 */
3575 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3576 if (!ppvR3 || !ppvR0 || !paPages)
3577 {
3578 Log(("Null pointer. All of these should be set: pSession=%p ppvR3=%p ppvR0=%p paPages=%p\n",
3579 pSession, ppvR3, ppvR0, paPages));
3580 return VERR_INVALID_PARAMETER;
3581
3582 }
3583 if (cPages < 1 || cPages >= 256)
3584 {
3585 Log(("Illegal request cPages=%d, must be greater than 0 and smaller than 256.\n", cPages));
3586 return VERR_PAGE_COUNT_OUT_OF_RANGE;
3587 }
3588
3589 /*
3590 * Let IPRT do the work.
3591 */
3592 rc = RTR0MemObjAllocLow(&Mem.MemObj, cPages << PAGE_SHIFT, true /* executable ring-0 mapping */);
3593 if (RT_SUCCESS(rc))
3594 {
3595 int rc2;
3596 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
3597 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3598 if (RT_SUCCESS(rc))
3599 {
3600 Mem.eType = MEMREF_TYPE_LOW;
3601 rc = supdrvMemAdd(&Mem, pSession);
3602 if (!rc)
3603 {
3604 for (iPage = 0; iPage < cPages; iPage++)
3605 {
3606 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MemObj, iPage);
3607 AssertMsg(!(paPages[iPage] & (PAGE_SIZE - 1)), ("iPage=%d Phys=%RHp\n", paPages[iPage]));
3608 }
3609 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3610 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3611 return 0;
3612 }
3613
3614 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3615 AssertRC(rc2);
3616 }
3617
3618 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3619 AssertRC(rc2);
3620 }
3621
3622 return rc;
3623}
3624SUPR0_EXPORT_SYMBOL(SUPR0LowAlloc);
3625
3626
3627/**
3628 * Frees memory allocated using SUPR0LowAlloc().
3629 *
3630 * @returns IPRT status code.
3631 * @param pSession The session to which the memory was allocated.
3632 * @param uPtr Pointer to the memory (ring-3 or ring-0).
3633 */
3634SUPR0DECL(int) SUPR0LowFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
3635{
3636 LogFlow(("SUPR0LowFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
3637 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3638 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_LOW);
3639}
3640SUPR0_EXPORT_SYMBOL(SUPR0LowFree);
3641
3642
3643
3644/**
3645 * Allocates a chunk of memory with both R0 and R3 mappings.
3646 * The memory is fixed and it's possible to query the physical addresses using SUPR0MemGetPhys().
3647 *
3648 * @returns IPRT status code.
3649 * @param pSession The session to associated the allocation with.
3650 * @param cb Number of bytes to allocate.
3651 * @param ppvR0 Where to store the address of the Ring-0 mapping.
3652 * @param ppvR3 Where to store the address of the Ring-3 mapping.
3653 */
3654SUPR0DECL(int) SUPR0MemAlloc(PSUPDRVSESSION pSession, uint32_t cb, PRTR0PTR ppvR0, PRTR3PTR ppvR3)
3655{
3656 int rc;
3657 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3658 LogFlow(("SUPR0MemAlloc: pSession=%p cb=%d ppvR0=%p ppvR3=%p\n", pSession, cb, ppvR0, ppvR3));
3659
3660 /*
3661 * Validate input.
3662 */
3663 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3664 AssertPtrReturn(ppvR0, VERR_INVALID_POINTER);
3665 AssertPtrReturn(ppvR3, VERR_INVALID_POINTER);
3666 if (cb < 1 || cb >= _4M)
3667 {
3668 Log(("Illegal request cb=%u; must be greater than 0 and smaller than 4MB.\n", cb));
3669 return VERR_INVALID_PARAMETER;
3670 }
3671
3672 /*
3673 * Let IPRT do the work.
3674 */
3675 rc = RTR0MemObjAllocPage(&Mem.MemObj, cb, true /* executable ring-0 mapping */);
3676 if (RT_SUCCESS(rc))
3677 {
3678 int rc2;
3679 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
3680 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3681 if (RT_SUCCESS(rc))
3682 {
3683 Mem.eType = MEMREF_TYPE_MEM;
3684 rc = supdrvMemAdd(&Mem, pSession);
3685 if (!rc)
3686 {
3687 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3688 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3689 return VINF_SUCCESS;
3690 }
3691
3692 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3693 AssertRC(rc2);
3694 }
3695
3696 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3697 AssertRC(rc2);
3698 }
3699
3700 return rc;
3701}
3702SUPR0_EXPORT_SYMBOL(SUPR0MemAlloc);
3703
3704
3705/**
3706 * Get the physical addresses of memory allocated using SUPR0MemAlloc().
3707 *
3708 * @returns IPRT status code.
3709 * @param pSession The session to which the memory was allocated.
3710 * @param uPtr The Ring-0 or Ring-3 address returned by SUPR0MemAlloc().
3711 * @param paPages Where to store the physical addresses.
3712 */
3713SUPR0DECL(int) SUPR0MemGetPhys(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, PSUPPAGE paPages) /** @todo switch this bugger to RTHCPHYS */
3714{
3715 PSUPDRVBUNDLE pBundle;
3716 LogFlow(("SUPR0MemGetPhys: pSession=%p uPtr=%p paPages=%p\n", pSession, (void *)uPtr, paPages));
3717
3718 /*
3719 * Validate input.
3720 */
3721 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3722 AssertPtrReturn(paPages, VERR_INVALID_POINTER);
3723 AssertReturn(uPtr, VERR_INVALID_PARAMETER);
3724
3725 /*
3726 * Search for the address.
3727 */
3728 RTSpinlockAcquire(pSession->Spinlock);
3729 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3730 {
3731 if (pBundle->cUsed > 0)
3732 {
3733 unsigned i;
3734 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
3735 {
3736 if ( pBundle->aMem[i].eType == MEMREF_TYPE_MEM
3737 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3738 && ( (RTHCUINTPTR)RTR0MemObjAddress(pBundle->aMem[i].MemObj) == uPtr
3739 || ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
3740 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == uPtr)
3741 )
3742 )
3743 {
3744 const size_t cPages = RTR0MemObjSize(pBundle->aMem[i].MemObj) >> PAGE_SHIFT;
3745 size_t iPage;
3746 for (iPage = 0; iPage < cPages; iPage++)
3747 {
3748 paPages[iPage].Phys = RTR0MemObjGetPagePhysAddr(pBundle->aMem[i].MemObj, iPage);
3749 paPages[iPage].uReserved = 0;
3750 }
3751 RTSpinlockRelease(pSession->Spinlock);
3752 return VINF_SUCCESS;
3753 }
3754 }
3755 }
3756 }
3757 RTSpinlockRelease(pSession->Spinlock);
3758 Log(("Failed to find %p!!!\n", (void *)uPtr));
3759 return VERR_INVALID_PARAMETER;
3760}
3761SUPR0_EXPORT_SYMBOL(SUPR0MemGetPhys);
3762
3763
3764/**
3765 * Free memory allocated by SUPR0MemAlloc().
3766 *
3767 * @returns IPRT status code.
3768 * @param pSession The session owning the allocation.
3769 * @param uPtr The Ring-0 or Ring-3 address returned by SUPR0MemAlloc().
3770 */
3771SUPR0DECL(int) SUPR0MemFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
3772{
3773 LogFlow(("SUPR0MemFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
3774 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3775 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_MEM);
3776}
3777SUPR0_EXPORT_SYMBOL(SUPR0MemFree);
3778
3779
3780/**
3781 * Allocates a chunk of memory with a kernel or/and a user mode mapping.
3782 *
3783 * The memory is fixed and it's possible to query the physical addresses using
3784 * SUPR0MemGetPhys().
3785 *
3786 * @returns IPRT status code.
3787 * @param pSession The session to associated the allocation with.
3788 * @param cPages The number of pages to allocate.
3789 * @param fFlags Flags, reserved for the future. Must be zero.
3790 * @param ppvR3 Where to store the address of the Ring-3 mapping.
3791 * NULL if no ring-3 mapping.
3792 * @param ppvR0 Where to store the address of the Ring-0 mapping.
3793 * NULL if no ring-0 mapping.
3794 * @param paPages Where to store the addresses of the pages. Optional.
3795 */
3796SUPR0DECL(int) SUPR0PageAllocEx(PSUPDRVSESSION pSession, uint32_t cPages, uint32_t fFlags, PRTR3PTR ppvR3, PRTR0PTR ppvR0, PRTHCPHYS paPages)
3797{
3798 int rc;
3799 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3800 LogFlow(("SUPR0PageAlloc: pSession=%p cb=%d ppvR3=%p\n", pSession, cPages, ppvR3));
3801
3802 /*
3803 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
3804 */
3805 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3806 AssertPtrNullReturn(ppvR3, VERR_INVALID_POINTER);
3807 AssertPtrNullReturn(ppvR0, VERR_INVALID_POINTER);
3808 AssertReturn(ppvR3 || ppvR0, VERR_INVALID_PARAMETER);
3809 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
3810 if (cPages < 1 || cPages > VBOX_MAX_ALLOC_PAGE_COUNT)
3811 {
3812 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)));
3813 return VERR_PAGE_COUNT_OUT_OF_RANGE;
3814 }
3815
3816 /*
3817 * Let IPRT do the work.
3818 */
3819 if (ppvR0)
3820 rc = RTR0MemObjAllocPage(&Mem.MemObj, (size_t)cPages * PAGE_SIZE, false /*fExecutable*/);
3821 else
3822 rc = RTR0MemObjAllocPhysNC(&Mem.MemObj, (size_t)cPages * PAGE_SIZE, NIL_RTHCPHYS);
3823 if (RT_SUCCESS(rc))
3824 {
3825 int rc2;
3826 if (ppvR3)
3827 {
3828 /* Make sure memory mapped into ring-3 is zero initialized if we can: */
3829 if ( ppvR0
3830 && !RTR0MemObjWasZeroInitialized(Mem.MemObj))
3831 {
3832 void *pv = RTR0MemObjAddress(Mem.MemObj);
3833 Assert(pv || !ppvR0);
3834 if (pv)
3835 RT_BZERO(pv, (size_t)cPages * PAGE_SIZE);
3836 }
3837
3838 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0, RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3839 }
3840 else
3841 Mem.MapObjR3 = NIL_RTR0MEMOBJ;
3842 if (RT_SUCCESS(rc))
3843 {
3844 Mem.eType = MEMREF_TYPE_PAGE;
3845 rc = supdrvMemAdd(&Mem, pSession);
3846 if (!rc)
3847 {
3848 if (ppvR3)
3849 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3850 if (ppvR0)
3851 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3852 if (paPages)
3853 {
3854 uint32_t iPage = cPages;
3855 while (iPage-- > 0)
3856 {
3857 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MapObjR3, iPage);
3858 Assert(paPages[iPage] != NIL_RTHCPHYS);
3859 }
3860 }
3861 return VINF_SUCCESS;
3862 }
3863
3864 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3865 AssertRC(rc2);
3866 }
3867
3868 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3869 AssertRC(rc2);
3870 }
3871 return rc;
3872}
3873SUPR0_EXPORT_SYMBOL(SUPR0PageAllocEx);
3874
3875
3876/**
3877 * Maps a chunk of memory previously allocated by SUPR0PageAllocEx into kernel
3878 * space.
3879 *
3880 * @returns IPRT status code.
3881 * @param pSession The session to associated the allocation with.
3882 * @param pvR3 The ring-3 address returned by SUPR0PageAllocEx.
3883 * @param offSub Where to start mapping. Must be page aligned.
3884 * @param cbSub How much to map. Must be page aligned.
3885 * @param fFlags Flags, MBZ.
3886 * @param ppvR0 Where to return the address of the ring-0 mapping on
3887 * success.
3888 */
3889SUPR0DECL(int) SUPR0PageMapKernel(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t offSub, uint32_t cbSub,
3890 uint32_t fFlags, PRTR0PTR ppvR0)
3891{
3892 int rc;
3893 PSUPDRVBUNDLE pBundle;
3894 RTR0MEMOBJ hMemObj = NIL_RTR0MEMOBJ;
3895 LogFlow(("SUPR0PageMapKernel: pSession=%p pvR3=%p offSub=%#x cbSub=%#x\n", pSession, pvR3, offSub, cbSub));
3896
3897 /*
3898 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
3899 */
3900 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3901 AssertPtrNullReturn(ppvR0, VERR_INVALID_POINTER);
3902 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
3903 AssertReturn(!(offSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3904 AssertReturn(!(cbSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3905 AssertReturn(cbSub, VERR_INVALID_PARAMETER);
3906
3907 /*
3908 * Find the memory object.
3909 */
3910 RTSpinlockAcquire(pSession->Spinlock);
3911 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3912 {
3913 if (pBundle->cUsed > 0)
3914 {
3915 unsigned i;
3916 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
3917 {
3918 if ( ( pBundle->aMem[i].eType == MEMREF_TYPE_PAGE
3919 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3920 && pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
3921 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3)
3922 || ( pBundle->aMem[i].eType == MEMREF_TYPE_LOCKED
3923 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3924 && pBundle->aMem[i].MapObjR3 == NIL_RTR0MEMOBJ
3925 && RTR0MemObjAddressR3(pBundle->aMem[i].MemObj) == pvR3))
3926 {
3927 hMemObj = pBundle->aMem[i].MemObj;
3928 break;
3929 }
3930 }
3931 }
3932 }
3933 RTSpinlockRelease(pSession->Spinlock);
3934
3935 rc = VERR_INVALID_PARAMETER;
3936 if (hMemObj != NIL_RTR0MEMOBJ)
3937 {
3938 /*
3939 * Do some further input validations before calling IPRT.
3940 * (Cleanup is done indirectly by telling RTR0MemObjFree to include mappings.)
3941 */
3942 size_t cbMemObj = RTR0MemObjSize(hMemObj);
3943 if ( offSub < cbMemObj
3944 && cbSub <= cbMemObj
3945 && offSub + cbSub <= cbMemObj)
3946 {
3947 RTR0MEMOBJ hMapObj;
3948 rc = RTR0MemObjMapKernelEx(&hMapObj, hMemObj, (void *)-1, 0,
3949 RTMEM_PROT_READ | RTMEM_PROT_WRITE, offSub, cbSub);
3950 if (RT_SUCCESS(rc))
3951 *ppvR0 = RTR0MemObjAddress(hMapObj);
3952 }
3953 else
3954 SUPR0Printf("SUPR0PageMapKernel: cbMemObj=%#x offSub=%#x cbSub=%#x\n", cbMemObj, offSub, cbSub);
3955
3956 }
3957 return rc;
3958}
3959SUPR0_EXPORT_SYMBOL(SUPR0PageMapKernel);
3960
3961
3962/**
3963 * Changes the page level protection of one or more pages previously allocated
3964 * by SUPR0PageAllocEx.
3965 *
3966 * @returns IPRT status code.
3967 * @param pSession The session to associated the allocation with.
3968 * @param pvR3 The ring-3 address returned by SUPR0PageAllocEx.
3969 * NIL_RTR3PTR if the ring-3 mapping should be unaffected.
3970 * @param pvR0 The ring-0 address returned by SUPR0PageAllocEx.
3971 * NIL_RTR0PTR if the ring-0 mapping should be unaffected.
3972 * @param offSub Where to start changing. Must be page aligned.
3973 * @param cbSub How much to change. Must be page aligned.
3974 * @param fProt The new page level protection, see RTMEM_PROT_*.
3975 */
3976SUPR0DECL(int) SUPR0PageProtect(PSUPDRVSESSION pSession, RTR3PTR pvR3, RTR0PTR pvR0, uint32_t offSub, uint32_t cbSub, uint32_t fProt)
3977{
3978 int rc;
3979 PSUPDRVBUNDLE pBundle;
3980 RTR0MEMOBJ hMemObjR0 = NIL_RTR0MEMOBJ;
3981 RTR0MEMOBJ hMemObjR3 = NIL_RTR0MEMOBJ;
3982 LogFlow(("SUPR0PageProtect: pSession=%p pvR3=%p pvR0=%p offSub=%#x cbSub=%#x fProt-%#x\n", pSession, pvR3, pvR0, offSub, cbSub, fProt));
3983
3984 /*
3985 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
3986 */
3987 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3988 AssertReturn(!(fProt & ~(RTMEM_PROT_READ | RTMEM_PROT_WRITE | RTMEM_PROT_EXEC | RTMEM_PROT_NONE)), VERR_INVALID_PARAMETER);
3989 AssertReturn(!(offSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3990 AssertReturn(!(cbSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3991 AssertReturn(cbSub, VERR_INVALID_PARAMETER);
3992
3993 /*
3994 * Find the memory object.
3995 */
3996 RTSpinlockAcquire(pSession->Spinlock);
3997 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3998 {
3999 if (pBundle->cUsed > 0)
4000 {
4001 unsigned i;
4002 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
4003 {
4004 if ( pBundle->aMem[i].eType == MEMREF_TYPE_PAGE
4005 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
4006 && ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
4007 || pvR3 == NIL_RTR3PTR)
4008 && ( pvR0 == NIL_RTR0PTR
4009 || RTR0MemObjAddress(pBundle->aMem[i].MemObj) == pvR0)
4010 && ( pvR3 == NIL_RTR3PTR
4011 || RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3))
4012 {
4013 if (pvR0 != NIL_RTR0PTR)
4014 hMemObjR0 = pBundle->aMem[i].MemObj;
4015 if (pvR3 != NIL_RTR3PTR)
4016 hMemObjR3 = pBundle->aMem[i].MapObjR3;
4017 break;
4018 }
4019 }
4020 }
4021 }
4022 RTSpinlockRelease(pSession->Spinlock);
4023
4024 rc = VERR_INVALID_PARAMETER;
4025 if ( hMemObjR0 != NIL_RTR0MEMOBJ
4026 || hMemObjR3 != NIL_RTR0MEMOBJ)
4027 {
4028 /*
4029 * Do some further input validations before calling IPRT.
4030 */
4031 size_t cbMemObj = hMemObjR0 != NIL_RTR0PTR ? RTR0MemObjSize(hMemObjR0) : RTR0MemObjSize(hMemObjR3);
4032 if ( offSub < cbMemObj
4033 && cbSub <= cbMemObj
4034 && offSub + cbSub <= cbMemObj)
4035 {
4036 rc = VINF_SUCCESS;
4037 if (hMemObjR3 != NIL_RTR0PTR)
4038 rc = RTR0MemObjProtect(hMemObjR3, offSub, cbSub, fProt);
4039 if (hMemObjR0 != NIL_RTR0PTR && RT_SUCCESS(rc))
4040 rc = RTR0MemObjProtect(hMemObjR0, offSub, cbSub, fProt);
4041 }
4042 else
4043 SUPR0Printf("SUPR0PageMapKernel: cbMemObj=%#x offSub=%#x cbSub=%#x\n", cbMemObj, offSub, cbSub);
4044
4045 }
4046 return rc;
4047
4048}
4049SUPR0_EXPORT_SYMBOL(SUPR0PageProtect);
4050
4051
4052/**
4053 * Free memory allocated by SUPR0PageAlloc() and SUPR0PageAllocEx().
4054 *
4055 * @returns IPRT status code.
4056 * @param pSession The session owning the allocation.
4057 * @param pvR3 The Ring-3 address returned by SUPR0PageAlloc() or
4058 * SUPR0PageAllocEx().
4059 */
4060SUPR0DECL(int) SUPR0PageFree(PSUPDRVSESSION pSession, RTR3PTR pvR3)
4061{
4062 LogFlow(("SUPR0PageFree: pSession=%p pvR3=%p\n", pSession, (void *)pvR3));
4063 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4064 return supdrvMemRelease(pSession, (RTHCUINTPTR)pvR3, MEMREF_TYPE_PAGE);
4065}
4066SUPR0_EXPORT_SYMBOL(SUPR0PageFree);
4067
4068
4069/**
4070 * Reports a bad context, currenctly that means EFLAGS.AC is 0 instead of 1.
4071 *
4072 * @param pDevExt The device extension.
4073 * @param pszFile The source file where the caller detected the bad
4074 * context.
4075 * @param uLine The line number in @a pszFile.
4076 * @param pszExtra Optional additional message to give further hints.
4077 */
4078void VBOXCALL supdrvBadContext(PSUPDRVDEVEXT pDevExt, const char *pszFile, uint32_t uLine, const char *pszExtra)
4079{
4080 uint32_t cCalls;
4081
4082 /*
4083 * Shorten the filename before displaying the message.
4084 */
4085 for (;;)
4086 {
4087 const char *pszTmp = strchr(pszFile, '/');
4088 if (!pszTmp)
4089 pszTmp = strchr(pszFile, '\\');
4090 if (!pszTmp)
4091 break;
4092 pszFile = pszTmp + 1;
4093 }
4094 if (RT_VALID_PTR(pszExtra) && *pszExtra)
4095 SUPR0Printf("vboxdrv: Bad CPU context error at line %u in %s: %s\n", uLine, pszFile, pszExtra);
4096 else
4097 SUPR0Printf("vboxdrv: Bad CPU context error at line %u in %s!\n", uLine, pszFile);
4098
4099 /*
4100 * Record the incident so that we stand a chance of blocking I/O controls
4101 * before panicing the system.
4102 */
4103 cCalls = ASMAtomicIncU32(&pDevExt->cBadContextCalls);
4104 if (cCalls > UINT32_MAX - _1K)
4105 ASMAtomicWriteU32(&pDevExt->cBadContextCalls, UINT32_MAX - _1K);
4106}
4107
4108
4109/**
4110 * Reports a bad context, currenctly that means EFLAGS.AC is 0 instead of 1.
4111 *
4112 * @param pSession The session of the caller.
4113 * @param pszFile The source file where the caller detected the bad
4114 * context.
4115 * @param uLine The line number in @a pszFile.
4116 * @param pszExtra Optional additional message to give further hints.
4117 */
4118SUPR0DECL(void) SUPR0BadContext(PSUPDRVSESSION pSession, const char *pszFile, uint32_t uLine, const char *pszExtra)
4119{
4120 PSUPDRVDEVEXT pDevExt;
4121
4122 AssertReturnVoid(SUP_IS_SESSION_VALID(pSession));
4123 pDevExt = pSession->pDevExt;
4124
4125 supdrvBadContext(pDevExt, pszFile, uLine, pszExtra);
4126}
4127SUPR0_EXPORT_SYMBOL(SUPR0BadContext);
4128
4129
4130/**
4131 * Gets the paging mode of the current CPU.
4132 *
4133 * @returns Paging mode, SUPPAGEINGMODE_INVALID on error.
4134 */
4135SUPR0DECL(SUPPAGINGMODE) SUPR0GetPagingMode(void)
4136{
4137 SUPPAGINGMODE enmMode;
4138
4139 RTR0UINTREG cr0 = ASMGetCR0();
4140 if ((cr0 & (X86_CR0_PG | X86_CR0_PE)) != (X86_CR0_PG | X86_CR0_PE))
4141 enmMode = SUPPAGINGMODE_INVALID;
4142 else
4143 {
4144 RTR0UINTREG cr4 = ASMGetCR4();
4145 uint32_t fNXEPlusLMA = 0;
4146 if (cr4 & X86_CR4_PAE)
4147 {
4148 uint32_t fExtFeatures = ASMCpuId_EDX(0x80000001);
4149 if (fExtFeatures & (X86_CPUID_EXT_FEATURE_EDX_NX | X86_CPUID_EXT_FEATURE_EDX_LONG_MODE))
4150 {
4151 uint64_t efer = ASMRdMsr(MSR_K6_EFER);
4152 if ((fExtFeatures & X86_CPUID_EXT_FEATURE_EDX_NX) && (efer & MSR_K6_EFER_NXE))
4153 fNXEPlusLMA |= RT_BIT(0);
4154 if ((fExtFeatures & X86_CPUID_EXT_FEATURE_EDX_LONG_MODE) && (efer & MSR_K6_EFER_LMA))
4155 fNXEPlusLMA |= RT_BIT(1);
4156 }
4157 }
4158
4159 switch ((cr4 & (X86_CR4_PAE | X86_CR4_PGE)) | fNXEPlusLMA)
4160 {
4161 case 0:
4162 enmMode = SUPPAGINGMODE_32_BIT;
4163 break;
4164
4165 case X86_CR4_PGE:
4166 enmMode = SUPPAGINGMODE_32_BIT_GLOBAL;
4167 break;
4168
4169 case X86_CR4_PAE:
4170 enmMode = SUPPAGINGMODE_PAE;
4171 break;
4172
4173 case X86_CR4_PAE | RT_BIT(0):
4174 enmMode = SUPPAGINGMODE_PAE_NX;
4175 break;
4176
4177 case X86_CR4_PAE | X86_CR4_PGE:
4178 enmMode = SUPPAGINGMODE_PAE_GLOBAL;
4179 break;
4180
4181 case X86_CR4_PAE | X86_CR4_PGE | RT_BIT(0):
4182 enmMode = SUPPAGINGMODE_PAE_GLOBAL;
4183 break;
4184
4185 case RT_BIT(1) | X86_CR4_PAE:
4186 enmMode = SUPPAGINGMODE_AMD64;
4187 break;
4188
4189 case RT_BIT(1) | X86_CR4_PAE | RT_BIT(0):
4190 enmMode = SUPPAGINGMODE_AMD64_NX;
4191 break;
4192
4193 case RT_BIT(1) | X86_CR4_PAE | X86_CR4_PGE:
4194 enmMode = SUPPAGINGMODE_AMD64_GLOBAL;
4195 break;
4196
4197 case RT_BIT(1) | X86_CR4_PAE | X86_CR4_PGE | RT_BIT(0):
4198 enmMode = SUPPAGINGMODE_AMD64_GLOBAL_NX;
4199 break;
4200
4201 default:
4202 AssertMsgFailed(("Cannot happen! cr4=%#x fNXEPlusLMA=%d\n", cr4, fNXEPlusLMA));
4203 enmMode = SUPPAGINGMODE_INVALID;
4204 break;
4205 }
4206 }
4207 return enmMode;
4208}
4209SUPR0_EXPORT_SYMBOL(SUPR0GetPagingMode);
4210
4211
4212/**
4213 * Change CR4 and take care of the kernel CR4 shadow if applicable.
4214 *
4215 * CR4 shadow handling is required for Linux >= 4.0. Calling this function
4216 * instead of ASMSetCR4() is only necessary for semi-permanent CR4 changes
4217 * for code with interrupts enabled.
4218 *
4219 * @returns the old CR4 value.
4220 *
4221 * @param fOrMask bits to be set in CR4.
4222 * @param fAndMask bits to be cleard in CR4.
4223 *
4224 * @remarks Must be called with preemption/interrupts disabled.
4225 */
4226SUPR0DECL(RTCCUINTREG) SUPR0ChangeCR4(RTCCUINTREG fOrMask, RTCCUINTREG fAndMask)
4227{
4228#ifdef RT_OS_LINUX
4229 return supdrvOSChangeCR4(fOrMask, fAndMask);
4230#else
4231 RTCCUINTREG uOld = ASMGetCR4();
4232 RTCCUINTREG uNew = (uOld & fAndMask) | fOrMask;
4233 if (uNew != uOld)
4234 ASMSetCR4(uNew);
4235 return uOld;
4236#endif
4237}
4238SUPR0_EXPORT_SYMBOL(SUPR0ChangeCR4);
4239
4240
4241/**
4242 * Enables or disabled hardware virtualization extensions using native OS APIs.
4243 *
4244 * @returns VBox status code.
4245 * @retval VINF_SUCCESS on success.
4246 * @retval VERR_NOT_SUPPORTED if not supported by the native OS.
4247 *
4248 * @param fEnable Whether to enable or disable.
4249 */
4250SUPR0DECL(int) SUPR0EnableVTx(bool fEnable)
4251{
4252#ifdef RT_OS_DARWIN
4253 return supdrvOSEnableVTx(fEnable);
4254#else
4255 RT_NOREF1(fEnable);
4256 return VERR_NOT_SUPPORTED;
4257#endif
4258}
4259SUPR0_EXPORT_SYMBOL(SUPR0EnableVTx);
4260
4261
4262/**
4263 * Suspends hardware virtualization extensions using the native OS API.
4264 *
4265 * This is called prior to entering raw-mode context.
4266 *
4267 * @returns @c true if suspended, @c false if not.
4268 */
4269SUPR0DECL(bool) SUPR0SuspendVTxOnCpu(void)
4270{
4271#ifdef RT_OS_DARWIN
4272 return supdrvOSSuspendVTxOnCpu();
4273#else
4274 return false;
4275#endif
4276}
4277SUPR0_EXPORT_SYMBOL(SUPR0SuspendVTxOnCpu);
4278
4279
4280/**
4281 * Resumes hardware virtualization extensions using the native OS API.
4282 *
4283 * This is called after to entering raw-mode context.
4284 *
4285 * @param fSuspended The return value of SUPR0SuspendVTxOnCpu.
4286 */
4287SUPR0DECL(void) SUPR0ResumeVTxOnCpu(bool fSuspended)
4288{
4289#ifdef RT_OS_DARWIN
4290 supdrvOSResumeVTxOnCpu(fSuspended);
4291#else
4292 RT_NOREF1(fSuspended);
4293 Assert(!fSuspended);
4294#endif
4295}
4296SUPR0_EXPORT_SYMBOL(SUPR0ResumeVTxOnCpu);
4297
4298
4299SUPR0DECL(int) SUPR0GetCurrentGdtRw(RTHCUINTPTR *pGdtRw)
4300{
4301#ifdef RT_OS_LINUX
4302 return supdrvOSGetCurrentGdtRw(pGdtRw);
4303#else
4304 NOREF(pGdtRw);
4305 return VERR_NOT_IMPLEMENTED;
4306#endif
4307}
4308SUPR0_EXPORT_SYMBOL(SUPR0GetCurrentGdtRw);
4309
4310
4311/**
4312 * Gets AMD-V and VT-x support for the calling CPU.
4313 *
4314 * @returns VBox status code.
4315 * @param pfCaps Where to store whether VT-x (SUPVTCAPS_VT_X) or AMD-V
4316 * (SUPVTCAPS_AMD_V) is supported.
4317 */
4318SUPR0DECL(int) SUPR0GetVTSupport(uint32_t *pfCaps)
4319{
4320 Assert(pfCaps);
4321 *pfCaps = 0;
4322
4323 /* Check if the CPU even supports CPUID (extremely ancient CPUs). */
4324 if (ASMHasCpuId())
4325 {
4326 /* Check the range of standard CPUID leafs. */
4327 uint32_t uMaxLeaf, uVendorEbx, uVendorEcx, uVendorEdx;
4328 ASMCpuId(0, &uMaxLeaf, &uVendorEbx, &uVendorEcx, &uVendorEdx);
4329 if (RTX86IsValidStdRange(uMaxLeaf))
4330 {
4331 /* Query the standard CPUID leaf. */
4332 uint32_t fFeatEcx, fFeatEdx, uDummy;
4333 ASMCpuId(1, &uDummy, &uDummy, &fFeatEcx, &fFeatEdx);
4334
4335 /* Check if the vendor is Intel (or compatible). */
4336 if ( RTX86IsIntelCpu(uVendorEbx, uVendorEcx, uVendorEdx)
4337 || RTX86IsViaCentaurCpu(uVendorEbx, uVendorEcx, uVendorEdx)
4338 || RTX86IsShanghaiCpu(uVendorEbx, uVendorEcx, uVendorEdx))
4339 {
4340 /* Check VT-x support. In addition, VirtualBox requires MSR and FXSAVE/FXRSTOR to function. */
4341 if ( (fFeatEcx & X86_CPUID_FEATURE_ECX_VMX)
4342 && (fFeatEdx & X86_CPUID_FEATURE_EDX_MSR)
4343 && (fFeatEdx & X86_CPUID_FEATURE_EDX_FXSR))
4344 {
4345 *pfCaps = SUPVTCAPS_VT_X;
4346 return VINF_SUCCESS;
4347 }
4348 return VERR_VMX_NO_VMX;
4349 }
4350
4351 /* Check if the vendor is AMD (or compatible). */
4352 if ( RTX86IsAmdCpu(uVendorEbx, uVendorEcx, uVendorEdx)
4353 || RTX86IsHygonCpu(uVendorEbx, uVendorEcx, uVendorEdx))
4354 {
4355 uint32_t fExtFeatEcx, uExtMaxId;
4356 ASMCpuId(0x80000000, &uExtMaxId, &uDummy, &uDummy, &uDummy);
4357 ASMCpuId(0x80000001, &uDummy, &uDummy, &fExtFeatEcx, &uDummy);
4358
4359 /* Check AMD-V support. In addition, VirtualBox requires MSR and FXSAVE/FXRSTOR to function. */
4360 if ( RTX86IsValidExtRange(uExtMaxId)
4361 && uExtMaxId >= 0x8000000a
4362 && (fExtFeatEcx & X86_CPUID_AMD_FEATURE_ECX_SVM)
4363 && (fFeatEdx & X86_CPUID_FEATURE_EDX_MSR)
4364 && (fFeatEdx & X86_CPUID_FEATURE_EDX_FXSR))
4365 {
4366 *pfCaps = SUPVTCAPS_AMD_V;
4367 return VINF_SUCCESS;
4368 }
4369 return VERR_SVM_NO_SVM;
4370 }
4371 }
4372 }
4373 return VERR_UNSUPPORTED_CPU;
4374}
4375SUPR0_EXPORT_SYMBOL(SUPR0GetVTSupport);
4376
4377
4378/**
4379 * Checks if Intel VT-x feature is usable on this CPU.
4380 *
4381 * @returns VBox status code.
4382 * @param pfIsSmxModeAmbiguous Where to return whether the SMX mode causes
4383 * ambiguity that makes us unsure whether we
4384 * really can use VT-x or not.
4385 *
4386 * @remarks Must be called with preemption disabled.
4387 * The caller is also expected to check that the CPU is an Intel (or
4388 * VIA/Shanghai) CPU -and- that it supports VT-x. Otherwise, this
4389 * function might throw a \#GP fault as it tries to read/write MSRs
4390 * that may not be present!
4391 */
4392SUPR0DECL(int) SUPR0GetVmxUsability(bool *pfIsSmxModeAmbiguous)
4393{
4394 uint64_t fFeatMsr;
4395 bool fMaybeSmxMode;
4396 bool fMsrLocked;
4397 bool fSmxVmxAllowed;
4398 bool fVmxAllowed;
4399 bool fIsSmxModeAmbiguous;
4400 int rc;
4401
4402 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4403
4404 fFeatMsr = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
4405 fMaybeSmxMode = RT_BOOL(ASMGetCR4() & X86_CR4_SMXE);
4406 fMsrLocked = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_LOCK);
4407 fSmxVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
4408 fVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_VMXON);
4409 fIsSmxModeAmbiguous = false;
4410 rc = VERR_INTERNAL_ERROR_5;
4411
4412 /* Check if the LOCK bit is set but excludes the required VMXON bit. */
4413 if (fMsrLocked)
4414 {
4415 if (fVmxAllowed && fSmxVmxAllowed)
4416 rc = VINF_SUCCESS;
4417 else if (!fVmxAllowed && !fSmxVmxAllowed)
4418 rc = VERR_VMX_MSR_ALL_VMX_DISABLED;
4419 else if (!fMaybeSmxMode)
4420 {
4421 if (fVmxAllowed)
4422 rc = VINF_SUCCESS;
4423 else
4424 rc = VERR_VMX_MSR_VMX_DISABLED;
4425 }
4426 else
4427 {
4428 /*
4429 * CR4.SMXE is set but this doesn't mean the CPU is necessarily in SMX mode. We shall assume
4430 * that it is -not- and that it is a stupid BIOS/OS setting CR4.SMXE for no good reason.
4431 * See @bugref{6873}.
4432 */
4433 Assert(fMaybeSmxMode == true);
4434 fIsSmxModeAmbiguous = true;
4435 rc = VINF_SUCCESS;
4436 }
4437 }
4438 else
4439 {
4440 /*
4441 * MSR is not yet locked; we can change it ourselves here. Once the lock bit is set,
4442 * this MSR can no longer be modified.
4443 *
4444 * Set both the VMX and SMX_VMX bits (if supported) as we can't determine SMX mode
4445 * accurately. See @bugref{6873}.
4446 *
4447 * We need to check for SMX hardware support here, before writing the MSR as
4448 * otherwise we will #GP fault on CPUs that do not support it. Callers do not check
4449 * for it.
4450 */
4451 uint32_t fFeaturesECX, uDummy;
4452#ifdef VBOX_STRICT
4453 /* Callers should have verified these at some point. */
4454 uint32_t uMaxId, uVendorEBX, uVendorECX, uVendorEDX;
4455 ASMCpuId(0, &uMaxId, &uVendorEBX, &uVendorECX, &uVendorEDX);
4456 Assert(RTX86IsValidStdRange(uMaxId));
4457 Assert( RTX86IsIntelCpu( uVendorEBX, uVendorECX, uVendorEDX)
4458 || RTX86IsViaCentaurCpu(uVendorEBX, uVendorECX, uVendorEDX)
4459 || RTX86IsShanghaiCpu( uVendorEBX, uVendorECX, uVendorEDX));
4460#endif
4461 ASMCpuId(1, &uDummy, &uDummy, &fFeaturesECX, &uDummy);
4462 bool fSmxVmxHwSupport = false;
4463 if ( (fFeaturesECX & X86_CPUID_FEATURE_ECX_VMX)
4464 && (fFeaturesECX & X86_CPUID_FEATURE_ECX_SMX))
4465 fSmxVmxHwSupport = true;
4466
4467 fFeatMsr |= MSR_IA32_FEATURE_CONTROL_LOCK
4468 | MSR_IA32_FEATURE_CONTROL_VMXON;
4469 if (fSmxVmxHwSupport)
4470 fFeatMsr |= MSR_IA32_FEATURE_CONTROL_SMX_VMXON;
4471
4472 /*
4473 * Commit.
4474 */
4475 ASMWrMsr(MSR_IA32_FEATURE_CONTROL, fFeatMsr);
4476
4477 /*
4478 * Verify.
4479 */
4480 fFeatMsr = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
4481 fMsrLocked = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_LOCK);
4482 if (fMsrLocked)
4483 {
4484 fSmxVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
4485 fVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_VMXON);
4486 if ( fVmxAllowed
4487 && ( !fSmxVmxHwSupport
4488 || fSmxVmxAllowed))
4489 rc = VINF_SUCCESS;
4490 else
4491 rc = !fSmxVmxHwSupport ? VERR_VMX_MSR_VMX_ENABLE_FAILED : VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED;
4492 }
4493 else
4494 rc = VERR_VMX_MSR_LOCKING_FAILED;
4495 }
4496
4497 if (pfIsSmxModeAmbiguous)
4498 *pfIsSmxModeAmbiguous = fIsSmxModeAmbiguous;
4499
4500 return rc;
4501}
4502SUPR0_EXPORT_SYMBOL(SUPR0GetVmxUsability);
4503
4504
4505/**
4506 * Checks if AMD-V SVM feature is usable on this CPU.
4507 *
4508 * @returns VBox status code.
4509 * @param fInitSvm If usable, try to initialize SVM on this CPU.
4510 *
4511 * @remarks Must be called with preemption disabled.
4512 */
4513SUPR0DECL(int) SUPR0GetSvmUsability(bool fInitSvm)
4514{
4515 int rc;
4516 uint64_t fVmCr;
4517 uint64_t fEfer;
4518
4519 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4520 fVmCr = ASMRdMsr(MSR_K8_VM_CR);
4521 if (!(fVmCr & MSR_K8_VM_CR_SVM_DISABLE))
4522 {
4523 rc = VINF_SUCCESS;
4524 if (fInitSvm)
4525 {
4526 /* Turn on SVM in the EFER MSR. */
4527 fEfer = ASMRdMsr(MSR_K6_EFER);
4528 if (fEfer & MSR_K6_EFER_SVME)
4529 rc = VERR_SVM_IN_USE;
4530 else
4531 {
4532 ASMWrMsr(MSR_K6_EFER, fEfer | MSR_K6_EFER_SVME);
4533
4534 /* Paranoia. */
4535 fEfer = ASMRdMsr(MSR_K6_EFER);
4536 if (fEfer & MSR_K6_EFER_SVME)
4537 {
4538 /* Restore previous value. */
4539 ASMWrMsr(MSR_K6_EFER, fEfer & ~MSR_K6_EFER_SVME);
4540 }
4541 else
4542 rc = VERR_SVM_ILLEGAL_EFER_MSR;
4543 }
4544 }
4545 }
4546 else
4547 rc = VERR_SVM_DISABLED;
4548 return rc;
4549}
4550SUPR0_EXPORT_SYMBOL(SUPR0GetSvmUsability);
4551
4552
4553/**
4554 * Queries the AMD-V and VT-x capabilities of the calling CPU.
4555 *
4556 * @returns VBox status code.
4557 * @retval VERR_VMX_NO_VMX
4558 * @retval VERR_VMX_MSR_ALL_VMX_DISABLED
4559 * @retval VERR_VMX_MSR_VMX_DISABLED
4560 * @retval VERR_VMX_MSR_LOCKING_FAILED
4561 * @retval VERR_VMX_MSR_VMX_ENABLE_FAILED
4562 * @retval VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED
4563 * @retval VERR_SVM_NO_SVM
4564 * @retval VERR_SVM_DISABLED
4565 * @retval VERR_UNSUPPORTED_CPU if not identifiable as an AMD, Intel or VIA
4566 * (centaur)/Shanghai CPU.
4567 *
4568 * @param pfCaps Where to store the capabilities.
4569 */
4570int VBOXCALL supdrvQueryVTCapsInternal(uint32_t *pfCaps)
4571{
4572 int rc = VERR_UNSUPPORTED_CPU;
4573 bool fIsSmxModeAmbiguous = false;
4574 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
4575
4576 /*
4577 * Input validation.
4578 */
4579 AssertPtrReturn(pfCaps, VERR_INVALID_POINTER);
4580 *pfCaps = 0;
4581
4582 /* We may modify MSRs and re-read them, disable preemption so we make sure we don't migrate CPUs. */
4583 RTThreadPreemptDisable(&PreemptState);
4584
4585 /* Check if VT-x/AMD-V is supported. */
4586 rc = SUPR0GetVTSupport(pfCaps);
4587 if (RT_SUCCESS(rc))
4588 {
4589 /* Check if VT-x is supported. */
4590 if (*pfCaps & SUPVTCAPS_VT_X)
4591 {
4592 /* Check if VT-x is usable. */
4593 rc = SUPR0GetVmxUsability(&fIsSmxModeAmbiguous);
4594 if (RT_SUCCESS(rc))
4595 {
4596 /* Query some basic VT-x capabilities (mainly required by our GUI). */
4597 VMXCTLSMSR vtCaps;
4598 vtCaps.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS);
4599 if (vtCaps.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
4600 {
4601 vtCaps.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS2);
4602 if (vtCaps.n.allowed1 & VMX_PROC_CTLS2_EPT)
4603 *pfCaps |= SUPVTCAPS_NESTED_PAGING;
4604 if (vtCaps.n.allowed1 & VMX_PROC_CTLS2_UNRESTRICTED_GUEST)
4605 *pfCaps |= SUPVTCAPS_VTX_UNRESTRICTED_GUEST;
4606 if (vtCaps.n.allowed1 & VMX_PROC_CTLS2_VMCS_SHADOWING)
4607 *pfCaps |= SUPVTCAPS_VTX_VMCS_SHADOWING;
4608 }
4609 }
4610 }
4611 /* Check if AMD-V is supported. */
4612 else if (*pfCaps & SUPVTCAPS_AMD_V)
4613 {
4614 /* Check is SVM is usable. */
4615 rc = SUPR0GetSvmUsability(false /* fInitSvm */);
4616 if (RT_SUCCESS(rc))
4617 {
4618 /* Query some basic AMD-V capabilities (mainly required by our GUI). */
4619 uint32_t uDummy, fSvmFeatures;
4620 ASMCpuId(0x8000000a, &uDummy, &uDummy, &uDummy, &fSvmFeatures);
4621 if (fSvmFeatures & X86_CPUID_SVM_FEATURE_EDX_NESTED_PAGING)
4622 *pfCaps |= SUPVTCAPS_NESTED_PAGING;
4623 if (fSvmFeatures & X86_CPUID_SVM_FEATURE_EDX_VIRT_VMSAVE_VMLOAD)
4624 *pfCaps |= SUPVTCAPS_AMDV_VIRT_VMSAVE_VMLOAD;
4625 }
4626 }
4627 }
4628
4629 /* Restore preemption. */
4630 RTThreadPreemptRestore(&PreemptState);
4631
4632 /* After restoring preemption, if we may be in SMX mode, print a warning as it's difficult to debug such problems. */
4633 if (fIsSmxModeAmbiguous)
4634 SUPR0Printf(("WARNING! CR4 hints SMX mode but your CPU is too secretive. Proceeding anyway... We wish you good luck!\n"));
4635
4636 return rc;
4637}
4638
4639
4640/**
4641 * Queries the AMD-V and VT-x capabilities of the calling CPU.
4642 *
4643 * @returns VBox status code.
4644 * @retval VERR_VMX_NO_VMX
4645 * @retval VERR_VMX_MSR_ALL_VMX_DISABLED
4646 * @retval VERR_VMX_MSR_VMX_DISABLED
4647 * @retval VERR_VMX_MSR_LOCKING_FAILED
4648 * @retval VERR_VMX_MSR_VMX_ENABLE_FAILED
4649 * @retval VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED
4650 * @retval VERR_SVM_NO_SVM
4651 * @retval VERR_SVM_DISABLED
4652 * @retval VERR_UNSUPPORTED_CPU if not identifiable as an AMD, Intel or VIA
4653 * (centaur)/Shanghai CPU.
4654 *
4655 * @param pSession The session handle.
4656 * @param pfCaps Where to store the capabilities.
4657 */
4658SUPR0DECL(int) SUPR0QueryVTCaps(PSUPDRVSESSION pSession, uint32_t *pfCaps)
4659{
4660 /*
4661 * Input validation.
4662 */
4663 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4664 AssertPtrReturn(pfCaps, VERR_INVALID_POINTER);
4665
4666 /*
4667 * Call common worker.
4668 */
4669 return supdrvQueryVTCapsInternal(pfCaps);
4670}
4671SUPR0_EXPORT_SYMBOL(SUPR0QueryVTCaps);
4672
4673
4674/**
4675 * Queries the CPU microcode revision.
4676 *
4677 * @returns VBox status code.
4678 * @retval VERR_UNSUPPORTED_CPU if not identifiable as a processor with
4679 * readable microcode rev.
4680 *
4681 * @param puRevision Where to store the microcode revision.
4682 */
4683static int VBOXCALL supdrvQueryUcodeRev(uint32_t *puRevision)
4684{
4685 int rc = VERR_UNSUPPORTED_CPU;
4686 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
4687
4688 /*
4689 * Input validation.
4690 */
4691 AssertPtrReturn(puRevision, VERR_INVALID_POINTER);
4692
4693 *puRevision = 0;
4694
4695 /* Disable preemption so we make sure we don't migrate CPUs, just in case. */
4696 /* NB: We assume that there aren't mismatched microcode revs in the system. */
4697 RTThreadPreemptDisable(&PreemptState);
4698
4699 if (ASMHasCpuId())
4700 {
4701 uint32_t uDummy, uTFMSEAX;
4702 uint32_t uMaxId, uVendorEBX, uVendorECX, uVendorEDX;
4703
4704 ASMCpuId(0, &uMaxId, &uVendorEBX, &uVendorECX, &uVendorEDX);
4705 ASMCpuId(1, &uTFMSEAX, &uDummy, &uDummy, &uDummy);
4706
4707 if (RTX86IsValidStdRange(uMaxId))
4708 {
4709 uint64_t uRevMsr;
4710 if (RTX86IsIntelCpu(uVendorEBX, uVendorECX, uVendorEDX))
4711 {
4712 /* Architectural MSR available on Pentium Pro and later. */
4713 if (RTX86GetCpuFamily(uTFMSEAX) >= 6)
4714 {
4715 /* Revision is in the high dword. */
4716 uRevMsr = ASMRdMsr(MSR_IA32_BIOS_SIGN_ID);
4717 *puRevision = RT_HIDWORD(uRevMsr);
4718 rc = VINF_SUCCESS;
4719 }
4720 }
4721 else if ( RTX86IsAmdCpu(uVendorEBX, uVendorECX, uVendorEDX)
4722 || RTX86IsHygonCpu(uVendorEBX, uVendorECX, uVendorEDX))
4723 {
4724 /* Not well documented, but at least all AMD64 CPUs support this. */
4725 if (RTX86GetCpuFamily(uTFMSEAX) >= 15)
4726 {
4727 /* Revision is in the low dword. */
4728 uRevMsr = ASMRdMsr(MSR_IA32_BIOS_SIGN_ID); /* Same MSR as Intel. */
4729 *puRevision = RT_LODWORD(uRevMsr);
4730 rc = VINF_SUCCESS;
4731 }
4732 }
4733 }
4734 }
4735
4736 RTThreadPreemptRestore(&PreemptState);
4737
4738 return rc;
4739}
4740
4741
4742/**
4743 * Queries the CPU microcode revision.
4744 *
4745 * @returns VBox status code.
4746 * @retval VERR_UNSUPPORTED_CPU if not identifiable as a processor with
4747 * readable microcode rev.
4748 *
4749 * @param pSession The session handle.
4750 * @param puRevision Where to store the microcode revision.
4751 */
4752SUPR0DECL(int) SUPR0QueryUcodeRev(PSUPDRVSESSION pSession, uint32_t *puRevision)
4753{
4754 /*
4755 * Input validation.
4756 */
4757 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4758 AssertPtrReturn(puRevision, VERR_INVALID_POINTER);
4759
4760 /*
4761 * Call common worker.
4762 */
4763 return supdrvQueryUcodeRev(puRevision);
4764}
4765SUPR0_EXPORT_SYMBOL(SUPR0QueryUcodeRev);
4766
4767
4768/**
4769 * Gets hardware-virtualization MSRs of the calling CPU.
4770 *
4771 * @returns VBox status code.
4772 * @param pMsrs Where to store the hardware-virtualization MSRs.
4773 * @param fCaps Hardware virtualization capabilities (SUPVTCAPS_XXX). Pass 0
4774 * to explicitly check for the presence of VT-x/AMD-V before
4775 * querying MSRs.
4776 * @param fForce Force querying of MSRs from the hardware.
4777 */
4778SUPR0DECL(int) SUPR0GetHwvirtMsrs(PSUPHWVIRTMSRS pMsrs, uint32_t fCaps, bool fForce)
4779{
4780 NOREF(fForce);
4781
4782 int rc;
4783 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
4784
4785 /*
4786 * Input validation.
4787 */
4788 AssertPtrReturn(pMsrs, VERR_INVALID_POINTER);
4789
4790 /*
4791 * Disable preemption so we make sure we don't migrate CPUs and because
4792 * we access global data.
4793 */
4794 RTThreadPreemptDisable(&PreemptState);
4795
4796 /*
4797 * Query the MSRs from the hardware.
4798 */
4799 SUPHWVIRTMSRS Msrs;
4800 RT_ZERO(Msrs);
4801
4802 /* If the caller claims VT-x/AMD-V is supported, don't need to recheck it. */
4803 if (!(fCaps & (SUPVTCAPS_VT_X | SUPVTCAPS_AMD_V)))
4804 rc = SUPR0GetVTSupport(&fCaps);
4805 else
4806 rc = VINF_SUCCESS;
4807 if (RT_SUCCESS(rc))
4808 {
4809 if (fCaps & SUPVTCAPS_VT_X)
4810 {
4811 Msrs.u.vmx.u64FeatCtrl = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
4812 Msrs.u.vmx.u64Basic = ASMRdMsr(MSR_IA32_VMX_BASIC);
4813 Msrs.u.vmx.PinCtls.u = ASMRdMsr(MSR_IA32_VMX_PINBASED_CTLS);
4814 Msrs.u.vmx.ProcCtls.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS);
4815 Msrs.u.vmx.ExitCtls.u = ASMRdMsr(MSR_IA32_VMX_EXIT_CTLS);
4816 Msrs.u.vmx.EntryCtls.u = ASMRdMsr(MSR_IA32_VMX_ENTRY_CTLS);
4817 Msrs.u.vmx.u64Misc = ASMRdMsr(MSR_IA32_VMX_MISC);
4818 Msrs.u.vmx.u64Cr0Fixed0 = ASMRdMsr(MSR_IA32_VMX_CR0_FIXED0);
4819 Msrs.u.vmx.u64Cr0Fixed1 = ASMRdMsr(MSR_IA32_VMX_CR0_FIXED1);
4820 Msrs.u.vmx.u64Cr4Fixed0 = ASMRdMsr(MSR_IA32_VMX_CR4_FIXED0);
4821 Msrs.u.vmx.u64Cr4Fixed1 = ASMRdMsr(MSR_IA32_VMX_CR4_FIXED1);
4822 Msrs.u.vmx.u64VmcsEnum = ASMRdMsr(MSR_IA32_VMX_VMCS_ENUM);
4823
4824 if (RT_BF_GET(Msrs.u.vmx.u64Basic, VMX_BF_BASIC_TRUE_CTLS))
4825 {
4826 Msrs.u.vmx.TruePinCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_PINBASED_CTLS);
4827 Msrs.u.vmx.TrueProcCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_PROCBASED_CTLS);
4828 Msrs.u.vmx.TrueEntryCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_ENTRY_CTLS);
4829 Msrs.u.vmx.TrueExitCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_EXIT_CTLS);
4830 }
4831
4832 if (Msrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
4833 {
4834 Msrs.u.vmx.ProcCtls2.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS2);
4835
4836 if (Msrs.u.vmx.ProcCtls2.n.allowed1 & (VMX_PROC_CTLS2_EPT | VMX_PROC_CTLS2_VPID))
4837 Msrs.u.vmx.u64EptVpidCaps = ASMRdMsr(MSR_IA32_VMX_EPT_VPID_CAP);
4838
4839 if (Msrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VMFUNC)
4840 Msrs.u.vmx.u64VmFunc = ASMRdMsr(MSR_IA32_VMX_VMFUNC);
4841 }
4842
4843 if (Msrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TERTIARY_CTLS)
4844 Msrs.u.vmx.u64ProcCtls3 = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS3);
4845
4846 if (Msrs.u.vmx.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_USE_SECONDARY_CTLS)
4847 Msrs.u.vmx.u64ExitCtls2 = ASMRdMsr(MSR_IA32_VMX_EXIT_CTLS2);
4848 }
4849 else if (fCaps & SUPVTCAPS_AMD_V)
4850 {
4851 Msrs.u.svm.u64MsrHwcr = ASMRdMsr(MSR_K8_HWCR);
4852 Msrs.u.svm.u64MsrSmmAddr = ASMRdMsr(MSR_K7_SMM_ADDR);
4853 Msrs.u.svm.u64MsrSmmMask = ASMRdMsr(MSR_K7_SMM_MASK);
4854 }
4855 else
4856 {
4857 RTThreadPreemptRestore(&PreemptState);
4858 AssertMsgFailedReturn(("SUPR0GetVTSupport returns success but neither VT-x nor AMD-V reported!\n"),
4859 VERR_INTERNAL_ERROR_2);
4860 }
4861
4862 /*
4863 * Copy the MSRs out.
4864 */
4865 memcpy(pMsrs, &Msrs, sizeof(*pMsrs));
4866 }
4867
4868 RTThreadPreemptRestore(&PreemptState);
4869
4870 return rc;
4871}
4872SUPR0_EXPORT_SYMBOL(SUPR0GetHwvirtMsrs);
4873
4874
4875/**
4876 * Register a component factory with the support driver.
4877 *
4878 * This is currently restricted to kernel sessions only.
4879 *
4880 * @returns VBox status code.
4881 * @retval VINF_SUCCESS on success.
4882 * @retval VERR_NO_MEMORY if we're out of memory.
4883 * @retval VERR_ALREADY_EXISTS if the factory has already been registered.
4884 * @retval VERR_ACCESS_DENIED if it isn't a kernel session.
4885 * @retval VERR_INVALID_PARAMETER on invalid parameter.
4886 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
4887 *
4888 * @param pSession The SUPDRV session (must be a ring-0 session).
4889 * @param pFactory Pointer to the component factory registration structure.
4890 *
4891 * @remarks This interface is also available via SUPR0IdcComponentRegisterFactory.
4892 */
4893SUPR0DECL(int) SUPR0ComponentRegisterFactory(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory)
4894{
4895 PSUPDRVFACTORYREG pNewReg;
4896 const char *psz;
4897 int rc;
4898
4899 /*
4900 * Validate parameters.
4901 */
4902 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4903 AssertReturn(pSession->R0Process == NIL_RTR0PROCESS, VERR_ACCESS_DENIED);
4904 AssertPtrReturn(pFactory, VERR_INVALID_POINTER);
4905 AssertPtrReturn(pFactory->pfnQueryFactoryInterface, VERR_INVALID_POINTER);
4906 psz = RTStrEnd(pFactory->szName, sizeof(pFactory->szName));
4907 AssertReturn(psz, VERR_INVALID_PARAMETER);
4908
4909 /*
4910 * Allocate and initialize a new registration structure.
4911 */
4912 pNewReg = (PSUPDRVFACTORYREG)RTMemAlloc(sizeof(SUPDRVFACTORYREG));
4913 if (pNewReg)
4914 {
4915 pNewReg->pNext = NULL;
4916 pNewReg->pFactory = pFactory;
4917 pNewReg->pSession = pSession;
4918 pNewReg->cchName = psz - &pFactory->szName[0];
4919
4920 /*
4921 * Add it to the tail of the list after checking for prior registration.
4922 */
4923 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
4924 if (RT_SUCCESS(rc))
4925 {
4926 PSUPDRVFACTORYREG pPrev = NULL;
4927 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
4928 while (pCur && pCur->pFactory != pFactory)
4929 {
4930 pPrev = pCur;
4931 pCur = pCur->pNext;
4932 }
4933 if (!pCur)
4934 {
4935 if (pPrev)
4936 pPrev->pNext = pNewReg;
4937 else
4938 pSession->pDevExt->pComponentFactoryHead = pNewReg;
4939 rc = VINF_SUCCESS;
4940 }
4941 else
4942 rc = VERR_ALREADY_EXISTS;
4943
4944 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
4945 }
4946
4947 if (RT_FAILURE(rc))
4948 RTMemFree(pNewReg);
4949 }
4950 else
4951 rc = VERR_NO_MEMORY;
4952 return rc;
4953}
4954SUPR0_EXPORT_SYMBOL(SUPR0ComponentRegisterFactory);
4955
4956
4957/**
4958 * Deregister a component factory.
4959 *
4960 * @returns VBox status code.
4961 * @retval VINF_SUCCESS on success.
4962 * @retval VERR_NOT_FOUND if the factory wasn't registered.
4963 * @retval VERR_ACCESS_DENIED if it isn't a kernel session.
4964 * @retval VERR_INVALID_PARAMETER on invalid parameter.
4965 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
4966 *
4967 * @param pSession The SUPDRV session (must be a ring-0 session).
4968 * @param pFactory Pointer to the component factory registration structure
4969 * previously passed SUPR0ComponentRegisterFactory().
4970 *
4971 * @remarks This interface is also available via SUPR0IdcComponentDeregisterFactory.
4972 */
4973SUPR0DECL(int) SUPR0ComponentDeregisterFactory(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory)
4974{
4975 int rc;
4976
4977 /*
4978 * Validate parameters.
4979 */
4980 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4981 AssertReturn(pSession->R0Process == NIL_RTR0PROCESS, VERR_ACCESS_DENIED);
4982 AssertPtrReturn(pFactory, VERR_INVALID_POINTER);
4983
4984 /*
4985 * Take the lock and look for the registration record.
4986 */
4987 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
4988 if (RT_SUCCESS(rc))
4989 {
4990 PSUPDRVFACTORYREG pPrev = NULL;
4991 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
4992 while (pCur && pCur->pFactory != pFactory)
4993 {
4994 pPrev = pCur;
4995 pCur = pCur->pNext;
4996 }
4997 if (pCur)
4998 {
4999 if (!pPrev)
5000 pSession->pDevExt->pComponentFactoryHead = pCur->pNext;
5001 else
5002 pPrev->pNext = pCur->pNext;
5003
5004 pCur->pNext = NULL;
5005 pCur->pFactory = NULL;
5006 pCur->pSession = NULL;
5007 rc = VINF_SUCCESS;
5008 }
5009 else
5010 rc = VERR_NOT_FOUND;
5011
5012 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
5013
5014 RTMemFree(pCur);
5015 }
5016 return rc;
5017}
5018SUPR0_EXPORT_SYMBOL(SUPR0ComponentDeregisterFactory);
5019
5020
5021/**
5022 * Queries a component factory.
5023 *
5024 * @returns VBox status code.
5025 * @retval VERR_INVALID_PARAMETER on invalid parameter.
5026 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
5027 * @retval VERR_SUPDRV_COMPONENT_NOT_FOUND if the component factory wasn't found.
5028 * @retval VERR_SUPDRV_INTERFACE_NOT_SUPPORTED if the interface wasn't supported.
5029 *
5030 * @param pSession The SUPDRV session.
5031 * @param pszName The name of the component factory.
5032 * @param pszInterfaceUuid The UUID of the factory interface (stringified).
5033 * @param ppvFactoryIf Where to store the factory interface.
5034 */
5035SUPR0DECL(int) SUPR0ComponentQueryFactory(PSUPDRVSESSION pSession, const char *pszName, const char *pszInterfaceUuid, void **ppvFactoryIf)
5036{
5037 const char *pszEnd;
5038 size_t cchName;
5039 int rc;
5040
5041 /*
5042 * Validate parameters.
5043 */
5044 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
5045
5046 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
5047 pszEnd = RTStrEnd(pszName, RT_SIZEOFMEMB(SUPDRVFACTORY, szName));
5048 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
5049 cchName = pszEnd - pszName;
5050
5051 AssertPtrReturn(pszInterfaceUuid, VERR_INVALID_POINTER);
5052 pszEnd = RTStrEnd(pszInterfaceUuid, RTUUID_STR_LENGTH);
5053 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
5054
5055 AssertPtrReturn(ppvFactoryIf, VERR_INVALID_POINTER);
5056 *ppvFactoryIf = NULL;
5057
5058 /*
5059 * Take the lock and try all factories by this name.
5060 */
5061 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
5062 if (RT_SUCCESS(rc))
5063 {
5064 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
5065 rc = VERR_SUPDRV_COMPONENT_NOT_FOUND;
5066 while (pCur)
5067 {
5068 if ( pCur->cchName == cchName
5069 && !memcmp(pCur->pFactory->szName, pszName, cchName))
5070 {
5071 void *pvFactory = pCur->pFactory->pfnQueryFactoryInterface(pCur->pFactory, pSession, pszInterfaceUuid);
5072 if (pvFactory)
5073 {
5074 *ppvFactoryIf = pvFactory;
5075 rc = VINF_SUCCESS;
5076 break;
5077 }
5078 rc = VERR_SUPDRV_INTERFACE_NOT_SUPPORTED;
5079 }
5080
5081 /* next */
5082 pCur = pCur->pNext;
5083 }
5084
5085 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
5086 }
5087 return rc;
5088}
5089SUPR0_EXPORT_SYMBOL(SUPR0ComponentQueryFactory);
5090
5091
5092/**
5093 * Adds a memory object to the session.
5094 *
5095 * @returns IPRT status code.
5096 * @param pMem Memory tracking structure containing the
5097 * information to track.
5098 * @param pSession The session.
5099 */
5100static int supdrvMemAdd(PSUPDRVMEMREF pMem, PSUPDRVSESSION pSession)
5101{
5102 PSUPDRVBUNDLE pBundle;
5103
5104 /*
5105 * Find free entry and record the allocation.
5106 */
5107 RTSpinlockAcquire(pSession->Spinlock);
5108 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
5109 {
5110 if (pBundle->cUsed < RT_ELEMENTS(pBundle->aMem))
5111 {
5112 unsigned i;
5113 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
5114 {
5115 if (pBundle->aMem[i].MemObj == NIL_RTR0MEMOBJ)
5116 {
5117 pBundle->cUsed++;
5118 pBundle->aMem[i] = *pMem;
5119 RTSpinlockRelease(pSession->Spinlock);
5120 return VINF_SUCCESS;
5121 }
5122 }
5123 AssertFailed(); /* !!this can't be happening!!! */
5124 }
5125 }
5126 RTSpinlockRelease(pSession->Spinlock);
5127
5128 /*
5129 * Need to allocate a new bundle.
5130 * Insert into the last entry in the bundle.
5131 */
5132 pBundle = (PSUPDRVBUNDLE)RTMemAllocZ(sizeof(*pBundle));
5133 if (!pBundle)
5134 return VERR_NO_MEMORY;
5135
5136 /* take last entry. */
5137 pBundle->cUsed++;
5138 pBundle->aMem[RT_ELEMENTS(pBundle->aMem) - 1] = *pMem;
5139
5140 /* insert into list. */
5141 RTSpinlockAcquire(pSession->Spinlock);
5142 pBundle->pNext = pSession->Bundle.pNext;
5143 pSession->Bundle.pNext = pBundle;
5144 RTSpinlockRelease(pSession->Spinlock);
5145
5146 return VINF_SUCCESS;
5147}
5148
5149
5150/**
5151 * Releases a memory object referenced by pointer and type.
5152 *
5153 * @returns IPRT status code.
5154 * @param pSession Session data.
5155 * @param uPtr Pointer to memory. This is matched against both the R0 and R3 addresses.
5156 * @param eType Memory type.
5157 */
5158static int supdrvMemRelease(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, SUPDRVMEMREFTYPE eType)
5159{
5160 PSUPDRVBUNDLE pBundle;
5161
5162 /*
5163 * Validate input.
5164 */
5165 if (!uPtr)
5166 {
5167 Log(("Illegal address %p\n", (void *)uPtr));
5168 return VERR_INVALID_PARAMETER;
5169 }
5170
5171 /*
5172 * Search for the address.
5173 */
5174 RTSpinlockAcquire(pSession->Spinlock);
5175 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
5176 {
5177 if (pBundle->cUsed > 0)
5178 {
5179 unsigned i;
5180 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
5181 {
5182 if ( pBundle->aMem[i].eType == eType
5183 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
5184 && ( (RTHCUINTPTR)RTR0MemObjAddress(pBundle->aMem[i].MemObj) == uPtr
5185 || ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
5186 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == uPtr))
5187 )
5188 {
5189 /* Make a copy of it and release it outside the spinlock. */
5190 SUPDRVMEMREF Mem = pBundle->aMem[i];
5191 pBundle->aMem[i].eType = MEMREF_TYPE_UNUSED;
5192 pBundle->aMem[i].MemObj = NIL_RTR0MEMOBJ;
5193 pBundle->aMem[i].MapObjR3 = NIL_RTR0MEMOBJ;
5194 RTSpinlockRelease(pSession->Spinlock);
5195
5196 if (Mem.MapObjR3 != NIL_RTR0MEMOBJ)
5197 {
5198 int rc = RTR0MemObjFree(Mem.MapObjR3, false);
5199 AssertRC(rc); /** @todo figure out how to handle this. */
5200 }
5201 if (Mem.MemObj != NIL_RTR0MEMOBJ)
5202 {
5203 int rc = RTR0MemObjFree(Mem.MemObj, true /* fFreeMappings */);
5204 AssertRC(rc); /** @todo figure out how to handle this. */
5205 }
5206 return VINF_SUCCESS;
5207 }
5208 }
5209 }
5210 }
5211 RTSpinlockRelease(pSession->Spinlock);
5212 Log(("Failed to find %p!!! (eType=%d)\n", (void *)uPtr, eType));
5213 return VERR_INVALID_PARAMETER;
5214}
5215
5216
5217/**
5218 * Opens an image. If it's the first time it's opened the call must upload
5219 * the bits using the supdrvIOCtl_LdrLoad() / SUPDRV_IOCTL_LDR_LOAD function.
5220 *
5221 * This is the 1st step of the loading.
5222 *
5223 * @returns IPRT status code.
5224 * @param pDevExt Device globals.
5225 * @param pSession Session data.
5226 * @param pReq The open request.
5227 */
5228static int supdrvIOCtl_LdrOpen(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDROPEN pReq)
5229{
5230 int rc;
5231 PSUPDRVLDRIMAGE pImage;
5232 void *pv;
5233 size_t cchName = strlen(pReq->u.In.szName); /* (caller checked < 32). */
5234 SUPDRV_CHECK_SMAP_SETUP();
5235 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5236 LogFlow(("supdrvIOCtl_LdrOpen: szName=%s cbImageWithEverything=%d\n", pReq->u.In.szName, pReq->u.In.cbImageWithEverything));
5237
5238 /*
5239 * Check if we got an instance of the image already.
5240 */
5241 supdrvLdrLock(pDevExt);
5242 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5243 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
5244 {
5245 if ( pImage->szName[cchName] == '\0'
5246 && !memcmp(pImage->szName, pReq->u.In.szName, cchName))
5247 {
5248 /** @todo Add an _1M (or something) per session reference. */
5249 if (RT_LIKELY(pImage->cImgUsage < UINT32_MAX / 2U))
5250 {
5251 /** @todo check cbImageBits and cbImageWithEverything here, if they differs
5252 * that indicates that the images are different. */
5253 pReq->u.Out.pvImageBase = pImage->pvImage;
5254 pReq->u.Out.fNeedsLoading = pImage->uState == SUP_IOCTL_LDR_OPEN;
5255 pReq->u.Out.fNativeLoader = pImage->fNative;
5256 supdrvLdrAddUsage(pDevExt, pSession, pImage, true /*fRing3Usage*/);
5257 supdrvLdrUnlock(pDevExt);
5258 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5259 return VINF_SUCCESS;
5260 }
5261 supdrvLdrUnlock(pDevExt);
5262 Log(("supdrvIOCtl_LdrOpen: Too many existing references to '%s'!\n", pReq->u.In.szName));
5263 return VERR_TOO_MANY_REFERENCES;
5264 }
5265 }
5266 /* (not found - add it!) */
5267
5268 /* If the loader interface is locked down, make userland fail early */
5269 if (pDevExt->fLdrLockedDown)
5270 {
5271 supdrvLdrUnlock(pDevExt);
5272 Log(("supdrvIOCtl_LdrOpen: Not adding '%s' to image list, loader interface is locked down!\n", pReq->u.In.szName));
5273 return VERR_PERMISSION_DENIED;
5274 }
5275
5276 /* Stop if caller doesn't wish to prepare loading things. */
5277 if (!pReq->u.In.cbImageBits)
5278 {
5279 supdrvLdrUnlock(pDevExt);
5280 Log(("supdrvIOCtl_LdrOpen: Returning VERR_MODULE_NOT_FOUND for '%s'!\n", pReq->u.In.szName));
5281 return VERR_MODULE_NOT_FOUND;
5282 }
5283
5284 /*
5285 * Allocate memory.
5286 */
5287 Assert(cchName < sizeof(pImage->szName));
5288 pv = RTMemAllocZ(sizeof(SUPDRVLDRIMAGE));
5289 if (!pv)
5290 {
5291 supdrvLdrUnlock(pDevExt);
5292 Log(("supdrvIOCtl_LdrOpen: RTMemAllocZ() failed\n"));
5293 return VERR_NO_MEMORY;
5294 }
5295 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5296
5297 /*
5298 * Setup and link in the LDR stuff.
5299 */
5300 pImage = (PSUPDRVLDRIMAGE)pv;
5301 pImage->pvImage = NULL;
5302 pImage->hMemObjImage = NIL_RTR0MEMOBJ;
5303 pImage->cbImageWithEverything = pReq->u.In.cbImageWithEverything;
5304 pImage->cbImageBits = pReq->u.In.cbImageBits;
5305 pImage->cSymbols = 0;
5306 pImage->paSymbols = NULL;
5307 pImage->pachStrTab = NULL;
5308 pImage->cbStrTab = 0;
5309 pImage->cSegments = 0;
5310 pImage->paSegments = NULL;
5311 pImage->pfnModuleInit = NULL;
5312 pImage->pfnModuleTerm = NULL;
5313 pImage->pfnServiceReqHandler = NULL;
5314 pImage->uState = SUP_IOCTL_LDR_OPEN;
5315 pImage->cImgUsage = 0; /* Increased by supdrvLdrAddUsage later */
5316 pImage->pDevExt = pDevExt;
5317 pImage->pImageImport = NULL;
5318 pImage->uMagic = SUPDRVLDRIMAGE_MAGIC;
5319 pImage->pWrappedModInfo = NULL;
5320 memcpy(pImage->szName, pReq->u.In.szName, cchName + 1);
5321
5322 /*
5323 * Try load it using the native loader, if that isn't supported, fall back
5324 * on the older method.
5325 */
5326 pImage->fNative = true;
5327 rc = supdrvOSLdrOpen(pDevExt, pImage, pReq->u.In.szFilename);
5328 if (rc == VERR_NOT_SUPPORTED)
5329 {
5330 rc = RTR0MemObjAllocPage(&pImage->hMemObjImage, pImage->cbImageBits, true /*fExecutable*/);
5331 if (RT_SUCCESS(rc))
5332 {
5333 pImage->pvImage = RTR0MemObjAddress(pImage->hMemObjImage);
5334 pImage->fNative = false;
5335 }
5336 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5337 }
5338 if (RT_SUCCESS(rc))
5339 rc = supdrvLdrAddUsage(pDevExt, pSession, pImage, true /*fRing3Usage*/);
5340 if (RT_FAILURE(rc))
5341 {
5342 supdrvLdrUnlock(pDevExt);
5343 pImage->uMagic = SUPDRVLDRIMAGE_MAGIC_DEAD;
5344 RTMemFree(pImage);
5345 Log(("supdrvIOCtl_LdrOpen(%s): failed - %Rrc\n", pReq->u.In.szName, rc));
5346 return rc;
5347 }
5348 Assert(RT_VALID_PTR(pImage->pvImage) || RT_FAILURE(rc));
5349
5350 /*
5351 * Link it.
5352 */
5353 pImage->pNext = pDevExt->pLdrImages;
5354 pDevExt->pLdrImages = pImage;
5355
5356 pReq->u.Out.pvImageBase = pImage->pvImage;
5357 pReq->u.Out.fNeedsLoading = true;
5358 pReq->u.Out.fNativeLoader = pImage->fNative;
5359 supdrvOSLdrNotifyOpened(pDevExt, pImage, pReq->u.In.szFilename);
5360
5361 supdrvLdrUnlock(pDevExt);
5362 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5363 return VINF_SUCCESS;
5364}
5365
5366
5367/**
5368 * Formats a load error message.
5369 *
5370 * @returns @a rc
5371 * @param rc Return code.
5372 * @param pReq The request.
5373 * @param pszFormat The error message format string.
5374 * @param ... Argument to the format string.
5375 */
5376int VBOXCALL supdrvLdrLoadError(int rc, PSUPLDRLOAD pReq, const char *pszFormat, ...)
5377{
5378 va_list va;
5379 va_start(va, pszFormat);
5380 pReq->u.Out.uErrorMagic = SUPLDRLOAD_ERROR_MAGIC;
5381 RTStrPrintfV(pReq->u.Out.szError, sizeof(pReq->u.Out.szError), pszFormat, va);
5382 va_end(va);
5383 Log(("SUP_IOCTL_LDR_LOAD: %s [rc=%Rrc]\n", pReq->u.Out.szError, rc));
5384 return rc;
5385}
5386
5387
5388/**
5389 * Worker that validates a pointer to an image entrypoint.
5390 *
5391 * Calls supdrvLdrLoadError on error.
5392 *
5393 * @returns IPRT status code.
5394 * @param pDevExt The device globals.
5395 * @param pImage The loader image.
5396 * @param pv The pointer into the image.
5397 * @param fMayBeNull Whether it may be NULL.
5398 * @param pszSymbol The entrypoint name or log name. If the symbol is
5399 * capitalized it signifies a specific symbol, otherwise it
5400 * for logging.
5401 * @param pbImageBits The image bits prepared by ring-3.
5402 * @param pReq The request for passing to supdrvLdrLoadError.
5403 *
5404 * @note Will leave the loader lock on failure!
5405 */
5406static int supdrvLdrValidatePointer(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, void *pv, bool fMayBeNull,
5407 const uint8_t *pbImageBits, const char *pszSymbol, PSUPLDRLOAD pReq)
5408{
5409 if (!fMayBeNull || pv)
5410 {
5411 uint32_t iSeg;
5412
5413 /* Must be within the image bits: */
5414 uintptr_t const uRva = (uintptr_t)pv - (uintptr_t)pImage->pvImage;
5415 if (uRva >= pImage->cbImageBits)
5416 {
5417 supdrvLdrUnlock(pDevExt);
5418 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq,
5419 "Invalid entry point address %p given for %s: RVA %#zx, image size %#zx",
5420 pv, pszSymbol, uRva, pImage->cbImageBits);
5421 }
5422
5423 /* Must be in an executable segment: */
5424 for (iSeg = 0; iSeg < pImage->cSegments; iSeg++)
5425 if (uRva - pImage->paSegments[iSeg].off < (uintptr_t)pImage->paSegments[iSeg].cb)
5426 {
5427 if (pImage->paSegments[iSeg].fProt & SUPLDR_PROT_EXEC)
5428 break;
5429 supdrvLdrUnlock(pDevExt);
5430 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq,
5431 "Bad entry point %p given for %s: not executable (seg #%u: %#RX32 LB %#RX32 prot %#x)",
5432 pv, pszSymbol, iSeg, pImage->paSegments[iSeg].off, pImage->paSegments[iSeg].cb,
5433 pImage->paSegments[iSeg].fProt);
5434 }
5435 if (iSeg >= pImage->cSegments)
5436 {
5437 supdrvLdrUnlock(pDevExt);
5438 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq,
5439 "Bad entry point %p given for %s: no matching segment found (RVA %#zx)!",
5440 pv, pszSymbol, uRva);
5441 }
5442
5443 if (pImage->fNative)
5444 {
5445 /** @todo pass pReq along to the native code. */
5446 int rc = supdrvOSLdrValidatePointer(pDevExt, pImage, pv, pbImageBits, pszSymbol);
5447 if (RT_FAILURE(rc))
5448 {
5449 supdrvLdrUnlock(pDevExt);
5450 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq,
5451 "Bad entry point address %p for %s: rc=%Rrc\n", pv, pszSymbol, rc);
5452 }
5453 }
5454 }
5455 return VINF_SUCCESS;
5456}
5457
5458
5459/**
5460 * Loads the image bits.
5461 *
5462 * This is the 2nd step of the loading.
5463 *
5464 * @returns IPRT status code.
5465 * @param pDevExt Device globals.
5466 * @param pSession Session data.
5467 * @param pReq The request.
5468 */
5469static int supdrvIOCtl_LdrLoad(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRLOAD pReq)
5470{
5471 PSUPDRVLDRUSAGE pUsage;
5472 PSUPDRVLDRIMAGE pImage;
5473 PSUPDRVLDRIMAGE pImageImport;
5474 int rc;
5475 SUPDRV_CHECK_SMAP_SETUP();
5476 LogFlow(("supdrvIOCtl_LdrLoad: pvImageBase=%p cbImageWithEverything=%d\n", pReq->u.In.pvImageBase, pReq->u.In.cbImageWithEverything));
5477 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5478
5479 /*
5480 * Find the ldr image.
5481 */
5482 supdrvLdrLock(pDevExt);
5483 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5484
5485 pUsage = pSession->pLdrUsage;
5486 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
5487 pUsage = pUsage->pNext;
5488 if (!pUsage)
5489 {
5490 supdrvLdrUnlock(pDevExt);
5491 return supdrvLdrLoadError(VERR_INVALID_HANDLE, pReq, "Image not found");
5492 }
5493 pImage = pUsage->pImage;
5494
5495 /*
5496 * Validate input.
5497 */
5498 if ( pImage->cbImageWithEverything != pReq->u.In.cbImageWithEverything
5499 || pImage->cbImageBits != pReq->u.In.cbImageBits)
5500 {
5501 supdrvLdrUnlock(pDevExt);
5502 return supdrvLdrLoadError(VERR_INVALID_HANDLE, pReq, "Image size mismatch found: %u(prep) != %u(load) or %u != %u",
5503 pImage->cbImageWithEverything, pReq->u.In.cbImageWithEverything, pImage->cbImageBits, pReq->u.In.cbImageBits);
5504 }
5505
5506 if (pImage->uState != SUP_IOCTL_LDR_OPEN)
5507 {
5508 unsigned uState = pImage->uState;
5509 supdrvLdrUnlock(pDevExt);
5510 if (uState != SUP_IOCTL_LDR_LOAD)
5511 AssertMsgFailed(("SUP_IOCTL_LDR_LOAD: invalid image state %d (%#x)!\n", uState, uState));
5512 pReq->u.Out.uErrorMagic = 0;
5513 return VERR_ALREADY_LOADED;
5514 }
5515
5516 /* If the loader interface is locked down, don't load new images */
5517 if (pDevExt->fLdrLockedDown)
5518 {
5519 supdrvLdrUnlock(pDevExt);
5520 return supdrvLdrLoadError(VERR_PERMISSION_DENIED, pReq, "Loader is locked down");
5521 }
5522
5523 /*
5524 * If the new image is a dependant of VMMR0.r0, resolve it via the
5525 * caller's usage list and make sure it's in ready state.
5526 */
5527 pImageImport = NULL;
5528 if (pReq->u.In.fFlags & SUPLDRLOAD_F_DEP_VMMR0)
5529 {
5530 PSUPDRVLDRUSAGE pUsageDependency = pSession->pLdrUsage;
5531 while (pUsageDependency && pUsageDependency->pImage->pvImage != pDevExt->pvVMMR0)
5532 pUsageDependency = pUsageDependency->pNext;
5533 if (!pUsageDependency || !pDevExt->pvVMMR0)
5534 {
5535 supdrvLdrUnlock(pDevExt);
5536 return supdrvLdrLoadError(VERR_MODULE_NOT_FOUND, pReq, "VMMR0.r0 not loaded by session");
5537 }
5538 pImageImport = pUsageDependency->pImage;
5539 if (pImageImport->uState != SUP_IOCTL_LDR_LOAD)
5540 {
5541 supdrvLdrUnlock(pDevExt);
5542 return supdrvLdrLoadError(VERR_MODULE_NOT_FOUND, pReq, "VMMR0.r0 is not ready (state %#x)", pImageImport->uState);
5543 }
5544 }
5545
5546 /*
5547 * Copy the segments before we start using supdrvLdrValidatePointer for entrypoint validation.
5548 */
5549 pImage->cSegments = pReq->u.In.cSegments;
5550 {
5551 size_t cbSegments = pImage->cSegments * sizeof(SUPLDRSEG);
5552 pImage->paSegments = (PSUPLDRSEG)RTMemDup(&pReq->u.In.abImage[pReq->u.In.offSegments], cbSegments);
5553 if (pImage->paSegments) /* Align the last segment size to avoid upsetting RTR0MemObjProtect. */ /** @todo relax RTR0MemObjProtect */
5554 pImage->paSegments[pImage->cSegments - 1].cb = RT_ALIGN_32(pImage->paSegments[pImage->cSegments - 1].cb, PAGE_SIZE);
5555 else
5556 {
5557 supdrvLdrUnlock(pDevExt);
5558 return supdrvLdrLoadError(VERR_NO_MEMORY, pReq, "Out of memory for segment table: %#x", cbSegments);
5559 }
5560 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5561 }
5562
5563 /*
5564 * Validate entrypoints.
5565 */
5566 switch (pReq->u.In.eEPType)
5567 {
5568 case SUPLDRLOADEP_NOTHING:
5569 break;
5570
5571 case SUPLDRLOADEP_VMMR0:
5572 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0EntryFast, false, pReq->u.In.abImage, "VMMR0EntryFast", pReq);
5573 if (RT_FAILURE(rc))
5574 return rc;
5575 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0EntryEx, false, pReq->u.In.abImage, "VMMR0EntryEx", pReq);
5576 if (RT_FAILURE(rc))
5577 return rc;
5578
5579 /* Fail here if there is already a VMMR0 module. */
5580 if (pDevExt->pvVMMR0 != NULL)
5581 {
5582 supdrvLdrUnlock(pDevExt);
5583 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq, "There is already a VMMR0 module loaded (%p)", pDevExt->pvVMMR0);
5584 }
5585 break;
5586
5587 case SUPLDRLOADEP_SERVICE:
5588 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.Service.pfnServiceReq, false, pReq->u.In.abImage, "pfnServiceReq", pReq);
5589 if (RT_FAILURE(rc))
5590 return rc;
5591 if ( pReq->u.In.EP.Service.apvReserved[0] != NIL_RTR0PTR
5592 || pReq->u.In.EP.Service.apvReserved[1] != NIL_RTR0PTR
5593 || pReq->u.In.EP.Service.apvReserved[2] != NIL_RTR0PTR)
5594 {
5595 supdrvLdrUnlock(pDevExt);
5596 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq, "apvReserved={%p,%p,%p} MBZ!",
5597 pReq->u.In.EP.Service.apvReserved[0], pReq->u.In.EP.Service.apvReserved[1],
5598 pReq->u.In.EP.Service.apvReserved[2]);
5599 }
5600 break;
5601
5602 default:
5603 supdrvLdrUnlock(pDevExt);
5604 return supdrvLdrLoadError(VERR_INVALID_PARAMETER, pReq, "Invalid eEPType=%d", pReq->u.In.eEPType);
5605 }
5606
5607 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.pfnModuleInit, true, pReq->u.In.abImage, "ModuleInit", pReq);
5608 if (RT_FAILURE(rc))
5609 return rc;
5610 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.pfnModuleTerm, true, pReq->u.In.abImage, "ModuleTerm", pReq);
5611 if (RT_FAILURE(rc))
5612 return rc;
5613 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5614
5615 /*
5616 * Allocate and copy the tables if non-native.
5617 * (No need to do try/except as this is a buffered request.)
5618 */
5619 if (!pImage->fNative)
5620 {
5621 pImage->cbStrTab = pReq->u.In.cbStrTab;
5622 if (pImage->cbStrTab)
5623 {
5624 pImage->pachStrTab = (char *)RTMemDup(&pReq->u.In.abImage[pReq->u.In.offStrTab], pImage->cbStrTab);
5625 if (!pImage->pachStrTab)
5626 rc = supdrvLdrLoadError(VERR_NO_MEMORY, pReq, "Out of memory for string table: %#x", pImage->cbStrTab);
5627 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5628 }
5629
5630 pImage->cSymbols = pReq->u.In.cSymbols;
5631 if (RT_SUCCESS(rc) && pImage->cSymbols)
5632 {
5633 size_t cbSymbols = pImage->cSymbols * sizeof(SUPLDRSYM);
5634 pImage->paSymbols = (PSUPLDRSYM)RTMemDup(&pReq->u.In.abImage[pReq->u.In.offSymbols], cbSymbols);
5635 if (!pImage->paSymbols)
5636 rc = supdrvLdrLoadError(VERR_NO_MEMORY, pReq, "Out of memory for symbol table: %#x", cbSymbols);
5637 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5638 }
5639 }
5640
5641 /*
5642 * Copy the bits and apply permissions / complete native loading.
5643 */
5644 if (RT_SUCCESS(rc))
5645 {
5646 pImage->uState = SUP_IOCTL_LDR_LOAD;
5647 pImage->pfnModuleInit = (PFNR0MODULEINIT)(uintptr_t)pReq->u.In.pfnModuleInit;
5648 pImage->pfnModuleTerm = (PFNR0MODULETERM)(uintptr_t)pReq->u.In.pfnModuleTerm;
5649
5650 if (pImage->fNative)
5651 rc = supdrvOSLdrLoad(pDevExt, pImage, pReq->u.In.abImage, pReq);
5652 else
5653 {
5654 uint32_t i;
5655 memcpy(pImage->pvImage, &pReq->u.In.abImage[0], pImage->cbImageBits);
5656
5657 for (i = 0; i < pImage->cSegments; i++)
5658 {
5659 rc = RTR0MemObjProtect(pImage->hMemObjImage, pImage->paSegments[i].off, pImage->paSegments[i].cb,
5660 pImage->paSegments[i].fProt);
5661 if (RT_SUCCESS(rc))
5662 continue;
5663 if (rc == VERR_NOT_SUPPORTED)
5664 rc = VINF_SUCCESS;
5665 else
5666 rc = supdrvLdrLoadError(rc, pReq, "RTR0MemObjProtect failed on seg#%u %#RX32 LB %#RX32 fProt=%#x",
5667 i, pImage->paSegments[i].off, pImage->paSegments[i].cb, pImage->paSegments[i].fProt);
5668 break;
5669 }
5670 Log(("vboxdrv: Loaded '%s' at %p\n", pImage->szName, pImage->pvImage));
5671 }
5672 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5673 }
5674
5675 /*
5676 * On success call the module initialization.
5677 */
5678 LogFlow(("supdrvIOCtl_LdrLoad: pfnModuleInit=%p\n", pImage->pfnModuleInit));
5679 if (RT_SUCCESS(rc) && pImage->pfnModuleInit)
5680 {
5681 Log(("supdrvIOCtl_LdrLoad: calling pfnModuleInit=%p\n", pImage->pfnModuleInit));
5682 pDevExt->pLdrInitImage = pImage;
5683 pDevExt->hLdrInitThread = RTThreadNativeSelf();
5684 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5685 rc = pImage->pfnModuleInit(pImage);
5686 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5687 pDevExt->pLdrInitImage = NULL;
5688 pDevExt->hLdrInitThread = NIL_RTNATIVETHREAD;
5689 if (RT_FAILURE(rc))
5690 supdrvLdrLoadError(rc, pReq, "ModuleInit failed: %Rrc", rc);
5691 }
5692 if (RT_SUCCESS(rc))
5693 {
5694 /*
5695 * Publish any standard entry points.
5696 */
5697 switch (pReq->u.In.eEPType)
5698 {
5699 case SUPLDRLOADEP_VMMR0:
5700 Assert(!pDevExt->pvVMMR0);
5701 Assert(!pDevExt->pfnVMMR0EntryFast);
5702 Assert(!pDevExt->pfnVMMR0EntryEx);
5703 ASMAtomicWritePtrVoid(&pDevExt->pvVMMR0, pImage->pvImage);
5704 ASMAtomicWritePtrVoid((void * volatile *)(uintptr_t)&pDevExt->pfnVMMR0EntryFast,
5705 (void *)(uintptr_t) pReq->u.In.EP.VMMR0.pvVMMR0EntryFast);
5706 ASMAtomicWritePtrVoid((void * volatile *)(uintptr_t)&pDevExt->pfnVMMR0EntryEx,
5707 (void *)(uintptr_t) pReq->u.In.EP.VMMR0.pvVMMR0EntryEx);
5708 break;
5709 case SUPLDRLOADEP_SERVICE:
5710 pImage->pfnServiceReqHandler = (PFNSUPR0SERVICEREQHANDLER)(uintptr_t)pReq->u.In.EP.Service.pfnServiceReq;
5711 break;
5712 default:
5713 break;
5714 }
5715
5716 /*
5717 * Increase the usage counter of any imported image.
5718 */
5719 if (pImageImport)
5720 {
5721 pImageImport->cImgUsage++;
5722 if (pImageImport->cImgUsage == 2 && pImageImport->pWrappedModInfo)
5723 supdrvOSLdrRetainWrapperModule(pDevExt, pImageImport);
5724 pImage->pImageImport = pImageImport;
5725 }
5726
5727 /*
5728 * Done!
5729 */
5730 SUPR0Printf("vboxdrv: %RKv %s\n", pImage->pvImage, pImage->szName);
5731 pReq->u.Out.uErrorMagic = 0;
5732 pReq->u.Out.szError[0] = '\0';
5733 }
5734 else
5735 {
5736 /* Inform the tracing component in case ModuleInit registered TPs. */
5737 supdrvTracerModuleUnloading(pDevExt, pImage);
5738
5739 pImage->uState = SUP_IOCTL_LDR_OPEN;
5740 pImage->pfnModuleInit = NULL;
5741 pImage->pfnModuleTerm = NULL;
5742 pImage->pfnServiceReqHandler= NULL;
5743 pImage->cbStrTab = 0;
5744 RTMemFree(pImage->pachStrTab);
5745 pImage->pachStrTab = NULL;
5746 RTMemFree(pImage->paSymbols);
5747 pImage->paSymbols = NULL;
5748 pImage->cSymbols = 0;
5749 }
5750
5751 supdrvLdrUnlock(pDevExt);
5752 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5753 return rc;
5754}
5755
5756
5757/**
5758 * Registers a .r0 module wrapped in a native one and manually loaded.
5759 *
5760 * @returns VINF_SUCCESS or error code (no info statuses).
5761 * @param pDevExt Device globals.
5762 * @param pWrappedModInfo The wrapped module info.
5763 * @param pvNative OS specific information.
5764 * @param phMod Where to store the module handle.
5765 */
5766int VBOXCALL supdrvLdrRegisterWrappedModule(PSUPDRVDEVEXT pDevExt, PCSUPLDRWRAPPEDMODULE pWrappedModInfo,
5767 void *pvNative, void **phMod)
5768{
5769 size_t cchName;
5770 PSUPDRVLDRIMAGE pImage;
5771 PCSUPLDRWRAPMODSYMBOL paSymbols;
5772 uint16_t idx;
5773 const char *pszPrevSymbol;
5774 int rc;
5775 SUPDRV_CHECK_SMAP_SETUP();
5776 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5777
5778 /*
5779 * Validate input.
5780 */
5781 AssertPtrReturn(phMod, VERR_INVALID_POINTER);
5782 *phMod = NULL;
5783 AssertPtrReturn(pDevExt, VERR_INTERNAL_ERROR_2);
5784
5785 AssertPtrReturn(pWrappedModInfo, VERR_INVALID_POINTER);
5786 AssertMsgReturn(pWrappedModInfo->uMagic == SUPLDRWRAPPEDMODULE_MAGIC,
5787 ("uMagic=%#x, expected %#x\n", pWrappedModInfo->uMagic, SUPLDRWRAPPEDMODULE_MAGIC),
5788 VERR_INVALID_MAGIC);
5789 AssertMsgReturn(pWrappedModInfo->uVersion == SUPLDRWRAPPEDMODULE_VERSION,
5790 ("Unsupported uVersion=%#x, current version %#x\n", pWrappedModInfo->uVersion, SUPLDRWRAPPEDMODULE_VERSION),
5791 VERR_VERSION_MISMATCH);
5792 AssertMsgReturn(pWrappedModInfo->uEndMagic == SUPLDRWRAPPEDMODULE_MAGIC,
5793 ("uEndMagic=%#x, expected %#x\n", pWrappedModInfo->uEndMagic, SUPLDRWRAPPEDMODULE_MAGIC),
5794 VERR_INVALID_MAGIC);
5795 AssertMsgReturn(pWrappedModInfo->fFlags <= SUPLDRWRAPPEDMODULE_F_VMMR0, ("Unknown flags in: %#x\n", pWrappedModInfo->fFlags),
5796 VERR_INVALID_FLAGS);
5797
5798 /* szName: */
5799 AssertReturn(RTStrEnd(pWrappedModInfo->szName, sizeof(pWrappedModInfo->szName)) != NULL, VERR_INVALID_NAME);
5800 AssertReturn(supdrvIsLdrModuleNameValid(pWrappedModInfo->szName), VERR_INVALID_NAME);
5801 AssertCompile(sizeof(pImage->szName) == sizeof(pWrappedModInfo->szName));
5802 cchName = strlen(pWrappedModInfo->szName);
5803
5804 /* Image range: */
5805 AssertPtrReturn(pWrappedModInfo->pvImageStart, VERR_INVALID_POINTER);
5806 AssertPtrReturn(pWrappedModInfo->pvImageEnd, VERR_INVALID_POINTER);
5807 AssertReturn((uintptr_t)pWrappedModInfo->pvImageEnd > (uintptr_t)pWrappedModInfo->pvImageStart, VERR_INVALID_PARAMETER);
5808
5809 /* Symbol table: */
5810 AssertMsgReturn(pWrappedModInfo->cSymbols <= _8K, ("Too many symbols: %u, max 8192\n", pWrappedModInfo->cSymbols),
5811 VERR_TOO_MANY_SYMLINKS);
5812 pszPrevSymbol = "\x7f";
5813 paSymbols = pWrappedModInfo->paSymbols;
5814 idx = pWrappedModInfo->cSymbols;
5815 while (idx-- > 0)
5816 {
5817 const char *pszSymbol = paSymbols[idx].pszSymbol;
5818 AssertMsgReturn(RT_VALID_PTR(pszSymbol) && RT_VALID_PTR(paSymbols[idx].pfnValue),
5819 ("paSymbols[%u]: %p/%p\n", idx, pszSymbol, paSymbols[idx].pfnValue),
5820 VERR_INVALID_POINTER);
5821 AssertReturn(*pszSymbol != '\0', VERR_EMPTY_STRING);
5822 AssertMsgReturn(strcmp(pszSymbol, pszPrevSymbol) < 0,
5823 ("symbol table out of order at index %u: '%s' vs '%s'\n", idx, pszSymbol, pszPrevSymbol),
5824 VERR_WRONG_ORDER);
5825 pszPrevSymbol = pszSymbol;
5826 }
5827
5828 /* Standard entry points: */
5829 AssertPtrNullReturn(pWrappedModInfo->pfnModuleInit, VERR_INVALID_POINTER);
5830 AssertPtrNullReturn(pWrappedModInfo->pfnModuleTerm, VERR_INVALID_POINTER);
5831 AssertReturn((uintptr_t)pWrappedModInfo->pfnModuleInit != (uintptr_t)pWrappedModInfo->pfnModuleTerm || pWrappedModInfo->pfnModuleInit == NULL,
5832 VERR_INVALID_PARAMETER);
5833 if (pWrappedModInfo->fFlags & SUPLDRWRAPPEDMODULE_F_VMMR0)
5834 {
5835 AssertReturn(pWrappedModInfo->pfnServiceReqHandler == NULL, VERR_INVALID_PARAMETER);
5836 AssertPtrReturn(pWrappedModInfo->pfnVMMR0EntryFast, VERR_INVALID_POINTER);
5837 AssertPtrReturn(pWrappedModInfo->pfnVMMR0EntryEx, VERR_INVALID_POINTER);
5838 AssertReturn(pWrappedModInfo->pfnVMMR0EntryFast != pWrappedModInfo->pfnVMMR0EntryEx, VERR_INVALID_PARAMETER);
5839 }
5840 else
5841 {
5842 AssertPtrNullReturn(pWrappedModInfo->pfnServiceReqHandler, VERR_INVALID_POINTER);
5843 AssertReturn(pWrappedModInfo->pfnVMMR0EntryFast == NULL, VERR_INVALID_PARAMETER);
5844 AssertReturn(pWrappedModInfo->pfnVMMR0EntryEx == NULL, VERR_INVALID_PARAMETER);
5845 }
5846
5847 /*
5848 * Check if we got an instance of the image already.
5849 */
5850 supdrvLdrLock(pDevExt);
5851 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5852 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
5853 {
5854 if ( pImage->szName[cchName] == '\0'
5855 && !memcmp(pImage->szName, pWrappedModInfo->szName, cchName))
5856 {
5857 supdrvLdrUnlock(pDevExt);
5858 Log(("supdrvLdrRegisterWrappedModule: '%s' already loaded!\n", pWrappedModInfo->szName));
5859 return VERR_ALREADY_LOADED;
5860 }
5861 }
5862 /* (not found - add it!) */
5863
5864 /* If the loader interface is locked down, make userland fail early */
5865 if (pDevExt->fLdrLockedDown)
5866 {
5867 supdrvLdrUnlock(pDevExt);
5868 Log(("supdrvLdrRegisterWrappedModule: Not adding '%s' to image list, loader interface is locked down!\n", pWrappedModInfo->szName));
5869 return VERR_PERMISSION_DENIED;
5870 }
5871
5872 /* Only one VMMR0: */
5873 if ( pDevExt->pvVMMR0 != NULL
5874 && (pWrappedModInfo->fFlags & SUPLDRWRAPPEDMODULE_F_VMMR0))
5875 {
5876 supdrvLdrUnlock(pDevExt);
5877 Log(("supdrvLdrRegisterWrappedModule: Rejecting '%s' as we already got a VMMR0 module!\n", pWrappedModInfo->szName));
5878 return VERR_ALREADY_EXISTS;
5879 }
5880
5881 /*
5882 * Allocate memory.
5883 */
5884 Assert(cchName < sizeof(pImage->szName));
5885 pImage = (PSUPDRVLDRIMAGE)RTMemAllocZ(sizeof(SUPDRVLDRIMAGE));
5886 if (!pImage)
5887 {
5888 supdrvLdrUnlock(pDevExt);
5889 Log(("supdrvLdrRegisterWrappedModule: RTMemAllocZ() failed\n"));
5890 return VERR_NO_MEMORY;
5891 }
5892 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5893
5894 /*
5895 * Setup and link in the LDR stuff.
5896 */
5897 pImage->pvImage = (void *)pWrappedModInfo->pvImageStart;
5898 pImage->hMemObjImage = NIL_RTR0MEMOBJ;
5899 pImage->cbImageWithEverything
5900 = pImage->cbImageBits = (uintptr_t)pWrappedModInfo->pvImageEnd - (uintptr_t)pWrappedModInfo->pvImageStart;
5901 pImage->cSymbols = 0;
5902 pImage->paSymbols = NULL;
5903 pImage->pachStrTab = NULL;
5904 pImage->cbStrTab = 0;
5905 pImage->cSegments = 0;
5906 pImage->paSegments = NULL;
5907 pImage->pfnModuleInit = pWrappedModInfo->pfnModuleInit;
5908 pImage->pfnModuleTerm = pWrappedModInfo->pfnModuleTerm;
5909 pImage->pfnServiceReqHandler = NULL; /* Only setting this after module init */
5910 pImage->uState = SUP_IOCTL_LDR_LOAD;
5911 pImage->cImgUsage = 1; /* Held by the wrapper module till unload. */
5912 pImage->pDevExt = pDevExt;
5913 pImage->pImageImport = NULL;
5914 pImage->uMagic = SUPDRVLDRIMAGE_MAGIC;
5915 pImage->pWrappedModInfo = pWrappedModInfo;
5916 pImage->pvWrappedNative = pvNative;
5917 pImage->fNative = true;
5918 memcpy(pImage->szName, pWrappedModInfo->szName, cchName + 1);
5919
5920 /*
5921 * Link it.
5922 */
5923 pImage->pNext = pDevExt->pLdrImages;
5924 pDevExt->pLdrImages = pImage;
5925
5926 /*
5927 * Call module init function if found.
5928 */
5929 rc = VINF_SUCCESS;
5930 if (pImage->pfnModuleInit)
5931 {
5932 Log(("supdrvIOCtl_LdrLoad: calling pfnModuleInit=%p\n", pImage->pfnModuleInit));
5933 pDevExt->pLdrInitImage = pImage;
5934 pDevExt->hLdrInitThread = RTThreadNativeSelf();
5935 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5936 rc = pImage->pfnModuleInit(pImage);
5937 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5938 pDevExt->pLdrInitImage = NULL;
5939 pDevExt->hLdrInitThread = NIL_RTNATIVETHREAD;
5940 }
5941 if (RT_SUCCESS(rc))
5942 {
5943 /*
5944 * Update entry points.
5945 */
5946 if (pWrappedModInfo->fFlags & SUPLDRWRAPPEDMODULE_F_VMMR0)
5947 {
5948 Assert(!pDevExt->pvVMMR0);
5949 Assert(!pDevExt->pfnVMMR0EntryFast);
5950 Assert(!pDevExt->pfnVMMR0EntryEx);
5951 ASMAtomicWritePtrVoid(&pDevExt->pvVMMR0, pImage->pvImage);
5952 ASMAtomicWritePtrVoid((void * volatile *)(uintptr_t)&pDevExt->pfnVMMR0EntryFast,
5953 (void *)(uintptr_t) pWrappedModInfo->pfnVMMR0EntryFast);
5954 ASMAtomicWritePtrVoid((void * volatile *)(uintptr_t)&pDevExt->pfnVMMR0EntryEx,
5955 (void *)(uintptr_t) pWrappedModInfo->pfnVMMR0EntryEx);
5956 }
5957 else
5958 pImage->pfnServiceReqHandler = pWrappedModInfo->pfnServiceReqHandler;
5959#ifdef IN_RING3
5960# error "WTF?"
5961#endif
5962 *phMod = pImage;
5963 }
5964 else
5965 {
5966 /*
5967 * Module init failed - bail, no module term callout.
5968 */
5969 SUPR0Printf("ModuleInit failed for '%s': %Rrc\n", pImage->szName, rc);
5970
5971 pImage->pfnModuleTerm = NULL;
5972 pImage->uState = SUP_IOCTL_LDR_OPEN;
5973 supdrvLdrFree(pDevExt, pImage);
5974 }
5975
5976 supdrvLdrUnlock(pDevExt);
5977 SUPDRV_CHECK_SMAP_CHECK(pDevExt, RT_NOTHING);
5978 return VINF_SUCCESS;
5979}
5980
5981
5982/**
5983 * Decrements SUPDRVLDRIMAGE::cImgUsage when two or greater.
5984 *
5985 * @param pDevExt Device globals.
5986 * @param pImage The image.
5987 * @param cReference Number of references being removed.
5988 */
5989DECLINLINE(void) supdrvLdrSubtractUsage(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, uint32_t cReference)
5990{
5991 Assert(cReference > 0);
5992 Assert(pImage->cImgUsage > cReference);
5993 pImage->cImgUsage -= cReference;
5994 if (pImage->cImgUsage == 1 && pImage->pWrappedModInfo)
5995 supdrvOSLdrReleaseWrapperModule(pDevExt, pImage);
5996}
5997
5998
5999/**
6000 * Frees a previously loaded (prep'ed) image.
6001 *
6002 * @returns IPRT status code.
6003 * @param pDevExt Device globals.
6004 * @param pSession Session data.
6005 * @param pReq The request.
6006 */
6007static int supdrvIOCtl_LdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRFREE pReq)
6008{
6009 int rc;
6010 PSUPDRVLDRUSAGE pUsagePrev;
6011 PSUPDRVLDRUSAGE pUsage;
6012 PSUPDRVLDRIMAGE pImage;
6013 LogFlow(("supdrvIOCtl_LdrFree: pvImageBase=%p\n", pReq->u.In.pvImageBase));
6014
6015 /*
6016 * Find the ldr image.
6017 */
6018 supdrvLdrLock(pDevExt);
6019 pUsagePrev = NULL;
6020 pUsage = pSession->pLdrUsage;
6021 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
6022 {
6023 pUsagePrev = pUsage;
6024 pUsage = pUsage->pNext;
6025 }
6026 if (!pUsage)
6027 {
6028 supdrvLdrUnlock(pDevExt);
6029 Log(("SUP_IOCTL_LDR_FREE: couldn't find image!\n"));
6030 return VERR_INVALID_HANDLE;
6031 }
6032 if (pUsage->cRing3Usage == 0)
6033 {
6034 supdrvLdrUnlock(pDevExt);
6035 Log(("SUP_IOCTL_LDR_FREE: No ring-3 reference to the image!\n"));
6036 return VERR_CALLER_NO_REFERENCE;
6037 }
6038
6039 /*
6040 * Check if we can remove anything.
6041 */
6042 rc = VINF_SUCCESS;
6043 pImage = pUsage->pImage;
6044 Log(("SUP_IOCTL_LDR_FREE: pImage=%p %s cImgUsage=%d r3=%d r0=%u\n",
6045 pImage, pImage->szName, pImage->cImgUsage, pUsage->cRing3Usage, pUsage->cRing0Usage));
6046 if (pImage->cImgUsage <= 1 || pUsage->cRing3Usage + pUsage->cRing0Usage <= 1)
6047 {
6048 /*
6049 * Check if there are any objects with destructors in the image, if
6050 * so leave it for the session cleanup routine so we get a chance to
6051 * clean things up in the right order and not leave them all dangling.
6052 */
6053 RTSpinlockAcquire(pDevExt->Spinlock);
6054 if (pImage->cImgUsage <= 1)
6055 {
6056 PSUPDRVOBJ pObj;
6057 for (pObj = pDevExt->pObjs; pObj; pObj = pObj->pNext)
6058 if (RT_UNLIKELY((uintptr_t)pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
6059 {
6060 rc = VERR_DANGLING_OBJECTS;
6061 break;
6062 }
6063 }
6064 else
6065 {
6066 PSUPDRVUSAGE pGenUsage;
6067 for (pGenUsage = pSession->pUsage; pGenUsage; pGenUsage = pGenUsage->pNext)
6068 if (RT_UNLIKELY((uintptr_t)pGenUsage->pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
6069 {
6070 rc = VERR_DANGLING_OBJECTS;
6071 break;
6072 }
6073 }
6074 RTSpinlockRelease(pDevExt->Spinlock);
6075 if (rc == VINF_SUCCESS)
6076 {
6077 /* unlink it */
6078 if (pUsagePrev)
6079 pUsagePrev->pNext = pUsage->pNext;
6080 else
6081 pSession->pLdrUsage = pUsage->pNext;
6082
6083 /* free it */
6084 pUsage->pImage = NULL;
6085 pUsage->pNext = NULL;
6086 RTMemFree(pUsage);
6087
6088 /*
6089 * Dereference the image.
6090 */
6091 if (pImage->cImgUsage <= 1)
6092 supdrvLdrFree(pDevExt, pImage);
6093 else
6094 supdrvLdrSubtractUsage(pDevExt, pImage, 1);
6095 }
6096 else
6097 Log(("supdrvIOCtl_LdrFree: Dangling objects in %p/%s!\n", pImage->pvImage, pImage->szName));
6098 }
6099 else
6100 {
6101 /*
6102 * Dereference both image and usage.
6103 */
6104 pUsage->cRing3Usage--;
6105 supdrvLdrSubtractUsage(pDevExt, pImage, 1);
6106 }
6107
6108 supdrvLdrUnlock(pDevExt);
6109 return rc;
6110}
6111
6112
6113/**
6114 * Deregisters a wrapped .r0 module.
6115 *
6116 * @param pDevExt Device globals.
6117 * @param pWrappedModInfo The wrapped module info.
6118 * @param phMod Where to store the module is stored (NIL'ed on
6119 * success).
6120 */
6121int VBOXCALL supdrvLdrDeregisterWrappedModule(PSUPDRVDEVEXT pDevExt, PCSUPLDRWRAPPEDMODULE pWrappedModInfo, void **phMod)
6122{
6123 PSUPDRVLDRIMAGE pImage;
6124 uint32_t cSleeps;
6125
6126 /*
6127 * Validate input.
6128 */
6129 AssertPtrReturn(pWrappedModInfo, VERR_INVALID_POINTER);
6130 AssertMsgReturn(pWrappedModInfo->uMagic == SUPLDRWRAPPEDMODULE_MAGIC,
6131 ("uMagic=%#x, expected %#x\n", pWrappedModInfo->uMagic, SUPLDRWRAPPEDMODULE_MAGIC),
6132 VERR_INVALID_MAGIC);
6133 AssertMsgReturn(pWrappedModInfo->uEndMagic == SUPLDRWRAPPEDMODULE_MAGIC,
6134 ("uEndMagic=%#x, expected %#x\n", pWrappedModInfo->uEndMagic, SUPLDRWRAPPEDMODULE_MAGIC),
6135 VERR_INVALID_MAGIC);
6136
6137 AssertPtrReturn(phMod, VERR_INVALID_POINTER);
6138 pImage = *(PSUPDRVLDRIMAGE *)phMod;
6139 if (!pImage)
6140 return VINF_SUCCESS;
6141 AssertPtrReturn(pImage, VERR_INVALID_POINTER);
6142 AssertMsgReturn(pImage->uMagic == SUPDRVLDRIMAGE_MAGIC, ("pImage=%p uMagic=%#x\n", pImage, pImage->uMagic),
6143 VERR_INVALID_MAGIC);
6144 AssertMsgReturn(pImage->pvImage == pWrappedModInfo->pvImageStart,
6145 ("pWrappedModInfo(%p)->pvImageStart=%p vs. pImage(=%p)->pvImage=%p\n",
6146 pWrappedModInfo, pWrappedModInfo->pvImageStart, pImage, pImage->pvImage),
6147 VERR_MISMATCH);
6148
6149 AssertPtrReturn(pDevExt, VERR_INVALID_POINTER);
6150
6151 /*
6152 * Try free it, but first we have to wait for its usage count to reach 1 (our).
6153 */
6154 supdrvLdrLock(pDevExt);
6155 for (cSleeps = 0; ; cSleeps++)
6156 {
6157 PSUPDRVLDRIMAGE pCur;
6158
6159 /* Check that the image is in the list. */
6160 for (pCur = pDevExt->pLdrImages; pCur; pCur = pCur->pNext)
6161 if (pCur == pImage)
6162 break;
6163 AssertBreak(pCur == pImage);
6164
6165 /* Anyone still using it? */
6166 if (pImage->cImgUsage <= 1)
6167 break;
6168
6169 /* Someone is using it, wait and check again. */
6170 if (!(cSleeps % 60))
6171 SUPR0Printf("supdrvLdrUnregisterWrappedModule: Still %u users of wrapped image '%s' ...\n",
6172 pImage->cImgUsage, pImage->szName);
6173 supdrvLdrUnlock(pDevExt);
6174 RTThreadSleep(1000);
6175 supdrvLdrLock(pDevExt);
6176 }
6177
6178 /* We're the last 'user', free it. */
6179 supdrvLdrFree(pDevExt, pImage);
6180
6181 supdrvLdrUnlock(pDevExt);
6182
6183 *phMod = NULL;
6184 return VINF_SUCCESS;
6185}
6186
6187
6188/**
6189 * Lock down the image loader interface.
6190 *
6191 * @returns IPRT status code.
6192 * @param pDevExt Device globals.
6193 */
6194static int supdrvIOCtl_LdrLockDown(PSUPDRVDEVEXT pDevExt)
6195{
6196 LogFlow(("supdrvIOCtl_LdrLockDown:\n"));
6197
6198 supdrvLdrLock(pDevExt);
6199 if (!pDevExt->fLdrLockedDown)
6200 {
6201 pDevExt->fLdrLockedDown = true;
6202 Log(("supdrvIOCtl_LdrLockDown: Image loader interface locked down\n"));
6203 }
6204 supdrvLdrUnlock(pDevExt);
6205
6206 return VINF_SUCCESS;
6207}
6208
6209
6210/**
6211 * Worker for getting the address of a symbol in an image.
6212 *
6213 * @returns IPRT status code.
6214 * @param pDevExt Device globals.
6215 * @param pImage The image to search.
6216 * @param pszSymbol The symbol name.
6217 * @param cchSymbol The length of the symbol name.
6218 * @param ppvValue Where to return the symbol
6219 * @note Caller owns the loader lock.
6220 */
6221static int supdrvLdrQuerySymbolWorker(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage,
6222 const char *pszSymbol, size_t cchSymbol, void **ppvValue)
6223{
6224 int rc = VERR_SYMBOL_NOT_FOUND;
6225 if (pImage->fNative && !pImage->pWrappedModInfo)
6226 rc = supdrvOSLdrQuerySymbol(pDevExt, pImage, pszSymbol, cchSymbol, ppvValue);
6227 else if (pImage->fNative && pImage->pWrappedModInfo)
6228 {
6229 PCSUPLDRWRAPMODSYMBOL paSymbols = pImage->pWrappedModInfo->paSymbols;
6230 uint32_t iEnd = pImage->pWrappedModInfo->cSymbols;
6231 uint32_t iStart = 0;
6232 while (iStart < iEnd)
6233 {
6234 uint32_t const i = iStart + (iEnd - iStart) / 2;
6235 int const iDiff = strcmp(paSymbols[i].pszSymbol, pszSymbol);
6236 if (iDiff < 0)
6237 iStart = i + 1;
6238 else if (iDiff > 0)
6239 iEnd = i;
6240 else
6241 {
6242 *ppvValue = (void *)(uintptr_t)paSymbols[i].pfnValue;
6243 rc = VINF_SUCCESS;
6244 break;
6245 }
6246 }
6247#ifdef VBOX_STRICT
6248 if (rc != VINF_SUCCESS)
6249 for (iStart = 0, iEnd = pImage->pWrappedModInfo->cSymbols; iStart < iEnd; iStart++)
6250 Assert(strcmp(paSymbols[iStart].pszSymbol, pszSymbol));
6251#endif
6252 }
6253 else
6254 {
6255 const char *pchStrings = pImage->pachStrTab;
6256 PSUPLDRSYM paSyms = pImage->paSymbols;
6257 uint32_t i;
6258 Assert(!pImage->pWrappedModInfo);
6259 for (i = 0; i < pImage->cSymbols; i++)
6260 {
6261 if ( paSyms[i].offName + cchSymbol + 1 <= pImage->cbStrTab
6262 && !memcmp(pchStrings + paSyms[i].offName, pszSymbol, cchSymbol + 1))
6263 {
6264 /*
6265 * Note! The int32_t is for native loading on solaris where the data
6266 * and text segments are in very different places.
6267 */
6268 *ppvValue = (uint8_t *)pImage->pvImage + (int32_t)paSyms[i].offSymbol;
6269 rc = VINF_SUCCESS;
6270 break;
6271 }
6272 }
6273 }
6274 return rc;
6275}
6276
6277
6278/**
6279 * Queries the address of a symbol in an open image.
6280 *
6281 * @returns IPRT status code.
6282 * @param pDevExt Device globals.
6283 * @param pSession Session data.
6284 * @param pReq The request buffer.
6285 */
6286static int supdrvIOCtl_LdrQuerySymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRGETSYMBOL pReq)
6287{
6288 PSUPDRVLDRIMAGE pImage;
6289 PSUPDRVLDRUSAGE pUsage;
6290 const size_t cchSymbol = strlen(pReq->u.In.szSymbol);
6291 void *pvSymbol = NULL;
6292 int rc;
6293 Log3(("supdrvIOCtl_LdrQuerySymbol: pvImageBase=%p szSymbol=\"%s\"\n", pReq->u.In.pvImageBase, pReq->u.In.szSymbol));
6294
6295 /*
6296 * Find the ldr image.
6297 */
6298 supdrvLdrLock(pDevExt);
6299
6300 pUsage = pSession->pLdrUsage;
6301 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
6302 pUsage = pUsage->pNext;
6303 if (pUsage)
6304 {
6305 pImage = pUsage->pImage;
6306 if (pImage->uState == SUP_IOCTL_LDR_LOAD)
6307 {
6308 /*
6309 * Search the image exports / symbol strings.
6310 */
6311 rc = supdrvLdrQuerySymbolWorker(pDevExt, pImage, pReq->u.In.szSymbol, cchSymbol, &pvSymbol);
6312 }
6313 else
6314 {
6315 Log(("SUP_IOCTL_LDR_GET_SYMBOL: invalid image state %d (%#x)!\n", pImage->uState, pImage->uState));
6316 rc = VERR_WRONG_ORDER;
6317 }
6318 }
6319 else
6320 {
6321 Log(("SUP_IOCTL_LDR_GET_SYMBOL: couldn't find image!\n"));
6322 rc = VERR_INVALID_HANDLE;
6323 }
6324
6325 supdrvLdrUnlock(pDevExt);
6326
6327 pReq->u.Out.pvSymbol = pvSymbol;
6328 return rc;
6329}
6330
6331
6332/**
6333 * Gets the address of a symbol in an open image or the support driver.
6334 *
6335 * @returns VBox status code.
6336 * @param pDevExt Device globals.
6337 * @param pSession Session data.
6338 * @param pReq The request buffer.
6339 */
6340static int supdrvIDC_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVIDCREQGETSYM pReq)
6341{
6342 const char *pszSymbol = pReq->u.In.pszSymbol;
6343 const char *pszModule = pReq->u.In.pszModule;
6344 size_t cchSymbol;
6345 char const *pszEnd;
6346 uint32_t i;
6347 int rc;
6348
6349 /*
6350 * Input validation.
6351 */
6352 AssertPtrReturn(pszSymbol, VERR_INVALID_POINTER);
6353 pszEnd = RTStrEnd(pszSymbol, 512);
6354 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
6355 cchSymbol = pszEnd - pszSymbol;
6356
6357 if (pszModule)
6358 {
6359 AssertPtrReturn(pszModule, VERR_INVALID_POINTER);
6360 pszEnd = RTStrEnd(pszModule, 64);
6361 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
6362 }
6363 Log3(("supdrvIDC_LdrGetSymbol: pszModule=%p:{%s} pszSymbol=%p:{%s}\n", pszModule, pszModule, pszSymbol, pszSymbol));
6364
6365 if ( !pszModule
6366 || !strcmp(pszModule, "SupDrv"))
6367 {
6368 /*
6369 * Search the support driver export table.
6370 */
6371 rc = VERR_SYMBOL_NOT_FOUND;
6372 for (i = 0; i < RT_ELEMENTS(g_aFunctions); i++)
6373 if (!strcmp(g_aFunctions[i].szName, pszSymbol))
6374 {
6375 pReq->u.Out.pfnSymbol = (PFNRT)(uintptr_t)g_aFunctions[i].pfn;
6376 rc = VINF_SUCCESS;
6377 break;
6378 }
6379 }
6380 else
6381 {
6382 /*
6383 * Find the loader image.
6384 */
6385 PSUPDRVLDRIMAGE pImage;
6386
6387 supdrvLdrLock(pDevExt);
6388
6389 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
6390 if (!strcmp(pImage->szName, pszModule))
6391 break;
6392 if (pImage && pImage->uState == SUP_IOCTL_LDR_LOAD)
6393 {
6394 /*
6395 * Search the image exports / symbol strings. Do usage counting on the session.
6396 */
6397 rc = supdrvLdrQuerySymbolWorker(pDevExt, pImage, pszSymbol, cchSymbol, (void **)&pReq->u.Out.pfnSymbol);
6398 if (RT_SUCCESS(rc))
6399 rc = supdrvLdrAddUsage(pDevExt, pSession, pImage, true /*fRing3Usage*/);
6400 }
6401 else
6402 rc = pImage ? VERR_WRONG_ORDER : VERR_MODULE_NOT_FOUND;
6403
6404 supdrvLdrUnlock(pDevExt);
6405 }
6406 return rc;
6407}
6408
6409
6410/**
6411 * Looks up a symbol in g_aFunctions
6412 *
6413 * @returns VINF_SUCCESS on success, VERR_SYMBOL_NOT_FOUND on failure.
6414 * @param pszSymbol The symbol to look up.
6415 * @param puValue Where to return the value.
6416 */
6417int VBOXCALL supdrvLdrGetExportedSymbol(const char *pszSymbol, uintptr_t *puValue)
6418{
6419 uint32_t i;
6420 for (i = 0; i < RT_ELEMENTS(g_aFunctions); i++)
6421 if (!strcmp(g_aFunctions[i].szName, pszSymbol))
6422 {
6423 *puValue = (uintptr_t)g_aFunctions[i].pfn;
6424 return VINF_SUCCESS;
6425 }
6426
6427 if (!strcmp(pszSymbol, "g_SUPGlobalInfoPage"))
6428 {
6429 *puValue = (uintptr_t)g_pSUPGlobalInfoPage;
6430 return VINF_SUCCESS;
6431 }
6432
6433 return VERR_SYMBOL_NOT_FOUND;
6434}
6435
6436
6437/**
6438 * Adds a usage reference in the specified session of an image.
6439 *
6440 * Called while owning the loader semaphore.
6441 *
6442 * @returns VINF_SUCCESS on success and VERR_NO_MEMORY on failure.
6443 * @param pDevExt Pointer to device extension.
6444 * @param pSession Session in question.
6445 * @param pImage Image which the session is using.
6446 * @param fRing3Usage Set if it's ring-3 usage, clear if ring-0.
6447 */
6448static int supdrvLdrAddUsage(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVLDRIMAGE pImage, bool fRing3Usage)
6449{
6450 PSUPDRVLDRUSAGE pUsage;
6451 LogFlow(("supdrvLdrAddUsage: pImage=%p %d\n", pImage, fRing3Usage));
6452
6453 /*
6454 * Referenced it already?
6455 */
6456 pUsage = pSession->pLdrUsage;
6457 while (pUsage)
6458 {
6459 if (pUsage->pImage == pImage)
6460 {
6461 if (fRing3Usage)
6462 pUsage->cRing3Usage++;
6463 else
6464 pUsage->cRing0Usage++;
6465 Assert(pImage->cImgUsage > 1 || !pImage->pWrappedModInfo);
6466 pImage->cImgUsage++;
6467 return VINF_SUCCESS;
6468 }
6469 pUsage = pUsage->pNext;
6470 }
6471
6472 /*
6473 * Allocate new usage record.
6474 */
6475 pUsage = (PSUPDRVLDRUSAGE)RTMemAlloc(sizeof(*pUsage));
6476 AssertReturn(pUsage, VERR_NO_MEMORY);
6477 pUsage->cRing3Usage = fRing3Usage ? 1 : 0;
6478 pUsage->cRing0Usage = fRing3Usage ? 0 : 1;
6479 pUsage->pImage = pImage;
6480 pUsage->pNext = pSession->pLdrUsage;
6481 pSession->pLdrUsage = pUsage;
6482
6483 /*
6484 * Wrapped modules needs to retain a native module reference.
6485 */
6486 pImage->cImgUsage++;
6487 if (pImage->cImgUsage == 2 && pImage->pWrappedModInfo)
6488 supdrvOSLdrRetainWrapperModule(pDevExt, pImage);
6489
6490 return VINF_SUCCESS;
6491}
6492
6493
6494/**
6495 * Frees a load image.
6496 *
6497 * @param pDevExt Pointer to device extension.
6498 * @param pImage Pointer to the image we're gonna free.
6499 * This image must exit!
6500 * @remark The caller MUST own SUPDRVDEVEXT::mtxLdr!
6501 */
6502static void supdrvLdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage)
6503{
6504 unsigned cLoops;
6505 for (cLoops = 0; ; cLoops++)
6506 {
6507 PSUPDRVLDRIMAGE pImagePrev;
6508 PSUPDRVLDRIMAGE pImageImport;
6509 LogFlow(("supdrvLdrFree: pImage=%p %s [loop %u]\n", pImage, pImage->szName, cLoops));
6510 AssertBreak(cLoops < 2);
6511
6512 /*
6513 * Warn if we're releasing images while the image loader interface is
6514 * locked down -- we won't be able to reload them!
6515 */
6516 if (pDevExt->fLdrLockedDown)
6517 Log(("supdrvLdrFree: Warning: unloading '%s' image, while loader interface is locked down!\n", pImage->szName));
6518
6519 /* find it - arg. should've used doubly linked list. */
6520 Assert(pDevExt->pLdrImages);
6521 pImagePrev = NULL;
6522 if (pDevExt->pLdrImages != pImage)
6523 {
6524 pImagePrev = pDevExt->pLdrImages;
6525 while (pImagePrev->pNext != pImage)
6526 pImagePrev = pImagePrev->pNext;
6527 Assert(pImagePrev->pNext == pImage);
6528 }
6529
6530 /* unlink */
6531 if (pImagePrev)
6532 pImagePrev->pNext = pImage->pNext;
6533 else
6534 pDevExt->pLdrImages = pImage->pNext;
6535
6536 /* check if this is VMMR0.r0 unset its entry point pointers. */
6537 if (pDevExt->pvVMMR0 == pImage->pvImage)
6538 {
6539 pDevExt->pvVMMR0 = NULL;
6540 pDevExt->pfnVMMR0EntryFast = NULL;
6541 pDevExt->pfnVMMR0EntryEx = NULL;
6542 }
6543
6544 /* check for objects with destructors in this image. (Shouldn't happen.) */
6545 if (pDevExt->pObjs)
6546 {
6547 unsigned cObjs = 0;
6548 PSUPDRVOBJ pObj;
6549 RTSpinlockAcquire(pDevExt->Spinlock);
6550 for (pObj = pDevExt->pObjs; pObj; pObj = pObj->pNext)
6551 if (RT_UNLIKELY((uintptr_t)pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
6552 {
6553 pObj->pfnDestructor = NULL;
6554 cObjs++;
6555 }
6556 RTSpinlockRelease(pDevExt->Spinlock);
6557 if (cObjs)
6558 OSDBGPRINT(("supdrvLdrFree: Image '%s' has %d dangling objects!\n", pImage->szName, cObjs));
6559 }
6560
6561 /* call termination function if fully loaded. */
6562 if ( pImage->pfnModuleTerm
6563 && pImage->uState == SUP_IOCTL_LDR_LOAD)
6564 {
6565 LogFlow(("supdrvIOCtl_LdrLoad: calling pfnModuleTerm=%p\n", pImage->pfnModuleTerm));
6566 pDevExt->hLdrTermThread = RTThreadNativeSelf();
6567 pImage->pfnModuleTerm(pImage);
6568 pDevExt->hLdrTermThread = NIL_RTNATIVETHREAD;
6569 }
6570
6571 /* Inform the tracing component. */
6572 supdrvTracerModuleUnloading(pDevExt, pImage);
6573
6574 /* Do native unload if appropriate, then inform the native code about the
6575 unloading (mainly for non-native loading case). */
6576 if (pImage->fNative)
6577 supdrvOSLdrUnload(pDevExt, pImage);
6578 supdrvOSLdrNotifyUnloaded(pDevExt, pImage);
6579
6580 /* free the image */
6581 pImage->uMagic = SUPDRVLDRIMAGE_MAGIC_DEAD;
6582 pImage->cImgUsage = 0;
6583 pImage->pDevExt = NULL;
6584 pImage->pNext = NULL;
6585 pImage->uState = SUP_IOCTL_LDR_FREE;
6586 RTR0MemObjFree(pImage->hMemObjImage, true /*fMappings*/);
6587 pImage->hMemObjImage = NIL_RTR0MEMOBJ;
6588 pImage->pvImage = NULL;
6589 RTMemFree(pImage->pachStrTab);
6590 pImage->pachStrTab = NULL;
6591 RTMemFree(pImage->paSymbols);
6592 pImage->paSymbols = NULL;
6593 RTMemFree(pImage->paSegments);
6594 pImage->paSegments = NULL;
6595
6596 pImageImport = pImage->pImageImport;
6597 pImage->pImageImport = NULL;
6598
6599 RTMemFree(pImage);
6600
6601 /*
6602 * Deal with any import image.
6603 */
6604 if (!pImageImport)
6605 break;
6606 if (pImageImport->cImgUsage > 1)
6607 {
6608 supdrvLdrSubtractUsage(pDevExt, pImageImport, 1);
6609 break;
6610 }
6611 pImage = pImageImport;
6612 }
6613}
6614
6615
6616/**
6617 * Acquires the loader lock.
6618 *
6619 * @returns IPRT status code.
6620 * @param pDevExt The device extension.
6621 * @note Not recursive on all platforms yet.
6622 */
6623DECLINLINE(int) supdrvLdrLock(PSUPDRVDEVEXT pDevExt)
6624{
6625#ifdef SUPDRV_USE_MUTEX_FOR_LDR
6626 int rc = RTSemMutexRequest(pDevExt->mtxLdr, RT_INDEFINITE_WAIT);
6627#else
6628 int rc = RTSemFastMutexRequest(pDevExt->mtxLdr);
6629#endif
6630 AssertRC(rc);
6631 return rc;
6632}
6633
6634
6635/**
6636 * Releases the loader lock.
6637 *
6638 * @returns IPRT status code.
6639 * @param pDevExt The device extension.
6640 */
6641DECLINLINE(int) supdrvLdrUnlock(PSUPDRVDEVEXT pDevExt)
6642{
6643#ifdef SUPDRV_USE_MUTEX_FOR_LDR
6644 return RTSemMutexRelease(pDevExt->mtxLdr);
6645#else
6646 return RTSemFastMutexRelease(pDevExt->mtxLdr);
6647#endif
6648}
6649
6650
6651/**
6652 * Acquires the global loader lock.
6653 *
6654 * This can be useful when accessing structures being modified by the ModuleInit
6655 * and ModuleTerm. Use SUPR0LdrUnlock() to unlock.
6656 *
6657 * @returns VBox status code.
6658 * @param pSession The session doing the locking.
6659 *
6660 * @note Cannot be used during ModuleInit or ModuleTerm callbacks.
6661 */
6662SUPR0DECL(int) SUPR0LdrLock(PSUPDRVSESSION pSession)
6663{
6664 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
6665 return supdrvLdrLock(pSession->pDevExt);
6666}
6667SUPR0_EXPORT_SYMBOL(SUPR0LdrLock);
6668
6669
6670/**
6671 * Releases the global loader lock.
6672 *
6673 * Must correspond to a SUPR0LdrLock call!
6674 *
6675 * @returns VBox status code.
6676 * @param pSession The session doing the locking.
6677 *
6678 * @note Cannot be used during ModuleInit or ModuleTerm callbacks.
6679 */
6680SUPR0DECL(int) SUPR0LdrUnlock(PSUPDRVSESSION pSession)
6681{
6682 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
6683 return supdrvLdrUnlock(pSession->pDevExt);
6684}
6685SUPR0_EXPORT_SYMBOL(SUPR0LdrUnlock);
6686
6687
6688/**
6689 * For checking lock ownership in Assert() statements during ModuleInit and
6690 * ModuleTerm.
6691 *
6692 * @returns Whether we own the loader lock or not.
6693 * @param hMod The module in question.
6694 * @param fWantToHear For hosts where it is difficult to know who owns the
6695 * lock, this will be returned instead.
6696 */
6697SUPR0DECL(bool) SUPR0LdrIsLockOwnerByMod(void *hMod, bool fWantToHear)
6698{
6699 PSUPDRVDEVEXT pDevExt;
6700 RTNATIVETHREAD hOwner;
6701
6702 PSUPDRVLDRIMAGE pImage = (PSUPDRVLDRIMAGE)hMod;
6703 AssertPtrReturn(pImage, fWantToHear);
6704 AssertReturn(pImage->uMagic == SUPDRVLDRIMAGE_MAGIC, fWantToHear);
6705
6706 pDevExt = pImage->pDevExt;
6707 AssertPtrReturn(pDevExt, fWantToHear);
6708
6709 /*
6710 * Expecting this to be called at init/term time only, so this will be sufficient.
6711 */
6712 hOwner = pDevExt->hLdrInitThread;
6713 if (hOwner == NIL_RTNATIVETHREAD)
6714 hOwner = pDevExt->hLdrTermThread;
6715 if (hOwner != NIL_RTNATIVETHREAD)
6716 return hOwner == RTThreadNativeSelf();
6717
6718 /*
6719 * Neither of the two semaphore variants currently offers very good
6720 * introspection, so we wing it for now. This API is VBOX_STRICT only.
6721 */
6722#ifdef SUPDRV_USE_MUTEX_FOR_LDR
6723 return RTSemMutexIsOwned(pDevExt->mtxLdr) && fWantToHear;
6724#else
6725 return fWantToHear;
6726#endif
6727}
6728SUPR0_EXPORT_SYMBOL(SUPR0LdrIsLockOwnerByMod);
6729
6730
6731/**
6732 * Locates and retains the given module for ring-0 usage.
6733 *
6734 * @returns VBox status code.
6735 * @param pSession The session to associate the module reference with.
6736 * @param pszName The module name (no path).
6737 * @param phMod Where to return the module handle. The module is
6738 * referenced and a call to SUPR0LdrModRelease() is
6739 * necessary when done with it.
6740 */
6741SUPR0DECL(int) SUPR0LdrModByName(PSUPDRVSESSION pSession, const char *pszName, void **phMod)
6742{
6743 int rc;
6744 size_t cchName;
6745 PSUPDRVDEVEXT pDevExt;
6746
6747 /*
6748 * Validate input.
6749 */
6750 AssertPtrReturn(phMod, VERR_INVALID_POINTER);
6751 *phMod = NULL;
6752 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
6753 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
6754 cchName = strlen(pszName);
6755 AssertReturn(cchName > 0, VERR_EMPTY_STRING);
6756 AssertReturn(cchName < RT_SIZEOFMEMB(SUPDRVLDRIMAGE, szName), VERR_MODULE_NOT_FOUND);
6757
6758 /*
6759 * Do the lookup.
6760 */
6761 pDevExt = pSession->pDevExt;
6762 rc = supdrvLdrLock(pDevExt);
6763 if (RT_SUCCESS(rc))
6764 {
6765 PSUPDRVLDRIMAGE pImage;
6766 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
6767 {
6768 if ( pImage->szName[cchName] == '\0'
6769 && !memcmp(pImage->szName, pszName, cchName))
6770 {
6771 /*
6772 * Check the state and make sure we don't overflow the reference counter before return it.
6773 */
6774 uint32_t uState = pImage->uState;
6775 if (uState == SUP_IOCTL_LDR_LOAD)
6776 {
6777 if (RT_LIKELY(pImage->cImgUsage < UINT32_MAX / 2U))
6778 {
6779 supdrvLdrAddUsage(pDevExt, pSession, pImage, false /*fRing3Usage*/);
6780 *phMod = pImage;
6781 supdrvLdrUnlock(pDevExt);
6782 return VINF_SUCCESS;
6783 }
6784 supdrvLdrUnlock(pDevExt);
6785 Log(("SUPR0LdrModByName: Too many existing references to '%s'!\n", pszName));
6786 return VERR_TOO_MANY_REFERENCES;
6787 }
6788 supdrvLdrUnlock(pDevExt);
6789 Log(("SUPR0LdrModByName: Module '%s' is not in the loaded state (%d)!\n", pszName, uState));
6790 return VERR_INVALID_STATE;
6791 }
6792 }
6793 supdrvLdrUnlock(pDevExt);
6794 Log(("SUPR0LdrModByName: Module '%s' not found!\n", pszName));
6795 rc = VERR_MODULE_NOT_FOUND;
6796 }
6797 return rc;
6798}
6799SUPR0_EXPORT_SYMBOL(SUPR0LdrModByName);
6800
6801
6802/**
6803 * Retains a ring-0 module reference.
6804 *
6805 * Release reference when done by calling SUPR0LdrModRelease().
6806 *
6807 * @returns VBox status code.
6808 * @param pSession The session to reference the module in. A usage
6809 * record is added if needed.
6810 * @param hMod The handle to the module to retain.
6811 */
6812SUPR0DECL(int) SUPR0LdrModRetain(PSUPDRVSESSION pSession, void *hMod)
6813{
6814 PSUPDRVDEVEXT pDevExt;
6815 PSUPDRVLDRIMAGE pImage;
6816 int rc;
6817
6818 /* Validate input a little. */
6819 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
6820 AssertPtrReturn(hMod, VERR_INVALID_HANDLE);
6821 pImage = (PSUPDRVLDRIMAGE)hMod;
6822 AssertReturn(pImage->uMagic == SUPDRVLDRIMAGE_MAGIC, VERR_INVALID_HANDLE);
6823
6824 /* Reference the module: */
6825 pDevExt = pSession->pDevExt;
6826 rc = supdrvLdrLock(pDevExt);
6827 if (RT_SUCCESS(rc))
6828 {
6829 if (pImage->uMagic == SUPDRVLDRIMAGE_MAGIC)
6830 {
6831 if (RT_LIKELY(pImage->cImgUsage < UINT32_MAX / 2U))
6832 rc = supdrvLdrAddUsage(pDevExt, pSession, pImage, false /*fRing3Usage*/);
6833 else
6834 AssertFailedStmt(rc = VERR_TOO_MANY_REFERENCES);
6835 }
6836 else
6837 AssertFailedStmt(rc = VERR_INVALID_HANDLE);
6838 supdrvLdrUnlock(pDevExt);
6839 }
6840 return rc;
6841}
6842SUPR0_EXPORT_SYMBOL(SUPR0LdrModRetain);
6843
6844
6845/**
6846 * Releases a ring-0 module reference retained by SUPR0LdrModByName() or
6847 * SUPR0LdrModRetain().
6848 *
6849 * @returns VBox status code.
6850 * @param pSession The session that the module was retained in.
6851 * @param hMod The module handle. NULL is silently ignored.
6852 */
6853SUPR0DECL(int) SUPR0LdrModRelease(PSUPDRVSESSION pSession, void *hMod)
6854{
6855 PSUPDRVDEVEXT pDevExt;
6856 PSUPDRVLDRIMAGE pImage;
6857 int rc;
6858
6859 /*
6860 * Validate input.
6861 */
6862 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
6863 if (!hMod)
6864 return VINF_SUCCESS;
6865 AssertPtrReturn(hMod, VERR_INVALID_HANDLE);
6866 pImage = (PSUPDRVLDRIMAGE)hMod;
6867 AssertReturn(pImage->uMagic == SUPDRVLDRIMAGE_MAGIC, VERR_INVALID_HANDLE);
6868
6869 /*
6870 * Take the loader lock and revalidate the module:
6871 */
6872 pDevExt = pSession->pDevExt;
6873 rc = supdrvLdrLock(pDevExt);
6874 if (RT_SUCCESS(rc))
6875 {
6876 if (pImage->uMagic == SUPDRVLDRIMAGE_MAGIC)
6877 {
6878 /*
6879 * Find the usage record for the module:
6880 */
6881 PSUPDRVLDRUSAGE pPrevUsage = NULL;
6882 PSUPDRVLDRUSAGE pUsage;
6883
6884 rc = VERR_MODULE_NOT_FOUND;
6885 for (pUsage = pSession->pLdrUsage; pUsage; pUsage = pUsage->pNext)
6886 {
6887 if (pUsage->pImage == pImage)
6888 {
6889 /*
6890 * Drop a ring-0 reference:
6891 */
6892 Assert(pImage->cImgUsage >= pUsage->cRing0Usage + pUsage->cRing3Usage);
6893 if (pUsage->cRing0Usage > 0)
6894 {
6895 if (pImage->cImgUsage > 1)
6896 {
6897 pUsage->cRing0Usage -= 1;
6898 supdrvLdrSubtractUsage(pDevExt, pImage, 1);
6899 rc = VINF_SUCCESS;
6900 }
6901 else
6902 {
6903 Assert(!pImage->pWrappedModInfo /* (The wrapper kmod has the last reference.) */);
6904 supdrvLdrFree(pDevExt, pImage);
6905
6906 if (pPrevUsage)
6907 pPrevUsage->pNext = pUsage->pNext;
6908 else
6909 pSession->pLdrUsage = pUsage->pNext;
6910 pUsage->pNext = NULL;
6911 pUsage->pImage = NULL;
6912 pUsage->cRing0Usage = 0;
6913 pUsage->cRing3Usage = 0;
6914 RTMemFree(pUsage);
6915
6916 rc = VINF_OBJECT_DESTROYED;
6917 }
6918 }
6919 else
6920 AssertFailedStmt(rc = VERR_CALLER_NO_REFERENCE);
6921 break;
6922 }
6923 pPrevUsage = pUsage;
6924 }
6925 }
6926 else
6927 AssertFailedStmt(rc = VERR_INVALID_HANDLE);
6928 supdrvLdrUnlock(pDevExt);
6929 }
6930 return rc;
6931
6932}
6933SUPR0_EXPORT_SYMBOL(SUPR0LdrModRelease);
6934
6935
6936/**
6937 * Implements the service call request.
6938 *
6939 * @returns VBox status code.
6940 * @param pDevExt The device extension.
6941 * @param pSession The calling session.
6942 * @param pReq The request packet, valid.
6943 */
6944static int supdrvIOCtl_CallServiceModule(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPCALLSERVICE pReq)
6945{
6946#if !defined(RT_OS_WINDOWS) || defined(RT_ARCH_AMD64) || defined(DEBUG)
6947 int rc;
6948
6949 /*
6950 * Find the module first in the module referenced by the calling session.
6951 */
6952 rc = supdrvLdrLock(pDevExt);
6953 if (RT_SUCCESS(rc))
6954 {
6955 PFNSUPR0SERVICEREQHANDLER pfnServiceReqHandler = NULL;
6956 PSUPDRVLDRUSAGE pUsage;
6957
6958 for (pUsage = pSession->pLdrUsage; pUsage; pUsage = pUsage->pNext)
6959 if ( pUsage->pImage->pfnServiceReqHandler
6960 && !strcmp(pUsage->pImage->szName, pReq->u.In.szName))
6961 {
6962 pfnServiceReqHandler = pUsage->pImage->pfnServiceReqHandler;
6963 break;
6964 }
6965 supdrvLdrUnlock(pDevExt);
6966
6967 if (pfnServiceReqHandler)
6968 {
6969 /*
6970 * Call it.
6971 */
6972 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_SERVICE_SIZE(0))
6973 rc = pfnServiceReqHandler(pSession, pReq->u.In.uOperation, pReq->u.In.u64Arg, NULL);
6974 else
6975 rc = pfnServiceReqHandler(pSession, pReq->u.In.uOperation, pReq->u.In.u64Arg, (PSUPR0SERVICEREQHDR)&pReq->abReqPkt[0]);
6976 }
6977 else
6978 rc = VERR_SUPDRV_SERVICE_NOT_FOUND;
6979 }
6980
6981 /* log it */
6982 if ( RT_FAILURE(rc)
6983 && rc != VERR_INTERRUPTED
6984 && rc != VERR_TIMEOUT)
6985 Log(("SUP_IOCTL_CALL_SERVICE: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
6986 rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
6987 else
6988 Log4(("SUP_IOCTL_CALL_SERVICE: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
6989 rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
6990 return rc;
6991#else /* RT_OS_WINDOWS && !RT_ARCH_AMD64 && !DEBUG */
6992 RT_NOREF3(pDevExt, pSession, pReq);
6993 return VERR_NOT_IMPLEMENTED;
6994#endif /* RT_OS_WINDOWS && !RT_ARCH_AMD64 && !DEBUG */
6995}
6996
6997
6998/**
6999 * Implements the logger settings request.
7000 *
7001 * @returns VBox status code.
7002 * @param pReq The request.
7003 */
7004static int supdrvIOCtl_LoggerSettings(PSUPLOGGERSETTINGS pReq)
7005{
7006 const char *pszGroup = &pReq->u.In.szStrings[pReq->u.In.offGroups];
7007 const char *pszFlags = &pReq->u.In.szStrings[pReq->u.In.offFlags];
7008 const char *pszDest = &pReq->u.In.szStrings[pReq->u.In.offDestination];
7009 PRTLOGGER pLogger = NULL;
7010 int rc;
7011
7012 /*
7013 * Some further validation.
7014 */
7015 switch (pReq->u.In.fWhat)
7016 {
7017 case SUPLOGGERSETTINGS_WHAT_SETTINGS:
7018 case SUPLOGGERSETTINGS_WHAT_CREATE:
7019 break;
7020
7021 case SUPLOGGERSETTINGS_WHAT_DESTROY:
7022 if (*pszGroup || *pszFlags || *pszDest)
7023 return VERR_INVALID_PARAMETER;
7024 if (pReq->u.In.fWhich == SUPLOGGERSETTINGS_WHICH_RELEASE)
7025 return VERR_ACCESS_DENIED;
7026 break;
7027
7028 default:
7029 return VERR_INTERNAL_ERROR;
7030 }
7031
7032 /*
7033 * Get the logger.
7034 */
7035 switch (pReq->u.In.fWhich)
7036 {
7037 case SUPLOGGERSETTINGS_WHICH_DEBUG:
7038 pLogger = RTLogGetDefaultInstance();
7039 break;
7040
7041 case SUPLOGGERSETTINGS_WHICH_RELEASE:
7042 pLogger = RTLogRelGetDefaultInstance();
7043 break;
7044
7045 default:
7046 return VERR_INTERNAL_ERROR;
7047 }
7048
7049 /*
7050 * Do the job.
7051 */
7052 switch (pReq->u.In.fWhat)
7053 {
7054 case SUPLOGGERSETTINGS_WHAT_SETTINGS:
7055 if (pLogger)
7056 {
7057 rc = RTLogFlags(pLogger, pszFlags);
7058 if (RT_SUCCESS(rc))
7059 rc = RTLogGroupSettings(pLogger, pszGroup);
7060 NOREF(pszDest);
7061 }
7062 else
7063 rc = VERR_NOT_FOUND;
7064 break;
7065
7066 case SUPLOGGERSETTINGS_WHAT_CREATE:
7067 {
7068 if (pLogger)
7069 rc = VERR_ALREADY_EXISTS;
7070 else
7071 {
7072 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
7073
7074 rc = RTLogCreate(&pLogger,
7075 0 /* fFlags */,
7076 pszGroup,
7077 pReq->u.In.fWhich == SUPLOGGERSETTINGS_WHICH_DEBUG
7078 ? "VBOX_LOG"
7079 : "VBOX_RELEASE_LOG",
7080 RT_ELEMENTS(s_apszGroups),
7081 s_apszGroups,
7082 RTLOGDEST_STDOUT | RTLOGDEST_DEBUGGER,
7083 NULL);
7084 if (RT_SUCCESS(rc))
7085 {
7086 rc = RTLogFlags(pLogger, pszFlags);
7087 NOREF(pszDest);
7088 if (RT_SUCCESS(rc))
7089 {
7090 switch (pReq->u.In.fWhich)
7091 {
7092 case SUPLOGGERSETTINGS_WHICH_DEBUG:
7093 pLogger = RTLogSetDefaultInstance(pLogger);
7094 break;
7095 case SUPLOGGERSETTINGS_WHICH_RELEASE:
7096 pLogger = RTLogRelSetDefaultInstance(pLogger);
7097 break;
7098 }
7099 }
7100 RTLogDestroy(pLogger);
7101 }
7102 }
7103 break;
7104 }
7105
7106 case SUPLOGGERSETTINGS_WHAT_DESTROY:
7107 switch (pReq->u.In.fWhich)
7108 {
7109 case SUPLOGGERSETTINGS_WHICH_DEBUG:
7110 pLogger = RTLogSetDefaultInstance(NULL);
7111 break;
7112 case SUPLOGGERSETTINGS_WHICH_RELEASE:
7113 pLogger = RTLogRelSetDefaultInstance(NULL);
7114 break;
7115 }
7116 rc = RTLogDestroy(pLogger);
7117 break;
7118
7119 default:
7120 {
7121 rc = VERR_INTERNAL_ERROR;
7122 break;
7123 }
7124 }
7125
7126 return rc;
7127}
7128
7129
7130/**
7131 * Implements the MSR prober operations.
7132 *
7133 * @returns VBox status code.
7134 * @param pDevExt The device extension.
7135 * @param pReq The request.
7136 */
7137static int supdrvIOCtl_MsrProber(PSUPDRVDEVEXT pDevExt, PSUPMSRPROBER pReq)
7138{
7139#ifdef SUPDRV_WITH_MSR_PROBER
7140 RTCPUID const idCpu = pReq->u.In.idCpu == UINT32_MAX ? NIL_RTCPUID : pReq->u.In.idCpu;
7141 int rc;
7142
7143 switch (pReq->u.In.enmOp)
7144 {
7145 case SUPMSRPROBEROP_READ:
7146 {
7147 uint64_t uValue;
7148 rc = supdrvOSMsrProberRead(pReq->u.In.uMsr, idCpu, &uValue);
7149 if (RT_SUCCESS(rc))
7150 {
7151 pReq->u.Out.uResults.Read.uValue = uValue;
7152 pReq->u.Out.uResults.Read.fGp = false;
7153 }
7154 else if (rc == VERR_ACCESS_DENIED)
7155 {
7156 pReq->u.Out.uResults.Read.uValue = 0;
7157 pReq->u.Out.uResults.Read.fGp = true;
7158 rc = VINF_SUCCESS;
7159 }
7160 break;
7161 }
7162
7163 case SUPMSRPROBEROP_WRITE:
7164 rc = supdrvOSMsrProberWrite(pReq->u.In.uMsr, idCpu, pReq->u.In.uArgs.Write.uToWrite);
7165 if (RT_SUCCESS(rc))
7166 pReq->u.Out.uResults.Write.fGp = false;
7167 else if (rc == VERR_ACCESS_DENIED)
7168 {
7169 pReq->u.Out.uResults.Write.fGp = true;
7170 rc = VINF_SUCCESS;
7171 }
7172 break;
7173
7174 case SUPMSRPROBEROP_MODIFY:
7175 case SUPMSRPROBEROP_MODIFY_FASTER:
7176 rc = supdrvOSMsrProberModify(idCpu, pReq);
7177 break;
7178
7179 default:
7180 return VERR_INVALID_FUNCTION;
7181 }
7182 RT_NOREF1(pDevExt);
7183 return rc;
7184#else
7185 RT_NOREF2(pDevExt, pReq);
7186 return VERR_NOT_IMPLEMENTED;
7187#endif
7188}
7189
7190
7191/**
7192 * Resume built-in keyboard on MacBook Air and Pro hosts.
7193 * If there is no built-in keyboard device, return success anyway.
7194 *
7195 * @returns 0 on Mac OS X platform, VERR_NOT_IMPLEMENTED on the other ones.
7196 */
7197static int supdrvIOCtl_ResumeSuspendedKbds(void)
7198{
7199#if defined(RT_OS_DARWIN)
7200 return supdrvDarwinResumeSuspendedKbds();
7201#else
7202 return VERR_NOT_IMPLEMENTED;
7203#endif
7204}
7205
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use