VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/darwin/iokit.cpp@ 56824

Last change on this file since 56824 was 52743, checked in by vboxsync, 10 years ago

Main/USB: Fix darwin assertion on Macbooks with USB 3.0 (Superspeed) ports and devices, introduce new device speed enum value for USB 3.0 devices

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 69.8 KB
Line 
1/* $Id: iokit.cpp 52743 2014-09-15 07:25:29Z vboxsync $ */
2/** @file
3 * Main - Darwin IOKit Routines.
4 *
5 * Because IOKit makes use of COM like interfaces, it does not mix very
6 * well with COM/XPCOM and must therefore be isolated from it using a
7 * simpler C interface.
8 */
9
10/*
11 * Copyright (C) 2006-2014 Oracle Corporation
12 *
13 * This file is part of VirtualBox Open Source Edition (OSE), as
14 * available from http://www.virtualbox.org. This file is free software;
15 * you can redistribute it and/or modify it under the terms of the GNU
16 * General Public License (GPL) as published by the Free Software
17 * Foundation, in version 2 as it comes in the "COPYING" file of the
18 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
19 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
20 */
21
22
23/*******************************************************************************
24* Header Files *
25*******************************************************************************/
26#define LOG_GROUP LOG_GROUP_MAIN
27#ifdef STANDALONE_TESTCASE
28# define VBOX_WITH_USB
29#endif
30
31#include <mach/mach.h>
32#include <Carbon/Carbon.h>
33#include <IOKit/IOKitLib.h>
34#include <IOKit/storage/IOStorageDeviceCharacteristics.h>
35#include <IOKit/scsi/SCSITaskLib.h>
36#include <SystemConfiguration/SystemConfiguration.h>
37#include <mach/mach_error.h>
38#ifdef VBOX_WITH_USB
39# include <IOKit/usb/IOUSBLib.h>
40# include <IOKit/IOCFPlugIn.h>
41# include <IOKit/storage/IOMedia.h>
42#endif
43
44#include <VBox/log.h>
45#include <VBox/err.h>
46#include <iprt/mem.h>
47#include <iprt/string.h>
48#include <iprt/process.h>
49#include <iprt/assert.h>
50#include <iprt/thread.h>
51#include <iprt/uuid.h>
52#ifdef STANDALONE_TESTCASE
53# include <iprt/initterm.h>
54# include <iprt/stream.h>
55#endif
56
57#include "iokit.h"
58
59/* A small hack... */
60#ifdef STANDALONE_TESTCASE
61# define DarwinFreeUSBDeviceFromIOKit(a) do { } while (0)
62#endif
63
64
65/*******************************************************************************
66* Defined Constants And Macros *
67*******************************************************************************/
68/** An attempt at catching reference leaks. */
69#define MY_CHECK_CREFS(cRefs) do { AssertMsg(cRefs < 25, ("%ld\n", cRefs)); NOREF(cRefs); } while (0)
70
71/** Contains the pid of the current client. If 0, the kernel is the current client. */
72#define VBOXUSB_CLIENT_KEY "VBoxUSB-Client"
73/** Contains the pid of the filter owner (i.e. the VBoxSVC pid). */
74#define VBOXUSB_OWNER_KEY "VBoxUSB-Owner"
75/** The VBoxUSBDevice class name. */
76#define VBOXUSBDEVICE_CLASS_NAME "org_virtualbox_VBoxUSBDevice"
77
78
79/*******************************************************************************
80* Global Variables *
81*******************************************************************************/
82/** The IO Master Port. */
83static mach_port_t g_MasterPort = NULL;
84
85
86/**
87 * Lazily opens the master port.
88 *
89 * @returns true if the port is open, false on failure (very unlikely).
90 */
91static bool darwinOpenMasterPort(void)
92{
93 if (!g_MasterPort)
94 {
95 kern_return_t krc = IOMasterPort(MACH_PORT_NULL, &g_MasterPort);
96 AssertReturn(krc == KERN_SUCCESS, false);
97 }
98 return true;
99}
100
101
102/**
103 * Checks whether the value exists.
104 *
105 * @returns true / false accordingly.
106 * @param DictRef The dictionary.
107 * @param KeyStrRef The key name.
108 */
109static bool darwinDictIsPresent(CFDictionaryRef DictRef, CFStringRef KeyStrRef)
110{
111 return !!CFDictionaryGetValue(DictRef, KeyStrRef);
112}
113
114
115/**
116 * Gets a boolean value.
117 *
118 * @returns Success indicator (true/false).
119 * @param DictRef The dictionary.
120 * @param KeyStrRef The key name.
121 * @param pf Where to store the key value.
122 */
123static bool darwinDictGetBool(CFDictionaryRef DictRef, CFStringRef KeyStrRef, bool *pf)
124{
125 CFTypeRef BoolRef = CFDictionaryGetValue(DictRef, KeyStrRef);
126 if ( BoolRef
127 && CFGetTypeID(BoolRef) == CFBooleanGetTypeID())
128 {
129 *pf = CFBooleanGetValue((CFBooleanRef)BoolRef);
130 return true;
131 }
132 *pf = false;
133 return false;
134}
135
136
137/**
138 * Gets an unsigned 8-bit integer value.
139 *
140 * @returns Success indicator (true/false).
141 * @param DictRef The dictionary.
142 * @param KeyStrRef The key name.
143 * @param pu8 Where to store the key value.
144 */
145static bool darwinDictGetU8(CFDictionaryRef DictRef, CFStringRef KeyStrRef, uint8_t *pu8)
146{
147 CFTypeRef ValRef = CFDictionaryGetValue(DictRef, KeyStrRef);
148 if (ValRef)
149 {
150 if (CFNumberGetValue((CFNumberRef)ValRef, kCFNumberSInt8Type, pu8))
151 return true;
152 }
153 *pu8 = 0;
154 return false;
155}
156
157
158/**
159 * Gets an unsigned 16-bit integer value.
160 *
161 * @returns Success indicator (true/false).
162 * @param DictRef The dictionary.
163 * @param KeyStrRef The key name.
164 * @param pu16 Where to store the key value.
165 */
166static bool darwinDictGetU16(CFDictionaryRef DictRef, CFStringRef KeyStrRef, uint16_t *pu16)
167{
168 CFTypeRef ValRef = CFDictionaryGetValue(DictRef, KeyStrRef);
169 if (ValRef)
170 {
171 if (CFNumberGetValue((CFNumberRef)ValRef, kCFNumberSInt16Type, pu16))
172 return true;
173 }
174 *pu16 = 0;
175 return false;
176}
177
178
179/**
180 * Gets an unsigned 32-bit integer value.
181 *
182 * @returns Success indicator (true/false).
183 * @param DictRef The dictionary.
184 * @param KeyStrRef The key name.
185 * @param pu32 Where to store the key value.
186 */
187static bool darwinDictGetU32(CFDictionaryRef DictRef, CFStringRef KeyStrRef, uint32_t *pu32)
188{
189 CFTypeRef ValRef = CFDictionaryGetValue(DictRef, KeyStrRef);
190 if (ValRef)
191 {
192 if (CFNumberGetValue((CFNumberRef)ValRef, kCFNumberSInt32Type, pu32))
193 return true;
194 }
195 *pu32 = 0;
196 return false;
197}
198
199
200/**
201 * Gets an unsigned 64-bit integer value.
202 *
203 * @returns Success indicator (true/false).
204 * @param DictRef The dictionary.
205 * @param KeyStrRef The key name.
206 * @param pu64 Where to store the key value.
207 */
208static bool darwinDictGetU64(CFDictionaryRef DictRef, CFStringRef KeyStrRef, uint64_t *pu64)
209{
210 CFTypeRef ValRef = CFDictionaryGetValue(DictRef, KeyStrRef);
211 if (ValRef)
212 {
213 if (CFNumberGetValue((CFNumberRef)ValRef, kCFNumberSInt64Type, pu64))
214 return true;
215 }
216 *pu64 = 0;
217 return false;
218}
219
220
221/**
222 * Gets a RTPROCESS value.
223 *
224 * @returns Success indicator (true/false).
225 * @param DictRef The dictionary.
226 * @param KeyStrRef The key name.
227 * @param pProcess Where to store the key value.
228 */
229static bool darwinDictGetProcess(CFMutableDictionaryRef DictRef, CFStringRef KeyStrRef, PRTPROCESS pProcess)
230{
231 switch (sizeof(*pProcess))
232 {
233 case sizeof(uint16_t): return darwinDictGetU16(DictRef, KeyStrRef, (uint16_t *)pProcess);
234 case sizeof(uint32_t): return darwinDictGetU32(DictRef, KeyStrRef, (uint32_t *)pProcess);
235 case sizeof(uint64_t): return darwinDictGetU64(DictRef, KeyStrRef, (uint64_t *)pProcess);
236 default:
237 AssertMsgFailedReturn(("%d\n", sizeof(*pProcess)), false);
238 }
239}
240
241
242/**
243 * Gets string value, converted to UTF-8 and put in user buffer.
244 *
245 * @returns Success indicator (true/false).
246 * @param DictRef The dictionary.
247 * @param KeyStrRef The key name.
248 * @param psz The string buffer. On failure this will be an empty string ("").
249 * @param cch The size of the buffer.
250 */
251static bool darwinDictGetString(CFDictionaryRef DictRef, CFStringRef KeyStrRef, char *psz, size_t cch)
252{
253 CFTypeRef ValRef = CFDictionaryGetValue(DictRef, KeyStrRef);
254 if (ValRef)
255 {
256 if (CFStringGetCString((CFStringRef)ValRef, psz, cch, kCFStringEncodingUTF8))
257 return true;
258 }
259 Assert(cch > 0);
260 *psz = '\0';
261 return false;
262}
263
264
265/**
266 * Gets string value, converted to UTF-8 and put in a IPRT string buffer.
267 *
268 * @returns Success indicator (true/false).
269 * @param DictRef The dictionary.
270 * @param KeyStrRef The key name.
271 * @param ppsz Where to store the key value. Free with RTStrFree. Set to NULL on failure.
272 */
273static bool darwinDictDupString(CFDictionaryRef DictRef, CFStringRef KeyStrRef, char **ppsz)
274{
275 char szBuf[512];
276 if (darwinDictGetString(DictRef, KeyStrRef, szBuf, sizeof(szBuf)))
277 {
278 *ppsz = RTStrDup(szBuf);
279 if (*ppsz)
280 return true;
281 }
282 *ppsz = NULL;
283 return false;
284}
285
286
287/**
288 * Gets a byte string (data) of a specific size.
289 *
290 * @returns Success indicator (true/false).
291 * @param DictRef The dictionary.
292 * @param KeyStrRef The key name.
293 * @param pvBuf The buffer to store the bytes in.
294 * @param cbBuf The size of the buffer. This must exactly match the data size.
295 */
296static bool darwinDictGetData(CFDictionaryRef DictRef, CFStringRef KeyStrRef, void *pvBuf, size_t cbBuf)
297{
298 CFTypeRef ValRef = CFDictionaryGetValue(DictRef, KeyStrRef);
299 if (ValRef)
300 {
301 CFIndex cbActual = CFDataGetLength((CFDataRef)ValRef);
302 if (cbActual >= 0 && cbBuf == (size_t)cbActual)
303 {
304 CFDataGetBytes((CFDataRef)ValRef, CFRangeMake(0, cbBuf), (uint8_t *)pvBuf);
305 return true;
306 }
307 }
308 memset(pvBuf, '\0', cbBuf);
309 return false;
310}
311
312
313#if 1 && !defined(STANDALONE_TESTCASE) /* dumping disabled */
314# define DARWIN_IOKIT_LOG(a) Log(a)
315# define DARWIN_IOKIT_LOG_FLUSH() do {} while (0)
316# define DARWIN_IOKIT_DUMP_OBJ(o) do {} while (0)
317#else
318# if defined(STANDALONE_TESTCASE)
319# include <iprt/stream.h>
320# define DARWIN_IOKIT_LOG(a) RTPrintf a
321# define DARWIN_IOKIT_LOG_FLUSH() RTStrmFlush(g_pStdOut)
322# else
323# define DARWIN_IOKIT_LOG(a) RTLogPrintf a
324# define DARWIN_IOKIT_LOG_FLUSH() RTLogFlush(NULL)
325# endif
326# define DARWIN_IOKIT_DUMP_OBJ(o) darwinDumpObj(o)
327
328/**
329 * Callback for dumping a dictionary key.
330 *
331 * @param pvKey The key name.
332 * @param pvValue The key value
333 * @param pvUser The recursion depth.
334 */
335static void darwinDumpDictCallback(const void *pvKey, const void *pvValue, void *pvUser)
336{
337 /* display the key name. */
338 char *pszKey = (char *)RTMemTmpAlloc(1024);
339 if (!CFStringGetCString((CFStringRef)pvKey, pszKey, 1024, kCFStringEncodingUTF8))
340 strcpy(pszKey, "CFStringGetCString failure");
341 DARWIN_IOKIT_LOG(("%+*s%s", (int)(uintptr_t)pvUser, "", pszKey));
342 RTMemTmpFree(pszKey);
343
344 /* display the value type */
345 CFTypeID Type = CFGetTypeID(pvValue);
346 DARWIN_IOKIT_LOG((" [%d-", Type));
347
348 /* display the value */
349 if (Type == CFDictionaryGetTypeID())
350 {
351 DARWIN_IOKIT_LOG(("dictionary] =\n"
352 "%-*s{\n", (int)(uintptr_t)pvUser, ""));
353 CFDictionaryApplyFunction((CFDictionaryRef)pvValue, darwinDumpDictCallback, (void *)((uintptr_t)pvUser + 4));
354 DARWIN_IOKIT_LOG(("%-*s}\n", (int)(uintptr_t)pvUser, ""));
355 }
356 else if (Type == CFBooleanGetTypeID())
357 DARWIN_IOKIT_LOG(("bool] = %s\n", CFBooleanGetValue((CFBooleanRef)pvValue) ? "true" : "false"));
358 else if (Type == CFNumberGetTypeID())
359 {
360 union
361 {
362 SInt8 s8;
363 SInt16 s16;
364 SInt32 s32;
365 SInt64 s64;
366 Float32 rf32;
367 Float64 rd64;
368 char ch;
369 short s;
370 int i;
371 long l;
372 long long ll;
373 float rf;
374 double rd;
375 CFIndex iCF;
376 } u;
377 RT_ZERO(u);
378 CFNumberType NumType = CFNumberGetType((CFNumberRef)pvValue);
379 if (CFNumberGetValue((CFNumberRef)pvValue, NumType, &u))
380 {
381 switch (CFNumberGetType((CFNumberRef)pvValue))
382 {
383 case kCFNumberSInt8Type: DARWIN_IOKIT_LOG(("SInt8] = %RI8 (%#RX8)\n", NumType, u.s8, u.s8)); break;
384 case kCFNumberSInt16Type: DARWIN_IOKIT_LOG(("SInt16] = %RI16 (%#RX16)\n", NumType, u.s16, u.s16)); break;
385 case kCFNumberSInt32Type: DARWIN_IOKIT_LOG(("SInt32] = %RI32 (%#RX32)\n", NumType, u.s32, u.s32)); break;
386 case kCFNumberSInt64Type: DARWIN_IOKIT_LOG(("SInt64] = %RI64 (%#RX64)\n", NumType, u.s64, u.s64)); break;
387 case kCFNumberFloat32Type: DARWIN_IOKIT_LOG(("float32] = %#lx\n", NumType, u.l)); break;
388 case kCFNumberFloat64Type: DARWIN_IOKIT_LOG(("float64] = %#llx\n", NumType, u.ll)); break;
389 case kCFNumberFloatType: DARWIN_IOKIT_LOG(("float] = %#lx\n", NumType, u.l)); break;
390 case kCFNumberDoubleType: DARWIN_IOKIT_LOG(("double] = %#llx\n", NumType, u.ll)); break;
391 case kCFNumberCharType: DARWIN_IOKIT_LOG(("char] = %hhd (%hhx)\n", NumType, u.ch, u.ch)); break;
392 case kCFNumberShortType: DARWIN_IOKIT_LOG(("short] = %hd (%hx)\n", NumType, u.s, u.s)); break;
393 case kCFNumberIntType: DARWIN_IOKIT_LOG(("int] = %d (%#x)\n", NumType, u.i, u.i)); break;
394 case kCFNumberLongType: DARWIN_IOKIT_LOG(("long] = %ld (%#lx)\n", NumType, u.l, u.l)); break;
395 case kCFNumberLongLongType: DARWIN_IOKIT_LOG(("long long] = %lld (%#llx)\n", NumType, u.ll, u.ll)); break;
396 case kCFNumberCFIndexType: DARWIN_IOKIT_LOG(("CFIndex] = %lld (%#llx)\n", NumType, (long long)u.iCF, (long long)u.iCF)); break;
397 break;
398 default: DARWIN_IOKIT_LOG(("%d?] = %lld (%llx)\n", NumType, u.ll, u.ll)); break;
399 }
400 }
401 else
402 DARWIN_IOKIT_LOG(("number] = CFNumberGetValue failed\n"));
403 }
404 else if (Type == CFBooleanGetTypeID())
405 DARWIN_IOKIT_LOG(("boolean] = %RTbool\n", CFBooleanGetValue((CFBooleanRef)pvValue)));
406 else if (Type == CFStringGetTypeID())
407 {
408 DARWIN_IOKIT_LOG(("string] = "));
409 char *pszValue = (char *)RTMemTmpAlloc(16*_1K);
410 if (!CFStringGetCString((CFStringRef)pvValue, pszValue, 16*_1K, kCFStringEncodingUTF8))
411 strcpy(pszValue, "CFStringGetCString failure");
412 DARWIN_IOKIT_LOG(("\"%s\"\n", pszValue));
413 RTMemTmpFree(pszValue);
414 }
415 else if (Type == CFDataGetTypeID())
416 {
417 CFIndex cb = CFDataGetLength((CFDataRef)pvValue);
418 DARWIN_IOKIT_LOG(("%zu bytes] =", (size_t)cb));
419 void *pvData = RTMemTmpAlloc(cb + 8);
420 CFDataGetBytes((CFDataRef)pvValue, CFRangeMake(0, cb), (uint8_t *)pvData);
421 if (!cb)
422 DARWIN_IOKIT_LOG((" \n"));
423 else if (cb <= 32)
424 DARWIN_IOKIT_LOG((" %.*Rhxs\n", cb, pvData));
425 else
426 DARWIN_IOKIT_LOG(("\n%.*Rhxd\n", cb, pvData));
427 RTMemTmpFree(pvData);
428 }
429 else
430 DARWIN_IOKIT_LOG(("??] = %p\n", pvValue));
431}
432
433
434/**
435 * Dumps a dictionary to the log.
436 *
437 * @param DictRef The dictionary to dump.
438 */
439static void darwinDumpDict(CFDictionaryRef DictRef, unsigned cIndents)
440{
441 CFDictionaryApplyFunction(DictRef, darwinDumpDictCallback, (void *)(uintptr_t)cIndents);
442 DARWIN_IOKIT_LOG_FLUSH();
443}
444
445
446/**
447 * Dumps an I/O kit registry object and all it children.
448 * @param Object The object to dump.
449 * @param cIndents The number of indents to use.
450 */
451static void darwinDumpObjInt(io_object_t Object, unsigned cIndents)
452{
453 static io_string_t s_szPath;
454 kern_return_t krc = IORegistryEntryGetPath(Object, kIOServicePlane, s_szPath);
455 if (krc != KERN_SUCCESS)
456 strcpy(s_szPath, "IORegistryEntryGetPath failed");
457 DARWIN_IOKIT_LOG(("Dumping %p - %s:\n", (const void *)Object, s_szPath));
458
459 CFMutableDictionaryRef PropsRef = 0;
460 krc = IORegistryEntryCreateCFProperties(Object, &PropsRef, kCFAllocatorDefault, kNilOptions);
461 if (krc == KERN_SUCCESS)
462 {
463 darwinDumpDict(PropsRef, cIndents + 4);
464 CFRelease(PropsRef);
465 }
466
467 /*
468 * Children.
469 */
470 io_iterator_t Children;
471 krc = IORegistryEntryGetChildIterator(Object, kIOServicePlane, &Children);
472 if (krc == KERN_SUCCESS)
473 {
474 io_object_t Child;
475 while ((Child = IOIteratorNext(Children)))
476 {
477 darwinDumpObjInt(Child, cIndents + 4);
478 IOObjectRelease(Child);
479 }
480 IOObjectRelease(Children);
481 }
482 else
483 DARWIN_IOKIT_LOG(("IORegistryEntryGetChildIterator -> %#x\n", krc));
484}
485
486/**
487 * Dumps an I/O kit registry object and all it children.
488 * @param Object The object to dump.
489 */
490static void darwinDumpObj(io_object_t Object)
491{
492 darwinDumpObjInt(Object, 0);
493}
494
495#endif /* helpers for dumping registry dictionaries */
496
497
498#ifdef VBOX_WITH_USB
499
500/**
501 * Notification data created by DarwinSubscribeUSBNotifications, used by
502 * the callbacks and finally freed by DarwinUnsubscribeUSBNotifications.
503 */
504typedef struct DARWINUSBNOTIFY
505{
506 /** The notification port.
507 * It's shared between the notification callbacks. */
508 IONotificationPortRef NotifyPort;
509 /** The run loop source for NotifyPort. */
510 CFRunLoopSourceRef NotifyRLSrc;
511 /** The attach notification iterator. */
512 io_iterator_t AttachIterator;
513 /** The 2nd attach notification iterator. */
514 io_iterator_t AttachIterator2;
515 /** The detach notification iterator. */
516 io_iterator_t DetachIterator;
517} DARWINUSBNOTIFY, *PDARWINUSBNOTIFY;
518
519
520/**
521 * Run thru an iterator.
522 *
523 * The docs says this is necessary to start getting notifications,
524 * so this function is called in the callbacks and right after
525 * registering the notification.
526 *
527 * @param pIterator The iterator reference.
528 */
529static void darwinDrainIterator(io_iterator_t pIterator)
530{
531 io_object_t Object;
532 while ((Object = IOIteratorNext(pIterator)))
533 {
534 DARWIN_IOKIT_DUMP_OBJ(Object);
535 IOObjectRelease(Object);
536 }
537}
538
539
540/**
541 * Callback for the 1st attach notification.
542 *
543 * @param pvNotify Our data.
544 * @param NotifyIterator The notification iterator.
545 */
546static void darwinUSBAttachNotification1(void *pvNotify, io_iterator_t NotifyIterator)
547{
548 DARWIN_IOKIT_LOG(("USB Attach Notification1\n"));
549 NOREF(pvNotify); //PDARWINUSBNOTIFY pNotify = (PDARWINUSBNOTIFY)pvNotify;
550 darwinDrainIterator(NotifyIterator);
551}
552
553
554/**
555 * Callback for the 2nd attach notification.
556 *
557 * @param pvNotify Our data.
558 * @param NotifyIterator The notification iterator.
559 */
560static void darwinUSBAttachNotification2(void *pvNotify, io_iterator_t NotifyIterator)
561{
562 DARWIN_IOKIT_LOG(("USB Attach Notification2\n"));
563 NOREF(pvNotify); //PDARWINUSBNOTIFY pNotify = (PDARWINUSBNOTIFY)pvNotify;
564 darwinDrainIterator(NotifyIterator);
565}
566
567
568/**
569 * Callback for the detach notifications.
570 *
571 * @param pvNotify Our data.
572 * @param NotifyIterator The notification iterator.
573 */
574static void darwinUSBDetachNotification(void *pvNotify, io_iterator_t NotifyIterator)
575{
576 DARWIN_IOKIT_LOG(("USB Detach Notification\n"));
577 NOREF(pvNotify); //PDARWINUSBNOTIFY pNotify = (PDARWINUSBNOTIFY)pvNotify;
578 darwinDrainIterator(NotifyIterator);
579}
580
581
582/**
583 * Subscribes the run loop to USB notification events relevant to
584 * device attach/detach.
585 *
586 * The source mode for these events is defined as VBOX_IOKIT_MODE_STRING
587 * so that the caller can listen to events from this mode only and
588 * re-evalutate the list of attached devices whenever an event arrives.
589 *
590 * @returns opaque for passing to the unsubscribe function. If NULL
591 * something unexpectedly failed during subscription.
592 */
593void *DarwinSubscribeUSBNotifications(void)
594{
595 AssertReturn(darwinOpenMasterPort(), NULL);
596
597 PDARWINUSBNOTIFY pNotify = (PDARWINUSBNOTIFY)RTMemAllocZ(sizeof(*pNotify));
598 AssertReturn(pNotify, NULL);
599
600 /*
601 * Create the notification port, bake it into a runloop source which we
602 * then add to our run loop.
603 */
604 pNotify->NotifyPort = IONotificationPortCreate(g_MasterPort);
605 Assert(pNotify->NotifyPort);
606 if (pNotify->NotifyPort)
607 {
608 pNotify->NotifyRLSrc = IONotificationPortGetRunLoopSource(pNotify->NotifyPort);
609 Assert(pNotify->NotifyRLSrc);
610 if (pNotify->NotifyRLSrc)
611 {
612 CFRunLoopRef RunLoopRef = CFRunLoopGetCurrent();
613 CFRetain(RunLoopRef); /* Workaround for crash when cleaning up the TLS / runloop((sub)mode). See @bugref{2807}. */
614 CFRunLoopAddSource(RunLoopRef, pNotify->NotifyRLSrc, CFSTR(VBOX_IOKIT_MODE_STRING));
615
616 /*
617 * Create the notification callbacks.
618 */
619 kern_return_t rc = IOServiceAddMatchingNotification(pNotify->NotifyPort,
620 kIOPublishNotification,
621 IOServiceMatching(kIOUSBDeviceClassName),
622 darwinUSBAttachNotification1,
623 pNotify,
624 &pNotify->AttachIterator);
625 if (rc == KERN_SUCCESS)
626 {
627 darwinDrainIterator(pNotify->AttachIterator);
628 rc = IOServiceAddMatchingNotification(pNotify->NotifyPort,
629 kIOMatchedNotification,
630 IOServiceMatching(kIOUSBDeviceClassName),
631 darwinUSBAttachNotification2,
632 pNotify,
633 &pNotify->AttachIterator2);
634 if (rc == KERN_SUCCESS)
635 {
636 darwinDrainIterator(pNotify->AttachIterator2);
637 rc = IOServiceAddMatchingNotification(pNotify->NotifyPort,
638 kIOTerminatedNotification,
639 IOServiceMatching(kIOUSBDeviceClassName),
640 darwinUSBDetachNotification,
641 pNotify,
642 &pNotify->DetachIterator);
643 {
644 darwinDrainIterator(pNotify->DetachIterator);
645 return pNotify;
646 }
647 IOObjectRelease(pNotify->AttachIterator2);
648 }
649 IOObjectRelease(pNotify->AttachIterator);
650 }
651 CFRunLoopRemoveSource(RunLoopRef, pNotify->NotifyRLSrc, CFSTR(VBOX_IOKIT_MODE_STRING));
652 }
653 IONotificationPortDestroy(pNotify->NotifyPort);
654 }
655
656 RTMemFree(pNotify);
657 return NULL;
658}
659
660
661/**
662 * Unsubscribe the run loop from USB notification subscribed to
663 * by DarwinSubscribeUSBNotifications.
664 *
665 * @param pvOpaque The return value from DarwinSubscribeUSBNotifications.
666 */
667void DarwinUnsubscribeUSBNotifications(void *pvOpaque)
668{
669 PDARWINUSBNOTIFY pNotify = (PDARWINUSBNOTIFY)pvOpaque;
670 if (!pNotify)
671 return;
672
673 IOObjectRelease(pNotify->AttachIterator);
674 pNotify->AttachIterator = NULL;
675 IOObjectRelease(pNotify->AttachIterator2);
676 pNotify->AttachIterator2 = NULL;
677 IOObjectRelease(pNotify->DetachIterator);
678 pNotify->DetachIterator = NULL;
679
680 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), pNotify->NotifyRLSrc, CFSTR(VBOX_IOKIT_MODE_STRING));
681 IONotificationPortDestroy(pNotify->NotifyPort);
682 pNotify->NotifyRLSrc = NULL;
683 pNotify->NotifyPort = NULL;
684
685 RTMemFree(pNotify);
686}
687
688
689/**
690 * Descends recursively into a IORegistry tree locating the first object of a given class.
691 *
692 * The search is performed depth first.
693 *
694 * @returns Object reference if found, NULL if not.
695 * @param Object The current tree root.
696 * @param pszClass The name of the class we're looking for.
697 * @param pszNameBuf A scratch buffer for query the class name in to avoid
698 * wasting 128 bytes on an io_name_t object for every recursion.
699 */
700static io_object_t darwinFindObjectByClass(io_object_t Object, const char *pszClass, io_name_t pszNameBuf)
701{
702 io_iterator_t Children;
703 kern_return_t krc = IORegistryEntryGetChildIterator(Object, kIOServicePlane, &Children);
704 if (krc != KERN_SUCCESS)
705 return NULL;
706 io_object_t Child;
707 while ((Child = IOIteratorNext(Children)))
708 {
709 krc = IOObjectGetClass(Child, pszNameBuf);
710 if ( krc == KERN_SUCCESS
711 && !strcmp(pszNameBuf, pszClass))
712 break;
713
714 io_object_t GrandChild = darwinFindObjectByClass(Child, pszClass, pszNameBuf);
715 IOObjectRelease(Child);
716 if (GrandChild)
717 {
718 Child = GrandChild;
719 break;
720 }
721 }
722 IOObjectRelease(Children);
723 return Child;
724}
725
726
727/**
728 * Descends recursively into IOUSBMassStorageClass tree to check whether
729 * the MSD is mounted or not.
730 *
731 * The current heuristic is to look for the IOMedia class.
732 *
733 * @returns true if mounted, false if not.
734 * @param MSDObj The IOUSBMassStorageClass object.
735 * @param pszNameBuf A scratch buffer for query the class name in to avoid
736 * wasting 128 bytes on an io_name_t object for every recursion.
737 */
738static bool darwinIsMassStorageInterfaceInUse(io_object_t MSDObj, io_name_t pszNameBuf)
739{
740 io_object_t MediaObj = darwinFindObjectByClass(MSDObj, kIOMediaClass, pszNameBuf);
741 if (MediaObj)
742 {
743 CFMutableDictionaryRef pProperties;
744 kern_return_t krc;
745 bool fInUse = true;
746
747 krc = IORegistryEntryCreateCFProperties(MediaObj, &pProperties, kCFAllocatorDefault, kNilOptions);
748 if (krc == KERN_SUCCESS)
749 {
750 CFBooleanRef pBoolValue = (CFBooleanRef)CFDictionaryGetValue(pProperties, CFSTR(kIOMediaOpenKey));
751 if (pBoolValue)
752 fInUse = CFBooleanGetValue(pBoolValue);
753
754 CFRelease(pProperties);
755 }
756
757 /* more checks? */
758 IOObjectRelease(MediaObj);
759 return fInUse;
760 }
761
762 return false;
763}
764
765
766/**
767 * Worker function for DarwinGetUSBDevices() that tries to figure out
768 * what state the device is in and set enmState.
769 *
770 * This is mostly a matter of distinguishing between devices that nobody
771 * uses, devices that can be seized and devices that cannot be grabbed.
772 *
773 * @param pCur The USB device data.
774 * @param USBDevice The USB device object.
775 * @param PropsRef The USB device properties.
776 */
777static void darwinDeterminUSBDeviceState(PUSBDEVICE pCur, io_object_t USBDevice, CFMutableDictionaryRef /* PropsRef */)
778{
779 /*
780 * Iterate the interfaces (among the children of the IOUSBDevice object).
781 */
782 io_iterator_t Interfaces;
783 kern_return_t krc = IORegistryEntryGetChildIterator(USBDevice, kIOServicePlane, &Interfaces);
784 if (krc != KERN_SUCCESS)
785 return;
786
787 bool fHaveOwner = false;
788 RTPROCESS Owner = NIL_RTPROCESS;
789 bool fHaveClient = false;
790 RTPROCESS Client = NIL_RTPROCESS;
791 bool fUserClientOnly = true;
792 bool fConfigured = false;
793 bool fInUse = false;
794 bool fSeizable = true;
795 io_object_t Interface;
796 while ((Interface = IOIteratorNext(Interfaces)))
797 {
798 io_name_t szName;
799 krc = IOObjectGetClass(Interface, szName);
800 if ( krc == KERN_SUCCESS
801 && !strcmp(szName, "IOUSBInterface"))
802 {
803 fConfigured = true;
804
805 /*
806 * Iterate the interface children looking for stuff other than
807 * IOUSBUserClientInit objects.
808 */
809 io_iterator_t Children1;
810 krc = IORegistryEntryGetChildIterator(Interface, kIOServicePlane, &Children1);
811 if (krc == KERN_SUCCESS)
812 {
813 io_object_t Child1;
814 while ((Child1 = IOIteratorNext(Children1)))
815 {
816 krc = IOObjectGetClass(Child1, szName);
817 if ( krc == KERN_SUCCESS
818 && strcmp(szName, "IOUSBUserClientInit"))
819 {
820 fUserClientOnly = false;
821
822 if (!strcmp(szName, "IOUSBMassStorageClass"))
823 {
824 /* Only permit capturing MSDs that aren't mounted, at least
825 until the GUI starts poping up warnings about data loss
826 and such when capturing a busy device. */
827 fSeizable = false;
828 fInUse |= darwinIsMassStorageInterfaceInUse(Child1, szName);
829 }
830 else if (!strcmp(szName, "IOUSBHIDDriver")
831 || !strcmp(szName, "AppleHIDMouse")
832 /** @todo more? */)
833 {
834 /* For now, just assume that all HID devices are inaccessible
835 because of the greedy HID service. */
836 fSeizable = false;
837 fInUse = true;
838 }
839 else
840 fInUse = true;
841 }
842 IOObjectRelease(Child1);
843 }
844 IOObjectRelease(Children1);
845 }
846 }
847 /*
848 * Not an interface, could it be VBoxUSBDevice?
849 * If it is, get the owner and client properties.
850 */
851 else if ( krc == KERN_SUCCESS
852 && !strcmp(szName, VBOXUSBDEVICE_CLASS_NAME))
853 {
854 CFMutableDictionaryRef PropsRef = 0;
855 krc = IORegistryEntryCreateCFProperties(Interface, &PropsRef, kCFAllocatorDefault, kNilOptions);
856 if (krc == KERN_SUCCESS)
857 {
858 fHaveOwner = darwinDictGetProcess(PropsRef, CFSTR(VBOXUSB_OWNER_KEY), &Owner);
859 fHaveClient = darwinDictGetProcess(PropsRef, CFSTR(VBOXUSB_CLIENT_KEY), &Client);
860 CFRelease(PropsRef);
861 }
862 }
863
864 IOObjectRelease(Interface);
865 }
866 IOObjectRelease(Interfaces);
867
868 /*
869 * Calc the status.
870 */
871 if (fHaveOwner)
872 {
873 if (Owner == RTProcSelf())
874 pCur->enmState = !fHaveClient || Client == NIL_RTPROCESS || !Client
875 ? USBDEVICESTATE_HELD_BY_PROXY
876 : USBDEVICESTATE_USED_BY_GUEST;
877 else
878 pCur->enmState = USBDEVICESTATE_USED_BY_HOST;
879 }
880 else if (fUserClientOnly)
881 /** @todo how to detect other user client?!? - Look for IOUSBUserClient! */
882 pCur->enmState = !fConfigured
883 ? USBDEVICESTATE_UNUSED
884 : USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
885 else if (!fInUse)
886 pCur->enmState = USBDEVICESTATE_UNUSED;
887 else
888 pCur->enmState = fSeizable
889 ? USBDEVICESTATE_USED_BY_HOST_CAPTURABLE
890 : USBDEVICESTATE_USED_BY_HOST;
891}
892
893
894/**
895 * Enumerate the USB devices returning a FIFO of them.
896 *
897 * @returns Pointer to the head.
898 * USBProxyService::freeDevice is expected to free each of the list elements.
899 */
900PUSBDEVICE DarwinGetUSBDevices(void)
901{
902 AssertReturn(darwinOpenMasterPort(), NULL);
903 //DARWIN_IOKIT_LOG(("DarwinGetUSBDevices\n"));
904
905 /*
906 * Create a matching dictionary for searching for USB Devices in the IOKit.
907 */
908 CFMutableDictionaryRef RefMatchingDict = IOServiceMatching(kIOUSBDeviceClassName);
909 AssertReturn(RefMatchingDict, NULL);
910
911 /*
912 * Perform the search and get a collection of USB Device back.
913 */
914 io_iterator_t USBDevices = NULL;
915 IOReturn rc = IOServiceGetMatchingServices(g_MasterPort, RefMatchingDict, &USBDevices);
916 AssertMsgReturn(rc == kIOReturnSuccess, ("rc=%d\n", rc), NULL);
917 RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
918
919 /*
920 * Enumerate the USB Devices.
921 */
922 PUSBDEVICE pHead = NULL;
923 PUSBDEVICE pTail = NULL;
924 unsigned i = 0;
925 io_object_t USBDevice;
926 while ((USBDevice = IOIteratorNext(USBDevices)) != 0)
927 {
928 DARWIN_IOKIT_DUMP_OBJ(USBDevice);
929
930 /*
931 * Query the device properties from the registry.
932 *
933 * We could alternatively use the device and such, but that will be
934 * slower and we would have to resort to the registry for the three
935 * string anyway.
936 */
937 CFMutableDictionaryRef PropsRef = 0;
938 kern_return_t krc = IORegistryEntryCreateCFProperties(USBDevice, &PropsRef, kCFAllocatorDefault, kNilOptions);
939 if (krc == KERN_SUCCESS)
940 {
941 bool fOk = false;
942 PUSBDEVICE pCur = (PUSBDEVICE)RTMemAllocZ(sizeof(*pCur));
943 do /* loop for breaking out of on failure. */
944 {
945 AssertBreak(pCur);
946
947 /*
948 * Mandatory
949 */
950 pCur->bcdUSB = 0; /* we've no idea. */
951 pCur->enmState = USBDEVICESTATE_USED_BY_HOST_CAPTURABLE; /* just a default, we'll try harder in a bit. */
952
953 AssertBreak(darwinDictGetU8(PropsRef, CFSTR(kUSBDeviceClass), &pCur->bDeviceClass));
954 /* skip hubs */
955 if (pCur->bDeviceClass == 0x09 /* hub, find a define! */)
956 break;
957 AssertBreak(darwinDictGetU8(PropsRef, CFSTR(kUSBDeviceSubClass), &pCur->bDeviceSubClass));
958 AssertBreak(darwinDictGetU8(PropsRef, CFSTR(kUSBDeviceProtocol), &pCur->bDeviceProtocol));
959 AssertBreak(darwinDictGetU16(PropsRef, CFSTR(kUSBVendorID), &pCur->idVendor));
960 AssertBreak(darwinDictGetU16(PropsRef, CFSTR(kUSBProductID), &pCur->idProduct));
961 AssertBreak(darwinDictGetU16(PropsRef, CFSTR(kUSBDeviceReleaseNumber), &pCur->bcdDevice));
962 uint32_t u32LocationId;
963 AssertBreak(darwinDictGetU32(PropsRef, CFSTR(kUSBDevicePropertyLocationID), &u32LocationId));
964 uint64_t u64SessionId;
965 AssertBreak(darwinDictGetU64(PropsRef, CFSTR("sessionID"), &u64SessionId));
966 char szAddress[64];
967 RTStrPrintf(szAddress, sizeof(szAddress), "p=0x%04RX16;v=0x%04RX16;s=0x%016RX64;l=0x%08RX32",
968 pCur->idProduct, pCur->idVendor, u64SessionId, u32LocationId);
969 pCur->pszAddress = RTStrDup(szAddress);
970 AssertBreak(pCur->pszAddress);
971 pCur->bBus = u32LocationId >> 24;
972 AssertBreak(darwinDictGetU8(PropsRef, CFSTR("PortNum"), &pCur->bPort));
973 uint8_t bSpeed;
974 AssertBreak(darwinDictGetU8(PropsRef, CFSTR(kUSBDevicePropertySpeed), &bSpeed));
975 Assert(bSpeed <= 3);
976 pCur->enmSpeed = bSpeed == 3 ? USBDEVICESPEED_SUPER
977 : bSpeed == 2 ? USBDEVICESPEED_HIGH
978 : bSpeed == 1 ? USBDEVICESPEED_FULL
979 : bSpeed == 0 ? USBDEVICESPEED_LOW
980 : USBDEVICESPEED_UNKNOWN;
981
982 /*
983 * Optional.
984 * There are some nameless device in the iMac, apply names to them.
985 */
986 darwinDictDupString(PropsRef, CFSTR("USB Vendor Name"), (char **)&pCur->pszManufacturer);
987 if ( !pCur->pszManufacturer
988 && pCur->idVendor == kIOUSBVendorIDAppleComputer)
989 pCur->pszManufacturer = RTStrDup("Apple Computer, Inc.");
990 darwinDictDupString(PropsRef, CFSTR("USB Product Name"), (char **)&pCur->pszProduct);
991 if ( !pCur->pszProduct
992 && pCur->bDeviceClass == 224 /* Wireless */
993 && pCur->bDeviceSubClass == 1 /* Radio Frequency */
994 && pCur->bDeviceProtocol == 1 /* Bluetooth */)
995 pCur->pszProduct = RTStrDup("Bluetooth");
996 darwinDictDupString(PropsRef, CFSTR("USB Serial Number"), (char **)&pCur->pszSerialNumber);
997
998#if 0 /* leave the remainder as zero for now. */
999 /*
1000 * Create a plugin interface for the service and query its USB Device interface.
1001 */
1002 SInt32 Score = 0;
1003 IOCFPlugInInterface **ppPlugInInterface = NULL;
1004 rc = IOCreatePlugInInterfaceForService(USBDevice, kIOUSBDeviceUserClientTypeID,
1005 kIOCFPlugInInterfaceID, &ppPlugInInterface, &Score);
1006 if (rc == kIOReturnSuccess)
1007 {
1008 IOUSBDeviceInterface245 **ppUSBDevI = NULL;
1009 HRESULT hrc = (*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
1010 CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID245),
1011 (LPVOID *)&ppUSBDevI);
1012 rc = IODestroyPlugInInterface(ppPlugInInterface); Assert(rc == kIOReturnSuccess);
1013 ppPlugInInterface = NULL;
1014 if (hrc == S_OK)
1015 {
1016 /** @todo enumerate configurations and interfaces if we actually need them. */
1017 //IOReturn (*GetNumberOfConfigurations)(void *self, UInt8 *numConfig);
1018 //IOReturn (*GetConfigurationDescriptorPtr)(void *self, UInt8 configIndex, IOUSBConfigurationDescriptorPtr *desc);
1019 //IOReturn (*CreateInterfaceIterator)(void *self, IOUSBFindInterfaceRequest *req, io_iterator_t *iter);
1020 }
1021 long cReft = (*ppUSBDeviceInterface)->Release(ppUSBDeviceInterface); MY_CHECK_CREFS(cRefs);
1022 }
1023#endif
1024 /*
1025 * Try determine the state.
1026 */
1027 darwinDeterminUSBDeviceState(pCur, USBDevice, PropsRef);
1028
1029 /*
1030 * We're good. Link the device.
1031 */
1032 pCur->pPrev = pTail;
1033 if (pTail)
1034 pTail = pTail->pNext = pCur;
1035 else
1036 pTail = pHead = pCur;
1037 fOk = true;
1038 } while (0);
1039
1040 /* cleanup on failure / skipped device. */
1041 if (!fOk && pCur)
1042 DarwinFreeUSBDeviceFromIOKit(pCur);
1043
1044 CFRelease(PropsRef);
1045 }
1046 else
1047 AssertMsgFailed(("krc=%#x\n", krc));
1048
1049 IOObjectRelease(USBDevice);
1050 i++;
1051 }
1052
1053 IOObjectRelease(USBDevices);
1054 //DARWIN_IOKIT_LOG_FLUSH();
1055
1056 /*
1057 * Some post processing. There are a couple of things we have to
1058 * make 100% sure about, and that is that the (Apple) keyboard
1059 * and mouse most likely to be in use by the user aren't available
1060 * for capturing. If there is no Apple mouse or keyboard we'll
1061 * take the first one from another vendor.
1062 */
1063 /* As it turns out, the HID service will take all keyboards and mice
1064 and we're not currently able to seize them. */
1065 PUSBDEVICE pMouse = NULL;
1066 PUSBDEVICE pKeyboard = NULL;
1067 for (PUSBDEVICE pCur = pHead; pCur; pCur = pCur->pNext)
1068 if (pCur->idVendor == kIOUSBVendorIDAppleComputer)
1069 {
1070 /*
1071 * This test is a bit rough, should check device class/protocol but
1072 * we don't have interface info yet so that might be a bit tricky.
1073 */
1074 if ( ( !pKeyboard
1075 || pKeyboard->idVendor != kIOUSBVendorIDAppleComputer)
1076 && pCur->pszProduct
1077 && strstr(pCur->pszProduct, " Keyboard"))
1078 pKeyboard = pCur;
1079 else if ( ( !pMouse
1080 || pMouse->idVendor != kIOUSBVendorIDAppleComputer)
1081 && pCur->pszProduct
1082 && strstr(pCur->pszProduct, " Mouse")
1083 )
1084 pMouse = pCur;
1085 }
1086 else if (!pKeyboard || !pMouse)
1087 {
1088 if ( pCur->bDeviceClass == 3 /* HID */
1089 && pCur->bDeviceProtocol == 1 /* Keyboard */)
1090 pKeyboard = pCur;
1091 else if ( pCur->bDeviceClass == 3 /* HID */
1092 && pCur->bDeviceProtocol == 2 /* Mouse */)
1093 pMouse = pCur;
1094 /** @todo examin interfaces */
1095 }
1096
1097 if (pKeyboard)
1098 pKeyboard->enmState = USBDEVICESTATE_USED_BY_HOST;
1099 if (pMouse)
1100 pMouse->enmState = USBDEVICESTATE_USED_BY_HOST;
1101
1102 return pHead;
1103}
1104
1105
1106/**
1107 * Triggers re-enumeration of a device.
1108 *
1109 * @returns VBox status code.
1110 * @param pCur The USBDEVICE structure for the device.
1111 */
1112int DarwinReEnumerateUSBDevice(PCUSBDEVICE pCur)
1113{
1114 int vrc;
1115 const char *pszAddress = pCur->pszAddress;
1116 AssertPtrReturn(pszAddress, VERR_INVALID_POINTER);
1117 AssertReturn(darwinOpenMasterPort(), VERR_GENERAL_FAILURE);
1118
1119 /*
1120 * This code is a short version of the Open method in USBProxyDevice-darwin.cpp stuff.
1121 * Fixes made to this code probably applies there too!
1122 */
1123
1124 CFMutableDictionaryRef RefMatchingDict = IOServiceMatching(kIOUSBDeviceClassName);
1125 AssertReturn(RefMatchingDict, NULL);
1126
1127 uint64_t u64SessionId = 0;
1128 uint32_t u32LocationId = 0;
1129 const char *psz = pszAddress;
1130 do
1131 {
1132 const char chValue = *psz;
1133 AssertReleaseReturn(psz[1] == '=', VERR_INTERNAL_ERROR);
1134 uint64_t u64Value;
1135 int rc = RTStrToUInt64Ex(psz + 2, (char **)&psz, 0, &u64Value);
1136 AssertReleaseRCReturn(rc, rc);
1137 AssertReleaseReturn(!*psz || *psz == ';', rc);
1138 switch (chValue)
1139 {
1140 case 'l':
1141 u32LocationId = (uint32_t)u64Value;
1142 break;
1143 case 's':
1144 u64SessionId = u64Value;
1145 break;
1146 case 'p':
1147 case 'v':
1148 {
1149#if 0 /* Guess what, this doesn't 'ing work either! */
1150 SInt32 i32 = (int16_t)u64Value;
1151 CFNumberRef Num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i32);
1152 AssertBreak(Num);
1153 CFDictionarySetValue(RefMatchingDict, chValue == 'p' ? CFSTR(kUSBProductID) : CFSTR(kUSBVendorID), Num);
1154 CFRelease(Num);
1155#endif
1156 break;
1157 }
1158 default:
1159 AssertReleaseMsgFailedReturn(("chValue=%#x\n", chValue), VERR_INTERNAL_ERROR);
1160 }
1161 if (*psz == ';')
1162 psz++;
1163 } while (*psz);
1164
1165 io_iterator_t USBDevices = NULL;
1166 IOReturn irc = IOServiceGetMatchingServices(g_MasterPort, RefMatchingDict, &USBDevices);
1167 AssertMsgReturn(irc == kIOReturnSuccess, ("irc=%#x\n", irc), NULL);
1168 RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
1169
1170 unsigned cMatches = 0;
1171 io_object_t USBDevice;
1172 while ((USBDevice = IOIteratorNext(USBDevices)))
1173 {
1174 cMatches++;
1175 CFMutableDictionaryRef PropsRef = 0;
1176 kern_return_t krc = IORegistryEntryCreateCFProperties(USBDevice, &PropsRef, kCFAllocatorDefault, kNilOptions);
1177 if (krc == KERN_SUCCESS)
1178 {
1179 uint64_t u64CurSessionId;
1180 uint32_t u32CurLocationId;
1181 if ( ( !u64SessionId
1182 || ( darwinDictGetU64(PropsRef, CFSTR("sessionID"), &u64CurSessionId)
1183 && u64CurSessionId == u64SessionId))
1184 && ( !u32LocationId
1185 || ( darwinDictGetU32(PropsRef, CFSTR(kUSBDevicePropertyLocationID), &u32CurLocationId)
1186 && u32CurLocationId == u32LocationId))
1187 )
1188 {
1189 CFRelease(PropsRef);
1190 break;
1191 }
1192 CFRelease(PropsRef);
1193 }
1194 IOObjectRelease(USBDevice);
1195 }
1196 IOObjectRelease(USBDevices);
1197 USBDevices = NULL;
1198 if (!USBDevice)
1199 {
1200 LogRel(("USB: Device '%s' not found (%d pid+vid matches)\n", pszAddress, cMatches));
1201 IOObjectRelease(USBDevices);
1202 return VERR_VUSB_DEVICE_NAME_NOT_FOUND;
1203 }
1204
1205 /*
1206 * Create a plugin interface for the device and query its IOUSBDeviceInterface.
1207 */
1208 SInt32 Score = 0;
1209 IOCFPlugInInterface **ppPlugInInterface = NULL;
1210 irc = IOCreatePlugInInterfaceForService(USBDevice, kIOUSBDeviceUserClientTypeID,
1211 kIOCFPlugInInterfaceID, &ppPlugInInterface, &Score);
1212 if (irc == kIOReturnSuccess)
1213 {
1214 IOUSBDeviceInterface245 **ppDevI = NULL;
1215 HRESULT hrc = (*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
1216 CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID245),
1217 (LPVOID *)&ppDevI);
1218 irc = IODestroyPlugInInterface(ppPlugInInterface); Assert(irc == kIOReturnSuccess);
1219 ppPlugInInterface = NULL;
1220 if (hrc == S_OK)
1221 {
1222 /*
1223 * Try open the device for exclusive access.
1224 */
1225 irc = (*ppDevI)->USBDeviceOpenSeize(ppDevI);
1226 if (irc == kIOReturnExclusiveAccess)
1227 {
1228 RTThreadSleep(20);
1229 irc = (*ppDevI)->USBDeviceOpenSeize(ppDevI);
1230 }
1231 if (irc == kIOReturnSuccess)
1232 {
1233 /*
1234 * Re-enumerate the device and bail out.
1235 */
1236 irc = (*ppDevI)->USBDeviceReEnumerate(ppDevI, 0);
1237 if (irc == kIOReturnSuccess)
1238 vrc = VINF_SUCCESS;
1239 else
1240 {
1241 LogRel(("USB: Failed to open device '%s', plug-in creation failed with irc=%#x.\n", pszAddress, irc));
1242 vrc = RTErrConvertFromDarwinIO(irc);
1243 }
1244
1245 (*ppDevI)->USBDeviceClose(ppDevI);
1246 }
1247 else if (irc == kIOReturnExclusiveAccess)
1248 {
1249 LogRel(("USB: Device '%s' is being used by another process\n", pszAddress));
1250 vrc = VERR_SHARING_VIOLATION;
1251 }
1252 else
1253 {
1254 LogRel(("USB: Failed to open device '%s', irc=%#x.\n", pszAddress, irc));
1255 vrc = VERR_OPEN_FAILED;
1256 }
1257 }
1258 else
1259 {
1260 LogRel(("USB: Failed to create plugin interface for device '%s', hrc=%#x.\n", pszAddress, hrc));
1261 vrc = VERR_OPEN_FAILED;
1262 }
1263
1264 (*ppDevI)->Release(ppDevI);
1265 }
1266 else
1267 {
1268 LogRel(("USB: Failed to open device '%s', plug-in creation failed with irc=%#x.\n", pszAddress, irc));
1269 vrc = RTErrConvertFromDarwinIO(irc);
1270 }
1271
1272 return vrc;
1273}
1274
1275#endif /* VBOX_WITH_USB */
1276
1277
1278/**
1279 * Enumerate the CD, DVD and BlueRay drives returning a FIFO of device name strings.
1280 *
1281 * @returns Pointer to the head.
1282 * The caller is responsible for calling RTMemFree() on each of the nodes.
1283 */
1284PDARWINDVD DarwinGetDVDDrives(void)
1285{
1286 AssertReturn(darwinOpenMasterPort(), NULL);
1287
1288 /*
1289 * Create a matching dictionary for searching for CD, DVD and BlueRay services in the IOKit.
1290 *
1291 * The idea is to find all the devices which are of class IOCDBlockStorageDevice.
1292 * CD devices are represented by IOCDBlockStorageDevice class itself, while DVD and BlueRay ones
1293 * have it as a parent class.
1294 */
1295 CFMutableDictionaryRef RefMatchingDict = IOServiceMatching("IOCDBlockStorageDevice");
1296 AssertReturn(RefMatchingDict, NULL);
1297
1298 /*
1299 * Perform the search and get a collection of DVD services.
1300 */
1301 io_iterator_t DVDServices = NULL;
1302 IOReturn rc = IOServiceGetMatchingServices(g_MasterPort, RefMatchingDict, &DVDServices);
1303 AssertMsgReturn(rc == kIOReturnSuccess, ("rc=%d\n", rc), NULL);
1304 RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
1305
1306 /*
1307 * Enumerate the matching services.
1308 * (This enumeration must be identical to the one performed in DrvHostBase.cpp.)
1309 */
1310 PDARWINDVD pHead = NULL;
1311 PDARWINDVD pTail = NULL;
1312 unsigned i = 0;
1313 io_object_t DVDService;
1314 while ((DVDService = IOIteratorNext(DVDServices)) != 0)
1315 {
1316 DARWIN_IOKIT_DUMP_OBJ(DVDService);
1317
1318 /*
1319 * Get the properties we use to identify the DVD drive.
1320 *
1321 * While there is a (weird 12 byte) GUID, it isn't persistent
1322 * across boots. So, we have to use a combination of the
1323 * vendor name and product name properties with an optional
1324 * sequence number for identification.
1325 */
1326 CFMutableDictionaryRef PropsRef = 0;
1327 kern_return_t krc = IORegistryEntryCreateCFProperties(DVDService, &PropsRef, kCFAllocatorDefault, kNilOptions);
1328 if (krc == KERN_SUCCESS)
1329 {
1330 /* Get the Device Characteristics dictionary. */
1331 CFDictionaryRef DevCharRef = (CFDictionaryRef)CFDictionaryGetValue(PropsRef, CFSTR(kIOPropertyDeviceCharacteristicsKey));
1332 if (DevCharRef)
1333 {
1334 /* The vendor name. */
1335 char szVendor[128];
1336 char *pszVendor = &szVendor[0];
1337 CFTypeRef ValueRef = CFDictionaryGetValue(DevCharRef, CFSTR(kIOPropertyVendorNameKey));
1338 if ( ValueRef
1339 && CFGetTypeID(ValueRef) == CFStringGetTypeID()
1340 && CFStringGetCString((CFStringRef)ValueRef, szVendor, sizeof(szVendor), kCFStringEncodingUTF8))
1341 pszVendor = RTStrStrip(szVendor);
1342 else
1343 *pszVendor = '\0';
1344
1345 /* The product name. */
1346 char szProduct[128];
1347 char *pszProduct = &szProduct[0];
1348 ValueRef = CFDictionaryGetValue(DevCharRef, CFSTR(kIOPropertyProductNameKey));
1349 if ( ValueRef
1350 && CFGetTypeID(ValueRef) == CFStringGetTypeID()
1351 && CFStringGetCString((CFStringRef)ValueRef, szProduct, sizeof(szProduct), kCFStringEncodingUTF8))
1352 pszProduct = RTStrStrip(szProduct);
1353 else
1354 *pszProduct = '\0';
1355
1356 /* Construct the name and check for duplicates. */
1357 char szName[256 + 32];
1358 if (*pszVendor || *pszProduct)
1359 {
1360 if (*pszVendor && *pszProduct)
1361 RTStrPrintf(szName, sizeof(szName), "%s %s", pszVendor, pszProduct);
1362 else
1363 strcpy(szName, *pszVendor ? pszVendor : pszProduct);
1364
1365 for (PDARWINDVD pCur = pHead; pCur; pCur = pCur->pNext)
1366 {
1367 if (!strcmp(szName, pCur->szName))
1368 {
1369 if (*pszVendor && *pszProduct)
1370 RTStrPrintf(szName, sizeof(szName), "%s %s (#%u)", pszVendor, pszProduct, i);
1371 else
1372 RTStrPrintf(szName, sizeof(szName), "%s (#%u)", *pszVendor ? pszVendor : pszProduct, i);
1373 break;
1374 }
1375 }
1376 }
1377 else
1378 RTStrPrintf(szName, sizeof(szName), "(#%u)", i);
1379
1380 /* Create the device. */
1381 size_t cbName = strlen(szName) + 1;
1382 PDARWINDVD pNew = (PDARWINDVD)RTMemAlloc(RT_OFFSETOF(DARWINDVD, szName[cbName]));
1383 if (pNew)
1384 {
1385 pNew->pNext = NULL;
1386 memcpy(pNew->szName, szName, cbName);
1387 if (pTail)
1388 pTail = pTail->pNext = pNew;
1389 else
1390 pTail = pHead = pNew;
1391 }
1392 }
1393 CFRelease(PropsRef);
1394 }
1395 else
1396 AssertMsgFailed(("krc=%#x\n", krc));
1397
1398 IOObjectRelease(DVDService);
1399 i++;
1400 }
1401
1402 IOObjectRelease(DVDServices);
1403
1404 return pHead;
1405}
1406
1407
1408/**
1409 * Enumerate the ethernet capable network devices returning a FIFO of them.
1410 *
1411 * @returns Pointer to the head.
1412 */
1413PDARWINETHERNIC DarwinGetEthernetControllers(void)
1414{
1415 AssertReturn(darwinOpenMasterPort(), NULL);
1416
1417 /*
1418 * Create a matching dictionary for searching for ethernet controller
1419 * services in the IOKit.
1420 *
1421 * For some really stupid reason I don't get all the controllers if I look for
1422 * objects that are instances of IOEthernetController or its descendants (only
1423 * get the AirPort on my mac pro). But fortunately using IOEthernetInterface
1424 * seems to work. Weird s**t!
1425 */
1426 //CFMutableDictionaryRef RefMatchingDict = IOServiceMatching("IOEthernetController"); - this doesn't work :-(
1427 CFMutableDictionaryRef RefMatchingDict = IOServiceMatching("IOEthernetInterface");
1428 AssertReturn(RefMatchingDict, NULL);
1429
1430 /*
1431 * Perform the search and get a collection of ethernet controller services.
1432 */
1433 io_iterator_t EtherIfServices = NULL;
1434 IOReturn rc = IOServiceGetMatchingServices(g_MasterPort, RefMatchingDict, &EtherIfServices);
1435 AssertMsgReturn(rc == kIOReturnSuccess, ("rc=%d\n", rc), NULL);
1436 RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
1437
1438 /*
1439 * Get a copy of the current network interfaces from the system configuration service.
1440 * We'll use this for looking up the proper interface names.
1441 */
1442 CFArrayRef IfsRef = SCNetworkInterfaceCopyAll();
1443 CFIndex cIfs = IfsRef ? CFArrayGetCount(IfsRef) : 0;
1444
1445 /*
1446 * Get the current preferences and make a copy of the network services so we
1447 * can look up the right interface names. The IfsRef is just for fallback.
1448 */
1449 CFArrayRef ServicesRef = NULL;
1450 CFIndex cServices = 0;
1451 SCPreferencesRef PrefsRef = SCPreferencesCreate(kCFAllocatorDefault, CFSTR("org.virtualbox.VBoxSVC"), NULL);
1452 if (PrefsRef)
1453 {
1454 SCNetworkSetRef SetRef = SCNetworkSetCopyCurrent(PrefsRef);
1455 CFRelease(PrefsRef);
1456 if (SetRef)
1457 {
1458 ServicesRef = SCNetworkSetCopyServices(SetRef);
1459 CFRelease(SetRef);
1460 cServices = ServicesRef ? CFArrayGetCount(ServicesRef) : 0;
1461 }
1462 }
1463
1464 /*
1465 * Enumerate the ethernet controller services.
1466 */
1467 PDARWINETHERNIC pHead = NULL;
1468 PDARWINETHERNIC pTail = NULL;
1469 io_object_t EtherIfService;
1470 while ((EtherIfService = IOIteratorNext(EtherIfServices)) != 0)
1471 {
1472 /*
1473 * Dig up the parent, meaning the IOEthernetController.
1474 */
1475 io_object_t EtherNICService;
1476 kern_return_t krc = IORegistryEntryGetParentEntry(EtherIfService, kIOServicePlane, &EtherNICService);
1477 /*krc = IORegistryEntryGetChildEntry(EtherNICService, kIOServicePlane, &EtherIfService); */
1478 if (krc == KERN_SUCCESS)
1479 {
1480 DARWIN_IOKIT_DUMP_OBJ(EtherNICService);
1481 /*
1482 * Get the properties we use to identify and name the Ethernet NIC.
1483 * We need the both the IOEthernetController and it's IONetworkInterface child.
1484 */
1485 CFMutableDictionaryRef PropsRef = 0;
1486 krc = IORegistryEntryCreateCFProperties(EtherNICService, &PropsRef, kCFAllocatorDefault, kNilOptions);
1487 if (krc == KERN_SUCCESS)
1488 {
1489 CFMutableDictionaryRef IfPropsRef = 0;
1490 krc = IORegistryEntryCreateCFProperties(EtherIfService, &IfPropsRef, kCFAllocatorDefault, kNilOptions);
1491 if (krc == KERN_SUCCESS)
1492 {
1493 /*
1494 * Gather the required data.
1495 * We'll create a UUID from the MAC address and the BSD name.
1496 */
1497 char szTmp[256];
1498 do
1499 {
1500 /* Check if airport (a bit heuristical - it's com.apple.driver.AirPortBrcm43xx here). */
1501 darwinDictGetString(PropsRef, CFSTR("CFBundleIdentifier"), szTmp, sizeof(szTmp));
1502 bool fWireless;
1503 bool fAirPort = fWireless = strstr(szTmp, ".AirPort") != NULL;
1504
1505 /* Check if it's USB. */
1506 darwinDictGetString(PropsRef, CFSTR("IOProviderClass"), szTmp, sizeof(szTmp));
1507 bool fUSB = strstr(szTmp, "USB") != NULL;
1508
1509
1510 /* Is it builtin? */
1511 bool fBuiltin;
1512 darwinDictGetBool(IfPropsRef, CFSTR("IOBuiltin"), &fBuiltin);
1513
1514 /* Is it the primary interface */
1515 bool fPrimaryIf;
1516 darwinDictGetBool(IfPropsRef, CFSTR("IOPrimaryInterface"), &fPrimaryIf);
1517
1518 /* Get the MAC address. */
1519 RTMAC Mac;
1520 AssertBreak(darwinDictGetData(PropsRef, CFSTR("IOMACAddress"), &Mac, sizeof(Mac)));
1521
1522 /* The BSD Name from the interface dictionary. */
1523 char szBSDName[RT_SIZEOFMEMB(DARWINETHERNIC, szBSDName)];
1524 AssertBreak(darwinDictGetString(IfPropsRef, CFSTR("BSD Name"), szBSDName, sizeof(szBSDName)));
1525
1526 /* Check if it's really wireless. */
1527 if ( darwinDictIsPresent(IfPropsRef, CFSTR("IO80211CountryCode"))
1528 || darwinDictIsPresent(IfPropsRef, CFSTR("IO80211DriverVersion"))
1529 || darwinDictIsPresent(IfPropsRef, CFSTR("IO80211HardwareVersion"))
1530 || darwinDictIsPresent(IfPropsRef, CFSTR("IO80211Locale")))
1531 fWireless = true;
1532 else
1533 fAirPort = fWireless = false;
1534
1535 /** @todo IOPacketFilters / IONetworkFilterGroup? */
1536 /*
1537 * Create the interface name.
1538 *
1539 * Note! The ConsoleImpl2.cpp code ASSUMES things about the name. It is also
1540 * stored in the VM config files. (really bright idea)
1541 */
1542 strcpy(szTmp, szBSDName);
1543 char *psz = strchr(szTmp, '\0');
1544 *psz++ = ':';
1545 *psz++ = ' ';
1546 size_t cchLeft = sizeof(szTmp) - (psz - &szTmp[0]) - (sizeof(" (Wireless)") - 1);
1547 bool fFound = false;
1548 CFIndex i;
1549
1550 /* look it up among the current services */
1551 for (i = 0; i < cServices; i++)
1552 {
1553 SCNetworkServiceRef ServiceRef = (SCNetworkServiceRef)CFArrayGetValueAtIndex(ServicesRef, i);
1554 SCNetworkInterfaceRef IfRef = SCNetworkServiceGetInterface(ServiceRef);
1555 if (IfRef)
1556 {
1557 CFStringRef BSDNameRef = SCNetworkInterfaceGetBSDName(IfRef);
1558 if ( BSDNameRef
1559 && CFStringGetCString(BSDNameRef, psz, cchLeft, kCFStringEncodingUTF8)
1560 && !strcmp(psz, szBSDName))
1561 {
1562 CFStringRef ServiceNameRef = SCNetworkServiceGetName(ServiceRef);
1563 if ( ServiceNameRef
1564 && CFStringGetCString(ServiceNameRef, psz, cchLeft, kCFStringEncodingUTF8))
1565 {
1566 fFound = true;
1567 break;
1568 }
1569 }
1570 }
1571 }
1572 /* Look it up in the interface list. */
1573 if (!fFound)
1574 for (i = 0; i < cIfs; i++)
1575 {
1576 SCNetworkInterfaceRef IfRef = (SCNetworkInterfaceRef)CFArrayGetValueAtIndex(IfsRef, i);
1577 CFStringRef BSDNameRef = SCNetworkInterfaceGetBSDName(IfRef);
1578 if ( BSDNameRef
1579 && CFStringGetCString(BSDNameRef, psz, cchLeft, kCFStringEncodingUTF8)
1580 && !strcmp(psz, szBSDName))
1581 {
1582 CFStringRef DisplayNameRef = SCNetworkInterfaceGetLocalizedDisplayName(IfRef);
1583 if ( DisplayNameRef
1584 && CFStringGetCString(DisplayNameRef, psz, cchLeft, kCFStringEncodingUTF8))
1585 {
1586 fFound = true;
1587 break;
1588 }
1589 }
1590 }
1591 /* Generate a half plausible name if we for some silly reason didn't find the interface. */
1592 if (!fFound)
1593 RTStrPrintf(szTmp, sizeof(szTmp), "%s: %s%s(?)",
1594 szBSDName,
1595 fUSB ? "USB " : "",
1596 fWireless ? fAirPort ? "AirPort " : "Wireless" : "Ethernet");
1597 /* If we did find it and it's wireless but without "AirPort" or "Wireless", fix it */
1598 else if ( fWireless
1599 && !strstr(psz, "AirPort")
1600 && !strstr(psz, "Wireless"))
1601 strcat(szTmp, fAirPort ? " (AirPort)" : " (Wireless)");
1602
1603 /*
1604 * Create the list entry.
1605 */
1606 DARWIN_IOKIT_LOG(("Found: if=%s mac=%.6Rhxs fWireless=%RTbool fAirPort=%RTbool fBuiltin=%RTbool fPrimaryIf=%RTbool fUSB=%RTbool\n",
1607 szBSDName, &Mac, fWireless, fAirPort, fBuiltin, fPrimaryIf, fUSB));
1608
1609 size_t cchName = strlen(szTmp);
1610 PDARWINETHERNIC pNew = (PDARWINETHERNIC)RTMemAlloc(RT_OFFSETOF(DARWINETHERNIC, szName[cchName + 1]));
1611 if (pNew)
1612 {
1613 strncpy(pNew->szBSDName, szBSDName, sizeof(pNew->szBSDName)); /* the '\0' padding is intentional! */
1614
1615 RTUuidClear(&pNew->Uuid);
1616 memcpy(&pNew->Uuid, pNew->szBSDName, RT_MIN(sizeof(pNew->szBSDName), sizeof(pNew->Uuid)));
1617 pNew->Uuid.Gen.u8ClockSeqHiAndReserved = (pNew->Uuid.Gen.u8ClockSeqHiAndReserved & 0x3f) | 0x80;
1618 pNew->Uuid.Gen.u16TimeHiAndVersion = (pNew->Uuid.Gen.u16TimeHiAndVersion & 0x0fff) | 0x4000;
1619 pNew->Uuid.Gen.au8Node[0] = Mac.au8[0];
1620 pNew->Uuid.Gen.au8Node[1] = Mac.au8[1];
1621 pNew->Uuid.Gen.au8Node[2] = Mac.au8[2];
1622 pNew->Uuid.Gen.au8Node[3] = Mac.au8[3];
1623 pNew->Uuid.Gen.au8Node[4] = Mac.au8[4];
1624 pNew->Uuid.Gen.au8Node[5] = Mac.au8[5];
1625
1626 pNew->Mac = Mac;
1627 pNew->fWireless = fWireless;
1628 pNew->fAirPort = fAirPort;
1629 pNew->fBuiltin = fBuiltin;
1630 pNew->fUSB = fUSB;
1631 pNew->fPrimaryIf = fPrimaryIf;
1632 memcpy(pNew->szName, szTmp, cchName + 1);
1633
1634 /*
1635 * Link it into the list, keep the list sorted by fPrimaryIf and the BSD name.
1636 */
1637 if (pTail)
1638 {
1639 PDARWINETHERNIC pPrev = pTail;
1640 if (strcmp(pNew->szBSDName, pPrev->szBSDName) < 0)
1641 {
1642 pPrev = NULL;
1643 for (PDARWINETHERNIC pCur = pHead; pCur; pPrev = pCur, pCur = pCur->pNext)
1644 if ( (int)pNew->fPrimaryIf - (int)pCur->fPrimaryIf > 0
1645 || ( (int)pNew->fPrimaryIf - (int)pCur->fPrimaryIf == 0
1646 && strcmp(pNew->szBSDName, pCur->szBSDName) >= 0))
1647 break;
1648 }
1649 if (pPrev)
1650 {
1651 /* tail or in list. */
1652 pNew->pNext = pPrev->pNext;
1653 pPrev->pNext = pNew;
1654 if (pPrev == pTail)
1655 pTail = pNew;
1656 }
1657 else
1658 {
1659 /* head */
1660 pNew->pNext = pHead;
1661 pHead = pNew;
1662 }
1663 }
1664 else
1665 {
1666 /* empty list */
1667 pNew->pNext = NULL;
1668 pTail = pHead = pNew;
1669 }
1670 }
1671 } while (0);
1672
1673 CFRelease(IfPropsRef);
1674 }
1675 CFRelease(PropsRef);
1676 }
1677 IOObjectRelease(EtherNICService);
1678 }
1679 else
1680 AssertMsgFailed(("krc=%#x\n", krc));
1681 IOObjectRelease(EtherIfService);
1682 }
1683
1684 IOObjectRelease(EtherIfServices);
1685 if (ServicesRef)
1686 CFRelease(ServicesRef);
1687 if (IfsRef)
1688 CFRelease(IfsRef);
1689 return pHead;
1690}
1691
1692#ifdef STANDALONE_TESTCASE
1693/**
1694 * This file can optionally be compiled into a testcase, this is the main function.
1695 * To build:
1696 * g++ -I ../../../../include -D IN_RING3 iokit.cpp ../../../../out/darwin.x86/debug/lib/RuntimeR3.a ../../../../out/darwin.x86/debug/lib/SUPR3.a ../../../../out/darwin.x86/debug/lib/RuntimeR3.a ../../../../out/darwin.x86/debug/lib/VBox-kStuff.a ../../../../out/darwin.x86/debug/lib/RuntimeR3.a -framework CoreFoundation -framework IOKit -framework SystemConfiguration -liconv -D STANDALONE_TESTCASE -o iokit -g && ./iokit
1697 */
1698int main(int argc, char **argv)
1699{
1700 RTR3InitExe(argc, &argv, 0);
1701
1702 if (1)
1703 {
1704 /*
1705 * Network preferences.
1706 */
1707 RTPrintf("Preferences: Network Services\n");
1708 SCPreferencesRef PrefsRef = SCPreferencesCreate(kCFAllocatorDefault, CFSTR("org.virtualbox.VBoxSVC"), NULL);
1709 if (PrefsRef)
1710 {
1711 CFDictionaryRef NetworkServiceRef = (CFDictionaryRef)SCPreferencesGetValue(PrefsRef, kSCPrefNetworkServices);
1712 darwinDumpDict(NetworkServiceRef, 4);
1713 CFRelease(PrefsRef);
1714 }
1715 }
1716
1717 if (1)
1718 {
1719 /*
1720 * Network services interfaces in the current config.
1721 */
1722 RTPrintf("Preferences: Network Service Interfaces\n");
1723 SCPreferencesRef PrefsRef = SCPreferencesCreate(kCFAllocatorDefault, CFSTR("org.virtualbox.VBoxSVC"), NULL);
1724 if (PrefsRef)
1725 {
1726 SCNetworkSetRef SetRef = SCNetworkSetCopyCurrent(PrefsRef);
1727 if (SetRef)
1728 {
1729 CFArrayRef ServicesRef = SCNetworkSetCopyServices(SetRef);
1730 CFIndex cServices = CFArrayGetCount(ServicesRef);
1731 for (CFIndex i = 0; i < cServices; i++)
1732 {
1733 SCNetworkServiceRef ServiceRef = (SCNetworkServiceRef)CFArrayGetValueAtIndex(ServicesRef, i);
1734 char szServiceName[128] = {0};
1735 CFStringGetCString(SCNetworkServiceGetName(ServiceRef), szServiceName, sizeof(szServiceName), kCFStringEncodingUTF8);
1736
1737 SCNetworkInterfaceRef IfRef = SCNetworkServiceGetInterface(ServiceRef);
1738 char szBSDName[16] = {0};
1739 if (SCNetworkInterfaceGetBSDName(IfRef))
1740 CFStringGetCString(SCNetworkInterfaceGetBSDName(IfRef), szBSDName, sizeof(szBSDName), kCFStringEncodingUTF8);
1741 char szDisplayName[128] = {0};
1742 if (SCNetworkInterfaceGetLocalizedDisplayName(IfRef))
1743 CFStringGetCString(SCNetworkInterfaceGetLocalizedDisplayName(IfRef), szDisplayName, sizeof(szDisplayName), kCFStringEncodingUTF8);
1744
1745 RTPrintf(" #%u ServiceName=\"%s\" IfBSDName=\"%s\" IfDisplayName=\"%s\"\n",
1746 i, szServiceName, szBSDName, szDisplayName);
1747 }
1748
1749 CFRelease(ServicesRef);
1750 CFRelease(SetRef);
1751 }
1752
1753 CFRelease(PrefsRef);
1754 }
1755 }
1756
1757 if (1)
1758 {
1759 /*
1760 * Network interfaces.
1761 */
1762 RTPrintf("Preferences: Network Interfaces\n");
1763 CFArrayRef IfsRef = SCNetworkInterfaceCopyAll();
1764 if (IfsRef)
1765 {
1766 CFIndex cIfs = CFArrayGetCount(IfsRef);
1767 for (CFIndex i = 0; i < cIfs; i++)
1768 {
1769 SCNetworkInterfaceRef IfRef = (SCNetworkInterfaceRef)CFArrayGetValueAtIndex(IfsRef, i);
1770 char szBSDName[16] = {0};
1771 if (SCNetworkInterfaceGetBSDName(IfRef))
1772 CFStringGetCString(SCNetworkInterfaceGetBSDName(IfRef), szBSDName, sizeof(szBSDName), kCFStringEncodingUTF8);
1773 char szDisplayName[128] = {0};
1774 if (SCNetworkInterfaceGetLocalizedDisplayName(IfRef))
1775 CFStringGetCString(SCNetworkInterfaceGetLocalizedDisplayName(IfRef), szDisplayName, sizeof(szDisplayName), kCFStringEncodingUTF8);
1776 RTPrintf(" #%u BSDName=\"%s\" DisplayName=\"%s\"\n",
1777 i, szBSDName, szDisplayName);
1778 }
1779
1780 CFRelease(IfsRef);
1781 }
1782 }
1783
1784 if (1)
1785 {
1786 /*
1787 * Get and display the ethernet controllers.
1788 */
1789 RTPrintf("Ethernet controllers:\n");
1790 PDARWINETHERNIC pEtherNICs = DarwinGetEthernetControllers();
1791 for (PDARWINETHERNIC pCur = pEtherNICs; pCur; pCur = pCur->pNext)
1792 {
1793 RTPrintf("%s\n", pCur->szName);
1794 RTPrintf(" szBSDName=%s\n", pCur->szBSDName);
1795 RTPrintf(" UUID=%RTuuid\n", &pCur->Uuid);
1796 RTPrintf(" Mac=%.6Rhxs\n", &pCur->Mac);
1797 RTPrintf(" fWireless=%RTbool\n", pCur->fWireless);
1798 RTPrintf(" fAirPort=%RTbool\n", pCur->fAirPort);
1799 RTPrintf(" fBuiltin=%RTbool\n", pCur->fBuiltin);
1800 RTPrintf(" fUSB=%RTbool\n", pCur->fUSB);
1801 RTPrintf(" fPrimaryIf=%RTbool\n", pCur->fPrimaryIf);
1802 }
1803 }
1804
1805
1806 return 0;
1807}
1808#endif
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