Skip to content

Instantly share code, notes, and snippets.

@JonnyJD
Created July 31, 2013 22:16
Show Gist options
  • Save JonnyJD/6126680 to your computer and use it in GitHub Desktop.
Save JonnyJD/6126680 to your computer and use it in GitHub Desktop.
traversing the I/O registry on Mac OS X (iokit)
traverse_io_registry: traverse_io_registry.c
${CC} $^ -framework CoreFoundation -framework IOKit -o $@
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
static void print_entry(io_registry_entry_t entry);
static void traverse_entry(io_registry_entry_t entry);
static void print_cf_string(CFStringRef cf_string) {
char * buffer;
CFIndex len = CFStringGetLength(cf_string);
buffer = (char *) malloc(sizeof(char) * len + 1);
CFStringGetCString(cf_string, buffer, len + 1,
CFStringGetSystemEncoding());
printf("%s", buffer);
free(buffer);
}
static void print_cf_number(CFNumberRef cf_number) {
int number;
/* TODO rather test CFNumberType, than approximate to int */
CFNumberGetValue(cf_number, kCFNumberIntType, &number);
printf("%d", number);
}
static void print_cf_type(CFTypeRef cf_type) {
CFTypeID type_id;
type_id = (CFTypeID) CFGetTypeID(cf_type);
if (type_id == CFStringGetTypeID()) {
print_cf_string(cf_type);
} else if (type_id == CFNumberGetTypeID()) {
print_cf_number(cf_type);
} else {
/* unknown Type (TODO) */
printf("<");
print_cf_string(CFCopyTypeIDDescription(type_id));
printf(">");
/* CFSHOW(type_id) for or
* print_cf_string(CFCopyDescription(type_id))
*/
}
}
static void print_properties(io_registry_entry_t entry) {
CFMutableDictionaryRef properties;
CFIndex count;
CFTypeRef *keys;
CFTypeRef *values;
int i;
IORegistryEntryCreateCFProperties(entry, &properties,
kCFAllocatorDefault, kNilOptions);
count = CFDictionaryGetCount(properties);
keys = (CFTypeRef *) malloc(sizeof(CFTypeRef) * count);
values = (CFTypeRef *) malloc(sizeof(CFTypeRef) * count);
CFDictionaryGetKeysAndValues(properties,
(const void **) keys, (const void **) values);
for (i = 0; i < count; i++) {
printf("\t");
print_cf_type(keys[i]);
printf(": ");
print_cf_type(values[i]);
printf("\n");
}
}
static void print_entry(io_registry_entry_t entry) {
io_name_t name;
IORegistryEntryGetName(entry, name);
printf("Starting %s\n", name);
print_properties(entry);
traverse_entry(entry);
printf("Finishing %s\n", name);
}
static void traverse_entry(io_registry_entry_t entry) {
io_iterator_t childIterator;
io_object_t child;
IORegistryEntryGetChildIterator(entry, kIOServicePlane, &childIterator);
while ((child = IOIteratorNext(childIterator))) {
print_entry(child);
IOObjectRelease(child);
}
IOObjectRelease(childIterator);
}
int main() {
mach_port_t masterPort;
io_registry_entry_t rootEntry;
IOMasterPort(MACH_PORT_NULL, &masterPort);
rootEntry = IORegistryGetRootEntry(masterPort);
print_entry(rootEntry);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment