Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[mc] Cleanup heap switching code
[simgrid.git] / src / xbt / mmalloc / mm_legacy.c
index f62d331..fac98b1 100644 (file)
@@ -6,12 +6,17 @@
 
 /* Redefine the classical malloc/free/realloc functions so that they fit well in the mmalloc framework */
 #define _GNU_SOURCE
+
+#include <stdlib.h>
+
 #include <dlfcn.h>
 
+#include "../../mc/mc_base.h"
 #include "mmprivate.h"
 #include "xbt_modinter.h"
 #include "internal_config.h"
 #include <math.h>
+#include "../mc/mc_protocol.h"
 
 //#define MM_LEGACY_VERBOSE 1 /* define this to see which version of malloc gets used */
 
    backwards compatibility with the non-mmap'd version. */
 xbt_mheap_t __mmalloc_default_mdp = NULL;
 
+static int __malloc_use_mmalloc;
+
+int malloc_use_mmalloc(void)
+{
+  return __malloc_use_mmalloc;
+}
 
 static xbt_mheap_t __mmalloc_current_heap = NULL;     /* The heap we are currently using. */
 
@@ -29,9 +40,11 @@ xbt_mheap_t mmalloc_get_current_heap(void)
   return __mmalloc_current_heap;
 }
 
-void mmalloc_set_current_heap(xbt_mheap_t new_heap)
+xbt_mheap_t mmalloc_set_current_heap(xbt_mheap_t new_heap)
 {
+  xbt_mheap_t heap = __mmalloc_current_heap;
   __mmalloc_current_heap = new_heap;
+  return heap;
 }
 
 #ifdef MMALLOC_WANT_OVERRIDE_LEGACY
@@ -62,8 +75,8 @@ static mm_realloc_t mm_real_realloc = mm_fake_realloc;
  */
 static void __attribute__((constructor(101))) mm_legacy_constructor()
 {
-  bool use_mm = !getenv("SIMGRID_MALLOC_NO_USE_MM");
-  if (use_mm) {
+  __malloc_use_mmalloc = getenv(MC_ENV_VARIABLE) ? 1 : 0;
+  if (__malloc_use_mmalloc) {
     __mmalloc_current_heap = mmalloc_preinit();
   } else {
     mm_real_realloc  = (mm_realloc_t) dlsym(RTLD_NEXT, "realloc");
@@ -73,9 +86,25 @@ static void __attribute__((constructor(101))) mm_legacy_constructor()
   }
 }
 
+void* malloc_no_memset(size_t n)
+{
+  if (!__malloc_use_mmalloc) {
+    return mm_real_malloc(n);
+  }
+
+  xbt_mheap_t mdp = GET_HEAP();
+  if (!mdp)
+    return NULL;
+
+  LOCK(mdp);
+  void *ret = mmalloc_no_memset(mdp, n);
+  UNLOCK(mdp);
+  return ret;
+}
+
 void *malloc(size_t n)
 {
-  if (!__mmalloc_current_heap) {
+  if (!__malloc_use_mmalloc) {
     return mm_real_malloc(n);
   }
 
@@ -91,7 +120,7 @@ void *malloc(size_t n)
 
 void *calloc(size_t nmemb, size_t size)
 {
-  if (!__mmalloc_current_heap) {
+  if (!__malloc_use_mmalloc) {
     return mm_real_calloc(nmemb, size);
   }
 
@@ -111,7 +140,7 @@ void *calloc(size_t nmemb, size_t size)
 
 void *realloc(void *p, size_t s)
 {
-  if (!__mmalloc_current_heap) {
+  if (!__malloc_use_mmalloc) {
     return mm_real_realloc(p, s);
   }
 
@@ -127,14 +156,14 @@ void *realloc(void *p, size_t s)
 
 void free(void *p)
 {
-  if (!p)
-    return;
-
-  if (!__mmalloc_current_heap) {
+  if (!__malloc_use_mmalloc) {
     mm_real_free(p);
     return;
   }
 
+  if (!p)
+    return;
+
   xbt_mheap_t mdp = GET_HEAP();
   LOCK(mdp);
   mfree(mdp, p);