forked from soot-oss/soot
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPhaseDumper.java
More file actions
428 lines (393 loc) · 14.3 KB
/
PhaseDumper.java
File metadata and controls
428 lines (393 loc) · 14.3 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
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
package soot.util;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 John Jorgensen
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.G;
import soot.Printer;
import soot.Scene;
import soot.Singletons;
import soot.SootClass;
import soot.SootMethod;
import soot.options.Options;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.graph.ExceptionalGraph;
import soot.util.cfgcmd.CFGToDotGraph;
import soot.util.dot.DotGraph;
/**
* The <tt>PhaseDumper</tt> is a debugging aid. It maintains two lists of phases to be debugged. If a phase is on the
* <code>bodyDumpingPhases</code> list, then the intermediate representation of the bodies being manipulated by the phase is
* dumped before and after the phase is applied. If a phase is on the <code>cfgDumpingPhases</code> list, then whenever a CFG
* is constructed during the phase, a dot file is dumped representing the CFG constructed.
*/
public class PhaseDumper {
private static final Logger logger = LoggerFactory.getLogger(PhaseDumper.class);
private static final String ALL_WILDCARD = "ALL";
private final PhaseStack phaseStack = new PhaseStack();
// As a minor optimization, we leave these lists null in the case were
// no phases at all are to be dumped, which is the most likely case.
private List<String> bodyDumpingPhases = null;
private List<String> cfgDumpingPhases = null;
// soot.Printer itself needs to create a BriefUnitGraph in order
// to format the text for a method's instructions, so this flag is
// a hack to avoid dumping graphs that we create in the course of
// dumping bodies or other graphs.
//
// Note that this hack would not work if a PhaseDumper might be
// accessed by multiple threads. So long as there is a single
// active PhaseDumper accessed through soot.G, it seems
// safe to assume it will be accessed by only a single thread.
private boolean alreadyDumping = false;
private class PhaseStack extends ArrayList<String> {
// We eschew java.util.Stack to avoid synchronization overhead.
private static final int initialCapacity = 4;
private static final String EMPTY_STACK_PHASE_NAME = "NOPHASE";
PhaseStack() {
super(initialCapacity);
}
String currentPhase() {
if (this.isEmpty()) {
return EMPTY_STACK_PHASE_NAME;
} else {
return this.get(this.size() - 1);
}
}
String pop() {
return this.remove(this.size() - 1);
}
String push(String phaseName) {
this.add(phaseName);
return phaseName;
}
}
public PhaseDumper(Singletons.Global g) {
List<String> bodyPhases = Options.v().dump_body();
if (!bodyPhases.isEmpty()) {
bodyDumpingPhases = bodyPhases;
}
List<String> cfgPhases = Options.v().dump_cfg();
if (!cfgPhases.isEmpty()) {
cfgDumpingPhases = cfgPhases;
}
}
/**
* Returns the single instance of <code>PhaseDumper</code>.
*
* @return Soot's <code>PhaseDumper</code>.
*/
public static PhaseDumper v() {
return G.v().soot_util_PhaseDumper();
}
private boolean isBodyDumpingPhase(String phaseName) {
return ((bodyDumpingPhases != null)
&& (bodyDumpingPhases.contains(phaseName) || bodyDumpingPhases.contains(ALL_WILDCARD)));
}
private boolean isCFGDumpingPhase(String phaseName) {
if (cfgDumpingPhases == null) {
return false;
}
if (cfgDumpingPhases.contains(ALL_WILDCARD)) {
return true;
} else {
while (true) { // loop exited by "return" or "break".
if (cfgDumpingPhases.contains(phaseName)) {
return true;
}
// Go on to check if phaseName is a subphase of a
// phase in cfgDumpingPhases.
int lastDot = phaseName.lastIndexOf('.');
if (lastDot < 0) {
break;
} else {
phaseName = phaseName.substring(0, lastDot);
}
}
return false;
}
}
private static File makeDirectoryIfMissing(Body b) throws IOException {
StringBuilder buf = new StringBuilder(soot.SourceLocator.v().getOutputDir());
buf.append(File.separatorChar);
buf.append(b.getMethod().getDeclaringClass().getName());
buf.append(File.separatorChar);
buf.append(b.getMethod().getSubSignature().replace('<', '[').replace('>', ']'));
File dir = new File(buf.toString());
if (dir.exists()) {
if (!dir.isDirectory()) {
throw new IOException(dir.getPath() + " exists but is not a directory.");
}
} else {
if (!dir.mkdirs()) {
throw new IOException("Unable to mkdirs " + dir.getPath());
}
}
return dir;
}
private static PrintWriter openBodyFile(Body b, String baseName) throws IOException {
File dir = makeDirectoryIfMissing(b);
String filePath = dir.toString() + File.separatorChar + baseName;
return new PrintWriter(new java.io.FileOutputStream(filePath));
}
/**
* Returns the next available name for a graph file.
*/
private static String nextGraphFileName(Body b, String baseName) throws IOException {
// We number output files to allow multiple graphs per phase.
File dir = makeDirectoryIfMissing(b);
final String prefix = dir.toString() + File.separatorChar + baseName;
File file = null;
int fileNumber = 0;
do {
file = new File(prefix + fileNumber + DotGraph.DOT_EXTENSION);
fileNumber++;
} while (file.exists());
return file.toString();
}
private static void deleteOldGraphFiles(final Body b, final String phaseName) {
try {
final File dir = makeDirectoryIfMissing(b);
final File[] toDelete = dir.listFiles(new java.io.FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(phaseName) && name.endsWith(DotGraph.DOT_EXTENSION);
}
});
if (toDelete != null) {
for (File element : toDelete) {
element.delete();
}
}
} catch (IOException e) {
// Don't abort execution because of an I/O error, but report the error.
logger.debug("PhaseDumper.dumpBody() caught: " + e.toString());
logger.error(e.getMessage(), e);
}
}
public void dumpBody(Body b, String baseName) {
final Printer printer = Printer.v();
alreadyDumping = true;
try (PrintWriter out = openBodyFile(b, baseName)) {
printer.setOption(Printer.USE_ABBREVIATIONS);
printer.printTo(b, out);
} catch (IOException e) {
// Don't abort execution because of an I/O error, but let
// the user know.
logger.debug("PhaseDumper.dumpBody() caught: " + e.toString());
logger.error(e.getMessage(), e);
} finally {
alreadyDumping = false;
}
}
private void dumpAllBodies(String baseName, boolean deleteGraphFiles) {
for (SootClass cls : Scene.v().getClasses(SootClass.BODIES)) {
for (SootMethod method : cls.getMethods()) {
if (method.hasActiveBody()) {
Body body = method.getActiveBody();
if (deleteGraphFiles) {
deleteOldGraphFiles(body, baseName);
}
dumpBody(body, baseName);
}
}
}
}
/**
* Tells the <code>PhaseDumper</code> that a {@link Body} transforming phase has started, so that it can dump the phases's
* “before” file. If the phase is to be dumped, <code>dumpBefore</code> deletes any old graph files dumped
* during previous runs of the phase.
*
* @param b
* the {@link Body} being transformed.
* @param phaseName
* the name of the phase that has just started.
*/
public void dumpBefore(Body b, String phaseName) {
phaseStack.push(phaseName);
if (isBodyDumpingPhase(phaseName)) {
deleteOldGraphFiles(b, phaseName);
dumpBody(b, phaseName + ".in");
}
}
/**
* Tells the <code>PhaseDumper</code> that a {@link Body} transforming phase has ended, so that it can dump the phases's
* “after” file.
*
* @param b
* the {@link Body} being transformed.
*
* @param phaseName
* the name of the phase that has just ended.
*
* @throws IllegalArgumentException
* if <code>phaseName</code> does not match the <code>PhaseDumper</code>'s record of the current phase.
*/
public void dumpAfter(Body b, String phaseName) {
String poppedPhaseName = phaseStack.pop();
if (poppedPhaseName != phaseName) {
throw new IllegalArgumentException("dumpAfter(" + phaseName + ") when poppedPhaseName == " + poppedPhaseName);
}
if (isBodyDumpingPhase(phaseName)) {
dumpBody(b, phaseName + ".out");
}
}
/**
* Tells the <code>PhaseDumper</code> that a {@link Scene} transforming phase has started, so that it can dump the phases's
* “before” files. If the phase is to be dumped, <code>dumpBefore</code> deletes any old graph files dumped
* during previous runs of the phase.
*
* @param phaseName
* the name of the phase that has just started.
*/
public void dumpBefore(String phaseName) {
phaseStack.push(phaseName);
if (isBodyDumpingPhase(phaseName)) {
dumpAllBodies(phaseName + ".in", true);
}
}
/**
* Tells the <code>PhaseDumper</code> that a {@link Scene} transforming phase has ended, so that it can dump the phases's
* “after” files.
*
* @param phaseName
* the name of the phase that has just ended.
*
* @throws IllegalArgumentException
* if <code>phaseName</code> does not match the <code>PhaseDumper</code>'s record of the current phase.
*/
public void dumpAfter(String phaseName) {
String poppedPhaseName = phaseStack.pop();
if (poppedPhaseName != phaseName) {
throw new IllegalArgumentException("dumpAfter(" + phaseName + ") when poppedPhaseName == " + poppedPhaseName);
}
if (isBodyDumpingPhase(phaseName)) {
dumpAllBodies(phaseName + ".out", false);
}
}
/**
* Asks the <code>PhaseDumper</code> to dump the passed {@link DirectedGraph} if the current phase is being dumped.
*
* @param g
* the graph to dump.
* @param b
* the {@link Body} represented by <code>g</code>.
*/
public <N> void dumpGraph(DirectedGraph<N> g, Body b) {
dumpGraph(g, b, false);
}
/**
* Asks the <code>PhaseDumper</code> to dump the passed {@link DirectedGraph} if the current phase is being dumped or
* {@code skipPhaseCheck == true}.
*
* @param g
* the graph to dump.
* @param b
* the {@link Body} represented by <code>g</code>.
* @param skipPhaseCheck
*/
public <N> void dumpGraph(DirectedGraph<N> g, Body b, boolean skipPhaseCheck) {
if (!alreadyDumping) {
try {
alreadyDumping = true;
String phaseName = phaseStack.currentPhase();
if (skipPhaseCheck || isCFGDumpingPhase(phaseName)) {
try {
String outputFile = nextGraphFileName(b, phaseName + '-' + getClassIdent(g) + '-');
CFGToDotGraph drawer = new CFGToDotGraph();
drawer.drawCFG(g, b).plot(outputFile);
} catch (IOException e) {
// Don't abort execution because of an I/O error, but
// report the error.
logger.debug("PhaseDumper.dumpBody() caught: " + e.toString());
logger.error(e.getMessage(), e);
}
}
} finally {
alreadyDumping = false;
}
}
}
/**
* Asks the <code>PhaseDumper</code> to dump the passed {@link ExceptionalGraph} if the current phase is being dumped.
*
* @param g
* the graph to dump.
*/
public <N> void dumpGraph(ExceptionalGraph<N> g) {
dumpGraph(g, false);
}
/**
* Asks the <code>PhaseDumper</code> to dump the passed {@link ExceptionalGraph} if the current phase is being dumped or
* {@code skipPhaseCheck == true}.
*
* @param g
* the graph to dump.
* @param skipPhaseCheck
*/
public <N> void dumpGraph(ExceptionalGraph<N> g, boolean skipPhaseCheck) {
if (!alreadyDumping) {
try {
alreadyDumping = true;
String phaseName = phaseStack.currentPhase();
if (skipPhaseCheck || isCFGDumpingPhase(phaseName)) {
try {
String outputFile = nextGraphFileName(g.getBody(), phaseName + '-' + getClassIdent(g) + '-');
CFGToDotGraph drawer = new CFGToDotGraph();
drawer.setShowExceptions(Options.v().show_exception_dests());
drawer.drawCFG(g).plot(outputFile);
} catch (IOException e) {
// Don't abort execution because of an I/O error, but
// report the error.
logger.debug("PhaseDumper.dumpBody() caught: " + e.toString());
logger.error(e.getMessage(), e);
}
}
} finally {
alreadyDumping = false;
}
}
}
/**
* A utility routine that returns the unqualified identifier naming the class of an object.
*
* @param obj
* The object whose class name is to be returned.
*/
private String getClassIdent(Object obj) {
String qualifiedName = obj.getClass().getName();
return qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1);
}
/**
* Prints the current stack trace, as a brute force tool for program understanding. This method appeared in response to the
* many times dumpGraph() was being called while the phase stack was empty. Turned out that the Printer needs to build a
* BriefUnitGraph in order to print a graph. Doh!
*/
public void printCurrentStackTrace() {
IOException e = new IOException("FAKE");
logger.error(e.getMessage(), e);
}
}