VirtualBox

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

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

SUP, VMM: bugref: 9562 Drop SUPR0GetRawModeUsability. No longer required with removal of raw-mode.

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