tags:

views:

229

answers:

1

On Windows there a few libraries that allow you to intercept calls to DLLs:

http://www.codeproject.com/kb/system/hooksys.aspx

Is it possible to do this on Mac OS? If so, how is it done?

+4  A: 

The answer depends on whether you want to do this in your own application or systemwide. In your own application, it's pretty easy; the dynamic linker provides features such as DYLD_INSERT_LIBRARIES. If you're doing this for debugging/instrumentation purposes, also check out DTrace.

You can replace Objective-C method implementations with method swizzling, e.g. JRSwizzle or Apple's method_exchangeImplementations (10.5+).

If you want to modify library behavior systemwide, you're going to need to load into other processes' address spaces.

  • Two loading mechanisms originally designed for other purposes (input managers and scripting additions) are commonly abused for this purpose, but I wouldn't really recommend them.
  • mach_inject/mach_override are an open-source set of libraries for loading code and replacing function implementations, respectively; however, you're responsible for writing your own application which uses the libraries. (Also, take a look at this answer; you need special permissions to inject code into other processes.)
  • If you don't want to write your own loader, there's a commercial loader, APE, for which a SDK is available. APE provides a management user interface and a lot of higher-level niceties, such as preference handling, that mach_inject doesn't.

Please keep in mind that application patching/code injection for non-debugging purposes is strongly discouraged by Apple and some Mac users (and developers) are extremely critical of the practice. Much of this criticism is poorly informed, but there have been a number of legitimately poorly written "plug-ins" (particularly those which patch Safari) that have been implicated in application crashes and problems. Code defensively.

(Disclaimer: I am the author of a (free) APE module and an application which uses mach_inject.)

Nicholas Riley