Valgrind is not friendly for swapcontext

Table of Contents

Okie, long time no see … I write this only better for me to remember something what happend, something what I want to share.

This is an experience what I’ve troubled, last week, when I tested my program about c-coroutine library, I found that a lot of critical informations in the output of valgrind. for example:

before switch
==1897== Warning: client switching stacks?  SP change: 0x7ff0003f8 --> 0x5716a58
==1897==          to suppress, use: --max-stackframe=34251643296 or greater
[in co1] arg=1
before switch
==1897== Warning: client switching stacks?  SP change: 0x57169f8 --> 0x7ff000400
==1897==          to suppress, use: --max-stackframe=34251643400 or greater
after switch
[in main] after resume1 n1=10
before switch
==1897== Warning: client switching stacks?  SP change: 0x7ff0003f8 --> 0x5716a00
==1897==          to suppress, use: --max-stackframe=34251643384 or greater
==1897==          further instances of this message will not be shown.
after switch
[in co1] after yield n2=100
[in co1] create co2
before switch
==1897== Invalid read of size 8
==1897==    at 0x529D42C: swapcontext (swapcontext.S:94)
==1897==    by 0x529F64F: ??? (in /lib/x86_64-linux-gnu/libc-2.15.so)
==1897==    by 0x561668F: ???
==1897==  Address 0x5716bc0 is 128 bytes inside a block of size 1,049,704 alloc'd
==1897==    at 0x4C2B3F8: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==1897==    by 0x4120D2: _fco_create (fco.c:134)
==1897==    by 0x40AD98: test (t_fco.c:41)
==1897==    by 0x412080: co_main (fco.c:217)
==1897==    by 0x529F64F: ??? (in /lib/x86_64-linux-gnu/libc-2.15.so)
==1897==    by 0x41280A: tu_run_cases (tu_inc.c:67)
==1897==    by 0x4024F2: main (main.c:33)

Here we can see “Invalid read of size 8” error, but after I make a deep dive, I found that there is a strange thing I have never seen that before: I read a valid memory which I actually alloc it, but valgrind prompt me something wrong in it. but when I swap from main thread context, the error has gone. Okie, so the root question is TheĀ source and destination of swapcontext both are alloc from heap, the error will raise.

For proving my point of view, we can see these lines:

==1897== Warning: client switching stacks?  SP change: 0x7ff0003f8 --> 0x5716a58
==1897==          to suppress, use: --max-stackframe=34251643296 or greater

When valgrind detect a switching action, we can see the warning at above, and when we swap to a new alloced context from a alloced context, we can’t see this warning instead of a Invalid read error, ok, I guess you understand what I’m talking about.

I also found some links from internet, other people also meet this issue:
http://old.nabble.com/Re:-Invalid-read-of-size-4-(fwd)-td118410.html
http://permalink.gmane.org/gmane.comp.debugging.valgrind/1702