Skip to content

Instantly share code, notes, and snippets.

@mfukar
Last active March 21, 2018 03:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mfukar/15cfa58efc421f6d8f3e to your computer and use it in GitHub Desktop.
Save mfukar/15cfa58efc421f6d8f3e to your computer and use it in GitHub Desktop.
Hook mach_msg and print message contents
/*
* View the contents of messages sent/received via `mach_msg`.
*
* Compile with:
* clang -arch x86_64 -arch i386 -Wall -o mach_msg_hook.dylib -dynamiclib mach_msg_hook.c
*
* and run as:
* DYLD_FORCE_FLAT_NAMESPACE=1 DYLD_INSERT_LIBRARIES=mach_msg_hook.dylib [COMMAND]
*
* Have fun.
*/
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <ctype.h>
#include <dlfcn.h>
#include <xpc/xpc.h>
void print_hexdump(const void *buf, size_t len)
{
/* Embrace the DIY paradigm. */
}
mach_msg_return_t (*orig_mach_msg)(mach_msg_header_t *,
mach_msg_option_t, mach_msg_size_t,
mach_msg_size_t,
mach_port_t,
mach_msg_timeout_t,
mach_port_t);
mach_msg_return_t mach_msg(mach_msg_header_t *msg,
mach_msg_option_t option,
mach_msg_size_t send_size,
mach_msg_size_t rcv_size,
mach_port_t rcv_name,
mach_msg_timeout_t timeout,
mach_port_t notify){
/* We will call the original `mach_msg` after we print out the contents of each
* message:
*/
if(!orig_mach_msg){
orig_mach_msg = dlsym(RTLD_NEXT, "mach_msg");
}
/* The mach message's local_port is how a response will be sent
* back. If this is set, we assume there will be a response.
*/
bool response = msg->msgh_local_port > 0;
/* Request:*/
print_hexdump(msg, send_size);
mach_msg_return_t ret = mach_msg(msg,
option,
send_size,
rcv_size,
rcv_name,
timeout,
notify);
/* Response: */
if(response){
print_hexdump(msg, rcv_size);
}
return(ret);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment