-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.cpp
83 lines (72 loc) · 2.78 KB
/
test.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <memory>
#include <dlfcn.h>
#include <cstdlib>
#include "rss.hpp"
int _new_count(void * handle) {
using callable_type = int (*) ();
callable_type libnew_get_new_count = reinterpret_cast<callable_type>(dlsym(handle, "get_new_count"));
if (!libnew_get_new_count) throw std::runtime_error("get_new_count not found");
return libnew_get_new_count();
}
int _malloc_count(void * handle) {
using callable_type = int (*) ();
callable_type libnew_get_malloc_count = reinterpret_cast<callable_type>(dlsym(handle, "get_malloc_count"));
if (!libnew_get_malloc_count) throw std::runtime_error("get_malloc_count not found");
return libnew_get_malloc_count();
}
std::string get_preload() {
const char* ld_preload = std::getenv("LD_PRELOAD");
if (ld_preload) return ld_preload;
const char* dyld_insert = std::getenv("DYLD_INSERT_LIBRARIES");
if (dyld_insert) return dyld_insert;
return "";
}
int main() {
try {
std::string preload = get_preload();
void * handle;
if (!preload.empty()) {
handle = dlopen(preload.c_str(),RTLD_LAZY);
} else {
throw std::runtime_error("Must provide LD_PRELOAD on linux and DYLD_INSERT_LIBRARIES on OS X");
}
std::clog << "nc1: " << _new_count(handle) << "\n";
std::clog << "mc1: " << _malloc_count(handle) << "\n";
memory_used();
{
std::clog << "long std::string\n";
std::string s("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
}
std::clog << "nc2: " << _new_count(handle) << "\n";
std::clog << "mc2: " << _malloc_count(handle) << "\n";
memory_used();
{
std::clog << "20 item unsigned int array\n";
std::unique_ptr<unsigned int[]> out_row(new unsigned int[20]);
}
std::clog << "nc3: " << _new_count(handle) << "\n";
std::clog << "mc3: " << _malloc_count(handle) << "\n";
memory_used();
{
std::clog << "direct malloc of unsigned int pointer\n";
unsigned int *ptr_one = (unsigned int *)malloc(sizeof(unsigned int));
free(ptr_one);
}
std::clog << "nc4: " << _new_count(handle) << "\n";
std::clog << "mc4: " << _malloc_count(handle) << "\n";
memory_used();
{
int* p1 = (int*)std::calloc(4, sizeof(int));
free(p1);
}
std::clog << "nc5: " << _new_count(handle) << "\n";
std::clog << "mc5: " << _malloc_count(handle) << "\n";
memory_used();
} catch (std::exception const& ex) {
std::clog << "Error: " << ex.what() << "\n";
return -1;
}
memory_used();
return 0;
}