Intercepting OpenGL Calls

To capture the OpenGL commands is fairly easy, all you need to do is link a library that implements the OpenGL function before it links the actual library.
Screen Shot 2014-04-28 at 09.46.51

Originally I had planned to use the environment variable DYLD_INSERT_LIBRARIES to achieve this, however I could not get it to work with my Cocoa application. So I decided to just compile it with it and let the user decide whether or not they want to run the executable and insert the library at runtime, or add it to their project to link first.

The next challenge is that now you have intercepted the call, you still need to forward it onto where it was going originally. To do this, I used the link library constructor to retrieve and store this pointer for later use to reduce overhead.

#include <stdio.h>
#include <dlfcn.h>
 
//
typedef void (*_fn_glViewport) (GLint x, GLint y, GLsizei width, GLsizei height);
_fn_glViewport g_glViewport = NULL;
 
//
__attribute__((constructor)) void DllMain()
{
	g_glViewport = (_fn_glViewport)dlsym(RTLD_NEXT, "glViewport");
}
 
//
void glViewport (GLint x, GLint y, GLsizei width, GLsizei height)
{
	printf("Intercepted glViewport call\n");
	g_glViewport(x, y, width, height);
}

The RTLD_NEXT parameter tells dlsym to retrieve the method from the next linked dependencies. Ideally you probably want to check the pointer to make sure it isn’t NULL before calling it, however since glViewport comes from OpenGL 1.0 and still exists in the latest version, I don’t bother.