VirtualBox

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

Last change on this file since 81883 was 81623, checked in by vboxsync, 5 years ago

SUPDrv: Export SUPR0PageMapKernel and SUPR0PageProtect. bugref:9218

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