2014-03-20

Yesterday we saw how to get line numbers in the stacktrace when using ASAN and gcc, today we're going to see how to deal with ASAN and libraries. For that we're going to use these three very simple files

shared.cpp

shared.h

main.cpp

We do the initial compilation:

and it segfaults :)

Now we want to use ASAN to find out what's wrong, where do we add the -fsanitize=address -fno-omit-frame-pointer? Logic would say that we add it to both places, but actually it's only necessary to add it to the final binary, i.e

and we get

There you go, no need to add the -fsanitize=address flag to the library compilation :)

Now, until a few minutes ago I did not know this, I actually was adding -fsanitize=address to the library itself; that comes with a few problems that i'll explain how i solved (just for completeness, since the above example shows you don't need it)

My logic was that by looking at main.cpp i knew nothing could be wrong there so i decided i wanted sanitize the library, my first attempt was:

which gives a linking error

OK, so we are told to recompile with -fPIC, easy peasy

Which still fails to link!

OK, so if ASAN symbols are missing, let's just compile libasan in

Links!

Next since I know nothing is wrong in main.cpp I don't need ASAN in there

Compiles!

But when run it segfaults :-/ And if you debug it you'll see a stack trace like

So something weird in ASAN thing is going on, let's compile -lasan in also

Same crash :-/

Ok, so then you think, well, let's just add the fsanitize in. And then it works, but as demonstrated a few lines ago, the whole thing of adding -fsanitize=address and -lasan to the library was unneeded since all that was required was just adding -fsanitize=address to the binary when it's compiled and that's it :)

Show more