/*

This file is a simple way (on Linux) to do a certain kind
of test.  "Code Testing Through Fault Injection" in ":login;"
magazine (December, 2014. Usenix.org) by Peter Gutmann offered
a simple example by an unnamed friend: instrument malloc() so
on call N it returns NULL. Try with N from 0 to some higher
number (I used 0 to 100).  Run your chosen executable and
see how it fares.  This test exposed a couple bugs in libdwarf.

Here are some of the example core dumps (running dwarfgen):
2000: Could not allocate Dwarf_Error structure, abort() in libdwarf.
1000: FAIL:bad alloc caughtstd::bad_alloc
500:  FAIL:bad alloc caughtstd::bad_alloc
250:  FAIL:bad alloc caughtstd::bad_alloc
125:  Could not allocate Dwarf_Error structure, abort() in libdwarf.
      Aborted (core dumped)
100:  FAIL:bad alloc caughtstd::bad_alloc
46-60: FAIL:bad alloc caughtstd::bad_alloc  
45- Could not allocate Dwarf_Error structure, abort() in libdwarf.
    Aborted (core dumped)
42-44: FAIL:bad alloc caughtstd::bad_alloc  
30- 41: Could not allocate Dwarf_Error structure, abort() in libdwarf.
    Aborted (core dumped)
28-29  :FAIL:bad alloc caught std::bad_alloc
    Aborted (core dumped)
  
8,9,10,11-27: Could not allocate Dwarf_Error structure, abort() in libdwarf.
    Aborted (core dumped)
7: 6: FAIL:bad alloc caught std::bad_alloc
 
0,1,2,3,4,5: terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
  Aborted (core dumped)

-------HOW TO USE:
Configure generates the following for Makefile.
$(CXX) $(CXXFLAGS) -o $@ $(DGOBJECTS) $(LDFLAGS)

In the generated Makefile, replace the above line with
these two lines.
$(CC) $(CFLAGS) -c fakemalloc.o
$(CXX) $(CXXFLAGS) -o $@ $(DGOBJECTS) $(LDFLAGS) fakemalloc.o

Run tests using the script TESTmallocfail
-------

*/

static unsigned count;
extern void * __libc_malloc();

void *malloc(unsigned len)
{
  /*  Perhaps the test should be count >= FAILCOUNT  ??? */
  if (count == FAILCOUNT) {
    return 0;
  }
  count++;
  return __libc_malloc(len);
}
