-----------------------------------------------------------------------------
overview
-----------------------------------------------------------------------------
Previously Valgrind had its own versions of malloc() et al that replaced
glibc's.  This is necessary for various reasons for Memcheck, but isn't needed,
and was actually detrimental, to some other skins.  I never managed to treat
this satisfactorily w.r.t the core/skin split.

Now I have.  If a skin needs to know about malloc() et al, it must provide its
own replacements.  But because this is not uncommon, the core provides a module
vg_replace_malloc.c which a skin can link with, which provides skeleton
definitions, to reduce the amount of work a skin must do.  The skeletons handle
the transfer of control from the simd CPU to the real CPU, and also the
--alignment, --sloppy-malloc and --trace-malloc options.  These skeleton
definitions subsequently call functions SK_(malloc), SK_(free), etc, which the
skin must define;  in these functions the skin can do the things it needs to do
about tracking heap blocks.

For skins that track extra info about malloc'd blocks -- previously done with
ShadowChunks -- there is a new file vg_hashtable.c that implements a
generic-ish hash table (using dodgy C-style inheritance using struct overlays)
which allows skins to continue doing this fairly easily.

Skins can also replace other functions too, eg. Memcheck has its own versions
of strcpy(), memcpy(), etc.

Overall, it's slightly more work now for skins that need to replace malloc(),
but other skins don't have to use Valgrind's malloc(), so they're getting a
"purer" program run, which is good, and most of the remaining rough edges from
the core/skin split have been removed.

-----------------------------------------------------------------------------
details
-----------------------------------------------------------------------------
Moved malloc() et al intercepts from vg_clientfuncs.c into vg_replace_malloc.c.
Skins can link to it if they want to replace malloc() and friends;  it does
some stuff then passes control to SK_(malloc)() et al which the skin must
define.  They can call VG_(cli_malloc)() and VG_(cli_free)() to do the actual
allocation/deallocation.  Redzone size for the client (the CLIENT arena) is
specified by the static variable VG_(vg_malloc_redzone_szB).
vg_replace_malloc.c thus represents a kind of "mantle" level service.

To get automake to build vg_replace_malloc.o, had to resort to a similar trick
as used for the demangler -- ask for a "no install" library (which is never
used) to be built from it.

Note that all malloc, calloc, realloc, builtin_new, builtin_vec_new, memalign
are now aware of --alignment, when running on simd CPU or real CPU.

This means the new_mem_heap, die_mem_heap, copy_mem_heap and ban_mem_heap
events no longer exist, since the core doesn't control malloc() any more, and
skins can watch for these events themselves.

This required moving all the ShadowChunk stuff out of the core, which meant
the sizeof_shadow_block ``need'' could be removed, yay -- it was a horrible
hack.  Now ShadowChunks are done with a generic HashTable type, in
vg_hashtable.c, which skins can "inherit from" (in a dodgy C-only fashion by
using structs with similar layouts).  Also, the free_list stuff was all moved
as a part of this.  Also, VgAllocKind was moved out of core into
Memcheck/Addrcheck and renamed MAC_AllocKind.

Moved these options out of core into vg_replace_malloc.c:
    --trace-malloc
    --sloppy-malloc
    --alignment

The alternative_free ``need'' could go, too, since Memcheck is now in complete
control of free(), yay -- another horribility.

The bad_free and free_mismatch events could go too, since they're now not
detected by core, yay -- yet another horribility.

Moved malloc() et al wrappers for Memcheck out of vg_clientmalloc.c into
mac_malloc_wrappers.c.  Helgrind has its own wrappers now too.

Introduced VG_USERREQ__CLIENT_CALL[123] client requests.  When a skin function
is operating on the simd CPU, this will call a given function and run it on the
real CPU.  The macros VG_NON_SIMD_CALL[123] in valgrind.h present a cleaner
interface to actually use.  Also introduce analogues of these that pass 'tst'
from the scheduler as the first arg to the called function -- needed for
MC_(client_malloc)() et al.

Fiddled with USERREQ_{MALLOC,FREE} etc. in vg_scheduler.c; they call
SK_({malloc,free})() which by default call VG_(cli_malloc)() -- can't call
glibc's malloc() here.  All the other default SK_(calloc)() etc. instantly
panic; there's a lock variable to ensure that the default SK_({malloc,free})()
are only called from the scheduler, which prevents a skin from forgetting to
override SK_({malloc,free})().  Got rid of the unused USERREQ_CALLOC,
USERREQ_BUILTIN_NEW, etc.

Moved special versions of strcpy/strlen, etc, memcpy() and memchr() into
mac_replace_strmem.c -- they are only necessary for memcheck, because the
hyper-optimised normal glibc versions confuse it, and for memcpy() etc. overlap
checking.

Also added dst/src overlap checks to strcpy(), memcpy(), strcat().  They are
reported not as proper errors, but just with single line warnings, as for silly
args to malloc() et al;  this is mainly because they're on the simulated CPU
and proper error handling would be a pain;  hopefully they're rare enough to
not be a problem.  The strcpy check is done after the copy, because it would
require counting the length of the string beforehand.  Also added strncpy() and
strncat(), which have overlap checks too.  Note that addrcheck doesn't do
overlap checking.

Put USERREQ__LOGMESSAGE in vg_skin.h to do the overlap check error messages.

After removing malloc() et al and strcpy() et al out of vg_clientfuncs.c, moved
the remaining three things (sigsuspend, VG_(__libc_freeres_wrapper),
__errno_location) into vg_intercept.c, since it contains things that run on the
simulated CPU too.  Removed vg_clientfuncs.c altogether.

Moved regression test "malloc3" out of corecheck into memcheck, since corecheck
no longer looks for silly (eg. negative) args to malloc().

Removed the m_eip, m_esp, m_ebp fields from the `Error' type.  They were being
set up, and then read immediately only once, only if GDB attachment was done.
So now they're just being held in local variables.  This saves 12 bytes per
Error.

Made replacement calloc() check for --sloppy-malloc;  previously it didn't.

Added "silly" negative size arg check to realloc(), it didn't have one.

Changed VG_(read_selfprocmaps)() so it can parse the file directly, or from a
previously read buffer.  Buffer can be filled with the new
VG_(read_selfprocmaps_contents)().  Using this at start-up to snapshot
/proc/self/maps before the skins do anything, and then parsing it once they
have done their setup stuff.  Skins can now safely call VG_(malloc)() in
SK_({pre,post}_clo_init)() without the mmap'd superblock erroneously being
identified as client memory.

Changed the --help usage message slightly, now divided into four sections: core
normal, skin normal, core debugging, skin debugging.  Changed the interface for
the command_line_options need slightly -- now two functions, VG_(print_usage)()
and VG_(print_debug_usage)(), and they do the printing themselves, instead of
just returning a string -- that's more flexible.

Removed DEBUG_CLIENTMALLOC code, it wasn't being used and was a pain.

Added a regression test testing leak suppressions (nanoleak_supp), and another
testing strcpy/memcpy/etc overlap warnings (overlap).

Also changed Addrcheck to link with the files shared with Memcheck, rather than
#including the .c files directly.

Commoned up a little more shared Addrcheck/Memcheck code, for the usage
message, and initialisation/finalisation.

Added a Bool param to VG_(unique_error)() dictating whether it should allow
GDB to be attached; for leak checks, because we don't want to attach GDB on
leak errors (causes seg faults).  A bit hacky, but it will do.

Had to change lots of the expected outputs from regression files now that
malloc() et al are in vg_replace_malloc.c rather than vg_clientfuncs.c.


git-svn-id: svn://svn.valgrind.org/valgrind/trunk@1524 a5019735-40e9-0310-863c-91ae7b9d1cf9
diff --git a/coregrind/vg_include.h b/coregrind/vg_include.h
index 85ba492..7eed65a 100644
--- a/coregrind/vg_include.h
+++ b/coregrind/vg_include.h
@@ -177,12 +177,6 @@
 extern Int   VG_(sanity_level);
 /* Automatically attempt to demangle C++ names?  default: YES */
 extern Bool  VG_(clo_demangle);
-/* Round malloc sizes upwards to integral number of words? default:
-   NO */
-extern Bool  VG_(clo_sloppy_malloc);
-/* Minimum alignment in functions that don't specify alignment explicitly.
-   default: 0, i.e. use default of the machine (== 4) */
-extern Int   VG_(clo_alignment);
 /* Simulate child processes? default: NO */
 extern Bool  VG_(clo_trace_children);
 
@@ -224,8 +218,6 @@
 extern Bool  VG_(clo_trace_signals);
 /* DEBUG: print symtab details?  default: NO */
 extern Bool  VG_(clo_trace_symtab);
-/* DEBUG: print malloc details?  default: NO */
-extern Bool  VG_(clo_trace_malloc);
 /* DEBUG: print thread scheduling events?  default: NO */
 extern Bool  VG_(clo_trace_sched);
 /* DEBUG: print pthread (mutex etc) events?  default: 0 (none), 1
@@ -304,8 +296,6 @@
       Bool client_requests;
       Bool extended_UCode;
       Bool syscall_wrapper;
-      UInt sizeof_shadow_block;
-      Bool alternative_free;
       Bool sanity_checks;
       Bool data_syms;
    } 
@@ -320,11 +310,16 @@
    struct {
       /* Memory events */
       void (*new_mem_startup)( Addr a, UInt len, Bool rr, Bool ww, Bool xx );
-      void (*new_mem_heap)   ( Addr a, UInt len, Bool is_inited );
       void (*new_mem_stack_signal)  ( Addr a, UInt len );
       void (*new_mem_brk)    ( Addr a, UInt len );
       void (*new_mem_mmap)   ( Addr a, UInt len, Bool rr, Bool ww, Bool xx );
 
+      void (*copy_mem_remap) ( Addr from, Addr to, UInt len );
+      void (*change_mem_mprotect) ( Addr a, UInt len, Bool rr, Bool ww, Bool xx );
+      void (*die_mem_stack_signal)  ( Addr a, UInt len );
+      void (*die_mem_brk)    ( Addr a, UInt len );
+      void (*die_mem_munmap) ( Addr a, UInt len );
+
       void (*new_mem_stack_4)  ( Addr new_ESP );
       void (*new_mem_stack_8)  ( Addr new_ESP );
       void (*new_mem_stack_12) ( Addr new_ESP );
@@ -332,19 +327,6 @@
       void (*new_mem_stack_32) ( Addr new_ESP );
       void (*new_mem_stack)    ( Addr a, UInt len );
 
-      void (*copy_mem_heap)  ( Addr from, Addr to, UInt len );
-      void (*copy_mem_remap) ( Addr from, Addr to, UInt len );
-      void (*change_mem_mprotect) ( Addr a, UInt len, Bool rr, Bool ww, Bool xx );
-      
-      /* Used on redzones around malloc'd blocks and at end of stack */
-      void (*ban_mem_heap)   ( Addr a, UInt len );
-      void (*ban_mem_stack)  ( Addr a, UInt len );
-
-      void (*die_mem_heap)   ( Addr a, UInt len );
-      void (*die_mem_stack_signal)  ( Addr a, UInt len );
-      void (*die_mem_brk)    ( Addr a, UInt len );
-      void (*die_mem_munmap) ( Addr a, UInt len );
-
       void (*die_mem_stack_4)  ( Addr die_ESP );
       void (*die_mem_stack_8)  ( Addr die_ESP );
       void (*die_mem_stack_12) ( Addr die_ESP );
@@ -352,8 +334,7 @@
       void (*die_mem_stack_32) ( Addr die_ESP );
       void (*die_mem_stack)    ( Addr a, UInt len );
 
-      void (*bad_free)        ( ThreadState* tst, Addr a );
-      void (*mismatched_free) ( ThreadState* tst, Addr a );
+      void (*ban_mem_stack)  ( Addr a, UInt len );
 
       void (*pre_mem_read)   ( CorePart part, ThreadState* tst,
                                Char* s, Addr a, UInt size );
@@ -386,7 +367,7 @@
                                   void* /*pthread_mutex_t* */ mutex );
 
       /* Signal events (not exhaustive) */
-      void (*pre_deliver_signal)  ( ThreadId tid, Int sigNo, Bool alt_stack );
+      void (* pre_deliver_signal) ( ThreadId tid, Int sigNo, Bool alt_stack );
       void (*post_deliver_signal) ( ThreadId tid, Int sigNo );
 
       
@@ -409,35 +390,38 @@
    ------------------------------------------------------------------ */
 
 /* Allocation arenas.  
-      CORE      is for the core's general use.
-      SKIN      is for the skin to use (and the only one it uses).
-      SYMTAB    is for Valgrind's symbol table storage.
-      JITTER    is for small storage during translation.
-      CLIENT    is for the client's mallocs/frees.
-      DEMANGLE  is for the C++ demangler.
-      EXECTXT   is for storing ExeContexts.
-      ERRORS    is for storing CoreErrors.
-      TRANSIENT is for very short-term use.  It should be empty
-                in between uses.
+
+      CORE      for the core's general use.
+      SKIN      for the skin to use (and the only one it uses).
+      SYMTAB    for Valgrind's symbol table storage.
+      JITTER    for small storage during translation.
+      CLIENT    for the client's mallocs/frees, if the skin replaces glibc's
+                    malloc() et al -- redzone size is chosen by the skin.
+      DEMANGLE  for the C++ demangler.
+      EXECTXT   for storing ExeContexts.
+      ERRORS    for storing CoreErrors.
+      TRANSIENT for very short-term use.  It should be empty in between uses.
+
    When adding a new arena, remember also to add it to ensure_mm_init(). 
 */
 typedef Int ArenaId;
 
-#define VG_N_ARENAS 9
+#define VG_N_ARENAS        9 
 
-#define VG_AR_CORE      0    /* :: ArenaId */
-#define VG_AR_SKIN      1    /* :: ArenaId */
-#define VG_AR_SYMTAB    2    /* :: ArenaId */
-#define VG_AR_JITTER    3    /* :: ArenaId */
-#define VG_AR_CLIENT    4    /* :: ArenaId */
-#define VG_AR_DEMANGLE  5    /* :: ArenaId */
-#define VG_AR_EXECTXT   6    /* :: ArenaId */
-#define VG_AR_ERRORS    7    /* :: ArenaId */
-#define VG_AR_TRANSIENT 8    /* :: ArenaId */
+#define VG_AR_CORE         0
+#define VG_AR_SKIN         1
+#define VG_AR_SYMTAB       2
+#define VG_AR_JITTER       3
+#define VG_AR_CLIENT       4
+#define VG_AR_DEMANGLE     5
+#define VG_AR_EXECTXT      6
+#define VG_AR_ERRORS       7
+#define VG_AR_TRANSIENT    8
 
 extern void* VG_(arena_malloc)  ( ArenaId arena, Int nbytes );
 extern void  VG_(arena_free)    ( ArenaId arena, void* ptr );
-extern void* VG_(arena_calloc)  ( ArenaId arena, Int nmemb, Int nbytes );
+extern void* VG_(arena_calloc)  ( ArenaId arena, Int alignment,
+                                  Int nmemb, Int nbytes );
 extern void* VG_(arena_realloc) ( ArenaId arena, void* ptr, Int alignment,
                                   Int size );
 extern void* VG_(arena_malloc_aligned) ( ArenaId aid, Int req_alignB, 
@@ -449,16 +433,8 @@
 extern Bool  VG_(is_empty_arena) ( ArenaId aid );
 
 
-/* The red-zone size for the client.  This can be arbitrary, but
-   unfortunately must be set at compile time. */
-#define VG_AR_CLIENT_REDZONE_SZW 4
-
-#define VG_AR_CLIENT_REDZONE_SZB \
-   (VG_AR_CLIENT_REDZONE_SZW * VKI_BYTES_PER_WORD)
-
-
 /* ---------------------------------------------------------------------
-   Exports of vg_clientfuncs.c
+   Exports of vg_intercept.c
    ------------------------------------------------------------------ */
 
 /* This doesn't export code or data that valgrind.so needs to link
@@ -467,17 +443,7 @@
    defined in valgrind.h, and similar headers for some skins. */
 
 #define VG_USERREQ__MALLOC              0x2001
-#define VG_USERREQ__BUILTIN_NEW         0x2002
-#define VG_USERREQ__BUILTIN_VEC_NEW     0x2003
-
-#define VG_USERREQ__FREE                0x2004
-#define VG_USERREQ__BUILTIN_DELETE      0x2005
-#define VG_USERREQ__BUILTIN_VEC_DELETE  0x2006
-
-#define VG_USERREQ__CALLOC              0x2007
-#define VG_USERREQ__REALLOC             0x2008
-#define VG_USERREQ__MEMALIGN            0x2009
-
+#define VG_USERREQ__FREE                0x2002
 
 /* (Fn, Arg): Create a new thread and run Fn applied to Arg in it.  Fn
    MUST NOT return -- ever.  Eventually it will do either __QUIT or
@@ -552,9 +518,11 @@
 #define VG_USERREQ__GET_PTHREAD_TRACE_LEVEL 0x3101
 /* Log a pthread error from client-space.  Cosmetic. */
 #define VG_USERREQ__PTHREAD_ERROR           0x3102
-/* Write a string to the logging sink. */
+/* 
+In vg_skin.h, so skins can use it.
+Write a string to the logging sink. 
 #define VG_USERREQ__LOGMESSAGE              0x3103
-
+*/
 
 /* 
 In vg_constants.h:
@@ -578,6 +546,13 @@
 
 
 /* ---------------------------------------------------------------------
+   Exports of vg_defaults.c
+   ------------------------------------------------------------------ */
+
+extern Bool VG_(sk_malloc_called_by_scheduler);
+
+
+/* ---------------------------------------------------------------------
    Exports of vg_ldt.c
    ------------------------------------------------------------------ */
 
@@ -1166,13 +1141,6 @@
    Supp* supp;
    Int count;
    ThreadId tid;
-   /* These record %EIP, %ESP and %EBP at the error point.  They
-      are only used to make GDB-attaching convenient; there is no
-      other purpose; specifically they are not used to do
-      comparisons between errors. */
-   UInt m_eip;
-   UInt m_esp;
-   UInt m_ebp;
 
    /* The skin-specific part */
    /* Initialised by core */
@@ -1206,9 +1174,16 @@
    Exports of vg_procselfmaps.c
    ------------------------------------------------------------------ */
 
+/* Reads /proc/self/maps into a static buffer. */
+void VG_(read_procselfmaps_contents) ( void );
+
+/* Parses /proc/self/maps, calling `record_mapping' for each entry.  If
+   `read_from_file' is True, /proc/self/maps is read directly, otherwise
+   it's read from the buffer filled by VG_(read_procselfmaps_contents)(). */
 extern 
 void VG_(read_procselfmaps) (
-   void (*record_mapping)( Addr, UInt, Char, Char, Char, UInt, UChar* )
+   void (*record_mapping)( Addr, UInt, Char, Char, Char, UInt, UChar* ),
+   Bool read_from_file
 );
 
 
@@ -1227,46 +1202,6 @@
 
 
 /* ---------------------------------------------------------------------
-   Exports of vg_clientmalloc.c
-   ------------------------------------------------------------------ */
-
-typedef
-   enum { 
-      Vg_AllocMalloc = 0,
-      Vg_AllocNew    = 1,
-      Vg_AllocNewVec = 2 
-   }
-   VgAllocKind;
-
-/* Description of a malloc'd chunk.  Functions for extracting skin-relevant
-   parts are in include/vg_skin.h Size of skin_extra array is given by
-   VG_(needs).sizeof_shadow_chunk. */
-struct _ShadowChunk {
-   struct _ShadowChunk* next;
-   UInt          size : 30;      /* size requested                   */
-   VgAllocKind   allockind : 2;  /* which wrapper did the allocation */
-   Addr          data;           /* ptr to actual block              */
-   UInt          extra[0];       /* extra skin-specific info         */
-};
-
-
-extern void  VG_(client_malloc_init)();
-
-/* These are called from the scheduler, when it intercepts a user
-   request. */
-extern void* VG_(client_malloc)   ( ThreadState* tst, 
-                                    UInt size, VgAllocKind kind );
-extern void* VG_(client_memalign) ( ThreadState* tst, 
-                                    UInt align, UInt size );
-extern void  VG_(client_free)     ( ThreadState* tst, 
-                                    void* ptrV, VgAllocKind  kind );
-extern void* VG_(client_calloc)   ( ThreadState* tst, 
-                                    UInt nmemb, UInt size1 );
-extern void* VG_(client_realloc)  ( ThreadState* tst, 
-                                    void* ptrV, UInt size_new );
-
-
-/* ---------------------------------------------------------------------
    Exports of vg_main.c
    ------------------------------------------------------------------ */