invalid read in mpn_copyi?

David Harvey d.harvey at unsw.edu.au
Tue Jan 21 20:46:25 UTC 2014


hi,

I'm not sure if the following is considered a bug. (This was picked up by Andrew Sutherland.)

The implementation of mpn_copyi in mpn/x86_64/core2/copyi.asm (GMP 5.1.3) generates invalid reads in certain circumstances, according to valgrind.

Here is the code:

========================================================

#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>

int main(int argc, char* argv[])
{ 
  long trial;
  mp_limb_t* src;
  mp_limb_t dest[13];

  /* try to get malloc to allocate a block of 13 * 8 bytes,
     aligned at 0x70 */

  for (trial = 0; trial < 10000; trial++)
    { 
      src = (mp_limb_t*) malloc(13 * sizeof(mp_limb_t));

      if ((((long) src) & 0xff) == 0x70)
        { 
          /* this line generates invalid read at src + 13 */
          mpn_copyi(dest, src + 5, 8);
          return 0;
        }
    }

  printf("could not get malloc'd block with desired alignment\n");
  return 0;
}

========================================================

This runs as normal with no crashes.

However, when I run under valgrind I get:

==7858== Invalid read of size 8
==7858==    at 0x4C64106: __gmpn_copyi (in /home/z2232064/temp/local/lib/libgmp.so.10.1.3)
==7858==    by 0x3E6281ECDC: (below main) (in /lib64/libc-2.12.so)
==7858==  Address 0x4e996d8 is 0 bytes after a block of size 104 alloc'd
==7858==    at 0x4A05FDE: malloc (vg_replace_malloc.c:236)
==7858==    by 0x40067F: main (in /home/z2232064/temp/thing)

I can see why this might be considered a non-bug, and perhaps it's even intentional for performance reasons, but it seemed dodgy enough to me to report it.

At the very least it makes it difficult to a debug a program with a tool like valgrind. We ended up rolling back to a previous version of GMP that did not exhibit this behaviour, so that we could eliminate the white noise.

david



More information about the gmp-bugs mailing list