kdebug

From The iPhone Wiki
Jump to: navigation, search

kdebug is a XNU built-in debugging facility, which has been around OS X from its early days, and is present - to varying extents - in iOS. In OS X, sc_usage(1), fs_usage(1) and latency(1) make use of it. The facility can be enabled and controlled via sysctl(2) calls, similar to the following code.

#define KDEBUG_ENABLE_TRACE   0x1
#define KDEBUG_ENABLE_ENTROPY 0x2
#define KDEBUG_ENABLE_CHUD    0x4

// N.B - must SETBUF before facility can be enabled. 

int mib[4];
mib[0] = CTL_KERN;
mib[1] = KERN_KDEBUG;
mib[2] = KERN_KDENABLE;         /* or a host of other codes from kdebug.h */
mib[3] = /* One of above values, 0 disables */;

if (sysctl(mib, 4, NULL, &needed, NULL, 0) < 0)
{
    perror("sysctl, KERN_KDENABLE\n");
}

kdebug's most useful feature is to enable kernel-level tracing, but can also be enabled for entropy collection (i.e. /dev/random like behavior), among other things. The CHUD (Computer Hardware Understanding) interfaces are very powerful, though woefully poorly documented, and private to Apple (and probably deserve a future Wiki entry on their own). They likely exist in iOS4, though a sysctl to enable them in iOS 5 fails.

The user mode header, <sys/kdebug.h> is partial, at best. A complete header can be found in the XNU source code.

In OS X, most of the kdebug functionality can be met (and exceeded) by DTrace. This is not an option with iOS, which does not have DTrace. The kdebug facility, however, is supported. iOS 5.01 has been verified to support it to a similar extent as OS X, including clean compilation and execution of sc_usage(1). The same cannot be said for iOS 4, wherein the binaries compile, but do not execute properly.

A utility to display kdebug output for both OS X and iOS can be found at http://NewOSXBook.com/tools/kdv.html

On recent macOS, there is an updated ktrace(1), which can be used to configure, record, and print events from kdebug kernel trace.

For iOS, the pymobiledevice3 [1], with DeveloperDiskImage mounted, could extract and show kdebug events. E.g.,

 $ pymobiledevice3 developer dvt core-profile-session live
 $ pymobiledevice3 developer dvt core-profile-session parse-live

[1] https://github.com/doronz88/pymobiledevice3