1 package Analysis.SSJava;
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.FileReader;
6 import java.io.FileWriter;
7 import java.io.IOException;
8 import java.util.ArrayList;
9 import java.util.Collections;
10 import java.util.Comparator;
11 import java.util.HashMap;
12 import java.util.HashSet;
13 import java.util.Iterator;
14 import java.util.LinkedList;
15 import java.util.List;
18 import java.util.Stack;
19 import java.util.Vector;
21 import IR.ClassDescriptor;
23 import IR.FieldDescriptor;
24 import IR.MethodDescriptor;
25 import IR.NameDescriptor;
28 import IR.SymbolTable;
29 import IR.TypeDescriptor;
30 import IR.VarDescriptor;
31 import IR.Tree.ArrayAccessNode;
32 import IR.Tree.AssignmentNode;
33 import IR.Tree.BlockExpressionNode;
34 import IR.Tree.BlockNode;
35 import IR.Tree.BlockStatementNode;
36 import IR.Tree.CastNode;
37 import IR.Tree.CreateObjectNode;
38 import IR.Tree.DeclarationNode;
39 import IR.Tree.ExpressionNode;
40 import IR.Tree.FieldAccessNode;
41 import IR.Tree.IfStatementNode;
43 import IR.Tree.LiteralNode;
44 import IR.Tree.LoopNode;
45 import IR.Tree.MethodInvokeNode;
46 import IR.Tree.NameNode;
47 import IR.Tree.OpNode;
48 import IR.Tree.ReturnNode;
49 import IR.Tree.SubBlockNode;
50 import IR.Tree.SwitchBlockNode;
51 import IR.Tree.SwitchStatementNode;
52 import IR.Tree.TertiaryNode;
53 import IR.Tree.TreeNode;
56 public class LocationInference {
59 SSJavaAnalysis ssjava;
61 List<ClassDescriptor> temp_toanalyzeList;
62 List<MethodDescriptor> temp_toanalyzeMethodList;
63 Map<MethodDescriptor, FlowGraph> mapMethodDescriptorToFlowGraph;
65 LinkedList<MethodDescriptor> toanalyze_methodDescList;
67 // map a method descriptor to its set of parameter descriptors
68 Map<MethodDescriptor, Set<Descriptor>> mapMethodDescriptorToParamDescSet;
70 // keep current descriptors to visit in fixed-point interprocedural analysis,
71 private Stack<MethodDescriptor> methodDescriptorsToVisitStack;
73 // map a class descriptor to a field lattice
74 private Map<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
76 // map a method descriptor to a method lattice
77 private Map<MethodDescriptor, SSJavaLattice<String>> md2lattice;
79 // map a method/class descriptor to a hierarchy graph
80 private Map<Descriptor, HierarchyGraph> mapDescriptorToHierarchyGraph;
82 // map a method/class descriptor to a skeleton hierarchy graph
83 private Map<Descriptor, HierarchyGraph> mapDescriptorToSkeletonHierarchyGraph;
85 private Map<Descriptor, HierarchyGraph> mapDescriptorToSimpleHierarchyGraph;
87 // map a method/class descriptor to a skeleton hierarchy graph with combination nodes
88 private Map<Descriptor, HierarchyGraph> mapDescriptorToCombineSkeletonHierarchyGraph;
90 // map a descriptor to a simple lattice
91 private Map<Descriptor, SSJavaLattice<String>> mapDescriptorToSimpleLattice;
93 // map a method descriptor to the set of method invocation nodes which are
94 // invoked by the method descriptor
95 private Map<MethodDescriptor, Set<MethodInvokeNode>> mapMethodDescriptorToMethodInvokeNodeSet;
97 private Map<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>> mapMethodInvokeNodeToArgIdxMap;
99 private Map<MethodInvokeNode, NTuple<Descriptor>> mapMethodInvokeNodeToBaseTuple;
101 private Map<MethodDescriptor, MethodLocationInfo> mapMethodDescToMethodLocationInfo;
103 private Map<ClassDescriptor, LocationInfo> mapClassToLocationInfo;
105 private Map<MethodDescriptor, Set<MethodDescriptor>> mapMethodToCalleeSet;
107 private Map<MethodDescriptor, Set<FlowNode>> mapMethodDescToParamNodeFlowsToReturnValue;
109 private Map<String, Vector<String>> mapFileNameToLineVector;
111 private Map<Descriptor, Integer> mapDescToDefinitionLine;
113 private Map<Descriptor, LocationSummary> mapDescToLocationSummary;
115 // maps a method descriptor to a sub global flow graph that captures all value flows caused by the
116 // set of callees reachable from the method
117 private Map<MethodDescriptor, GlobalFlowGraph> mapMethodDescriptorToSubGlobalFlowGraph;
119 private Map<MethodInvokeNode, Map<NTuple<Descriptor>, NTuple<Descriptor>>> mapMethodInvokeNodeToMapCallerArgToCalleeArg;
121 public static final String GLOBALLOC = "GLOBALLOC";
123 public static final String TOPLOC = "TOPLOC";
125 public static final String INTERLOC = "INTERLOC";
127 public static final String PCLOC = "PCLOC";
129 public static final String RLOC = "RLOC";
131 public static final Descriptor GLOBALDESC = new NameDescriptor(GLOBALLOC);
133 public static final Descriptor TOPDESC = new NameDescriptor(TOPLOC);
135 public static final Descriptor RETURNLOC = new NameDescriptor(RLOC);
137 public static String newline = System.getProperty("line.separator");
139 LocationInfo curMethodInfo;
141 boolean debug = true;
143 private static int locSeed = 0;
145 public LocationInference(SSJavaAnalysis ssjava, State state) {
146 this.ssjava = ssjava;
148 this.temp_toanalyzeList = new ArrayList<ClassDescriptor>();
149 this.temp_toanalyzeMethodList = new ArrayList<MethodDescriptor>();
150 this.mapMethodDescriptorToFlowGraph = new HashMap<MethodDescriptor, FlowGraph>();
151 this.cd2lattice = new HashMap<ClassDescriptor, SSJavaLattice<String>>();
152 this.md2lattice = new HashMap<MethodDescriptor, SSJavaLattice<String>>();
153 this.methodDescriptorsToVisitStack = new Stack<MethodDescriptor>();
154 this.mapMethodDescriptorToMethodInvokeNodeSet =
155 new HashMap<MethodDescriptor, Set<MethodInvokeNode>>();
156 this.mapMethodInvokeNodeToArgIdxMap =
157 new HashMap<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>>();
158 this.mapMethodDescToMethodLocationInfo = new HashMap<MethodDescriptor, MethodLocationInfo>();
159 this.mapMethodToCalleeSet = new HashMap<MethodDescriptor, Set<MethodDescriptor>>();
160 this.mapClassToLocationInfo = new HashMap<ClassDescriptor, LocationInfo>();
162 this.mapFileNameToLineVector = new HashMap<String, Vector<String>>();
163 this.mapDescToDefinitionLine = new HashMap<Descriptor, Integer>();
164 this.mapMethodDescToParamNodeFlowsToReturnValue =
165 new HashMap<MethodDescriptor, Set<FlowNode>>();
167 this.mapDescriptorToHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
168 this.mapMethodInvokeNodeToBaseTuple = new HashMap<MethodInvokeNode, NTuple<Descriptor>>();
170 this.mapDescriptorToSkeletonHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
171 this.mapDescriptorToCombineSkeletonHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
172 this.mapDescriptorToSimpleHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
174 this.mapDescriptorToSimpleLattice = new HashMap<Descriptor, SSJavaLattice<String>>();
176 this.mapDescToLocationSummary = new HashMap<Descriptor, LocationSummary>();
178 this.mapMethodDescriptorToSubGlobalFlowGraph = new HashMap<MethodDescriptor, GlobalFlowGraph>();
180 this.mapMethodInvokeNodeToMapCallerArgToCalleeArg =
181 new HashMap<MethodInvokeNode, Map<NTuple<Descriptor>, NTuple<Descriptor>>>();
185 public void setupToAnalyze() {
186 SymbolTable classtable = state.getClassSymbolTable();
187 temp_toanalyzeList.clear();
188 temp_toanalyzeList.addAll(classtable.getValueSet());
189 // Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
190 // public int compare(ClassDescriptor o1, ClassDescriptor o2) {
191 // return o1.getClassName().compareToIgnoreCase(o2.getClassName());
196 public void setupToAnalazeMethod(ClassDescriptor cd) {
198 SymbolTable methodtable = cd.getMethodTable();
199 temp_toanalyzeMethodList.clear();
200 temp_toanalyzeMethodList.addAll(methodtable.getValueSet());
201 Collections.sort(temp_toanalyzeMethodList, new Comparator<MethodDescriptor>() {
202 public int compare(MethodDescriptor o1, MethodDescriptor o2) {
203 return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
208 public boolean toAnalyzeMethodIsEmpty() {
209 return temp_toanalyzeMethodList.isEmpty();
212 public boolean toAnalyzeIsEmpty() {
213 return temp_toanalyzeList.isEmpty();
216 public ClassDescriptor toAnalyzeNext() {
217 return temp_toanalyzeList.remove(0);
220 public MethodDescriptor toAnalyzeMethodNext() {
221 return temp_toanalyzeMethodList.remove(0);
224 public void inference() {
226 // construct value flow graph
227 constructFlowGraph();
229 assignCompositeLocation();
233 constructHierarchyGraph();
235 debug_writeHierarchyDotFiles();
237 // calculate RETURNLOC,PCLOC
238 calculateExtraLocations();
240 simplifyHierarchyGraph();
242 debug_writeSimpleHierarchyDotFiles();
244 constructSkeletonHierarchyGraph();
246 debug_writeSkeletonHierarchyDotFiles();
248 insertCombinationNodes();
250 debug_writeSkeletonCombinationHierarchyDotFiles();
254 debug_writeLattices();
256 updateCompositeLocationAssignments();
258 generateMethodSummary();
260 generateAnnoatedCode();
266 public Map<NTuple<Descriptor>, NTuple<Descriptor>> getMapCallerArgToCalleeParam(
267 MethodInvokeNode min) {
269 if (!mapMethodInvokeNodeToMapCallerArgToCalleeArg.containsKey(min)) {
270 mapMethodInvokeNodeToMapCallerArgToCalleeArg.put(min,
271 new HashMap<NTuple<Descriptor>, NTuple<Descriptor>>());
274 return mapMethodInvokeNodeToMapCallerArgToCalleeArg.get(min);
277 public void addMapCallerArgToCalleeParam(MethodInvokeNode min, NTuple<Descriptor> callerArg,
278 NTuple<Descriptor> calleeParam) {
279 getMapCallerArgToCalleeParam(min).put(callerArg, calleeParam);
282 private void assignCompositeLocation() {
283 calculateGlobalValueFlowCompositeLocation();
284 translateCompositeLocationAssignmentToFlowGraph();
287 private void translateCompositeLocationAssignmentToFlowGraph() {
288 System.out.println("\nSSJAVA: Translate composite location assignments to flow graphs:");
289 MethodDescriptor methodEventLoopDesc = ssjava.getMethodContainingSSJavaLoop();
290 translateCompositeLocationAssignmentToFlowGraph(methodEventLoopDesc);
294 private void updateCompositeLocationAssignments() {
296 LinkedList<MethodDescriptor> methodDescList =
297 (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
299 while (!methodDescList.isEmpty()) {
300 MethodDescriptor md = methodDescList.removeLast();
302 System.out.println("\n#updateCompositeLocationAssignments=" + md);
304 FlowGraph flowGraph = getFlowGraph(md);
306 MethodSummary methodSummary = getMethodSummary(md);
308 Set<FlowNode> nodeSet = flowGraph.getNodeSet();
309 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
310 FlowNode node = (FlowNode) iterator.next();
311 System.out.println("-node=" + node + " node.getDescTuple=" + node.getDescTuple());
312 if (node.getCompositeLocation() != null) {
313 CompositeLocation compLoc = node.getCompositeLocation();
314 CompositeLocation updatedCompLoc = updateCompositeLocation(compLoc);
315 node.setCompositeLocation(updatedCompLoc);
316 System.out.println("---updatedCompLoc1=" + updatedCompLoc);
318 NTuple<Descriptor> descTuple = node.getDescTuple();
319 CompositeLocation compLoc = convertToCompositeLocation(md, descTuple);
320 compLoc = updateCompositeLocation(compLoc);
321 node.setCompositeLocation(compLoc);
322 System.out.println("---updatedCompLoc2=" + compLoc);
325 if (node.isDeclaratonNode()) {
326 Descriptor localVarDesc = node.getDescTuple().get(0);
327 CompositeLocation compLoc = updateCompositeLocation(node.getCompositeLocation());
328 methodSummary.addMapVarNameToInferCompLoc(localVarDesc, compLoc);
332 // update PCLOC and RETURNLOC if they have a composite location assignment
333 if (methodSummary.getRETURNLoc() != null) {
334 methodSummary.setRETURNLoc(updateCompositeLocation(methodSummary.getRETURNLoc()));
336 if (methodSummary.getPCLoc() != null) {
337 methodSummary.setPCLoc(updateCompositeLocation(methodSummary.getPCLoc()));
344 private CompositeLocation updateCompositeLocation(CompositeLocation compLoc) {
345 CompositeLocation updatedCompLoc = new CompositeLocation();
346 for (int i = 0; i < compLoc.getSize(); i++) {
347 Location loc = compLoc.get(i);
348 String nodeIdentifier = loc.getLocIdentifier();
349 Descriptor enclosingDesc = loc.getDescriptor();
351 if (!enclosingDesc.equals(GLOBALDESC)) {
352 LocationSummary locSummary = getLocationSummary(enclosingDesc);
353 locName = locSummary.getLocationName(nodeIdentifier);
355 locName = nodeIdentifier;
357 Location updatedLoc = new Location(enclosingDesc, locName);
358 updatedCompLoc.addLocation(updatedLoc);
361 return updatedCompLoc;
364 private void translateCompositeLocationAssignmentToFlowGraph(MethodDescriptor mdCaller) {
367 // First, assign a composite location to a node in the flow graph
368 GlobalFlowGraph callerGlobalFlowGraph = getSubGlobalFlowGraph(mdCaller);
370 FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
371 Map<Location, CompositeLocation> callerMapLocToCompLoc =
372 callerGlobalFlowGraph.getMapLocationToInferCompositeLocation();
373 Set<Location> methodLocSet = callerMapLocToCompLoc.keySet();
374 for (Iterator iterator = methodLocSet.iterator(); iterator.hasNext();) {
375 Location methodLoc = (Location) iterator.next();
376 if (methodLoc.getDescriptor().equals(mdCaller)) {
377 CompositeLocation inferCompLoc = callerMapLocToCompLoc.get(methodLoc);
378 assignCompositeLocationToFlowGraph(callerFlowGraph, methodLoc, inferCompLoc);
382 Set<MethodInvokeNode> minSet = mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
384 Set<MethodDescriptor> calleeSet = new HashSet<MethodDescriptor>();
385 for (Iterator iterator = minSet.iterator(); iterator.hasNext();) {
386 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
387 // need to translate a composite location that is started with the base
389 translateMapLocationToInferCompositeLocationToCalleeGraph(callerGlobalFlowGraph, min);
390 calleeSet.add(min.getMethod());
393 for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
394 MethodDescriptor callee = (MethodDescriptor) iterator.next();
395 translateCompositeLocationAssignmentToFlowGraph(callee);
400 public void assignCompositeLocationToFlowGraph(FlowGraph flowGraph, Location loc,
401 CompositeLocation inferCompLoc) {
402 Descriptor localDesc = loc.getLocDescriptor();
404 Set<FlowNode> nodeSet = flowGraph.getNodeSet();
405 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
406 FlowNode node = (FlowNode) iterator.next();
407 if (node.getDescTuple().startsWith(localDesc)) {
408 // need to assign the inferred composite location to this node
409 CompositeLocation newCompLoc = generateCompositeLocation(node.getDescTuple(), inferCompLoc);
410 node.setCompositeLocation(newCompLoc);
411 System.out.println("SET Node=" + node + " inferCompLoc=" + newCompLoc);
416 private CompositeLocation generateCompositeLocation(NTuple<Descriptor> nodeDescTuple,
417 CompositeLocation inferCompLoc) {
419 System.out.println("generateCompositeLocation=" + nodeDescTuple + " with inferCompLoc="
422 CompositeLocation newCompLoc = new CompositeLocation();
423 for (int i = 0; i < inferCompLoc.getSize(); i++) {
424 newCompLoc.addLocation(inferCompLoc.get(i));
427 Descriptor lastDescOfPrefix = nodeDescTuple.get(0);
428 Descriptor enclosingDescriptor;
429 if (lastDescOfPrefix instanceof InterDescriptor) {
430 enclosingDescriptor = null;
432 enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
435 for (int i = 1; i < nodeDescTuple.size(); i++) {
436 Descriptor desc = nodeDescTuple.get(i);
437 Location locElement = new Location(enclosingDescriptor, desc);
438 newCompLoc.addLocation(locElement);
440 enclosingDescriptor = ((FieldDescriptor) desc).getClassDescriptor();
446 private void translateMapLocationToInferCompositeLocationToCalleeGraph(
447 GlobalFlowGraph callerGraph, MethodInvokeNode min) {
449 MethodDescriptor mdCallee = min.getMethod();
450 MethodDescriptor mdCaller = callerGraph.getMethodDescriptor();
451 Map<Location, CompositeLocation> callerMapLocToCompLoc =
452 callerGraph.getMapLocationToInferCompositeLocation();
454 FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
455 GlobalFlowGraph calleeGlobalGraph = getSubGlobalFlowGraph(mdCallee);
457 NTuple<Location> baseLocTuple = null;
458 if (mapMethodInvokeNodeToBaseTuple.containsKey(min)) {
459 baseLocTuple = translateToLocTuple(mdCaller, mapMethodInvokeNodeToBaseTuple.get(min));
462 // System.out.println("\n-translate caller infer composite loc to callee=" + mdCallee
463 // + " baseLocTuple=" + baseLocTuple);
464 Set<Location> keySet = callerMapLocToCompLoc.keySet();
465 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
466 Location key = (Location) iterator.next();
467 CompositeLocation callerCompLoc = callerMapLocToCompLoc.get(key);
469 if (!key.getDescriptor().equals(mdCaller)) {
471 CompositeLocation newCalleeCompLoc;
472 if (baseLocTuple != null && callerCompLoc.getTuple().startsWith(baseLocTuple)) {
473 // System.out.println("---need to translate callerCompLoc=" + callerCompLoc
474 // + " with baseTuple=" + baseLocTuple);
476 translateCompositeLocationToCallee(callerCompLoc, baseLocTuple, mdCallee);
478 calleeGlobalGraph.addMapLocationToInferCompositeLocation(key, newCalleeCompLoc);
479 // System.out.println("---callee loc=" + key + " newCalleeCompLoc=" + newCalleeCompLoc);
481 // check if it is the global access
482 Location compLocFirstElement = callerCompLoc.getTuple().get(0);
483 if (compLocFirstElement.getDescriptor().equals(mdCallee)
484 && compLocFirstElement.getLocDescriptor().equals(GLOBALDESC)) {
486 newCalleeCompLoc = new CompositeLocation();
487 Location newMethodLoc = new Location(mdCallee, GLOBALDESC);
489 newCalleeCompLoc.addLocation(newMethodLoc);
490 for (int i = 1; i < callerCompLoc.getSize(); i++) {
491 newCalleeCompLoc.addLocation(callerCompLoc.get(i));
493 calleeGlobalGraph.addMapLocationToInferCompositeLocation(key, newCalleeCompLoc);
502 System.out.println("-----*AFTER TRANSLATING COMP LOC MAPPING, CALLEE MAPPING="
503 + calleeGlobalGraph.getMapLocationToInferCompositeLocation());
505 // If the location of an argument has a composite location
506 // need to assign a proper composite location to the corresponding callee parameter
507 // System.out.println("---translate arg composite location to callee param. min="
508 // + min.printNode(0));
509 Map<Integer, NTuple<Descriptor>> mapIdxToArgTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
510 Set<Integer> idxSet = mapIdxToArgTuple.keySet();
511 for (Iterator iterator = idxSet.iterator(); iterator.hasNext();) {
512 Integer idx = (Integer) iterator.next();
514 if (idx == 0 && !min.getMethod().isStatic()) {
518 NTuple<Descriptor> argTuple = mapIdxToArgTuple.get(idx);
519 if (argTuple.size() > 0) {
520 // check if an arg tuple has been already assigned to a composite location
521 NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argTuple);
522 Location argLocalLoc = argLocTuple.get(0);
524 // if (!isPrimitiveType(argTuple)) {
525 if (callerMapLocToCompLoc.containsKey(argLocalLoc)) {
527 CompositeLocation callerCompLoc = callerMapLocToCompLoc.get(argLocalLoc);
528 for (int i = 1; i < argLocTuple.size(); i++) {
529 callerCompLoc.addLocation(argLocTuple.get(i));
532 if (baseLocTuple != null && callerCompLoc.getTuple().startsWith(baseLocTuple)) {
534 FlowNode calleeParamFlowNode = calleeFlowGraph.getParamFlowNode(idx);
535 NTuple<Descriptor> calleeParamDescTuple = calleeParamFlowNode.getDescTuple();
536 NTuple<Location> calleeParamLocTuple =
537 translateToLocTuple(mdCallee, calleeParamDescTuple);
539 System.out.println("---need to translate callerCompLoc=" + callerCompLoc
540 + " with baseTuple=" + baseLocTuple + " calleeParamLocTuple="
541 + calleeParamLocTuple);
543 CompositeLocation newCalleeCompLoc =
544 translateCompositeLocationToCallee(callerCompLoc, baseLocTuple, mdCallee);
546 calleeGlobalGraph.addMapLocationToInferCompositeLocation(calleeParamLocTuple.get(0),
549 System.out.println("---callee loc=" + calleeParamLocTuple.get(0)
550 + " newCalleeCompLoc=" + newCalleeCompLoc);
552 // System.out.println("###need to assign composite location to=" + calleeParamDescTuple
553 // + " with baseTuple=" + baseLocTuple);
563 private boolean isPrimitiveType(NTuple<Descriptor> argTuple) {
565 Descriptor lastDesc = argTuple.get(argTuple.size() - 1);
567 if (lastDesc instanceof FieldDescriptor) {
568 return ((FieldDescriptor) lastDesc).getType().isPrimitive();
569 } else if (lastDesc instanceof VarDescriptor) {
570 return ((VarDescriptor) lastDesc).getType().isPrimitive();
576 private CompositeLocation translateCompositeLocationToCallee(CompositeLocation callerCompLoc,
577 NTuple<Location> baseLocTuple, MethodDescriptor mdCallee) {
579 CompositeLocation newCalleeCompLoc = new CompositeLocation();
581 Location calleeThisLoc = new Location(mdCallee, mdCallee.getThis());
582 newCalleeCompLoc.addLocation(calleeThisLoc);
584 // remove the base tuple from the caller
585 // ex; In the method invoation foo.bar.methodA(), the callee will have the composite location
586 // ,which is relative to the 'this' variable, <THIS,...>
587 for (int i = baseLocTuple.size(); i < callerCompLoc.getSize(); i++) {
588 newCalleeCompLoc.addLocation(callerCompLoc.get(i));
591 return newCalleeCompLoc;
595 private void calculateGlobalValueFlowCompositeLocation() {
597 System.out.println("SSJAVA: Calculate composite locations in the global value flow graph");
598 MethodDescriptor methodDescEventLoop = ssjava.getMethodContainingSSJavaLoop();
599 GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(methodDescEventLoop);
601 Set<Location> calculatedPrefixSet = new HashSet<Location>();
603 Set<GlobalFlowNode> nodeSet = globalFlowGraph.getNodeSet();
605 next: for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
606 GlobalFlowNode node = (GlobalFlowNode) iterator.next();
608 Location prefixLoc = node.getLocTuple().get(0);
610 if (calculatedPrefixSet.contains(prefixLoc)) {
611 // the prefix loc has been already assigned to a composite location
615 calculatedPrefixSet.add(prefixLoc);
617 // Set<GlobalFlowNode> incomingNodeSet = globalFlowGraph.getIncomingNodeSet(node);
618 List<NTuple<Location>> prefixList = calculatePrefixList(globalFlowGraph, node);
620 Set<GlobalFlowNode> reachableNodeSet =
621 globalFlowGraph.getReachableNodeSetByPrefix(node.getLocTuple().get(0));
622 // Set<GlobalFlowNode> reachNodeSet = globalFlowGraph.getReachableNodeSetFrom(node);
624 // System.out.println("node=" + node + " prefixList=" + prefixList + " reachableNodeSet="
625 // + reachableNodeSet);
627 for (int i = 0; i < prefixList.size(); i++) {
628 NTuple<Location> curPrefix = prefixList.get(i);
629 Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
631 for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
632 GlobalFlowNode reachNode = (GlobalFlowNode) iterator2.next();
633 if (reachNode.getLocTuple().startsWith(curPrefix)) {
634 reachableCommonPrefixSet.add(reachNode.getLocTuple());
638 if (!reachableCommonPrefixSet.isEmpty()) {
640 MethodDescriptor curPrefixFirstElementMethodDesc =
641 (MethodDescriptor) curPrefix.get(0).getDescriptor();
643 MethodDescriptor nodePrefixLocFirstElementMethodDesc =
644 (MethodDescriptor) prefixLoc.getDescriptor();
646 if (curPrefixFirstElementMethodDesc.equals(nodePrefixLocFirstElementMethodDesc)
647 || isTransitivelyCalledFrom(nodePrefixLocFirstElementMethodDesc,
648 curPrefixFirstElementMethodDesc)) {
651 // if (!node.getLocTuple().startsWith(curPrefix.get(0))) {
653 Location curPrefixLocalLoc = curPrefix.get(0);
654 if (globalFlowGraph.mapLocationToInferCompositeLocation.containsKey(curPrefixLocalLoc)) {
655 // in this case, the local variable of the current prefix has already got a composite
657 // so we just ignore the current composite location.
659 // System.out.println("HERE WE DO NOT ASSIGN A COMPOSITE LOCATION TO =" + node
660 // + " DUE TO " + curPrefix);
665 Location targetLocalLoc = node.getLocTuple().get(0);
666 // CompositeLocation curCompLoc = globalFlowGraph.getCompositeLocation(targetLocalLoc);
667 // if ((curPrefix.size() + 1) > curCompLoc.getSize()) {
669 CompositeLocation newCompLoc = generateCompositeLocation(curPrefix);
670 System.out.println("NEED TO ASSIGN COMP LOC TO " + node + " with prefix=" + curPrefix);
671 System.out.println("- newCompLoc=" + newCompLoc);
672 globalFlowGraph.addMapLocationToInferCompositeLocation(targetLocalLoc, newCompLoc);
685 // Set<GlobalFlowNode> inNodeSet =
686 // graph.getIncomingNodeSetWithPrefix(prefix);
687 // System.out.println("inNodeSet=" + inNodeSet + " from=" + node);
690 private void assignCompositeLocation(CompositeLocation compLocPrefix, GlobalFlowNode node) {
691 CompositeLocation newCompLoc = compLocPrefix.clone();
692 NTuple<Location> locTuple = node.getLocTuple();
693 for (int i = 1; i < locTuple.size(); i++) {
694 newCompLoc.addLocation(locTuple.get(i));
696 node.setInferCompositeLocation(newCompLoc);
699 private List<NTuple<Location>> calculatePrefixList(GlobalFlowGraph graph, GlobalFlowNode node) {
701 System.out.println("\n##### calculatePrefixList node=" + node);
703 Set<GlobalFlowNode> incomingNodeSetPrefix =
704 graph.getIncomingNodeSetByPrefix(node.getLocTuple().get(0));
705 // System.out.println("incomingNodeSetPrefix=" + incomingNodeSetPrefix);
707 // Set<GlobalFlowNode> reachableNodeSetPrefix =
708 // graph.getReachableNodeSetByPrefix(node.getLocTuple().get(0));
709 // System.out.println("reachableNodeSetPrefix=" + reachableNodeSetPrefix);
711 List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
713 for (Iterator iterator = incomingNodeSetPrefix.iterator(); iterator.hasNext();) {
714 GlobalFlowNode inNode = (GlobalFlowNode) iterator.next();
715 NTuple<Location> inNodeTuple = inNode.getLocTuple();
717 for (int i = 1; i < inNodeTuple.size(); i++) {
718 NTuple<Location> prefix = inNodeTuple.subList(0, i);
719 if (!prefixList.contains(prefix)) {
720 prefixList.add(prefix);
725 Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
726 public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
727 int s0 = arg0.size();
728 int s1 = arg1.size();
731 } else if (s0 == s1) {
739 // remove a prefix which is not suitable for generating composite location
740 Location localVarLoc = node.getLocTuple().get(0);
741 MethodDescriptor md = (MethodDescriptor) localVarLoc.getDescriptor();
742 ClassDescriptor cd = md.getClassDesc();
746 Set<NTuple<Location>> toberemoved = new HashSet<NTuple<Location>>();
747 for (int i = 0; i < prefixList.size(); i++) {
748 NTuple<Location> prefixLocTuple = prefixList.get(i);
749 if (!containsClassDesc(cd, prefixLocTuple)) {
750 toberemoved.add(prefixLocTuple);
754 prefixList.removeAll(toberemoved);
758 // List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
760 // for (Iterator iterator = incomingNodeSet.iterator(); iterator.hasNext();) {
761 // GlobalFlowNode inNode = (GlobalFlowNode) iterator.next();
762 // NTuple<Location> inNodeTuple = inNode.getLocTuple();
764 // for (int i = 1; i < inNodeTuple.size(); i++) {
765 // NTuple<Location> prefix = inNodeTuple.subList(0, i);
766 // if (!prefixList.contains(prefix)) {
767 // prefixList.add(prefix);
772 // Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
773 // public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
774 // int s0 = arg0.size();
775 // int s1 = arg1.size();
778 // } else if (s0 == s1) {
785 // return prefixList;
788 private boolean containsClassDesc(ClassDescriptor cd, NTuple<Location> prefixLocTuple) {
789 for (int i = 0; i < prefixLocTuple.size(); i++) {
790 Location loc = prefixLocTuple.get(i);
791 Descriptor locDesc = loc.getLocDescriptor();
792 if (locDesc != null) {
793 ClassDescriptor type = getClassTypeDescriptor(locDesc);
794 if (type != null && type.equals(cd)) {
802 private GlobalFlowGraph constructSubGlobalFlowGraph(FlowGraph flowGraph) {
804 MethodDescriptor md = flowGraph.getMethodDescriptor();
806 GlobalFlowGraph globalGraph = new GlobalFlowGraph(md);
808 // Set<FlowNode> nodeSet = flowGraph.getNodeSet();
809 Set<FlowEdge> edgeSet = flowGraph.getEdgeSet();
811 for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
813 FlowEdge edge = (FlowEdge) iterator.next();
814 NTuple<Descriptor> srcDescTuple = edge.getInitTuple();
815 NTuple<Descriptor> dstDescTuple = edge.getEndTuple();
817 // here only keep the first element(method location) of the descriptor
819 NTuple<Location> srcLocTuple = translateToLocTuple(md, srcDescTuple);
820 // Location srcMethodLoc = srcLocTuple.get(0);
821 // Descriptor srcVarDesc = srcMethodLoc.getLocDescriptor();
822 // // if (flowGraph.isParamDesc(srcVarDesc) &&
823 // (!srcVarDesc.equals(md.getThis()))) {
824 // if (!srcVarDesc.equals(md.getThis())) {
825 // srcLocTuple = new NTuple<Location>();
826 // Location loc = new Location(md, srcVarDesc);
827 // srcLocTuple.add(loc);
830 NTuple<Location> dstLocTuple = translateToLocTuple(md, dstDescTuple);
831 // Location dstMethodLoc = dstLocTuple.get(0);
832 // Descriptor dstVarDesc = dstMethodLoc.getLocDescriptor();
833 // if (!dstVarDesc.equals(md.getThis())) {
834 // dstLocTuple = new NTuple<Location>();
835 // Location loc = new Location(md, dstVarDesc);
836 // dstLocTuple.add(loc);
839 globalGraph.addValueFlowEdge(srcLocTuple, dstLocTuple);
846 private NTuple<Location> translateToLocTuple(MethodDescriptor md, NTuple<Descriptor> descTuple) {
848 NTuple<Location> locTuple = new NTuple<Location>();
850 Descriptor enclosingDesc = md;
851 // System.out.println("md=" + md + " descTuple=" + descTuple);
852 for (int i = 0; i < descTuple.size(); i++) {
853 Descriptor desc = descTuple.get(i);
855 Location loc = new Location(enclosingDesc, desc);
858 if (desc instanceof VarDescriptor) {
859 enclosingDesc = ((VarDescriptor) desc).getType().getClassDesc();
860 } else if (desc instanceof FieldDescriptor) {
861 enclosingDesc = ((FieldDescriptor) desc).getType().getClassDesc();
863 // TODO: inter descriptor case
864 enclosingDesc = desc;
873 private void addValueFlowsFromCalleeSubGlobalFlowGraph(MethodDescriptor mdCaller,
874 GlobalFlowGraph subGlobalFlowGraph) {
876 // the transformation for a call site propagates flows through parameters
877 // if the method is virtual, it also grab all relations from any possible
880 Set<MethodInvokeNode> setMethodInvokeNode = getMethodInvokeNodeSet(mdCaller);
882 for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
883 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
884 MethodDescriptor mdCallee = min.getMethod();
885 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
886 if (mdCallee.isStatic()) {
887 setPossibleCallees.add(mdCallee);
889 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
890 // removes method descriptors that are not invoked by the caller
891 calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
892 setPossibleCallees.addAll(calleeSet);
895 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
896 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
897 propagateValueFlowsToCallerFromSubGlobalFlowGraph(min, mdCaller, possibleMdCallee);
904 private void propagateValueFlowsToCallerFromSubGlobalFlowGraph(MethodInvokeNode min,
905 MethodDescriptor mdCaller, MethodDescriptor possibleMdCallee) {
907 System.out.println("---propagate from " + min.printNode(0) + " to caller=" + mdCaller);
908 FlowGraph calleeFlowGraph = getFlowGraph(possibleMdCallee);
909 Map<Integer, NTuple<Descriptor>> mapIdxToArg = mapMethodInvokeNodeToArgIdxMap.get(min);
911 System.out.println("-----mapMethodInvokeNodeToArgIdxMap.get(min)="
912 + mapMethodInvokeNodeToArgIdxMap.get(min));
913 Set<Integer> keySet = mapIdxToArg.keySet();
914 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
915 Integer idx = (Integer) iterator.next();
916 NTuple<Descriptor> argDescTuple = mapIdxToArg.get(idx);
917 if (argDescTuple.size() > 0) {
918 NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argDescTuple);
919 NTuple<Descriptor> paramDescTuple = calleeFlowGraph.getParamFlowNode(idx).getDescTuple();
920 NTuple<Location> paramLocTuple = translateToLocTuple(possibleMdCallee, paramDescTuple);
921 addMapCallerArgToCalleeParam(min, argDescTuple, paramDescTuple);
925 NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
926 GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(possibleMdCallee);
927 Set<GlobalFlowNode> calleeNodeSet = calleeSubGlobalGraph.getNodeSet();
928 for (Iterator iterator = calleeNodeSet.iterator(); iterator.hasNext();) {
929 GlobalFlowNode calleeNode = (GlobalFlowNode) iterator.next();
930 addValueFlowFromCalleeNode(min, mdCaller, possibleMdCallee, calleeNode);
933 // int numParam = calleeFlowGraph.getNumParameters();
934 // for (int idx = 0; idx < numParam; idx++) {
936 // FlowNode paramNode = calleeFlowGraph.getParamFlowNode(idx);
938 // NTuple<Location> paramLocTuple =
939 // translateToLocTuple(possibleMdCallee, paramNode.getCurrentDescTuple());
941 // GlobalFlowNode globalParamNode =
942 // calleeSubGlobalGraph.getFlowNode(paramLocTuple);
944 // NTuple<Descriptor> argTuple =
945 // mapMethodInvokeNodeToArgIdxMap.get(min).get(idx);
947 // NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argTuple);
949 // System.out.println("argTupleSet=" + argLocTuple + " param=" +
951 // // here, it adds all value flows reachable from the paramNode in the
952 // callee's flow graph
954 // addValueFlowsFromCalleeParam(mdCaller, argLocTuple, baseLocTuple,
960 // // FlowGraph callerSubGlobalGraph = getSubGlobalFlowGraph(mdCaller);
961 // // FlowGraph calleeSubGlobalGraph =
962 // getSubGlobalFlowGraph(possibleMdCallee);
964 // // int numParam = calleeSubGlobalGraph.getNumParameters();
965 // // for (int idx = 0; idx < numParam; idx++) {
966 // // FlowNode paramNode = calleeSubGlobalGraph.getParamFlowNode(idx);
967 // // NTuple<Descriptor> argTuple =
968 // mapMethodInvokeNodeToArgIdxMap.get(min).get(idx);
969 // // System.out.println("argTupleSet=" + argTuple + " param=" +
971 // // // here, it adds all value flows reachable from the paramNode in the
972 // callee's flow graph
973 // // addValueFlowsFromCalleeParam(min, calleeSubGlobalGraph, paramNode,
974 // callerSubGlobalGraph,
975 // // argTuple, baseTuple);
980 private void addValueFlowFromCalleeNode(MethodInvokeNode min, MethodDescriptor mdCaller,
981 MethodDescriptor mdCallee, GlobalFlowNode calleeSrcNode) {
983 GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(mdCallee);
984 GlobalFlowGraph callerSubGlobalGraph = getSubGlobalFlowGraph(mdCaller);
986 NTuple<Location> callerSrcNodeLocTuple =
987 translateToCallerLocTuple(min, mdCallee, mdCaller, calleeSrcNode.getLocTuple());
989 if (callerSrcNodeLocTuple != null) {
990 Set<GlobalFlowNode> outNodeSet = calleeSubGlobalGraph.getOutNodeSet(calleeSrcNode);
992 for (Iterator iterator = outNodeSet.iterator(); iterator.hasNext();) {
993 GlobalFlowNode outNode = (GlobalFlowNode) iterator.next();
994 NTuple<Location> callerDstNodeLocTuple =
995 translateToCallerLocTuple(min, mdCallee, mdCaller, outNode.getLocTuple());
996 if (callerDstNodeLocTuple != null) {
997 callerSubGlobalGraph.addValueFlowEdge(callerSrcNodeLocTuple, callerDstNodeLocTuple);
1004 private NTuple<Location> translateToCallerLocTuple(MethodInvokeNode min,
1005 MethodDescriptor mdCallee, MethodDescriptor mdCaller, NTuple<Location> nodeLocTuple) {
1006 // this method will return the same nodeLocTuple if the corresponding argument is literal
1009 FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
1011 NTuple<Descriptor> nodeDescTuple = translateToDescTuple(nodeLocTuple);
1012 if (calleeFlowGraph.isParameter(nodeDescTuple)) {
1013 int paramIdx = calleeFlowGraph.getParamIdx(nodeDescTuple);
1014 NTuple<Descriptor> argDescTuple = mapMethodInvokeNodeToArgIdxMap.get(min).get(paramIdx);
1016 if (isPrimitive(nodeLocTuple.get(0).getLocDescriptor())) {
1017 // the type of argument is primitive.
1018 return nodeLocTuple.clone();
1020 NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argDescTuple);
1022 NTuple<Location> callerLocTuple = new NTuple<Location>();
1024 callerLocTuple.addAll(argLocTuple);
1025 for (int i = 1; i < nodeLocTuple.size(); i++) {
1026 callerLocTuple.add(nodeLocTuple.get(i));
1028 return callerLocTuple;
1030 return nodeLocTuple.clone();
1035 public static boolean isPrimitive(Descriptor desc) {
1037 if (desc instanceof FieldDescriptor) {
1038 return ((FieldDescriptor) desc).getType().isPrimitive();
1039 } else if (desc instanceof VarDescriptor) {
1040 return ((VarDescriptor) desc).getType().isPrimitive();
1041 } else if (desc instanceof InterDescriptor) {
1048 private NTuple<Descriptor> translateToDescTuple(NTuple<Location> locTuple) {
1050 NTuple<Descriptor> descTuple = new NTuple<Descriptor>();
1051 for (int i = 0; i < locTuple.size(); i++) {
1052 descTuple.add(locTuple.get(i).getLocDescriptor());
1058 private void addValueFlowsFromCalleeParam(MethodDescriptor mdCaller,
1059 NTuple<Location> argLocTuple, NTuple<Location> baseLocTuple, MethodDescriptor mdCallee,
1060 GlobalFlowNode globalParamNode) {
1062 Set<GlobalFlowNode> visited = new HashSet<GlobalFlowNode>();
1063 visited.add(globalParamNode);
1064 recurAddValueFlowsFromCalleeParam(mdCaller, argLocTuple, baseLocTuple, mdCallee,
1069 private void recurAddValueFlowsFromCalleeParam(MethodDescriptor mdCaller,
1070 NTuple<Location> argLocTuple, NTuple<Location> baseLocTuple, MethodDescriptor mdCallee,
1071 GlobalFlowNode calleeCurNode) {
1073 // FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
1074 // GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(mdCallee);
1076 // NTuple<Location> curNodeLocTuple = calleeCurNode.getLocTuple();
1077 // NTuple<Descriptor> curNodeDescTuple = calleeCurNode.getDescTuple();
1078 // if (calleeFlowGraph.isParameter(curNodeDescTuple)) {
1079 // curNodeLocTuple = translateToCaller(argLocTuple, curNodeLocTuple);
1082 // Set<GlobalFlowNode> outNodeSet =
1083 // calleeSubGlobalGraph.getOutNodeSet(calleeCurNode);
1084 // for (Iterator iterator = outNodeSet.iterator(); iterator.hasNext();) {
1085 // GlobalFlowNode outNode = (GlobalFlowNode) iterator.next();
1087 // NTuple<Location> curNodeLocTuple = calleeCurNode.getLocTuple();
1088 // NTuple<Descriptor> curNodeDescTuple = calleeCurNode.getDescTuple();
1089 // if (calleeFlowGraph.isParameter(curNodeDescTuple)) {
1090 // curNodeLocTuple = translateToCaller(argLocTuple, curNodeLocTuple);
1093 // outNode.getDescTuple();
1095 // if (calleeFlowGraph.is)
1097 // if (calleeSubGlobalGraph.isParameter(srcDescTuple)) {
1098 // // destination node is started with 'parameter'
1099 // // need to translate it in terms of the caller's a node
1101 // translateToCaller(min, calleeSubGlobalGraph.getParamIdx(srcDescTuple),
1107 // Set<FlowEdge> edgeSet =
1108 // calleeSubGlobalGraph.getOutEdgeSetStartingFrom(calleeSrcNode);
1109 // for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
1110 // FlowEdge flowEdge = (FlowEdge) iterator.next();
1112 // NTuple<Descriptor> srcDescTuple = flowEdge.getInitTuple();
1113 // NTuple<Descriptor> dstDescTuple = flowEdge.getEndTuple();
1115 // FlowNode dstNode = calleeSubGlobalGraph.getFlowNode(dstDescTuple);
1117 // if (calleeSubGlobalGraph.isParameter(srcDescTuple)) {
1118 // // destination node is started with 'parameter'
1119 // // need to translate it in terms of the caller's a node
1121 // translateToCaller(min, calleeSubGlobalGraph.getParamIdx(srcDescTuple),
1125 // if (calleeSubGlobalGraph.isParameter(dstDescTuple)) {
1126 // // destination node is started with 'parameter'
1127 // // need to translate it in terms of the caller's a node
1129 // translateToCaller(min, calleeSubGlobalGraph.getParamIdx(dstDescTuple),
1133 // callerSubGlobalGraph.addValueFlowEdge(srcDescTuple, dstDescTuple);
1135 // if (!visited.contains(dstNode)) {
1136 // visited.add(dstNode);
1137 // recurAddValueFlowsFromCalleeParam(min, calleeSubGlobalGraph, dstNode,
1138 // callerSubGlobalGraph,
1139 // dstDescTuple, visited, baseTuple);
1146 private NTuple<Location> translateToCaller(NTuple<Location> argLocTuple,
1147 NTuple<Location> curNodeLocTuple) {
1149 NTuple<Location> callerLocTuple = new NTuple<Location>();
1151 callerLocTuple.addAll(argLocTuple);
1152 for (int i = 1; i < curNodeLocTuple.size(); i++) {
1153 callerLocTuple.add(curNodeLocTuple.get(i));
1156 return callerLocTuple;
1159 private void recurAddValueFlowsFromCalleeParam(MethodInvokeNode min,
1160 FlowGraph calleeSubGlobalGraph, FlowNode calleeSrcNode, FlowGraph callerSubGlobalGraph,
1161 NTuple<Descriptor> callerSrcTuple, Set<FlowNode> visited, NTuple<Descriptor> baseTuple) {
1163 MethodDescriptor mdCallee = calleeSubGlobalGraph.getMethodDescriptor();
1165 // Set<FlowEdge> edgeSet =
1166 // calleeSubGlobalGraph.getOutEdgeSet(calleeSrcNode);
1167 Set<FlowEdge> edgeSet = calleeSubGlobalGraph.getOutEdgeSetStartingFrom(calleeSrcNode);
1168 for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
1169 FlowEdge flowEdge = (FlowEdge) iterator.next();
1171 NTuple<Descriptor> srcDescTuple = flowEdge.getInitTuple();
1172 NTuple<Descriptor> dstDescTuple = flowEdge.getEndTuple();
1174 FlowNode dstNode = calleeSubGlobalGraph.getFlowNode(dstDescTuple);
1176 if (calleeSubGlobalGraph.isParameter(srcDescTuple)) {
1177 // destination node is started with 'parameter'
1178 // need to translate it in terms of the caller's a node
1180 translateToCaller(min, calleeSubGlobalGraph.getParamIdx(srcDescTuple), srcDescTuple);
1183 if (calleeSubGlobalGraph.isParameter(dstDescTuple)) {
1184 // destination node is started with 'parameter'
1185 // need to translate it in terms of the caller's a node
1187 translateToCaller(min, calleeSubGlobalGraph.getParamIdx(dstDescTuple), dstDescTuple);
1190 callerSubGlobalGraph.addValueFlowEdge(srcDescTuple, dstDescTuple);
1192 if (!visited.contains(dstNode)) {
1193 visited.add(dstNode);
1194 recurAddValueFlowsFromCalleeParam(min, calleeSubGlobalGraph, dstNode, callerSubGlobalGraph,
1195 dstDescTuple, visited, baseTuple);
1202 private NTuple<Descriptor> translateToCaller(MethodInvokeNode min, int paramIdx,
1203 NTuple<Descriptor> srcDescTuple) {
1205 NTuple<Descriptor> callerTuple = new NTuple<Descriptor>();
1207 NTuple<Descriptor> argTuple = mapMethodInvokeNodeToArgIdxMap.get(min).get(paramIdx);
1209 for (int i = 0; i < argTuple.size(); i++) {
1210 callerTuple.add(argTuple.get(i));
1213 for (int i = 1; i < srcDescTuple.size(); i++) {
1214 callerTuple.add(srcDescTuple.get(i));
1220 private NTuple<Descriptor> traslateToCalleeParamTupleToCallerArgTuple(
1221 NTuple<Descriptor> calleeInitTuple, NTuple<Descriptor> callerSrcTuple) {
1223 NTuple<Descriptor> callerInitTuple = new NTuple<Descriptor>();
1225 for (int i = 0; i < callerSrcTuple.size(); i++) {
1226 callerInitTuple.add(callerSrcTuple.get(i));
1229 for (int i = 1; i < calleeInitTuple.size(); i++) {
1230 callerInitTuple.add(calleeInitTuple.get(i));
1233 return callerInitTuple;
1236 public LocationSummary getLocationSummary(Descriptor d) {
1237 if (!mapDescToLocationSummary.containsKey(d)) {
1238 if (d instanceof MethodDescriptor) {
1239 mapDescToLocationSummary.put(d, new MethodSummary((MethodDescriptor) d));
1240 } else if (d instanceof ClassDescriptor) {
1241 mapDescToLocationSummary.put(d, new FieldSummary());
1244 return mapDescToLocationSummary.get(d);
1247 private void generateMethodSummary() {
1249 Set<MethodDescriptor> keySet = md2lattice.keySet();
1250 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1251 MethodDescriptor md = (MethodDescriptor) iterator.next();
1253 System.out.println("\nSSJAVA: generate method summary: " + md);
1255 FlowGraph flowGraph = getFlowGraph(md);
1256 MethodSummary methodSummary = getMethodSummary(md);
1258 HierarchyGraph scGraph = getSkeletonCombinationHierarchyGraph(md);
1260 // set the 'this' reference location
1261 if (!md.isStatic()) {
1262 System.out.println("setThisLocName=" + scGraph.getHNode(md.getThis()).getName());
1263 methodSummary.setThisLocName(scGraph.getHNode(md.getThis()).getName());
1266 // set the 'global' reference location if needed
1267 if (methodSummary.hasGlobalAccess()) {
1268 methodSummary.setGlobalLocName(scGraph.getHNode(GLOBALDESC).getName());
1271 // construct a parameter mapping that maps a parameter descriptor to an
1272 // inferred composite location
1273 for (int paramIdx = 0; paramIdx < flowGraph.getNumParameters(); paramIdx++) {
1274 FlowNode flowNode = flowGraph.getParamFlowNode(paramIdx);
1275 CompositeLocation inferredCompLoc = flowNode.getCompositeLocation();
1276 // NTuple<Descriptor> descTuple = flowNode.getDescTuple();
1278 // CompositeLocation assignedCompLoc = flowNode.getCompositeLocation();
1279 // CompositeLocation inferredCompLoc;
1280 // if (assignedCompLoc != null) {
1281 // inferredCompLoc = translateCompositeLocation(assignedCompLoc);
1283 // Descriptor locDesc = descTuple.get(0);
1284 // Location loc = new Location(md, locDesc.getSymbol());
1285 // loc.setLocDescriptor(locDesc);
1286 // inferredCompLoc = new CompositeLocation(loc);
1288 System.out.println("-paramIdx=" + paramIdx + " infer=" + inferredCompLoc);
1289 System.out.println("-flowNode inferLoc=" + flowNode.getCompositeLocation());
1291 Descriptor localVarDesc = flowNode.getDescTuple().get(0);
1292 methodSummary.addMapVarNameToInferCompLoc(localVarDesc, inferredCompLoc);
1293 methodSummary.addMapParamIdxToInferLoc(paramIdx, inferredCompLoc);
1300 private boolean hasOrderingRelation(NTuple<Location> locTuple1, NTuple<Location> locTuple2) {
1302 int size = locTuple1.size() >= locTuple2.size() ? locTuple2.size() : locTuple1.size();
1304 for (int idx = 0; idx < size; idx++) {
1305 Location loc1 = locTuple1.get(idx);
1306 Location loc2 = locTuple2.get(idx);
1308 Descriptor desc1 = loc1.getDescriptor();
1309 Descriptor desc2 = loc2.getDescriptor();
1311 if (!desc1.equals(desc2)) {
1312 throw new Error("Fail to compare " + locTuple1 + " and " + locTuple2);
1315 Descriptor locDesc1 = loc1.getLocDescriptor();
1316 Descriptor locDesc2 = loc2.getLocDescriptor();
1318 HierarchyGraph hierarchyGraph = getHierarchyGraph(desc1);
1320 HNode node1 = hierarchyGraph.getHNode(locDesc1);
1321 HNode node2 = hierarchyGraph.getHNode(locDesc2);
1323 System.out.println("---node1=" + node1 + " node2=" + node2);
1324 System.out.println("---hierarchyGraph.getIncomingNodeSet(node2)="
1325 + hierarchyGraph.getIncomingNodeSet(node2));
1327 if (locDesc1.equals(locDesc2)) {
1329 } else if (!hierarchyGraph.getIncomingNodeSet(node2).contains(node1)
1330 && !hierarchyGraph.getIncomingNodeSet(node1).contains(node2)) {
1342 private boolean isHigherThan(NTuple<Location> locTuple1, NTuple<Location> locTuple2) {
1344 int size = locTuple1.size() >= locTuple2.size() ? locTuple2.size() : locTuple1.size();
1346 for (int idx = 0; idx < size; idx++) {
1347 Location loc1 = locTuple1.get(idx);
1348 Location loc2 = locTuple2.get(idx);
1350 Descriptor desc1 = loc1.getDescriptor();
1351 Descriptor desc2 = loc2.getDescriptor();
1353 if (!desc1.equals(desc2)) {
1354 throw new Error("Fail to compare " + locTuple1 + " and " + locTuple2);
1357 Descriptor locDesc1 = loc1.getLocDescriptor();
1358 Descriptor locDesc2 = loc2.getLocDescriptor();
1360 HierarchyGraph hierarchyGraph = getHierarchyGraph(desc1);
1362 HNode node1 = hierarchyGraph.getHNode(locDesc1);
1363 HNode node2 = hierarchyGraph.getHNode(locDesc2);
1365 System.out.println("---node1=" + node1 + " node2=" + node2);
1366 System.out.println("---hierarchyGraph.getIncomingNodeSet(node2)="
1367 + hierarchyGraph.getIncomingNodeSet(node2));
1369 if (locDesc1.equals(locDesc2)) {
1371 } else if (hierarchyGraph.getIncomingNodeSet(node2).contains(node1)) {
1382 private CompositeLocation translateCompositeLocation(CompositeLocation compLoc) {
1383 CompositeLocation newCompLoc = new CompositeLocation();
1385 // System.out.println("compLoc=" + compLoc);
1386 for (int i = 0; i < compLoc.getSize(); i++) {
1387 Location loc = compLoc.get(i);
1388 Descriptor enclosingDescriptor = loc.getDescriptor();
1389 Descriptor locDescriptor = loc.getLocDescriptor();
1391 HNode hnode = getHierarchyGraph(enclosingDescriptor).getHNode(locDescriptor);
1392 // System.out.println("-hnode=" + hnode + " from=" + locDescriptor +
1393 // " enclosingDescriptor="
1394 // + enclosingDescriptor);
1395 // System.out.println("-getLocationSummary(enclosingDescriptor)="
1396 // + getLocationSummary(enclosingDescriptor));
1397 String locName = getLocationSummary(enclosingDescriptor).getLocationName(hnode.getName());
1398 // System.out.println("-locName=" + locName);
1399 Location newLoc = new Location(enclosingDescriptor, locName);
1400 newLoc.setLocDescriptor(locDescriptor);
1401 newCompLoc.addLocation(newLoc);
1407 private void debug_writeLattices() {
1409 Set<Descriptor> keySet = mapDescriptorToSimpleLattice.keySet();
1410 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1411 Descriptor key = (Descriptor) iterator.next();
1412 SSJavaLattice<String> simpleLattice = mapDescriptorToSimpleLattice.get(key);
1413 // HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(key);
1414 HierarchyGraph scHierarchyGraph = getSkeletonCombinationHierarchyGraph(key);
1415 if (key instanceof ClassDescriptor) {
1416 writeInferredLatticeDotFile((ClassDescriptor) key, scHierarchyGraph, simpleLattice,
1418 } else if (key instanceof MethodDescriptor) {
1419 MethodDescriptor md = (MethodDescriptor) key;
1420 writeInferredLatticeDotFile(md.getClassDesc(), md, scHierarchyGraph, simpleLattice,
1424 LocationSummary ls = getLocationSummary(key);
1425 System.out.println("####LOC SUMMARY=" + key + "\n" + ls.getMapHNodeNameToLocationName());
1428 Set<ClassDescriptor> cdKeySet = cd2lattice.keySet();
1429 for (Iterator iterator = cdKeySet.iterator(); iterator.hasNext();) {
1430 ClassDescriptor cd = (ClassDescriptor) iterator.next();
1431 writeInferredLatticeDotFile((ClassDescriptor) cd, getSkeletonCombinationHierarchyGraph(cd),
1432 cd2lattice.get(cd), "");
1435 Set<MethodDescriptor> mdKeySet = md2lattice.keySet();
1436 for (Iterator iterator = mdKeySet.iterator(); iterator.hasNext();) {
1437 MethodDescriptor md = (MethodDescriptor) iterator.next();
1438 writeInferredLatticeDotFile(md.getClassDesc(), md, getSkeletonCombinationHierarchyGraph(md),
1439 md2lattice.get(md), "");
1444 private void buildLattice() {
1446 BuildLattice buildLattice = new BuildLattice(this);
1448 Set<Descriptor> keySet = mapDescriptorToCombineSkeletonHierarchyGraph.keySet();
1449 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1450 Descriptor desc = (Descriptor) iterator.next();
1452 SSJavaLattice<String> simpleLattice = buildLattice.buildLattice(desc);
1454 addMapDescToSimpleLattice(desc, simpleLattice);
1456 HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
1457 System.out.println("\n## insertIntermediateNodesToStraightLine:"
1458 + simpleHierarchyGraph.getName());
1459 SSJavaLattice<String> lattice =
1460 buildLattice.insertIntermediateNodesToStraightLine(desc, simpleLattice);
1461 lattice.removeRedundantEdges();
1463 if (desc instanceof ClassDescriptor) {
1465 cd2lattice.put((ClassDescriptor) desc, lattice);
1466 // ssjava.writeLatticeDotFile((ClassDescriptor) desc, null, lattice);
1467 } else if (desc instanceof MethodDescriptor) {
1469 md2lattice.put((MethodDescriptor) desc, lattice);
1470 MethodDescriptor md = (MethodDescriptor) desc;
1471 ClassDescriptor cd = md.getClassDesc();
1472 // ssjava.writeLatticeDotFile(cd, md, lattice);
1475 // System.out.println("\nSSJAVA: Insering Combination Nodes:" + desc);
1476 // HierarchyGraph skeletonGraph = getSkeletonHierarchyGraph(desc);
1477 // HierarchyGraph skeletonGraphWithCombinationNode =
1478 // skeletonGraph.clone();
1479 // skeletonGraphWithCombinationNode.setName(desc + "_SC");
1481 // HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
1482 // System.out.println("Identifying Combination Nodes:");
1483 // skeletonGraphWithCombinationNode.insertCombinationNodesToGraph(simpleHierarchyGraph);
1484 // skeletonGraphWithCombinationNode.simplifySkeletonCombinationHierarchyGraph();
1485 // mapDescriptorToCombineSkeletonHierarchyGraph.put(desc,
1486 // skeletonGraphWithCombinationNode);
1491 public void addMapDescToSimpleLattice(Descriptor desc, SSJavaLattice<String> lattice) {
1492 mapDescriptorToSimpleLattice.put(desc, lattice);
1495 public SSJavaLattice<String> getSimpleLattice(Descriptor desc) {
1496 return mapDescriptorToSimpleLattice.get(desc);
1499 private void simplifyHierarchyGraph() {
1500 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1501 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1502 Descriptor desc = (Descriptor) iterator.next();
1503 HierarchyGraph simpleHierarchyGraph = getHierarchyGraph(desc).clone();
1504 simpleHierarchyGraph.setName(desc + "_SIMPLE");
1505 simpleHierarchyGraph.removeRedundantEdges();
1506 // simpleHierarchyGraph.simplifyHierarchyGraph();
1507 mapDescriptorToSimpleHierarchyGraph.put(desc, simpleHierarchyGraph);
1511 private void insertCombinationNodes() {
1512 Set<Descriptor> keySet = mapDescriptorToSkeletonHierarchyGraph.keySet();
1513 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1514 Descriptor desc = (Descriptor) iterator.next();
1515 System.out.println("\nSSJAVA: Insering Combination Nodes:" + desc);
1516 HierarchyGraph skeletonGraph = getSkeletonHierarchyGraph(desc);
1517 HierarchyGraph skeletonGraphWithCombinationNode = skeletonGraph.clone();
1518 skeletonGraphWithCombinationNode.setName(desc + "_SC");
1520 HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
1521 System.out.println("Identifying Combination Nodes:");
1522 skeletonGraphWithCombinationNode.insertCombinationNodesToGraph(simpleHierarchyGraph);
1523 skeletonGraphWithCombinationNode.simplifySkeletonCombinationHierarchyGraph();
1524 mapDescriptorToCombineSkeletonHierarchyGraph.put(desc, skeletonGraphWithCombinationNode);
1528 private void constructSkeletonHierarchyGraph() {
1529 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1530 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1531 Descriptor desc = (Descriptor) iterator.next();
1532 HierarchyGraph simpleGraph = getSimpleHierarchyGraph(desc);
1533 HierarchyGraph skeletonGraph = simpleGraph.generateSkeletonGraph();
1534 skeletonGraph.setMapDescToHNode(simpleGraph.getMapDescToHNode());
1535 skeletonGraph.setMapHNodeToDescSet(simpleGraph.getMapHNodeToDescSet());
1536 skeletonGraph.simplifyHierarchyGraph();
1537 // skeletonGraph.combineRedundantNodes(false);
1538 // skeletonGraph.removeRedundantEdges();
1539 mapDescriptorToSkeletonHierarchyGraph.put(desc, skeletonGraph);
1543 private void debug_writeHierarchyDotFiles() {
1545 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1546 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1547 Descriptor desc = (Descriptor) iterator.next();
1548 getHierarchyGraph(desc).writeGraph();
1553 private void debug_writeSimpleHierarchyDotFiles() {
1555 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1556 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1557 Descriptor desc = (Descriptor) iterator.next();
1558 getHierarchyGraph(desc).writeGraph();
1559 getSimpleHierarchyGraph(desc).writeGraph();
1564 private void debug_writeSkeletonHierarchyDotFiles() {
1566 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1567 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1568 Descriptor desc = (Descriptor) iterator.next();
1569 getSkeletonHierarchyGraph(desc).writeGraph();
1574 private void debug_writeSkeletonCombinationHierarchyDotFiles() {
1576 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1577 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1578 Descriptor desc = (Descriptor) iterator.next();
1579 getSkeletonCombinationHierarchyGraph(desc).writeGraph();
1584 public HierarchyGraph getSimpleHierarchyGraph(Descriptor d) {
1585 return mapDescriptorToSimpleHierarchyGraph.get(d);
1588 private HierarchyGraph getSkeletonHierarchyGraph(Descriptor d) {
1589 if (!mapDescriptorToSkeletonHierarchyGraph.containsKey(d)) {
1590 mapDescriptorToSkeletonHierarchyGraph.put(d, new HierarchyGraph(d));
1592 return mapDescriptorToSkeletonHierarchyGraph.get(d);
1595 public HierarchyGraph getSkeletonCombinationHierarchyGraph(Descriptor d) {
1596 if (!mapDescriptorToCombineSkeletonHierarchyGraph.containsKey(d)) {
1597 mapDescriptorToCombineSkeletonHierarchyGraph.put(d, new HierarchyGraph(d));
1599 return mapDescriptorToCombineSkeletonHierarchyGraph.get(d);
1602 private void constructHierarchyGraph() {
1604 // do fixed-point analysis
1607 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
1609 // Collections.sort(descriptorListToAnalyze, new
1610 // Comparator<MethodDescriptor>() {
1611 // public int compare(MethodDescriptor o1, MethodDescriptor o2) {
1612 // return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
1616 // current descriptors to visit in fixed-point interprocedural analysis,
1617 // prioritized by dependency in the call graph
1618 methodDescriptorsToVisitStack.clear();
1620 Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
1621 methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
1623 while (!descriptorListToAnalyze.isEmpty()) {
1624 MethodDescriptor md = descriptorListToAnalyze.removeFirst();
1625 methodDescriptorsToVisitStack.add(md);
1628 // analyze scheduled methods until there are no more to visit
1629 while (!methodDescriptorsToVisitStack.isEmpty()) {
1630 // start to analyze leaf node
1631 MethodDescriptor md = methodDescriptorsToVisitStack.pop();
1633 HierarchyGraph hierarchyGraph = new HierarchyGraph(md);
1634 // MethodSummary methodSummary = new MethodSummary(md);
1636 // MethodLocationInfo methodInfo = new MethodLocationInfo(md);
1637 // curMethodInfo = methodInfo;
1639 System.out.println();
1640 System.out.println("SSJAVA: Construcing the hierarchy graph from " + md);
1642 constructHierarchyGraph(md, hierarchyGraph);
1644 HierarchyGraph prevHierarchyGraph = getHierarchyGraph(md);
1645 // MethodSummary prevMethodSummary = getMethodSummary(md);
1647 if (!hierarchyGraph.equals(prevHierarchyGraph)) {
1649 mapDescriptorToHierarchyGraph.put(md, hierarchyGraph);
1650 // mapDescToLocationSummary.put(md, methodSummary);
1652 // results for callee changed, so enqueue dependents caller for
1654 Iterator<MethodDescriptor> depsItr = ssjava.getDependents(md).iterator();
1655 while (depsItr.hasNext()) {
1656 MethodDescriptor methodNext = depsItr.next();
1657 if (!methodDescriptorsToVisitStack.contains(methodNext)
1658 && methodDescriptorToVistSet.contains(methodNext)) {
1659 methodDescriptorsToVisitStack.add(methodNext);
1668 while (!toAnalyzeIsEmpty()) {
1669 ClassDescriptor cd = toAnalyzeNext();
1670 HierarchyGraph graph = getHierarchyGraph(cd);
1671 for (Iterator iter = cd.getFields(); iter.hasNext();) {
1672 FieldDescriptor fieldDesc = (FieldDescriptor) iter.next();
1673 if (!(fieldDesc.isStatic() && fieldDesc.isFinal())) {
1674 graph.getHNode(fieldDesc);
1681 private HierarchyGraph getHierarchyGraph(Descriptor d) {
1682 if (!mapDescriptorToHierarchyGraph.containsKey(d)) {
1683 mapDescriptorToHierarchyGraph.put(d, new HierarchyGraph(d));
1685 return mapDescriptorToHierarchyGraph.get(d);
1688 private void constructHierarchyGraph(MethodDescriptor md, HierarchyGraph methodGraph) {
1690 // visit each node of method flow graph
1691 FlowGraph fg = getFlowGraph(md);
1692 Set<FlowNode> nodeSet = fg.getNodeSet();
1694 Set<Descriptor> paramDescSet = fg.getMapParamDescToIdx().keySet();
1695 for (Iterator iterator = paramDescSet.iterator(); iterator.hasNext();) {
1696 Descriptor desc = (Descriptor) iterator.next();
1697 methodGraph.getHNode(desc).setSkeleton(true);
1700 // for the method lattice, we need to look at the first element of
1701 // NTuple<Descriptor>
1702 boolean hasGlobalAccess = false;
1703 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1704 FlowNode srcNode = (FlowNode) iterator.next();
1706 // if the srcNode is started with the global descriptor
1707 // need to set as a skeleton node
1708 if (!hasGlobalAccess && srcNode.getDescTuple().startsWith(GLOBALDESC)) {
1709 hasGlobalAccess = true;
1712 Set<FlowEdge> outEdgeSet = fg.getOutEdgeSet(srcNode);
1713 for (Iterator iterator2 = outEdgeSet.iterator(); iterator2.hasNext();) {
1714 FlowEdge outEdge = (FlowEdge) iterator2.next();
1715 FlowNode dstNode = outEdge.getDst();
1717 NTuple<Descriptor> srcNodeTuple = srcNode.getDescTuple();
1718 NTuple<Descriptor> dstNodeTuple = dstNode.getDescTuple();
1720 if (outEdge.getInitTuple().equals(srcNodeTuple)
1721 && outEdge.getEndTuple().equals(dstNodeTuple)) {
1723 NTuple<Descriptor> srcCurTuple = srcNode.getCurrentDescTuple();
1724 NTuple<Descriptor> dstCurTuple = dstNode.getCurrentDescTuple();
1726 if ((srcCurTuple.size() > 1 && dstCurTuple.size() > 1)
1727 && srcCurTuple.get(0).equals(dstCurTuple.get(0))) {
1729 // value flows between fields
1730 Descriptor desc = srcCurTuple.get(0);
1731 ClassDescriptor classDesc;
1733 if (desc.equals(GLOBALDESC)) {
1734 classDesc = md.getClassDesc();
1736 VarDescriptor varDesc = (VarDescriptor) srcCurTuple.get(0);
1737 classDesc = varDesc.getType().getClassDesc();
1739 extractFlowsBetweenFields(classDesc, srcNode, dstNode, 1);
1742 // value flow between local var - local var or local var - field
1744 Descriptor srcDesc = srcCurTuple.get(0);
1745 Descriptor dstDesc = dstCurTuple.get(0);
1747 methodGraph.addEdge(srcDesc, dstDesc);
1749 if (fg.isParamDesc(srcDesc)) {
1750 methodGraph.setParamHNode(srcDesc);
1752 if (fg.isParamDesc(dstDesc)) {
1753 methodGraph.setParamHNode(dstDesc);
1762 // If the method accesses static fields
1763 // set hasGloabalAccess true in the method summary.
1764 if (hasGlobalAccess) {
1765 getMethodSummary(md).setHasGlobalAccess();
1767 methodGraph.getHNode(GLOBALDESC).setSkeleton(true);
1771 private MethodSummary getMethodSummary(MethodDescriptor md) {
1772 if (!mapDescToLocationSummary.containsKey(md)) {
1773 mapDescToLocationSummary.put(md, new MethodSummary(md));
1775 return (MethodSummary) mapDescToLocationSummary.get(md);
1778 private void addMapClassDefinitionToLineNum(ClassDescriptor cd, String strLine, int lineNum) {
1780 String classSymbol = cd.getSymbol();
1781 int idx = classSymbol.lastIndexOf("$");
1783 classSymbol = classSymbol.substring(idx + 1);
1786 String pattern = "class " + classSymbol + " ";
1787 if (strLine.indexOf(pattern) != -1) {
1788 mapDescToDefinitionLine.put(cd, lineNum);
1792 private void addMapMethodDefinitionToLineNum(Set<MethodDescriptor> methodSet, String strLine,
1794 for (Iterator iterator = methodSet.iterator(); iterator.hasNext();) {
1795 MethodDescriptor md = (MethodDescriptor) iterator.next();
1796 String pattern = md.getMethodDeclaration();
1797 if (strLine.indexOf(pattern) != -1) {
1798 mapDescToDefinitionLine.put(md, lineNum);
1799 methodSet.remove(md);
1806 private void readOriginalSourceFiles() {
1808 SymbolTable classtable = state.getClassSymbolTable();
1810 Set<ClassDescriptor> classDescSet = new HashSet<ClassDescriptor>();
1811 classDescSet.addAll(classtable.getValueSet());
1814 // inefficient implement. it may re-visit the same file if the file
1815 // contains more than one class definitions.
1816 for (Iterator iterator = classDescSet.iterator(); iterator.hasNext();) {
1817 ClassDescriptor cd = (ClassDescriptor) iterator.next();
1819 Set<MethodDescriptor> methodSet = new HashSet<MethodDescriptor>();
1820 methodSet.addAll(cd.getMethodTable().getValueSet());
1822 String sourceFileName = cd.getSourceFileName();
1823 Vector<String> lineVec = new Vector<String>();
1825 mapFileNameToLineVector.put(sourceFileName, lineVec);
1827 BufferedReader in = new BufferedReader(new FileReader(sourceFileName));
1830 lineVec.add(""); // the index is started from 1.
1831 while ((strLine = in.readLine()) != null) {
1832 lineVec.add(lineNum, strLine);
1833 addMapClassDefinitionToLineNum(cd, strLine, lineNum);
1834 addMapMethodDefinitionToLineNum(methodSet, strLine, lineNum);
1840 } catch (IOException e) {
1841 e.printStackTrace();
1846 private String generateLatticeDefinition(Descriptor desc) {
1848 Set<String> sharedLocSet = new HashSet<String>();
1850 SSJavaLattice<String> lattice = getLattice(desc);
1851 String rtr = "@LATTICE(\"";
1853 Map<String, Set<String>> map = lattice.getTable();
1854 Set<String> keySet = map.keySet();
1855 boolean first = true;
1856 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1857 String key = (String) iterator.next();
1858 if (!key.equals(lattice.getTopItem())) {
1859 Set<String> connectedSet = map.get(key);
1861 if (connectedSet.size() == 1) {
1862 if (connectedSet.iterator().next().equals(lattice.getBottomItem())) {
1870 if (lattice.isSharedLoc(key)) {
1871 rtr += "," + key + "*";
1876 for (Iterator iterator2 = connectedSet.iterator(); iterator2.hasNext();) {
1877 String loc = (String) iterator2.next();
1878 if (!loc.equals(lattice.getBottomItem())) {
1885 rtr += loc + "<" + key;
1886 if (lattice.isSharedLoc(key) && (!sharedLocSet.contains(key))) {
1887 rtr += "," + key + "*";
1888 sharedLocSet.add(key);
1890 if (lattice.isSharedLoc(loc) && (!sharedLocSet.contains(loc))) {
1891 rtr += "," + loc + "*";
1892 sharedLocSet.add(loc);
1902 if (desc instanceof MethodDescriptor) {
1903 System.out.println("#EXTRA LOC DECLARATION GEN=" + desc);
1905 MethodSummary methodSummary = getMethodSummary((MethodDescriptor) desc);
1907 if (!ssjava.getMethodContainingSSJavaLoop().equals(desc)) {
1908 TypeDescriptor returnType = ((MethodDescriptor) desc).getReturnType();
1909 if (returnType != null && (!returnType.isVoid())) {
1911 "\n@RETURNLOC(\"" + generateLocationAnnoatation(methodSummary.getRETURNLoc()) + "\")";
1913 CompositeLocation pcLoc = methodSummary.getPCLoc();
1914 if ((pcLoc != null) && (!pcLoc.get(0).isTop())) {
1915 rtr += "\n@PCLOC(\"" + generateLocationAnnoatation(pcLoc) + "\")";
1919 rtr += "\n@THISLOC(\"" + methodSummary.getThisLocName() + "\")";
1920 rtr += "\n@GLOBALLOC(\"" + methodSummary.getGlobalLocName() + "\")";
1927 private void generateAnnoatedCode() {
1929 readOriginalSourceFiles();
1932 while (!toAnalyzeIsEmpty()) {
1933 ClassDescriptor cd = toAnalyzeNext();
1935 setupToAnalazeMethod(cd);
1937 String sourceFileName = cd.getSourceFileName();
1939 if (cd.isInterface()) {
1943 int classDefLine = mapDescToDefinitionLine.get(cd);
1944 Vector<String> sourceVec = mapFileNameToLineVector.get(sourceFileName);
1946 LocationSummary fieldLocSummary = getLocationSummary(cd);
1948 String fieldLatticeDefStr = generateLatticeDefinition(cd);
1949 String annoatedSrc = fieldLatticeDefStr + newline + sourceVec.get(classDefLine);
1950 sourceVec.set(classDefLine, annoatedSrc);
1952 // generate annotations for field declarations
1953 // Map<Descriptor, CompositeLocation> inferLocMap = fieldLocInfo.getMapDescToInferLocation();
1954 Map<String, String> mapFieldNameToLocName = fieldLocSummary.getMapHNodeNameToLocationName();
1956 for (Iterator iter = cd.getFields(); iter.hasNext();) {
1957 FieldDescriptor fd = (FieldDescriptor) iter.next();
1959 String locAnnotationStr;
1960 // CompositeLocation inferLoc = inferLocMap.get(fd);
1961 String locName = mapFieldNameToLocName.get(fd.getSymbol());
1963 if (locName != null) {
1964 // infer loc is null if the corresponding field is static and final
1965 // locAnnotationStr = "@LOC(\"" + generateLocationAnnoatation(inferLoc) + "\")";
1966 locAnnotationStr = "@LOC(\"" + locName + "\")";
1967 int fdLineNum = fd.getLineNum();
1968 String orgFieldDeclarationStr = sourceVec.get(fdLineNum);
1969 String fieldDeclaration = fd.toString();
1970 fieldDeclaration = fieldDeclaration.substring(0, fieldDeclaration.length() - 1);
1971 String annoatedStr = locAnnotationStr + " " + orgFieldDeclarationStr;
1972 sourceVec.set(fdLineNum, annoatedStr);
1977 while (!toAnalyzeMethodIsEmpty()) {
1978 MethodDescriptor md = toAnalyzeMethodNext();
1980 if (!ssjava.needTobeAnnotated(md)) {
1984 SSJavaLattice<String> methodLattice = md2lattice.get(md);
1985 if (methodLattice != null) {
1987 int methodDefLine = md.getLineNum();
1989 // MethodLocationInfo methodLocInfo = getMethodLocationInfo(md);
1990 // Map<Descriptor, CompositeLocation> methodInferLocMap =
1991 // methodLocInfo.getMapDescToInferLocation();
1993 MethodSummary methodSummary = getMethodSummary(md);
1995 Map<Descriptor, CompositeLocation> mapVarDescToInferLoc =
1996 methodSummary.getMapVarDescToInferCompositeLocation();
1997 System.out.println("-----md=" + md);
1998 System.out.println("-----mapVarDescToInferLoc=" + mapVarDescToInferLoc);
2000 Set<Descriptor> localVarDescSet = mapVarDescToInferLoc.keySet();
2002 Set<String> localLocElementSet = methodLattice.getElementSet();
2004 for (Iterator iterator = localVarDescSet.iterator(); iterator.hasNext();) {
2005 Descriptor localVarDesc = (Descriptor) iterator.next();
2006 System.out.println("-------localVarDesc=" + localVarDesc);
2007 CompositeLocation inferLoc = mapVarDescToInferLoc.get(localVarDesc);
2009 String localLocIdentifier = inferLoc.get(0).getLocIdentifier();
2010 if (!localLocElementSet.contains(localLocIdentifier)) {
2011 methodLattice.put(localLocIdentifier);
2014 String locAnnotationStr = "@LOC(\"" + generateLocationAnnoatation(inferLoc) + "\")";
2016 if (!isParameter(md, localVarDesc)) {
2017 if (mapDescToDefinitionLine.containsKey(localVarDesc)) {
2018 int varLineNum = mapDescToDefinitionLine.get(localVarDesc);
2019 String orgSourceLine = sourceVec.get(varLineNum);
2021 orgSourceLine.indexOf(generateVarDeclaration((VarDescriptor) localVarDesc));
2023 String annoatedStr =
2024 orgSourceLine.substring(0, idx) + locAnnotationStr + " "
2025 + orgSourceLine.substring(idx);
2026 sourceVec.set(varLineNum, annoatedStr);
2029 String methodDefStr = sourceVec.get(methodDefLine);
2032 getParamLocation(methodDefStr,
2033 generateVarDeclaration((VarDescriptor) localVarDesc));
2037 String annoatedStr =
2038 methodDefStr.substring(0, idx) + locAnnotationStr + " "
2039 + methodDefStr.substring(idx);
2040 sourceVec.set(methodDefLine, annoatedStr);
2045 // check if the lattice has to have the location type for the this
2048 // boolean needToAddthisRef = hasThisReference(md);
2049 // if (localLocElementSet.contains("this")) {
2050 // methodLattice.put("this");
2053 String methodLatticeDefStr = generateLatticeDefinition(md);
2054 String annoatedStr = methodLatticeDefStr + newline + sourceVec.get(methodDefLine);
2055 sourceVec.set(methodDefLine, annoatedStr);
2065 private boolean hasThisReference(MethodDescriptor md) {
2067 FlowGraph fg = getFlowGraph(md);
2068 Set<FlowNode> nodeSet = fg.getNodeSet();
2069 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
2070 FlowNode flowNode = (FlowNode) iterator.next();
2071 if (flowNode.getDescTuple().get(0).equals(md.getThis())) {
2079 private int getParamLocation(String methodStr, String paramStr) {
2081 String pattern = paramStr + ",";
2083 int idx = methodStr.indexOf(pattern);
2087 pattern = paramStr + ")";
2088 return methodStr.indexOf(pattern);
2093 private String generateVarDeclaration(VarDescriptor varDesc) {
2095 TypeDescriptor td = varDesc.getType();
2096 String rtr = td.toString();
2098 for (int i = 0; i < td.getArrayCount(); i++) {
2102 rtr += " " + varDesc.getName();
2107 private String generateLocationAnnoatation(CompositeLocation loc) {
2108 System.out.println("loc=" + loc);
2111 Location methodLoc = loc.get(0);
2112 rtr += methodLoc.getLocIdentifier();
2114 for (int i = 1; i < loc.getSize(); i++) {
2115 Location element = loc.get(i);
2116 rtr += "," + element.getDescriptor().getSymbol() + "." + element.getLocIdentifier();
2122 private boolean isParameter(MethodDescriptor md, Descriptor localVarDesc) {
2123 return getFlowGraph(md).isParamDesc(localVarDesc);
2126 private String extractFileName(String fileName) {
2127 int idx = fileName.lastIndexOf("/");
2131 return fileName.substring(idx + 1);
2136 private void codeGen() {
2138 Set<String> originalFileNameSet = mapFileNameToLineVector.keySet();
2139 for (Iterator iterator = originalFileNameSet.iterator(); iterator.hasNext();) {
2140 String orgFileName = (String) iterator.next();
2141 String outputFileName = extractFileName(orgFileName);
2143 Vector<String> sourceVec = mapFileNameToLineVector.get(orgFileName);
2147 FileWriter fileWriter = new FileWriter("./infer/" + outputFileName);
2148 BufferedWriter out = new BufferedWriter(fileWriter);
2150 for (int i = 0; i < sourceVec.size(); i++) {
2151 out.write(sourceVec.get(i));
2155 } catch (IOException e) {
2156 e.printStackTrace();
2163 private void checkLattices() {
2165 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
2167 // current descriptors to visit in fixed-point interprocedural analysis,
2169 // dependency in the call graph
2170 methodDescriptorsToVisitStack.clear();
2172 // descriptorListToAnalyze.removeFirst();
2174 Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
2175 methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
2177 while (!descriptorListToAnalyze.isEmpty()) {
2178 MethodDescriptor md = descriptorListToAnalyze.removeFirst();
2179 checkLatticesOfVirtualMethods(md);
2184 private void debug_writeLatticeDotFile() {
2185 // generate lattice dot file
2189 while (!toAnalyzeIsEmpty()) {
2190 ClassDescriptor cd = toAnalyzeNext();
2192 setupToAnalazeMethod(cd);
2194 SSJavaLattice<String> classLattice = cd2lattice.get(cd);
2195 if (classLattice != null) {
2196 ssjava.writeLatticeDotFile(cd, null, classLattice);
2197 debug_printDescriptorToLocNameMapping(cd);
2200 while (!toAnalyzeMethodIsEmpty()) {
2201 MethodDescriptor md = toAnalyzeMethodNext();
2202 SSJavaLattice<String> methodLattice = md2lattice.get(md);
2203 if (methodLattice != null) {
2204 ssjava.writeLatticeDotFile(cd, md, methodLattice);
2205 debug_printDescriptorToLocNameMapping(md);
2212 private void debug_printDescriptorToLocNameMapping(Descriptor desc) {
2214 LocationInfo info = getLocationInfo(desc);
2215 System.out.println("## " + desc + " ##");
2216 System.out.println(info.getMapDescToInferLocation());
2217 LocationInfo locInfo = getLocationInfo(desc);
2218 System.out.println("mapping=" + locInfo.getMapLocSymbolToDescSet());
2219 System.out.println("###################");
2223 private void inferLattices() {
2226 private void calculateExtraLocations() {
2227 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
2228 for (Iterator iterator = descriptorListToAnalyze.iterator(); iterator.hasNext();) {
2229 MethodDescriptor md = (MethodDescriptor) iterator.next();
2230 if (!ssjava.getMethodContainingSSJavaLoop().equals(md)) {
2231 calculateExtraLocations(md);
2236 private void checkLatticesOfVirtualMethods(MethodDescriptor md) {
2238 if (!md.isStatic()) {
2239 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
2240 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
2242 for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
2243 MethodDescriptor mdCallee = (MethodDescriptor) iterator.next();
2244 if (!md.equals(mdCallee)) {
2245 checkConsistency(md, mdCallee);
2253 private void checkConsistency(MethodDescriptor md1, MethodDescriptor md2) {
2255 // check that two lattice have the same relations between parameters(+PC
2256 // LOC, GLOBAL_LOC RETURN LOC)
2258 List<CompositeLocation> list1 = new ArrayList<CompositeLocation>();
2259 List<CompositeLocation> list2 = new ArrayList<CompositeLocation>();
2261 MethodLocationInfo locInfo1 = getMethodLocationInfo(md1);
2262 MethodLocationInfo locInfo2 = getMethodLocationInfo(md2);
2264 Map<Integer, CompositeLocation> paramMap1 = locInfo1.getMapParamIdxToInferLoc();
2265 Map<Integer, CompositeLocation> paramMap2 = locInfo2.getMapParamIdxToInferLoc();
2267 int numParam = locInfo1.getMapParamIdxToInferLoc().keySet().size();
2269 // add location types of paramters
2270 for (int idx = 0; idx < numParam; idx++) {
2271 list1.add(paramMap1.get(Integer.valueOf(idx)));
2272 list2.add(paramMap2.get(Integer.valueOf(idx)));
2275 // add program counter location
2276 list1.add(locInfo1.getPCLoc());
2277 list2.add(locInfo2.getPCLoc());
2279 if (!md1.getReturnType().isVoid()) {
2280 // add return value location
2281 CompositeLocation rtrLoc1 = getMethodLocationInfo(md1).getReturnLoc();
2282 CompositeLocation rtrLoc2 = getMethodLocationInfo(md2).getReturnLoc();
2287 // add global location type
2288 if (md1.isStatic()) {
2289 CompositeLocation globalLoc1 =
2290 new CompositeLocation(new Location(md1, locInfo1.getGlobalLocName()));
2291 CompositeLocation globalLoc2 =
2292 new CompositeLocation(new Location(md2, locInfo2.getGlobalLocName()));
2293 list1.add(globalLoc1);
2294 list2.add(globalLoc2);
2297 for (int i = 0; i < list1.size(); i++) {
2298 CompositeLocation locA1 = list1.get(i);
2299 CompositeLocation locA2 = list2.get(i);
2300 for (int k = 0; k < list1.size(); k++) {
2302 CompositeLocation locB1 = list1.get(k);
2303 CompositeLocation locB2 = list2.get(k);
2304 boolean r1 = isGreaterThan(getLattice(md1), locA1, locB1);
2306 boolean r2 = isGreaterThan(getLattice(md1), locA2, locB2);
2309 throw new Error("The method " + md1 + " is not consistent with the method " + md2
2310 + ".:: They have a different ordering relation between locations (" + locA1 + ","
2311 + locB1 + ") and (" + locA2 + "," + locB2 + ").");
2319 private String getSymbol(int idx, FlowNode node) {
2320 Descriptor desc = node.getDescTuple().get(idx);
2321 return desc.getSymbol();
2324 private Descriptor getDescriptor(int idx, FlowNode node) {
2325 Descriptor desc = node.getDescTuple().get(idx);
2329 private void calculatePCLOC(MethodDescriptor md) {
2331 System.out.println("#calcualtePCLOC");
2332 MethodSummary methodSummary = getMethodSummary(md);
2333 FlowGraph fg = getFlowGraph(md);
2334 Map<Integer, CompositeLocation> mapParamToLoc = methodSummary.getMapParamIdxToInferLoc();
2336 // calculate the initial program counter location
2337 // PC location is higher than location types of parameters which has incoming flows.
2339 Set<NTuple<Location>> paramLocTupleHavingInFlowSet = new HashSet<NTuple<Location>>();
2341 int numParams = fg.getNumParameters();
2342 for (int i = 0; i < numParams; i++) {
2343 FlowNode paramFlowNode = fg.getParamFlowNode(i);
2344 Descriptor prefix = paramFlowNode.getDescTuple().get(0);
2346 if (fg.getIncomingNodeSetByPrefix(prefix).size() > 0) {
2347 // parameter has in-value flows
2348 NTuple<Descriptor> paramDescTuple = paramFlowNode.getCurrentDescTuple();
2349 NTuple<Location> paramLocTuple = translateToLocTuple(md, paramDescTuple);
2350 paramLocTupleHavingInFlowSet.add(paramLocTuple);
2354 System.out.println("paramLocTupleHavingInFlowSet=" + paramLocTupleHavingInFlowSet);
2356 if (paramLocTupleHavingInFlowSet.size() > 0
2357 && !coversAllParamters(md, fg, paramLocTupleHavingInFlowSet)) {
2359 // Here, generates a location in the method lattice that is higher than the
2360 // paramLocTupleHavingInFlowSet
2361 NTuple<Location> pcLocTuple =
2362 generateLocTupleRelativeTo(md, paramLocTupleHavingInFlowSet, PCLOC);
2364 int pcLocTupleIdx = pcLocTuple.size() - 1;
2365 Location pcLoc = pcLocTuple.get(pcLocTupleIdx);
2366 Descriptor pcDesc = pcLoc.getLocDescriptor();
2367 Descriptor enclosingDesc = pcLocTuple.get(pcLocTupleIdx).getDescriptor();
2369 HierarchyGraph hierarchyGraph = getHierarchyGraph(enclosingDesc);
2370 HNode pcNode = hierarchyGraph.getHNode(pcDesc);
2371 pcNode.setSkeleton(true);
2373 for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
2374 NTuple<Location> paramLocTuple = (NTuple<Location>) iterator.next();
2375 if (paramLocTuple.size() > pcLocTupleIdx) {
2376 Descriptor lowerDesc = paramLocTuple.get(pcLocTupleIdx).getLocDescriptor();
2377 hierarchyGraph.addEdge(pcDesc, lowerDesc);
2381 System.out.println("pcLoc=" + pcLoc);
2383 methodSummary.setPCLoc(new CompositeLocation(pcLocTuple));
2387 private boolean coversAllParamters(MethodDescriptor md, FlowGraph fg,
2388 Set<NTuple<Location>> paramLocTupleHavingInFlowSet) {
2390 int numParam = fg.getNumParameters();
2391 int size = paramLocTupleHavingInFlowSet.size();
2393 if (!md.isStatic()) {
2395 // if the method is not static && there is a parameter composite location &&
2396 // it is started with 'this',
2397 // paramLocTupleHavingInFlowSet need to have 'this' parameter.
2399 FlowNode thisParamNode = fg.getParamFlowNode(0);
2400 NTuple<Location> thisParamLocTuple =
2401 translateToLocTuple(md, thisParamNode.getCurrentDescTuple());
2403 if (!paramLocTupleHavingInFlowSet.contains(thisParamLocTuple)) {
2405 for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
2406 NTuple<Location> paramTuple = (NTuple<Location>) iterator.next();
2407 if (paramTuple.size() > 1 && paramTuple.get(0).getLocDescriptor().equals(md.getThis())) {
2408 // paramLocTupleHavingInFlowSet.add(thisParamLocTuple);
2417 if (size == numParam) {
2425 private void calculateRETURNLOC(MethodDescriptor md) {
2427 System.out.println("#calculateRETURNLOC= " + md);
2428 // calculate a return location:
2429 // the return location type is lower than all parameters and the location of return values
2431 MethodSummary methodSummary = getMethodSummary(md);
2433 FlowGraph fg = getFlowGraph(md);
2435 Map<Integer, CompositeLocation> mapParamToLoc = methodSummary.getMapParamIdxToInferLoc();
2436 Set<Integer> paramIdxSet = mapParamToLoc.keySet();
2438 if (!md.getReturnType().isVoid()) {
2439 // first, generate the set of return value location types that starts
2440 // with 'this' reference
2442 Set<NTuple<Location>> inferFieldReturnLocSet = new HashSet<NTuple<Location>>();
2444 Set<FlowNode> paramFlowNodeFlowingToReturnValueSet = getParamNodeFlowingToReturnValue(md);
2445 System.out.println("paramFlowNodeFlowingToReturnValueSet="
2446 + paramFlowNodeFlowingToReturnValueSet);
2448 Set<NTuple<Location>> locFlowingToReturnValueSet = new HashSet<NTuple<Location>>();
2449 for (Iterator iterator = paramFlowNodeFlowingToReturnValueSet.iterator(); iterator.hasNext();) {
2450 FlowNode fn = (FlowNode) iterator.next();
2452 NTuple<Descriptor> paramDescTuple = fn.getCurrentDescTuple();
2453 NTuple<Location> paramLocTuple = translateToLocTuple(md, paramDescTuple);
2455 locFlowingToReturnValueSet.add(paramLocTuple);
2458 Set<FlowNode> returnNodeSet = fg.getReturnNodeSet();
2459 for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2460 FlowNode returnNode = (FlowNode) iterator.next();
2461 NTuple<Descriptor> returnDescTuple = returnNode.getCurrentDescTuple();
2462 NTuple<Location> returnLocTuple = translateToLocTuple(md, returnDescTuple);
2463 locFlowingToReturnValueSet.add(returnLocTuple);
2465 System.out.println("locFlowingToReturnValueSet=" + locFlowingToReturnValueSet);
2467 // Here, generates a return location in the method lattice that is lower than the
2468 // locFlowingToReturnValueSet
2469 NTuple<Location> returnLocTuple =
2470 generateLocTupleRelativeTo(md, locFlowingToReturnValueSet, RLOC);
2472 System.out.println("returnLocTuple=" + returnLocTuple);
2474 int returnLocTupleIdx = returnLocTuple.size() - 1;
2475 Location returnLoc = returnLocTuple.get(returnLocTupleIdx);
2476 Descriptor returnDesc = returnLoc.getLocDescriptor();
2477 Descriptor enclosingDesc = returnLocTuple.get(returnLocTupleIdx).getDescriptor();
2479 HierarchyGraph hierarchyGraph = getHierarchyGraph(enclosingDesc);
2480 HNode returnNode = hierarchyGraph.getHNode(returnDesc);
2481 returnNode.setSkeleton(true);
2483 for (Iterator iterator = locFlowingToReturnValueSet.iterator(); iterator.hasNext();) {
2484 NTuple<Location> locTuple = (NTuple<Location>) iterator.next();
2485 Descriptor higherDesc = locTuple.get(returnLocTupleIdx).getLocDescriptor();
2486 hierarchyGraph.addEdge(higherDesc, returnDesc);
2489 methodSummary.setRETURNLoc(new CompositeLocation(returnLocTuple));
2491 // skip: for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2492 // FlowNode returnNode = (FlowNode) iterator.next();
2494 // NTuple<Descriptor> returnDescTuple = returnNode.getCurrentDescTuple();
2495 // NTuple<Location> returnLocTuple = translateToLocTuple(md, returnDescTuple);
2497 // if (returnLocTuple.get(0).getLocDescriptor().equals(md.getThis())) {
2498 // // if the location type of the return value matches "this" reference
2499 // // then, check whether this return value is equal to/lower than all
2500 // // of parameters that possibly flow into the return values
2501 // for (Iterator iterator2 = inferParamLocSet.iterator(); iterator2.hasNext();) {
2502 // CompositeLocation paramInferLoc = (CompositeLocation) iterator2.next();
2504 // if ((!paramInferLoc.equals(returnLocTuple))
2505 // && !isGreaterThan(methodLattice, paramInferLoc, inferReturnLoc)) {
2509 // inferFieldReturnLocSet.add(returnLocTuple);
2514 // if (inferFieldReturnLocSet.size() > 0) {
2516 // // CompositeLocation returnLoc = getLowest(methodLattice, inferFieldReturnLocSet);
2517 // CompositeLocation returnLoc = null;
2518 // if (returnLoc == null) {
2519 // // in this case, assign <'this',bottom> to the RETURNLOC
2520 // returnLoc = new CompositeLocation(new Location(md, md.getThis().getSymbol()));
2521 // returnLoc.addLocation(new Location(md.getClassDesc(), getLattice(md.getClassDesc())
2522 // .getBottomItem()));
2524 // methodInfo.setReturnLoc(returnLoc);
2527 // String returnLocSymbol = "RETURNLOC";
2528 // CompositeLocation returnLocInferLoc =
2529 // new CompositeLocation(new Location(md, returnLocSymbol));
2530 // methodInfo.setReturnLoc(returnLocInferLoc);
2532 // for (Iterator iterator = paramIdxSet.iterator(); iterator.hasNext();) {
2533 // Integer paramIdx = (Integer) iterator.next();
2534 // CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
2535 // String paramLocLocalSymbol = inferLoc.get(0).getLocIdentifier();
2536 // if (!methodLattice.isGreaterThan(paramLocLocalSymbol, returnLocSymbol)) {
2538 // // addRelationHigherToLower(methodLattice, methodInfo,
2539 // // paramLocLocalSymbol,
2540 // // returnLocSymbol);
2544 // for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2545 // FlowNode returnNode = (FlowNode) iterator.next();
2546 // CompositeLocation inferLoc =
2547 // generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
2548 // if (!isGreaterThan(methodLattice, inferLoc, returnLocInferLoc)) {
2550 // // addRelation(methodLattice, methodInfo, inferLoc,
2551 // // returnLocInferLoc);
2560 private void calculateExtraLocations(MethodDescriptor md) {
2561 // calcualte pcloc, returnloc,...
2563 System.out.println("\nSSJAVA:Calculate PCLOC/RETURNLOC locations: " + md);
2566 calculateRETURNLOC(md);
2570 private NTuple<Location> generateLocTupleRelativeTo(MethodDescriptor md,
2571 Set<NTuple<Location>> paramLocTupleHavingInFlowSet, String locNamePrefix) {
2573 System.out.println("-generateLocTupleRelativeTo=" + paramLocTupleHavingInFlowSet);
2575 NTuple<Location> higherLocTuple = new NTuple<Location>();
2577 VarDescriptor thisVarDesc = md.getThis();
2578 // check if all paramter loc tuple is started with 'this' reference
2579 boolean hasParamNotStartedWithThisRef = false;
2583 Set<NTuple<Location>> paramLocTupleStartedWithThis = new HashSet<NTuple<Location>>();
2585 for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
2586 NTuple<Location> paramLocTuple = (NTuple<Location>) iterator.next();
2587 if (!paramLocTuple.get(0).getLocDescriptor().equals(thisVarDesc)) {
2588 hasParamNotStartedWithThisRef = true;
2589 } else if (paramLocTuple.size() > 1) {
2590 paramLocTupleStartedWithThis.add(paramLocTuple);
2591 if (minSize == 0 || minSize > paramLocTuple.size()) {
2592 minSize = paramLocTuple.size();
2597 System.out.println("---paramLocTupleStartedWithThis=" + paramLocTupleStartedWithThis);
2598 Descriptor enclosingDesc = md;
2599 if (hasParamNotStartedWithThisRef) {
2600 // in this case, PCLOC will be the local location
2602 // all parameter is started with 'this', so PCLOC will be set relative to the composite
2603 // location started with 'this'.
2604 for (int idx = 0; idx < minSize - 1; idx++) {
2605 Set<Descriptor> locDescSet = new HashSet<Descriptor>();
2606 Location curLoc = null;
2607 NTuple<Location> paramLocTuple = null;
2608 for (Iterator iterator = paramLocTupleStartedWithThis.iterator(); iterator.hasNext();) {
2609 paramLocTuple = (NTuple<Location>) iterator.next();
2610 System.out.println("-----paramLocTuple=" + paramLocTuple + " idx=" + idx);
2611 curLoc = paramLocTuple.get(idx);
2612 Descriptor locDesc = curLoc.getLocDescriptor();
2613 locDescSet.add(locDesc);
2615 System.out.println("-----locDescSet=" + locDescSet + " idx=" + idx);
2616 if (locDescSet.size() != 1) {
2619 Location newLocElement = new Location(curLoc.getDescriptor(), curLoc.getLocDescriptor());
2620 higherLocTuple.add(newLocElement);
2621 enclosingDesc = getClassTypeDescriptor(curLoc.getLocDescriptor());
2626 String pcLocIdentifier = locNamePrefix + (locSeed++);
2627 NameDescriptor pcLocDesc = new NameDescriptor(pcLocIdentifier);
2628 Location newLoc = new Location(enclosingDesc, pcLocDesc);
2629 higherLocTuple.add(newLoc);
2631 System.out.println("---new loc tuple=" + higherLocTuple);
2633 return higherLocTuple;
2637 public ClassDescriptor getClassTypeDescriptor(Descriptor in) {
2639 if (in instanceof VarDescriptor) {
2640 return ((VarDescriptor) in).getType().getClassDesc();
2641 } else if (in instanceof FieldDescriptor) {
2642 return ((FieldDescriptor) in).getType().getClassDesc();
2644 // else if (in instanceof LocationDescriptor) {
2645 // // here is the case that the descriptor 'in' is the last element of the assigned composite
2647 // return ((VarDescriptor) locTuple.get(0).getLocDescriptor()).getType().getClassDesc();
2655 private Set<NTuple<Location>> calculateHighestLocTupleSet(
2656 Set<NTuple<Location>> paramLocTupleHavingInFlowSet) {
2658 Set<NTuple<Location>> highestSet = new HashSet<NTuple<Location>>();
2660 Iterator<NTuple<Location>> iterator = paramLocTupleHavingInFlowSet.iterator();
2661 NTuple<Location> highest = iterator.next();
2663 for (; iterator.hasNext();) {
2664 NTuple<Location> curLocTuple = (NTuple<Location>) iterator.next();
2665 if (isHigherThan(curLocTuple, highest)) {
2666 System.out.println(curLocTuple + " is greater than " + highest);
2667 highest = curLocTuple;
2671 highestSet.add(highest);
2673 MethodDescriptor md = (MethodDescriptor) highest.get(0).getDescriptor();
2674 VarDescriptor thisVarDesc = md.getThis();
2676 System.out.println("highest=" + highest);
2678 for (Iterator<NTuple<Location>> iter = paramLocTupleHavingInFlowSet.iterator(); iter.hasNext();) {
2679 NTuple<Location> curLocTuple = iter.next();
2681 if (!curLocTuple.equals(highest) && !hasOrderingRelation(highest, curLocTuple)) {
2683 System.out.println("add it to the highest set=" + curLocTuple);
2684 highestSet.add(curLocTuple);
2693 private void calculateExtraLocations2(MethodDescriptor md) {
2694 // calcualte pcloc, returnloc,...
2696 SSJavaLattice<String> methodLattice = getMethodLattice(md);
2697 MethodLocationInfo methodInfo = getMethodLocationInfo(md);
2698 FlowGraph fg = getFlowGraph(md);
2699 Set<FlowNode> nodeSet = fg.getNodeSet();
2701 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
2702 FlowNode flowNode = (FlowNode) iterator.next();
2703 if (flowNode.isDeclaratonNode()) {
2704 CompositeLocation inferLoc = methodInfo.getInferLocation(flowNode.getDescTuple().get(0));
2705 String locIdentifier = inferLoc.get(0).getLocIdentifier();
2706 if (!methodLattice.containsKey(locIdentifier)) {
2707 methodLattice.put(locIdentifier);
2713 Map<Integer, CompositeLocation> mapParamToLoc = methodInfo.getMapParamIdxToInferLoc();
2714 Set<Integer> paramIdxSet = mapParamToLoc.keySet();
2716 if (!ssjava.getMethodContainingSSJavaLoop().equals(md)) {
2717 // calculate the initial program counter location
2718 // PC location is higher than location types of all parameters
2719 String pcLocSymbol = "PCLOC";
2721 Set<CompositeLocation> paramInFlowSet = new HashSet<CompositeLocation>();
2723 for (Iterator iterator = paramIdxSet.iterator(); iterator.hasNext();) {
2724 Integer paramIdx = (Integer) iterator.next();
2726 FlowNode paramFlowNode = fg.getParamFlowNode(paramIdx);
2728 if (fg.getIncomingFlowNodeSet(paramFlowNode).size() > 0) {
2729 // parameter has in-value flows
2730 CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
2731 paramInFlowSet.add(inferLoc);
2735 if (paramInFlowSet.size() > 0) {
2736 CompositeLocation lowestLoc = getLowest(methodLattice, paramInFlowSet);
2737 assert (lowestLoc != null);
2738 methodInfo.setPCLoc(lowestLoc);
2743 // calculate a return location
2744 // the return location type is lower than all parameters and location
2747 if (!md.getReturnType().isVoid()) {
2748 // first, generate the set of return value location types that starts
2752 Set<CompositeLocation> inferFieldReturnLocSet = new HashSet<CompositeLocation>();
2754 Set<FlowNode> paramFlowNode = getParamNodeFlowingToReturnValue(md);
2755 Set<CompositeLocation> inferParamLocSet = new HashSet<CompositeLocation>();
2756 if (paramFlowNode != null) {
2757 for (Iterator iterator = paramFlowNode.iterator(); iterator.hasNext();) {
2758 FlowNode fn = (FlowNode) iterator.next();
2759 CompositeLocation inferLoc =
2760 generateInferredCompositeLocation(methodInfo, getFlowGraph(md).getLocationTuple(fn));
2761 inferParamLocSet.add(inferLoc);
2765 Set<FlowNode> returnNodeSet = fg.getReturnNodeSet();
2767 skip: for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2768 FlowNode returnNode = (FlowNode) iterator.next();
2769 CompositeLocation inferReturnLoc =
2770 generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
2771 if (inferReturnLoc.get(0).getLocIdentifier().equals("this")) {
2772 // if the location type of the return value matches "this" reference
2773 // then, check whether this return value is equal to/lower than all
2775 // parameters that possibly flow into the return values
2776 for (Iterator iterator2 = inferParamLocSet.iterator(); iterator2.hasNext();) {
2777 CompositeLocation paramInferLoc = (CompositeLocation) iterator2.next();
2779 if ((!paramInferLoc.equals(inferReturnLoc))
2780 && !isGreaterThan(methodLattice, paramInferLoc, inferReturnLoc)) {
2784 inferFieldReturnLocSet.add(inferReturnLoc);
2789 if (inferFieldReturnLocSet.size() > 0) {
2791 CompositeLocation returnLoc = getLowest(methodLattice, inferFieldReturnLocSet);
2792 if (returnLoc == null) {
2793 // in this case, assign <'this',bottom> to the RETURNLOC
2794 returnLoc = new CompositeLocation(new Location(md, md.getThis().getSymbol()));
2795 returnLoc.addLocation(new Location(md.getClassDesc(), getLattice(md.getClassDesc())
2798 methodInfo.setReturnLoc(returnLoc);
2801 String returnLocSymbol = "RETURNLOC";
2802 CompositeLocation returnLocInferLoc =
2803 new CompositeLocation(new Location(md, returnLocSymbol));
2804 methodInfo.setReturnLoc(returnLocInferLoc);
2806 for (Iterator iterator = paramIdxSet.iterator(); iterator.hasNext();) {
2807 Integer paramIdx = (Integer) iterator.next();
2808 CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
2809 String paramLocLocalSymbol = inferLoc.get(0).getLocIdentifier();
2810 if (!methodLattice.isGreaterThan(paramLocLocalSymbol, returnLocSymbol)) {
2812 // addRelationHigherToLower(methodLattice, methodInfo,
2813 // paramLocLocalSymbol,
2814 // returnLocSymbol);
2818 for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2819 FlowNode returnNode = (FlowNode) iterator.next();
2820 CompositeLocation inferLoc =
2821 generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
2822 if (!isGreaterThan(methodLattice, inferLoc, returnLocInferLoc)) {
2824 // addRelation(methodLattice, methodInfo, inferLoc,
2825 // returnLocInferLoc);
2834 private Set<String> getHigherLocSymbolThan(SSJavaLattice<String> lattice, String loc) {
2835 Set<String> higherLocSet = new HashSet<String>();
2837 Set<String> locSet = lattice.getTable().keySet();
2838 for (Iterator iterator = locSet.iterator(); iterator.hasNext();) {
2839 String element = (String) iterator.next();
2840 if (lattice.isGreaterThan(element, loc) && (!element.equals(lattice.getTopItem()))) {
2841 higherLocSet.add(element);
2844 return higherLocSet;
2847 private CompositeLocation getLowest(SSJavaLattice<String> methodLattice,
2848 Set<CompositeLocation> set) {
2850 CompositeLocation lowest = set.iterator().next();
2852 if (set.size() == 1) {
2856 for (Iterator iterator = set.iterator(); iterator.hasNext();) {
2857 CompositeLocation loc = (CompositeLocation) iterator.next();
2859 if ((!loc.equals(lowest)) && (!isComparable(methodLattice, lowest, loc))) {
2860 // if there is a case where composite locations are incomparable, just
2865 if ((!loc.equals(lowest)) && isGreaterThan(methodLattice, lowest, loc)) {
2872 private boolean isComparable(SSJavaLattice<String> methodLattice, CompositeLocation comp1,
2873 CompositeLocation comp2) {
2875 int size = comp1.getSize() >= comp2.getSize() ? comp2.getSize() : comp1.getSize();
2877 for (int idx = 0; idx < size; idx++) {
2878 Location loc1 = comp1.get(idx);
2879 Location loc2 = comp2.get(idx);
2881 Descriptor desc1 = loc1.getDescriptor();
2882 Descriptor desc2 = loc2.getDescriptor();
2884 if (!desc1.equals(desc2)) {
2885 throw new Error("Fail to compare " + comp1 + " and " + comp2);
2888 String symbol1 = loc1.getLocIdentifier();
2889 String symbol2 = loc2.getLocIdentifier();
2891 SSJavaLattice<String> lattice;
2893 lattice = methodLattice;
2895 lattice = getLattice(desc1);
2898 if (symbol1.equals(symbol2)) {
2900 } else if (!lattice.isComparable(symbol1, symbol2)) {
2909 private boolean isGreaterThan(SSJavaLattice<String> methodLattice, CompositeLocation comp1,
2910 CompositeLocation comp2) {
2912 int size = comp1.getSize() >= comp2.getSize() ? comp2.getSize() : comp1.getSize();
2914 for (int idx = 0; idx < size; idx++) {
2915 Location loc1 = comp1.get(idx);
2916 Location loc2 = comp2.get(idx);
2918 Descriptor desc1 = loc1.getDescriptor();
2919 Descriptor desc2 = loc2.getDescriptor();
2921 if (!desc1.equals(desc2)) {
2922 throw new Error("Fail to compare " + comp1 + " and " + comp2);
2925 String symbol1 = loc1.getLocIdentifier();
2926 String symbol2 = loc2.getLocIdentifier();
2928 SSJavaLattice<String> lattice;
2930 lattice = methodLattice;
2932 lattice = getLattice(desc1);
2935 if (symbol1.equals(symbol2)) {
2937 } else if (lattice.isGreaterThan(symbol1, symbol2)) {
2948 private void contributeCalleeFlows(MethodInvokeNode min, MethodDescriptor mdCaller,
2949 MethodDescriptor mdCallee) {
2951 System.out.println("\n##contributeCalleeFlows callee=" + mdCallee + "TO caller=" + mdCaller);
2953 getSubGlobalFlowGraph(mdCallee);
2957 private GlobalFlowGraph getSubGlobalFlowGraph(MethodDescriptor md) {
2958 return mapMethodDescriptorToSubGlobalFlowGraph.get(md);
2961 private void propagateFlowsToCallerWithNoCompositeLocation(MethodInvokeNode min,
2962 MethodDescriptor mdCaller, MethodDescriptor mdCallee) {
2965 // if the parameter A reaches to the parameter B
2966 // then, add an edge the argument A -> the argument B to the caller's flow
2969 FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
2970 FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
2971 int numParam = calleeFlowGraph.getNumParameters();
2973 for (int i = 0; i < numParam; i++) {
2974 for (int k = 0; k < numParam; k++) {
2978 FlowNode paramNode1 = calleeFlowGraph.getParamFlowNode(i);
2979 FlowNode paramNode2 = calleeFlowGraph.getParamFlowNode(k);
2981 NTuple<Descriptor> arg1Tuple = getNodeTupleByArgIdx(min, i);
2982 NTuple<Descriptor> arg2Tuple = getNodeTupleByArgIdx(min, k);
2984 // check if the callee propagates an ordering constraints through
2987 Set<FlowNode> localReachSet = calleeFlowGraph.getLocalReachFlowNodeSetFrom(paramNode1);
2988 // System.out.println("-param1=" + paramNode1 + " is higher than param2=" + paramNode2);
2989 // System.out.println("-- localReachSet from param1=" + localReachSet);
2991 if (arg1Tuple.size() > 0 && arg2Tuple.size() > 0 && localReachSet.contains(paramNode2)) {
2992 // need to propagate an ordering relation s.t. arg1 is higher
2996 // .println("-arg1Tuple=" + arg1Tuple + " is higher than arg2Tuple=" + arg2Tuple);
2998 // otherwise, flows between method/field locations...
2999 callerFlowGraph.addValueFlowEdge(arg1Tuple, arg2Tuple);
3000 // System.out.println("arg1=" + arg1Tuple + " arg2=" + arg2Tuple);
3004 System.out.println();
3008 // System.out.println("##\n");
3012 private void propagateFlowsToCaller(MethodInvokeNode min, MethodDescriptor mdCaller,
3013 MethodDescriptor mdCallee) {
3015 System.out.println("\n##PROPAGATE callee=" + mdCallee + "TO caller=" + mdCaller);
3017 // if the parameter A reaches to the parameter B
3018 // then, add an edge the argument A -> the argument B to the caller's flow
3022 // also if a parameter is a composite location and is started with "this"
3024 // need to make sure that the corresponding argument is higher than the
3025 // translated location of
3028 FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
3029 FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
3030 int numParam = calleeFlowGraph.getNumParameters();
3032 for (int i = 0; i < numParam; i++) {
3033 for (int k = 0; k < numParam; k++) {
3037 FlowNode paramNode1 = calleeFlowGraph.getParamFlowNode(i);
3038 FlowNode paramNode2 = calleeFlowGraph.getParamFlowNode(k);
3040 System.out.println("param1=" + paramNode1 + " curDescTuple="
3041 + paramNode1.getCurrentDescTuple());
3042 System.out.println("param2=" + paramNode2 + " curDescTuple="
3043 + paramNode2.getCurrentDescTuple());
3045 // TODO: deprecated method
3046 // NodeTupleSet tupleSetArg1 = getNodeTupleSetByArgIdx(min, i);
3047 // NodeTupleSet tupleSetArg2 = getNodeTupleSetByArgIdx(min, k);
3048 NodeTupleSet tupleSetArg1 = null;
3049 NodeTupleSet tupleSetArg2 = null;
3051 for (Iterator<NTuple<Descriptor>> iter1 = tupleSetArg1.iterator(); iter1.hasNext();) {
3052 NTuple<Descriptor> arg1Tuple = iter1.next();
3054 for (Iterator<NTuple<Descriptor>> iter2 = tupleSetArg2.iterator(); iter2.hasNext();) {
3055 NTuple<Descriptor> arg2Tuple = iter2.next();
3057 // check if the callee propagates an ordering constraints through
3060 Set<FlowNode> localReachSet =
3061 calleeFlowGraph.getLocalReachFlowNodeSetFrom(paramNode1);
3063 if (localReachSet.contains(paramNode2)) {
3064 // need to propagate an ordering relation s.t. arg1 is higher
3068 .println("-param1=" + paramNode1 + " is higher than param2=" + paramNode2);
3069 System.out.println("-arg1Tuple=" + arg1Tuple + " is higher than arg2Tuple="
3072 if (!min.getMethod().isStatic()) {
3073 // check if this is the case that values flow to/from the
3074 // current object reference 'this'
3076 NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
3077 Descriptor baseRef = baseTuple.get(baseTuple.size() - 1);
3079 System.out.println("paramNode1.getCurrentDescTuple()="
3080 + paramNode1.getCurrentDescTuple());
3081 // calculate the prefix of the argument
3083 if (arg2Tuple.size() == 1 && arg2Tuple.get(0).equals(baseRef)) {
3084 // in this case, the callee flow causes a caller flow to the
3085 // object whose method
3088 if (!paramNode1.getCurrentDescTuple().startsWith(mdCallee.getThis())) {
3089 // check whether ???
3091 NTuple<Descriptor> param1Prefix =
3092 calculatePrefixForParam(callerFlowGraph, calleeFlowGraph, min, arg1Tuple,
3095 if (param1Prefix != null && param1Prefix.startsWith(mdCallee.getThis())) {
3096 // in this case, we need to create a new edge
3097 // 'this.FIELD'->'this'
3098 // but we couldn't... instead we assign a new composite
3100 // with 'this' reference to the corresponding parameter
3102 CompositeLocation compLocForParam1 =
3103 generateCompositeLocation(mdCallee, param1Prefix);
3106 .println("set comp loc=" + compLocForParam1 + " to " + paramNode1);
3107 paramNode1.setCompositeLocation(compLocForParam1);
3109 // then, we need to make sure that the corresponding
3110 // argument in the caller
3111 // is required to be higher than or equal to the
3112 // translated parameter
3115 NTuple<Descriptor> translatedParamTuple =
3116 translateCompositeLocationToCaller(min, compLocForParam1);
3118 // TODO : check if the arg >= the tranlated parameter
3120 System.out.println("add a flow edge= " + arg1Tuple + "->"
3121 + translatedParamTuple);
3122 callerFlowGraph.addValueFlowEdge(arg1Tuple, translatedParamTuple);
3129 // param1 has already been assigned a composite location
3131 System.out.println("--param1 has already been assigned a composite location");
3132 CompositeLocation compLocForParam1 = paramNode1.getCompositeLocation();
3133 NTuple<Descriptor> translatedParamTuple =
3134 translateCompositeLocationToCaller(min, compLocForParam1);
3136 // TODO : check if the arg >= the tranlated parameter
3138 System.out.println("add a flow edge= " + arg1Tuple + "->"
3139 + translatedParamTuple);
3140 callerFlowGraph.addValueFlowEdge(arg1Tuple, translatedParamTuple);
3146 } else if (arg1Tuple.size() == 1 && arg1Tuple.get(0).equals(baseRef)) {
3147 // in this case, the callee flow causes a caller flow
3148 // originated from the object
3150 // method is invoked.
3152 System.out.println("###FROM CASE");
3154 if (!paramNode2.getCurrentDescTuple().startsWith(mdCallee.getThis())) {
3156 NTuple<Descriptor> param2Prefix =
3157 calculatePrefixForParam(callerFlowGraph, calleeFlowGraph, min, arg2Tuple,
3160 if (param2Prefix != null && param2Prefix.startsWith(mdCallee.getThis())) {
3161 // in this case, we need to create a new edge 'this' ->
3162 // 'this.FIELD' but we couldn't... instead we assign the
3164 // parameter a new composite location started with
3167 CompositeLocation compLocForParam2 =
3168 generateCompositeLocation(mdCallee, param2Prefix);
3170 // System.out.println("set comp loc=" + compLocForParam2
3172 // " to " + paramNode2);
3173 paramNode1.setCompositeLocation(compLocForParam2);
3181 // otherwise, flows between method/field locations...
3182 callerFlowGraph.addValueFlowEdge(arg1Tuple, arg2Tuple);
3183 System.out.println("arg1=" + arg1Tuple + " arg2=" + arg2Tuple);
3190 System.out.println();
3194 System.out.println("##\n");
3197 private NTuple<Descriptor> translateCompositeLocationToCaller(MethodInvokeNode min,
3198 CompositeLocation compLocForParam1) {
3199 NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
3201 NTuple<Descriptor> tuple = new NTuple<Descriptor>();
3203 for (int i = 0; i < baseTuple.size(); i++) {
3204 tuple.add(baseTuple.get(i));
3207 for (int i = 1; i < compLocForParam1.getSize(); i++) {
3208 Location loc = compLocForParam1.get(i);
3209 tuple.add(loc.getLocDescriptor());
3215 private CompositeLocation generateCompositeLocation(NTuple<Location> prefixLocTuple) {
3217 System.out.println("generateCompositeLocation=" + prefixLocTuple);
3219 CompositeLocation newCompLoc = new CompositeLocation();
3220 for (int i = 0; i < prefixLocTuple.size(); i++) {
3221 newCompLoc.addLocation(prefixLocTuple.get(i));
3224 Descriptor lastDescOfPrefix = prefixLocTuple.get(prefixLocTuple.size() - 1).getLocDescriptor();
3226 ClassDescriptor enclosingDescriptor;
3227 if (lastDescOfPrefix instanceof FieldDescriptor) {
3228 enclosingDescriptor = ((FieldDescriptor) lastDescOfPrefix).getType().getClassDesc();
3229 // System.out.println("enclosingDescriptor0=" + enclosingDescriptor);
3230 } else if (lastDescOfPrefix.equals(GLOBALDESC)) {
3231 MethodDescriptor currentMethodDesc = (MethodDescriptor) prefixLocTuple.get(0).getDescriptor();
3232 enclosingDescriptor = currentMethodDesc.getClassDesc();
3234 // var descriptor case
3235 enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
3237 // System.out.println("enclosingDescriptor=" + enclosingDescriptor);
3239 LocationDescriptor newLocDescriptor = generateNewLocationDescriptor();
3240 newLocDescriptor.setEnclosingClassDesc(enclosingDescriptor);
3242 Location newLoc = new Location(enclosingDescriptor, newLocDescriptor.getSymbol());
3243 newLoc.setLocDescriptor(newLocDescriptor);
3244 newCompLoc.addLocation(newLoc);
3246 // System.out.println("--newCompLoc=" + newCompLoc);
3250 private CompositeLocation generateCompositeLocation(MethodDescriptor md,
3251 NTuple<Descriptor> paramPrefix) {
3253 System.out.println("generateCompositeLocation=" + paramPrefix);
3255 CompositeLocation newCompLoc = convertToCompositeLocation(md, paramPrefix);
3257 Descriptor lastDescOfPrefix = paramPrefix.get(paramPrefix.size() - 1);
3258 // System.out.println("lastDescOfPrefix=" + lastDescOfPrefix + " kind="
3259 // + lastDescOfPrefix.getClass());
3260 ClassDescriptor enclosingDescriptor;
3261 if (lastDescOfPrefix instanceof FieldDescriptor) {
3262 enclosingDescriptor = ((FieldDescriptor) lastDescOfPrefix).getType().getClassDesc();
3263 // System.out.println("enclosingDescriptor0=" + enclosingDescriptor);
3265 // var descriptor case
3266 enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
3268 // System.out.println("enclosingDescriptor=" + enclosingDescriptor);
3270 LocationDescriptor newLocDescriptor = generateNewLocationDescriptor();
3271 newLocDescriptor.setEnclosingClassDesc(enclosingDescriptor);
3273 Location newLoc = new Location(enclosingDescriptor, newLocDescriptor.getSymbol());
3274 newLoc.setLocDescriptor(newLocDescriptor);
3275 newCompLoc.addLocation(newLoc);
3277 // System.out.println("--newCompLoc=" + newCompLoc);
3281 private NTuple<Descriptor> calculatePrefixForParam(FlowGraph callerFlowGraph,
3282 FlowGraph calleeFlowGraph, MethodInvokeNode min, NTuple<Descriptor> arg1Tuple,
3283 FlowNode paramNode1) {
3285 NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
3286 Descriptor baseRef = baseTuple.get(baseTuple.size() - 1);
3287 System.out.println("baseRef=" + baseRef);
3289 FlowNode flowNodeArg1 = callerFlowGraph.getFlowNode(arg1Tuple);
3290 List<NTuple<Descriptor>> callerPrefixList = calculatePrefixList(callerFlowGraph, flowNodeArg1);
3291 System.out.println("callerPrefixList=" + callerPrefixList);
3293 List<NTuple<Descriptor>> prefixList = calculatePrefixList(calleeFlowGraph, paramNode1);
3294 System.out.println("###prefixList from node=" + paramNode1 + " =" + prefixList);
3296 List<NTuple<Descriptor>> calleePrefixList =
3297 translatePrefixListToCallee(baseRef, min.getMethod(), callerPrefixList);
3299 System.out.println("calleePrefixList=" + calleePrefixList);
3301 Set<FlowNode> reachNodeSetFromParam1 = calleeFlowGraph.getReachFlowNodeSetFrom(paramNode1);
3302 System.out.println("reachNodeSetFromParam1=" + reachNodeSetFromParam1);
3304 for (int i = 0; i < calleePrefixList.size(); i++) {
3305 NTuple<Descriptor> curPrefix = calleePrefixList.get(i);
3306 Set<NTuple<Descriptor>> reachableCommonPrefixSet = new HashSet<NTuple<Descriptor>>();
3308 for (Iterator iterator2 = reachNodeSetFromParam1.iterator(); iterator2.hasNext();) {
3309 FlowNode reachNode = (FlowNode) iterator2.next();
3310 if (reachNode.getCurrentDescTuple().startsWith(curPrefix)) {
3311 reachableCommonPrefixSet.add(reachNode.getCurrentDescTuple());
3315 if (!reachableCommonPrefixSet.isEmpty()) {
3316 System.out.println("###REACHABLECOMONPREFIX=" + reachableCommonPrefixSet
3317 + " with curPreFix=" + curPrefix);
3326 private List<NTuple<Descriptor>> translatePrefixListToCallee(Descriptor baseRef,
3327 MethodDescriptor mdCallee, List<NTuple<Descriptor>> callerPrefixList) {
3329 List<NTuple<Descriptor>> calleePrefixList = new ArrayList<NTuple<Descriptor>>();
3331 for (int i = 0; i < callerPrefixList.size(); i++) {
3332 NTuple<Descriptor> prefix = callerPrefixList.get(i);
3333 if (prefix.startsWith(baseRef)) {
3334 NTuple<Descriptor> calleePrefix = new NTuple<Descriptor>();
3335 calleePrefix.add(mdCallee.getThis());
3336 for (int k = 1; k < prefix.size(); k++) {
3337 calleePrefix.add(prefix.get(k));
3339 calleePrefixList.add(calleePrefix);
3343 return calleePrefixList;
3347 private List<NTuple<Descriptor>> calculatePrefixList(FlowGraph flowGraph, FlowNode flowNode) {
3349 System.out.println("\n##### calculatePrefixList=" + flowNode);
3351 Set<FlowNode> inNodeSet = flowGraph.getIncomingFlowNodeSet(flowNode);
3352 inNodeSet.add(flowNode);
3354 System.out.println("inNodeSet=" + inNodeSet);
3356 List<NTuple<Descriptor>> prefixList = new ArrayList<NTuple<Descriptor>>();
3358 for (Iterator iterator = inNodeSet.iterator(); iterator.hasNext();) {
3359 FlowNode inNode = (FlowNode) iterator.next();
3361 NTuple<Descriptor> inNodeTuple = inNode.getCurrentDescTuple();
3363 // CompositeLocation inNodeInferredLoc =
3364 // generateInferredCompositeLocation(methodInfo, inNodeTuple);
3365 // NTuple<Location> inNodeInferredLocTuple = inNodeInferredLoc.getTuple();
3367 for (int i = 1; i < inNodeTuple.size(); i++) {
3368 NTuple<Descriptor> prefix = inNodeTuple.subList(0, i);
3369 if (!prefixList.contains(prefix)) {
3370 prefixList.add(prefix);
3375 Collections.sort(prefixList, new Comparator<NTuple<Descriptor>>() {
3376 public int compare(NTuple<Descriptor> arg0, NTuple<Descriptor> arg1) {
3377 int s0 = arg0.size();
3378 int s1 = arg1.size();
3381 } else if (s0 == s1) {
3393 public CompositeLocation convertToCompositeLocation(MethodDescriptor md, NTuple<Descriptor> tuple) {
3395 CompositeLocation compLoc = new CompositeLocation();
3397 Descriptor enclosingDescriptor = md;
3399 for (int i = 0; i < tuple.size(); i++) {
3400 Descriptor curDescriptor = tuple.get(i);
3401 Location locElement = new Location(enclosingDescriptor, curDescriptor.getSymbol());
3402 locElement.setLocDescriptor(curDescriptor);
3403 compLoc.addLocation(locElement);
3405 if (curDescriptor instanceof VarDescriptor) {
3406 enclosingDescriptor = md.getClassDesc();
3407 } else if (curDescriptor instanceof NameDescriptor) {
3408 // it is "GLOBAL LOC" case!
3409 enclosingDescriptor = GLOBALDESC;
3410 } else if (curDescriptor instanceof InterDescriptor) {
3411 enclosingDescriptor = null;
3413 enclosingDescriptor = ((FieldDescriptor) curDescriptor).getClassDescriptor();
3421 private LocationDescriptor generateNewLocationDescriptor() {
3422 return new LocationDescriptor("Loc" + (locSeed++));
3425 private int getPrefixIndex(NTuple<Descriptor> tuple1, NTuple<Descriptor> tuple2) {
3427 // return the index where the prefix shared by tuple1 and tuple2 is ended
3428 // if there is no prefix shared by both of them, return -1
3430 int minSize = tuple1.size();
3431 if (minSize > tuple2.size()) {
3432 minSize = tuple2.size();
3436 for (int i = 0; i < minSize; i++) {
3437 if (!tuple1.get(i).equals(tuple2.get(i))) {
3447 private CompositeLocation generateInferredCompositeLocation(MethodLocationInfo methodInfo,
3448 NTuple<Location> tuple) {
3450 // first, retrieve inferred location by the local var descriptor
3451 CompositeLocation inferLoc = new CompositeLocation();
3453 CompositeLocation localVarInferLoc =
3454 methodInfo.getInferLocation(tuple.get(0).getLocDescriptor());
3456 localVarInferLoc.get(0).setLocDescriptor(tuple.get(0).getLocDescriptor());
3458 for (int i = 0; i < localVarInferLoc.getSize(); i++) {
3459 inferLoc.addLocation(localVarInferLoc.get(i));
3462 for (int i = 1; i < tuple.size(); i++) {
3463 Location cur = tuple.get(i);
3464 Descriptor enclosingDesc = cur.getDescriptor();
3465 Descriptor curDesc = cur.getLocDescriptor();
3467 Location inferLocElement;
3468 if (curDesc == null) {
3469 // in this case, we have a newly generated location.
3470 inferLocElement = new Location(enclosingDesc, cur.getLocIdentifier());
3472 String fieldLocSymbol =
3473 getLocationInfo(enclosingDesc).getInferLocation(curDesc).get(0).getLocIdentifier();
3474 inferLocElement = new Location(enclosingDesc, fieldLocSymbol);
3475 inferLocElement.setLocDescriptor(curDesc);
3478 inferLoc.addLocation(inferLocElement);
3482 assert (inferLoc.get(0).getLocDescriptor().getSymbol() == inferLoc.get(0).getLocIdentifier());
3486 public LocationInfo getLocationInfo(Descriptor d) {
3487 if (d instanceof MethodDescriptor) {
3488 return getMethodLocationInfo((MethodDescriptor) d);
3490 return getFieldLocationInfo((ClassDescriptor) d);
3494 private MethodLocationInfo getMethodLocationInfo(MethodDescriptor md) {
3496 if (!mapMethodDescToMethodLocationInfo.containsKey(md)) {
3497 mapMethodDescToMethodLocationInfo.put(md, new MethodLocationInfo(md));
3500 return mapMethodDescToMethodLocationInfo.get(md);
3504 private LocationInfo getFieldLocationInfo(ClassDescriptor cd) {
3506 if (!mapClassToLocationInfo.containsKey(cd)) {
3507 mapClassToLocationInfo.put(cd, new LocationInfo(cd));
3510 return mapClassToLocationInfo.get(cd);
3514 private void addPrefixMapping(Map<NTuple<Location>, Set<NTuple<Location>>> map,
3515 NTuple<Location> prefix, NTuple<Location> element) {
3517 if (!map.containsKey(prefix)) {
3518 map.put(prefix, new HashSet<NTuple<Location>>());
3520 map.get(prefix).add(element);
3523 private boolean containsNonPrimitiveElement(Set<Descriptor> descSet) {
3524 for (Iterator iterator = descSet.iterator(); iterator.hasNext();) {
3525 Descriptor desc = (Descriptor) iterator.next();
3527 if (desc.equals(LocationInference.GLOBALDESC)) {
3529 } else if (desc instanceof VarDescriptor) {
3530 if (!((VarDescriptor) desc).getType().isPrimitive()) {
3533 } else if (desc instanceof FieldDescriptor) {
3534 if (!((FieldDescriptor) desc).getType().isPrimitive()) {
3543 private SSJavaLattice<String> getLattice(Descriptor d) {
3544 if (d instanceof MethodDescriptor) {
3545 return getMethodLattice((MethodDescriptor) d);
3547 return getFieldLattice((ClassDescriptor) d);
3551 private SSJavaLattice<String> getMethodLattice(MethodDescriptor md) {
3552 if (!md2lattice.containsKey(md)) {
3553 md2lattice.put(md, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
3555 return md2lattice.get(md);
3558 private void setMethodLattice(MethodDescriptor md, SSJavaLattice<String> lattice) {
3559 md2lattice.put(md, lattice);
3562 private void extractFlowsBetweenFields(ClassDescriptor cd, FlowNode srcNode, FlowNode dstNode,
3565 NTuple<Descriptor> srcCurTuple = srcNode.getCurrentDescTuple();
3566 NTuple<Descriptor> dstCurTuple = dstNode.getCurrentDescTuple();
3568 if (srcCurTuple.get(idx).equals(dstCurTuple.get(idx)) && srcCurTuple.size() > (idx + 1)
3569 && dstCurTuple.size() > (idx + 1)) {
3570 // value flow between fields: we don't need to add a binary relation
3573 Descriptor desc = srcCurTuple.get(idx);
3574 ClassDescriptor classDesc;
3577 classDesc = ((VarDescriptor) desc).getType().getClassDesc();
3579 if (desc instanceof FieldDescriptor) {
3580 classDesc = ((FieldDescriptor) desc).getType().getClassDesc();
3582 // this case is that the local variable has a composite location assignment
3583 // the following element after the composite location to the local variable
3584 // has the enclosing descriptor of the local variable
3585 Descriptor localDesc = srcNode.getDescTuple().get(0);
3586 classDesc = ((VarDescriptor) localDesc).getType().getClassDesc();
3589 extractFlowsBetweenFields(classDesc, srcNode, dstNode, idx + 1);
3593 Descriptor srcFieldDesc = srcCurTuple.get(idx);
3594 Descriptor dstFieldDesc = dstCurTuple.get(idx);
3597 getHierarchyGraph(cd).addEdge(srcFieldDesc, dstFieldDesc);
3603 public SSJavaLattice<String> getFieldLattice(ClassDescriptor cd) {
3604 if (!cd2lattice.containsKey(cd)) {
3605 cd2lattice.put(cd, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
3607 return cd2lattice.get(cd);
3610 public LinkedList<MethodDescriptor> computeMethodList() {
3612 Set<MethodDescriptor> toSort = new HashSet<MethodDescriptor>();
3616 Set<MethodDescriptor> visited = new HashSet<MethodDescriptor>();
3617 Set<MethodDescriptor> reachableCallee = new HashSet<MethodDescriptor>();
3619 while (!toAnalyzeIsEmpty()) {
3620 ClassDescriptor cd = toAnalyzeNext();
3622 setupToAnalazeMethod(cd);
3623 temp_toanalyzeMethodList.removeAll(visited);
3625 while (!toAnalyzeMethodIsEmpty()) {
3626 MethodDescriptor md = toAnalyzeMethodNext();
3627 if ((!visited.contains(md))
3628 && (ssjava.needTobeAnnotated(md) || reachableCallee.contains(md))) {
3630 // creates a mapping from a method descriptor to virtual methods
3631 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3632 if (md.isStatic()) {
3633 setPossibleCallees.add(md);
3635 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
3638 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getCalleeSet(md);
3639 Set<MethodDescriptor> needToAnalyzeCalleeSet = new HashSet<MethodDescriptor>();
3641 for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
3642 MethodDescriptor calleemd = (MethodDescriptor) iterator.next();
3643 if ((!ssjava.isTrustMethod(calleemd))
3644 && (!ssjava.isSSJavaUtil(calleemd.getClassDesc()))) {
3645 if (!visited.contains(calleemd)) {
3646 temp_toanalyzeMethodList.add(calleemd);
3648 reachableCallee.add(calleemd);
3649 needToAnalyzeCalleeSet.add(calleemd);
3653 mapMethodToCalleeSet.put(md, needToAnalyzeCalleeSet);
3662 return ssjava.topologicalSort(toSort);
3666 public boolean isTransitivelyCalledFrom(MethodDescriptor callee, MethodDescriptor caller) {
3667 // if the callee is transitively invoked from the caller
3670 int callerIdx = toanalyze_methodDescList.indexOf(caller);
3671 int calleeIdx = toanalyze_methodDescList.indexOf(callee);
3673 if (callerIdx < calleeIdx) {
3681 public void constructFlowGraph() {
3683 System.out.println("");
3684 toanalyze_methodDescList = computeMethodList();
3686 LinkedList<MethodDescriptor> methodDescList =
3687 (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
3689 System.out.println("@@@methodDescList=" + methodDescList);
3692 while (!methodDescList.isEmpty()) {
3693 MethodDescriptor md = methodDescList.removeLast();
3694 if (state.SSJAVADEBUG) {
3695 System.out.println();
3696 System.out.println("SSJAVA: Constructing a flow graph: " + md);
3698 // creates a mapping from a parameter descriptor to its index
3699 Map<Descriptor, Integer> mapParamDescToIdx = new HashMap<Descriptor, Integer>();
3701 if (!md.isStatic()) {
3703 mapParamDescToIdx.put(md.getThis(), 0);
3706 for (int i = 0; i < md.numParameters(); i++) {
3707 Descriptor paramDesc = (Descriptor) md.getParameter(i);
3708 mapParamDescToIdx.put(paramDesc, new Integer(i + offset));
3711 FlowGraph fg = new FlowGraph(md, mapParamDescToIdx);
3712 mapMethodDescriptorToFlowGraph.put(md, fg);
3714 analyzeMethodBody(md.getClassDesc(), md);
3716 // System.out.println("##constructSubGlobalFlowGraph");
3717 // GlobalFlowGraph subGlobalFlowGraph = constructSubGlobalFlowGraph(fg);
3718 // mapMethodDescriptorToSubGlobalFlowGraph.put(md, subGlobalFlowGraph);
3721 // System.out.println("##addValueFlowsFromCalleeSubGlobalFlowGraph");
3722 // addValueFlowsFromCalleeSubGlobalFlowGraph(md, subGlobalFlowGraph);
3723 // subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
3725 // propagateFlowsFromCalleesWithNoCompositeLocation(md);
3729 // _debug_printGraph();
3731 methodDescList = (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
3733 while (!methodDescList.isEmpty()) {
3734 MethodDescriptor md = methodDescList.removeLast();
3735 if (state.SSJAVADEBUG) {
3736 System.out.println();
3737 System.out.println("SSJAVA: Constructing a sub global flow graph: " + md);
3739 GlobalFlowGraph subGlobalFlowGraph = constructSubGlobalFlowGraph(getFlowGraph(md));
3740 mapMethodDescriptorToSubGlobalFlowGraph.put(md, subGlobalFlowGraph);
3743 System.out.println("-add Value Flows From CalleeSubGlobalFlowGraph");
3744 addValueFlowsFromCalleeSubGlobalFlowGraph(md, subGlobalFlowGraph);
3745 subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
3747 System.out.println("-propagate Flows From Callees With No CompositeLocation");
3748 propagateFlowsFromCalleesWithNoCompositeLocation(md);
3755 private Set<MethodInvokeNode> getMethodInvokeNodeSet(MethodDescriptor md) {
3756 if (!mapMethodDescriptorToMethodInvokeNodeSet.containsKey(md)) {
3757 mapMethodDescriptorToMethodInvokeNodeSet.put(md, new HashSet<MethodInvokeNode>());
3759 return mapMethodDescriptorToMethodInvokeNodeSet.get(md);
3762 private void constructSubGlobalFlowGraph(MethodDescriptor md) {
3764 FlowGraph flowGraph = getFlowGraph(md);
3766 Set<MethodInvokeNode> setMethodInvokeNode = getMethodInvokeNodeSet(md);
3768 for (Iterator<MethodInvokeNode> iter = setMethodInvokeNode.iterator(); iter.hasNext();) {
3769 MethodInvokeNode min = iter.next();
3770 propagateFlowsFromMethodInvokeNode(md, min);
3775 private void propagateFlowsFromMethodInvokeNode(MethodDescriptor mdCaller, MethodInvokeNode min) {
3776 // the transformation for a call site propagates flows through parameters
3777 // if the method is virtual, it also grab all relations from any possible
3780 MethodDescriptor mdCallee = min.getMethod();
3781 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3782 if (mdCallee.isStatic()) {
3783 setPossibleCallees.add(mdCallee);
3785 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
3786 // removes method descriptors that are not invoked by the caller
3787 calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
3788 setPossibleCallees.addAll(calleeSet);
3791 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
3792 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
3793 contributeCalleeFlows(min, mdCaller, possibleMdCallee);
3798 private void assignCompositeLocation(MethodDescriptor md) {
3800 FlowGraph flowGraph = getFlowGraph(md);
3802 Set<FlowNode> nodeSet = flowGraph.getNodeSet();
3804 next: for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
3805 FlowNode flowNode = (FlowNode) iterator.next();
3807 // assign a composite location only to the local variable
3808 if (flowNode.getCurrentDescTuple().size() == 1) {
3810 List<NTuple<Descriptor>> prefixList = calculatePrefixList(flowGraph, flowNode);
3811 Set<FlowNode> reachSet = flowGraph.getReachFlowNodeSetFrom(flowNode);
3813 for (int i = 0; i < prefixList.size(); i++) {
3814 NTuple<Descriptor> curPrefix = prefixList.get(i);
3815 Set<NTuple<Descriptor>> reachableCommonPrefixSet = new HashSet<NTuple<Descriptor>>();
3817 for (Iterator iterator2 = reachSet.iterator(); iterator2.hasNext();) {
3818 FlowNode reachNode = (FlowNode) iterator2.next();
3819 if (reachNode.getCurrentDescTuple().startsWith(curPrefix)) {
3820 reachableCommonPrefixSet.add(reachNode.getCurrentDescTuple());
3824 if (!reachableCommonPrefixSet.isEmpty()) {
3825 System.out.println("NEED TO ASSIGN COMP LOC TO " + flowNode + " with prefix="
3827 CompositeLocation newCompLoc = generateCompositeLocation(md, curPrefix);
3828 flowNode.setCompositeLocation(newCompLoc);
3839 private void propagateFlowsFromCalleesWithNoCompositeLocation(MethodDescriptor mdCaller) {
3841 // the transformation for a call site propagates flows through parameters
3842 // if the method is virtual, it also grab all relations from any possible
3845 Set<MethodInvokeNode> setMethodInvokeNode =
3846 mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
3848 if (setMethodInvokeNode != null) {
3850 for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
3851 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
3852 MethodDescriptor mdCallee = min.getMethod();
3853 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3854 if (mdCallee.isStatic()) {
3855 setPossibleCallees.add(mdCallee);
3857 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
3858 // removes method descriptors that are not invoked by the caller
3859 calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
3860 setPossibleCallees.addAll(calleeSet);
3863 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
3864 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
3865 propagateFlowsToCallerWithNoCompositeLocation(min, mdCaller, possibleMdCallee);
3873 private void propagateFlowsFromCallees(MethodDescriptor mdCaller) {
3875 // the transformation for a call site propagates flows through parameters
3876 // if the method is virtual, it also grab all relations from any possible
3879 Set<MethodInvokeNode> setMethodInvokeNode =
3880 mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
3882 if (setMethodInvokeNode != null) {
3884 for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
3885 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
3886 MethodDescriptor mdCallee = min.getMethod();
3887 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3888 if (mdCallee.isStatic()) {
3889 setPossibleCallees.add(mdCallee);
3891 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
3892 // removes method descriptors that are not invoked by the caller
3893 calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
3894 setPossibleCallees.addAll(calleeSet);
3897 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
3898 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
3899 propagateFlowsToCaller(min, mdCaller, possibleMdCallee);
3907 private void analyzeMethodBody(ClassDescriptor cd, MethodDescriptor md) {
3908 BlockNode bn = state.getMethodBody(md);
3909 NodeTupleSet implicitFlowTupleSet = new NodeTupleSet();
3910 analyzeFlowBlockNode(md, md.getParameterTable(), bn, implicitFlowTupleSet);
3913 private void analyzeFlowBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn,
3914 NodeTupleSet implicitFlowTupleSet) {
3916 bn.getVarTable().setParent(nametable);
3917 for (int i = 0; i < bn.size(); i++) {
3918 BlockStatementNode bsn = bn.get(i);
3919 analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
3924 private void analyzeBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
3925 BlockStatementNode bsn, NodeTupleSet implicitFlowTupleSet) {
3927 switch (bsn.kind()) {
3928 case Kind.BlockExpressionNode:
3929 analyzeBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, implicitFlowTupleSet);
3932 case Kind.DeclarationNode:
3933 analyzeFlowDeclarationNode(md, nametable, (DeclarationNode) bsn, implicitFlowTupleSet);
3936 case Kind.IfStatementNode:
3937 analyzeFlowIfStatementNode(md, nametable, (IfStatementNode) bsn, implicitFlowTupleSet);
3941 analyzeFlowLoopNode(md, nametable, (LoopNode) bsn, implicitFlowTupleSet);
3944 case Kind.ReturnNode:
3945 analyzeFlowReturnNode(md, nametable, (ReturnNode) bsn, implicitFlowTupleSet);
3948 case Kind.SubBlockNode:
3949 analyzeFlowSubBlockNode(md, nametable, (SubBlockNode) bsn, implicitFlowTupleSet);
3952 case Kind.ContinueBreakNode:
3955 case Kind.SwitchStatementNode:
3956 analyzeSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, implicitFlowTupleSet);
3963 private void analyzeSwitchBlockNode(MethodDescriptor md, SymbolTable nametable,
3964 SwitchBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
3966 analyzeFlowBlockNode(md, nametable, sbn.getSwitchBlockStatement(), implicitFlowTupleSet);
3970 private void analyzeSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
3971 SwitchStatementNode ssn, NodeTupleSet implicitFlowTupleSet) {
3973 NodeTupleSet condTupleNode = new NodeTupleSet();
3974 analyzeFlowExpressionNode(md, nametable, ssn.getCondition(), condTupleNode, null,
3975 implicitFlowTupleSet, false);
3977 NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
3979 newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
3980 newImplicitTupleSet.addTupleSet(condTupleNode);
3982 if (newImplicitTupleSet.size() > 1) {
3983 // need to create an intermediate node for the GLB of conditional
3984 // locations & implicit flows
3985 NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
3986 for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter.hasNext();) {
3987 NTuple<Descriptor> tuple = idxIter.next();
3988 addFlowGraphEdge(md, tuple, interTuple);
3990 newImplicitTupleSet.clear();
3991 newImplicitTupleSet.addTuple(interTuple);
3994 BlockNode sbn = ssn.getSwitchBody();
3995 for (int i = 0; i < sbn.size(); i++) {
3996 analyzeSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), newImplicitTupleSet);
4001 private void analyzeFlowSubBlockNode(MethodDescriptor md, SymbolTable nametable,
4002 SubBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
4003 analyzeFlowBlockNode(md, nametable, sbn.getBlockNode(), implicitFlowTupleSet);
4006 private void analyzeFlowReturnNode(MethodDescriptor md, SymbolTable nametable, ReturnNode rn,
4007 NodeTupleSet implicitFlowTupleSet) {
4009 ExpressionNode returnExp = rn.getReturnExpression();
4011 if (returnExp != null) {
4012 NodeTupleSet nodeSet = new NodeTupleSet();
4013 // if a return expression returns a literal value, nodeSet is empty
4014 analyzeFlowExpressionNode(md, nametable, returnExp, nodeSet, false);
4015 FlowGraph fg = getFlowGraph(md);
4017 // if (implicitFlowTupleSet.size() == 1
4019 // fg.getFlowNode(implicitFlowTupleSet.iterator().next()).isIntermediate())
4022 // // since there is already an intermediate node for the GLB of implicit
4024 // // we don't need to create another intermediate node.
4025 // // just re-use the intermediate node for implicit flows.
4027 // FlowNode meetNode =
4028 // fg.getFlowNode(implicitFlowTupleSet.iterator().next());
4030 // for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
4031 // NTuple<Descriptor> returnNodeTuple = (NTuple<Descriptor>)
4033 // fg.addValueFlowEdge(returnNodeTuple, meetNode.getDescTuple());
4038 NodeTupleSet currentFlowTupleSet = new NodeTupleSet();
4040 // add tuples from return node
4041 currentFlowTupleSet.addTupleSet(nodeSet);
4043 // add tuples corresponding to the current implicit flows
4044 currentFlowTupleSet.addTupleSet(implicitFlowTupleSet);
4046 if (currentFlowTupleSet.size() > 1) {
4047 FlowNode meetNode = fg.createIntermediateNode();
4048 for (Iterator iterator = currentFlowTupleSet.iterator(); iterator.hasNext();) {
4049 NTuple<Descriptor> currentFlowTuple = (NTuple<Descriptor>) iterator.next();
4050 fg.addValueFlowEdge(currentFlowTuple, meetNode.getDescTuple());
4052 fg.addReturnFlowNode(meetNode.getDescTuple());
4053 } else if (currentFlowTupleSet.size() == 1) {
4054 NTuple<Descriptor> tuple = currentFlowTupleSet.iterator().next();
4055 fg.addReturnFlowNode(tuple);
4062 private void analyzeFlowLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln,
4063 NodeTupleSet implicitFlowTupleSet) {
4065 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
4067 NodeTupleSet condTupleNode = new NodeTupleSet();
4068 analyzeFlowExpressionNode(md, nametable, ln.getCondition(), condTupleNode, null,
4069 implicitFlowTupleSet, false);
4071 NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
4073 newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
4074 newImplicitTupleSet.addTupleSet(condTupleNode);
4076 if (newImplicitTupleSet.size() > 1) {
4077 // need to create an intermediate node for the GLB of conditional
4078 // locations & implicit flows
4079 NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4080 for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter
4082 NTuple<Descriptor> tuple = idxIter.next();
4083 addFlowGraphEdge(md, tuple, interTuple);
4085 newImplicitTupleSet.clear();
4086 newImplicitTupleSet.addTuple(interTuple);
4091 // System.out.println("condTupleNode="+condTupleNode);
4092 // NTuple<Descriptor> interTuple =
4093 // getFlowGraph(md).createIntermediateNode().getDescTuple();
4095 // for (Iterator<NTuple<Descriptor>> idxIter = condTupleNode.iterator();
4096 // idxIter.hasNext();) {
4097 // NTuple<Descriptor> tuple = idxIter.next();
4098 // addFlowGraphEdge(md, tuple, interTuple);
4101 // for (Iterator<NTuple<Descriptor>> idxIter =
4102 // implicitFlowTupleSet.iterator(); idxIter
4104 // NTuple<Descriptor> tuple = idxIter.next();
4105 // addFlowGraphEdge(md, tuple, interTuple);
4108 // NodeTupleSet newImplicitSet = new NodeTupleSet();
4109 // newImplicitSet.addTuple(interTuple);
4110 analyzeFlowBlockNode(md, nametable, ln.getBody(), newImplicitTupleSet);
4113 // condTupleNode.addTupleSet(implicitFlowTupleSet);
4115 // add edges from condNodeTupleSet to all nodes of conditional nodes
4116 // analyzeFlowBlockNode(md, nametable, ln.getBody(), condTupleNode);
4119 // check 'for loop' case
4120 BlockNode bn = ln.getInitializer();
4121 bn.getVarTable().setParent(nametable);
4122 for (int i = 0; i < bn.size(); i++) {
4123 BlockStatementNode bsn = bn.get(i);
4124 analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
4127 NodeTupleSet condTupleNode = new NodeTupleSet();
4128 analyzeFlowExpressionNode(md, bn.getVarTable(), ln.getCondition(), condTupleNode, null,
4129 implicitFlowTupleSet, false);
4132 NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4134 for (Iterator<NTuple<Descriptor>> idxIter = condTupleNode.iterator(); idxIter.hasNext();) {
4135 NTuple<Descriptor> tuple = idxIter.next();
4136 addFlowGraphEdge(md, tuple, interTuple);
4139 for (Iterator<NTuple<Descriptor>> idxIter = implicitFlowTupleSet.iterator(); idxIter
4141 NTuple<Descriptor> tuple = idxIter.next();
4142 addFlowGraphEdge(md, tuple, interTuple);
4145 NodeTupleSet newImplicitSet = new NodeTupleSet();
4146 newImplicitSet.addTuple(interTuple);
4147 analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(), newImplicitSet);
4148 analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(), newImplicitSet);
4151 // condTupleNode.addTupleSet(implicitFlowTupleSet);
4153 // analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(),
4155 // analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(),
4162 private void analyzeFlowIfStatementNode(MethodDescriptor md, SymbolTable nametable,
4163 IfStatementNode isn, NodeTupleSet implicitFlowTupleSet) {
4165 // System.out.println("analyzeFlowIfStatementNode=" + isn.printNode(0));
4167 NodeTupleSet condTupleNode = new NodeTupleSet();
4168 analyzeFlowExpressionNode(md, nametable, isn.getCondition(), condTupleNode, null,
4169 implicitFlowTupleSet, false);
4171 NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
4173 newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
4174 newImplicitTupleSet.addTupleSet(condTupleNode);
4176 // System.out.println("condTupleNode=" + condTupleNode);
4177 // System.out.println("implicitFlowTupleSet=" + implicitFlowTupleSet);
4178 // System.out.println("newImplicitTupleSet=" + newImplicitTupleSet);
4180 if (newImplicitTupleSet.size() > 1) {
4182 // need to create an intermediate node for the GLB of conditional locations & implicit flows
4183 NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4184 for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter.hasNext();) {
4185 NTuple<Descriptor> tuple = idxIter.next();
4186 addFlowGraphEdge(md, tuple, interTuple);
4188 newImplicitTupleSet.clear();
4189 newImplicitTupleSet.addTuple(interTuple);
4192 analyzeFlowBlockNode(md, nametable, isn.getTrueBlock(), newImplicitTupleSet);
4194 if (isn.getFalseBlock() != null) {
4195 analyzeFlowBlockNode(md, nametable, isn.getFalseBlock(), newImplicitTupleSet);
4200 private void analyzeFlowDeclarationNode(MethodDescriptor md, SymbolTable nametable,
4201 DeclarationNode dn, NodeTupleSet implicitFlowTupleSet) {
4203 VarDescriptor vd = dn.getVarDescriptor();
4204 mapDescToDefinitionLine.put(vd, dn.getNumLine());
4205 NTuple<Descriptor> tupleLHS = new NTuple<Descriptor>();
4207 FlowNode fn = getFlowGraph(md).createNewFlowNode(tupleLHS);
4208 fn.setDeclarationNode();
4210 if (dn.getExpression() != null) {
4212 NodeTupleSet nodeSetRHS = new NodeTupleSet();
4213 analyzeFlowExpressionNode(md, nametable, dn.getExpression(), nodeSetRHS, null,
4214 implicitFlowTupleSet, false);
4216 // creates edges from RHS to LHS
4217 NTuple<Descriptor> interTuple = null;
4218 if (nodeSetRHS.size() > 1) {
4219 interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4222 for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
4223 NTuple<Descriptor> fromTuple = iter.next();
4224 addFlowGraphEdge(md, fromTuple, interTuple, tupleLHS);
4227 // creates edges from implicitFlowTupleSet to LHS
4228 for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
4229 NTuple<Descriptor> implicitTuple = iter.next();
4230 addFlowGraphEdge(md, implicitTuple, tupleLHS);
4237 private void analyzeBlockExpressionNode(MethodDescriptor md, SymbolTable nametable,
4238 BlockExpressionNode ben, NodeTupleSet implicitFlowTupleSet) {
4239 analyzeFlowExpressionNode(md, nametable, ben.getExpression(), null, null, implicitFlowTupleSet,
4243 private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
4244 ExpressionNode en, NodeTupleSet nodeSet, boolean isLHS) {
4245 return analyzeFlowExpressionNode(md, nametable, en, nodeSet, null, new NodeTupleSet(), isLHS);
4248 private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
4249 ExpressionNode en, NodeTupleSet nodeSet, NTuple<Descriptor> base,
4250 NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
4252 // note that expression node can create more than one flow node
4253 // nodeSet contains of flow nodes
4254 // base is always assigned to null except the case of a name node!
4256 NTuple<Descriptor> flowTuple;
4258 switch (en.kind()) {
4260 case Kind.AssignmentNode:
4261 analyzeFlowAssignmentNode(md, nametable, (AssignmentNode) en, nodeSet, base,
4262 implicitFlowTupleSet);
4265 case Kind.FieldAccessNode:
4267 analyzeFlowFieldAccessNode(md, nametable, (FieldAccessNode) en, nodeSet, base,
4268 implicitFlowTupleSet, isLHS);
4269 if (flowTuple != null) {
4270 nodeSet.addTuple(flowTuple);
4275 NodeTupleSet nameNodeSet = new NodeTupleSet();
4277 analyzeFlowNameNode(md, nametable, (NameNode) en, nameNodeSet, base, implicitFlowTupleSet);
4278 if (flowTuple != null) {
4279 nodeSet.addTuple(flowTuple);
4284 analyzeFlowOpNode(md, nametable, (OpNode) en, nodeSet, implicitFlowTupleSet);
4287 case Kind.CreateObjectNode:
4288 analyzeCreateObjectNode(md, nametable, (CreateObjectNode) en);
4291 case Kind.ArrayAccessNode:
4292 analyzeFlowArrayAccessNode(md, nametable, (ArrayAccessNode) en, nodeSet, isLHS);
4295 case Kind.LiteralNode:
4296 analyzeLiteralNode(md, nametable, (LiteralNode) en);
4299 case Kind.MethodInvokeNode:
4300 analyzeFlowMethodInvokeNode(md, nametable, (MethodInvokeNode) en, nodeSet,
4301 implicitFlowTupleSet);
4304 case Kind.TertiaryNode:
4305 analyzeFlowTertiaryNode(md, nametable, (TertiaryNode) en, nodeSet, implicitFlowTupleSet);
4309 analyzeFlowCastNode(md, nametable, (CastNode) en, nodeSet, base, implicitFlowTupleSet);
4311 // case Kind.InstanceOfNode:
4312 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
4315 // case Kind.ArrayInitializerNode:
4316 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
4320 // case Kind.ClassTypeNode:
4321 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
4324 // case Kind.OffsetNode:
4325 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
4333 private void analyzeFlowCastNode(MethodDescriptor md, SymbolTable nametable, CastNode cn,
4334 NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
4336 analyzeFlowExpressionNode(md, nametable, cn.getExpression(), nodeSet, base,
4337 implicitFlowTupleSet, false);
4341 private void analyzeFlowTertiaryNode(MethodDescriptor md, SymbolTable nametable, TertiaryNode tn,
4342 NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
4344 NodeTupleSet tertiaryTupleNode = new NodeTupleSet();
4345 analyzeFlowExpressionNode(md, nametable, tn.getCond(), tertiaryTupleNode, null,
4346 implicitFlowTupleSet, false);
4348 // add edges from tertiaryTupleNode to all nodes of conditional nodes
4349 tertiaryTupleNode.addTupleSet(implicitFlowTupleSet);
4350 analyzeFlowExpressionNode(md, nametable, tn.getTrueExpr(), tertiaryTupleNode, null,
4351 implicitFlowTupleSet, false);
4353 analyzeFlowExpressionNode(md, nametable, tn.getFalseExpr(), tertiaryTupleNode, null,
4354 implicitFlowTupleSet, false);
4356 nodeSet.addTupleSet(tertiaryTupleNode);
4360 private void addMapCallerMethodDescToMethodInvokeNodeSet(MethodDescriptor caller,
4361 MethodInvokeNode min) {
4362 Set<MethodInvokeNode> set = mapMethodDescriptorToMethodInvokeNodeSet.get(caller);
4364 set = new HashSet<MethodInvokeNode>();
4365 mapMethodDescriptorToMethodInvokeNodeSet.put(caller, set);
4370 private void addParamNodeFlowingToReturnValue(MethodDescriptor md, FlowNode fn) {
4372 if (!mapMethodDescToParamNodeFlowsToReturnValue.containsKey(md)) {
4373 mapMethodDescToParamNodeFlowsToReturnValue.put(md, new HashSet<FlowNode>());
4375 mapMethodDescToParamNodeFlowsToReturnValue.get(md).add(fn);
4378 private Set<FlowNode> getParamNodeFlowingToReturnValue(MethodDescriptor md) {
4380 if (!mapMethodDescToParamNodeFlowsToReturnValue.containsKey(md)) {
4381 mapMethodDescToParamNodeFlowsToReturnValue.put(md, new HashSet<FlowNode>());
4384 return mapMethodDescToParamNodeFlowsToReturnValue.get(md);
4387 private void analyzeFlowMethodInvokeNode(MethodDescriptor md, SymbolTable nametable,
4388 MethodInvokeNode min, NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
4390 System.out.println("analyzeFlowMethodInvokeNode=" + min.printNode(0));
4392 mapMethodInvokeNodeToArgIdxMap.put(min, new HashMap<Integer, NTuple<Descriptor>>());
4394 if (nodeSet == null) {
4395 nodeSet = new NodeTupleSet();
4398 MethodDescriptor calleeMethodDesc = min.getMethod();
4400 NameDescriptor baseName = min.getBaseName();
4401 boolean isSystemout = false;
4402 if (baseName != null) {
4403 isSystemout = baseName.getSymbol().equals("System.out");
4406 if (!ssjava.isSSJavaUtil(calleeMethodDesc.getClassDesc())
4407 && !ssjava.isTrustMethod(calleeMethodDesc) && !isSystemout) {
4409 addMapCallerMethodDescToMethodInvokeNodeSet(md, min);
4411 FlowGraph calleeFlowGraph = getFlowGraph(calleeMethodDesc);
4412 Set<FlowNode> calleeReturnSet = calleeFlowGraph.getReturnNodeSet();
4414 // System.out.println("-calleeReturnSet=" + calleeReturnSet);
4416 if (min.getExpression() != null) {
4418 NodeTupleSet baseNodeSet = new NodeTupleSet();
4419 analyzeFlowExpressionNode(md, nametable, min.getExpression(), baseNodeSet, null,
4420 implicitFlowTupleSet, false);
4422 assert (baseNodeSet.size() == 1);
4423 NTuple<Descriptor> baseTuple = baseNodeSet.iterator().next();
4424 mapMethodInvokeNodeToBaseTuple.put(min, baseTuple);
4426 if (!min.getMethod().isStatic()) {
4427 addArgIdxMap(min, 0, baseTuple);
4429 for (Iterator iterator = calleeReturnSet.iterator(); iterator.hasNext();) {
4430 FlowNode returnNode = (FlowNode) iterator.next();
4431 NTuple<Descriptor> returnDescTuple = returnNode.getDescTuple();
4432 if (returnDescTuple.startsWith(calleeMethodDesc.getThis())) {
4433 // the location type of the return value is started with 'this'
4435 NTuple<Descriptor> inFlowTuple = new NTuple<Descriptor>(baseTuple.getList());
4436 inFlowTuple.addAll(returnDescTuple.subList(1, returnDescTuple.size()));
4437 nodeSet.addTuple(inFlowTuple);
4440 Set<FlowNode> inFlowSet = calleeFlowGraph.getIncomingFlowNodeSet(returnNode);
4441 // System.out.println("inFlowSet=" + inFlowSet + " from retrunNode=" + returnNode);
4442 for (Iterator iterator2 = inFlowSet.iterator(); iterator2.hasNext();) {
4443 FlowNode inFlowNode = (FlowNode) iterator2.next();
4444 if (inFlowNode.getDescTuple().startsWith(calleeMethodDesc.getThis())) {
4445 nodeSet.addTupleSet(baseNodeSet);
4454 // analyze parameter flows
4456 if (min.numArgs() > 0) {
4459 if (min.getMethod().isStatic()) {
4465 for (int i = 0; i < min.numArgs(); i++) {
4466 ExpressionNode en = min.getArg(i);
4467 int idx = i + offset;
4468 NodeTupleSet argTupleSet = new NodeTupleSet();
4469 analyzeFlowExpressionNode(md, nametable, en, argTupleSet, false);
4470 // if argument is liternal node, argTuple is set to NULL
4472 NTuple<Descriptor> argTuple = new NTuple<Descriptor>();
4473 if (argTupleSet.size() > 1) {
4474 NTuple<Descriptor> interTuple =
4475 getFlowGraph(md).createIntermediateNode().getDescTuple();
4476 for (Iterator<NTuple<Descriptor>> idxIter = argTupleSet.iterator(); idxIter.hasNext();) {
4477 NTuple<Descriptor> tuple = idxIter.next();
4478 addFlowGraphEdge(md, tuple, interTuple);
4480 argTuple = interTuple;
4481 } else if (argTupleSet.size() == 1) {
4482 argTuple = argTupleSet.iterator().next();
4484 argTuple = new NTuple<Descriptor>();
4488 addArgIdxMap(min, idx, argTuple);
4490 FlowNode paramNode = calleeFlowGraph.getParamFlowNode(idx);
4491 if (hasInFlowTo(calleeFlowGraph, paramNode, calleeReturnSet)
4492 || calleeMethodDesc.getModifiers().isNative()) {
4493 addParamNodeFlowingToReturnValue(calleeMethodDesc, paramNode);
4494 nodeSet.addTupleSet(argTupleSet);
4500 // propagateFlowsFromCallee(min, md, min.getMethod());
4502 System.out.println("min nodeSet=" + nodeSet);
4507 private boolean hasInFlowTo(FlowGraph fg, FlowNode inNode, Set<FlowNode> nodeSet) {
4508 // return true if inNode has in-flows to nodeSet
4510 // Set<FlowNode> reachableSet = fg.getReachFlowNodeSetFrom(inNode);
4511 Set<FlowNode> reachableSet = fg.getReachableSetFrom(inNode.getDescTuple());
4512 System.out.println("inNode=" + inNode + " reachalbeSet=" + reachableSet);
4514 for (Iterator iterator = reachableSet.iterator(); iterator.hasNext();) {
4515 FlowNode fn = (FlowNode) iterator.next();
4516 if (nodeSet.contains(fn)) {
4523 private NTuple<Descriptor> getNodeTupleByArgIdx(MethodInvokeNode min, int idx) {
4524 return mapMethodInvokeNodeToArgIdxMap.get(min).get(new Integer(idx));
4527 private void addArgIdxMap(MethodInvokeNode min, int idx, NTuple<Descriptor> argTuple /*
4531 Map<Integer, NTuple<Descriptor>> mapIdxToTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
4532 if (mapIdxToTuple == null) {
4533 mapIdxToTuple = new HashMap<Integer, NTuple<Descriptor>>();
4534 mapMethodInvokeNodeToArgIdxMap.put(min, mapIdxToTuple);
4536 mapIdxToTuple.put(new Integer(idx), argTuple);
4539 private void analyzeLiteralNode(MethodDescriptor md, SymbolTable nametable, LiteralNode en) {
4543 private void analyzeFlowArrayAccessNode(MethodDescriptor md, SymbolTable nametable,
4544 ArrayAccessNode aan, NodeTupleSet nodeSet, boolean isLHS) {
4546 NodeTupleSet expNodeTupleSet = new NodeTupleSet();
4547 NTuple<Descriptor> base =
4548 analyzeFlowExpressionNode(md, nametable, aan.getExpression(), expNodeTupleSet, isLHS);
4550 NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
4551 analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, isLHS);
4554 // need to create an edge from idx to array
4555 for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
4556 NTuple<Descriptor> idxTuple = idxIter.next();
4557 for (Iterator<NTuple<Descriptor>> arrIter = expNodeTupleSet.iterator(); arrIter.hasNext();) {
4558 NTuple<Descriptor> arrTuple = arrIter.next();
4559 getFlowGraph(md).addValueFlowEdge(idxTuple, arrTuple);
4563 nodeSet.addTupleSet(expNodeTupleSet);
4565 nodeSet.addTupleSet(expNodeTupleSet);
4566 nodeSet.addTupleSet(idxNodeTupleSet);
4570 private void analyzeCreateObjectNode(MethodDescriptor md, SymbolTable nametable,
4571 CreateObjectNode en) {
4572 // TODO Auto-generated method stub
4576 private void analyzeFlowOpNode(MethodDescriptor md, SymbolTable nametable, OpNode on,
4577 NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
4579 NodeTupleSet leftOpSet = new NodeTupleSet();
4580 NodeTupleSet rightOpSet = new NodeTupleSet();
4583 analyzeFlowExpressionNode(md, nametable, on.getLeft(), leftOpSet, null, implicitFlowTupleSet,
4586 if (on.getRight() != null) {
4588 analyzeFlowExpressionNode(md, nametable, on.getRight(), rightOpSet, null,
4589 implicitFlowTupleSet, false);
4592 Operation op = on.getOp();
4594 switch (op.getOp()) {
4596 case Operation.UNARYPLUS:
4597 case Operation.UNARYMINUS:
4598 case Operation.LOGIC_NOT:
4600 nodeSet.addTupleSet(leftOpSet);
4603 case Operation.LOGIC_OR:
4604 case Operation.LOGIC_AND:
4605 case Operation.COMP:
4606 case Operation.BIT_OR:
4607 case Operation.BIT_XOR:
4608 case Operation.BIT_AND:
4609 case Operation.ISAVAILABLE:
4610 case Operation.EQUAL:
4611 case Operation.NOTEQUAL:
4618 case Operation.MULT:
4621 case Operation.LEFTSHIFT:
4622 case Operation.RIGHTSHIFT:
4623 case Operation.URIGHTSHIFT:
4625 // there are two operands
4626 nodeSet.addTupleSet(leftOpSet);
4627 nodeSet.addTupleSet(rightOpSet);
4631 throw new Error(op.toString());
4636 private NTuple<Descriptor> analyzeFlowNameNode(MethodDescriptor md, SymbolTable nametable,
4637 NameNode nn, NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
4639 // System.out.println("analyzeFlowNameNode=" + nn.printNode(0));
4642 base = new NTuple<Descriptor>();
4645 NameDescriptor nd = nn.getName();
4647 if (nd.getBase() != null) {
4649 analyzeFlowExpressionNode(md, nametable, nn.getExpression(), nodeSet, base,
4650 implicitFlowTupleSet, false);
4652 // base node has the top location
4656 String varname = nd.toString();
4657 if (varname.equals("this")) {
4659 base.add(md.getThis());
4663 Descriptor d = (Descriptor) nametable.get(varname);
4665 if (d instanceof VarDescriptor) {
4666 VarDescriptor vd = (VarDescriptor) d;
4668 } else if (d instanceof FieldDescriptor) {
4669 // the type of field descriptor has a location!
4670 FieldDescriptor fd = (FieldDescriptor) d;
4671 if (fd.isStatic()) {
4673 // if it is 'static final', no need to have flow node for the TOP
4677 // if 'static', assign the default GLOBAL LOCATION to the first
4678 // element of the tuple
4679 base.add(GLOBALDESC);
4682 // the location of field access starts from this, followed by field
4684 base.add(md.getThis());
4688 } else if (d == null) {
4689 // access static field
4690 base.add(GLOBALDESC);
4691 base.add(nn.getField());
4694 // FieldDescriptor fd = nn.getField();addFlowGraphEdge
4696 // MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
4697 // String globalLocId = localLattice.getGlobalLoc();
4698 // if (globalLocId == null) {
4700 // Error("Method lattice does not define global variable location at "
4701 // + generateErrorMessage(md.getClassDesc(), nn));
4703 // loc.addLocation(new Location(md, globalLocId));
4705 // Location fieldLoc = (Location) fd.getType().getExtension();
4706 // loc.addLocation(fieldLoc);
4712 getFlowGraph(md).createNewFlowNode(base);
4718 private NTuple<Descriptor> analyzeFlowFieldAccessNode(MethodDescriptor md, SymbolTable nametable,
4719 FieldAccessNode fan, NodeTupleSet nodeSet, NTuple<Descriptor> base,
4720 NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
4722 ExpressionNode left = fan.getExpression();
4723 TypeDescriptor ltd = left.getType();
4724 FieldDescriptor fd = fan.getField();
4726 String varName = null;
4727 if (left.kind() == Kind.NameNode) {
4728 NameDescriptor nd = ((NameNode) left).getName();
4729 varName = nd.toString();
4732 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
4733 // using a class name directly or access using this
4734 if (fd.isStatic() && fd.isFinal()) {
4739 NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
4741 if (left instanceof ArrayAccessNode) {
4743 ArrayAccessNode aan = (ArrayAccessNode) left;
4744 left = aan.getExpression();
4745 analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, base,
4746 implicitFlowTupleSet, isLHS);
4748 nodeSet.addTupleSet(idxNodeTupleSet);
4751 analyzeFlowExpressionNode(md, nametable, left, nodeSet, base, implicitFlowTupleSet, isLHS);
4754 // in this case, field is TOP location
4758 NTuple<Descriptor> flowFieldTuple = new NTuple<Descriptor>(base.toList());
4760 if (!left.getType().isPrimitive()) {
4762 if (!fd.getSymbol().equals("length")) {
4763 // array.length access, just have the location of the array
4764 flowFieldTuple.add(fd);
4765 nodeSet.removeTuple(base);
4769 getFlowGraph(md).createNewFlowNode(flowFieldTuple);
4772 for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
4773 NTuple<Descriptor> idxTuple = idxIter.next();
4774 getFlowGraph(md).addValueFlowEdge(idxTuple, flowFieldTuple);
4777 return flowFieldTuple;
4783 private void debug_printTreeNode(TreeNode tn) {
4785 System.out.println("DEBUG: " + tn.printNode(0) + " line#=" + tn.getNumLine());
4789 private void analyzeFlowAssignmentNode(MethodDescriptor md, SymbolTable nametable,
4790 AssignmentNode an, NodeTupleSet nodeSet, NTuple<Descriptor> base,
4791 NodeTupleSet implicitFlowTupleSet) {
4793 NodeTupleSet nodeSetRHS = new NodeTupleSet();
4794 NodeTupleSet nodeSetLHS = new NodeTupleSet();
4796 boolean postinc = true;
4797 if (an.getOperation().getBaseOp() == null
4798 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
4799 .getBaseOp().getOp() != Operation.POSTDEC)) {
4802 // if LHS is array access node, need to capture value flows between an array
4803 // and its index value
4804 analyzeFlowExpressionNode(md, nametable, an.getDest(), nodeSetLHS, null, implicitFlowTupleSet,
4808 // analyze value flows of rhs expression
4809 analyzeFlowExpressionNode(md, nametable, an.getSrc(), nodeSetRHS, null, implicitFlowTupleSet,
4812 // System.out.println("-analyzeFlowAssignmentNode=" + an.printNode(0));
4813 // System.out.println("-nodeSetLHS=" + nodeSetLHS);
4814 // System.out.println("-nodeSetRHS=" + nodeSetRHS);
4815 // System.out.println("-implicitFlowTupleSet=" + implicitFlowTupleSet);
4816 // System.out.println("-");
4818 if (an.getOperation().getOp() >= 2 && an.getOperation().getOp() <= 12) {
4819 // if assignment contains OP+EQ operator, creates edges from LHS to LHS
4821 for (Iterator<NTuple<Descriptor>> iter = nodeSetLHS.iterator(); iter.hasNext();) {
4822 NTuple<Descriptor> fromTuple = iter.next();
4823 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4824 NTuple<Descriptor> toTuple = iter2.next();
4825 addFlowGraphEdge(md, fromTuple, toTuple);
4830 // creates edges from RHS to LHS
4831 NTuple<Descriptor> interTuple = null;
4832 if (nodeSetRHS.size() > 1) {
4833 interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4836 for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
4837 NTuple<Descriptor> fromTuple = iter.next();
4838 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4839 NTuple<Descriptor> toTuple = iter2.next();
4840 addFlowGraphEdge(md, fromTuple, interTuple, toTuple);
4844 // creates edges from implicitFlowTupleSet to LHS
4845 for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
4846 NTuple<Descriptor> fromTuple = iter.next();
4847 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4848 NTuple<Descriptor> toTuple = iter2.next();
4849 addFlowGraphEdge(md, fromTuple, toTuple);
4856 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4857 NTuple<Descriptor> tuple = iter2.next();
4858 addFlowGraphEdge(md, tuple, tuple);
4861 // creates edges from implicitFlowTupleSet to LHS
4862 for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
4863 NTuple<Descriptor> fromTuple = iter.next();
4864 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4865 NTuple<Descriptor> toTuple = iter2.next();
4866 addFlowGraphEdge(md, fromTuple, toTuple);
4872 if (nodeSet != null) {
4873 nodeSet.addTupleSet(nodeSetLHS);
4877 public FlowGraph getFlowGraph(MethodDescriptor md) {
4878 return mapMethodDescriptorToFlowGraph.get(md);
4881 private boolean addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
4882 NTuple<Descriptor> to) {
4883 FlowGraph graph = getFlowGraph(md);
4884 graph.addValueFlowEdge(from, to);
4888 private void addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
4889 NTuple<Descriptor> inter, NTuple<Descriptor> to) {
4891 FlowGraph graph = getFlowGraph(md);
4893 if (inter != null) {
4894 graph.addValueFlowEdge(from, inter);
4895 graph.addValueFlowEdge(inter, to);
4897 graph.addValueFlowEdge(from, to);
4902 public void writeInferredLatticeDotFile(ClassDescriptor cd, HierarchyGraph simpleHierarchyGraph,
4903 SSJavaLattice<String> locOrder, String nameSuffix) {
4904 writeInferredLatticeDotFile(cd, null, simpleHierarchyGraph, locOrder, nameSuffix);
4907 public void writeInferredLatticeDotFile(ClassDescriptor cd, MethodDescriptor md,
4908 HierarchyGraph simpleHierarchyGraph, SSJavaLattice<String> locOrder, String nameSuffix) {
4910 String fileName = "lattice_";
4913 cd.getSymbol().replaceAll("[\\W_]", "") + "_" + md.toString().replaceAll("[\\W_]", "");
4915 fileName += cd.getSymbol().replaceAll("[\\W_]", "");
4918 fileName += nameSuffix;
4920 Set<Pair<String, String>> pairSet = locOrder.getOrderingPairSet();
4922 Set<String> addedLocSet = new HashSet<String>();
4924 if (pairSet.size() > 0) {
4926 BufferedWriter bw = new BufferedWriter(new FileWriter(fileName + ".dot"));
4928 bw.write("digraph " + fileName + " {\n");
4930 for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
4931 // pair is in the form of <higher, lower>
4932 Pair<String, String> pair = (Pair<String, String>) iterator.next();
4934 String highLocId = pair.getFirst();
4935 String lowLocId = pair.getSecond();
4937 if (!addedLocSet.contains(highLocId)) {
4938 addedLocSet.add(highLocId);
4939 drawNode(bw, locOrder, simpleHierarchyGraph, highLocId);
4942 if (!addedLocSet.contains(lowLocId)) {
4943 addedLocSet.add(lowLocId);
4944 drawNode(bw, locOrder, simpleHierarchyGraph, lowLocId);
4947 bw.write(highLocId + " -> " + lowLocId + ";\n");
4952 } catch (IOException e) {
4953 e.printStackTrace();
4960 private String convertMergeSetToString(HierarchyGraph graph, Set<HNode> mergeSet) {
4962 for (Iterator iterator = mergeSet.iterator(); iterator.hasNext();) {
4963 HNode merged = (HNode) iterator.next();
4964 if (merged.isMergeNode()) {
4965 str += convertMergeSetToString(graph, graph.getMapHNodetoMergeSet().get(merged));
4967 str += " " + merged.getName();
4973 private void drawNode(BufferedWriter bw, SSJavaLattice<String> lattice, HierarchyGraph graph,
4974 String locName) throws IOException {
4976 HNode node = graph.getHNode(locName);
4983 if (lattice.isSharedLoc(locName)) {
4984 prettyStr = locName + "*";
4986 prettyStr = locName;
4989 if (node.isMergeNode()) {
4990 Set<HNode> mergeSet = graph.getMapHNodetoMergeSet().get(node);
4991 prettyStr += ":" + convertMergeSetToString(graph, mergeSet);
4993 bw.write(locName + " [label=\"" + prettyStr + "\"]" + ";\n");
4996 public void _debug_printGraph() {
4997 Set<MethodDescriptor> keySet = mapMethodDescriptorToFlowGraph.keySet();
4999 for (Iterator<MethodDescriptor> iterator = keySet.iterator(); iterator.hasNext();) {
5000 MethodDescriptor md = (MethodDescriptor) iterator.next();
5001 FlowGraph fg = mapMethodDescriptorToFlowGraph.get(md);
5004 } catch (IOException e) {
5005 e.printStackTrace();
5013 class CyclicFlowException extends Exception {
5017 class InterDescriptor extends Descriptor {
5019 public InterDescriptor(String name) {