-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnetcallgraph.cpp
More file actions
362 lines (302 loc) · 12.1 KB
/
Copy pathnetcallgraph.cpp
File metadata and controls
362 lines (302 loc) · 12.1 KB
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
/*
* File: rcovtrace.cpp
* Author: amoneger
*
* Created on September 4, 2015, 1:31 PM
*/
/*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2010 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. Redistributions
in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution. Neither the name of
the Intel Corporation nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
END_LEGAL */
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/syscall.h>
#include <sys/types.h> // mkfifo
#include <sys/stat.h> // mkfifo
#include <map>
#include <list>
#include <iostream>
#include <utility>
#include <vector>
#include <fstream>
#include <sstream>
#include "pin.H"
#ifdef _WIN32
#define linesep "\\"
#else
#define linesep "/"
#endif
// Force each thread's data to be in its own data cache line so that
// multiple threads do not contend for the same data cache line.
// This avoids the false sharing problem.
// See https://software.intel.com/sites/landingpage/pintool/docs/55942/Pin/html/index.html#InscountTLS
#define PADSIZE 56 // 64 byte line size: 64-8
#define INIT_CALLGRAPH_SIZE 1000
#define PIPE_NAME "/tmp/netcallgraph"
#if defined(__APPLE__)
#define SYS_ACCEPT (SYS_accept + 0x2000000)
#define SYS_READ (SYS_read + 0x2000000)
#define SYS_WRITE (SYS_write + 0x2000000)
#define SYS_CLOSE (SYS_close + 0x2000000)
#else
#define SYS_ACCEPT SYS_accept
#define SYS_READ SYS_read
#define SYS_WRITE SYS_write
#define SYS_CLOSE SYS_close
#endif
KNOB<std::string> KnobModuleList(KNOB_MODE_APPEND, "pintool", "m", "", "whitelist of module names, use more than once");
size_t traceCount = 0;
static BOOL whitelistMode = false;
std::map<THREADID, struct TraceInfo> threadInfoMap;
std::map<std::string, std::pair<ADDRINT,ADDRINT> > moduleList;
static TLS_KEY tlsKey;
int pipe_fd = -1;
struct BBLEdge {
ADDRINT parent;
ADDRINT child;
};
struct TraceInfo {
ADDRINT prevAddress;
std::vector<struct BBLEdge> *callGraph;
size_t hitCount;
};
struct ThreadInfo {
UINT32 hasHitAccept;
UINT32 fd;
UINT8 _pad[PADSIZE];
};
UINT32 Usage() {
std::cout << "CodeCoverage tool for dumping BBL control flows" << std::endl;
std::cout << KNOB_BASE::StringKnobSummary() << std::endl;
return 2;
}
static inline size_t getAddressOffset(IMG img, ADDRINT address) {
return address - IMG_LowAddress(img);
}
static inline string basename(const string &fullpath) {
ssize_t index = fullpath.rfind(linesep);
return std::string(fullpath.substr(index + 1));
}
static inline BOOL requiresLogging(ADDRINT bblParentAddress, ADDRINT bblChildAddress) {
std::map<std::string, std::pair<ADDRINT,ADDRINT> >::iterator module;
for (module = moduleList.begin(); module != moduleList.end(); module++) {
if ((module->second.first <= bblParentAddress && bblParentAddress <= module->second.second) ||
(module->second.first <= bblChildAddress && bblChildAddress <= module->second.second)) {
return TRUE;
}
}
return FALSE;
}
static std::ostringstream* logCallGraph(const THREADID tid, const std::vector<struct BBLEdge> *callGraph) {
std::vector<struct BBLEdge>::const_iterator edge;
std::ostringstream *traceBuffer = new std::ostringstream();
for (edge = callGraph->begin(); edge != callGraph->end(); edge++) {
if (requiresLogging(edge->parent, edge->child)) {
PIN_LockClient();
IMG parentImg = IMG_FindByAddress(edge->parent);
IMG childImg = IMG_FindByAddress(edge->child);
PIN_UnlockClient();
std::string parentImgName = basename(IMG_Name(parentImg));
std::string childImgName = basename(IMG_Name(childImg));
size_t parentOfset = getAddressOffset(parentImg, edge->parent);
size_t childOffset = getAddressOffset(childImg, edge->child);
*traceBuffer << parentImgName << "+" << parentOfset << "->" << childImgName << "+" << childOffset << ";";
}
}
return traceBuffer;
}
static VOID logBasicBlock(THREADID tid, ADDRINT address) {
// We have a new thread here. Initialize the per thread call graph
if (threadInfoMap.count(tid) != 0) {
TraceInfo *traceInfo = &(threadInfoMap[tid]);
if (traceInfo->prevAddress != 0) {
BBLEdge edge = {traceInfo->prevAddress, address};
traceInfo->prevAddress = address;
(traceInfo->callGraph)->push_back(edge);
traceInfo->hitCount++;
} else {
traceInfo->prevAddress = address;
}
}
}
static VOID traceBasicBlocks(TRACE trace, VOID *v) {
for (BBL bbl = TRACE_BblHead(trace); BBL_Valid(bbl); bbl = BBL_Next(bbl)) {
INS first_ins = BBL_InsHead(bbl);
INS last_ins = BBL_InsTail(bbl);
// Follow only conditional branches (CALL, RET, JNE, JZ, ...). Ignore unconditional JMPs
if ((INS_IsBranch(last_ins) && INS_HasFallThrough(last_ins)) || INS_IsCall(last_ins) || INS_IsRet(last_ins)) {
INS_InsertCall(first_ins, IPOINT_BEFORE, AFUNPTR(logBasicBlock), IARG_THREAD_ID, IARG_INST_PTR, IARG_END);
}
}
}
static VOID traceImageLoad(IMG img, VOID *v) {
ADDRINT start = IMG_LowAddress(img);
ADDRINT end = IMG_HighAddress(img);
std::map<std::string, std::pair<ADDRINT, ADDRINT> >::iterator module;
const std::string &fullpath = IMG_Name(img);
std::string imgName = basename(fullpath);
if (whitelistMode) {
for (module = moduleList.begin(); module != moduleList.end(); module++) {
if (module->first == imgName) {
module->second = std::make_pair(start, end);
}
}
} else {
moduleList[imgName] = std::make_pair(start,end);
}
}
static size_t pipeWrite(std::string data) {
size_t totalWriteLen = 0;
int writeLen = 0;
size_t dataLen = data.length();
while (totalWriteLen < dataLen) {
writeLen = write(pipe_fd, data.c_str() + totalWriteLen, dataLen - totalWriteLen);
if (writeLen < 1) {
break;
}
totalWriteLen += (size_t)writeLen;
}
return totalWriteLen;
}
static BOOL pipeWriteMessage(std::string msgType, size_t fd, std::string payload) {
std::ostringstream msgStream;
// Format is syscall name=trace\n
msgStream << msgType << ":" << fd << "=";
size_t msgLen = msgStream.str().length();
if ((pipeWrite(msgStream.str().c_str()) != msgLen) || (pipeWrite(payload) != payload.length())
|| pipeWrite(std::string("\n")) != 1) {
return FALSE;
}
return TRUE;
}
VOID traceSyscallEntry(THREADID tid, CONTEXT *ctx, SYSCALL_STANDARD std, VOID *v) {
ThreadInfo *threadInfo = static_cast<ThreadInfo*>(PIN_GetThreadData(tlsKey, tid));
ADDRINT syscallId = PIN_GetSyscallNumber(ctx, std);
ADDRINT fd = PIN_GetSyscallArgument(ctx, std, 0);
switch (syscallId) {
case SYS_ACCEPT:
threadInfo->hasHitAccept = 1;
break;
case SYS_READ:
if (threadInfo->fd == fd && threadInfoMap.count(tid) == 0) {
std::vector<struct BBLEdge> *callGraph = new std::vector<struct BBLEdge>(INIT_CALLGRAPH_SIZE);
TraceInfo traceInfo = {0, callGraph, 0};
threadInfoMap[tid] = traceInfo;
}
break;
case SYS_WRITE:
if (threadInfo->fd == fd && threadInfoMap.count(tid) != 0) {
TraceInfo *traceInfo = &(threadInfoMap[tid]);
std::ostringstream *traceBuffer = logCallGraph(tid, traceInfo->callGraph);
if (!pipeWriteMessage(string("write"), fd, traceBuffer->str())) {
std::cerr << "Failed to write trace to pipe" << std::endl;
}
delete traceBuffer;
delete traceInfo->callGraph;
threadInfoMap.erase(tid);
}
break;
case SYS_CLOSE:
if (threadInfo->fd == fd) {
if (threadInfoMap.count(tid) != 0) {
TraceInfo *traceInfo = &(threadInfoMap[tid]);
std::ostringstream *traceBuffer = logCallGraph(tid, traceInfo->callGraph);
if (!pipeWriteMessage(std::string("close"), fd, traceBuffer->str())) {
std::cerr << "Failed to write trace to pipe" << std::endl;
}
threadInfo->fd = 0;
delete traceBuffer;
delete traceInfo->callGraph;
threadInfoMap.erase(tid);
} else {
if (!pipeWriteMessage(std::string("close"), fd, std::string(""))) {
std::cerr << "Failed to write trace to pipe" << std::endl;
}
}
}
break;
default:
break;
}
}
VOID traceSyscallExit(THREADID tid, CONTEXT *ctx, SYSCALL_STANDARD std, VOID *v) {
ThreadInfo *threadInfo = static_cast<ThreadInfo*>(PIN_GetThreadData(tlsKey, tid));
if (threadInfo->hasHitAccept == 1) {
threadInfo->hasHitAccept = 0;
threadInfo->fd = PIN_GetSyscallReturn(ctx, std);
}
}
VOID traceThreadStart(THREADID tid, CONTEXT *ctx, INT32 flags, VOID *v)
{
ThreadInfo *threadInfo = new ThreadInfo;
threadInfo->hasHitAccept = 0;
PIN_SetThreadData(tlsKey, threadInfo, tid);
}
VOID traceThreadExit(THREADID tid, const CONTEXT *ctx, INT32 flags, VOID *v)
{
ThreadInfo *threadInfo = static_cast<ThreadInfo*>(PIN_GetThreadData(tlsKey, tid));
delete threadInfo;
PIN_SetThreadData(tlsKey, 0, tid);
}
int main(int argc, char **argv) {
PIN_InitSymbols();
if (PIN_Init(argc, argv)) {
return Usage();
}
for (size_t i = 0; i < KnobModuleList.NumberOfValues(); i++) {
std::string module = std::string(KnobModuleList.Value(i));
moduleList[module] = std::make_pair(0,0);
whitelistMode = true;
}
// Ignore SIGPIPEs. Just fail on write
signal(SIGPIPE, SIG_IGN);
// Create named pipe if it doesn't exist
struct stat buf;
if (stat(PIPE_NAME, &buf) != 0) {
if (mkfifo(PIPE_NAME, S_IREAD|S_IWRITE|S_IRGRP) != 0) {
std::cerr << "Failed to create named pipe at " << PIPE_NAME << ": " << strerror(errno) << std::endl;
exit(1);
}
}
std::cerr << "Opening named pipe " << PIPE_NAME << ". Halting until other end opened for read" << std::endl;
if ((pipe_fd = open(PIPE_NAME, O_WRONLY)) < 0) {
std::cerr << "Failed to open named pipe at " << PIPE_NAME << ": " << strerror(errno) << std::endl;
exit(1);
}
tlsKey = PIN_CreateThreadDataKey(NULL);
PIN_AddThreadStartFunction(traceThreadStart, 0);
PIN_AddThreadFiniFunction(traceThreadExit, 0);
PIN_AddSyscallEntryFunction(traceSyscallEntry, 0);
PIN_AddSyscallExitFunction(traceSyscallExit, 0);
TRACE_AddInstrumentFunction(traceBasicBlocks, 0);
IMG_AddInstrumentFunction(traceImageLoad, 0);
PIN_StartProgram();
return 0;
}