Skip to content

Commit a6b87c7

Browse files
committed
Added for sanity checking (no intervening mallocs in test).
1 parent 1e88cc0 commit a6b87c7

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

src/malloc-counter.cpp

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// clang++ -compatibility_version 1 -current_version 1 -dynamiclib malloc-counter.cpp printf.cpp -o malloc-counter.dylib
2+
3+
4+
// -*- C++ -*-
5+
6+
#ifndef HL_MACINTERPOSE_H
7+
#define HL_MACINTERPOSE_H
8+
9+
// The interposition data structure (just pairs of function pointers),
10+
// used an interposition table like the following:
11+
//
12+
13+
typedef struct interpose_s {
14+
void *new_func;
15+
void *orig_func;
16+
} interpose_t;
17+
18+
#define MAC_INTERPOSE(newf,oldf) __attribute__((used)) \
19+
static const interpose_t macinterpose##newf##oldf \
20+
__attribute__ ((section("__DATA, __interpose"))) = \
21+
{ (void *) newf, (void *) oldf }
22+
23+
#endif
24+
25+
#include <stdlib.h>
26+
#include <malloc/malloc.h>
27+
#include <stdio.h>
28+
#include <unistd.h>
29+
30+
#include "printf.h"
31+
32+
// For use by the replacement printf routines (see
33+
// https://github.com/mpaland/printf)
34+
extern "C" void _putchar(char ch) { ::write(1, (void *)&ch, 1); }
35+
36+
static int mallocs = 0;
37+
static int frees = 0;
38+
39+
extern "C" void * replace_malloc(size_t sz) {
40+
auto ptr = ::malloc(sz);
41+
++mallocs;
42+
printf_("malloc(%lu): %d\n", sz, mallocs);
43+
return ptr;
44+
}
45+
46+
extern "C" void replace_free(void * ptr) {
47+
++frees;
48+
printf_("frees: %d\n", frees);
49+
::free(ptr);
50+
}
51+
52+
MAC_INTERPOSE(replace_malloc, malloc);
53+
MAC_INTERPOSE(replace_free, free);
54+

0 commit comments

Comments
 (0)