VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/Support/darwin/SUPDrv-darwin.cpp@ 109127

Last change on this file since 109127 was 109127, checked in by vboxsync, 12 days ago

SUPDrv: Make it build on darwin.amd64. jiraref:VBP-1653

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 80.0 KB
Line 
1/* $Id: SUPDrv-darwin.cpp 109127 2025-05-01 00:34:31Z vboxsync $ */
2/** @file
3 * VirtualBox Support Driver - Darwin Specific Code.
4 */
5
6/*
7 * Copyright (C) 2006-2024 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.215389.xyz.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * The contents of this file may alternatively be used under the terms
26 * of the Common Development and Distribution License Version 1.0
27 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
28 * in the VirtualBox distribution, in which case the provisions of the
29 * CDDL are applicable instead of those of the GPL.
30 *
31 * You may elect to license modified versions of this file under the
32 * terms and conditions of either the GPL or the CDDL or both.
33 *
34 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
35 */
36
37
38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
41#define LOG_GROUP LOG_GROUP_SUP_DRV
42#include "../../../Runtime/r0drv/darwin/the-darwin-kernel.h"
43
44#include "../SUPDrvInternal.h"
45#include <VBox/version.h>
46#include <iprt/assert.h>
47#include <iprt/asm.h>
48#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
49# include <iprt/asm-amd64-x86.h>
50#elif defined(RT_ARCH_ARM64) || defined(RT_ARCH_ARM32)
51# include <iprt/asm-arm.h>
52#endif
53#include <iprt/ctype.h>
54#include <iprt/dbg.h>
55#include <iprt/initterm.h>
56#include <iprt/file.h>
57#include <iprt/ldr.h>
58#include <iprt/mem.h>
59#include <iprt/power.h>
60#include <iprt/process.h>
61#include <iprt/spinlock.h>
62#include <iprt/semaphore.h>
63#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
64# include <iprt/x86.h>
65#endif
66#include <iprt/crypto/applecodesign.h>
67#include <iprt/crypto/store.h>
68#include <iprt/crypto/pkcs7.h>
69#include <iprt/crypto/x509.h>
70#include <VBox/err.h>
71#include <VBox/log.h>
72
73#include <mach/kmod.h>
74#include <miscfs/devfs/devfs.h>
75#include <sys/conf.h>
76#include <sys/errno.h>
77#include <sys/ioccom.h>
78#include <sys/malloc.h>
79#include <sys/proc.h>
80#include <sys/kauth.h>
81#include <IOKit/IOService.h>
82#include <IOKit/IOUserClient.h>
83#include <IOKit/pwr_mgt/RootDomain.h>
84#include <IOKit/IODeviceTreeSupport.h>
85#if MAC_OS_X_VERSION_MIN_REQUIRED < 101100
86# include <IOKit/usb/IOUSBHIDDriver.h>
87#endif
88#if RT_CLANG_PREREQ(15,0)
89# pragma clang diagnostic push
90# pragma GCC diagnostic ignored "-Winvalid-utf8"
91#endif
92#include <IOKit/bluetooth/IOBluetoothHIDDriver.h>
93#include <IOKit/bluetooth/IOBluetoothHIDDriverTypes.h>
94#if RT_CLANG_PREREQ(15,0)
95# pragma clang diagnostic pop
96#endif
97
98#ifdef VBOX_WITH_HOST_VMX
99# include <libkern/version.h>
100RT_C_DECLS_BEGIN
101# include <i386/vmx.h>
102RT_C_DECLS_END
103#endif
104
105
106/*********************************************************************************************************************************
107* Defined Constants And Macros *
108*********************************************************************************************************************************/
109
110/** The system device node name. */
111#define DEVICE_NAME_SYS "vboxdrv"
112/** The user device node name. */
113#define DEVICE_NAME_USR "vboxdrvu"
114
115
116/** @name For debugging/whatever, now permanent.
117 * @{ */
118#define VBOX_PROC_SELFNAME_LEN 31
119#define VBOX_RETRIEVE_CUR_PROC_NAME(a_Name) char a_Name[VBOX_PROC_SELFNAME_LEN + 1]; \
120 proc_selfname(a_Name, VBOX_PROC_SELFNAME_LEN)
121/** @} */
122
123
124/*********************************************************************************************************************************
125* Internal Functions *
126*********************************************************************************************************************************/
127RT_C_DECLS_BEGIN
128static kern_return_t VBoxDrvDarwinStart(struct kmod_info *pKModInfo, void *pvData);
129static kern_return_t VBoxDrvDarwinStop(struct kmod_info *pKModInfo, void *pvData);
130#ifdef VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION
131static int supdrvDarwinInitCertStores(PSUPDRVDEVEXT pDevExt);
132static void supdrvDarwinDestroyCertStores(PSUPDRVDEVEXT pDevExt);
133#endif
134
135static int VBoxDrvDarwinOpen(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess);
136static int VBoxDrvDarwinClose(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess);
137static int VBoxDrvDarwinIOCtl(dev_t Dev, u_long iCmd, caddr_t pData, int fFlags, struct proc *pProcess);
138#ifndef VBOX_WITHOUT_EFLAGS_AC_SET_IN_VBOXDRV
139static int VBoxDrvDarwinIOCtlSMAP(dev_t Dev, u_long iCmd, caddr_t pData, int fFlags, struct proc *pProcess);
140#endif
141static int VBoxDrvDarwinIOCtlSlow(PSUPDRVSESSION pSession, u_long iCmd, caddr_t pData, struct proc *pProcess);
142
143static int VBoxDrvDarwinErr2DarwinErr(int rc);
144
145static IOReturn VBoxDrvDarwinSleepHandler(void *pvTarget, void *pvRefCon, UInt32 uMessageType, IOService *pProvider, void *pvMessageArgument, vm_size_t argSize);
146RT_C_DECLS_END
147
148static int vboxdrvDarwinResolveSymbols(void);
149#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
150static bool vboxdrvDarwinCpuHasSMAP(void);
151#endif
152
153
154/*********************************************************************************************************************************
155* Structures and Typedefs *
156*********************************************************************************************************************************/
157/**
158 * The service class.
159 * This is just a formality really.
160 */
161class org_virtualbox_SupDrv : public IOService
162{
163 OSDeclareDefaultStructors(org_virtualbox_SupDrv);
164
165public:
166 virtual bool init(OSDictionary *pDictionary = 0);
167 virtual void free(void);
168 virtual bool start(IOService *pProvider);
169 virtual void stop(IOService *pProvider);
170 virtual IOService *probe(IOService *pProvider, SInt32 *pi32Score);
171 virtual bool terminate(IOOptionBits fOptions);
172
173 RTR0MEMEF_NEW_AND_DELETE_OPERATORS_IOKIT();
174
175private:
176 /** Guard against the parent class growing and us using outdated headers. */
177 uint8_t m_abSafetyPadding[256];
178};
179
180OSDefineMetaClassAndStructors(org_virtualbox_SupDrv, IOService);
181
182
183/**
184 * An attempt at getting that clientDied() notification.
185 * I don't think it'll work as I cannot figure out where/what creates the correct
186 * port right.
187 */
188class org_virtualbox_SupDrvClient : public IOUserClient
189{
190 OSDeclareDefaultStructors(org_virtualbox_SupDrvClient);
191
192private:
193 /** Guard against the parent class growing and us using outdated headers. */
194 uint8_t m_abSafetyPadding[256];
195
196 PSUPDRVSESSION m_pSession; /**< The session. */
197 task_t m_Task; /**< The client task. */
198 org_virtualbox_SupDrv *m_pProvider; /**< The service provider. */
199
200public:
201 virtual bool initWithTask(task_t OwningTask, void *pvSecurityId, UInt32 u32Type);
202 virtual bool start(IOService *pProvider);
203 static void sessionClose(RTPROCESS Process);
204 virtual IOReturn clientClose(void);
205 virtual IOReturn clientDied(void);
206 virtual bool terminate(IOOptionBits fOptions = 0);
207 virtual bool finalize(IOOptionBits fOptions);
208 virtual void stop(IOService *pProvider);
209
210 RTR0MEMEF_NEW_AND_DELETE_OPERATORS_IOKIT();
211};
212
213OSDefineMetaClassAndStructors(org_virtualbox_SupDrvClient, IOUserClient);
214
215
216
217/*********************************************************************************************************************************
218* Global Variables *
219*********************************************************************************************************************************/
220/**
221 * Declare the module stuff.
222 */
223RT_C_DECLS_BEGIN
224extern kern_return_t _start(struct kmod_info *pKModInfo, void *pvData);
225extern kern_return_t _stop(struct kmod_info *pKModInfo, void *pvData);
226
227KMOD_EXPLICIT_DECL(VBoxDrv, VBOX_VERSION_STRING, _start, _stop)
228DECL_HIDDEN_DATA(kmod_start_func_t *) _realmain = VBoxDrvDarwinStart;
229DECL_HIDDEN_DATA(kmod_stop_func_t *) _antimain = VBoxDrvDarwinStop;
230DECL_HIDDEN_DATA(int) _kext_apple_cc = __APPLE_CC__;
231RT_C_DECLS_END
232
233
234/**
235 * Device extention & session data association structure.
236 */
237static SUPDRVDEVEXT g_DevExt;
238
239/**
240 * The character device switch table for the driver.
241 */
242static struct cdevsw g_DevCW =
243{
244 /** @todo g++ doesn't like this syntax - it worked with gcc before renaming to .cpp. */
245 /*.d_open = */VBoxDrvDarwinOpen,
246 /*.d_close = */VBoxDrvDarwinClose,
247 /*.d_read = */eno_rdwrt,
248 /*.d_write = */eno_rdwrt,
249 /*.d_ioctl = */VBoxDrvDarwinIOCtl,
250 /*.d_stop = */eno_stop,
251 /*.d_reset = */eno_reset,
252 /*.d_ttys = */NULL,
253 /*.d_select= */eno_select,
254 /*.d_mmap = */eno_mmap,
255 /*.d_strategy = */eno_strat,
256#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1200 /* changed from 'void *' to 'rsvd_fcn_t' */
257 /*.d_getc/d_reserved_1 = */eno_getc,
258 /*.d_putc/d_reserved_2 = */eno_putc,
259#else
260 /*.d_getc = */(void *)(uintptr_t)&enodev, //eno_getc,
261 /*.d_putc = */(void *)(uintptr_t)&enodev, //eno_putc,
262#endif
263 /*.d_type = */0
264};
265
266/** Major device number. */
267static int g_iMajorDeviceNo = -1;
268/** Registered devfs device handle for the system device. */
269static void *g_hDevFsDeviceSys = NULL;
270/** Registered devfs device handle for the user device. */
271static void *g_hDevFsDeviceUsr = NULL;
272
273/** Spinlock protecting g_apSessionHashTab. */
274static RTSPINLOCK g_Spinlock = NIL_RTSPINLOCK;
275/** Hash table */
276static PSUPDRVSESSION g_apSessionHashTab[19];
277/** Calculates the index into g_apSessionHashTab.*/
278#define SESSION_HASH(pid) ((pid) % RT_ELEMENTS(g_apSessionHashTab))
279/** The number of open sessions. */
280static int32_t volatile g_cSessions = 0;
281/** The notifier handle for the sleep callback handler. */
282static IONotifier *g_pSleepNotifier = NULL;
283
284#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
285/** Pointer to vmx_suspend(). */
286static PFNRT g_pfnVmxSuspend = NULL;
287/** Pointer to vmx_resume(). */
288static PFNRT g_pfnVmxResume = NULL;
289/** Pointer to vmx_use_count. */
290static int volatile *g_pVmxUseCount = NULL;
291
292# ifdef SUPDRV_WITH_MSR_PROBER
293/** Pointer to rdmsr_carefully if found. Returns 0 on success. */
294static int (*g_pfnRdMsrCarefully)(uint32_t uMsr, uint32_t *puLow, uint32_t *puHigh) = NULL;
295/** Pointer to rdmsr64_carefully if found. Returns 0 on success. */
296static int (*g_pfnRdMsr64Carefully)(uint32_t uMsr, uint64_t *uValue) = NULL;
297/** Pointer to wrmsr[64]_carefully if found. Returns 0 on success. */
298static int (*g_pfnWrMsr64Carefully)(uint32_t uMsr, uint64_t uValue) = NULL;
299# endif
300#endif /* RT_ARCH_AMD64 || RT_ARCH_X86 */
301
302/** SUPKERNELFEATURES_XXX */
303static uint32_t g_fKernelFeatures = 0;
304
305/**
306 * Start the kernel module.
307 */
308static kern_return_t VBoxDrvDarwinStart(struct kmod_info *pKModInfo, void *pvData)
309{
310 RT_NOREF(pKModInfo, pvData);
311#ifdef DEBUG
312 printf("VBoxDrvDarwinStart\n");
313#endif
314
315 /*
316 * Initialize IPRT.
317 */
318 int rc = RTR0Init(0);
319 if (RT_SUCCESS(rc))
320 {
321 /*
322 * Initialize the device extension.
323 */
324 rc = supdrvInitDevExt(&g_DevExt, sizeof(SUPDRVSESSION));
325 if (RT_SUCCESS(rc))
326 {
327#ifdef VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION
328 supdrvDarwinInitCertStores(&g_DevExt);
329#endif
330
331 /*
332 * Initialize the session hash table.
333 */
334 memset(g_apSessionHashTab, 0, sizeof(g_apSessionHashTab)); /* paranoia */
335 rc = RTSpinlockCreate(&g_Spinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "VBoxDrvDarwin");
336 if (RT_SUCCESS(rc))
337 {
338#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
339 if (vboxdrvDarwinCpuHasSMAP())
340 {
341 g_fKernelFeatures |= SUPKERNELFEATURES_SMAP;
342# ifndef VBOX_WITHOUT_EFLAGS_AC_SET_IN_VBOXDRV
343 LogRel(("disabling SMAP for VBoxDrvDarwinIOCtl\n"));
344 g_DevCW.d_ioctl = VBoxDrvDarwinIOCtlSMAP;
345# endif
346 }
347#endif
348
349 /*
350 * Resolve some extra kernel symbols.
351 */
352 rc = vboxdrvDarwinResolveSymbols();
353 if (RT_SUCCESS(rc))
354 {
355
356 /*
357 * Registering ourselves as a character device.
358 */
359 g_iMajorDeviceNo = cdevsw_add(-1, &g_DevCW);
360 if (g_iMajorDeviceNo >= 0)
361 {
362#ifdef VBOX_WITH_HARDENING
363 g_hDevFsDeviceSys = devfs_make_node(makedev(g_iMajorDeviceNo, 0), DEVFS_CHAR,
364 UID_ROOT, GID_WHEEL, 0600, DEVICE_NAME_SYS);
365#else
366 g_hDevFsDeviceSys = devfs_make_node(makedev(g_iMajorDeviceNo, 0), DEVFS_CHAR,
367 UID_ROOT, GID_WHEEL, 0666, DEVICE_NAME_SYS);
368#endif
369 if (g_hDevFsDeviceSys)
370 {
371 g_hDevFsDeviceUsr = devfs_make_node(makedev(g_iMajorDeviceNo, 1), DEVFS_CHAR,
372 UID_ROOT, GID_WHEEL, 0666, DEVICE_NAME_USR);
373 if (g_hDevFsDeviceUsr)
374 {
375 LogRel(("VBoxDrv: version " VBOX_VERSION_STRING " r%d; IOCtl version %#x; IDC version %#x; dev major=%d\n",
376 VBOX_SVN_REV, SUPDRV_IOC_VERSION, SUPDRV_IDC_VERSION, g_iMajorDeviceNo));
377
378 /* Register a sleep/wakeup notification callback */
379 g_pSleepNotifier = registerPrioritySleepWakeInterest(&VBoxDrvDarwinSleepHandler, &g_DevExt, NULL);
380 if (g_pSleepNotifier == NULL)
381 LogRel(("VBoxDrv: register for sleep/wakeup events failed\n"));
382
383 return KMOD_RETURN_SUCCESS;
384 }
385
386 LogRel(("VBoxDrv: devfs_make_node(makedev(%d,1),,,,%s) failed\n", g_iMajorDeviceNo, DEVICE_NAME_USR));
387 devfs_remove(g_hDevFsDeviceSys);
388 g_hDevFsDeviceSys = NULL;
389 }
390 else
391 LogRel(("VBoxDrv: devfs_make_node(makedev(%d,0),,,,%s) failed\n", g_iMajorDeviceNo, DEVICE_NAME_SYS));
392
393 cdevsw_remove(g_iMajorDeviceNo, &g_DevCW);
394 g_iMajorDeviceNo = -1;
395 }
396 else
397 LogRel(("VBoxDrv: cdevsw_add failed (%d)\n", g_iMajorDeviceNo));
398 }
399#ifdef VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION
400 supdrvDarwinDestroyCertStores(&g_DevExt);
401#endif
402 RTSpinlockDestroy(g_Spinlock);
403 g_Spinlock = NIL_RTSPINLOCK;
404 }
405 else
406 LogRel(("VBoxDrv: RTSpinlockCreate failed (rc=%d)\n", rc));
407 supdrvDeleteDevExt(&g_DevExt);
408 }
409 else
410 printf("VBoxDrv: failed to initialize device extension (rc=%d)\n", rc);
411 RTR0TermForced();
412 }
413 else
414 printf("VBoxDrv: failed to initialize IPRT (rc=%d)\n", rc);
415
416 memset(&g_DevExt, 0, sizeof(g_DevExt));
417 return KMOD_RETURN_FAILURE;
418}
419
420
421/**
422 * Resolves kernel symbols we need and some we just would like to have.
423 */
424static int vboxdrvDarwinResolveSymbols(void)
425{
426#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
427 RTDBGKRNLINFO hKrnlInfo;
428 int rc = RTR0DbgKrnlInfoOpen(&hKrnlInfo, 0);
429 if (RT_SUCCESS(rc))
430 {
431 /*
432 * The VMX stuff - required with raw-mode (in theory for 64-bit on
433 * 32-bit too, but we never did that on darwin).
434 */
435 int rc1 = RTR0DbgKrnlInfoQuerySymbol(hKrnlInfo, NULL, "vmx_resume", (void **)&g_pfnVmxResume);
436 int rc2 = RTR0DbgKrnlInfoQuerySymbol(hKrnlInfo, NULL, "vmx_suspend", (void **)&g_pfnVmxSuspend);
437 int rc3 = RTR0DbgKrnlInfoQuerySymbol(hKrnlInfo, NULL, "vmx_use_count", (void **)&g_pVmxUseCount);
438 if (RT_SUCCESS(rc1) && RT_SUCCESS(rc2) && RT_SUCCESS(rc3))
439 {
440 LogRel(("VBoxDrv: vmx_resume=%p vmx_suspend=%p vmx_use_count=%p (%d) cr4=%#x\n",
441 g_pfnVmxResume, g_pfnVmxSuspend, g_pVmxUseCount, *g_pVmxUseCount, ASMGetCR4() ));
442 }
443 else
444 {
445 LogRel(("VBoxDrv: failed to resolve vmx stuff: vmx_resume=%Rrc vmx_suspend=%Rrc vmx_use_count=%Rrc", rc1, rc2, rc3));
446 g_pfnVmxResume = NULL;
447 g_pfnVmxSuspend = NULL;
448 g_pVmxUseCount = NULL;
449# ifdef VBOX_WITH_RAW_MODE
450 rc = VERR_SYMBOL_NOT_FOUND;
451# endif
452 }
453
454 if (RT_SUCCESS(rc))
455 {
456# ifdef SUPDRV_WITH_MSR_PROBER
457 /*
458 * MSR prober stuff - optional!
459 */
460 rc2 = RTR0DbgKrnlInfoQuerySymbol(hKrnlInfo, NULL, "rdmsr_carefully", (void **)&g_pfnRdMsrCarefully);
461 if (RT_FAILURE(rc2))
462 g_pfnRdMsrCarefully = NULL;
463 rc2 = RTR0DbgKrnlInfoQuerySymbol(hKrnlInfo, NULL, "rdmsr64_carefully", (void **)&g_pfnRdMsr64Carefully);
464 if (RT_FAILURE(rc2))
465 g_pfnRdMsr64Carefully = NULL;
466# ifdef RT_ARCH_AMD64 /* Missing 64 in name, so if implemented on 32-bit it could have different signature. */
467 rc2 = RTR0DbgKrnlInfoQuerySymbol(hKrnlInfo, NULL, "wrmsr_carefully", (void **)&g_pfnWrMsr64Carefully);
468 if (RT_FAILURE(rc2))
469# endif
470 g_pfnWrMsr64Carefully = NULL;
471
472 LogRel(("VBoxDrv: g_pfnRdMsrCarefully=%p g_pfnRdMsr64Carefully=%p g_pfnWrMsr64Carefully=%p\n",
473 g_pfnRdMsrCarefully, g_pfnRdMsr64Carefully, g_pfnWrMsr64Carefully));
474
475# endif /* SUPDRV_WITH_MSR_PROBER */
476 }
477
478 RTR0DbgKrnlInfoRelease(hKrnlInfo);
479 }
480 else
481 LogRel(("VBoxDrv: Failed to open kernel symbols, rc=%Rrc\n", rc));
482 return rc;
483#else /* !RT_ARCH_AMD64 && !RT_ARCH_X86 */
484 return VINF_SUCCESS;
485#endif /* !RT_ARCH_AMD64 && !RT_ARCH_X86 */
486}
487
488
489#ifdef VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION
490
491/**
492 * Initalizes the certificate stores (code signing) in the device extension.
493 */
494static int supdrvDarwinInitCertStores(PSUPDRVDEVEXT pDevExt)
495{
496 pDevExt->hAdditionalStore = NIL_RTCRSTORE;
497
498 pDevExt->hRootStore = NIL_RTCRSTORE;
499 int rc = RTCrStoreCreateInMem(&pDevExt->hRootStore, g_cSUPTrustedTAs + 1);
500 if (RT_SUCCESS(rc))
501 {
502 for (uint32_t i = 0; i < g_cSUPTrustedTAs; i++)
503 {
504 int rc2 = RTCrStoreCertAddEncoded(pDevExt->hRootStore, RTCRCERTCTX_F_ENC_TAF_DER,
505 g_aSUPTrustedTAs[i].pch, g_aSUPTrustedTAs[i].cb, NULL);
506 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
507 {
508 printf("VBoxDrv: Error loading g_aSUPTrustedTAs[%u]: %d\n", i, rc);
509 rc = rc2;
510 }
511 }
512
513 /* We implicitly trust the build certificate. */
514 int rc2 = RTCrStoreCertAddEncoded(pDevExt->hRootStore, RTCRCERTCTX_F_ENC_X509_DER,
515 g_abSUPBuildCert, g_cbSUPBuildCert, NULL);
516 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
517 {
518 printf("VBoxDrv: Error loading g_cbSUPBuildCert: %d\n", rc);
519 rc = rc2;
520 }
521 }
522 return rc;
523}
524
525
526/**
527 * Releases the certificate stores in the device extension.
528 */
529static void supdrvDarwinDestroyCertStores(PSUPDRVDEVEXT pDevExt)
530{
531 if (pDevExt->hRootStore != NIL_RTCRSTORE)
532 {
533 uint32_t cRefs = RTCrStoreRelease(pDevExt->hRootStore);
534 Assert(cRefs == 0); RT_NOREF(cRefs);
535 pDevExt->hRootStore = NIL_RTCRSTORE;
536 }
537 if (pDevExt->hAdditionalStore != NIL_RTCRSTORE)
538 {
539 uint32_t cRefs = RTCrStoreRelease(pDevExt->hAdditionalStore);
540 Assert(cRefs == 0); RT_NOREF(cRefs);
541 pDevExt->hAdditionalStore = NIL_RTCRSTORE;
542 }
543}
544
545#endif /* VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION */
546
547/**
548 * Stop the kernel module.
549 */
550static kern_return_t VBoxDrvDarwinStop(struct kmod_info *pKModInfo, void *pvData)
551{
552 RT_NOREF(pKModInfo, pvData);
553 int rc;
554 LogFlow(("VBoxDrvDarwinStop\n"));
555
556 /** @todo I've got a nagging feeling that we'll have to keep track of users and refuse
557 * unloading if we're busy. Investigate and implement this! */
558
559 /*
560 * Undo the work done during start (in reverse order).
561 */
562 if (g_pSleepNotifier)
563 {
564 g_pSleepNotifier->remove();
565 g_pSleepNotifier = NULL;
566 }
567
568 devfs_remove(g_hDevFsDeviceUsr);
569 g_hDevFsDeviceUsr = NULL;
570
571 devfs_remove(g_hDevFsDeviceSys);
572 g_hDevFsDeviceSys = NULL;
573
574 rc = cdevsw_remove(g_iMajorDeviceNo, &g_DevCW);
575 Assert(rc == g_iMajorDeviceNo);
576 g_iMajorDeviceNo = -1;
577
578 supdrvDeleteDevExt(&g_DevExt);
579
580 rc = RTSpinlockDestroy(g_Spinlock);
581 AssertRC(rc);
582 g_Spinlock = NIL_RTSPINLOCK;
583
584#ifdef VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION
585 supdrvDarwinDestroyCertStores(&g_DevExt);
586#endif
587
588 RTR0TermForced();
589
590 memset(&g_DevExt, 0, sizeof(g_DevExt));
591#ifdef DEBUG
592 printf("VBoxDrvDarwinStop - done\n");
593#endif
594 return KMOD_RETURN_SUCCESS;
595}
596
597
598/**
599 * Device open. Called on open /dev/vboxdrv
600 *
601 * @param Dev The device number.
602 * @param fFlags ???.
603 * @param fDevType ???.
604 * @param pProcess The process issuing this request.
605 */
606static int VBoxDrvDarwinOpen(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess)
607{
608 RT_NOREF(fFlags, fDevType);
609#ifdef DEBUG_DARWIN_GIP
610 char szName[128];
611 szName[0] = '\0';
612 proc_name(proc_pid(pProcess), szName, sizeof(szName));
613 Log(("VBoxDrvDarwinOpen: pid=%d '%s'\n", proc_pid(pProcess), szName));
614#endif
615
616 /*
617 * Only two minor devices numbers are allowed.
618 */
619 if (minor(Dev) != 0 && minor(Dev) != 1)
620 return EACCES;
621
622 /*
623 * The process issuing the request must be the current process.
624 */
625 RTPROCESS Process = RTProcSelf();
626 if ((int)Process != proc_pid(pProcess))
627 return EIO;
628
629 /*
630 * Find the session created by org_virtualbox_SupDrvClient, fail
631 * if no such session, and mark it as opened. We set the uid & gid
632 * here too, since that is more straight forward at this point.
633 */
634 const bool fUnrestricted = minor(Dev) == 0;
635 int rc = VINF_SUCCESS;
636 PSUPDRVSESSION pSession = NULL;
637 kauth_cred_t pCred = kauth_cred_proc_ref(pProcess);
638 if (pCred)
639 {
640#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
641 RTUID Uid = kauth_cred_getruid(pCred);
642 RTGID Gid = kauth_cred_getrgid(pCred);
643#else
644 RTUID Uid = pCred->cr_ruid;
645 RTGID Gid = pCred->cr_rgid;
646#endif
647 unsigned iHash = SESSION_HASH(Process);
648 RTSpinlockAcquire(g_Spinlock);
649
650 pSession = g_apSessionHashTab[iHash];
651 while (pSession && pSession->Process != Process)
652 pSession = pSession->pNextHash;
653 if (pSession)
654 {
655 if (!pSession->fOpened)
656 {
657 pSession->fOpened = true;
658 pSession->fUnrestricted = fUnrestricted;
659 pSession->Uid = Uid;
660 pSession->Gid = Gid;
661 }
662 else
663 rc = VERR_ALREADY_LOADED;
664 }
665 else
666 rc = VERR_GENERAL_FAILURE;
667
668 RTSpinlockRelease(g_Spinlock);
669#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
670 kauth_cred_unref(&pCred);
671#else /* 10.4 */
672 /* The 10.4u SDK headers and 10.4.11 kernel source have inconsistent definitions
673 of kauth_cred_unref(), so use the other (now deprecated) API for releasing it. */
674 kauth_cred_rele(pCred);
675#endif /* 10.4 */
676 }
677 else
678 rc = VERR_INVALID_PARAMETER;
679
680#ifdef DEBUG_DARWIN_GIP
681 OSDBGPRINT(("VBoxDrvDarwinOpen: pid=%d '%s' pSession=%p rc=%d\n", proc_pid(pProcess), szName, pSession, rc));
682#else
683 Log(("VBoxDrvDarwinOpen: g_DevExt=%p pSession=%p rc=%d pid=%d\n", &g_DevExt, pSession, rc, proc_pid(pProcess)));
684#endif
685 return VBoxDrvDarwinErr2DarwinErr(rc);
686}
687
688
689/**
690 * Close device.
691 */
692static int VBoxDrvDarwinClose(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess)
693{
694 RT_NOREF(Dev, fFlags, fDevType, pProcess);
695 Log(("VBoxDrvDarwinClose: pid=%d\n", (int)RTProcSelf()));
696 Assert(proc_pid(pProcess) == (int)RTProcSelf());
697
698 /*
699 * Hand the session closing to org_virtualbox_SupDrvClient.
700 */
701 org_virtualbox_SupDrvClient::sessionClose(RTProcSelf());
702 return 0;
703}
704
705
706/**
707 * Device I/O Control entry point.
708 *
709 * @returns Darwin for slow IOCtls and VBox status code for the fast ones.
710 * @param Dev The device number (major+minor).
711 * @param iCmd The IOCtl command.
712 * @param pData Pointer to the data (if any it's a SUPDRVIOCTLDATA (kernel copy)).
713 * @param fFlags Flag saying we're a character device (like we didn't know already).
714 * @param pProcess The process issuing this request.
715 */
716static int VBoxDrvDarwinIOCtl(dev_t Dev, u_long iCmd, caddr_t pData, int fFlags, struct proc *pProcess)
717{
718 RT_NOREF(fFlags);
719 const bool fUnrestricted = minor(Dev) == 0;
720 const RTPROCESS Process = proc_pid(pProcess);
721 const unsigned iHash = SESSION_HASH(Process);
722 PSUPDRVSESSION pSession;
723
724#ifdef VBOX_WITH_EFLAGS_AC_SET_IN_VBOXDRV
725 /*
726 * Refuse all I/O control calls if we've ever detected EFLAGS.AC being cleared.
727 *
728 * This isn't a problem, as there is absolutely nothing in the kernel context that
729 * depend on user context triggering cleanups. That would be pretty wild, right?
730 */
731 if (RT_UNLIKELY(g_DevExt.cBadContextCalls > 0))
732 {
733 SUPR0Printf("VBoxDrvDarwinIOCtl: EFLAGS.AC=0 detected %u times, refusing all I/O controls!\n", g_DevExt.cBadContextCalls);
734 return EDEVERR;
735 }
736#endif
737
738 /*
739 * Find the session.
740 */
741 RTSpinlockAcquire(g_Spinlock);
742
743 pSession = g_apSessionHashTab[iHash];
744 while (pSession && (pSession->Process != Process || pSession->fUnrestricted != fUnrestricted || !pSession->fOpened))
745 pSession = pSession->pNextHash;
746
747 if (RT_LIKELY(pSession))
748 supdrvSessionRetain(pSession);
749
750 RTSpinlockRelease(g_Spinlock);
751 if (RT_UNLIKELY(!pSession))
752 {
753 OSDBGPRINT(("VBoxDrvDarwinIOCtl: WHAT?!? pSession == NULL! This must be a mistake... pid=%d iCmd=%#lx\n",
754 (int)Process, iCmd));
755 return EINVAL;
756 }
757
758 /*
759 * Deal with the two high-speed IOCtl that takes it's arguments from
760 * the session and iCmd, and only returns a VBox status code.
761 */
762 int rc;
763 AssertCompile((SUP_IOCTL_FAST_DO_FIRST & 0xff) == (SUP_IOCTL_FLAG | 64));
764 if ( (uintptr_t)(iCmd - SUP_IOCTL_FAST_DO_FIRST) < (uintptr_t)32
765 && fUnrestricted)
766 rc = supdrvIOCtlFast(iCmd - SUP_IOCTL_FAST_DO_FIRST, *(uint32_t *)pData, &g_DevExt, pSession);
767 else
768 rc = VBoxDrvDarwinIOCtlSlow(pSession, iCmd, pData, pProcess);
769
770 supdrvSessionRelease(pSession);
771 return rc;
772}
773
774
775#ifndef VBOX_WITHOUT_EFLAGS_AC_SET_IN_VBOXDRV
776/**
777 * Alternative Device I/O Control entry point on hosts with SMAP support.
778 *
779 * @returns Darwin for slow IOCtls and VBox status code for the fast ones.
780 * @param Dev The device number (major+minor).
781 * @param iCmd The IOCtl command.
782 * @param pData Pointer to the data (if any it's a SUPDRVIOCTLDATA (kernel copy)).
783 * @param fFlags Flag saying we're a character device (like we didn't know already).
784 * @param pProcess The process issuing this request.
785 */
786static int VBoxDrvDarwinIOCtlSMAP(dev_t Dev, u_long iCmd, caddr_t pData, int fFlags, struct proc *pProcess)
787{
788 /*
789 * Allow VBox R0 code to touch R3 memory. Setting the AC bit disables the
790 * SMAP check.
791 */
792 RTCCUINTREG fSavedEfl = ASMAddFlags(X86_EFL_AC);
793
794 int rc = VBoxDrvDarwinIOCtl(Dev, iCmd, pData, fFlags, pProcess);
795
796# if defined(VBOX_STRICT) || defined(VBOX_WITH_EFLAGS_AC_SET_IN_VBOXDRV)
797 /*
798 * Before we restore AC and the rest of EFLAGS, check if the IOCtl handler code
799 * accidentially modified it or some other important flag.
800 */
801 if (RT_UNLIKELY( (ASMGetFlags() & (X86_EFL_AC | X86_EFL_IF | X86_EFL_DF | X86_EFL_IOPL))
802 != ((fSavedEfl & (X86_EFL_AC | X86_EFL_IF | X86_EFL_DF | X86_EFL_IOPL)) | X86_EFL_AC) ))
803 {
804 char szTmp[48];
805 RTStrPrintf(szTmp, sizeof(szTmp), "iCmd=%#x: %#x->%#x!", iCmd, (uint32_t)fSavedEfl, (uint32_t)ASMGetFlags());
806 supdrvBadContext(&g_DevExt, "SUPDrv-darwin.cpp", __LINE__, szTmp);
807 }
808# endif
809
810 ASMSetFlags(fSavedEfl);
811 return rc;
812}
813#endif /* VBOX_WITHOUT_EFLAGS_AC_SET_IN_VBOXDRV */
814
815
816/**
817 * Worker for VBoxDrvDarwinIOCtl that takes the slow IOCtl functions.
818 *
819 * @returns Darwin errno.
820 *
821 * @param pSession The session.
822 * @param iCmd The IOCtl command.
823 * @param pData Pointer to the kernel copy of the SUPDRVIOCTLDATA buffer.
824 * @param pProcess The calling process.
825 */
826static int VBoxDrvDarwinIOCtlSlow(PSUPDRVSESSION pSession, u_long iCmd, caddr_t pData, struct proc *pProcess)
827{
828 RT_NOREF(pProcess);
829 LogFlow(("VBoxDrvDarwinIOCtlSlow: pSession=%p iCmd=%p pData=%p pProcess=%p\n", pSession, iCmd, pData, pProcess));
830
831
832 /*
833 * Buffered or unbuffered?
834 */
835 PSUPREQHDR pHdr;
836 user_addr_t pUser = 0;
837 void *pvPageBuf = NULL;
838 uint32_t cbReq = IOCPARM_LEN(iCmd);
839 if ((IOC_DIRMASK & iCmd) == IOC_INOUT)
840 {
841 pHdr = (PSUPREQHDR)pData;
842 if (RT_UNLIKELY(cbReq < sizeof(*pHdr)))
843 {
844 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: cbReq=%#x < %#x; iCmd=%#lx\n", cbReq, (int)sizeof(*pHdr), iCmd));
845 return EINVAL;
846 }
847 if (RT_UNLIKELY((pHdr->fFlags & SUPREQHDR_FLAGS_MAGIC_MASK) != SUPREQHDR_FLAGS_MAGIC))
848 {
849 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: bad magic fFlags=%#x; iCmd=%#lx\n", pHdr->fFlags, iCmd));
850 return EINVAL;
851 }
852 if (RT_UNLIKELY( RT_MAX(pHdr->cbIn, pHdr->cbOut) != cbReq
853 || pHdr->cbIn < sizeof(*pHdr)
854 || pHdr->cbOut < sizeof(*pHdr)))
855 {
856 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: max(%#x,%#x) != %#x; iCmd=%#lx\n", pHdr->cbIn, pHdr->cbOut, cbReq, iCmd));
857 return EINVAL;
858 }
859 }
860 else if ((IOC_DIRMASK & iCmd) == IOC_VOID && !cbReq)
861 {
862 /*
863 * Get the header and figure out how much we're gonna have to read.
864 */
865 IPRT_DARWIN_SAVE_EFL_AC();
866 SUPREQHDR Hdr;
867 pUser = (user_addr_t)*(void **)pData;
868 int rc = copyin(pUser, &Hdr, sizeof(Hdr));
869 if (RT_UNLIKELY(rc))
870 {
871 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: copyin(%llx,Hdr,) -> %#x; iCmd=%#lx\n", (unsigned long long)pUser, rc, iCmd));
872 IPRT_DARWIN_RESTORE_EFL_AC();
873 return rc;
874 }
875 if (RT_UNLIKELY((Hdr.fFlags & SUPREQHDR_FLAGS_MAGIC_MASK) != SUPREQHDR_FLAGS_MAGIC))
876 {
877 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: bad magic fFlags=%#x; iCmd=%#lx\n", Hdr.fFlags, iCmd));
878 IPRT_DARWIN_RESTORE_EFL_AC();
879 return EINVAL;
880 }
881 cbReq = RT_MAX(Hdr.cbIn, Hdr.cbOut);
882 if (RT_UNLIKELY( Hdr.cbIn < sizeof(Hdr)
883 || Hdr.cbOut < sizeof(Hdr)
884 || cbReq > _1M*16))
885 {
886 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: max(%#x,%#x); iCmd=%#lx\n", Hdr.cbIn, Hdr.cbOut, iCmd));
887 IPRT_DARWIN_RESTORE_EFL_AC();
888 return EINVAL;
889 }
890
891 /*
892 * Allocate buffer and copy in the data.
893 */
894 pHdr = (PSUPREQHDR)RTMemTmpAlloc(cbReq);
895 if (!pHdr)
896 pvPageBuf = pHdr = (PSUPREQHDR)IOMallocAligned(RT_ALIGN_Z(cbReq, PAGE_SIZE), 8);
897 if (RT_UNLIKELY(!pHdr))
898 {
899 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: failed to allocate buffer of %d bytes; iCmd=%#lx\n", cbReq, iCmd));
900 IPRT_DARWIN_RESTORE_EFL_AC();
901 return ENOMEM;
902 }
903 rc = copyin(pUser, pHdr, Hdr.cbIn);
904 if (RT_UNLIKELY(rc))
905 {
906 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: copyin(%llx,%p,%#x) -> %#x; iCmd=%#lx\n",
907 (unsigned long long)pUser, pHdr, Hdr.cbIn, rc, iCmd));
908 if (pvPageBuf)
909 IOFreeAligned(pvPageBuf, RT_ALIGN_Z(cbReq, PAGE_SIZE));
910 else
911 RTMemTmpFree(pHdr);
912 IPRT_DARWIN_RESTORE_EFL_AC();
913 return rc;
914 }
915 if (Hdr.cbIn < cbReq)
916 RT_BZERO((uint8_t *)pHdr + Hdr.cbIn, cbReq - Hdr.cbIn);
917 IPRT_DARWIN_RESTORE_EFL_AC();
918 }
919 else
920 {
921 Log(("VBoxDrvDarwinIOCtlSlow: huh? cbReq=%#x iCmd=%#lx\n", cbReq, iCmd));
922 return EINVAL;
923 }
924
925 /*
926 * Process the IOCtl.
927 */
928 int rc = supdrvIOCtl(iCmd, &g_DevExt, pSession, pHdr, cbReq);
929 if (RT_LIKELY(!rc))
930 {
931 /*
932 * If not buffered, copy back the buffer before returning.
933 */
934 if (pUser)
935 {
936 IPRT_DARWIN_SAVE_EFL_AC();
937 uint32_t cbOut = pHdr->cbOut;
938 if (cbOut > cbReq)
939 {
940 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: too much output! %#x > %#x; uCmd=%#lx!\n", cbOut, cbReq, iCmd));
941 cbOut = cbReq;
942 }
943 rc = copyout(pHdr, pUser, cbOut);
944 if (RT_UNLIKELY(rc))
945 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: copyout(%p,%llx,%#x) -> %d; uCmd=%#lx!\n",
946 pHdr, (unsigned long long)pUser, cbOut, rc, iCmd));
947
948 /* cleanup */
949 if (pvPageBuf)
950 IOFreeAligned(pvPageBuf, RT_ALIGN_Z(cbReq, PAGE_SIZE));
951 else
952 RTMemTmpFree(pHdr);
953 IPRT_DARWIN_RESTORE_EFL_AC();
954 }
955 }
956 else
957 {
958 /*
959 * The request failed, just clean up.
960 */
961 if (pUser)
962 {
963 if (pvPageBuf)
964 {
965 IPRT_DARWIN_SAVE_EFL_AC();
966 IOFreeAligned(pvPageBuf, RT_ALIGN_Z(cbReq, PAGE_SIZE));
967 IPRT_DARWIN_RESTORE_EFL_AC();
968 }
969 else
970 RTMemTmpFree(pHdr);
971 }
972
973 Log(("VBoxDrvDarwinIOCtlSlow: pid=%d iCmd=%lx pData=%p failed, rc=%d\n", proc_pid(pProcess), iCmd, (void *)pData, rc));
974 rc = EINVAL;
975 }
976
977 Log2(("VBoxDrvDarwinIOCtlSlow: returns %d\n", rc));
978 return rc;
979}
980
981
982/**
983 * The SUPDRV IDC entry point.
984 *
985 * @returns VBox status code, see supdrvIDC.
986 * @param uReq The request code.
987 * @param pReq The request.
988 */
989DECLEXPORT(int) VBOXCALL SUPDrvDarwinIDC(uint32_t uReq, PSUPDRVIDCREQHDR pReq)
990{
991 PSUPDRVSESSION pSession;
992
993 /*
994 * Some quick validations.
995 */
996 if (RT_UNLIKELY(!RT_VALID_PTR(pReq)))
997 return VERR_INVALID_POINTER;
998
999 pSession = pReq->pSession;
1000 if (pSession)
1001 {
1002 if (RT_UNLIKELY(!RT_VALID_PTR(pSession)))
1003 return VERR_INVALID_PARAMETER;
1004 if (RT_UNLIKELY(pSession->pDevExt != &g_DevExt))
1005 return VERR_INVALID_PARAMETER;
1006 }
1007 else if (RT_UNLIKELY(uReq != SUPDRV_IDC_REQ_CONNECT))
1008 return VERR_INVALID_PARAMETER;
1009
1010 /*
1011 * Do the job.
1012 */
1013 return supdrvIDC(uReq, &g_DevExt, pSession, pReq);
1014}
1015
1016
1017void VBOXCALL supdrvOSCleanupSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
1018{
1019 NOREF(pDevExt);
1020 NOREF(pSession);
1021}
1022
1023
1024void VBOXCALL supdrvOSSessionHashTabInserted(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
1025{
1026 NOREF(pDevExt); NOREF(pSession); NOREF(pvUser);
1027}
1028
1029
1030void VBOXCALL supdrvOSSessionHashTabRemoved(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
1031{
1032 NOREF(pDevExt); NOREF(pSession); NOREF(pvUser);
1033}
1034
1035
1036/**
1037 * Initializes any OS specific object creator fields.
1038 */
1039void VBOXCALL supdrvOSObjInitCreator(PSUPDRVOBJ pObj, PSUPDRVSESSION pSession)
1040{
1041 NOREF(pObj);
1042 NOREF(pSession);
1043}
1044
1045
1046/**
1047 * Checks if the session can access the object.
1048 *
1049 * @returns true if a decision has been made.
1050 * @returns false if the default access policy should be applied.
1051 *
1052 * @param pObj The object in question.
1053 * @param pSession The session wanting to access the object.
1054 * @param pszObjName The object name, can be NULL.
1055 * @param prc Where to store the result when returning true.
1056 */
1057bool VBOXCALL supdrvOSObjCanAccess(PSUPDRVOBJ pObj, PSUPDRVSESSION pSession, const char *pszObjName, int *prc)
1058{
1059 NOREF(pObj);
1060 NOREF(pSession);
1061 NOREF(pszObjName);
1062 NOREF(prc);
1063 return false;
1064}
1065
1066/**
1067 * Callback for blah blah blah.
1068 */
1069IOReturn VBoxDrvDarwinSleepHandler(void * /* pvTarget */, void *pvRefCon, UInt32 uMessageType,
1070 IOService *pProvider, void *pvMsgArg, vm_size_t cbMsgArg)
1071{
1072 RT_NOREF(pProvider, pvMsgArg, cbMsgArg);
1073 LogFlow(("VBoxDrv: Got sleep/wake notice. Message type was %x\n", uMessageType));
1074
1075 if (uMessageType == kIOMessageSystemWillSleep)
1076 RTPowerSignalEvent(RTPOWEREVENT_SUSPEND);
1077 else if (uMessageType == kIOMessageSystemHasPoweredOn)
1078 RTPowerSignalEvent(RTPOWEREVENT_RESUME);
1079
1080 acknowledgeSleepWakeNotification(pvRefCon);
1081
1082 return 0;
1083}
1084
1085#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
1086
1087# ifdef VBOX_WITH_HOST_VMX
1088/**
1089 * For cleaning up the mess we left behind on Yosemite with 4.3.28 and earlier.
1090 *
1091 * We ASSUME VT-x is supported by the CPU.
1092 *
1093 * @param idCpu Unused.
1094 * @param pvUser1 Unused.
1095 * @param pvUser2 Unused.
1096 */
1097static DECLCALLBACK(void) vboxdrvDarwinVmxEnableFix(RTCPUID idCpu, void *pvUser1, void *pvUser2)
1098{
1099 RT_NOREF(idCpu, pvUser1, pvUser2);
1100 RTCCUINTREG uCr4 = ASMGetCR4();
1101 if (!(uCr4 & X86_CR4_VMXE))
1102 {
1103 uCr4 |= X86_CR4_VMXE;
1104 ASMSetCR4(uCr4);
1105 }
1106}
1107# endif
1108
1109
1110/**
1111 * @copydoc SUPR0EnableVTx
1112 */
1113int VBOXCALL supdrvOSEnableVTx(bool fEnable)
1114{
1115# ifdef VBOX_WITH_HOST_VMX
1116 int rc;
1117 if ( version_major >= 10 /* 10 = 10.6.x = Snow Leopard */
1118# ifdef VBOX_WITH_RAW_MODE
1119 && g_pfnVmxSuspend
1120 && g_pfnVmxResume
1121 && g_pVmxUseCount
1122# endif
1123 )
1124 {
1125 IPRT_DARWIN_SAVE_EFL_AC();
1126 if (fEnable)
1127 {
1128 /*
1129 * We screwed up on Yosemite and didn't notice that we weren't
1130 * calling host_vmxon. CR4.VMXE may therefore have been disabled
1131 * by us. So, first time around we make sure it's set so we won't
1132 * crash in the pre-4.3.28/5.0RC1 upgrade scenario.
1133 * See @bugref{7907}.
1134 */
1135 static bool volatile g_fDoneCleanup = false;
1136 if (!g_fDoneCleanup)
1137 {
1138 if (version_major == 14 /* 14 = 10.10 = yosemite */)
1139 {
1140 uint32_t fCaps;
1141 rc = supdrvQueryVTCapsInternal(&fCaps);
1142 if (RT_SUCCESS(rc))
1143 {
1144 if (fCaps & SUPVTCAPS_VT_X)
1145 rc = RTMpOnAll(vboxdrvDarwinVmxEnableFix, NULL, NULL);
1146 else
1147 rc = VERR_VMX_NO_VMX;
1148 }
1149 if (RT_FAILURE(rc))
1150 {
1151 IPRT_DARWIN_RESTORE_EFL_AC();
1152 return rc;
1153 }
1154 }
1155 g_fDoneCleanup = true;
1156 }
1157
1158 /*
1159 * Call the kernel.
1160 */
1161 AssertLogRelMsg(!g_pVmxUseCount || *g_pVmxUseCount >= 0,
1162 ("vmx_use_count=%d (@ %p, expected it to be a positive number\n",
1163 *g_pVmxUseCount, g_pVmxUseCount));
1164
1165 rc = host_vmxon(false /* exclusive */);
1166 if (rc == VMX_OK)
1167 rc = VINF_SUCCESS;
1168 else if (rc == VMX_UNSUPPORTED)
1169 rc = VERR_VMX_NO_VMX;
1170 else if (rc == VMX_INUSE)
1171 rc = VERR_VMX_IN_VMX_ROOT_MODE;
1172 else /* shouldn't happen, but just in case. */
1173 {
1174 LogRel(("host_vmxon returned %d\n", rc));
1175 rc = VERR_UNRESOLVED_ERROR;
1176 }
1177 LogRel(("VBoxDrv: host_vmxon -> vmx_use_count=%d rc=%Rrc\n", *g_pVmxUseCount, rc));
1178 }
1179 else
1180 {
1181 AssertLogRelMsgReturn(!g_pVmxUseCount || *g_pVmxUseCount >= 1,
1182 ("vmx_use_count=%d (@ %p, expected it to be a non-zero positive number\n",
1183 *g_pVmxUseCount, g_pVmxUseCount),
1184 VERR_WRONG_ORDER);
1185 host_vmxoff();
1186 rc = VINF_SUCCESS;
1187 LogRel(("VBoxDrv: host_vmxoff -> vmx_use_count=%d\n", *g_pVmxUseCount));
1188 }
1189 IPRT_DARWIN_RESTORE_EFL_AC();
1190 }
1191 else
1192 {
1193 /* In 10.5.x the host_vmxon is severely broken! Don't use it, it will
1194 frequnetly panic the host. */
1195 rc = VERR_NOT_SUPPORTED;
1196 }
1197 return rc;
1198# else /* !VBOX_WITH_HOST_VMX */
1199 return VERR_NOT_SUPPORTED;
1200# endif /* !VBOX_WITH_HOST_VMX */
1201}
1202
1203
1204/**
1205 * @copydoc SUPR0SuspendVTxOnCpu
1206 */
1207bool VBOXCALL supdrvOSSuspendVTxOnCpu(void)
1208{
1209# ifdef VBOX_WITH_HOST_VMX
1210 /*
1211 * Consult the VMX usage counter, don't try suspend if not enabled.
1212 *
1213 * Note! The host_vmxon/off code is still race prone since, but this is
1214 * currently the best we can do without always enable VMX when
1215 * loading the driver.
1216 */
1217 if ( g_pVmxUseCount
1218 && *g_pVmxUseCount > 0)
1219 {
1220 IPRT_DARWIN_SAVE_EFL_AC();
1221 g_pfnVmxSuspend();
1222 IPRT_DARWIN_RESTORE_EFL_AC();
1223 return true;
1224 }
1225 return false;
1226# else
1227 return false;
1228# endif
1229}
1230
1231
1232/**
1233 * @copydoc SUPR0ResumeVTxOnCpu
1234 */
1235void VBOXCALL supdrvOSResumeVTxOnCpu(bool fSuspended)
1236{
1237# ifdef VBOX_WITH_HOST_VMX
1238 /*
1239 * Don't consult the counter here, the state knows better.
1240 * We're executing with interrupts disabled and anyone racing us with
1241 * disabling VT-x will be waiting in the rendezvous code.
1242 */
1243 if ( fSuspended
1244 && g_pfnVmxResume)
1245 {
1246 IPRT_DARWIN_SAVE_EFL_AC();
1247 g_pfnVmxResume();
1248 IPRT_DARWIN_RESTORE_EFL_AC();
1249 }
1250 else
1251 Assert(!fSuspended);
1252# else
1253 Assert(!fSuspended);
1254# endif
1255}
1256
1257#endif /* RT_ARCH_AMD64 || RT_ARCH_X86 */
1258
1259bool VBOXCALL supdrvOSGetForcedAsyncTscMode(PSUPDRVDEVEXT pDevExt)
1260{
1261 NOREF(pDevExt);
1262 return false;
1263}
1264
1265
1266bool VBOXCALL supdrvOSAreCpusOfflinedOnSuspend(void)
1267{
1268 /** @todo verify this. */
1269 return false;
1270}
1271
1272
1273bool VBOXCALL supdrvOSAreTscDeltasInSync(void)
1274{
1275 return false;
1276}
1277
1278
1279#ifdef VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION
1280
1281/**
1282 * @callback_method_impl{FNRTLDRIMPORT}
1283 */
1284static DECLCALLBACK(int) supdrvDarwinLdrOpenImportCallback(RTLDRMOD hLdrMod, const char *pszModule, const char *pszSymbol,
1285 unsigned uSymbol, PRTLDRADDR pValue, void *pvUser)
1286{
1287 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
1288
1289 /*
1290 * First consult the VMMR0 module if there is one fully loaded.
1291 * This is necessary as VMMR0 may overload assertion and logger symbols.
1292 */
1293 if (pDevExt->pvVMMR0)
1294 for (PSUPDRVLDRIMAGE pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
1295 if (pImage->pvImage == pDevExt->pvVMMR0)
1296 {
1297 if ( pImage->uState == SUP_IOCTL_LDR_LOAD
1298 && pImage->hLdrMod != NIL_RTLDRMOD)
1299 {
1300 int rc = RTLdrGetSymbolEx(pImage->hLdrMod, pImage->pvImage, (uintptr_t)pImage->pvImage,
1301 UINT32_MAX, pszSymbol, pValue);
1302 if (RT_SUCCESS(rc))
1303 return VINF_SUCCESS;
1304 }
1305 break;
1306 }
1307
1308 /*
1309 * Then we consult the SUPDrv export table.
1310 */
1311 uintptr_t uValue = 0;
1312 int rc = supdrvLdrGetExportedSymbol(pszSymbol, &uValue);
1313 if (RT_SUCCESS(rc))
1314 {
1315 *pValue = uValue;
1316 return VINF_SUCCESS;
1317 }
1318
1319 /*
1320 * Failed.
1321 */
1322 printf("VBoxDrv: Unable to resolve symbol '%s'.\n", pszSymbol);
1323 RT_NOREF(hLdrMod, pszModule, uSymbol);
1324 return VERR_SYMBOL_NOT_FOUND;
1325}
1326
1327
1328/**
1329 * @callback_method_impl{FNRTCRPKCS7VERIFYCERTCALLBACK,
1330 * Verify that the signing certificate is sane.}
1331 */
1332static DECLCALLBACK(int) supdrvDarwinLdrOpenVerifyCertificatCallback(PCRTCRX509CERTIFICATE pCert, RTCRX509CERTPATHS hCertPaths,
1333 uint32_t fFlags, void *pvUser, PRTERRINFO pErrInfo)
1334{
1335 RT_NOREF(pvUser); //PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
1336# ifdef DEBUG_bird
1337 printf("supdrvDarwinLdrOpenVerifyCertificatCallback: pCert=%p hCertPaths=%p\n", (void *)pCert, (void *)hCertPaths);
1338# endif
1339
1340# if 0
1341 /*
1342 * Test signing certificates normally doesn't have all the necessary
1343 * features required below. So, treat them as special cases.
1344 */
1345 if ( hCertPaths == NIL_RTCRX509CERTPATHS
1346 && RTCrX509Name_Compare(&pCert->TbsCertificate.Issuer, &pCert->TbsCertificate.Subject) == 0)
1347 {
1348 RTMsgInfo("Test signed.\n");
1349 return VINF_SUCCESS;
1350 }
1351# endif
1352
1353 /*
1354 * Standard code signing capabilites required.
1355 */
1356 int rc = RTCrPkcs7VerifyCertCallbackCodeSigning(pCert, hCertPaths, fFlags, NULL, pErrInfo);
1357 if ( RT_SUCCESS(rc)
1358 && (fFlags & RTCRPKCS7VCC_F_SIGNED_DATA))
1359 {
1360 uint32_t cDevIdApp = 0;
1361 uint32_t cDevIdKext = 0;
1362 uint32_t cDevIdMacDev = 0;
1363 for (uint32_t i = 0; i < pCert->TbsCertificate.T3.Extensions.cItems; i++)
1364 {
1365 PCRTCRX509EXTENSION pExt = pCert->TbsCertificate.T3.Extensions.papItems[i];
1366 if (RTAsn1ObjId_CompareWithString(&pExt->ExtnId, RTCR_APPLE_CS_DEVID_APPLICATION_OID) == 0)
1367 {
1368 cDevIdApp++;
1369 if (!pExt->Critical.fValue)
1370 rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
1371 "Dev ID Application certificate extension is not flagged critical");
1372 }
1373 else if (RTAsn1ObjId_CompareWithString(&pExt->ExtnId, RTCR_APPLE_CS_DEVID_KEXT_OID) == 0)
1374 {
1375 cDevIdKext++;
1376 if (!pExt->Critical.fValue)
1377 rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
1378 "Dev ID kext certificate extension is not flagged critical");
1379 }
1380 else if (RTAsn1ObjId_CompareWithString(&pExt->ExtnId, RTCR_APPLE_CS_DEVID_MAC_SW_DEV_OID) == 0)
1381 {
1382 cDevIdMacDev++;
1383 if (!pExt->Critical.fValue)
1384 rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
1385 "Dev ID MAC SW dev certificate extension is not flagged critical");
1386 }
1387 }
1388# ifdef VBOX_WITH_DARWIN_R0_TEST_SIGN
1389 /*
1390 * Mac application software development certs do not have the usually required extensions.
1391 */
1392 if (cDevIdMacDev)
1393 {
1394 cDevIdApp++;
1395 cDevIdKext++;
1396 }
1397# endif
1398 if (cDevIdApp == 0)
1399 rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
1400 "Certificate is missing the 'Dev ID Application' extension");
1401 if (cDevIdKext == 0)
1402 rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
1403 "Certificate is missing the 'Dev ID kext' extension");
1404 }
1405
1406 return rc;
1407}
1408
1409
1410/**
1411 * @callback_method_impl{FNRTLDRVALIDATESIGNEDDATA}
1412 */
1413static DECLCALLBACK(int) supdrvDarwinLdrOpenVerifyCallback(RTLDRMOD hLdrMod, PCRTLDRSIGNATUREINFO pInfo,
1414 PRTERRINFO pErrInfo, void *pvUser)
1415{
1416 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
1417 RT_NOREF_PV(hLdrMod);
1418
1419 switch (pInfo->enmType)
1420 {
1421 case RTLDRSIGNATURETYPE_PKCS7_SIGNED_DATA:
1422 if (pInfo->pvExternalData)
1423 {
1424 PCRTCRPKCS7CONTENTINFO pContentInfo = (PCRTCRPKCS7CONTENTINFO)pInfo->pvSignature;
1425 RTTIMESPEC ValidationTime;
1426 RTTimeNow(&ValidationTime);
1427
1428 return RTCrPkcs7VerifySignedDataWithExternalData(pContentInfo,
1429 RTCRPKCS7VERIFY_SD_F_COUNTER_SIGNATURE_SIGNING_TIME_ONLY
1430 | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_SIGNING_TIME_IF_PRESENT
1431 | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_MS_TIMESTAMP_IF_PRESENT,
1432 pDevExt->hAdditionalStore, pDevExt->hRootStore, &ValidationTime,
1433 supdrvDarwinLdrOpenVerifyCertificatCallback, pDevExt,
1434 pInfo->pvExternalData, pInfo->cbExternalData, pErrInfo);
1435 }
1436 return RTErrInfoSetF(pErrInfo, VERR_NOT_SUPPORTED, "Expected external data with signature!");
1437
1438 default:
1439 return RTErrInfoSetF(pErrInfo, VERR_NOT_SUPPORTED, "Unsupported signature type: %d", pInfo->enmType);
1440 }
1441}
1442
1443#endif /* VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION */
1444
1445int VBOXCALL supdrvOSLdrOpen(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, const char *pszFilename)
1446{
1447#ifdef VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION
1448 /*
1449 * Initialize our members.
1450 */
1451 pImage->hLdrMod = NIL_RTLDRMOD;
1452 pImage->hMemAlloc = NIL_RTR0MEMOBJ;
1453
1454 /*
1455 * We have to double buffer the file to be avoid a potential race between
1456 * validation and actual image loading. This could be eliminated later by
1457 * baking the image validation into the RTLdrGetBits operation.
1458 *
1459 * Note! After calling RTLdrOpenInMemory, pvFile is owned by the loader and will be
1460 * freed via the RTFileReadAllFree callback when the loader module is closed.
1461 */
1462 void *pvFile = NULL;
1463 size_t cbFile = 0;
1464 int rc = RTFileReadAllEx(pszFilename, 0, _32M, RTFILE_RDALL_O_DENY_WRITE, &pvFile, &cbFile);
1465 if (RT_SUCCESS(rc))
1466 {
1467 PRTERRINFOSTATIC pErrInfo = (PRTERRINFOSTATIC)RTMemTmpAlloc(sizeof(RTERRINFOSTATIC));
1468 RTLDRMOD hLdrMod = NIL_RTLDRMOD;
1469 rc = RTLdrOpenInMemory(pszFilename, 0 /*fFlags*/, RTLDRARCH_HOST, cbFile,
1470 NULL /*pfnRead*/, RTFileReadAllFree, pvFile,
1471 &hLdrMod, pErrInfo ? RTErrInfoInitStatic(pErrInfo) : NULL);
1472 if (RT_SUCCESS(rc))
1473 {
1474 /*
1475 * Validate the image.
1476 */
1477 rc = RTLdrVerifySignature(hLdrMod, supdrvDarwinLdrOpenVerifyCallback, pDevExt,
1478 pErrInfo ? RTErrInfoInitStatic(pErrInfo) : NULL);
1479 if (RT_SUCCESS(rc))
1480 {
1481 /*
1482 * Allocate memory for the object and load it into it.
1483 */
1484 size_t cbImage = RTLdrSize(hLdrMod);
1485 if (cbImage == pImage->cbImageBits)
1486 {
1487 RTR0MEMOBJ hMemAlloc;
1488 rc = RTR0MemObjAllocPage(&hMemAlloc, cbImage, true /*fExecutable*/);
1489 if (RT_SUCCESS(rc))
1490 {
1491 void *pvImageBits = RTR0MemObjAddress(hMemAlloc);
1492 rc = RTLdrGetBits(hLdrMod, pvImageBits, (uintptr_t)pvImageBits,
1493 supdrvDarwinLdrOpenImportCallback, pDevExt);
1494 if (RT_SUCCESS(rc))
1495 {
1496 /*
1497 * Commit.
1498 */
1499 pImage->hMemAlloc = hMemAlloc;
1500 pImage->hLdrMod = hLdrMod;
1501 pImage->pvImage = pvImageBits;
1502 RTMemTmpFree(pErrInfo);
1503 /** @todo Call RTLdrDone. */
1504 kprintf("VBoxDrv: Loaded %s at %p\n", pImage->szName, pvImageBits);
1505 return VINF_SUCCESS;
1506 }
1507
1508 RTR0MemObjFree(hMemAlloc, true /*fFreeMappings*/);
1509 }
1510 else
1511 printf("VBoxDrv: Failed to allocate %u bytes for %s: %d\n", (unsigned)cbImage, pszFilename, rc);
1512 }
1513 else
1514 {
1515 printf("VBoxDrv: Image size mismatch for %s: %#x, ring-3 says %#x\n",
1516 pszFilename, (unsigned)cbImage, (unsigned)pImage->cbImageBits);
1517 rc = VERR_LDR_MISMATCH_NATIVE;
1518 }
1519 }
1520 else if (pErrInfo && RTErrInfoIsSet(&pErrInfo->Core))
1521 printf("VBoxDrv: RTLdrVerifySignature(%s) failed: %d - %s\n", pszFilename, rc, pErrInfo->Core.pszMsg);
1522 else
1523 printf("VBoxDrv: RTLdrVerifySignature(%s) failed: %d\n", pszFilename, rc);
1524 RTLdrClose(hLdrMod);
1525 }
1526 else if (pErrInfo && RTErrInfoIsSet(&pErrInfo->Core))
1527 printf("VBoxDrv: RTLdrOpenInMemory(%s) failed: %d - %s\n", pszFilename, rc, pErrInfo->Core.pszMsg);
1528 else
1529 printf("VBoxDrv: RTLdrOpenInMemory(%s) failed: %d\n", pszFilename, rc);
1530 RTMemTmpFree(pErrInfo);
1531 }
1532 return rc;
1533#else /* !VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION */
1534 NOREF(pDevExt); NOREF(pImage); NOREF(pszFilename);
1535 return VERR_NOT_SUPPORTED;
1536#endif /* !VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION */
1537}
1538
1539
1540#ifdef VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION
1541/**
1542 * @callback_method_impl{FNRTLDRENUMSYMS,
1543 * Worker for supdrvOSLdrValidatePointer.
1544 */
1545static DECLCALLBACK(int) supdrvDarwinLdrValidatePointerCallback(RTLDRMOD hLdrMod, const char *pszSymbol, unsigned uSymbol,
1546 RTLDRADDR Value, void *pvUser)
1547{
1548 RT_NOREF(hLdrMod, pszSymbol, uSymbol);
1549 if (Value == (uintptr_t)pvUser)
1550 return VINF_CALLBACK_RETURN;
1551 return VINF_SUCCESS;
1552}
1553#endif
1554
1555
1556int VBOXCALL supdrvOSLdrValidatePointer(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, void *pv,
1557 const uint8_t *pbImageBits, const char *pszSymbol)
1558{
1559#ifdef VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION
1560 AssertReturn(pImage->hLdrMod != NIL_RTLDRMOD, VERR_INVALID_STATE);
1561
1562 /*
1563 * If we've got a symbol name, just to a lookup and compare addresses.
1564 */
1565 int rc;
1566 if (RT_C_IS_UPPER(*pszSymbol))
1567 {
1568 RTLDRADDR uValueFound;
1569 rc = RTLdrGetSymbolEx(pImage->hLdrMod, pImage->pvImage, (uintptr_t)pImage->pvImage, UINT32_MAX, pszSymbol, &uValueFound);
1570 if (RT_SUCCESS(rc))
1571 {
1572 if (uValueFound == (uintptr_t)pv)
1573 rc = VINF_SUCCESS;
1574 else
1575 {
1576 SUPR0Printf("SUPDrv: Different exports found for %s in %s: %RTptr, expected %p\n",
1577 pszSymbol, pImage->szName, (RTUINTPTR)uValueFound, pv);
1578 rc = VERR_LDR_BAD_FIXUP;
1579 }
1580 }
1581 else
1582 SUPR0Printf("SUPDrv: No export named %s (%p) in %s!\n", pszSymbol, pv, pImage->szName);
1583 }
1584 /*
1585 * Otherwise do a symbol enumeration and look for the entrypoint.
1586 */
1587 else
1588 {
1589 rc = RTLdrEnumSymbols(pImage->hLdrMod, 0 /*fFlags*/, pImage->pvImage, (uintptr_t)pImage->pvImage,
1590 supdrvDarwinLdrValidatePointerCallback, pv);
1591 if (rc == VINF_CALLBACK_RETURN)
1592 rc = VINF_SUCCESS;
1593 else if (RT_SUCCESS(rc))
1594 {
1595 SUPR0Printf("SUPDrv: No export with address %p (%s) in %s!\n", pv, pszSymbol, pImage->szName);
1596 rc = VERR_NOT_FOUND;
1597 }
1598 else
1599 SUPR0Printf("SUPDrv: RTLdrEnumSymbols failed on %s: %Rrc\n", pImage->szName, rc);
1600 }
1601 RT_NOREF(pDevExt, pbImageBits);
1602 return rc;
1603#else
1604 NOREF(pDevExt); NOREF(pImage); NOREF(pv); NOREF(pbImageBits); NOREF(pszSymbol);
1605 return VERR_NOT_SUPPORTED;
1606#endif
1607}
1608
1609
1610int VBOXCALL supdrvOSLdrQuerySymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage,
1611 const char *pszSymbol, size_t cchSymbol, void **ppvSymbol)
1612{
1613#ifdef VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION
1614 /*
1615 * Just hand the problem to RTLdrGetSymbolEx.
1616 */
1617 RTLDRADDR uValueFound;
1618 int rc = RTLdrGetSymbolEx(pImage->hLdrMod, pImage->pvImage, (uintptr_t)pImage->pvImage, UINT32_MAX, pszSymbol, &uValueFound);
1619 if (RT_SUCCESS(rc))
1620 {
1621 *ppvSymbol = (void *)(uintptr_t)uValueFound;
1622 return VINF_SUCCESS;
1623 }
1624 RT_NOREF(pDevExt, cchSymbol);
1625 return rc;
1626
1627#else
1628 RT_NOREF(pDevExt, pImage, pszSymbol, cchSymbol, ppvSymbol);
1629 return VERR_WRONG_ORDER;
1630#endif
1631}
1632
1633
1634int VBOXCALL supdrvOSLdrLoad(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, const uint8_t *pbImageBits, PSUPLDRLOAD pReq)
1635{
1636#ifdef VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION
1637 /* State paranoia. */
1638 AssertReturn(pImage->hLdrMod != NIL_RTLDRMOD, VERR_INVALID_STATE);
1639 AssertReturn(pImage->hMemAlloc != NIL_RTR0MEMOBJ, VERR_INVALID_STATE);
1640 AssertReturn(pImage->pvImage, VERR_INVALID_STATE);
1641
1642 /*
1643 * We should get an identical match with ring-3 here, so the code here is
1644 * trivial in comparision to SUPDrv-win.cpp.
1645 */
1646 if (!memcmp(pImage->pvImage, pbImageBits, pImage->cbImageBits))
1647 return VINF_SUCCESS;
1648
1649 /*
1650 * Try show what when wrong (code is copied from supdrvNtCompare).
1651 */
1652 uint32_t cbLeft = pImage->cbImageBits;
1653 const uint8_t *pbNativeBits = (const uint8_t *)pImage->pvImage;
1654 for (size_t off = 0; cbLeft > 0; off++, cbLeft--)
1655 if (pbNativeBits[off] != pbImageBits[off])
1656 {
1657 /* Note! We need to copy image bits into a temporary stack buffer here as we'd
1658 otherwise risk overwriting them while formatting the error message. */
1659 uint8_t abBytes[64];
1660 memcpy(abBytes, &pbImageBits[off], RT_MIN(64, cbLeft));
1661 supdrvLdrLoadError(VERR_LDR_MISMATCH_NATIVE, pReq,
1662 "Mismatch at %#x (%p) of %s loaded at %p:\n"
1663 "ring-0: %.*Rhxs\n"
1664 "ring-3: %.*Rhxs",
1665 off, &pbNativeBits[off], pImage->szName, pImage->pvImage,
1666 RT_MIN(64, cbLeft), &pbNativeBits[off],
1667 RT_MIN(64, cbLeft), &abBytes[0]);
1668 printf("SUPDrv: %s\n", pReq->u.Out.szError);
1669 break;
1670 }
1671
1672 RT_NOREF(pDevExt);
1673 return VERR_LDR_MISMATCH_NATIVE;
1674
1675#else
1676 NOREF(pDevExt); NOREF(pImage); NOREF(pbImageBits); NOREF(pReq);
1677 return VERR_NOT_SUPPORTED;
1678#endif
1679}
1680
1681
1682void VBOXCALL supdrvOSLdrUnload(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage)
1683{
1684#ifdef VBOX_WITH_DARWIN_R0_DARWIN_IMAGE_VERIFICATION
1685 if (pImage->hLdrMod != NIL_RTLDRMOD)
1686 {
1687 int rc = RTLdrClose(pImage->hLdrMod);
1688 AssertRC(rc);
1689 pImage->hLdrMod = NIL_RTLDRMOD;
1690 }
1691 if (pImage->hMemAlloc != NIL_RTR0MEMOBJ)
1692 {
1693 RTR0MemObjFree(pImage->hMemAlloc, true /*fFreeMappings*/);
1694 pImage->hMemAlloc = NIL_RTR0MEMOBJ;
1695 }
1696 NOREF(pDevExt);
1697#else
1698 NOREF(pDevExt); NOREF(pImage);
1699#endif
1700}
1701
1702
1703void VBOXCALL supdrvOSLdrNotifyLoaded(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage)
1704{
1705 NOREF(pDevExt); NOREF(pImage);
1706}
1707
1708
1709void VBOXCALL supdrvOSLdrNotifyOpened(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, const char *pszFilename)
1710{
1711#if 1
1712 NOREF(pDevExt); NOREF(pImage); NOREF(pszFilename);
1713#else
1714 /*
1715 * Try store the image load address in NVRAM so we can retrived it on panic.
1716 * Note! This only works if you're root! - Acutally, it doesn't work at all at the moment. FIXME!
1717 */
1718 IORegistryEntry *pEntry = IORegistryEntry::fromPath("/options", gIODTPlane);
1719 if (pEntry)
1720 {
1721 char szVar[80];
1722 RTStrPrintf(szVar, sizeof(szVar), "vboximage"/*-%s*/, pImage->szName);
1723 char szValue[48];
1724 RTStrPrintf(szValue, sizeof(szValue), "%#llx,%#llx", (uint64_t)(uintptr_t)pImage->pvImage,
1725 (uint64_t)(uintptr_t)pImage->pvImage + pImage->cbImageBits - 1);
1726 bool fRc = pEntry->setProperty(szVar, szValue); NOREF(fRc);
1727 pEntry->release();
1728 SUPR0Printf("fRc=%d '%s'='%s'\n", fRc, szVar, szValue);
1729 }
1730 /*else
1731 SUPR0Printf("failed to find /options in gIODTPlane\n");*/
1732#endif
1733}
1734
1735
1736void VBOXCALL supdrvOSLdrNotifyUnloaded(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage)
1737{
1738 NOREF(pDevExt); NOREF(pImage);
1739}
1740
1741
1742void VBOXCALL supdrvOSLdrRetainWrapperModule(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage)
1743{
1744 RT_NOREF(pDevExt, pImage);
1745 AssertFailed();
1746}
1747
1748
1749void VBOXCALL supdrvOSLdrReleaseWrapperModule(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage)
1750{
1751 RT_NOREF(pDevExt, pImage);
1752 AssertFailed();
1753}
1754
1755
1756#if defined(SUPDRV_WITH_MSR_PROBER) && (defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86))
1757
1758typedef struct SUPDRVDARWINMSRARGS
1759{
1760 RTUINT64U uValue;
1761 uint32_t uMsr;
1762 int rc;
1763} SUPDRVDARWINMSRARGS, *PSUPDRVDARWINMSRARGS;
1764
1765/**
1766 * On CPU worker for supdrvOSMsrProberRead.
1767 *
1768 * @param idCpu Ignored.
1769 * @param pvUser1 Pointer to a SUPDRVDARWINMSRARGS.
1770 * @param pvUser2 Ignored.
1771 */
1772static DECLCALLBACK(void) supdrvDarwinMsrProberReadOnCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
1773{
1774 PSUPDRVDARWINMSRARGS pArgs = (PSUPDRVDARWINMSRARGS)pvUser1;
1775 if (g_pfnRdMsr64Carefully)
1776 pArgs->rc = g_pfnRdMsr64Carefully(pArgs->uMsr, &pArgs->uValue.u);
1777 else if (g_pfnRdMsrCarefully)
1778 pArgs->rc = g_pfnRdMsrCarefully(pArgs->uMsr, &pArgs->uValue.s.Lo, &pArgs->uValue.s.Hi);
1779 else
1780 pArgs->rc = 2;
1781 NOREF(idCpu); NOREF(pvUser2);
1782}
1783
1784
1785int VBOXCALL supdrvOSMsrProberRead(uint32_t uMsr, RTCPUID idCpu, uint64_t *puValue)
1786{
1787 if (!g_pfnRdMsr64Carefully && !g_pfnRdMsrCarefully)
1788 return VERR_NOT_SUPPORTED;
1789
1790 SUPDRVDARWINMSRARGS Args;
1791 Args.uMsr = uMsr;
1792 Args.uValue.u = 0;
1793 Args.rc = -1;
1794
1795 if (idCpu == NIL_RTCPUID)
1796 {
1797 IPRT_DARWIN_SAVE_EFL_AC();
1798 supdrvDarwinMsrProberReadOnCpu(idCpu, &Args, NULL);
1799 IPRT_DARWIN_RESTORE_EFL_AC();
1800 }
1801 else
1802 {
1803 int rc = RTMpOnSpecific(idCpu, supdrvDarwinMsrProberReadOnCpu, &Args, NULL);
1804 if (RT_FAILURE(rc))
1805 return rc;
1806 }
1807
1808 if (Args.rc)
1809 return VERR_ACCESS_DENIED;
1810 *puValue = Args.uValue.u;
1811 return VINF_SUCCESS;
1812}
1813
1814
1815/**
1816 * On CPU worker for supdrvOSMsrProberWrite.
1817 *
1818 * @param idCpu Ignored.
1819 * @param pvUser1 Pointer to a SUPDRVDARWINMSRARGS.
1820 * @param pvUser2 Ignored.
1821 */
1822static DECLCALLBACK(void) supdrvDarwinMsrProberWriteOnCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
1823{
1824 PSUPDRVDARWINMSRARGS pArgs = (PSUPDRVDARWINMSRARGS)pvUser1;
1825 if (g_pfnWrMsr64Carefully)
1826 pArgs->rc = g_pfnWrMsr64Carefully(pArgs->uMsr, pArgs->uValue.u);
1827 else
1828 pArgs->rc = 2;
1829 NOREF(idCpu); NOREF(pvUser2);
1830}
1831
1832
1833int VBOXCALL supdrvOSMsrProberWrite(uint32_t uMsr, RTCPUID idCpu, uint64_t uValue)
1834{
1835 if (!g_pfnWrMsr64Carefully)
1836 return VERR_NOT_SUPPORTED;
1837
1838 SUPDRVDARWINMSRARGS Args;
1839 Args.uMsr = uMsr;
1840 Args.uValue.u = uValue;
1841 Args.rc = -1;
1842
1843 if (idCpu == NIL_RTCPUID)
1844 {
1845 IPRT_DARWIN_SAVE_EFL_AC();
1846 supdrvDarwinMsrProberWriteOnCpu(idCpu, &Args, NULL);
1847 IPRT_DARWIN_RESTORE_EFL_AC();
1848 }
1849 else
1850 {
1851 int rc = RTMpOnSpecific(idCpu, supdrvDarwinMsrProberWriteOnCpu, &Args, NULL);
1852 if (RT_FAILURE(rc))
1853 return rc;
1854 }
1855
1856 if (Args.rc)
1857 return VERR_ACCESS_DENIED;
1858 return VINF_SUCCESS;
1859}
1860
1861
1862/**
1863 * Worker for supdrvOSMsrProberModify.
1864 */
1865static DECLCALLBACK(void) supdrvDarwinMsrProberModifyOnCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
1866{
1867 RT_NOREF(idCpu, pvUser2);
1868 PSUPMSRPROBER pReq = (PSUPMSRPROBER)pvUser1;
1869 register uint32_t uMsr = pReq->u.In.uMsr;
1870 bool const fFaster = pReq->u.In.enmOp == SUPMSRPROBEROP_MODIFY_FASTER;
1871 uint64_t uBefore;
1872 uint64_t uWritten;
1873 uint64_t uAfter;
1874 int rcBefore, rcWrite, rcAfter, rcRestore;
1875 RTCCUINTREG fOldFlags;
1876
1877 /* Initialize result variables. */
1878 uBefore = uWritten = uAfter = 0;
1879 rcWrite = rcAfter = rcRestore = -1;
1880
1881 /*
1882 * Do the job.
1883 */
1884 fOldFlags = ASMIntDisableFlags();
1885 ASMCompilerBarrier(); /* paranoia */
1886 if (!fFaster)
1887 ASMWriteBackAndInvalidateCaches();
1888
1889 rcBefore = g_pfnRdMsr64Carefully(uMsr, &uBefore);
1890 if (rcBefore >= 0)
1891 {
1892 register uint64_t uRestore = uBefore;
1893 uWritten = uRestore;
1894 uWritten &= pReq->u.In.uArgs.Modify.fAndMask;
1895 uWritten |= pReq->u.In.uArgs.Modify.fOrMask;
1896
1897 rcWrite = g_pfnWrMsr64Carefully(uMsr, uWritten);
1898 rcAfter = g_pfnRdMsr64Carefully(uMsr, &uAfter);
1899 rcRestore = g_pfnWrMsr64Carefully(uMsr, uRestore);
1900
1901 if (!fFaster)
1902 {
1903 ASMWriteBackAndInvalidateCaches();
1904 ASMReloadCR3();
1905 ASMNopPause();
1906 }
1907 }
1908
1909 ASMCompilerBarrier(); /* paranoia */
1910 ASMSetFlags(fOldFlags);
1911
1912 /*
1913 * Write out the results.
1914 */
1915 pReq->u.Out.uResults.Modify.uBefore = uBefore;
1916 pReq->u.Out.uResults.Modify.uWritten = uWritten;
1917 pReq->u.Out.uResults.Modify.uAfter = uAfter;
1918 pReq->u.Out.uResults.Modify.fBeforeGp = rcBefore != 0;
1919 pReq->u.Out.uResults.Modify.fModifyGp = rcWrite != 0;
1920 pReq->u.Out.uResults.Modify.fAfterGp = rcAfter != 0;
1921 pReq->u.Out.uResults.Modify.fRestoreGp = rcRestore != 0;
1922 RT_ZERO(pReq->u.Out.uResults.Modify.afReserved);
1923}
1924
1925
1926int VBOXCALL supdrvOSMsrProberModify(RTCPUID idCpu, PSUPMSRPROBER pReq)
1927{
1928 if (!g_pfnWrMsr64Carefully || !g_pfnRdMsr64Carefully)
1929 return VERR_NOT_SUPPORTED;
1930 if (idCpu == NIL_RTCPUID)
1931 {
1932 IPRT_DARWIN_SAVE_EFL_AC();
1933 supdrvDarwinMsrProberModifyOnCpu(idCpu, pReq, NULL);
1934 IPRT_DARWIN_RESTORE_EFL_AC();
1935 return VINF_SUCCESS;
1936 }
1937 return RTMpOnSpecific(idCpu, supdrvDarwinMsrProberModifyOnCpu, pReq, NULL);
1938}
1939
1940#endif /* SUPDRV_WITH_MSR_PROBER || (defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86) */
1941
1942/**
1943 * Resume Bluetooth keyboard.
1944 * If there is no Bluetooth keyboard device connected to the system we just ignore this.
1945 */
1946static void supdrvDarwinResumeBluetoothKbd(void)
1947{
1948 OSDictionary *pDictionary = IOService::serviceMatching("AppleBluetoothHIDKeyboard");
1949 if (pDictionary)
1950 {
1951 OSIterator *pIter;
1952 IOBluetoothHIDDriver *pDriver;
1953
1954 pIter = IOService::getMatchingServices(pDictionary);
1955 if (pIter)
1956 {
1957 while ((pDriver = (IOBluetoothHIDDriver *)pIter->getNextObject()))
1958 if (pDriver->isKeyboard())
1959 (void)pDriver->hidControl(IOBTHID_CONTROL_EXIT_SUSPEND);
1960
1961 pIter->release();
1962 }
1963 pDictionary->release();
1964 }
1965}
1966
1967/**
1968 * Resume built-in keyboard on MacBook Air and Pro hosts.
1969 * If there is no built-in keyboard device attached to the system we just ignore this.
1970 */
1971static void supdrvDarwinResumeBuiltinKbd(void)
1972{
1973 /** @todo macbook pro 16 w/ 10.15.5 as the "Apple Internal Keyboard /
1974 * Trackpad" hooked up to "HID Relay" / "AppleUserUSBHostHIDDevice"
1975 * and "AppleUserUSBHostHIDDevice" among other things, but not
1976 * "AppleUSBTCKeyboard". This change is probably older than 10.15,
1977 * given that IOUSBHIDDriver not is present in the 10.11 SDK. */
1978#if MAC_OS_X_VERSION_MIN_REQUIRED < 101100
1979 /*
1980 * AppleUSBTCKeyboard KEXT is responsible for built-in keyboard management.
1981 * We resume keyboard by accessing to its IOService.
1982 */
1983 OSDictionary *pDictionary = IOService::serviceMatching("AppleUSBTCKeyboard");
1984 if (pDictionary)
1985 {
1986 OSIterator *pIter;
1987 IOUSBHIDDriver *pDriver;
1988
1989 pIter = IOService::getMatchingServices(pDictionary);
1990 if (pIter)
1991 {
1992 while ((pDriver = (IOUSBHIDDriver *)pIter->getNextObject()))
1993 if (pDriver->IsPortSuspended())
1994 pDriver->SuspendPort(false, 0);
1995
1996 pIter->release();
1997 }
1998 pDictionary->release();
1999 }
2000#endif
2001}
2002
2003
2004/**
2005 * Resume suspended keyboard devices (if any).
2006 */
2007int VBOXCALL supdrvDarwinResumeSuspendedKbds(void)
2008{
2009 IPRT_DARWIN_SAVE_EFL_AC();
2010 supdrvDarwinResumeBuiltinKbd();
2011 supdrvDarwinResumeBluetoothKbd();
2012 IPRT_DARWIN_RESTORE_EFL_AC();
2013 return 0;
2014}
2015
2016
2017/**
2018 * Converts an IPRT error code to a darwin error code.
2019 *
2020 * @returns corresponding darwin error code.
2021 * @param rc IPRT status code.
2022 */
2023static int VBoxDrvDarwinErr2DarwinErr(int rc)
2024{
2025 switch (rc)
2026 {
2027 case VINF_SUCCESS: return 0;
2028 case VERR_GENERAL_FAILURE: return EACCES;
2029 case VERR_INVALID_PARAMETER: return EINVAL;
2030 case VERR_INVALID_MAGIC: return EILSEQ;
2031 case VERR_INVALID_HANDLE: return ENXIO;
2032 case VERR_INVALID_POINTER: return EFAULT;
2033 case VERR_LOCK_FAILED: return ENOLCK;
2034 case VERR_ALREADY_LOADED: return EEXIST;
2035 case VERR_PERMISSION_DENIED: return EPERM;
2036 case VERR_VERSION_MISMATCH: return ENOSYS;
2037 }
2038
2039 return EPERM;
2040}
2041
2042
2043#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
2044/**
2045 * Check if the CPU has SMAP support.
2046 */
2047static bool vboxdrvDarwinCpuHasSMAP(void)
2048{
2049 uint32_t uMaxId, uEAX, uEBX, uECX, uEDX;
2050 ASMCpuId(0, &uMaxId, &uEBX, &uECX, &uEDX);
2051 if ( RTX86IsValidStdRange(uMaxId)
2052 && uMaxId >= 0x00000007)
2053 {
2054 ASMCpuId_Idx_ECX(0x00000007, 0, &uEAX, &uEBX, &uECX, &uEDX);
2055 if (uEBX & X86_CPUID_STEXT_FEATURE_EBX_SMAP)
2056 return true;
2057 }
2058# ifdef VBOX_WITH_EFLAGS_AC_SET_IN_VBOXDRV
2059 return true;
2060# else
2061 return false;
2062# endif
2063}
2064#endif /* RT_ARCH_AMD64 || RT_ARCH_X86 */
2065
2066
2067RTDECL(int) SUPR0PrintfV(const char *pszFormat, va_list va)
2068{
2069 IPRT_DARWIN_SAVE_EFL_AC();
2070
2071 char szMsg[512];
2072 RTStrPrintfV(szMsg, sizeof(szMsg) - 1, pszFormat, va);
2073 szMsg[sizeof(szMsg) - 1] = '\0';
2074
2075 printf("%s", szMsg);
2076 kprintf("%s", szMsg);
2077
2078 IPRT_DARWIN_RESTORE_EFL_AC();
2079 return 0;
2080}
2081
2082
2083SUPR0DECL(uint32_t) SUPR0GetKernelFeatures(void)
2084{
2085 return g_fKernelFeatures;
2086}
2087
2088
2089SUPR0DECL(bool) SUPR0FpuBegin(bool fCtxHook)
2090{
2091 RT_NOREF(fCtxHook);
2092 return false;
2093}
2094
2095
2096SUPR0DECL(void) SUPR0FpuEnd(bool fCtxHook)
2097{
2098 RT_NOREF(fCtxHook);
2099}
2100
2101/*
2102 *
2103 * org_virtualbox_SupDrv
2104 *
2105 * - IOService diff resync -
2106 * - IOService diff resync -
2107 * - IOService diff resync -
2108 *
2109 */
2110
2111
2112/**
2113 * Initialize the object.
2114 */
2115bool org_virtualbox_SupDrv::init(OSDictionary *pDictionary)
2116{
2117 LogFlow(("IOService::init([%p], %p)\n", this, pDictionary));
2118 if (IOService::init(pDictionary))
2119 {
2120 /* init members. */
2121 return true;
2122 }
2123 return false;
2124}
2125
2126
2127/**
2128 * Free the object.
2129 */
2130void org_virtualbox_SupDrv::free(void)
2131{
2132 LogFlow(("IOService::free([%p])\n", this));
2133 IOService::free();
2134}
2135
2136
2137/**
2138 * Check if it's ok to start this service.
2139 * It's always ok by us, so it's up to IOService to decide really.
2140 */
2141IOService *org_virtualbox_SupDrv::probe(IOService *pProvider, SInt32 *pi32Score)
2142{
2143 LogFlow(("IOService::probe([%p])\n", this));
2144 return IOService::probe(pProvider, pi32Score);
2145}
2146
2147
2148/**
2149 * Start this service.
2150 */
2151bool org_virtualbox_SupDrv::start(IOService *pProvider)
2152{
2153 LogFlow(("org_virtualbox_SupDrv::start([%p])\n", this));
2154
2155 if (IOService::start(pProvider))
2156 {
2157 /* register the service. */
2158 registerService();
2159 return true;
2160 }
2161 return false;
2162}
2163
2164
2165/**
2166 * Stop this service.
2167 */
2168void org_virtualbox_SupDrv::stop(IOService *pProvider)
2169{
2170 LogFlow(("org_virtualbox_SupDrv::stop([%p], %p)\n", this, pProvider));
2171 IOService::stop(pProvider);
2172}
2173
2174
2175/**
2176 * Termination request.
2177 *
2178 * @return true if we're ok with shutting down now, false if we're not.
2179 * @param fOptions Flags.
2180 */
2181bool org_virtualbox_SupDrv::terminate(IOOptionBits fOptions)
2182{
2183 bool fRc;
2184 LogFlow(("org_virtualbox_SupDrv::terminate: reference_count=%d g_cSessions=%d (fOptions=%#x)\n",
2185 KMOD_INFO_NAME.reference_count, ASMAtomicUoReadS32(&g_cSessions), fOptions));
2186 if ( KMOD_INFO_NAME.reference_count != 0
2187 || ASMAtomicUoReadS32(&g_cSessions))
2188 fRc = false;
2189 else
2190 fRc = IOService::terminate(fOptions);
2191 LogFlow(("org_virtualbox_SupDrv::terminate: returns %d\n", fRc));
2192 return fRc;
2193}
2194
2195
2196/*
2197 *
2198 * org_virtualbox_SupDrvClient
2199 *
2200 */
2201
2202
2203/**
2204 * Initializer called when the client opens the service.
2205 */
2206bool org_virtualbox_SupDrvClient::initWithTask(task_t OwningTask, void *pvSecurityId, UInt32 u32Type)
2207{
2208 LogFlow(("org_virtualbox_SupDrvClient::initWithTask([%p], %#x, %p, %#x) (cur pid=%d proc=%p)\n",
2209 this, OwningTask, pvSecurityId, u32Type, RTProcSelf(), RTR0ProcHandleSelf()));
2210 AssertMsg((RTR0PROCESS)OwningTask == RTR0ProcHandleSelf(), ("%p %p\n", OwningTask, RTR0ProcHandleSelf()));
2211
2212 if (!OwningTask)
2213 return false;
2214
2215 if (u32Type != SUP_DARWIN_IOSERVICE_COOKIE)
2216 {
2217 VBOX_RETRIEVE_CUR_PROC_NAME(szProcName);
2218 LogRelMax(10,("org_virtualbox_SupDrvClient::initWithTask: Bad cookie %#x (%s)\n", u32Type, szProcName));
2219 return false;
2220 }
2221
2222 if (IOUserClient::initWithTask(OwningTask, pvSecurityId , u32Type))
2223 {
2224 /*
2225 * In theory we have to call task_reference() to make sure that the task is
2226 * valid during the lifetime of this object. The pointer is only used to check
2227 * for the context this object is called in though and never dereferenced
2228 * or passed to anything which might, so we just skip this step.
2229 */
2230 m_Task = OwningTask;
2231 m_pSession = NULL;
2232 m_pProvider = NULL;
2233 return true;
2234 }
2235 return false;
2236}
2237
2238
2239/**
2240 * Start the client service.
2241 */
2242bool org_virtualbox_SupDrvClient::start(IOService *pProvider)
2243{
2244 LogFlow(("org_virtualbox_SupDrvClient::start([%p], %p) (cur pid=%d proc=%p)\n",
2245 this, pProvider, RTProcSelf(), RTR0ProcHandleSelf() ));
2246 AssertMsgReturn((RTR0PROCESS)m_Task == RTR0ProcHandleSelf(),
2247 ("%p %p\n", m_Task, RTR0ProcHandleSelf()),
2248 false);
2249
2250 if (IOUserClient::start(pProvider))
2251 {
2252 m_pProvider = OSDynamicCast(org_virtualbox_SupDrv, pProvider);
2253 if (m_pProvider)
2254 {
2255 Assert(!m_pSession);
2256
2257 /*
2258 * Create a new session.
2259 */
2260 int rc = supdrvCreateSession(&g_DevExt, true /* fUser */, false /*fUnrestricted*/, &m_pSession);
2261 if (RT_SUCCESS(rc))
2262 {
2263 m_pSession->fOpened = false;
2264 /* The Uid, Gid and fUnrestricted fields are set on open. */
2265
2266 /*
2267 * Insert it into the hash table, checking that there isn't
2268 * already one for this process first. (One session per proc!)
2269 */
2270 unsigned iHash = SESSION_HASH(m_pSession->Process);
2271 RTSpinlockAcquire(g_Spinlock);
2272
2273 PSUPDRVSESSION pCur = g_apSessionHashTab[iHash];
2274 while (pCur && pCur->Process != m_pSession->Process)
2275 pCur = pCur->pNextHash;
2276 if (!pCur)
2277 {
2278 m_pSession->pNextHash = g_apSessionHashTab[iHash];
2279 g_apSessionHashTab[iHash] = m_pSession;
2280 m_pSession->pvSupDrvClient = this;
2281 ASMAtomicIncS32(&g_cSessions);
2282 rc = VINF_SUCCESS;
2283 }
2284 else
2285 rc = VERR_ALREADY_LOADED;
2286
2287 RTSpinlockRelease(g_Spinlock);
2288 if (RT_SUCCESS(rc))
2289 {
2290 Log(("org_virtualbox_SupDrvClient::start: created session %p for pid %d\n", m_pSession, (int)RTProcSelf()));
2291 return true;
2292 }
2293
2294 LogFlow(("org_virtualbox_SupDrvClient::start: already got a session for this process (%p)\n", pCur));
2295 supdrvSessionRelease(m_pSession);
2296 }
2297
2298 m_pSession = NULL;
2299 LogFlow(("org_virtualbox_SupDrvClient::start: rc=%Rrc from supdrvCreateSession\n", rc));
2300 }
2301 else
2302 LogFlow(("org_virtualbox_SupDrvClient::start: %p isn't org_virtualbox_SupDrv\n", pProvider));
2303 }
2304 return false;
2305}
2306
2307
2308/**
2309 * Common worker for clientClose and VBoxDrvDarwinClose.
2310 */
2311/* static */ void org_virtualbox_SupDrvClient::sessionClose(RTPROCESS Process)
2312{
2313 /*
2314 * Find the session and remove it from the hash table.
2315 *
2316 * Note! Only one session per process. (Both start() and
2317 * VBoxDrvDarwinOpen makes sure this is so.)
2318 */
2319 const unsigned iHash = SESSION_HASH(Process);
2320 RTSpinlockAcquire(g_Spinlock);
2321 PSUPDRVSESSION pSession = g_apSessionHashTab[iHash];
2322 if (pSession)
2323 {
2324 if (pSession->Process == Process)
2325 {
2326 g_apSessionHashTab[iHash] = pSession->pNextHash;
2327 pSession->pNextHash = NULL;
2328 ASMAtomicDecS32(&g_cSessions);
2329 }
2330 else
2331 {
2332 PSUPDRVSESSION pPrev = pSession;
2333 pSession = pSession->pNextHash;
2334 while (pSession)
2335 {
2336 if (pSession->Process == Process)
2337 {
2338 pPrev->pNextHash = pSession->pNextHash;
2339 pSession->pNextHash = NULL;
2340 ASMAtomicDecS32(&g_cSessions);
2341 break;
2342 }
2343
2344 /* next */
2345 pPrev = pSession;
2346 pSession = pSession->pNextHash;
2347 }
2348 }
2349 }
2350 RTSpinlockRelease(g_Spinlock);
2351 if (!pSession)
2352 {
2353 Log(("SupDrvClient::sessionClose: pSession == NULL, pid=%d; freed already?\n", (int)Process));
2354 return;
2355 }
2356
2357 /*
2358 * Remove it from the client object.
2359 */
2360 org_virtualbox_SupDrvClient *pThis = (org_virtualbox_SupDrvClient *)pSession->pvSupDrvClient;
2361 pSession->pvSupDrvClient = NULL;
2362 if (pThis)
2363 {
2364 Assert(pThis->m_pSession == pSession);
2365 pThis->m_pSession = NULL;
2366 }
2367
2368 /*
2369 * Close the session.
2370 */
2371 supdrvSessionRelease(pSession);
2372}
2373
2374
2375/**
2376 * Client exits normally.
2377 */
2378IOReturn org_virtualbox_SupDrvClient::clientClose(void)
2379{
2380 LogFlow(("org_virtualbox_SupDrvClient::clientClose([%p]) (cur pid=%d proc=%p)\n", this, RTProcSelf(), RTR0ProcHandleSelf()));
2381 AssertMsg((RTR0PROCESS)m_Task == RTR0ProcHandleSelf(), ("%p %p\n", m_Task, RTR0ProcHandleSelf()));
2382
2383 /*
2384 * Clean up the session if it's still around.
2385 *
2386 * We cannot rely 100% on close, and in the case of a dead client
2387 * we'll end up hanging inside vm_map_remove() if we postpone it.
2388 */
2389 if (m_pSession)
2390 {
2391 sessionClose(RTProcSelf());
2392 Assert(!m_pSession);
2393 }
2394
2395 m_pProvider = NULL;
2396 terminate();
2397
2398 return kIOReturnSuccess;
2399}
2400
2401
2402/**
2403 * The client exits abnormally / forgets to do cleanups. (logging)
2404 */
2405IOReturn org_virtualbox_SupDrvClient::clientDied(void)
2406{
2407 LogFlow(("IOService::clientDied([%p]) m_Task=%p R0Process=%p Process=%d\n", this, m_Task, RTR0ProcHandleSelf(), RTProcSelf()));
2408
2409 /* IOUserClient::clientDied() calls clientClose, so we'll just do the work there. */
2410 return IOUserClient::clientDied();
2411}
2412
2413
2414/**
2415 * Terminate the service (initiate the destruction). (logging)
2416 */
2417bool org_virtualbox_SupDrvClient::terminate(IOOptionBits fOptions)
2418{
2419 LogFlow(("IOService::terminate([%p], %#x)\n", this, fOptions));
2420 return IOUserClient::terminate(fOptions);
2421}
2422
2423
2424/**
2425 * The final stage of the client service destruction. (logging)
2426 */
2427bool org_virtualbox_SupDrvClient::finalize(IOOptionBits fOptions)
2428{
2429 LogFlow(("IOService::finalize([%p], %#x)\n", this, fOptions));
2430 return IOUserClient::finalize(fOptions);
2431}
2432
2433
2434/**
2435 * Stop the client service. (logging)
2436 */
2437void org_virtualbox_SupDrvClient::stop(IOService *pProvider)
2438{
2439 LogFlow(("IOService::stop([%p])\n", this));
2440 IOUserClient::stop(pProvider);
2441}
2442
Note: See TracBrowser for help on using the repository browser.

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