-
Notifications
You must be signed in to change notification settings - Fork 3
/
tabarnac.cpp
513 lines (418 loc) · 13.8 KB
/
tabarnac.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
/*
* Copyright (C) 2015 Diener, Matthias <[email protected]> and Beniamine, David <[email protected]>
* Author: Beniamine, David <[email protected]>
* Author: Diener, Matthias <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <map>
#include <array>
#include <cmath>
#include <cstring>
#include <fstream>
#include <tuple>
#include <unistd.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <libelf/libelf.h>
#include <libelf/gelf.h>
#include <execinfo.h>
#include "pin.H"
#define REAL_TID(tid) ((tid)>=2 ? (tid)-1 : (tid))
#define ACC_T_READ 0
#define ACC_T_WRITE 1
char TYPE_NAME[2]={'R','W'};
const int MAXTHREADS = 1024;
int PAGESIZE;
unsigned int REAL_PAGESIZE;
KNOB<int> INTERVAL(KNOB_MODE_WRITEONCE, "pintool", "i", "0", "print interval (ms) (0=disable)");
struct{
string sym;
ADDRINT sz;
int ended; // 0 if the malloc is not completed (missing ret val)
} Allocs[MAXTHREADS+1];
ofstream fstructStream;
int num_threads = 0;
array<unordered_map<UINT64, UINT64>, MAXTHREADS+1> pagemap[2];
array<unordered_map<UINT64, UINT64>, MAXTHREADS+1> ftmap;
map<UINT32, UINT32> pidmap; // pid -> tid
array<UINT64, MAXTHREADS> stacksize; // stack size of each thread in pages
array<UINT64, MAXTHREADS> stackmax; // tid -> stack base address from file (unpinned application)
map<UINT32, UINT64> stackmap; // stack base address from pinned application
string img_name;
static inline
UINT64 get_tsc()
{
#if defined(__i386) || defined(__x86_64__)
unsigned int lo, hi;
__asm__ __volatile__ (
"cpuid \n"
"rdtsc"
: "=a"(lo), "=d"(hi) /* outputs */
: "a"(0) /* inputs */
: "%ebx", "%ecx"); /* clobbers*/
return ((UINT64)lo) | (((UINT64)hi) << 32);
#elif defined(__ia64)
UINT64 r;
__asm__ __volatile__ ("mov %0=ar.itc" : "=r" (r) :: "memory");
return r;
#else
#error "architecture not supported"
#endif
}
VOID do_numa(ADDRINT addr, THREADID tid, ADDRINT type)
{
UINT64 page = addr >> PAGESIZE;
tid=REAL_TID(tid);
if (pagemap[type][tid][page]++ == 0 && pagemap[(type+1)%2][tid][page]==0)
ftmap[tid][page] = get_tsc();
}
VOID trace_memory_page(INS ins, VOID *v)
{
if (INS_IsMemoryRead(ins))
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)do_numa, IARG_MEMORYREAD_EA, IARG_THREAD_ID,IARG_UINT32,ACC_T_READ, IARG_END);
if (INS_HasMemoryRead2(ins))
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)do_numa, IARG_MEMORYREAD2_EA, IARG_THREAD_ID, IARG_UINT32,ACC_T_READ,IARG_END);
if (INS_IsMemoryWrite(ins))
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)do_numa, IARG_MEMORYWRITE_EA, IARG_THREAD_ID, IARG_UINT32,ACC_T_WRITE, IARG_END);
}
long GetStackSize()
{
struct rlimit sl;
int returnVal = getrlimit(RLIMIT_STACK, &sl);
if (returnVal == -1)
{
cerr << "Error. errno: " << errno << endl;
}
return sl.rlim_cur;
}
VOID ThreadStart(THREADID tid, CONTEXT *ctxt, INT32 flags, VOID *v)
{
__sync_add_and_fetch(&num_threads, 1);
if (num_threads>=MAXTHREADS+1) {
cerr << "ERROR: num_threads (" << num_threads << ") higher than MAXTHREADS (" << MAXTHREADS << ")." << endl;
}
int pid = PIN_GetTid();
pidmap[pid] = REAL_TID(tid);
stackmap[pid] = PIN_GetContextReg(ctxt, REG_STACK_PTR) >> PAGESIZE;
// Print Tid, StackMin, StackSize
ofstream ofs;
if(tid==0)
{
ofs.open(img_name + ".stackmap.csv");
ofs << "tid,stackmax,sz"<<endl;
}
else
{
ofs.open(img_name + ".stackmap.csv", std::ios_base::app);
}
ofs << REAL_TID(tid) <<"," << stackmap[pid] <<","<< GetStackSize() << endl;
ofs.close();
}
void print_numa()
{
int real_tid[MAXTHREADS+1];
unordered_map<UINT64, array<UINT64, MAXTHREADS+1>> finalmap[2];
unordered_map<UINT64, pair<UINT64, UINT32>> finalft;
int i = 0;
static long n = 0;
ofstream f;
char fname[255];
if (INTERVAL)
sprintf(fname, "%s.%06ld.page.csv", img_name.c_str(), n++);
else
sprintf(fname, "%s.full.page.csv", img_name.c_str());
cout << ">>> " << fname << endl;
f.open(fname);
for (auto it : pidmap){
real_tid[it.second] = i++;
cout << it.second << "->" << i-1 << " Stack " << stackmap[it.first] << " " << stacksize[i-1] << endl;
}
f << "addr,firstacc,type";
for (int i = 0; i<num_threads; i++)
f << ",T" << i;
f << "\n";
// determine which thread accessed each page first
for (int tid = 0; tid<num_threads; tid++) {
for(int i=0; i < 2; ++i){
for (auto it : pagemap[i][tid]) {
//TODO
finalmap[i][it.first][tid] = pagemap[i][tid][it.first];
if (finalft[it.first].first == 0 || finalft[it.first].first > ftmap[tid][it.first])
finalft[it.first] = make_pair(ftmap[tid][it.first], real_tid[tid]);
}
}
}
// fix stack and print pages to csv
for(int i=0; i < 2; ++i)
{
for(auto it : finalmap[i]) {
UINT64 pageaddr = it.first;
f << pageaddr << "," << finalft[it.first].second<< ","<< TYPE_NAME[i] ;
for (int i=0; i<num_threads; i++)
f << "," << it.second[real_tid[i]];
f << "\n";
}
}
f.close();
}
VOID mythread(VOID * arg)
{
while(!PIN_IsProcessExiting()) {
PIN_Sleep(INTERVAL ? INTERVAL : 100);
if (INTERVAL == 0)
continue;
print_numa();
// for(auto it : pagemap)
// fill(begin(it.second), end(it.second), 0);
}
}
//retrieve structures names address and size
int getStructs(const char* file);
string get_struct_name(string str, int ln, string fname, int rec);
string get_complex_struct_name(int ln, string fname)
{
ifstream fstr(fname);
int lastmalloc=0;
// Find the real malloc line
string line,allocstr;
for(int i=0; i< ln; ++i)
{
getline(fstr, line);
if(line.find("alloc")!=string::npos)
{
allocstr=line;
lastmalloc=i;
}
}
fstr.close();
if(allocstr.find("=")==string::npos)
{
/*
* Allocation split among several lines,
* we assume it looks like
* foo =
* malloc(bar)
* Note:
* if foo and '=' are on different lines, we will give up
*/
fstr.open(fname);
for(int i=0; i< lastmalloc; ++i)
{
getline(fstr, line);
if(line.find("=")!=string::npos)
allocstr=line;
}
fstr.close();
}
//Now that we have the good line, extract the struct name
return get_struct_name(allocstr, ln, fname, 1/*forbid recursive calls*/);
}
string get_struct_name(string str, int ln, string fname, int hops)
{
if( str.find(string("alloc"))==string::npos && hops==0)
return get_complex_struct_name(ln, fname); //Return Ip is not malloc line
// Remove everything after first '='
string ret=str.substr(0,str.find('='));
//remove trailing whitespaces
while(ret.back()==' ')
ret.resize(ret.size()-1);
// Take the last word
ret=ret.substr(ret.find_last_of(string(" )*"))+1);
// Our search have failed, it will be an anonymous malloc
if(ret.compare("")==0)
{
cerr << "Unable to find a suitable alloc name for file "
<< fname << " l: " << ln << endl;
return string("AnonymousStruct");
}
return ret;
}
VOID PREMALLOC(ADDRINT retip, THREADID tid, ADDRINT sz)
{
int col, ln;
int id=REAL_TID(tid);
string fname;
if( (unsigned int) sz >= REAL_PAGESIZE)
{
PIN_LockClient();
PIN_GetSourceLocation (retip, &col, &ln, &fname);
PIN_UnlockClient();
//TODO: optimize this to read file only once
ifstream fstr(fname);
string line;
if(!fstr)
{
cerr << "Can't open file '" << fname << "', malloc will be anonymous"<< endl;
cerr << "Have you compiled your program with '-g' flag ?" <<endl;
Allocs[id].sym="AnonymousStruct";
}
else
{
for(int i=0; i< ln; ++i)
getline(fstr, line);
fstr.close();
Allocs[id].sym=get_struct_name(line, ln, fname, 0/*allow recursive calls*/);
}
Allocs[id].sz=sz;
Allocs[id].ended=0;
}
}
VOID POSTMALLOC(ADDRINT ret, THREADID tid)
{
int id=REAL_TID(tid);
static int anonymousId=0;
if (Allocs[id].ended==0)
{
fstructStream << Allocs[id].sym;
if(Allocs[id].sym.compare("AnonymousStruct")==0)
fstructStream << anonymousId++;
fstructStream <<","<<ret<<","<<Allocs[id].sz<<endl;
Allocs[id].ended=1;
}
}
VOID binName(IMG img, VOID *v)
{
if (IMG_IsMainExecutable(img))
{
img_name = basename(IMG_Name(img).c_str());
char fname[255];
sprintf(fname, "%s.structs.csv", img_name.c_str());
fstructStream.open(fname);
fstructStream << "name,start,sz" << endl;
}
getStructs(IMG_Name(img).c_str());
RTN mallocRtn = RTN_FindByName(img, "malloc");
if (RTN_Valid(mallocRtn))
{
RTN_Open(mallocRtn);
RTN_InsertCall(mallocRtn, IPOINT_BEFORE, (AFUNPTR)PREMALLOC,
IARG_RETURN_IP, IARG_THREAD_ID,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0, IARG_END);
RTN_InsertCall(mallocRtn, IPOINT_AFTER, (AFUNPTR)POSTMALLOC,
IARG_FUNCRET_EXITPOINT_VALUE, IARG_THREAD_ID, IARG_END);
RTN_Close(mallocRtn);
}
}
VOID Fini(INT32 code, VOID *v)
{
print_numa();
fstructStream.close();
cout << endl << "MAXTHREADS: " << MAXTHREADS << " PAGESIZE: " << PAGESIZE << " INTERVAL: " << INTERVAL << endl << endl;
}
int main(int argc, char *argv[])
{
PIN_InitSymbols();
if (PIN_Init(argc,argv)) return 1;
REAL_PAGESIZE=sysconf(_SC_PAGESIZE);
PAGESIZE = log2(REAL_PAGESIZE);
THREADID t = PIN_SpawnInternalThread(mythread, NULL, 0, NULL);
if (t!=1)
cerr << "ERROR internal thread " << t << endl;
cout << endl << "MAXTHREADS: " << MAXTHREADS << " PAGESIZE: " << PAGESIZE << " INTERVAL: " << INTERVAL << endl << endl;
INS_AddInstrumentFunction(trace_memory_page, 0);
IMG_AddInstrumentFunction(binName, 0);
PIN_AddThreadStartFunction(ThreadStart, 0);
PIN_AddFiniFunction(Fini, 0);
PIN_StartProgram();
}
/*
* The following function is an adaptation of the libelf-howto.c from:
* http://em386.blogspot.com
*
*/
#define ERR -1
int getStructs(const char* file)
{
Elf *elf; /* Our Elf pointer for libelf */
Elf_Scn *scn=NULL; /* Section Descriptor */
Elf_Data *edata=NULL; /* Data Descriptor */
GElf_Sym sym; /* Symbol */
GElf_Shdr shdr; /* Section Header */
int fd; // File Descriptor
char *base_ptr; // ptr to our object in memory
struct stat elf_stats; // fstat struct
cout << "Retrieving data structures from file "<< file << endl;
if((fd = open(file, O_RDONLY)) == ERR)
{
cerr << "couldnt open" << file << endl;
return ERR;
}
if((fstat(fd, &elf_stats)))
{
cerr << "could not fstat" << file << endl;
close(fd);
return ERR;
}
if((base_ptr = (char *) malloc(elf_stats.st_size)) == NULL)
{
cerr << "could not malloc" << endl;
close(fd);
return ERR;
}
if((read(fd, base_ptr, elf_stats.st_size)) < elf_stats.st_size)
{
cerr << "could not read" << file << endl;
free(base_ptr);
close(fd);
return ERR;
}
/* Check libelf version first */
if(elf_version(EV_CURRENT) == EV_NONE)
{
cerr << "WARNING Elf Library is out of date!" << endl;
}
elf = elf_begin(fd, ELF_C_READ, NULL); // Initialize 'elf' pointer to our file descriptor
elf = elf_begin(fd, ELF_C_READ, NULL);
int symbol_count;
int i;
while((scn = elf_nextscn(elf, scn)) != NULL)
{
gelf_getshdr(scn, &shdr);
// Get the symbol table
if(shdr.sh_type == SHT_SYMTAB)
{
// edata points to our symbol table
edata = elf_getdata(scn, edata);
// how many symbols are there? this number comes from the size of
// the section divided by the entry size
symbol_count = shdr.sh_size / shdr.sh_entsize;
// loop through to grab all symbols
for(i = 0; i < symbol_count; i++)
{
// libelf grabs the symbol data using gelf_getsym()
gelf_getsym(edata, i, &sym);
// Keep only objects big enough to be data structures
if(ELF32_ST_TYPE(sym.st_info)==STT_OBJECT &&
sym.st_size >= REAL_PAGESIZE)
{
fstructStream << elf_strptr(elf, shdr.sh_link, sym.st_name) <<
"," << sym.st_value << "," << sym.st_size << endl;
}
}
}
}
return 0;
}