VirtualBox

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

Last change on this file since 82963 was 82590, checked in by vboxsync, 5 years ago

SUPDrv,IPRT: Adding SUPR0HCPhysToVirt to linux & solaris; introducing IPRT_WITHOUT_EFLAGS_AC_PRESERVING and VBOX_WITHOUT_EFLAGS_AC_SET_IN_VBOXDRV config macros for disabling EFLAGS.AC hacks (not active). bugref:9627

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

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