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 String newline = System.getProperty("line.separator");
137 LocationInfo curMethodInfo;
139 boolean debug = true;
141 private static int locSeed = 0;
143 public LocationInference(SSJavaAnalysis ssjava, State state) {
144 this.ssjava = ssjava;
146 this.temp_toanalyzeList = new ArrayList<ClassDescriptor>();
147 this.temp_toanalyzeMethodList = new ArrayList<MethodDescriptor>();
148 this.mapMethodDescriptorToFlowGraph = new HashMap<MethodDescriptor, FlowGraph>();
149 this.cd2lattice = new HashMap<ClassDescriptor, SSJavaLattice<String>>();
150 this.md2lattice = new HashMap<MethodDescriptor, SSJavaLattice<String>>();
151 this.methodDescriptorsToVisitStack = new Stack<MethodDescriptor>();
152 this.mapMethodDescriptorToMethodInvokeNodeSet =
153 new HashMap<MethodDescriptor, Set<MethodInvokeNode>>();
154 this.mapMethodInvokeNodeToArgIdxMap =
155 new HashMap<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>>();
156 this.mapMethodDescToMethodLocationInfo = new HashMap<MethodDescriptor, MethodLocationInfo>();
157 this.mapMethodToCalleeSet = new HashMap<MethodDescriptor, Set<MethodDescriptor>>();
158 this.mapClassToLocationInfo = new HashMap<ClassDescriptor, LocationInfo>();
160 this.mapFileNameToLineVector = new HashMap<String, Vector<String>>();
161 this.mapDescToDefinitionLine = new HashMap<Descriptor, Integer>();
162 this.mapMethodDescToParamNodeFlowsToReturnValue =
163 new HashMap<MethodDescriptor, Set<FlowNode>>();
165 this.mapDescriptorToHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
166 this.mapMethodInvokeNodeToBaseTuple = new HashMap<MethodInvokeNode, NTuple<Descriptor>>();
168 this.mapDescriptorToSkeletonHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
169 this.mapDescriptorToCombineSkeletonHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
170 this.mapDescriptorToSimpleHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
172 this.mapDescriptorToSimpleLattice = new HashMap<Descriptor, SSJavaLattice<String>>();
174 this.mapDescToLocationSummary = new HashMap<Descriptor, LocationSummary>();
176 this.mapMethodDescriptorToSubGlobalFlowGraph = new HashMap<MethodDescriptor, GlobalFlowGraph>();
178 this.mapMethodInvokeNodeToMapCallerArgToCalleeArg =
179 new HashMap<MethodInvokeNode, Map<NTuple<Descriptor>, NTuple<Descriptor>>>();
183 public void setupToAnalyze() {
184 SymbolTable classtable = state.getClassSymbolTable();
185 temp_toanalyzeList.clear();
186 temp_toanalyzeList.addAll(classtable.getValueSet());
187 // Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
188 // public int compare(ClassDescriptor o1, ClassDescriptor o2) {
189 // return o1.getClassName().compareToIgnoreCase(o2.getClassName());
194 public void setupToAnalazeMethod(ClassDescriptor cd) {
196 SymbolTable methodtable = cd.getMethodTable();
197 temp_toanalyzeMethodList.clear();
198 temp_toanalyzeMethodList.addAll(methodtable.getValueSet());
199 Collections.sort(temp_toanalyzeMethodList, new Comparator<MethodDescriptor>() {
200 public int compare(MethodDescriptor o1, MethodDescriptor o2) {
201 return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
206 public boolean toAnalyzeMethodIsEmpty() {
207 return temp_toanalyzeMethodList.isEmpty();
210 public boolean toAnalyzeIsEmpty() {
211 return temp_toanalyzeList.isEmpty();
214 public ClassDescriptor toAnalyzeNext() {
215 return temp_toanalyzeList.remove(0);
218 public MethodDescriptor toAnalyzeMethodNext() {
219 return temp_toanalyzeMethodList.remove(0);
222 public void inference() {
224 // construct value flow graph
225 constructFlowGraph();
227 assignCompositeLocation();
229 constructHierarchyGraph();
231 debug_writeHierarchyDotFiles();
233 // calculate RETURNLOC,PCLOC
234 calculateExtraLocations();
236 simplifyHierarchyGraph();
238 debug_writeSimpleHierarchyDotFiles();
240 constructSkeletonHierarchyGraph();
242 debug_writeSkeletonHierarchyDotFiles();
244 insertCombinationNodes();
246 debug_writeSkeletonCombinationHierarchyDotFiles();
250 debug_writeLattices();
252 updateCompositeLocationAssignments();
254 generateMethodSummary();
256 generateAnnoatedCode();
260 // 2) construct lattices
262 // simplifyLattices();
263 // 3) check properties
266 debug_writeLatticeDotFile();
268 // 4) generate annotated source codes
269 generateAnnoatedCode();
273 public Map<NTuple<Descriptor>, NTuple<Descriptor>> getMapCallerArgToCalleeParam(
274 MethodInvokeNode min) {
276 if (!mapMethodInvokeNodeToMapCallerArgToCalleeArg.containsKey(min)) {
277 mapMethodInvokeNodeToMapCallerArgToCalleeArg.put(min,
278 new HashMap<NTuple<Descriptor>, NTuple<Descriptor>>());
281 return mapMethodInvokeNodeToMapCallerArgToCalleeArg.get(min);
284 public void addMapCallerArgToCalleeParam(MethodInvokeNode min, NTuple<Descriptor> callerArg,
285 NTuple<Descriptor> calleeParam) {
286 getMapCallerArgToCalleeParam(min).put(callerArg, calleeParam);
289 private void assignCompositeLocation() {
290 calculateGlobalValueFlowCompositeLocation();
291 translateCompositeLocationAssignmentToFlowGraph();
294 private void translateCompositeLocationAssignmentToFlowGraph() {
295 MethodDescriptor methodEventLoopDesc = ssjava.getMethodContainingSSJavaLoop();
296 translateCompositeLocationAssignmentToFlowGraph(methodEventLoopDesc);
300 private void updateCompositeLocationAssignments() {
302 LinkedList<MethodDescriptor> methodDescList =
303 (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
305 while (!methodDescList.isEmpty()) {
306 MethodDescriptor md = methodDescList.removeLast();
307 FlowGraph flowGraph = getFlowGraph(md);
309 MethodSummary methodSummary = getMethodSummary(md);
311 Set<FlowNode> nodeSet = flowGraph.getNodeSet();
312 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
313 FlowNode node = (FlowNode) iterator.next();
314 if (node.getCompositeLocation() != null) {
315 CompositeLocation compLoc = node.getCompositeLocation();
316 CompositeLocation updatedCompLoc = updateCompositeLocation(compLoc);
317 node.setCompositeLocation(updatedCompLoc);
319 NTuple<Descriptor> descTuple = node.getDescTuple();
320 CompositeLocation compLoc = convertToCompositeLocation(md, descTuple);
321 compLoc = updateCompositeLocation(compLoc);
322 node.setCompositeLocation(compLoc);
325 if (node.isDeclaratonNode()) {
326 Descriptor localVarDesc = node.getDescTuple().get(0);
327 methodSummary.addMapVarNameToInferCompLoc(localVarDesc, node.getCompositeLocation());
335 private CompositeLocation updateCompositeLocation(CompositeLocation compLoc) {
336 CompositeLocation updatedCompLoc = new CompositeLocation();
337 for (int i = 0; i < compLoc.getSize(); i++) {
338 Location loc = compLoc.get(i);
339 String nodeIdentifier = loc.getLocIdentifier();
340 Descriptor enclosingDesc = loc.getDescriptor();
341 System.out.println("enclosingDesc=" + enclosingDesc);
343 if (!enclosingDesc.equals(GLOBALDESC)) {
344 LocationSummary locSummary = getLocationSummary(enclosingDesc);
345 locName = locSummary.getLocationName(nodeIdentifier);
347 locName = nodeIdentifier;
349 Location updatedLoc = new Location(enclosingDesc, locName);
350 updatedCompLoc.addLocation(updatedLoc);
353 return updatedCompLoc;
356 private void translateCompositeLocationAssignmentToFlowGraph(MethodDescriptor mdCaller) {
358 System.out.println("\n#translateCompositeLocationAssignmentToFlowGraph=" + mdCaller);
360 // First, assign a composite location to a node in the flow graph
361 GlobalFlowGraph callerGlobalFlowGraph = getSubGlobalFlowGraph(mdCaller);
363 FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
364 Map<Location, CompositeLocation> callerMapLocToCompLoc =
365 callerGlobalFlowGraph.getMapLocationToInferCompositeLocation();
366 System.out.println("---callerMapLocToCompLoc=" + callerMapLocToCompLoc);
367 Set<Location> methodLocSet = callerMapLocToCompLoc.keySet();
368 for (Iterator iterator = methodLocSet.iterator(); iterator.hasNext();) {
369 Location methodLoc = (Location) iterator.next();
370 if (methodLoc.getDescriptor().equals(mdCaller)) {
371 CompositeLocation inferCompLoc = callerMapLocToCompLoc.get(methodLoc);
372 assignCompositeLocationToFlowGraph(callerFlowGraph, methodLoc, inferCompLoc);
376 Set<MethodInvokeNode> minSet = mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
378 Set<MethodDescriptor> calleeSet = new HashSet<MethodDescriptor>();
379 for (Iterator iterator = minSet.iterator(); iterator.hasNext();) {
380 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
381 // need to translate a composite location that is started with the base
383 if (mapMethodInvokeNodeToBaseTuple.get(min) != null) {
384 // if mapMethodInvokeNodeToBaseTuple doesn't have a mapping
385 // it means that the corresponding callee method does not cause any
387 translateMapLocationToInferCompositeLocationToCalleeGraph(callerGlobalFlowGraph, min);
389 calleeSet.add(min.getMethod());
392 for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
393 MethodDescriptor callee = (MethodDescriptor) iterator.next();
394 translateCompositeLocationAssignmentToFlowGraph(callee);
399 public void assignCompositeLocationToFlowGraph(FlowGraph flowGraph, Location loc,
400 CompositeLocation inferCompLoc) {
401 Descriptor localDesc = loc.getLocDescriptor();
403 Set<FlowNode> nodeSet = flowGraph.getNodeSet();
404 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
405 FlowNode node = (FlowNode) iterator.next();
406 if (node.getDescTuple().startsWith(localDesc)) {
407 // need to assign the inferred composite location to this node
408 CompositeLocation newCompLoc = generateCompositeLocation(node.getDescTuple(), inferCompLoc);
409 node.setCompositeLocation(newCompLoc);
410 System.out.println("SET Node=" + node + " inferCompLoc=" + newCompLoc);
415 private CompositeLocation generateCompositeLocation(NTuple<Descriptor> nodeDescTuple,
416 CompositeLocation inferCompLoc) {
418 System.out.println("generateCompositeLocation=" + nodeDescTuple + " with inferCompLoc="
421 CompositeLocation newCompLoc = new CompositeLocation();
422 for (int i = 0; i < inferCompLoc.getSize(); i++) {
423 newCompLoc.addLocation(inferCompLoc.get(i));
426 Descriptor lastDescOfPrefix = nodeDescTuple.get(0);
427 Descriptor enclosingDescriptor;
428 if (lastDescOfPrefix instanceof InterDescriptor) {
429 enclosingDescriptor = null;
431 enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
434 for (int i = 1; i < nodeDescTuple.size(); i++) {
435 Descriptor desc = nodeDescTuple.get(i);
436 Location locElement = new Location(enclosingDescriptor, desc);
437 newCompLoc.addLocation(locElement);
439 enclosingDescriptor = ((FieldDescriptor) desc).getClassDescriptor();
445 private void translateMapLocationToInferCompositeLocationToCalleeGraph(
446 GlobalFlowGraph callerGraph, MethodInvokeNode min) {
448 MethodDescriptor mdCallee = min.getMethod();
449 MethodDescriptor mdCaller = callerGraph.getMethodDescriptor();
450 Map<Location, CompositeLocation> callerMapLocToCompLoc =
451 callerGraph.getMapLocationToInferCompositeLocation();
453 FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
454 GlobalFlowGraph calleeGlobalGraph = getSubGlobalFlowGraph(mdCallee);
456 NTuple<Location> baseLocTuple =
457 translateToLocTuple(mdCaller, mapMethodInvokeNodeToBaseTuple.get(min));
459 // System.out.println("\n-translate caller infer composite loc to callee=" + mdCallee
460 // + " baseLocTuple=" + baseLocTuple);
461 Set<Location> keySet = callerMapLocToCompLoc.keySet();
462 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
463 Location key = (Location) iterator.next();
464 CompositeLocation callerCompLoc = callerMapLocToCompLoc.get(key);
466 if (!key.getDescriptor().equals(mdCaller)) {
467 // System.out.println("--- caller key=" + key + " callerCompLoc=" + callerCompLoc);
469 // && callerCompLoc.getTuple().startsWith(baseLocTuple)) {
470 // need to translate to the callee side
473 CompositeLocation newCalleeCompLoc;
474 if (callerCompLoc.getTuple().startsWith(baseLocTuple)) {
475 System.out.println("---need to translate callerCompLoc=" + callerCompLoc
476 + " with baseTuple=" + baseLocTuple);
478 translateCompositeLocationToCallee(callerCompLoc, baseLocTuple, mdCallee);
480 calleeGlobalGraph.addMapLocationToInferCompositeLocation(key, newCalleeCompLoc);
481 System.out.println("---callee loc=" + key + " newCalleeCompLoc=" + newCalleeCompLoc);
483 // newCalleeCompLoc = callerCompLoc.clone();
489 // If the location of an argument has a composite location
490 // need to assign a proper composite location to the corresponding callee parameter
491 System.out.println("\n-translate arg composite location to callee param. min="
493 Map<Integer, NTuple<Descriptor>> mapIdxToArgTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
494 Set<Integer> idxSet = mapIdxToArgTuple.keySet();
495 for (Iterator iterator = idxSet.iterator(); iterator.hasNext();) {
496 Integer idx = (Integer) iterator.next();
498 if (idx == 0 && !min.getMethod().isStatic()) {
502 NTuple<Descriptor> argTuple = mapIdxToArgTuple.get(idx);
503 if (argTuple.size() > 0) {
504 // check if an arg tuple has been already assigned to a composite location
505 NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argTuple);
506 Location argLocalLoc = argLocTuple.get(0);
508 // if (!isPrimitiveType(argTuple)) {
509 if (callerMapLocToCompLoc.containsKey(argLocalLoc)) {
511 CompositeLocation callerCompLoc = callerMapLocToCompLoc.get(argLocalLoc);
512 for (int i = 1; i < argLocTuple.size(); i++) {
513 callerCompLoc.addLocation(argLocTuple.get(i));
516 if (callerCompLoc.getTuple().startsWith(baseLocTuple)) {
518 FlowNode calleeParamFlowNode = calleeFlowGraph.getParamFlowNode(idx);
519 NTuple<Descriptor> calleeParamDescTuple = calleeParamFlowNode.getDescTuple();
520 NTuple<Location> calleeParamLocTuple =
521 translateToLocTuple(mdCallee, calleeParamDescTuple);
523 System.out.println("---need to translate callerCompLoc=" + callerCompLoc
524 + " with baseTuple=" + baseLocTuple + " calleeParamLocTuple="
525 + calleeParamLocTuple);
527 CompositeLocation newCalleeCompLoc =
528 translateCompositeLocationToCallee(callerCompLoc, baseLocTuple, mdCallee);
530 calleeGlobalGraph.addMapLocationToInferCompositeLocation(calleeParamLocTuple.get(0),
533 System.out.println("---callee loc=" + calleeParamLocTuple.get(0)
534 + " newCalleeCompLoc=" + newCalleeCompLoc);
536 // System.out.println("###need to assign composite location to=" + calleeParamDescTuple
537 // + " with baseTuple=" + baseLocTuple);
547 private boolean isPrimitiveType(NTuple<Descriptor> argTuple) {
549 Descriptor lastDesc = argTuple.get(argTuple.size() - 1);
551 if (lastDesc instanceof FieldDescriptor) {
552 return ((FieldDescriptor) lastDesc).getType().isPrimitive();
553 } else if (lastDesc instanceof VarDescriptor) {
554 return ((VarDescriptor) lastDesc).getType().isPrimitive();
560 private CompositeLocation translateCompositeLocationToCallee(CompositeLocation callerCompLoc,
561 NTuple<Location> baseLocTuple, MethodDescriptor mdCallee) {
563 CompositeLocation newCalleeCompLoc = new CompositeLocation();
565 Location calleeThisLoc = new Location(mdCallee, mdCallee.getThis());
566 newCalleeCompLoc.addLocation(calleeThisLoc);
568 // remove the base tuple from the caller
569 // ex; In the method invoation foo.bar.methodA(), the callee will have the composite location
570 // ,which is relative to the 'this' variable, <THIS,...>
571 for (int i = baseLocTuple.size(); i < callerCompLoc.getSize(); i++) {
572 newCalleeCompLoc.addLocation(callerCompLoc.get(i));
575 return newCalleeCompLoc;
579 private void calculateGlobalValueFlowCompositeLocation() {
581 System.out.println("SSJAVA: Calculate composite locations in the global value flow graph");
582 MethodDescriptor methodDescEventLoop = ssjava.getMethodContainingSSJavaLoop();
583 GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(methodDescEventLoop);
585 Set<Location> calculatedPrefixSet = new HashSet<Location>();
587 Set<GlobalFlowNode> nodeSet = globalFlowGraph.getNodeSet();
589 next: for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
590 GlobalFlowNode node = (GlobalFlowNode) iterator.next();
592 Location prefixLoc = node.getLocTuple().get(0);
594 if (calculatedPrefixSet.contains(prefixLoc)) {
595 // the prefix loc has been already assigned to a composite location
599 calculatedPrefixSet.add(prefixLoc);
601 // Set<GlobalFlowNode> incomingNodeSet = globalFlowGraph.getIncomingNodeSet(node);
602 List<NTuple<Location>> prefixList = calculatePrefixList(globalFlowGraph, node);
604 Set<GlobalFlowNode> reachableNodeSet =
605 globalFlowGraph.getReachableNodeSetByPrefix(node.getLocTuple().get(0));
606 // Set<GlobalFlowNode> reachNodeSet = globalFlowGraph.getReachableNodeSetFrom(node);
608 // System.out.println("node=" + node + " prefixList=" + prefixList + " reachableNodeSet="
609 // + reachableNodeSet);
611 for (int i = 0; i < prefixList.size(); i++) {
612 NTuple<Location> curPrefix = prefixList.get(i);
613 Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
615 for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
616 GlobalFlowNode reachNode = (GlobalFlowNode) iterator2.next();
617 if (reachNode.getLocTuple().startsWith(curPrefix)) {
618 reachableCommonPrefixSet.add(reachNode.getLocTuple());
622 if (!reachableCommonPrefixSet.isEmpty()) {
624 MethodDescriptor curPrefixFirstElementMethodDesc =
625 (MethodDescriptor) curPrefix.get(0).getDescriptor();
627 MethodDescriptor nodePrefixLocFirstElementMethodDesc =
628 (MethodDescriptor) prefixLoc.getDescriptor();
630 if (curPrefixFirstElementMethodDesc.equals(nodePrefixLocFirstElementMethodDesc)
631 || isTransitivelyCalledFrom(nodePrefixLocFirstElementMethodDesc,
632 curPrefixFirstElementMethodDesc)) {
635 // if (!node.getLocTuple().startsWith(curPrefix.get(0))) {
637 Location curPrefixLocalLoc = curPrefix.get(0);
638 if (globalFlowGraph.mapLocationToInferCompositeLocation.containsKey(curPrefixLocalLoc)) {
639 // in this case, the local variable of the current prefix has already got a composite
641 // so we just ignore the current composite location.
643 // System.out.println("HERE WE DO NOT ASSIGN A COMPOSITE LOCATION TO =" + node
644 // + " DUE TO " + curPrefix);
649 Location targetLocalLoc = node.getLocTuple().get(0);
650 // CompositeLocation curCompLoc = globalFlowGraph.getCompositeLocation(targetLocalLoc);
651 // if ((curPrefix.size() + 1) > curCompLoc.getSize()) {
653 CompositeLocation newCompLoc = generateCompositeLocation(curPrefix);
654 System.out.println("NEED TO ASSIGN COMP LOC TO " + node + " with prefix=" + curPrefix);
655 System.out.println("- newCompLoc=" + newCompLoc);
656 globalFlowGraph.addMapLocationToInferCompositeLocation(targetLocalLoc, newCompLoc);
669 // Set<GlobalFlowNode> inNodeSet =
670 // graph.getIncomingNodeSetWithPrefix(prefix);
671 // System.out.println("inNodeSet=" + inNodeSet + " from=" + node);
674 private void assignCompositeLocation(CompositeLocation compLocPrefix, GlobalFlowNode node) {
675 CompositeLocation newCompLoc = compLocPrefix.clone();
676 NTuple<Location> locTuple = node.getLocTuple();
677 for (int i = 1; i < locTuple.size(); i++) {
678 newCompLoc.addLocation(locTuple.get(i));
680 node.setInferCompositeLocation(newCompLoc);
683 private List<NTuple<Location>> calculatePrefixList(GlobalFlowGraph graph, GlobalFlowNode node) {
685 System.out.println("\n##### calculatePrefixList node=" + node);
687 MethodDescriptor md = graph.getMethodDescriptor();
689 Set<GlobalFlowNode> incomingNodeSetPrefix =
690 graph.getIncomingNodeSetByPrefix(node.getLocTuple().get(0));
691 // System.out.println("incomingNodeSetPrefix=" + incomingNodeSetPrefix);
693 // Set<GlobalFlowNode> reachableNodeSetPrefix =
694 // graph.getReachableNodeSetByPrefix(node.getLocTuple().get(0));
695 // System.out.println("reachableNodeSetPrefix=" + reachableNodeSetPrefix);
697 List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
699 for (Iterator iterator = incomingNodeSetPrefix.iterator(); iterator.hasNext();) {
700 GlobalFlowNode inNode = (GlobalFlowNode) iterator.next();
701 NTuple<Location> inNodeTuple = inNode.getLocTuple();
703 for (int i = 1; i < inNodeTuple.size(); i++) {
704 NTuple<Location> prefix = inNodeTuple.subList(0, i);
705 if (!prefixList.contains(prefix)) {
706 prefixList.add(prefix);
711 Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
712 public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
713 int s0 = arg0.size();
714 int s1 = arg1.size();
717 } else if (s0 == s1) {
726 // List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
728 // for (Iterator iterator = incomingNodeSet.iterator(); iterator.hasNext();) {
729 // GlobalFlowNode inNode = (GlobalFlowNode) iterator.next();
730 // NTuple<Location> inNodeTuple = inNode.getLocTuple();
732 // for (int i = 1; i < inNodeTuple.size(); i++) {
733 // NTuple<Location> prefix = inNodeTuple.subList(0, i);
734 // if (!prefixList.contains(prefix)) {
735 // prefixList.add(prefix);
740 // Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
741 // public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
742 // int s0 = arg0.size();
743 // int s1 = arg1.size();
746 // } else if (s0 == s1) {
753 // return prefixList;
756 private GlobalFlowGraph constructSubGlobalFlowGraph(FlowGraph flowGraph) {
758 MethodDescriptor md = flowGraph.getMethodDescriptor();
760 GlobalFlowGraph globalGraph = new GlobalFlowGraph(md);
762 // Set<FlowNode> nodeSet = flowGraph.getNodeSet();
763 Set<FlowEdge> edgeSet = flowGraph.getEdgeSet();
765 for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
767 FlowEdge edge = (FlowEdge) iterator.next();
768 NTuple<Descriptor> srcDescTuple = edge.getInitTuple();
769 NTuple<Descriptor> dstDescTuple = edge.getEndTuple();
771 // here only keep the first element(method location) of the descriptor
773 NTuple<Location> srcLocTuple = translateToLocTuple(md, srcDescTuple);
774 // Location srcMethodLoc = srcLocTuple.get(0);
775 // Descriptor srcVarDesc = srcMethodLoc.getLocDescriptor();
776 // // if (flowGraph.isParamDesc(srcVarDesc) &&
777 // (!srcVarDesc.equals(md.getThis()))) {
778 // if (!srcVarDesc.equals(md.getThis())) {
779 // srcLocTuple = new NTuple<Location>();
780 // Location loc = new Location(md, srcVarDesc);
781 // srcLocTuple.add(loc);
784 NTuple<Location> dstLocTuple = translateToLocTuple(md, dstDescTuple);
785 // Location dstMethodLoc = dstLocTuple.get(0);
786 // Descriptor dstVarDesc = dstMethodLoc.getLocDescriptor();
787 // if (!dstVarDesc.equals(md.getThis())) {
788 // dstLocTuple = new NTuple<Location>();
789 // Location loc = new Location(md, dstVarDesc);
790 // dstLocTuple.add(loc);
793 globalGraph.addValueFlowEdge(srcLocTuple, dstLocTuple);
800 private NTuple<Location> translateToLocTuple(MethodDescriptor md, NTuple<Descriptor> descTuple) {
802 NTuple<Location> locTuple = new NTuple<Location>();
804 Descriptor enclosingDesc = md;
805 // System.out.println("md=" + md + " descTuple=" + descTuple);
806 for (int i = 0; i < descTuple.size(); i++) {
807 Descriptor desc = descTuple.get(i);
809 Location loc = new Location(enclosingDesc, desc);
812 if (desc instanceof VarDescriptor) {
813 enclosingDesc = ((VarDescriptor) desc).getType().getClassDesc();
814 } else if (desc instanceof FieldDescriptor) {
815 enclosingDesc = ((FieldDescriptor) desc).getType().getClassDesc();
817 // TODO: inter descriptor case
818 enclosingDesc = desc;
827 private void addValueFlowsFromCalleeSubGlobalFlowGraph(MethodDescriptor mdCaller,
828 GlobalFlowGraph subGlobalFlowGraph) {
830 // the transformation for a call site propagates flows through parameters
831 // if the method is virtual, it also grab all relations from any possible
834 Set<MethodInvokeNode> setMethodInvokeNode = getMethodInvokeNodeSet(mdCaller);
836 for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
837 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
838 MethodDescriptor mdCallee = min.getMethod();
839 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
840 if (mdCallee.isStatic()) {
841 setPossibleCallees.add(mdCallee);
843 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
844 // removes method descriptors that are not invoked by the caller
845 calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
846 setPossibleCallees.addAll(calleeSet);
849 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
850 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
851 propagateValueFlowsToCallerFromSubGlobalFlowGraph(min, mdCaller, possibleMdCallee);
858 private void propagateValueFlowsToCallerFromSubGlobalFlowGraph(MethodInvokeNode min,
859 MethodDescriptor mdCaller, MethodDescriptor possibleMdCallee) {
861 System.out.println("propagateValueFlowsToCallerFromSubGlobalFlowGraph=" + min.printNode(0)
862 + " by caller=" + mdCaller);
863 FlowGraph calleeFlowGraph = getFlowGraph(possibleMdCallee);
864 Map<Integer, NTuple<Descriptor>> mapIdxToArg = mapMethodInvokeNodeToArgIdxMap.get(min);
866 System.out.println("mapMethodInvokeNodeToArgIdxMap.get(min)="
867 + mapMethodInvokeNodeToArgIdxMap.get(min));
868 Set<Integer> keySet = mapIdxToArg.keySet();
869 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
870 Integer idx = (Integer) iterator.next();
871 NTuple<Descriptor> argDescTuple = mapIdxToArg.get(idx);
872 if (argDescTuple.size() > 0) {
873 NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argDescTuple);
874 NTuple<Descriptor> paramDescTuple = calleeFlowGraph.getParamFlowNode(idx).getDescTuple();
875 NTuple<Location> paramLocTuple = translateToLocTuple(possibleMdCallee, paramDescTuple);
876 addMapCallerArgToCalleeParam(min, argDescTuple, paramDescTuple);
881 NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
882 GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(possibleMdCallee);
883 Set<GlobalFlowNode> calleeNodeSet = calleeSubGlobalGraph.getNodeSet();
884 System.out.println("#calleeNodeSet=" + calleeNodeSet);
885 for (Iterator iterator = calleeNodeSet.iterator(); iterator.hasNext();) {
886 GlobalFlowNode calleeNode = (GlobalFlowNode) iterator.next();
887 addValueFlowFromCalleeNode(min, mdCaller, possibleMdCallee, calleeNode);
890 // int numParam = calleeFlowGraph.getNumParameters();
891 // for (int idx = 0; idx < numParam; idx++) {
893 // FlowNode paramNode = calleeFlowGraph.getParamFlowNode(idx);
895 // NTuple<Location> paramLocTuple =
896 // translateToLocTuple(possibleMdCallee, paramNode.getCurrentDescTuple());
898 // GlobalFlowNode globalParamNode =
899 // calleeSubGlobalGraph.getFlowNode(paramLocTuple);
901 // NTuple<Descriptor> argTuple =
902 // mapMethodInvokeNodeToArgIdxMap.get(min).get(idx);
904 // NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argTuple);
906 // System.out.println("argTupleSet=" + argLocTuple + " param=" +
908 // // here, it adds all value flows reachable from the paramNode in the
909 // callee's flow graph
911 // addValueFlowsFromCalleeParam(mdCaller, argLocTuple, baseLocTuple,
917 // // FlowGraph callerSubGlobalGraph = getSubGlobalFlowGraph(mdCaller);
918 // // FlowGraph calleeSubGlobalGraph =
919 // getSubGlobalFlowGraph(possibleMdCallee);
921 // // int numParam = calleeSubGlobalGraph.getNumParameters();
922 // // for (int idx = 0; idx < numParam; idx++) {
923 // // FlowNode paramNode = calleeSubGlobalGraph.getParamFlowNode(idx);
924 // // NTuple<Descriptor> argTuple =
925 // mapMethodInvokeNodeToArgIdxMap.get(min).get(idx);
926 // // System.out.println("argTupleSet=" + argTuple + " param=" +
928 // // // here, it adds all value flows reachable from the paramNode in the
929 // callee's flow graph
930 // // addValueFlowsFromCalleeParam(min, calleeSubGlobalGraph, paramNode,
931 // callerSubGlobalGraph,
932 // // argTuple, baseTuple);
937 private void addValueFlowFromCalleeNode(MethodInvokeNode min, MethodDescriptor mdCaller,
938 MethodDescriptor mdCallee, GlobalFlowNode calleeSrcNode) {
940 GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(mdCallee);
941 GlobalFlowGraph callerSubGlobalGraph = getSubGlobalFlowGraph(mdCaller);
943 NTuple<Location> callerSrcNodeLocTuple =
944 translateToCallerLocTuple(min, mdCallee, mdCaller, calleeSrcNode.getLocTuple());
946 if (callerSrcNodeLocTuple != null) {
947 Set<GlobalFlowNode> outNodeSet = calleeSubGlobalGraph.getOutNodeSet(calleeSrcNode);
949 for (Iterator iterator = outNodeSet.iterator(); iterator.hasNext();) {
950 GlobalFlowNode outNode = (GlobalFlowNode) iterator.next();
951 NTuple<Location> callerDstNodeLocTuple =
952 translateToCallerLocTuple(min, mdCallee, mdCaller, outNode.getLocTuple());
953 if (callerDstNodeLocTuple != null) {
954 callerSubGlobalGraph.addValueFlowEdge(callerSrcNodeLocTuple, callerDstNodeLocTuple);
961 private NTuple<Location> translateToCallerLocTuple(MethodInvokeNode min,
962 MethodDescriptor mdCallee, MethodDescriptor mdCaller, NTuple<Location> nodeLocTuple) {
963 // this method will return NULL if the corresponding argument is literal
965 // assumes that we don't need to propagate callee flows to the argument
968 // System.out.println("---translateToCallerLocTuple=" + min.printNode(0)
969 // + " callee nodeLocTuple=" + nodeLocTuple);
971 FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
973 NTuple<Descriptor> nodeDescTuple = translateToDescTuple(nodeLocTuple);
974 if (calleeFlowGraph.isParameter(nodeDescTuple)) {
975 int paramIdx = calleeFlowGraph.getParamIdx(nodeDescTuple);
976 NTuple<Descriptor> argDescTuple = mapMethodInvokeNodeToArgIdxMap.get(min).get(paramIdx);
977 // System.out.println(" mapMethodInvokeNodeToArgIdxMap.get(min)="
978 // + mapMethodInvokeNodeToArgIdxMap.get(min));
980 if (argDescTuple.size() == 0) {
981 // argument is literal
984 NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argDescTuple);
986 NTuple<Location> callerLocTuple = new NTuple<Location>();
988 callerLocTuple.addAll(argLocTuple);
989 for (int i = 1; i < nodeLocTuple.size(); i++) {
990 callerLocTuple.add(nodeLocTuple.get(i));
992 return callerLocTuple;
994 return nodeLocTuple.clone();
999 private NTuple<Descriptor> translateToDescTuple(NTuple<Location> locTuple) {
1001 NTuple<Descriptor> descTuple = new NTuple<Descriptor>();
1002 for (int i = 0; i < locTuple.size(); i++) {
1003 descTuple.add(locTuple.get(i).getLocDescriptor());
1009 private void addValueFlowsFromCalleeParam(MethodDescriptor mdCaller,
1010 NTuple<Location> argLocTuple, NTuple<Location> baseLocTuple, MethodDescriptor mdCallee,
1011 GlobalFlowNode globalParamNode) {
1013 Set<GlobalFlowNode> visited = new HashSet<GlobalFlowNode>();
1014 visited.add(globalParamNode);
1015 recurAddValueFlowsFromCalleeParam(mdCaller, argLocTuple, baseLocTuple, mdCallee,
1020 private void recurAddValueFlowsFromCalleeParam(MethodDescriptor mdCaller,
1021 NTuple<Location> argLocTuple, NTuple<Location> baseLocTuple, MethodDescriptor mdCallee,
1022 GlobalFlowNode calleeCurNode) {
1024 // FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
1025 // GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(mdCallee);
1027 // NTuple<Location> curNodeLocTuple = calleeCurNode.getLocTuple();
1028 // NTuple<Descriptor> curNodeDescTuple = calleeCurNode.getDescTuple();
1029 // if (calleeFlowGraph.isParameter(curNodeDescTuple)) {
1030 // curNodeLocTuple = translateToCaller(argLocTuple, curNodeLocTuple);
1033 // Set<GlobalFlowNode> outNodeSet =
1034 // calleeSubGlobalGraph.getOutNodeSet(calleeCurNode);
1035 // for (Iterator iterator = outNodeSet.iterator(); iterator.hasNext();) {
1036 // GlobalFlowNode outNode = (GlobalFlowNode) iterator.next();
1038 // NTuple<Location> curNodeLocTuple = calleeCurNode.getLocTuple();
1039 // NTuple<Descriptor> curNodeDescTuple = calleeCurNode.getDescTuple();
1040 // if (calleeFlowGraph.isParameter(curNodeDescTuple)) {
1041 // curNodeLocTuple = translateToCaller(argLocTuple, curNodeLocTuple);
1044 // outNode.getDescTuple();
1046 // if (calleeFlowGraph.is)
1048 // if (calleeSubGlobalGraph.isParameter(srcDescTuple)) {
1049 // // destination node is started with 'parameter'
1050 // // need to translate it in terms of the caller's a node
1052 // translateToCaller(min, calleeSubGlobalGraph.getParamIdx(srcDescTuple),
1058 // Set<FlowEdge> edgeSet =
1059 // calleeSubGlobalGraph.getOutEdgeSetStartingFrom(calleeSrcNode);
1060 // for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
1061 // FlowEdge flowEdge = (FlowEdge) iterator.next();
1063 // NTuple<Descriptor> srcDescTuple = flowEdge.getInitTuple();
1064 // NTuple<Descriptor> dstDescTuple = flowEdge.getEndTuple();
1066 // FlowNode dstNode = calleeSubGlobalGraph.getFlowNode(dstDescTuple);
1068 // if (calleeSubGlobalGraph.isParameter(srcDescTuple)) {
1069 // // destination node is started with 'parameter'
1070 // // need to translate it in terms of the caller's a node
1072 // translateToCaller(min, calleeSubGlobalGraph.getParamIdx(srcDescTuple),
1076 // if (calleeSubGlobalGraph.isParameter(dstDescTuple)) {
1077 // // destination node is started with 'parameter'
1078 // // need to translate it in terms of the caller's a node
1080 // translateToCaller(min, calleeSubGlobalGraph.getParamIdx(dstDescTuple),
1084 // callerSubGlobalGraph.addValueFlowEdge(srcDescTuple, dstDescTuple);
1086 // if (!visited.contains(dstNode)) {
1087 // visited.add(dstNode);
1088 // recurAddValueFlowsFromCalleeParam(min, calleeSubGlobalGraph, dstNode,
1089 // callerSubGlobalGraph,
1090 // dstDescTuple, visited, baseTuple);
1097 private NTuple<Location> translateToCaller(NTuple<Location> argLocTuple,
1098 NTuple<Location> curNodeLocTuple) {
1100 NTuple<Location> callerLocTuple = new NTuple<Location>();
1102 callerLocTuple.addAll(argLocTuple);
1103 for (int i = 1; i < curNodeLocTuple.size(); i++) {
1104 callerLocTuple.add(curNodeLocTuple.get(i));
1107 return callerLocTuple;
1110 private void recurAddValueFlowsFromCalleeParam(MethodInvokeNode min,
1111 FlowGraph calleeSubGlobalGraph, FlowNode calleeSrcNode, FlowGraph callerSubGlobalGraph,
1112 NTuple<Descriptor> callerSrcTuple, Set<FlowNode> visited, NTuple<Descriptor> baseTuple) {
1114 MethodDescriptor mdCallee = calleeSubGlobalGraph.getMethodDescriptor();
1116 // Set<FlowEdge> edgeSet =
1117 // calleeSubGlobalGraph.getOutEdgeSet(calleeSrcNode);
1118 Set<FlowEdge> edgeSet = calleeSubGlobalGraph.getOutEdgeSetStartingFrom(calleeSrcNode);
1119 for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
1120 FlowEdge flowEdge = (FlowEdge) iterator.next();
1122 NTuple<Descriptor> srcDescTuple = flowEdge.getInitTuple();
1123 NTuple<Descriptor> dstDescTuple = flowEdge.getEndTuple();
1125 FlowNode dstNode = calleeSubGlobalGraph.getFlowNode(dstDescTuple);
1127 if (calleeSubGlobalGraph.isParameter(srcDescTuple)) {
1128 // destination node is started with 'parameter'
1129 // need to translate it in terms of the caller's a node
1131 translateToCaller(min, calleeSubGlobalGraph.getParamIdx(srcDescTuple), srcDescTuple);
1134 if (calleeSubGlobalGraph.isParameter(dstDescTuple)) {
1135 // destination node is started with 'parameter'
1136 // need to translate it in terms of the caller's a node
1138 translateToCaller(min, calleeSubGlobalGraph.getParamIdx(dstDescTuple), dstDescTuple);
1141 callerSubGlobalGraph.addValueFlowEdge(srcDescTuple, dstDescTuple);
1143 if (!visited.contains(dstNode)) {
1144 visited.add(dstNode);
1145 recurAddValueFlowsFromCalleeParam(min, calleeSubGlobalGraph, dstNode, callerSubGlobalGraph,
1146 dstDescTuple, visited, baseTuple);
1153 private NTuple<Descriptor> translateToCaller(MethodInvokeNode min, int paramIdx,
1154 NTuple<Descriptor> srcDescTuple) {
1156 NTuple<Descriptor> callerTuple = new NTuple<Descriptor>();
1158 NTuple<Descriptor> argTuple = mapMethodInvokeNodeToArgIdxMap.get(min).get(paramIdx);
1160 for (int i = 0; i < argTuple.size(); i++) {
1161 callerTuple.add(argTuple.get(i));
1164 for (int i = 1; i < srcDescTuple.size(); i++) {
1165 callerTuple.add(srcDescTuple.get(i));
1171 private NTuple<Descriptor> traslateToCalleeParamTupleToCallerArgTuple(
1172 NTuple<Descriptor> calleeInitTuple, NTuple<Descriptor> callerSrcTuple) {
1174 NTuple<Descriptor> callerInitTuple = new NTuple<Descriptor>();
1176 for (int i = 0; i < callerSrcTuple.size(); i++) {
1177 callerInitTuple.add(callerSrcTuple.get(i));
1180 for (int i = 1; i < calleeInitTuple.size(); i++) {
1181 callerInitTuple.add(calleeInitTuple.get(i));
1184 return callerInitTuple;
1187 public LocationSummary getLocationSummary(Descriptor d) {
1188 if (!mapDescToLocationSummary.containsKey(d)) {
1189 if (d instanceof MethodDescriptor) {
1190 mapDescToLocationSummary.put(d, new MethodSummary((MethodDescriptor) d));
1191 } else if (d instanceof ClassDescriptor) {
1192 mapDescToLocationSummary.put(d, new FieldSummary());
1195 return mapDescToLocationSummary.get(d);
1198 private void generateMethodSummary() {
1200 Set<MethodDescriptor> keySet = md2lattice.keySet();
1201 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1202 MethodDescriptor md = (MethodDescriptor) iterator.next();
1204 System.out.println("\nSSJAVA: generate method summary: " + md);
1206 FlowGraph flowGraph = getFlowGraph(md);
1207 MethodSummary methodSummary = getMethodSummary(md);
1209 // construct a parameter mapping that maps a parameter descriptor to an
1210 // inferred composite
1213 for (int paramIdx = 0; paramIdx < flowGraph.getNumParameters(); paramIdx++) {
1214 FlowNode flowNode = flowGraph.getParamFlowNode(paramIdx);
1215 CompositeLocation inferredCompLoc = flowNode.getCompositeLocation();
1216 // NTuple<Descriptor> descTuple = flowNode.getDescTuple();
1218 // CompositeLocation assignedCompLoc = flowNode.getCompositeLocation();
1219 // CompositeLocation inferredCompLoc;
1220 // if (assignedCompLoc != null) {
1221 // inferredCompLoc = translateCompositeLocation(assignedCompLoc);
1223 // Descriptor locDesc = descTuple.get(0);
1224 // Location loc = new Location(md, locDesc.getSymbol());
1225 // loc.setLocDescriptor(locDesc);
1226 // inferredCompLoc = new CompositeLocation(loc);
1228 System.out.println("-paramIdx=" + paramIdx + " infer=" + inferredCompLoc);
1229 System.out.println("-flowNode inferLoc=" + flowNode.getCompositeLocation());
1231 Descriptor localVarDesc = flowNode.getDescTuple().get(0);
1232 methodSummary.addMapVarNameToInferCompLoc(localVarDesc, inferredCompLoc);
1233 methodSummary.addMapParamIdxToInferLoc(paramIdx, inferredCompLoc);
1240 private boolean hasOrderingRelation(NTuple<Location> locTuple1, NTuple<Location> locTuple2) {
1242 int size = locTuple1.size() >= locTuple2.size() ? locTuple2.size() : locTuple1.size();
1244 for (int idx = 0; idx < size; idx++) {
1245 Location loc1 = locTuple1.get(idx);
1246 Location loc2 = locTuple2.get(idx);
1248 Descriptor desc1 = loc1.getDescriptor();
1249 Descriptor desc2 = loc2.getDescriptor();
1251 if (!desc1.equals(desc2)) {
1252 throw new Error("Fail to compare " + locTuple1 + " and " + locTuple2);
1255 Descriptor locDesc1 = loc1.getLocDescriptor();
1256 Descriptor locDesc2 = loc2.getLocDescriptor();
1258 HierarchyGraph hierarchyGraph = getHierarchyGraph(desc1);
1260 HNode node1 = hierarchyGraph.getHNode(locDesc1);
1261 HNode node2 = hierarchyGraph.getHNode(locDesc2);
1263 System.out.println("---node1=" + node1 + " node2=" + node2);
1264 System.out.println("---hierarchyGraph.getIncomingNodeSet(node2)="
1265 + hierarchyGraph.getIncomingNodeSet(node2));
1267 if (locDesc1.equals(locDesc2)) {
1269 } else if (!hierarchyGraph.getIncomingNodeSet(node2).contains(node1)
1270 && !hierarchyGraph.getIncomingNodeSet(node1).contains(node2)) {
1282 private boolean isHigherThan(NTuple<Location> locTuple1, NTuple<Location> locTuple2) {
1284 int size = locTuple1.size() >= locTuple2.size() ? locTuple2.size() : locTuple1.size();
1286 for (int idx = 0; idx < size; idx++) {
1287 Location loc1 = locTuple1.get(idx);
1288 Location loc2 = locTuple2.get(idx);
1290 Descriptor desc1 = loc1.getDescriptor();
1291 Descriptor desc2 = loc2.getDescriptor();
1293 if (!desc1.equals(desc2)) {
1294 throw new Error("Fail to compare " + locTuple1 + " and " + locTuple2);
1297 Descriptor locDesc1 = loc1.getLocDescriptor();
1298 Descriptor locDesc2 = loc2.getLocDescriptor();
1300 HierarchyGraph hierarchyGraph = getHierarchyGraph(desc1);
1302 HNode node1 = hierarchyGraph.getHNode(locDesc1);
1303 HNode node2 = hierarchyGraph.getHNode(locDesc2);
1305 System.out.println("---node1=" + node1 + " node2=" + node2);
1306 System.out.println("---hierarchyGraph.getIncomingNodeSet(node2)="
1307 + hierarchyGraph.getIncomingNodeSet(node2));
1309 if (locDesc1.equals(locDesc2)) {
1311 } else if (hierarchyGraph.getIncomingNodeSet(node2).contains(node1)) {
1322 private CompositeLocation translateCompositeLocation(CompositeLocation compLoc) {
1323 CompositeLocation newCompLoc = new CompositeLocation();
1325 // System.out.println("compLoc=" + compLoc);
1326 for (int i = 0; i < compLoc.getSize(); i++) {
1327 Location loc = compLoc.get(i);
1328 Descriptor enclosingDescriptor = loc.getDescriptor();
1329 Descriptor locDescriptor = loc.getLocDescriptor();
1331 HNode hnode = getHierarchyGraph(enclosingDescriptor).getHNode(locDescriptor);
1332 // System.out.println("-hnode=" + hnode + " from=" + locDescriptor +
1333 // " enclosingDescriptor="
1334 // + enclosingDescriptor);
1335 // System.out.println("-getLocationSummary(enclosingDescriptor)="
1336 // + getLocationSummary(enclosingDescriptor));
1337 String locName = getLocationSummary(enclosingDescriptor).getLocationName(hnode.getName());
1338 // System.out.println("-locName=" + locName);
1339 Location newLoc = new Location(enclosingDescriptor, locName);
1340 newLoc.setLocDescriptor(locDescriptor);
1341 newCompLoc.addLocation(newLoc);
1347 private void debug_writeLattices() {
1349 Set<Descriptor> keySet = mapDescriptorToSimpleLattice.keySet();
1350 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1351 Descriptor key = (Descriptor) iterator.next();
1352 SSJavaLattice<String> simpleLattice = mapDescriptorToSimpleLattice.get(key);
1353 // HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(key);
1354 HierarchyGraph scHierarchyGraph = getSkeletonCombinationHierarchyGraph(key);
1355 if (key instanceof ClassDescriptor) {
1356 writeInferredLatticeDotFile((ClassDescriptor) key, scHierarchyGraph, simpleLattice,
1358 } else if (key instanceof MethodDescriptor) {
1359 MethodDescriptor md = (MethodDescriptor) key;
1360 writeInferredLatticeDotFile(md.getClassDesc(), md, scHierarchyGraph, simpleLattice,
1364 LocationSummary ls = getLocationSummary(key);
1365 System.out.println("####LOC SUMMARY=" + key + "\n" + ls.getMapHNodeNameToLocationName());
1368 Set<ClassDescriptor> cdKeySet = cd2lattice.keySet();
1369 for (Iterator iterator = cdKeySet.iterator(); iterator.hasNext();) {
1370 ClassDescriptor cd = (ClassDescriptor) iterator.next();
1371 writeInferredLatticeDotFile((ClassDescriptor) cd, getSkeletonCombinationHierarchyGraph(cd),
1372 cd2lattice.get(cd), "");
1375 Set<MethodDescriptor> mdKeySet = md2lattice.keySet();
1376 for (Iterator iterator = mdKeySet.iterator(); iterator.hasNext();) {
1377 MethodDescriptor md = (MethodDescriptor) iterator.next();
1378 writeInferredLatticeDotFile(md.getClassDesc(), md, getSkeletonCombinationHierarchyGraph(md),
1379 md2lattice.get(md), "");
1384 private void buildLattice() {
1386 BuildLattice buildLattice = new BuildLattice(this);
1388 Set<Descriptor> keySet = mapDescriptorToCombineSkeletonHierarchyGraph.keySet();
1389 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1390 Descriptor desc = (Descriptor) iterator.next();
1392 SSJavaLattice<String> simpleLattice = buildLattice.buildLattice(desc);
1394 addMapDescToSimpleLattice(desc, simpleLattice);
1396 HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
1397 System.out.println("\n## insertIntermediateNodesToStraightLine:"
1398 + simpleHierarchyGraph.getName());
1399 SSJavaLattice<String> lattice =
1400 buildLattice.insertIntermediateNodesToStraightLine(desc, simpleLattice);
1401 lattice.removeRedundantEdges();
1403 if (desc instanceof ClassDescriptor) {
1405 cd2lattice.put((ClassDescriptor) desc, lattice);
1406 // ssjava.writeLatticeDotFile((ClassDescriptor) desc, null, lattice);
1407 } else if (desc instanceof MethodDescriptor) {
1409 md2lattice.put((MethodDescriptor) desc, lattice);
1410 MethodDescriptor md = (MethodDescriptor) desc;
1411 ClassDescriptor cd = md.getClassDesc();
1412 // ssjava.writeLatticeDotFile(cd, md, lattice);
1415 // System.out.println("\nSSJAVA: Insering Combination Nodes:" + desc);
1416 // HierarchyGraph skeletonGraph = getSkeletonHierarchyGraph(desc);
1417 // HierarchyGraph skeletonGraphWithCombinationNode =
1418 // skeletonGraph.clone();
1419 // skeletonGraphWithCombinationNode.setName(desc + "_SC");
1421 // HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
1422 // System.out.println("Identifying Combination Nodes:");
1423 // skeletonGraphWithCombinationNode.insertCombinationNodesToGraph(simpleHierarchyGraph);
1424 // skeletonGraphWithCombinationNode.simplifySkeletonCombinationHierarchyGraph();
1425 // mapDescriptorToCombineSkeletonHierarchyGraph.put(desc,
1426 // skeletonGraphWithCombinationNode);
1431 public void addMapDescToSimpleLattice(Descriptor desc, SSJavaLattice<String> lattice) {
1432 mapDescriptorToSimpleLattice.put(desc, lattice);
1435 public SSJavaLattice<String> getSimpleLattice(Descriptor desc) {
1436 return mapDescriptorToSimpleLattice.get(desc);
1439 private void simplifyHierarchyGraph() {
1440 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1441 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1442 Descriptor desc = (Descriptor) iterator.next();
1443 HierarchyGraph simpleHierarchyGraph = getHierarchyGraph(desc).clone();
1444 simpleHierarchyGraph.setName(desc + "_SIMPLE");
1445 simpleHierarchyGraph.removeRedundantEdges();
1446 // simpleHierarchyGraph.simplifyHierarchyGraph();
1447 mapDescriptorToSimpleHierarchyGraph.put(desc, simpleHierarchyGraph);
1451 private void insertCombinationNodes() {
1452 Set<Descriptor> keySet = mapDescriptorToSkeletonHierarchyGraph.keySet();
1453 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1454 Descriptor desc = (Descriptor) iterator.next();
1455 System.out.println("\nSSJAVA: Insering Combination Nodes:" + desc);
1456 HierarchyGraph skeletonGraph = getSkeletonHierarchyGraph(desc);
1457 HierarchyGraph skeletonGraphWithCombinationNode = skeletonGraph.clone();
1458 skeletonGraphWithCombinationNode.setName(desc + "_SC");
1460 HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
1461 System.out.println("Identifying Combination Nodes:");
1462 skeletonGraphWithCombinationNode.insertCombinationNodesToGraph(simpleHierarchyGraph);
1463 skeletonGraphWithCombinationNode.simplifySkeletonCombinationHierarchyGraph();
1464 mapDescriptorToCombineSkeletonHierarchyGraph.put(desc, skeletonGraphWithCombinationNode);
1468 private void constructSkeletonHierarchyGraph() {
1469 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1470 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1471 Descriptor desc = (Descriptor) iterator.next();
1472 HierarchyGraph simpleGraph = getSimpleHierarchyGraph(desc);
1473 HierarchyGraph skeletonGraph = simpleGraph.generateSkeletonGraph();
1474 skeletonGraph.setMapDescToHNode(simpleGraph.getMapDescToHNode());
1475 skeletonGraph.setMapHNodeToDescSet(simpleGraph.getMapHNodeToDescSet());
1476 skeletonGraph.simplifyHierarchyGraph();
1477 // skeletonGraph.combineRedundantNodes(false);
1478 // skeletonGraph.removeRedundantEdges();
1479 mapDescriptorToSkeletonHierarchyGraph.put(desc, skeletonGraph);
1483 private void debug_writeHierarchyDotFiles() {
1485 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1486 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1487 Descriptor desc = (Descriptor) iterator.next();
1488 getHierarchyGraph(desc).writeGraph();
1493 private void debug_writeSimpleHierarchyDotFiles() {
1495 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1496 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1497 Descriptor desc = (Descriptor) iterator.next();
1498 getHierarchyGraph(desc).writeGraph();
1499 getSimpleHierarchyGraph(desc).writeGraph();
1504 private void debug_writeSkeletonHierarchyDotFiles() {
1506 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1507 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1508 Descriptor desc = (Descriptor) iterator.next();
1509 getSkeletonHierarchyGraph(desc).writeGraph();
1514 private void debug_writeSkeletonCombinationHierarchyDotFiles() {
1516 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1517 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1518 Descriptor desc = (Descriptor) iterator.next();
1519 getSkeletonCombinationHierarchyGraph(desc).writeGraph();
1524 public HierarchyGraph getSimpleHierarchyGraph(Descriptor d) {
1525 return mapDescriptorToSimpleHierarchyGraph.get(d);
1528 private HierarchyGraph getSkeletonHierarchyGraph(Descriptor d) {
1529 if (!mapDescriptorToSkeletonHierarchyGraph.containsKey(d)) {
1530 mapDescriptorToSkeletonHierarchyGraph.put(d, new HierarchyGraph(d));
1532 return mapDescriptorToSkeletonHierarchyGraph.get(d);
1535 public HierarchyGraph getSkeletonCombinationHierarchyGraph(Descriptor d) {
1536 if (!mapDescriptorToCombineSkeletonHierarchyGraph.containsKey(d)) {
1537 mapDescriptorToCombineSkeletonHierarchyGraph.put(d, new HierarchyGraph(d));
1539 return mapDescriptorToCombineSkeletonHierarchyGraph.get(d);
1542 private void constructHierarchyGraph() {
1544 // do fixed-point analysis
1547 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
1549 // Collections.sort(descriptorListToAnalyze, new
1550 // Comparator<MethodDescriptor>() {
1551 // public int compare(MethodDescriptor o1, MethodDescriptor o2) {
1552 // return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
1556 // current descriptors to visit in fixed-point interprocedural analysis,
1557 // prioritized by dependency in the call graph
1558 methodDescriptorsToVisitStack.clear();
1560 Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
1561 methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
1563 while (!descriptorListToAnalyze.isEmpty()) {
1564 MethodDescriptor md = descriptorListToAnalyze.removeFirst();
1565 methodDescriptorsToVisitStack.add(md);
1568 // analyze scheduled methods until there are no more to visit
1569 while (!methodDescriptorsToVisitStack.isEmpty()) {
1570 // start to analyze leaf node
1571 MethodDescriptor md = methodDescriptorsToVisitStack.pop();
1573 HierarchyGraph hierarchyGraph = new HierarchyGraph(md);
1574 // MethodSummary methodSummary = new MethodSummary(md);
1576 // MethodLocationInfo methodInfo = new MethodLocationInfo(md);
1577 // curMethodInfo = methodInfo;
1579 System.out.println();
1580 System.out.println("SSJAVA: Construcing the hierarchy graph from " + md);
1582 constructHierarchyGraph(md, hierarchyGraph);
1584 HierarchyGraph prevHierarchyGraph = getHierarchyGraph(md);
1585 // MethodSummary prevMethodSummary = getMethodSummary(md);
1587 if (!hierarchyGraph.equals(prevHierarchyGraph)) {
1589 mapDescriptorToHierarchyGraph.put(md, hierarchyGraph);
1590 // mapDescToLocationSummary.put(md, methodSummary);
1592 // results for callee changed, so enqueue dependents caller for
1594 Iterator<MethodDescriptor> depsItr = ssjava.getDependents(md).iterator();
1595 while (depsItr.hasNext()) {
1596 MethodDescriptor methodNext = depsItr.next();
1597 if (!methodDescriptorsToVisitStack.contains(methodNext)
1598 && methodDescriptorToVistSet.contains(methodNext)) {
1599 methodDescriptorsToVisitStack.add(methodNext);
1609 private HierarchyGraph getHierarchyGraph(Descriptor d) {
1610 if (!mapDescriptorToHierarchyGraph.containsKey(d)) {
1611 mapDescriptorToHierarchyGraph.put(d, new HierarchyGraph(d));
1613 return mapDescriptorToHierarchyGraph.get(d);
1616 private void constructHierarchyGraph(MethodDescriptor md, HierarchyGraph methodGraph) {
1618 // visit each node of method flow graph
1619 FlowGraph fg = getFlowGraph(md);
1620 Set<FlowNode> nodeSet = fg.getNodeSet();
1622 Set<Descriptor> paramDescSet = fg.getMapParamDescToIdx().keySet();
1623 for (Iterator iterator = paramDescSet.iterator(); iterator.hasNext();) {
1624 Descriptor desc = (Descriptor) iterator.next();
1625 methodGraph.getHNode(desc).setSkeleton(true);
1628 // for the method lattice, we need to look at the first element of
1629 // NTuple<Descriptor>
1630 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1631 FlowNode srcNode = (FlowNode) iterator.next();
1633 Set<FlowEdge> outEdgeSet = fg.getOutEdgeSet(srcNode);
1634 for (Iterator iterator2 = outEdgeSet.iterator(); iterator2.hasNext();) {
1635 FlowEdge outEdge = (FlowEdge) iterator2.next();
1636 FlowNode dstNode = outEdge.getDst();
1638 NTuple<Descriptor> srcNodeTuple = srcNode.getDescTuple();
1639 NTuple<Descriptor> dstNodeTuple = dstNode.getDescTuple();
1641 if (outEdge.getInitTuple().equals(srcNodeTuple)
1642 && outEdge.getEndTuple().equals(dstNodeTuple)) {
1644 NTuple<Descriptor> srcCurTuple = srcNode.getCurrentDescTuple();
1645 NTuple<Descriptor> dstCurTuple = dstNode.getCurrentDescTuple();
1647 if ((srcCurTuple.size() > 1 && dstCurTuple.size() > 1)
1648 && srcCurTuple.get(0).equals(dstCurTuple.get(0))) {
1650 // value flows between fields
1651 Descriptor desc = srcCurTuple.get(0);
1652 ClassDescriptor classDesc;
1654 if (desc.equals(GLOBALDESC)) {
1655 classDesc = md.getClassDesc();
1657 VarDescriptor varDesc = (VarDescriptor) srcCurTuple.get(0);
1658 classDesc = varDesc.getType().getClassDesc();
1660 extractFlowsBetweenFields(classDesc, srcNode, dstNode, 1);
1663 // value flow between local var - local var or local var - field
1665 Descriptor srcDesc = srcCurTuple.get(0);
1666 Descriptor dstDesc = dstCurTuple.get(0);
1668 methodGraph.addEdge(srcDesc, dstDesc);
1670 if (fg.isParamDesc(srcDesc)) {
1671 methodGraph.setParamHNode(srcDesc);
1673 if (fg.isParamDesc(dstDesc)) {
1674 methodGraph.setParamHNode(dstDesc);
1685 private MethodSummary getMethodSummary(MethodDescriptor md) {
1686 if (!mapDescToLocationSummary.containsKey(md)) {
1687 mapDescToLocationSummary.put(md, new MethodSummary(md));
1689 return (MethodSummary) mapDescToLocationSummary.get(md);
1692 private void addMapClassDefinitionToLineNum(ClassDescriptor cd, String strLine, int lineNum) {
1694 String classSymbol = cd.getSymbol();
1695 int idx = classSymbol.lastIndexOf("$");
1697 classSymbol = classSymbol.substring(idx + 1);
1700 String pattern = "class " + classSymbol + " ";
1701 if (strLine.indexOf(pattern) != -1) {
1702 mapDescToDefinitionLine.put(cd, lineNum);
1706 private void addMapMethodDefinitionToLineNum(Set<MethodDescriptor> methodSet, String strLine,
1708 for (Iterator iterator = methodSet.iterator(); iterator.hasNext();) {
1709 MethodDescriptor md = (MethodDescriptor) iterator.next();
1710 String pattern = md.getMethodDeclaration();
1711 if (strLine.indexOf(pattern) != -1) {
1712 mapDescToDefinitionLine.put(md, lineNum);
1713 methodSet.remove(md);
1720 private void readOriginalSourceFiles() {
1722 SymbolTable classtable = state.getClassSymbolTable();
1724 Set<ClassDescriptor> classDescSet = new HashSet<ClassDescriptor>();
1725 classDescSet.addAll(classtable.getValueSet());
1728 // inefficient implement. it may re-visit the same file if the file
1729 // contains more than one class definitions.
1730 for (Iterator iterator = classDescSet.iterator(); iterator.hasNext();) {
1731 ClassDescriptor cd = (ClassDescriptor) iterator.next();
1733 Set<MethodDescriptor> methodSet = new HashSet<MethodDescriptor>();
1734 methodSet.addAll(cd.getMethodTable().getValueSet());
1736 String sourceFileName = cd.getSourceFileName();
1737 Vector<String> lineVec = new Vector<String>();
1739 mapFileNameToLineVector.put(sourceFileName, lineVec);
1741 BufferedReader in = new BufferedReader(new FileReader(sourceFileName));
1744 lineVec.add(""); // the index is started from 1.
1745 while ((strLine = in.readLine()) != null) {
1746 lineVec.add(lineNum, strLine);
1747 addMapClassDefinitionToLineNum(cd, strLine, lineNum);
1748 addMapMethodDefinitionToLineNum(methodSet, strLine, lineNum);
1754 } catch (IOException e) {
1755 e.printStackTrace();
1760 private String generateLatticeDefinition(Descriptor desc) {
1762 Set<String> sharedLocSet = new HashSet<String>();
1764 SSJavaLattice<String> lattice = getLattice(desc);
1765 String rtr = "@LATTICE(\"";
1767 Map<String, Set<String>> map = lattice.getTable();
1768 Set<String> keySet = map.keySet();
1769 boolean first = true;
1770 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1771 String key = (String) iterator.next();
1772 if (!key.equals(lattice.getTopItem())) {
1773 Set<String> connectedSet = map.get(key);
1775 if (connectedSet.size() == 1) {
1776 if (connectedSet.iterator().next().equals(lattice.getBottomItem())) {
1784 if (lattice.isSharedLoc(key)) {
1785 rtr += "," + key + "*";
1790 for (Iterator iterator2 = connectedSet.iterator(); iterator2.hasNext();) {
1791 String loc = (String) iterator2.next();
1792 if (!loc.equals(lattice.getBottomItem())) {
1799 rtr += loc + "<" + key;
1800 if (lattice.isSharedLoc(key) && (!sharedLocSet.contains(key))) {
1801 rtr += "," + key + "*";
1802 sharedLocSet.add(key);
1804 if (lattice.isSharedLoc(loc) && (!sharedLocSet.contains(loc))) {
1805 rtr += "," + loc + "*";
1806 sharedLocSet.add(loc);
1816 if (desc instanceof MethodDescriptor) {
1817 TypeDescriptor returnType = ((MethodDescriptor) desc).getReturnType();
1819 MethodSummary methodSummary = getMethodSummary((MethodDescriptor) desc);
1821 if (returnType != null && (!returnType.isVoid())) {
1823 "\n@RETURNLOC(\"" + generateLocationAnnoatation(methodSummary.getRETURNLoc()) + "\")";
1826 rtr += "\n@THISLOC(\"this\")";
1827 rtr += "\n@GLOBALLOC(\"GLOBALLOC\")";
1829 CompositeLocation pcLoc = methodSummary.getPCLoc();
1830 if ((pcLoc != null) && (!pcLoc.get(0).isTop())) {
1831 rtr += "\n@PCLOC(\"" + generateLocationAnnoatation(pcLoc) + "\")";
1839 private void generateAnnoatedCode() {
1841 readOriginalSourceFiles();
1844 while (!toAnalyzeIsEmpty()) {
1845 ClassDescriptor cd = toAnalyzeNext();
1847 setupToAnalazeMethod(cd);
1849 LocationInfo locInfo = mapClassToLocationInfo.get(cd);
1850 String sourceFileName = cd.getSourceFileName();
1852 if (cd.isInterface()) {
1856 int classDefLine = mapDescToDefinitionLine.get(cd);
1857 Vector<String> sourceVec = mapFileNameToLineVector.get(sourceFileName);
1859 if (locInfo == null) {
1860 locInfo = getLocationInfo(cd);
1863 for (Iterator iter = cd.getFields(); iter.hasNext();) {
1864 FieldDescriptor fieldDesc = (FieldDescriptor) iter.next();
1865 if (!(fieldDesc.isStatic() && fieldDesc.isFinal())) {
1866 String locIdentifier = locInfo.getFieldInferLocation(fieldDesc).getLocIdentifier();
1867 if (!getLattice(cd).getElementSet().contains(locIdentifier)) {
1868 getLattice(cd).put(locIdentifier);
1873 String fieldLatticeDefStr = generateLatticeDefinition(cd);
1874 String annoatedSrc = fieldLatticeDefStr + newline + sourceVec.get(classDefLine);
1875 sourceVec.set(classDefLine, annoatedSrc);
1877 // generate annotations for field declarations
1878 LocationSummary fieldLocSummary = getLocationSummary(cd);
1879 // Map<Descriptor, CompositeLocation> inferLocMap = fieldLocInfo.getMapDescToInferLocation();
1880 Map<String, String> mapFieldNameToLocName = fieldLocSummary.getMapHNodeNameToLocationName();
1882 for (Iterator iter = cd.getFields(); iter.hasNext();) {
1883 FieldDescriptor fd = (FieldDescriptor) iter.next();
1885 String locAnnotationStr;
1886 // CompositeLocation inferLoc = inferLocMap.get(fd);
1887 String locName = mapFieldNameToLocName.get(fd.getSymbol());
1889 if (locName != null) {
1890 // infer loc is null if the corresponding field is static and final
1891 // locAnnotationStr = "@LOC(\"" + generateLocationAnnoatation(inferLoc) + "\")";
1892 locAnnotationStr = "@LOC(\"" + locName + "\")";
1893 int fdLineNum = fd.getLineNum();
1894 String orgFieldDeclarationStr = sourceVec.get(fdLineNum);
1895 String fieldDeclaration = fd.toString();
1896 fieldDeclaration = fieldDeclaration.substring(0, fieldDeclaration.length() - 1);
1897 String annoatedStr = locAnnotationStr + " " + orgFieldDeclarationStr;
1898 sourceVec.set(fdLineNum, annoatedStr);
1903 while (!toAnalyzeMethodIsEmpty()) {
1904 MethodDescriptor md = toAnalyzeMethodNext();
1906 if (!ssjava.needTobeAnnotated(md)) {
1910 SSJavaLattice<String> methodLattice = md2lattice.get(md);
1911 if (methodLattice != null) {
1913 int methodDefLine = md.getLineNum();
1915 // MethodLocationInfo methodLocInfo = getMethodLocationInfo(md);
1916 // Map<Descriptor, CompositeLocation> methodInferLocMap =
1917 // methodLocInfo.getMapDescToInferLocation();
1919 MethodSummary methodSummary = getMethodSummary(md);
1921 Map<Descriptor, CompositeLocation> mapVarDescToInferLoc =
1922 methodSummary.getMapVarDescToInferCompositeLocation();
1923 System.out.println("-----md=" + md);
1924 System.out.println("-----mapVarDescToInferLoc=" + mapVarDescToInferLoc);
1926 Set<Descriptor> localVarDescSet = mapVarDescToInferLoc.keySet();
1928 Set<String> localLocElementSet = methodLattice.getElementSet();
1930 for (Iterator iterator = localVarDescSet.iterator(); iterator.hasNext();) {
1931 Descriptor localVarDesc = (Descriptor) iterator.next();
1932 System.out.println("-------localVarDesc=" + localVarDesc);
1933 CompositeLocation inferLoc = mapVarDescToInferLoc.get(localVarDesc);
1935 String localLocIdentifier = inferLoc.get(0).getLocIdentifier();
1936 if (!localLocElementSet.contains(localLocIdentifier)) {
1937 methodLattice.put(localLocIdentifier);
1940 String locAnnotationStr = "@LOC(\"" + generateLocationAnnoatation(inferLoc) + "\")";
1942 if (!isParameter(md, localVarDesc)) {
1943 if (mapDescToDefinitionLine.containsKey(localVarDesc)) {
1944 int varLineNum = mapDescToDefinitionLine.get(localVarDesc);
1945 String orgSourceLine = sourceVec.get(varLineNum);
1947 orgSourceLine.indexOf(generateVarDeclaration((VarDescriptor) localVarDesc));
1949 String annoatedStr =
1950 orgSourceLine.substring(0, idx) + locAnnotationStr + " "
1951 + orgSourceLine.substring(idx);
1952 sourceVec.set(varLineNum, annoatedStr);
1955 String methodDefStr = sourceVec.get(methodDefLine);
1958 getParamLocation(methodDefStr,
1959 generateVarDeclaration((VarDescriptor) localVarDesc));
1963 String annoatedStr =
1964 methodDefStr.substring(0, idx) + locAnnotationStr + " "
1965 + methodDefStr.substring(idx);
1966 sourceVec.set(methodDefLine, annoatedStr);
1971 // check if the lattice has to have the location type for the this
1974 // boolean needToAddthisRef = hasThisReference(md);
1975 if (localLocElementSet.contains("this")) {
1976 methodLattice.put("this");
1979 String methodLatticeDefStr = generateLatticeDefinition(md);
1980 String annoatedStr = methodLatticeDefStr + newline + sourceVec.get(methodDefLine);
1981 sourceVec.set(methodDefLine, annoatedStr);
1991 private boolean hasThisReference(MethodDescriptor md) {
1993 FlowGraph fg = getFlowGraph(md);
1994 Set<FlowNode> nodeSet = fg.getNodeSet();
1995 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1996 FlowNode flowNode = (FlowNode) iterator.next();
1997 if (flowNode.getDescTuple().get(0).equals(md.getThis())) {
2005 private int getParamLocation(String methodStr, String paramStr) {
2007 String pattern = paramStr + ",";
2009 int idx = methodStr.indexOf(pattern);
2013 pattern = paramStr + ")";
2014 return methodStr.indexOf(pattern);
2019 private String generateVarDeclaration(VarDescriptor varDesc) {
2021 TypeDescriptor td = varDesc.getType();
2022 String rtr = td.toString();
2024 for (int i = 0; i < td.getArrayCount(); i++) {
2028 rtr += " " + varDesc.getName();
2033 private String generateLocationAnnoatation(CompositeLocation loc) {
2034 System.out.println("loc=" + loc);
2037 Location methodLoc = loc.get(0);
2038 rtr += methodLoc.getLocIdentifier();
2040 for (int i = 1; i < loc.getSize(); i++) {
2041 Location element = loc.get(i);
2042 rtr += "," + element.getDescriptor().getSymbol() + "." + element.getLocIdentifier();
2048 private boolean isParameter(MethodDescriptor md, Descriptor localVarDesc) {
2049 return getFlowGraph(md).isParamDesc(localVarDesc);
2052 private String extractFileName(String fileName) {
2053 int idx = fileName.lastIndexOf("/");
2057 return fileName.substring(idx + 1);
2062 private void codeGen() {
2064 Set<String> originalFileNameSet = mapFileNameToLineVector.keySet();
2065 for (Iterator iterator = originalFileNameSet.iterator(); iterator.hasNext();) {
2066 String orgFileName = (String) iterator.next();
2067 String outputFileName = extractFileName(orgFileName);
2069 Vector<String> sourceVec = mapFileNameToLineVector.get(orgFileName);
2073 FileWriter fileWriter = new FileWriter("./infer/" + outputFileName);
2074 BufferedWriter out = new BufferedWriter(fileWriter);
2076 for (int i = 0; i < sourceVec.size(); i++) {
2077 out.write(sourceVec.get(i));
2081 } catch (IOException e) {
2082 e.printStackTrace();
2089 private void checkLattices() {
2091 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
2093 // current descriptors to visit in fixed-point interprocedural analysis,
2095 // dependency in the call graph
2096 methodDescriptorsToVisitStack.clear();
2098 // descriptorListToAnalyze.removeFirst();
2100 Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
2101 methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
2103 while (!descriptorListToAnalyze.isEmpty()) {
2104 MethodDescriptor md = descriptorListToAnalyze.removeFirst();
2105 checkLatticesOfVirtualMethods(md);
2110 private void debug_writeLatticeDotFile() {
2111 // generate lattice dot file
2115 while (!toAnalyzeIsEmpty()) {
2116 ClassDescriptor cd = toAnalyzeNext();
2118 setupToAnalazeMethod(cd);
2120 SSJavaLattice<String> classLattice = cd2lattice.get(cd);
2121 if (classLattice != null) {
2122 ssjava.writeLatticeDotFile(cd, null, classLattice);
2123 debug_printDescriptorToLocNameMapping(cd);
2126 while (!toAnalyzeMethodIsEmpty()) {
2127 MethodDescriptor md = toAnalyzeMethodNext();
2128 SSJavaLattice<String> methodLattice = md2lattice.get(md);
2129 if (methodLattice != null) {
2130 ssjava.writeLatticeDotFile(cd, md, methodLattice);
2131 debug_printDescriptorToLocNameMapping(md);
2138 private void debug_printDescriptorToLocNameMapping(Descriptor desc) {
2140 LocationInfo info = getLocationInfo(desc);
2141 System.out.println("## " + desc + " ##");
2142 System.out.println(info.getMapDescToInferLocation());
2143 LocationInfo locInfo = getLocationInfo(desc);
2144 System.out.println("mapping=" + locInfo.getMapLocSymbolToDescSet());
2145 System.out.println("###################");
2149 private void inferLattices() {
2152 private void calculateExtraLocations() {
2153 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
2154 for (Iterator iterator = descriptorListToAnalyze.iterator(); iterator.hasNext();) {
2155 MethodDescriptor md = (MethodDescriptor) iterator.next();
2156 if (!ssjava.getMethodContainingSSJavaLoop().equals(md)) {
2157 calculateExtraLocations(md);
2162 private void checkLatticesOfVirtualMethods(MethodDescriptor md) {
2164 if (!md.isStatic()) {
2165 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
2166 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
2168 for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
2169 MethodDescriptor mdCallee = (MethodDescriptor) iterator.next();
2170 if (!md.equals(mdCallee)) {
2171 checkConsistency(md, mdCallee);
2179 private void checkConsistency(MethodDescriptor md1, MethodDescriptor md2) {
2181 // check that two lattice have the same relations between parameters(+PC
2182 // LOC, GLOBAL_LOC RETURN LOC)
2184 List<CompositeLocation> list1 = new ArrayList<CompositeLocation>();
2185 List<CompositeLocation> list2 = new ArrayList<CompositeLocation>();
2187 MethodLocationInfo locInfo1 = getMethodLocationInfo(md1);
2188 MethodLocationInfo locInfo2 = getMethodLocationInfo(md2);
2190 Map<Integer, CompositeLocation> paramMap1 = locInfo1.getMapParamIdxToInferLoc();
2191 Map<Integer, CompositeLocation> paramMap2 = locInfo2.getMapParamIdxToInferLoc();
2193 int numParam = locInfo1.getMapParamIdxToInferLoc().keySet().size();
2195 // add location types of paramters
2196 for (int idx = 0; idx < numParam; idx++) {
2197 list1.add(paramMap1.get(Integer.valueOf(idx)));
2198 list2.add(paramMap2.get(Integer.valueOf(idx)));
2201 // add program counter location
2202 list1.add(locInfo1.getPCLoc());
2203 list2.add(locInfo2.getPCLoc());
2205 if (!md1.getReturnType().isVoid()) {
2206 // add return value location
2207 CompositeLocation rtrLoc1 = getMethodLocationInfo(md1).getReturnLoc();
2208 CompositeLocation rtrLoc2 = getMethodLocationInfo(md2).getReturnLoc();
2213 // add global location type
2214 if (md1.isStatic()) {
2215 CompositeLocation globalLoc1 =
2216 new CompositeLocation(new Location(md1, locInfo1.getGlobalLocName()));
2217 CompositeLocation globalLoc2 =
2218 new CompositeLocation(new Location(md2, locInfo2.getGlobalLocName()));
2219 list1.add(globalLoc1);
2220 list2.add(globalLoc2);
2223 for (int i = 0; i < list1.size(); i++) {
2224 CompositeLocation locA1 = list1.get(i);
2225 CompositeLocation locA2 = list2.get(i);
2226 for (int k = 0; k < list1.size(); k++) {
2228 CompositeLocation locB1 = list1.get(k);
2229 CompositeLocation locB2 = list2.get(k);
2230 boolean r1 = isGreaterThan(getLattice(md1), locA1, locB1);
2232 boolean r2 = isGreaterThan(getLattice(md1), locA2, locB2);
2235 throw new Error("The method " + md1 + " is not consistent with the method " + md2
2236 + ".:: They have a different ordering relation between locations (" + locA1 + ","
2237 + locB1 + ") and (" + locA2 + "," + locB2 + ").");
2245 private String getSymbol(int idx, FlowNode node) {
2246 Descriptor desc = node.getDescTuple().get(idx);
2247 return desc.getSymbol();
2250 private Descriptor getDescriptor(int idx, FlowNode node) {
2251 Descriptor desc = node.getDescTuple().get(idx);
2255 private void calcualtePCLOC(MethodDescriptor md) {
2257 System.out.println("#calcualtePCLOC");
2258 MethodSummary methodSummary = getMethodSummary(md);
2259 FlowGraph fg = getFlowGraph(md);
2260 Map<Integer, CompositeLocation> mapParamToLoc = methodSummary.getMapParamIdxToInferLoc();
2262 // calculate the initial program counter location
2263 // PC location is higher than location types of parameters which has incoming flows.
2265 Set<NTuple<Location>> paramLocTupleHavingInFlowSet = new HashSet<NTuple<Location>>();
2267 int numParams = fg.getNumParameters();
2268 for (int i = 0; i < numParams; i++) {
2269 FlowNode paramFlowNode = fg.getParamFlowNode(i);
2270 Descriptor prefix = paramFlowNode.getDescTuple().get(0);
2272 if (fg.getIncomingNodeSetByPrefix(prefix).size() > 0) {
2273 // parameter has in-value flows
2274 NTuple<Descriptor> paramDescTuple = paramFlowNode.getCurrentDescTuple();
2275 NTuple<Location> paramLocTuple = translateToLocTuple(md, paramDescTuple);
2276 paramLocTupleHavingInFlowSet.add(paramLocTuple);
2280 System.out.println("paramLocTupleHavingInFlowSet=" + paramLocTupleHavingInFlowSet);
2282 if (!coversAllParamters(md, fg, paramLocTupleHavingInFlowSet)) {
2283 // if (numParamsWithIncomingValue > 0 && numParamsWithIncomingValue != fg.getNumParameters())
2286 // Here, generates a location in the method lattice that is higher than the
2287 // paramLocTupleHavingInFlowSet
2288 NTuple<Location> pcLocTuple =
2289 generateLocTupleRelativeTo(md, paramLocTupleHavingInFlowSet, PCLOC);
2291 int pcLocTupleIdx = pcLocTuple.size() - 1;
2292 Location pcLoc = pcLocTuple.get(pcLocTupleIdx);
2293 Descriptor pcDesc = pcLoc.getLocDescriptor();
2294 Descriptor enclosingDesc = pcLocTuple.get(pcLocTupleIdx).getDescriptor();
2296 HierarchyGraph hierarchyGraph = getHierarchyGraph(enclosingDesc);
2297 HNode pcNode = hierarchyGraph.getHNode(pcDesc);
2298 pcNode.setSkeleton(true);
2300 for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
2301 NTuple<Location> paramLocTuple = (NTuple<Location>) iterator.next();
2302 if (paramLocTuple.size() > pcLocTupleIdx) {
2303 Descriptor lowerDesc = paramLocTuple.get(pcLocTupleIdx).getLocDescriptor();
2304 hierarchyGraph.addEdge(pcDesc, lowerDesc);
2308 System.out.println("pcLoc=" + pcLoc);
2310 methodSummary.setPCLoc(new CompositeLocation(pcLocTuple));
2314 private boolean coversAllParamters(MethodDescriptor md, FlowGraph fg,
2315 Set<NTuple<Location>> paramLocTupleHavingInFlowSet) {
2317 int numParam = fg.getNumParameters();
2318 int size = paramLocTupleHavingInFlowSet.size();
2320 if (!md.isStatic()) {
2322 // if the method is not static && there is a parameter composite location &&
2323 // it is started with 'this',
2324 // paramLocTupleHavingInFlowSet need to have 'this' parameter.
2326 FlowNode thisParamNode = fg.getParamFlowNode(0);
2327 NTuple<Location> thisParamLocTuple =
2328 translateToLocTuple(md, thisParamNode.getCurrentDescTuple());
2330 if (!paramLocTupleHavingInFlowSet.contains(thisParamLocTuple)) {
2332 for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
2333 NTuple<Location> paramTuple = (NTuple<Location>) iterator.next();
2334 if (paramTuple.size() > 1 && paramTuple.get(0).getLocDescriptor().equals(md.getThis())) {
2335 // paramLocTupleHavingInFlowSet.add(thisParamLocTuple);
2344 if (size == numParam) {
2352 private void calculateRETURNLOC(MethodDescriptor md) {
2354 System.out.println("#calculateRETURNLOC");
2355 // calculate a return location:
2356 // the return location type is lower than all parameters and the location of return values
2358 MethodSummary methodSummary = getMethodSummary(md);
2360 FlowGraph fg = getFlowGraph(md);
2362 Map<Integer, CompositeLocation> mapParamToLoc = methodSummary.getMapParamIdxToInferLoc();
2363 Set<Integer> paramIdxSet = mapParamToLoc.keySet();
2365 if (!md.getReturnType().isVoid()) {
2366 // first, generate the set of return value location types that starts
2367 // with 'this' reference
2369 Set<NTuple<Location>> inferFieldReturnLocSet = new HashSet<NTuple<Location>>();
2371 Set<FlowNode> paramFlowNodeFlowingToReturnValueSet = getParamNodeFlowingToReturnValue(md);
2372 System.out.println("paramFlowNodeFlowingToReturnValueSet="
2373 + paramFlowNodeFlowingToReturnValueSet);
2375 Set<NTuple<Location>> locFlowingToReturnValueSet = new HashSet<NTuple<Location>>();
2376 for (Iterator iterator = paramFlowNodeFlowingToReturnValueSet.iterator(); iterator.hasNext();) {
2377 FlowNode fn = (FlowNode) iterator.next();
2379 NTuple<Descriptor> paramDescTuple = fn.getCurrentDescTuple();
2380 NTuple<Location> paramLocTuple = translateToLocTuple(md, paramDescTuple);
2382 locFlowingToReturnValueSet.add(paramLocTuple);
2385 Set<FlowNode> returnNodeSet = fg.getReturnNodeSet();
2386 for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2387 FlowNode returnNode = (FlowNode) iterator.next();
2388 NTuple<Descriptor> returnDescTuple = returnNode.getCurrentDescTuple();
2389 NTuple<Location> returnLocTuple = translateToLocTuple(md, returnDescTuple);
2390 locFlowingToReturnValueSet.add(returnLocTuple);
2392 System.out.println("locFlowingToReturnValueSet=" + locFlowingToReturnValueSet);
2394 // Here, generates a return location in the method lattice that is lower than the
2395 // locFlowingToReturnValueSet
2396 NTuple<Location> returnLocTuple =
2397 generateLocTupleRelativeTo(md, locFlowingToReturnValueSet, RLOC);
2399 System.out.println("returnLocTuple=" + returnLocTuple);
2401 int returnLocTupleIdx = returnLocTuple.size() - 1;
2402 Location returnLoc = returnLocTuple.get(returnLocTupleIdx);
2403 Descriptor returnDesc = returnLoc.getLocDescriptor();
2404 Descriptor enclosingDesc = returnLocTuple.get(returnLocTupleIdx).getDescriptor();
2406 HierarchyGraph hierarchyGraph = getHierarchyGraph(enclosingDesc);
2407 HNode returnNode = hierarchyGraph.getHNode(returnDesc);
2408 returnNode.setSkeleton(true);
2410 for (Iterator iterator = locFlowingToReturnValueSet.iterator(); iterator.hasNext();) {
2411 NTuple<Location> locTuple = (NTuple<Location>) iterator.next();
2412 Descriptor higherDesc = locTuple.get(returnLocTupleIdx).getLocDescriptor();
2413 hierarchyGraph.addEdge(higherDesc, returnDesc);
2416 methodSummary.setRETURNLoc(new CompositeLocation(returnLocTuple));
2418 // skip: for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2419 // FlowNode returnNode = (FlowNode) iterator.next();
2421 // NTuple<Descriptor> returnDescTuple = returnNode.getCurrentDescTuple();
2422 // NTuple<Location> returnLocTuple = translateToLocTuple(md, returnDescTuple);
2424 // if (returnLocTuple.get(0).getLocDescriptor().equals(md.getThis())) {
2425 // // if the location type of the return value matches "this" reference
2426 // // then, check whether this return value is equal to/lower than all
2427 // // of parameters that possibly flow into the return values
2428 // for (Iterator iterator2 = inferParamLocSet.iterator(); iterator2.hasNext();) {
2429 // CompositeLocation paramInferLoc = (CompositeLocation) iterator2.next();
2431 // if ((!paramInferLoc.equals(returnLocTuple))
2432 // && !isGreaterThan(methodLattice, paramInferLoc, inferReturnLoc)) {
2436 // inferFieldReturnLocSet.add(returnLocTuple);
2441 // if (inferFieldReturnLocSet.size() > 0) {
2443 // // CompositeLocation returnLoc = getLowest(methodLattice, inferFieldReturnLocSet);
2444 // CompositeLocation returnLoc = null;
2445 // if (returnLoc == null) {
2446 // // in this case, assign <'this',bottom> to the RETURNLOC
2447 // returnLoc = new CompositeLocation(new Location(md, md.getThis().getSymbol()));
2448 // returnLoc.addLocation(new Location(md.getClassDesc(), getLattice(md.getClassDesc())
2449 // .getBottomItem()));
2451 // methodInfo.setReturnLoc(returnLoc);
2454 // String returnLocSymbol = "RETURNLOC";
2455 // CompositeLocation returnLocInferLoc =
2456 // new CompositeLocation(new Location(md, returnLocSymbol));
2457 // methodInfo.setReturnLoc(returnLocInferLoc);
2459 // for (Iterator iterator = paramIdxSet.iterator(); iterator.hasNext();) {
2460 // Integer paramIdx = (Integer) iterator.next();
2461 // CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
2462 // String paramLocLocalSymbol = inferLoc.get(0).getLocIdentifier();
2463 // if (!methodLattice.isGreaterThan(paramLocLocalSymbol, returnLocSymbol)) {
2465 // // addRelationHigherToLower(methodLattice, methodInfo,
2466 // // paramLocLocalSymbol,
2467 // // returnLocSymbol);
2471 // for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2472 // FlowNode returnNode = (FlowNode) iterator.next();
2473 // CompositeLocation inferLoc =
2474 // generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
2475 // if (!isGreaterThan(methodLattice, inferLoc, returnLocInferLoc)) {
2477 // // addRelation(methodLattice, methodInfo, inferLoc,
2478 // // returnLocInferLoc);
2487 private void calculateExtraLocations(MethodDescriptor md) {
2488 // calcualte pcloc, returnloc,...
2490 System.out.println("\nSSJAVA:Calculate PCLOC/RETURNLOC locations: " + md);
2493 calculateRETURNLOC(md);
2497 private NTuple<Location> generateLocTupleRelativeTo(MethodDescriptor md,
2498 Set<NTuple<Location>> paramLocTupleHavingInFlowSet, String locNamePrefix) {
2500 System.out.println("-generateLocTupleRelativeTo=" + paramLocTupleHavingInFlowSet);
2502 NTuple<Location> higherLocTuple = new NTuple<Location>();
2504 VarDescriptor thisVarDesc = md.getThis();
2505 // check if all paramter loc tuple is started with 'this' reference
2506 boolean hasParamNotStartedWithThisRef = false;
2510 Set<NTuple<Location>> paramLocTupleStartedWithThis = new HashSet<NTuple<Location>>();
2512 for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
2513 NTuple<Location> paramLocTuple = (NTuple<Location>) iterator.next();
2514 if (!paramLocTuple.get(0).getLocDescriptor().equals(thisVarDesc)) {
2515 hasParamNotStartedWithThisRef = true;
2516 } else if (paramLocTuple.size() > 1) {
2517 paramLocTupleStartedWithThis.add(paramLocTuple);
2518 if (minSize == 0 || minSize > paramLocTuple.size()) {
2519 minSize = paramLocTuple.size();
2524 System.out.println("---paramLocTupleStartedWithThis=" + paramLocTupleStartedWithThis);
2525 Descriptor enclosingDesc = md;
2526 if (hasParamNotStartedWithThisRef) {
2527 // in this case, PCLOC will be the local location
2529 // all parameter is started with 'this', so PCLOC will be set relative to the composite
2530 // location started with 'this'.
2531 for (int idx = 0; idx < minSize - 1; idx++) {
2532 Set<Descriptor> locDescSet = new HashSet<Descriptor>();
2533 Location curLoc = null;
2534 NTuple<Location> paramLocTuple = null;
2535 for (Iterator iterator = paramLocTupleStartedWithThis.iterator(); iterator.hasNext();) {
2536 paramLocTuple = (NTuple<Location>) iterator.next();
2537 System.out.println("-----paramLocTuple=" + paramLocTuple + " idx=" + idx);
2538 curLoc = paramLocTuple.get(idx);
2539 Descriptor locDesc = curLoc.getLocDescriptor();
2540 locDescSet.add(locDesc);
2542 System.out.println("-----locDescSet=" + locDescSet + " idx=" + idx);
2543 if (locDescSet.size() != 1) {
2546 Location newLocElement = new Location(curLoc.getDescriptor(), curLoc.getLocDescriptor());
2547 higherLocTuple.add(newLocElement);
2548 enclosingDesc = getClassTypeDescriptor(curLoc.getLocDescriptor());
2553 String pcLocIdentifier = locNamePrefix + (locSeed++);
2554 NameDescriptor pcLocDesc = new NameDescriptor(pcLocIdentifier);
2555 Location newLoc = new Location(enclosingDesc, pcLocDesc);
2556 higherLocTuple.add(newLoc);
2558 System.out.println("---new loc tuple=" + higherLocTuple);
2560 return higherLocTuple;
2564 public ClassDescriptor getClassTypeDescriptor(Descriptor in) {
2566 if (in instanceof VarDescriptor) {
2567 return ((VarDescriptor) in).getType().getClassDesc();
2568 } else if (in instanceof FieldDescriptor) {
2569 return ((FieldDescriptor) in).getType().getClassDesc();
2571 // else if (in instanceof LocationDescriptor) {
2572 // // here is the case that the descriptor 'in' is the last element of the assigned composite
2574 // return ((VarDescriptor) locTuple.get(0).getLocDescriptor()).getType().getClassDesc();
2582 private Set<NTuple<Location>> calculateHighestLocTupleSet(
2583 Set<NTuple<Location>> paramLocTupleHavingInFlowSet) {
2585 Set<NTuple<Location>> highestSet = new HashSet<NTuple<Location>>();
2587 Iterator<NTuple<Location>> iterator = paramLocTupleHavingInFlowSet.iterator();
2588 NTuple<Location> highest = iterator.next();
2590 for (; iterator.hasNext();) {
2591 NTuple<Location> curLocTuple = (NTuple<Location>) iterator.next();
2592 if (isHigherThan(curLocTuple, highest)) {
2593 System.out.println(curLocTuple + " is greater than " + highest);
2594 highest = curLocTuple;
2598 highestSet.add(highest);
2600 MethodDescriptor md = (MethodDescriptor) highest.get(0).getDescriptor();
2601 VarDescriptor thisVarDesc = md.getThis();
2603 System.out.println("highest=" + highest);
2605 for (Iterator<NTuple<Location>> iter = paramLocTupleHavingInFlowSet.iterator(); iter.hasNext();) {
2606 NTuple<Location> curLocTuple = iter.next();
2608 if (!curLocTuple.equals(highest) && !hasOrderingRelation(highest, curLocTuple)) {
2610 System.out.println("add it to the highest set=" + curLocTuple);
2611 highestSet.add(curLocTuple);
2620 private void calculateExtraLocations2(MethodDescriptor md) {
2621 // calcualte pcloc, returnloc,...
2623 SSJavaLattice<String> methodLattice = getMethodLattice(md);
2624 MethodLocationInfo methodInfo = getMethodLocationInfo(md);
2625 FlowGraph fg = getFlowGraph(md);
2626 Set<FlowNode> nodeSet = fg.getNodeSet();
2628 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
2629 FlowNode flowNode = (FlowNode) iterator.next();
2630 if (flowNode.isDeclaratonNode()) {
2631 CompositeLocation inferLoc = methodInfo.getInferLocation(flowNode.getDescTuple().get(0));
2632 String locIdentifier = inferLoc.get(0).getLocIdentifier();
2633 if (!methodLattice.containsKey(locIdentifier)) {
2634 methodLattice.put(locIdentifier);
2640 Map<Integer, CompositeLocation> mapParamToLoc = methodInfo.getMapParamIdxToInferLoc();
2641 Set<Integer> paramIdxSet = mapParamToLoc.keySet();
2643 if (!ssjava.getMethodContainingSSJavaLoop().equals(md)) {
2644 // calculate the initial program counter location
2645 // PC location is higher than location types of all parameters
2646 String pcLocSymbol = "PCLOC";
2648 Set<CompositeLocation> paramInFlowSet = new HashSet<CompositeLocation>();
2650 for (Iterator iterator = paramIdxSet.iterator(); iterator.hasNext();) {
2651 Integer paramIdx = (Integer) iterator.next();
2653 FlowNode paramFlowNode = fg.getParamFlowNode(paramIdx);
2655 if (fg.getIncomingFlowNodeSet(paramFlowNode).size() > 0) {
2656 // parameter has in-value flows
2657 CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
2658 paramInFlowSet.add(inferLoc);
2662 if (paramInFlowSet.size() > 0) {
2663 CompositeLocation lowestLoc = getLowest(methodLattice, paramInFlowSet);
2664 assert (lowestLoc != null);
2665 methodInfo.setPCLoc(lowestLoc);
2670 // calculate a return location
2671 // the return location type is lower than all parameters and location
2674 if (!md.getReturnType().isVoid()) {
2675 // first, generate the set of return value location types that starts
2679 Set<CompositeLocation> inferFieldReturnLocSet = new HashSet<CompositeLocation>();
2681 Set<FlowNode> paramFlowNode = getParamNodeFlowingToReturnValue(md);
2682 Set<CompositeLocation> inferParamLocSet = new HashSet<CompositeLocation>();
2683 if (paramFlowNode != null) {
2684 for (Iterator iterator = paramFlowNode.iterator(); iterator.hasNext();) {
2685 FlowNode fn = (FlowNode) iterator.next();
2686 CompositeLocation inferLoc =
2687 generateInferredCompositeLocation(methodInfo, getFlowGraph(md).getLocationTuple(fn));
2688 inferParamLocSet.add(inferLoc);
2692 Set<FlowNode> returnNodeSet = fg.getReturnNodeSet();
2694 skip: for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2695 FlowNode returnNode = (FlowNode) iterator.next();
2696 CompositeLocation inferReturnLoc =
2697 generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
2698 if (inferReturnLoc.get(0).getLocIdentifier().equals("this")) {
2699 // if the location type of the return value matches "this" reference
2700 // then, check whether this return value is equal to/lower than all
2702 // parameters that possibly flow into the return values
2703 for (Iterator iterator2 = inferParamLocSet.iterator(); iterator2.hasNext();) {
2704 CompositeLocation paramInferLoc = (CompositeLocation) iterator2.next();
2706 if ((!paramInferLoc.equals(inferReturnLoc))
2707 && !isGreaterThan(methodLattice, paramInferLoc, inferReturnLoc)) {
2711 inferFieldReturnLocSet.add(inferReturnLoc);
2716 if (inferFieldReturnLocSet.size() > 0) {
2718 CompositeLocation returnLoc = getLowest(methodLattice, inferFieldReturnLocSet);
2719 if (returnLoc == null) {
2720 // in this case, assign <'this',bottom> to the RETURNLOC
2721 returnLoc = new CompositeLocation(new Location(md, md.getThis().getSymbol()));
2722 returnLoc.addLocation(new Location(md.getClassDesc(), getLattice(md.getClassDesc())
2725 methodInfo.setReturnLoc(returnLoc);
2728 String returnLocSymbol = "RETURNLOC";
2729 CompositeLocation returnLocInferLoc =
2730 new CompositeLocation(new Location(md, returnLocSymbol));
2731 methodInfo.setReturnLoc(returnLocInferLoc);
2733 for (Iterator iterator = paramIdxSet.iterator(); iterator.hasNext();) {
2734 Integer paramIdx = (Integer) iterator.next();
2735 CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
2736 String paramLocLocalSymbol = inferLoc.get(0).getLocIdentifier();
2737 if (!methodLattice.isGreaterThan(paramLocLocalSymbol, returnLocSymbol)) {
2739 // addRelationHigherToLower(methodLattice, methodInfo,
2740 // paramLocLocalSymbol,
2741 // returnLocSymbol);
2745 for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2746 FlowNode returnNode = (FlowNode) iterator.next();
2747 CompositeLocation inferLoc =
2748 generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
2749 if (!isGreaterThan(methodLattice, inferLoc, returnLocInferLoc)) {
2751 // addRelation(methodLattice, methodInfo, inferLoc,
2752 // returnLocInferLoc);
2761 private Set<String> getHigherLocSymbolThan(SSJavaLattice<String> lattice, String loc) {
2762 Set<String> higherLocSet = new HashSet<String>();
2764 Set<String> locSet = lattice.getTable().keySet();
2765 for (Iterator iterator = locSet.iterator(); iterator.hasNext();) {
2766 String element = (String) iterator.next();
2767 if (lattice.isGreaterThan(element, loc) && (!element.equals(lattice.getTopItem()))) {
2768 higherLocSet.add(element);
2771 return higherLocSet;
2774 private CompositeLocation getLowest(SSJavaLattice<String> methodLattice,
2775 Set<CompositeLocation> set) {
2777 CompositeLocation lowest = set.iterator().next();
2779 if (set.size() == 1) {
2783 for (Iterator iterator = set.iterator(); iterator.hasNext();) {
2784 CompositeLocation loc = (CompositeLocation) iterator.next();
2786 if ((!loc.equals(lowest)) && (!isComparable(methodLattice, lowest, loc))) {
2787 // if there is a case where composite locations are incomparable, just
2792 if ((!loc.equals(lowest)) && isGreaterThan(methodLattice, lowest, loc)) {
2799 private boolean isComparable(SSJavaLattice<String> methodLattice, CompositeLocation comp1,
2800 CompositeLocation comp2) {
2802 int size = comp1.getSize() >= comp2.getSize() ? comp2.getSize() : comp1.getSize();
2804 for (int idx = 0; idx < size; idx++) {
2805 Location loc1 = comp1.get(idx);
2806 Location loc2 = comp2.get(idx);
2808 Descriptor desc1 = loc1.getDescriptor();
2809 Descriptor desc2 = loc2.getDescriptor();
2811 if (!desc1.equals(desc2)) {
2812 throw new Error("Fail to compare " + comp1 + " and " + comp2);
2815 String symbol1 = loc1.getLocIdentifier();
2816 String symbol2 = loc2.getLocIdentifier();
2818 SSJavaLattice<String> lattice;
2820 lattice = methodLattice;
2822 lattice = getLattice(desc1);
2825 if (symbol1.equals(symbol2)) {
2827 } else if (!lattice.isComparable(symbol1, symbol2)) {
2836 private boolean isGreaterThan(SSJavaLattice<String> methodLattice, CompositeLocation comp1,
2837 CompositeLocation comp2) {
2839 int size = comp1.getSize() >= comp2.getSize() ? comp2.getSize() : comp1.getSize();
2841 for (int idx = 0; idx < size; idx++) {
2842 Location loc1 = comp1.get(idx);
2843 Location loc2 = comp2.get(idx);
2845 Descriptor desc1 = loc1.getDescriptor();
2846 Descriptor desc2 = loc2.getDescriptor();
2848 if (!desc1.equals(desc2)) {
2849 throw new Error("Fail to compare " + comp1 + " and " + comp2);
2852 String symbol1 = loc1.getLocIdentifier();
2853 String symbol2 = loc2.getLocIdentifier();
2855 SSJavaLattice<String> lattice;
2857 lattice = methodLattice;
2859 lattice = getLattice(desc1);
2862 if (symbol1.equals(symbol2)) {
2864 } else if (lattice.isGreaterThan(symbol1, symbol2)) {
2875 private void contributeCalleeFlows(MethodInvokeNode min, MethodDescriptor mdCaller,
2876 MethodDescriptor mdCallee) {
2878 System.out.println("\n##contributeCalleeFlows callee=" + mdCallee + "TO caller=" + mdCaller);
2880 getSubGlobalFlowGraph(mdCallee);
2884 private GlobalFlowGraph getSubGlobalFlowGraph(MethodDescriptor md) {
2885 return mapMethodDescriptorToSubGlobalFlowGraph.get(md);
2888 private void propagateFlowsToCallerWithNoCompositeLocation(MethodInvokeNode min,
2889 MethodDescriptor mdCaller, MethodDescriptor mdCallee) {
2891 System.out.println("\n##PROPAGATE callee=" + mdCallee + "TO caller=" + mdCaller);
2893 // if the parameter A reaches to the parameter B
2894 // then, add an edge the argument A -> the argument B to the caller's flow
2897 FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
2898 FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
2899 int numParam = calleeFlowGraph.getNumParameters();
2901 for (int i = 0; i < numParam; i++) {
2902 for (int k = 0; k < numParam; k++) {
2906 FlowNode paramNode1 = calleeFlowGraph.getParamFlowNode(i);
2907 FlowNode paramNode2 = calleeFlowGraph.getParamFlowNode(k);
2909 NTuple<Descriptor> arg1Tuple = getNodeTupleByArgIdx(min, i);
2910 NTuple<Descriptor> arg2Tuple = getNodeTupleByArgIdx(min, k);
2912 // check if the callee propagates an ordering constraints through
2915 Set<FlowNode> localReachSet = calleeFlowGraph.getLocalReachFlowNodeSetFrom(paramNode1);
2916 System.out.println("-param1=" + paramNode1 + " is higher than param2=" + paramNode2);
2917 System.out.println("-- localReachSet from param1=" + localReachSet);
2919 if (arg1Tuple.size() > 0 && arg2Tuple.size() > 0 && localReachSet.contains(paramNode2)) {
2920 // need to propagate an ordering relation s.t. arg1 is higher
2924 .println("-arg1Tuple=" + arg1Tuple + " is higher than arg2Tuple=" + arg2Tuple);
2926 // otherwise, flows between method/field locations...
2927 callerFlowGraph.addValueFlowEdge(arg1Tuple, arg2Tuple);
2928 System.out.println("arg1=" + arg1Tuple + " arg2=" + arg2Tuple);
2932 System.out.println();
2936 System.out.println("##\n");
2940 private void propagateFlowsToCaller(MethodInvokeNode min, MethodDescriptor mdCaller,
2941 MethodDescriptor mdCallee) {
2943 System.out.println("\n##PROPAGATE callee=" + mdCallee + "TO caller=" + mdCaller);
2945 // if the parameter A reaches to the parameter B
2946 // then, add an edge the argument A -> the argument B to the caller's flow
2950 // also if a parameter is a composite location and is started with "this"
2952 // need to make sure that the corresponding argument is higher than the
2953 // translated location of
2956 FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
2957 FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
2958 int numParam = calleeFlowGraph.getNumParameters();
2960 for (int i = 0; i < numParam; i++) {
2961 for (int k = 0; k < numParam; k++) {
2965 FlowNode paramNode1 = calleeFlowGraph.getParamFlowNode(i);
2966 FlowNode paramNode2 = calleeFlowGraph.getParamFlowNode(k);
2968 System.out.println("param1=" + paramNode1 + " curDescTuple="
2969 + paramNode1.getCurrentDescTuple());
2970 System.out.println("param2=" + paramNode2 + " curDescTuple="
2971 + paramNode2.getCurrentDescTuple());
2973 // TODO: deprecated method
2974 // NodeTupleSet tupleSetArg1 = getNodeTupleSetByArgIdx(min, i);
2975 // NodeTupleSet tupleSetArg2 = getNodeTupleSetByArgIdx(min, k);
2976 NodeTupleSet tupleSetArg1 = null;
2977 NodeTupleSet tupleSetArg2 = null;
2979 for (Iterator<NTuple<Descriptor>> iter1 = tupleSetArg1.iterator(); iter1.hasNext();) {
2980 NTuple<Descriptor> arg1Tuple = iter1.next();
2982 for (Iterator<NTuple<Descriptor>> iter2 = tupleSetArg2.iterator(); iter2.hasNext();) {
2983 NTuple<Descriptor> arg2Tuple = iter2.next();
2985 // check if the callee propagates an ordering constraints through
2988 Set<FlowNode> localReachSet =
2989 calleeFlowGraph.getLocalReachFlowNodeSetFrom(paramNode1);
2991 if (localReachSet.contains(paramNode2)) {
2992 // need to propagate an ordering relation s.t. arg1 is higher
2996 .println("-param1=" + paramNode1 + " is higher than param2=" + paramNode2);
2997 System.out.println("-arg1Tuple=" + arg1Tuple + " is higher than arg2Tuple="
3000 if (!min.getMethod().isStatic()) {
3001 // check if this is the case that values flow to/from the
3002 // current object reference 'this'
3004 NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
3005 Descriptor baseRef = baseTuple.get(baseTuple.size() - 1);
3007 System.out.println("paramNode1.getCurrentDescTuple()="
3008 + paramNode1.getCurrentDescTuple());
3009 // calculate the prefix of the argument
3011 if (arg2Tuple.size() == 1 && arg2Tuple.get(0).equals(baseRef)) {
3012 // in this case, the callee flow causes a caller flow to the
3013 // object whose method
3016 if (!paramNode1.getCurrentDescTuple().startsWith(mdCallee.getThis())) {
3017 // check whether ???
3019 NTuple<Descriptor> param1Prefix =
3020 calculatePrefixForParam(callerFlowGraph, calleeFlowGraph, min, arg1Tuple,
3023 if (param1Prefix != null && param1Prefix.startsWith(mdCallee.getThis())) {
3024 // in this case, we need to create a new edge
3025 // 'this.FIELD'->'this'
3026 // but we couldn't... instead we assign a new composite
3028 // with 'this' reference to the corresponding parameter
3030 CompositeLocation compLocForParam1 =
3031 generateCompositeLocation(mdCallee, param1Prefix);
3034 .println("set comp loc=" + compLocForParam1 + " to " + paramNode1);
3035 paramNode1.setCompositeLocation(compLocForParam1);
3037 // then, we need to make sure that the corresponding
3038 // argument in the caller
3039 // is required to be higher than or equal to the
3040 // translated parameter
3043 NTuple<Descriptor> translatedParamTuple =
3044 translateCompositeLocationToCaller(min, compLocForParam1);
3046 // TODO : check if the arg >= the tranlated parameter
3048 System.out.println("add a flow edge= " + arg1Tuple + "->"
3049 + translatedParamTuple);
3050 callerFlowGraph.addValueFlowEdge(arg1Tuple, translatedParamTuple);
3057 // param1 has already been assigned a composite location
3059 System.out.println("--param1 has already been assigned a composite location");
3060 CompositeLocation compLocForParam1 = paramNode1.getCompositeLocation();
3061 NTuple<Descriptor> translatedParamTuple =
3062 translateCompositeLocationToCaller(min, compLocForParam1);
3064 // TODO : check if the arg >= the tranlated parameter
3066 System.out.println("add a flow edge= " + arg1Tuple + "->"
3067 + translatedParamTuple);
3068 callerFlowGraph.addValueFlowEdge(arg1Tuple, translatedParamTuple);
3074 } else if (arg1Tuple.size() == 1 && arg1Tuple.get(0).equals(baseRef)) {
3075 // in this case, the callee flow causes a caller flow
3076 // originated from the object
3078 // method is invoked.
3080 System.out.println("###FROM CASE");
3082 if (!paramNode2.getCurrentDescTuple().startsWith(mdCallee.getThis())) {
3084 NTuple<Descriptor> param2Prefix =
3085 calculatePrefixForParam(callerFlowGraph, calleeFlowGraph, min, arg2Tuple,
3088 if (param2Prefix != null && param2Prefix.startsWith(mdCallee.getThis())) {
3089 // in this case, we need to create a new edge 'this' ->
3090 // 'this.FIELD' but we couldn't... instead we assign the
3092 // parameter a new composite location started with
3095 CompositeLocation compLocForParam2 =
3096 generateCompositeLocation(mdCallee, param2Prefix);
3098 // System.out.println("set comp loc=" + compLocForParam2
3100 // " to " + paramNode2);
3101 paramNode1.setCompositeLocation(compLocForParam2);
3109 // otherwise, flows between method/field locations...
3110 callerFlowGraph.addValueFlowEdge(arg1Tuple, arg2Tuple);
3111 System.out.println("arg1=" + arg1Tuple + " arg2=" + arg2Tuple);
3118 System.out.println();
3122 System.out.println("##\n");
3125 private NTuple<Descriptor> translateCompositeLocationToCaller(MethodInvokeNode min,
3126 CompositeLocation compLocForParam1) {
3127 NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
3129 NTuple<Descriptor> tuple = new NTuple<Descriptor>();
3131 for (int i = 0; i < baseTuple.size(); i++) {
3132 tuple.add(baseTuple.get(i));
3135 for (int i = 1; i < compLocForParam1.getSize(); i++) {
3136 Location loc = compLocForParam1.get(i);
3137 tuple.add(loc.getLocDescriptor());
3143 private CompositeLocation generateCompositeLocation(NTuple<Location> prefixLocTuple) {
3145 System.out.println("generateCompositeLocation=" + prefixLocTuple);
3147 CompositeLocation newCompLoc = new CompositeLocation();
3148 for (int i = 0; i < prefixLocTuple.size(); i++) {
3149 newCompLoc.addLocation(prefixLocTuple.get(i));
3152 Descriptor lastDescOfPrefix = prefixLocTuple.get(prefixLocTuple.size() - 1).getLocDescriptor();
3154 ClassDescriptor enclosingDescriptor;
3155 if (lastDescOfPrefix instanceof FieldDescriptor) {
3156 enclosingDescriptor = ((FieldDescriptor) lastDescOfPrefix).getType().getClassDesc();
3157 // System.out.println("enclosingDescriptor0=" + enclosingDescriptor);
3159 // var descriptor case
3160 enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
3162 // System.out.println("enclosingDescriptor=" + enclosingDescriptor);
3164 LocationDescriptor newLocDescriptor = generateNewLocationDescriptor();
3165 newLocDescriptor.setEnclosingClassDesc(enclosingDescriptor);
3167 Location newLoc = new Location(enclosingDescriptor, newLocDescriptor.getSymbol());
3168 newLoc.setLocDescriptor(newLocDescriptor);
3169 newCompLoc.addLocation(newLoc);
3171 // System.out.println("--newCompLoc=" + newCompLoc);
3175 private CompositeLocation generateCompositeLocation(MethodDescriptor md,
3176 NTuple<Descriptor> paramPrefix) {
3178 System.out.println("generateCompositeLocation=" + paramPrefix);
3180 CompositeLocation newCompLoc = convertToCompositeLocation(md, paramPrefix);
3182 Descriptor lastDescOfPrefix = paramPrefix.get(paramPrefix.size() - 1);
3183 // System.out.println("lastDescOfPrefix=" + lastDescOfPrefix + " kind="
3184 // + lastDescOfPrefix.getClass());
3185 ClassDescriptor enclosingDescriptor;
3186 if (lastDescOfPrefix instanceof FieldDescriptor) {
3187 enclosingDescriptor = ((FieldDescriptor) lastDescOfPrefix).getType().getClassDesc();
3188 // System.out.println("enclosingDescriptor0=" + enclosingDescriptor);
3190 // var descriptor case
3191 enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
3193 // System.out.println("enclosingDescriptor=" + enclosingDescriptor);
3195 LocationDescriptor newLocDescriptor = generateNewLocationDescriptor();
3196 newLocDescriptor.setEnclosingClassDesc(enclosingDescriptor);
3198 Location newLoc = new Location(enclosingDescriptor, newLocDescriptor.getSymbol());
3199 newLoc.setLocDescriptor(newLocDescriptor);
3200 newCompLoc.addLocation(newLoc);
3202 // System.out.println("--newCompLoc=" + newCompLoc);
3206 private NTuple<Descriptor> calculatePrefixForParam(FlowGraph callerFlowGraph,
3207 FlowGraph calleeFlowGraph, MethodInvokeNode min, NTuple<Descriptor> arg1Tuple,
3208 FlowNode paramNode1) {
3210 NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
3211 Descriptor baseRef = baseTuple.get(baseTuple.size() - 1);
3212 System.out.println("baseRef=" + baseRef);
3214 FlowNode flowNodeArg1 = callerFlowGraph.getFlowNode(arg1Tuple);
3215 List<NTuple<Descriptor>> callerPrefixList = calculatePrefixList(callerFlowGraph, flowNodeArg1);
3216 System.out.println("callerPrefixList=" + callerPrefixList);
3218 List<NTuple<Descriptor>> prefixList = calculatePrefixList(calleeFlowGraph, paramNode1);
3219 System.out.println("###prefixList from node=" + paramNode1 + " =" + prefixList);
3221 List<NTuple<Descriptor>> calleePrefixList =
3222 translatePrefixListToCallee(baseRef, min.getMethod(), callerPrefixList);
3224 System.out.println("calleePrefixList=" + calleePrefixList);
3226 Set<FlowNode> reachNodeSetFromParam1 = calleeFlowGraph.getReachFlowNodeSetFrom(paramNode1);
3227 System.out.println("reachNodeSetFromParam1=" + reachNodeSetFromParam1);
3229 for (int i = 0; i < calleePrefixList.size(); i++) {
3230 NTuple<Descriptor> curPrefix = calleePrefixList.get(i);
3231 Set<NTuple<Descriptor>> reachableCommonPrefixSet = new HashSet<NTuple<Descriptor>>();
3233 for (Iterator iterator2 = reachNodeSetFromParam1.iterator(); iterator2.hasNext();) {
3234 FlowNode reachNode = (FlowNode) iterator2.next();
3235 if (reachNode.getCurrentDescTuple().startsWith(curPrefix)) {
3236 reachableCommonPrefixSet.add(reachNode.getCurrentDescTuple());
3240 if (!reachableCommonPrefixSet.isEmpty()) {
3241 System.out.println("###REACHABLECOMONPREFIX=" + reachableCommonPrefixSet
3242 + " with curPreFix=" + curPrefix);
3251 private List<NTuple<Descriptor>> translatePrefixListToCallee(Descriptor baseRef,
3252 MethodDescriptor mdCallee, List<NTuple<Descriptor>> callerPrefixList) {
3254 List<NTuple<Descriptor>> calleePrefixList = new ArrayList<NTuple<Descriptor>>();
3256 for (int i = 0; i < callerPrefixList.size(); i++) {
3257 NTuple<Descriptor> prefix = callerPrefixList.get(i);
3258 if (prefix.startsWith(baseRef)) {
3259 NTuple<Descriptor> calleePrefix = new NTuple<Descriptor>();
3260 calleePrefix.add(mdCallee.getThis());
3261 for (int k = 1; k < prefix.size(); k++) {
3262 calleePrefix.add(prefix.get(k));
3264 calleePrefixList.add(calleePrefix);
3268 return calleePrefixList;
3272 private List<NTuple<Descriptor>> calculatePrefixList(FlowGraph flowGraph, FlowNode flowNode) {
3274 System.out.println("\n##### calculatePrefixList=" + flowNode);
3276 Set<FlowNode> inNodeSet = flowGraph.getIncomingFlowNodeSet(flowNode);
3277 inNodeSet.add(flowNode);
3279 System.out.println("inNodeSet=" + inNodeSet);
3281 List<NTuple<Descriptor>> prefixList = new ArrayList<NTuple<Descriptor>>();
3283 for (Iterator iterator = inNodeSet.iterator(); iterator.hasNext();) {
3284 FlowNode inNode = (FlowNode) iterator.next();
3286 NTuple<Descriptor> inNodeTuple = inNode.getCurrentDescTuple();
3288 // CompositeLocation inNodeInferredLoc =
3289 // generateInferredCompositeLocation(methodInfo, inNodeTuple);
3290 // NTuple<Location> inNodeInferredLocTuple = inNodeInferredLoc.getTuple();
3292 for (int i = 1; i < inNodeTuple.size(); i++) {
3293 NTuple<Descriptor> prefix = inNodeTuple.subList(0, i);
3294 if (!prefixList.contains(prefix)) {
3295 prefixList.add(prefix);
3300 Collections.sort(prefixList, new Comparator<NTuple<Descriptor>>() {
3301 public int compare(NTuple<Descriptor> arg0, NTuple<Descriptor> arg1) {
3302 int s0 = arg0.size();
3303 int s1 = arg1.size();
3306 } else if (s0 == s1) {
3318 public CompositeLocation convertToCompositeLocation(MethodDescriptor md, NTuple<Descriptor> tuple) {
3320 CompositeLocation compLoc = new CompositeLocation();
3322 Descriptor enclosingDescriptor = md;
3324 for (int i = 0; i < tuple.size(); i++) {
3325 Descriptor curDescriptor = tuple.get(i);
3326 Location locElement = new Location(enclosingDescriptor, curDescriptor.getSymbol());
3327 locElement.setLocDescriptor(curDescriptor);
3328 compLoc.addLocation(locElement);
3330 if (curDescriptor instanceof VarDescriptor) {
3331 enclosingDescriptor = md.getClassDesc();
3332 } else if (curDescriptor instanceof NameDescriptor) {
3333 // it is "GLOBAL LOC" case!
3334 enclosingDescriptor = GLOBALDESC;
3335 } else if (curDescriptor instanceof InterDescriptor) {
3336 enclosingDescriptor = null;
3338 enclosingDescriptor = ((FieldDescriptor) curDescriptor).getClassDescriptor();
3346 private LocationDescriptor generateNewLocationDescriptor() {
3347 return new LocationDescriptor("Loc" + (locSeed++));
3350 private int getPrefixIndex(NTuple<Descriptor> tuple1, NTuple<Descriptor> tuple2) {
3352 // return the index where the prefix shared by tuple1 and tuple2 is ended
3353 // if there is no prefix shared by both of them, return -1
3355 int minSize = tuple1.size();
3356 if (minSize > tuple2.size()) {
3357 minSize = tuple2.size();
3361 for (int i = 0; i < minSize; i++) {
3362 if (!tuple1.get(i).equals(tuple2.get(i))) {
3372 private CompositeLocation generateInferredCompositeLocation(MethodLocationInfo methodInfo,
3373 NTuple<Location> tuple) {
3375 // first, retrieve inferred location by the local var descriptor
3376 CompositeLocation inferLoc = new CompositeLocation();
3378 CompositeLocation localVarInferLoc =
3379 methodInfo.getInferLocation(tuple.get(0).getLocDescriptor());
3381 localVarInferLoc.get(0).setLocDescriptor(tuple.get(0).getLocDescriptor());
3383 for (int i = 0; i < localVarInferLoc.getSize(); i++) {
3384 inferLoc.addLocation(localVarInferLoc.get(i));
3387 for (int i = 1; i < tuple.size(); i++) {
3388 Location cur = tuple.get(i);
3389 Descriptor enclosingDesc = cur.getDescriptor();
3390 Descriptor curDesc = cur.getLocDescriptor();
3392 Location inferLocElement;
3393 if (curDesc == null) {
3394 // in this case, we have a newly generated location.
3395 inferLocElement = new Location(enclosingDesc, cur.getLocIdentifier());
3397 String fieldLocSymbol =
3398 getLocationInfo(enclosingDesc).getInferLocation(curDesc).get(0).getLocIdentifier();
3399 inferLocElement = new Location(enclosingDesc, fieldLocSymbol);
3400 inferLocElement.setLocDescriptor(curDesc);
3403 inferLoc.addLocation(inferLocElement);
3407 assert (inferLoc.get(0).getLocDescriptor().getSymbol() == inferLoc.get(0).getLocIdentifier());
3411 public LocationInfo getLocationInfo(Descriptor d) {
3412 if (d instanceof MethodDescriptor) {
3413 return getMethodLocationInfo((MethodDescriptor) d);
3415 return getFieldLocationInfo((ClassDescriptor) d);
3419 private MethodLocationInfo getMethodLocationInfo(MethodDescriptor md) {
3421 if (!mapMethodDescToMethodLocationInfo.containsKey(md)) {
3422 mapMethodDescToMethodLocationInfo.put(md, new MethodLocationInfo(md));
3425 return mapMethodDescToMethodLocationInfo.get(md);
3429 private LocationInfo getFieldLocationInfo(ClassDescriptor cd) {
3431 if (!mapClassToLocationInfo.containsKey(cd)) {
3432 mapClassToLocationInfo.put(cd, new LocationInfo(cd));
3435 return mapClassToLocationInfo.get(cd);
3439 private void addPrefixMapping(Map<NTuple<Location>, Set<NTuple<Location>>> map,
3440 NTuple<Location> prefix, NTuple<Location> element) {
3442 if (!map.containsKey(prefix)) {
3443 map.put(prefix, new HashSet<NTuple<Location>>());
3445 map.get(prefix).add(element);
3448 private boolean containsNonPrimitiveElement(Set<Descriptor> descSet) {
3449 for (Iterator iterator = descSet.iterator(); iterator.hasNext();) {
3450 Descriptor desc = (Descriptor) iterator.next();
3452 if (desc.equals(LocationInference.GLOBALDESC)) {
3454 } else if (desc instanceof VarDescriptor) {
3455 if (!((VarDescriptor) desc).getType().isPrimitive()) {
3458 } else if (desc instanceof FieldDescriptor) {
3459 if (!((FieldDescriptor) desc).getType().isPrimitive()) {
3468 private SSJavaLattice<String> getLattice(Descriptor d) {
3469 if (d instanceof MethodDescriptor) {
3470 return getMethodLattice((MethodDescriptor) d);
3472 return getFieldLattice((ClassDescriptor) d);
3476 private SSJavaLattice<String> getMethodLattice(MethodDescriptor md) {
3477 if (!md2lattice.containsKey(md)) {
3478 md2lattice.put(md, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
3480 return md2lattice.get(md);
3483 private void setMethodLattice(MethodDescriptor md, SSJavaLattice<String> lattice) {
3484 md2lattice.put(md, lattice);
3487 private void extractFlowsBetweenFields(ClassDescriptor cd, FlowNode srcNode, FlowNode dstNode,
3490 NTuple<Descriptor> srcCurTuple = srcNode.getCurrentDescTuple();
3491 NTuple<Descriptor> dstCurTuple = dstNode.getCurrentDescTuple();
3493 if (srcCurTuple.get(idx).equals(dstCurTuple.get(idx)) && srcCurTuple.size() > (idx + 1)
3494 && dstCurTuple.size() > (idx + 1)) {
3495 // value flow between fields: we don't need to add a binary relation
3498 Descriptor desc = srcCurTuple.get(idx);
3499 ClassDescriptor classDesc;
3502 classDesc = ((VarDescriptor) desc).getType().getClassDesc();
3504 if (desc instanceof FieldDescriptor) {
3505 classDesc = ((FieldDescriptor) desc).getType().getClassDesc();
3507 // this case is that the local variable has a composite location assignment
3508 // the following element after the composite location to the local variable
3509 // has the enclosing descriptor of the local variable
3510 Descriptor localDesc = srcNode.getDescTuple().get(0);
3511 classDesc = ((VarDescriptor) localDesc).getType().getClassDesc();
3514 extractFlowsBetweenFields(classDesc, srcNode, dstNode, idx + 1);
3518 Descriptor srcFieldDesc = srcCurTuple.get(idx);
3519 Descriptor dstFieldDesc = dstCurTuple.get(idx);
3522 getHierarchyGraph(cd).addEdge(srcFieldDesc, dstFieldDesc);
3528 public SSJavaLattice<String> getFieldLattice(ClassDescriptor cd) {
3529 if (!cd2lattice.containsKey(cd)) {
3530 cd2lattice.put(cd, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
3532 return cd2lattice.get(cd);
3535 public LinkedList<MethodDescriptor> computeMethodList() {
3537 Set<MethodDescriptor> toSort = new HashSet<MethodDescriptor>();
3541 Set<MethodDescriptor> visited = new HashSet<MethodDescriptor>();
3542 Set<MethodDescriptor> reachableCallee = new HashSet<MethodDescriptor>();
3544 while (!toAnalyzeIsEmpty()) {
3545 ClassDescriptor cd = toAnalyzeNext();
3547 setupToAnalazeMethod(cd);
3548 temp_toanalyzeMethodList.removeAll(visited);
3550 while (!toAnalyzeMethodIsEmpty()) {
3551 MethodDescriptor md = toAnalyzeMethodNext();
3552 if ((!visited.contains(md))
3553 && (ssjava.needTobeAnnotated(md) || reachableCallee.contains(md))) {
3555 // creates a mapping from a method descriptor to virtual methods
3556 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3557 if (md.isStatic()) {
3558 setPossibleCallees.add(md);
3560 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
3563 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getCalleeSet(md);
3564 Set<MethodDescriptor> needToAnalyzeCalleeSet = new HashSet<MethodDescriptor>();
3566 for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
3567 MethodDescriptor calleemd = (MethodDescriptor) iterator.next();
3568 if ((!ssjava.isTrustMethod(calleemd))
3569 && (!ssjava.isSSJavaUtil(calleemd.getClassDesc()))) {
3570 if (!visited.contains(calleemd)) {
3571 temp_toanalyzeMethodList.add(calleemd);
3573 reachableCallee.add(calleemd);
3574 needToAnalyzeCalleeSet.add(calleemd);
3578 mapMethodToCalleeSet.put(md, needToAnalyzeCalleeSet);
3587 return ssjava.topologicalSort(toSort);
3591 public boolean isTransitivelyCalledFrom(MethodDescriptor callee, MethodDescriptor caller) {
3592 // if the callee is transitively invoked from the caller
3595 int callerIdx = toanalyze_methodDescList.indexOf(caller);
3596 int calleeIdx = toanalyze_methodDescList.indexOf(callee);
3598 if (callerIdx < calleeIdx) {
3606 public void constructFlowGraph() {
3608 System.out.println("");
3609 toanalyze_methodDescList = computeMethodList();
3611 LinkedList<MethodDescriptor> methodDescList =
3612 (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
3614 System.out.println("@@@methodDescList=" + methodDescList);
3617 while (!methodDescList.isEmpty()) {
3618 MethodDescriptor md = methodDescList.removeLast();
3619 if (state.SSJAVADEBUG) {
3620 System.out.println();
3621 System.out.println("SSJAVA: Constructing a flow graph: " + md);
3623 // creates a mapping from a parameter descriptor to its index
3624 Map<Descriptor, Integer> mapParamDescToIdx = new HashMap<Descriptor, Integer>();
3626 if (!md.isStatic()) {
3628 mapParamDescToIdx.put(md.getThis(), 0);
3631 for (int i = 0; i < md.numParameters(); i++) {
3632 Descriptor paramDesc = (Descriptor) md.getParameter(i);
3633 mapParamDescToIdx.put(paramDesc, new Integer(i + offset));
3636 FlowGraph fg = new FlowGraph(md, mapParamDescToIdx);
3637 mapMethodDescriptorToFlowGraph.put(md, fg);
3639 analyzeMethodBody(md.getClassDesc(), md);
3641 // System.out.println("##constructSubGlobalFlowGraph");
3642 // GlobalFlowGraph subGlobalFlowGraph = constructSubGlobalFlowGraph(fg);
3643 // mapMethodDescriptorToSubGlobalFlowGraph.put(md, subGlobalFlowGraph);
3646 // System.out.println("##addValueFlowsFromCalleeSubGlobalFlowGraph");
3647 // addValueFlowsFromCalleeSubGlobalFlowGraph(md, subGlobalFlowGraph);
3648 // subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
3650 // propagateFlowsFromCalleesWithNoCompositeLocation(md);
3654 // _debug_printGraph();
3656 methodDescList = (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
3658 while (!methodDescList.isEmpty()) {
3659 MethodDescriptor md = methodDescList.removeLast();
3660 if (state.SSJAVADEBUG) {
3661 System.out.println();
3662 System.out.println("SSJAVA: Constructing a flow graph2: " + md);
3664 System.out.println("##constructSubGlobalFlowGraph");
3665 GlobalFlowGraph subGlobalFlowGraph = constructSubGlobalFlowGraph(getFlowGraph(md));
3666 mapMethodDescriptorToSubGlobalFlowGraph.put(md, subGlobalFlowGraph);
3669 System.out.println("##addValueFlowsFromCalleeSubGlobalFlowGraph");
3670 addValueFlowsFromCalleeSubGlobalFlowGraph(md, subGlobalFlowGraph);
3671 subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
3673 propagateFlowsFromCalleesWithNoCompositeLocation(md);
3680 private Set<MethodInvokeNode> getMethodInvokeNodeSet(MethodDescriptor md) {
3681 if (!mapMethodDescriptorToMethodInvokeNodeSet.containsKey(md)) {
3682 mapMethodDescriptorToMethodInvokeNodeSet.put(md, new HashSet<MethodInvokeNode>());
3684 return mapMethodDescriptorToMethodInvokeNodeSet.get(md);
3687 private void constructSubGlobalFlowGraph(MethodDescriptor md) {
3689 FlowGraph flowGraph = getFlowGraph(md);
3691 Set<MethodInvokeNode> setMethodInvokeNode = getMethodInvokeNodeSet(md);
3693 for (Iterator<MethodInvokeNode> iter = setMethodInvokeNode.iterator(); iter.hasNext();) {
3694 MethodInvokeNode min = iter.next();
3695 propagateFlowsFromMethodInvokeNode(md, min);
3700 private void propagateFlowsFromMethodInvokeNode(MethodDescriptor mdCaller, MethodInvokeNode min) {
3701 // the transformation for a call site propagates flows through parameters
3702 // if the method is virtual, it also grab all relations from any possible
3705 MethodDescriptor mdCallee = min.getMethod();
3706 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3707 if (mdCallee.isStatic()) {
3708 setPossibleCallees.add(mdCallee);
3710 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
3711 // removes method descriptors that are not invoked by the caller
3712 calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
3713 setPossibleCallees.addAll(calleeSet);
3716 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
3717 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
3718 contributeCalleeFlows(min, mdCaller, possibleMdCallee);
3723 private void assignCompositeLocation(MethodDescriptor md) {
3725 FlowGraph flowGraph = getFlowGraph(md);
3727 Set<FlowNode> nodeSet = flowGraph.getNodeSet();
3729 next: for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
3730 FlowNode flowNode = (FlowNode) iterator.next();
3732 // assign a composite location only to the local variable
3733 if (flowNode.getCurrentDescTuple().size() == 1) {
3735 List<NTuple<Descriptor>> prefixList = calculatePrefixList(flowGraph, flowNode);
3736 Set<FlowNode> reachSet = flowGraph.getReachFlowNodeSetFrom(flowNode);
3738 for (int i = 0; i < prefixList.size(); i++) {
3739 NTuple<Descriptor> curPrefix = prefixList.get(i);
3740 Set<NTuple<Descriptor>> reachableCommonPrefixSet = new HashSet<NTuple<Descriptor>>();
3742 for (Iterator iterator2 = reachSet.iterator(); iterator2.hasNext();) {
3743 FlowNode reachNode = (FlowNode) iterator2.next();
3744 if (reachNode.getCurrentDescTuple().startsWith(curPrefix)) {
3745 reachableCommonPrefixSet.add(reachNode.getCurrentDescTuple());
3749 if (!reachableCommonPrefixSet.isEmpty()) {
3750 System.out.println("NEED TO ASSIGN COMP LOC TO " + flowNode + " with prefix="
3752 CompositeLocation newCompLoc = generateCompositeLocation(md, curPrefix);
3753 flowNode.setCompositeLocation(newCompLoc);
3764 private void propagateFlowsFromCalleesWithNoCompositeLocation(MethodDescriptor mdCaller) {
3766 // the transformation for a call site propagates flows through parameters
3767 // if the method is virtual, it also grab all relations from any possible
3770 Set<MethodInvokeNode> setMethodInvokeNode =
3771 mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
3773 if (setMethodInvokeNode != null) {
3775 for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
3776 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
3777 MethodDescriptor mdCallee = min.getMethod();
3778 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3779 if (mdCallee.isStatic()) {
3780 setPossibleCallees.add(mdCallee);
3782 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
3783 // removes method descriptors that are not invoked by the caller
3784 calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
3785 setPossibleCallees.addAll(calleeSet);
3788 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
3789 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
3790 propagateFlowsToCallerWithNoCompositeLocation(min, mdCaller, possibleMdCallee);
3798 private void propagateFlowsFromCallees(MethodDescriptor mdCaller) {
3800 // the transformation for a call site propagates flows through parameters
3801 // if the method is virtual, it also grab all relations from any possible
3804 Set<MethodInvokeNode> setMethodInvokeNode =
3805 mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
3807 if (setMethodInvokeNode != null) {
3809 for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
3810 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
3811 MethodDescriptor mdCallee = min.getMethod();
3812 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3813 if (mdCallee.isStatic()) {
3814 setPossibleCallees.add(mdCallee);
3816 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
3817 // removes method descriptors that are not invoked by the caller
3818 calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
3819 setPossibleCallees.addAll(calleeSet);
3822 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
3823 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
3824 propagateFlowsToCaller(min, mdCaller, possibleMdCallee);
3832 private void analyzeMethodBody(ClassDescriptor cd, MethodDescriptor md) {
3833 BlockNode bn = state.getMethodBody(md);
3834 NodeTupleSet implicitFlowTupleSet = new NodeTupleSet();
3835 analyzeFlowBlockNode(md, md.getParameterTable(), bn, implicitFlowTupleSet);
3838 private void analyzeFlowBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn,
3839 NodeTupleSet implicitFlowTupleSet) {
3841 bn.getVarTable().setParent(nametable);
3842 for (int i = 0; i < bn.size(); i++) {
3843 BlockStatementNode bsn = bn.get(i);
3844 analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
3849 private void analyzeBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
3850 BlockStatementNode bsn, NodeTupleSet implicitFlowTupleSet) {
3852 switch (bsn.kind()) {
3853 case Kind.BlockExpressionNode:
3854 analyzeBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, implicitFlowTupleSet);
3857 case Kind.DeclarationNode:
3858 analyzeFlowDeclarationNode(md, nametable, (DeclarationNode) bsn, implicitFlowTupleSet);
3861 case Kind.IfStatementNode:
3862 analyzeFlowIfStatementNode(md, nametable, (IfStatementNode) bsn, implicitFlowTupleSet);
3866 analyzeFlowLoopNode(md, nametable, (LoopNode) bsn, implicitFlowTupleSet);
3869 case Kind.ReturnNode:
3870 analyzeFlowReturnNode(md, nametable, (ReturnNode) bsn, implicitFlowTupleSet);
3873 case Kind.SubBlockNode:
3874 analyzeFlowSubBlockNode(md, nametable, (SubBlockNode) bsn, implicitFlowTupleSet);
3877 case Kind.ContinueBreakNode:
3880 case Kind.SwitchStatementNode:
3881 analyzeSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, implicitFlowTupleSet);
3888 private void analyzeSwitchBlockNode(MethodDescriptor md, SymbolTable nametable,
3889 SwitchBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
3891 analyzeFlowBlockNode(md, nametable, sbn.getSwitchBlockStatement(), implicitFlowTupleSet);
3895 private void analyzeSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
3896 SwitchStatementNode ssn, NodeTupleSet implicitFlowTupleSet) {
3898 NodeTupleSet condTupleNode = new NodeTupleSet();
3899 analyzeFlowExpressionNode(md, nametable, ssn.getCondition(), condTupleNode, null,
3900 implicitFlowTupleSet, false);
3902 NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
3904 newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
3905 newImplicitTupleSet.addTupleSet(condTupleNode);
3907 if (newImplicitTupleSet.size() > 1) {
3908 // need to create an intermediate node for the GLB of conditional
3909 // locations & implicit flows
3910 NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
3911 for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter.hasNext();) {
3912 NTuple<Descriptor> tuple = idxIter.next();
3913 addFlowGraphEdge(md, tuple, interTuple);
3915 newImplicitTupleSet.clear();
3916 newImplicitTupleSet.addTuple(interTuple);
3919 BlockNode sbn = ssn.getSwitchBody();
3920 for (int i = 0; i < sbn.size(); i++) {
3921 analyzeSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), newImplicitTupleSet);
3926 private void analyzeFlowSubBlockNode(MethodDescriptor md, SymbolTable nametable,
3927 SubBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
3928 analyzeFlowBlockNode(md, nametable, sbn.getBlockNode(), implicitFlowTupleSet);
3931 private void analyzeFlowReturnNode(MethodDescriptor md, SymbolTable nametable, ReturnNode rn,
3932 NodeTupleSet implicitFlowTupleSet) {
3934 ExpressionNode returnExp = rn.getReturnExpression();
3936 if (returnExp != null) {
3937 NodeTupleSet nodeSet = new NodeTupleSet();
3938 // if a return expression returns a literal value, nodeSet is empty
3939 analyzeFlowExpressionNode(md, nametable, returnExp, nodeSet, false);
3940 FlowGraph fg = getFlowGraph(md);
3942 // if (implicitFlowTupleSet.size() == 1
3944 // fg.getFlowNode(implicitFlowTupleSet.iterator().next()).isIntermediate())
3947 // // since there is already an intermediate node for the GLB of implicit
3949 // // we don't need to create another intermediate node.
3950 // // just re-use the intermediate node for implicit flows.
3952 // FlowNode meetNode =
3953 // fg.getFlowNode(implicitFlowTupleSet.iterator().next());
3955 // for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
3956 // NTuple<Descriptor> returnNodeTuple = (NTuple<Descriptor>)
3958 // fg.addValueFlowEdge(returnNodeTuple, meetNode.getDescTuple());
3963 NodeTupleSet currentFlowTupleSet = new NodeTupleSet();
3965 // add tuples from return node
3966 currentFlowTupleSet.addTupleSet(nodeSet);
3968 // add tuples corresponding to the current implicit flows
3969 currentFlowTupleSet.addTupleSet(implicitFlowTupleSet);
3971 if (currentFlowTupleSet.size() > 1) {
3972 FlowNode meetNode = fg.createIntermediateNode();
3973 for (Iterator iterator = currentFlowTupleSet.iterator(); iterator.hasNext();) {
3974 NTuple<Descriptor> currentFlowTuple = (NTuple<Descriptor>) iterator.next();
3975 fg.addValueFlowEdge(currentFlowTuple, meetNode.getDescTuple());
3977 fg.addReturnFlowNode(meetNode.getDescTuple());
3978 } else if (currentFlowTupleSet.size() == 1) {
3979 NTuple<Descriptor> tuple = currentFlowTupleSet.iterator().next();
3980 fg.addReturnFlowNode(tuple);
3987 private void analyzeFlowLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln,
3988 NodeTupleSet implicitFlowTupleSet) {
3990 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
3992 NodeTupleSet condTupleNode = new NodeTupleSet();
3993 analyzeFlowExpressionNode(md, nametable, ln.getCondition(), condTupleNode, null,
3994 implicitFlowTupleSet, false);
3996 NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
3998 newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
3999 newImplicitTupleSet.addTupleSet(condTupleNode);
4001 if (newImplicitTupleSet.size() > 1) {
4002 // need to create an intermediate node for the GLB of conditional
4003 // locations & implicit flows
4004 NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4005 for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter
4007 NTuple<Descriptor> tuple = idxIter.next();
4008 addFlowGraphEdge(md, tuple, interTuple);
4010 newImplicitTupleSet.clear();
4011 newImplicitTupleSet.addTuple(interTuple);
4016 // System.out.println("condTupleNode="+condTupleNode);
4017 // NTuple<Descriptor> interTuple =
4018 // getFlowGraph(md).createIntermediateNode().getDescTuple();
4020 // for (Iterator<NTuple<Descriptor>> idxIter = condTupleNode.iterator();
4021 // idxIter.hasNext();) {
4022 // NTuple<Descriptor> tuple = idxIter.next();
4023 // addFlowGraphEdge(md, tuple, interTuple);
4026 // for (Iterator<NTuple<Descriptor>> idxIter =
4027 // implicitFlowTupleSet.iterator(); idxIter
4029 // NTuple<Descriptor> tuple = idxIter.next();
4030 // addFlowGraphEdge(md, tuple, interTuple);
4033 // NodeTupleSet newImplicitSet = new NodeTupleSet();
4034 // newImplicitSet.addTuple(interTuple);
4035 analyzeFlowBlockNode(md, nametable, ln.getBody(), newImplicitTupleSet);
4038 // condTupleNode.addTupleSet(implicitFlowTupleSet);
4040 // add edges from condNodeTupleSet to all nodes of conditional nodes
4041 // analyzeFlowBlockNode(md, nametable, ln.getBody(), condTupleNode);
4044 // check 'for loop' case
4045 BlockNode bn = ln.getInitializer();
4046 bn.getVarTable().setParent(nametable);
4047 for (int i = 0; i < bn.size(); i++) {
4048 BlockStatementNode bsn = bn.get(i);
4049 analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
4052 NodeTupleSet condTupleNode = new NodeTupleSet();
4053 analyzeFlowExpressionNode(md, bn.getVarTable(), ln.getCondition(), condTupleNode, null,
4054 implicitFlowTupleSet, false);
4057 NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4059 for (Iterator<NTuple<Descriptor>> idxIter = condTupleNode.iterator(); idxIter.hasNext();) {
4060 NTuple<Descriptor> tuple = idxIter.next();
4061 addFlowGraphEdge(md, tuple, interTuple);
4064 for (Iterator<NTuple<Descriptor>> idxIter = implicitFlowTupleSet.iterator(); idxIter
4066 NTuple<Descriptor> tuple = idxIter.next();
4067 addFlowGraphEdge(md, tuple, interTuple);
4070 NodeTupleSet newImplicitSet = new NodeTupleSet();
4071 newImplicitSet.addTuple(interTuple);
4072 analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(), newImplicitSet);
4073 analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(), newImplicitSet);
4076 // condTupleNode.addTupleSet(implicitFlowTupleSet);
4078 // analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(),
4080 // analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(),
4087 private void analyzeFlowIfStatementNode(MethodDescriptor md, SymbolTable nametable,
4088 IfStatementNode isn, NodeTupleSet implicitFlowTupleSet) {
4090 System.out.println("analyzeFlowIfStatementNode=" + isn.printNode(0));
4092 NodeTupleSet condTupleNode = new NodeTupleSet();
4093 analyzeFlowExpressionNode(md, nametable, isn.getCondition(), condTupleNode, null,
4094 implicitFlowTupleSet, false);
4096 NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
4098 newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
4099 newImplicitTupleSet.addTupleSet(condTupleNode);
4101 System.out.println("condTupleNode=" + condTupleNode);
4102 System.out.println("implicitFlowTupleSet=" + implicitFlowTupleSet);
4103 System.out.println("newImplicitTupleSet=" + newImplicitTupleSet);
4105 if (newImplicitTupleSet.size() > 1) {
4107 // need to create an intermediate node for the GLB of conditional locations & implicit flows
4108 NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4109 for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter.hasNext();) {
4110 NTuple<Descriptor> tuple = idxIter.next();
4111 addFlowGraphEdge(md, tuple, interTuple);
4113 newImplicitTupleSet.clear();
4114 newImplicitTupleSet.addTuple(interTuple);
4117 analyzeFlowBlockNode(md, nametable, isn.getTrueBlock(), newImplicitTupleSet);
4119 if (isn.getFalseBlock() != null) {
4120 analyzeFlowBlockNode(md, nametable, isn.getFalseBlock(), newImplicitTupleSet);
4125 private void analyzeFlowDeclarationNode(MethodDescriptor md, SymbolTable nametable,
4126 DeclarationNode dn, NodeTupleSet implicitFlowTupleSet) {
4128 VarDescriptor vd = dn.getVarDescriptor();
4129 mapDescToDefinitionLine.put(vd, dn.getNumLine());
4130 NTuple<Descriptor> tupleLHS = new NTuple<Descriptor>();
4132 FlowNode fn = getFlowGraph(md).createNewFlowNode(tupleLHS);
4133 fn.setDeclarationNode();
4135 if (dn.getExpression() != null) {
4137 NodeTupleSet nodeSetRHS = new NodeTupleSet();
4138 analyzeFlowExpressionNode(md, nametable, dn.getExpression(), nodeSetRHS, null,
4139 implicitFlowTupleSet, false);
4141 // creates edges from RHS to LHS
4142 NTuple<Descriptor> interTuple = null;
4143 if (nodeSetRHS.size() > 1) {
4144 interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4147 for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
4148 NTuple<Descriptor> fromTuple = iter.next();
4149 addFlowGraphEdge(md, fromTuple, interTuple, tupleLHS);
4152 // creates edges from implicitFlowTupleSet to LHS
4153 for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
4154 NTuple<Descriptor> implicitTuple = iter.next();
4155 addFlowGraphEdge(md, implicitTuple, tupleLHS);
4162 private void analyzeBlockExpressionNode(MethodDescriptor md, SymbolTable nametable,
4163 BlockExpressionNode ben, NodeTupleSet implicitFlowTupleSet) {
4164 analyzeFlowExpressionNode(md, nametable, ben.getExpression(), null, null, implicitFlowTupleSet,
4168 private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
4169 ExpressionNode en, NodeTupleSet nodeSet, boolean isLHS) {
4170 return analyzeFlowExpressionNode(md, nametable, en, nodeSet, null, new NodeTupleSet(), isLHS);
4173 private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
4174 ExpressionNode en, NodeTupleSet nodeSet, NTuple<Descriptor> base,
4175 NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
4177 // note that expression node can create more than one flow node
4178 // nodeSet contains of flow nodes
4179 // base is always assigned to null except the case of a name node!
4181 NTuple<Descriptor> flowTuple;
4183 switch (en.kind()) {
4185 case Kind.AssignmentNode:
4186 analyzeFlowAssignmentNode(md, nametable, (AssignmentNode) en, nodeSet, base,
4187 implicitFlowTupleSet);
4190 case Kind.FieldAccessNode:
4192 analyzeFlowFieldAccessNode(md, nametable, (FieldAccessNode) en, nodeSet, base,
4193 implicitFlowTupleSet, isLHS);
4194 if (flowTuple != null) {
4195 nodeSet.addTuple(flowTuple);
4200 NodeTupleSet nameNodeSet = new NodeTupleSet();
4202 analyzeFlowNameNode(md, nametable, (NameNode) en, nameNodeSet, base, implicitFlowTupleSet);
4203 if (flowTuple != null) {
4204 nodeSet.addTuple(flowTuple);
4209 analyzeFlowOpNode(md, nametable, (OpNode) en, nodeSet, implicitFlowTupleSet);
4212 case Kind.CreateObjectNode:
4213 analyzeCreateObjectNode(md, nametable, (CreateObjectNode) en);
4216 case Kind.ArrayAccessNode:
4217 analyzeFlowArrayAccessNode(md, nametable, (ArrayAccessNode) en, nodeSet, isLHS);
4220 case Kind.LiteralNode:
4221 analyzeLiteralNode(md, nametable, (LiteralNode) en);
4224 case Kind.MethodInvokeNode:
4225 analyzeFlowMethodInvokeNode(md, nametable, (MethodInvokeNode) en, nodeSet,
4226 implicitFlowTupleSet);
4229 case Kind.TertiaryNode:
4230 analyzeFlowTertiaryNode(md, nametable, (TertiaryNode) en, nodeSet, implicitFlowTupleSet);
4234 analyzeFlowCastNode(md, nametable, (CastNode) en, nodeSet, base, implicitFlowTupleSet);
4236 // case Kind.InstanceOfNode:
4237 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
4240 // case Kind.ArrayInitializerNode:
4241 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
4245 // case Kind.ClassTypeNode:
4246 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
4249 // case Kind.OffsetNode:
4250 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
4258 private void analyzeFlowCastNode(MethodDescriptor md, SymbolTable nametable, CastNode cn,
4259 NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
4261 analyzeFlowExpressionNode(md, nametable, cn.getExpression(), nodeSet, base,
4262 implicitFlowTupleSet, false);
4266 private void analyzeFlowTertiaryNode(MethodDescriptor md, SymbolTable nametable, TertiaryNode tn,
4267 NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
4269 NodeTupleSet tertiaryTupleNode = new NodeTupleSet();
4270 analyzeFlowExpressionNode(md, nametable, tn.getCond(), tertiaryTupleNode, null,
4271 implicitFlowTupleSet, false);
4273 // add edges from tertiaryTupleNode to all nodes of conditional nodes
4274 tertiaryTupleNode.addTupleSet(implicitFlowTupleSet);
4275 analyzeFlowExpressionNode(md, nametable, tn.getTrueExpr(), tertiaryTupleNode, null,
4276 implicitFlowTupleSet, false);
4278 analyzeFlowExpressionNode(md, nametable, tn.getFalseExpr(), tertiaryTupleNode, null,
4279 implicitFlowTupleSet, false);
4281 nodeSet.addTupleSet(tertiaryTupleNode);
4285 private void addMapCallerMethodDescToMethodInvokeNodeSet(MethodDescriptor caller,
4286 MethodInvokeNode min) {
4287 Set<MethodInvokeNode> set = mapMethodDescriptorToMethodInvokeNodeSet.get(caller);
4289 set = new HashSet<MethodInvokeNode>();
4290 mapMethodDescriptorToMethodInvokeNodeSet.put(caller, set);
4295 private void addParamNodeFlowingToReturnValue(MethodDescriptor md, FlowNode fn) {
4297 if (!mapMethodDescToParamNodeFlowsToReturnValue.containsKey(md)) {
4298 mapMethodDescToParamNodeFlowsToReturnValue.put(md, new HashSet<FlowNode>());
4300 mapMethodDescToParamNodeFlowsToReturnValue.get(md).add(fn);
4303 private Set<FlowNode> getParamNodeFlowingToReturnValue(MethodDescriptor md) {
4305 if (!mapMethodDescToParamNodeFlowsToReturnValue.containsKey(md)) {
4306 mapMethodDescToParamNodeFlowsToReturnValue.put(md, new HashSet<FlowNode>());
4309 return mapMethodDescToParamNodeFlowsToReturnValue.get(md);
4312 private void analyzeFlowMethodInvokeNode(MethodDescriptor md, SymbolTable nametable,
4313 MethodInvokeNode min, NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
4315 System.out.println("analyzeFlowMethodInvokeNode=" + min.printNode(0));
4317 mapMethodInvokeNodeToArgIdxMap.put(min, new HashMap<Integer, NTuple<Descriptor>>());
4319 if (nodeSet == null) {
4320 nodeSet = new NodeTupleSet();
4323 MethodDescriptor calleeMethodDesc = min.getMethod();
4325 NameDescriptor baseName = min.getBaseName();
4326 boolean isSystemout = false;
4327 if (baseName != null) {
4328 isSystemout = baseName.getSymbol().equals("System.out");
4331 if (!ssjava.isSSJavaUtil(calleeMethodDesc.getClassDesc())
4332 && !ssjava.isTrustMethod(calleeMethodDesc) && !isSystemout) {
4334 addMapCallerMethodDescToMethodInvokeNodeSet(md, min);
4336 FlowGraph calleeFlowGraph = getFlowGraph(calleeMethodDesc);
4337 Set<FlowNode> calleeReturnSet = calleeFlowGraph.getReturnNodeSet();
4339 System.out.println("-calleeReturnSet=" + calleeReturnSet);
4341 if (min.getExpression() != null) {
4343 NodeTupleSet baseNodeSet = new NodeTupleSet();
4344 analyzeFlowExpressionNode(md, nametable, min.getExpression(), baseNodeSet, null,
4345 implicitFlowTupleSet, false);
4347 assert (baseNodeSet.size() == 1);
4348 NTuple<Descriptor> baseTuple = baseNodeSet.iterator().next();
4349 mapMethodInvokeNodeToBaseTuple.put(min, baseTuple);
4351 if (!min.getMethod().isStatic()) {
4352 addArgIdxMap(min, 0, baseTuple);
4354 for (Iterator iterator = calleeReturnSet.iterator(); iterator.hasNext();) {
4355 FlowNode returnNode = (FlowNode) iterator.next();
4356 NTuple<Descriptor> returnDescTuple = returnNode.getDescTuple();
4357 if (returnDescTuple.startsWith(calleeMethodDesc.getThis())) {
4358 // the location type of the return value is started with 'this'
4360 NTuple<Descriptor> inFlowTuple = new NTuple<Descriptor>(baseTuple.getList());
4361 inFlowTuple.addAll(returnDescTuple.subList(1, returnDescTuple.size()));
4362 nodeSet.addTuple(inFlowTuple);
4365 Set<FlowNode> inFlowSet = calleeFlowGraph.getIncomingFlowNodeSet(returnNode);
4366 System.out.println("inFlowSet=" + inFlowSet + " from retrunNode=" + returnNode);
4367 for (Iterator iterator2 = inFlowSet.iterator(); iterator2.hasNext();) {
4368 FlowNode inFlowNode = (FlowNode) iterator2.next();
4369 if (inFlowNode.getDescTuple().startsWith(calleeMethodDesc.getThis())) {
4370 nodeSet.addTupleSet(baseNodeSet);
4379 // analyze parameter flows
4381 if (min.numArgs() > 0) {
4384 if (min.getMethod().isStatic()) {
4390 for (int i = 0; i < min.numArgs(); i++) {
4391 ExpressionNode en = min.getArg(i);
4392 int idx = i + offset;
4393 NodeTupleSet argTupleSet = new NodeTupleSet();
4394 analyzeFlowExpressionNode(md, nametable, en, argTupleSet, false);
4395 // if argument is liternal node, argTuple is set to NULL
4397 NTuple<Descriptor> argTuple = new NTuple<Descriptor>();
4398 System.out.println("-argTupleSet=" + argTupleSet + " from en=" + en.printNode(0));
4399 if (argTupleSet.size() > 1) {
4400 NTuple<Descriptor> interTuple =
4401 getFlowGraph(md).createIntermediateNode().getDescTuple();
4402 for (Iterator<NTuple<Descriptor>> idxIter = argTupleSet.iterator(); idxIter.hasNext();) {
4403 NTuple<Descriptor> tuple = idxIter.next();
4404 addFlowGraphEdge(md, tuple, interTuple);
4406 argTuple = interTuple;
4407 } else if (argTupleSet.size() == 1) {
4408 argTuple = argTupleSet.iterator().next();
4410 argTuple = new NTuple<Descriptor>();
4413 addArgIdxMap(min, idx, argTuple);
4415 FlowNode paramNode = calleeFlowGraph.getParamFlowNode(idx);
4416 System.out.println("-paramNode=" + paramNode + " hasInFlowTo="
4417 + hasInFlowTo(calleeFlowGraph, paramNode, calleeReturnSet));
4419 if (hasInFlowTo(calleeFlowGraph, paramNode, calleeReturnSet)
4420 || calleeMethodDesc.getModifiers().isNative()) {
4421 addParamNodeFlowingToReturnValue(calleeMethodDesc, paramNode);
4422 nodeSet.addTupleSet(argTupleSet);
4428 // propagateFlowsFromCallee(min, md, min.getMethod());
4430 System.out.println("min nodeSet=" + nodeSet);
4435 private boolean hasInFlowTo(FlowGraph fg, FlowNode inNode, Set<FlowNode> nodeSet) {
4436 // return true if inNode has in-flows to nodeSet
4438 // Set<FlowNode> reachableSet = fg.getReachFlowNodeSetFrom(inNode);
4439 Set<FlowNode> reachableSet = fg.getReachableSetFrom(inNode.getDescTuple());
4440 System.out.println("inNode=" + inNode + " reachalbeSet=" + reachableSet);
4442 for (Iterator iterator = reachableSet.iterator(); iterator.hasNext();) {
4443 FlowNode fn = (FlowNode) iterator.next();
4444 if (nodeSet.contains(fn)) {
4451 private NTuple<Descriptor> getNodeTupleByArgIdx(MethodInvokeNode min, int idx) {
4452 return mapMethodInvokeNodeToArgIdxMap.get(min).get(new Integer(idx));
4455 private void addArgIdxMap(MethodInvokeNode min, int idx, NTuple<Descriptor> argTuple /*
4459 Map<Integer, NTuple<Descriptor>> mapIdxToTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
4460 if (mapIdxToTuple == null) {
4461 mapIdxToTuple = new HashMap<Integer, NTuple<Descriptor>>();
4462 mapMethodInvokeNodeToArgIdxMap.put(min, mapIdxToTuple);
4464 mapIdxToTuple.put(new Integer(idx), argTuple);
4467 private void analyzeLiteralNode(MethodDescriptor md, SymbolTable nametable, LiteralNode en) {
4471 private void analyzeFlowArrayAccessNode(MethodDescriptor md, SymbolTable nametable,
4472 ArrayAccessNode aan, NodeTupleSet nodeSet, boolean isLHS) {
4474 NodeTupleSet expNodeTupleSet = new NodeTupleSet();
4475 NTuple<Descriptor> base =
4476 analyzeFlowExpressionNode(md, nametable, aan.getExpression(), expNodeTupleSet, isLHS);
4478 NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
4479 analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, isLHS);
4482 // need to create an edge from idx to array
4483 for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
4484 NTuple<Descriptor> idxTuple = idxIter.next();
4485 for (Iterator<NTuple<Descriptor>> arrIter = expNodeTupleSet.iterator(); arrIter.hasNext();) {
4486 NTuple<Descriptor> arrTuple = arrIter.next();
4487 getFlowGraph(md).addValueFlowEdge(idxTuple, arrTuple);
4491 nodeSet.addTupleSet(expNodeTupleSet);
4493 nodeSet.addTupleSet(expNodeTupleSet);
4494 nodeSet.addTupleSet(idxNodeTupleSet);
4498 private void analyzeCreateObjectNode(MethodDescriptor md, SymbolTable nametable,
4499 CreateObjectNode en) {
4500 // TODO Auto-generated method stub
4504 private void analyzeFlowOpNode(MethodDescriptor md, SymbolTable nametable, OpNode on,
4505 NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
4507 NodeTupleSet leftOpSet = new NodeTupleSet();
4508 NodeTupleSet rightOpSet = new NodeTupleSet();
4511 analyzeFlowExpressionNode(md, nametable, on.getLeft(), leftOpSet, null, implicitFlowTupleSet,
4514 if (on.getRight() != null) {
4516 analyzeFlowExpressionNode(md, nametable, on.getRight(), rightOpSet, null,
4517 implicitFlowTupleSet, false);
4520 Operation op = on.getOp();
4522 switch (op.getOp()) {
4524 case Operation.UNARYPLUS:
4525 case Operation.UNARYMINUS:
4526 case Operation.LOGIC_NOT:
4528 nodeSet.addTupleSet(leftOpSet);
4531 case Operation.LOGIC_OR:
4532 case Operation.LOGIC_AND:
4533 case Operation.COMP:
4534 case Operation.BIT_OR:
4535 case Operation.BIT_XOR:
4536 case Operation.BIT_AND:
4537 case Operation.ISAVAILABLE:
4538 case Operation.EQUAL:
4539 case Operation.NOTEQUAL:
4546 case Operation.MULT:
4549 case Operation.LEFTSHIFT:
4550 case Operation.RIGHTSHIFT:
4551 case Operation.URIGHTSHIFT:
4553 // there are two operands
4554 nodeSet.addTupleSet(leftOpSet);
4555 nodeSet.addTupleSet(rightOpSet);
4559 throw new Error(op.toString());
4564 private NTuple<Descriptor> analyzeFlowNameNode(MethodDescriptor md, SymbolTable nametable,
4565 NameNode nn, NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
4567 // System.out.println("analyzeFlowNameNode=" + nn.printNode(0));
4570 base = new NTuple<Descriptor>();
4573 NameDescriptor nd = nn.getName();
4575 if (nd.getBase() != null) {
4577 analyzeFlowExpressionNode(md, nametable, nn.getExpression(), nodeSet, base,
4578 implicitFlowTupleSet, false);
4580 // base node has the top location
4584 String varname = nd.toString();
4585 if (varname.equals("this")) {
4587 base.add(md.getThis());
4591 Descriptor d = (Descriptor) nametable.get(varname);
4593 if (d instanceof VarDescriptor) {
4594 VarDescriptor vd = (VarDescriptor) d;
4596 } else if (d instanceof FieldDescriptor) {
4597 // the type of field descriptor has a location!
4598 FieldDescriptor fd = (FieldDescriptor) d;
4599 if (fd.isStatic()) {
4601 // if it is 'static final', no need to have flow node for the TOP
4605 // if 'static', assign the default GLOBAL LOCATION to the first
4606 // element of the tuple
4607 base.add(GLOBALDESC);
4610 // the location of field access starts from this, followed by field
4612 base.add(md.getThis());
4616 } else if (d == null) {
4617 // access static field
4618 base.add(GLOBALDESC);
4619 base.add(nn.getField());
4622 // FieldDescriptor fd = nn.getField();addFlowGraphEdge
4624 // MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
4625 // String globalLocId = localLattice.getGlobalLoc();
4626 // if (globalLocId == null) {
4628 // Error("Method lattice does not define global variable location at "
4629 // + generateErrorMessage(md.getClassDesc(), nn));
4631 // loc.addLocation(new Location(md, globalLocId));
4633 // Location fieldLoc = (Location) fd.getType().getExtension();
4634 // loc.addLocation(fieldLoc);
4640 getFlowGraph(md).createNewFlowNode(base);
4646 private NTuple<Descriptor> analyzeFlowFieldAccessNode(MethodDescriptor md, SymbolTable nametable,
4647 FieldAccessNode fan, NodeTupleSet nodeSet, NTuple<Descriptor> base,
4648 NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
4650 ExpressionNode left = fan.getExpression();
4651 TypeDescriptor ltd = left.getType();
4652 FieldDescriptor fd = fan.getField();
4654 String varName = null;
4655 if (left.kind() == Kind.NameNode) {
4656 NameDescriptor nd = ((NameNode) left).getName();
4657 varName = nd.toString();
4660 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
4661 // using a class name directly or access using this
4662 if (fd.isStatic() && fd.isFinal()) {
4667 NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
4669 if (left instanceof ArrayAccessNode) {
4671 ArrayAccessNode aan = (ArrayAccessNode) left;
4672 left = aan.getExpression();
4673 analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, base,
4674 implicitFlowTupleSet, isLHS);
4676 nodeSet.addTupleSet(idxNodeTupleSet);
4679 analyzeFlowExpressionNode(md, nametable, left, nodeSet, base, implicitFlowTupleSet, isLHS);
4682 // in this case, field is TOP location
4686 NTuple<Descriptor> flowFieldTuple = new NTuple<Descriptor>(base.toList());
4688 if (!left.getType().isPrimitive()) {
4690 if (!fd.getSymbol().equals("length")) {
4691 // array.length access, just have the location of the array
4692 flowFieldTuple.add(fd);
4693 nodeSet.removeTuple(base);
4697 getFlowGraph(md).createNewFlowNode(flowFieldTuple);
4700 for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
4701 NTuple<Descriptor> idxTuple = idxIter.next();
4702 getFlowGraph(md).addValueFlowEdge(idxTuple, flowFieldTuple);
4705 return flowFieldTuple;
4711 private void debug_printTreeNode(TreeNode tn) {
4713 System.out.println("DEBUG: " + tn.printNode(0) + " line#=" + tn.getNumLine());
4717 private void analyzeFlowAssignmentNode(MethodDescriptor md, SymbolTable nametable,
4718 AssignmentNode an, NodeTupleSet nodeSet, NTuple<Descriptor> base,
4719 NodeTupleSet implicitFlowTupleSet) {
4721 NodeTupleSet nodeSetRHS = new NodeTupleSet();
4722 NodeTupleSet nodeSetLHS = new NodeTupleSet();
4724 boolean postinc = true;
4725 if (an.getOperation().getBaseOp() == null
4726 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
4727 .getBaseOp().getOp() != Operation.POSTDEC)) {
4730 // if LHS is array access node, need to capture value flows between an array
4731 // and its index value
4732 analyzeFlowExpressionNode(md, nametable, an.getDest(), nodeSetLHS, null, implicitFlowTupleSet,
4736 // analyze value flows of rhs expression
4737 analyzeFlowExpressionNode(md, nametable, an.getSrc(), nodeSetRHS, null, implicitFlowTupleSet,
4740 // System.out.println("-analyzeFlowAssignmentNode=" + an.printNode(0));
4741 // System.out.println("-nodeSetLHS=" + nodeSetLHS);
4742 // System.out.println("-nodeSetRHS=" + nodeSetRHS);
4743 // System.out.println("-implicitFlowTupleSet=" + implicitFlowTupleSet);
4744 // System.out.println("-");
4746 if (an.getOperation().getOp() >= 2 && an.getOperation().getOp() <= 12) {
4747 // if assignment contains OP+EQ operator, creates edges from LHS to LHS
4749 for (Iterator<NTuple<Descriptor>> iter = nodeSetLHS.iterator(); iter.hasNext();) {
4750 NTuple<Descriptor> fromTuple = iter.next();
4751 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4752 NTuple<Descriptor> toTuple = iter2.next();
4753 addFlowGraphEdge(md, fromTuple, toTuple);
4758 // creates edges from RHS to LHS
4759 NTuple<Descriptor> interTuple = null;
4760 if (nodeSetRHS.size() > 1) {
4761 interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4764 for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
4765 NTuple<Descriptor> fromTuple = iter.next();
4766 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4767 NTuple<Descriptor> toTuple = iter2.next();
4768 addFlowGraphEdge(md, fromTuple, interTuple, toTuple);
4772 // creates edges from implicitFlowTupleSet to LHS
4773 for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
4774 NTuple<Descriptor> fromTuple = iter.next();
4775 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4776 NTuple<Descriptor> toTuple = iter2.next();
4777 addFlowGraphEdge(md, fromTuple, toTuple);
4784 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4785 NTuple<Descriptor> tuple = iter2.next();
4786 addFlowGraphEdge(md, tuple, tuple);
4789 // creates edges from implicitFlowTupleSet to LHS
4790 for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
4791 NTuple<Descriptor> fromTuple = iter.next();
4792 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4793 NTuple<Descriptor> toTuple = iter2.next();
4794 addFlowGraphEdge(md, fromTuple, toTuple);
4800 if (nodeSet != null) {
4801 nodeSet.addTupleSet(nodeSetLHS);
4805 public FlowGraph getFlowGraph(MethodDescriptor md) {
4806 return mapMethodDescriptorToFlowGraph.get(md);
4809 private boolean addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
4810 NTuple<Descriptor> to) {
4811 FlowGraph graph = getFlowGraph(md);
4812 graph.addValueFlowEdge(from, to);
4816 private void addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
4817 NTuple<Descriptor> inter, NTuple<Descriptor> to) {
4819 FlowGraph graph = getFlowGraph(md);
4821 if (inter != null) {
4822 graph.addValueFlowEdge(from, inter);
4823 graph.addValueFlowEdge(inter, to);
4825 graph.addValueFlowEdge(from, to);
4830 public void writeInferredLatticeDotFile(ClassDescriptor cd, HierarchyGraph simpleHierarchyGraph,
4831 SSJavaLattice<String> locOrder, String nameSuffix) {
4832 writeInferredLatticeDotFile(cd, null, simpleHierarchyGraph, locOrder, nameSuffix);
4835 public void writeInferredLatticeDotFile(ClassDescriptor cd, MethodDescriptor md,
4836 HierarchyGraph simpleHierarchyGraph, SSJavaLattice<String> locOrder, String nameSuffix) {
4838 String fileName = "lattice_";
4841 cd.getSymbol().replaceAll("[\\W_]", "") + "_" + md.toString().replaceAll("[\\W_]", "");
4843 fileName += cd.getSymbol().replaceAll("[\\W_]", "");
4846 fileName += nameSuffix;
4848 Set<Pair<String, String>> pairSet = locOrder.getOrderingPairSet();
4850 Set<String> addedLocSet = new HashSet<String>();
4852 if (pairSet.size() > 0) {
4854 BufferedWriter bw = new BufferedWriter(new FileWriter(fileName + ".dot"));
4856 bw.write("digraph " + fileName + " {\n");
4858 for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
4859 // pair is in the form of <higher, lower>
4860 Pair<String, String> pair = (Pair<String, String>) iterator.next();
4862 String highLocId = pair.getFirst();
4863 String lowLocId = pair.getSecond();
4865 if (!addedLocSet.contains(highLocId)) {
4866 addedLocSet.add(highLocId);
4867 drawNode(bw, locOrder, simpleHierarchyGraph, highLocId);
4870 if (!addedLocSet.contains(lowLocId)) {
4871 addedLocSet.add(lowLocId);
4872 drawNode(bw, locOrder, simpleHierarchyGraph, lowLocId);
4875 bw.write(highLocId + " -> " + lowLocId + ";\n");
4880 } catch (IOException e) {
4881 e.printStackTrace();
4888 private String convertMergeSetToString(HierarchyGraph graph, Set<HNode> mergeSet) {
4890 for (Iterator iterator = mergeSet.iterator(); iterator.hasNext();) {
4891 HNode merged = (HNode) iterator.next();
4892 if (merged.isMergeNode()) {
4893 str += convertMergeSetToString(graph, graph.getMapHNodetoMergeSet().get(merged));
4895 str += " " + merged.getName();
4901 private void drawNode(BufferedWriter bw, SSJavaLattice<String> lattice, HierarchyGraph graph,
4902 String locName) throws IOException {
4904 HNode node = graph.getHNode(locName);
4911 if (lattice.isSharedLoc(locName)) {
4912 prettyStr = locName + "*";
4914 prettyStr = locName;
4917 if (node.isMergeNode()) {
4918 Set<HNode> mergeSet = graph.getMapHNodetoMergeSet().get(node);
4919 prettyStr += ":" + convertMergeSetToString(graph, mergeSet);
4921 bw.write(locName + " [label=\"" + prettyStr + "\"]" + ";\n");
4924 public void _debug_printGraph() {
4925 Set<MethodDescriptor> keySet = mapMethodDescriptorToFlowGraph.keySet();
4927 for (Iterator<MethodDescriptor> iterator = keySet.iterator(); iterator.hasNext();) {
4928 MethodDescriptor md = (MethodDescriptor) iterator.next();
4929 FlowGraph fg = mapMethodDescriptorToFlowGraph.get(md);
4932 } catch (IOException e) {
4933 e.printStackTrace();
4941 class CyclicFlowException extends Exception {
4945 class InterDescriptor extends Descriptor {
4947 public InterDescriptor(String name) {