29.01.2014 Views

A CIL Tutorial - Department of Computer Science - ETH Zürich

A CIL Tutorial - Department of Computer Science - ETH Zürich

A CIL Tutorial - Department of Computer Science - ETH Zürich

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 6. OVERRIDING FUNCTIONS 48<br />

open Cil<br />

let tut6 (f : file) : unit = ()<br />

6.3 tut6.c<br />

In tut6.c, we demonstrate how to use the dynamic linker to override library functions. In particular,<br />

we wrap calls to pthread mutex lock and pthread mutex unlock. We'll do this by calling dlsym<br />

found in dlfcn.h with the ag RTLD NEXT, which fetches a pointer to the original function we are<br />

overriding. Below are the includes we'll need.<br />

../ciltut-lib/src/tut6.c<br />

# define _GNU_SOURCE // Needed for RTLD_NEXT<br />

# include // For printf<br />

# include // for RTLD_NEXT<br />

# include // for pthread_*<br />

# include // for checked_dlsym<br />

First, we set up function pointers at global scope to point at the original versions <strong>of</strong> the functions,<br />

which we'll call from inside <strong>of</strong> our wrappers.<br />

../ciltut-lib/src/tut6.c<br />

static int (*pthread_mutex_lock_orig) (pthread_mutex_t *m) = NULL;<br />

static int (*pthread_mutex_unlock_orig)(pthread_mutex_t *m) = NULL;<br />

We'll also declare a ag so that we can enable and disable lock tracing.<br />

../ciltut-lib/src/tut6.c<br />

static int enable_lock_tracking = 0;<br />

With the pointers to the original functions declared, we can now write the wrappers. The wrappers<br />

have the same name as the original functions. This way, calls to the functions will be routed to these<br />

versions. The rst thing that the wrapper functions do is set up the pointers to the original calls<br />

using checked dlsym. checked dlsym will abort the program if the function named by the string<br />

does not exist. After ensuring that the original functions exist, the wrappers may then execute<br />

whatever actions are needed to implement their purpose, and to call the original functions.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!