1 package Analysis.SSJava;
3 import java.io.IOException;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.Comparator;
7 import java.util.HashMap;
8 import java.util.HashSet;
9 import java.util.Iterator;
10 import java.util.LinkedList;
11 import java.util.List;
14 import java.util.Stack;
16 import IR.ClassDescriptor;
18 import IR.FieldDescriptor;
19 import IR.MethodDescriptor;
20 import IR.NameDescriptor;
23 import IR.SymbolTable;
24 import IR.TypeDescriptor;
25 import IR.VarDescriptor;
26 import IR.Tree.ArrayAccessNode;
27 import IR.Tree.AssignmentNode;
28 import IR.Tree.BlockExpressionNode;
29 import IR.Tree.BlockNode;
30 import IR.Tree.BlockStatementNode;
31 import IR.Tree.CastNode;
32 import IR.Tree.CreateObjectNode;
33 import IR.Tree.DeclarationNode;
34 import IR.Tree.ExpressionNode;
35 import IR.Tree.FieldAccessNode;
36 import IR.Tree.IfStatementNode;
38 import IR.Tree.LiteralNode;
39 import IR.Tree.LoopNode;
40 import IR.Tree.MethodInvokeNode;
41 import IR.Tree.NameNode;
42 import IR.Tree.OpNode;
43 import IR.Tree.ReturnNode;
44 import IR.Tree.SubBlockNode;
45 import IR.Tree.SwitchStatementNode;
46 import IR.Tree.TertiaryNode;
48 public class LocationInference {
51 SSJavaAnalysis ssjava;
53 List<ClassDescriptor> toanalyzeList;
54 List<MethodDescriptor> toanalyzeMethodList;
55 Map<MethodDescriptor, FlowGraph> mapMethodDescriptorToFlowGraph;
57 // map a method descriptor to its set of parameter descriptors
58 Map<MethodDescriptor, Set<Descriptor>> mapMethodDescriptorToParamDescSet;
60 // keep current descriptors to visit in fixed-point interprocedural analysis,
61 private Stack<MethodDescriptor> methodDescriptorsToVisitStack;
63 // map a class descriptor to a field lattice
64 private Map<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
66 // map a method descriptor to a method lattice
67 private Map<MethodDescriptor, SSJavaLattice<String>> md2lattice;
69 // map a method descriptor to the set of method invocation nodes which are
70 // invoked by the method descriptor
71 private Map<MethodDescriptor, Set<MethodInvokeNode>> mapMethodDescriptorToMethodInvokeNodeSet;
73 private Map<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>> mapMethodInvokeNodeToArgIdxMap;
75 private Map<MethodDescriptor, MethodLocationInfo> mapMethodDescToMethodLocationInfo;
77 private Map<ClassDescriptor, LocationInfo> mapClassToLocationInfo;
79 private Map<MethodDescriptor, Set<MethodDescriptor>> mapMethodDescToPossibleMethodDescSet;
83 public LocationInference(SSJavaAnalysis ssjava, State state) {
86 this.toanalyzeList = new ArrayList<ClassDescriptor>();
87 this.toanalyzeMethodList = new ArrayList<MethodDescriptor>();
88 this.mapMethodDescriptorToFlowGraph = new HashMap<MethodDescriptor, FlowGraph>();
89 this.cd2lattice = new HashMap<ClassDescriptor, SSJavaLattice<String>>();
90 this.md2lattice = new HashMap<MethodDescriptor, SSJavaLattice<String>>();
91 this.methodDescriptorsToVisitStack = new Stack<MethodDescriptor>();
92 this.mapMethodDescriptorToMethodInvokeNodeSet =
93 new HashMap<MethodDescriptor, Set<MethodInvokeNode>>();
94 this.mapMethodInvokeNodeToArgIdxMap =
95 new HashMap<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>>();
96 this.mapMethodDescToMethodLocationInfo = new HashMap<MethodDescriptor, MethodLocationInfo>();
97 this.mapMethodDescToPossibleMethodDescSet =
98 new HashMap<MethodDescriptor, Set<MethodDescriptor>>();
99 this.mapClassToLocationInfo = new HashMap<ClassDescriptor, LocationInfo>();
102 public void setupToAnalyze() {
103 SymbolTable classtable = state.getClassSymbolTable();
104 toanalyzeList.clear();
105 toanalyzeList.addAll(classtable.getValueSet());
106 Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
107 public int compare(ClassDescriptor o1, ClassDescriptor o2) {
108 return o1.getClassName().compareToIgnoreCase(o2.getClassName());
113 public void setupToAnalazeMethod(ClassDescriptor cd) {
115 SymbolTable methodtable = cd.getMethodTable();
116 toanalyzeMethodList.clear();
117 toanalyzeMethodList.addAll(methodtable.getValueSet());
118 Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
119 public int compare(MethodDescriptor o1, MethodDescriptor o2) {
120 return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
125 public boolean toAnalyzeMethodIsEmpty() {
126 return toanalyzeMethodList.isEmpty();
129 public boolean toAnalyzeIsEmpty() {
130 return toanalyzeList.isEmpty();
133 public ClassDescriptor toAnalyzeNext() {
134 return toanalyzeList.remove(0);
137 public MethodDescriptor toAnalyzeMethodNext() {
138 return toanalyzeMethodList.remove(0);
141 public void inference() {
143 // 1) construct value flow graph
144 constructFlowGraph();
146 // 2) construct lattices
151 debug_writeLatticeDotFile();
153 // 3) check properties
158 private void simplifyLattices() {
160 // generate lattice dot file
163 while (!toAnalyzeIsEmpty()) {
164 ClassDescriptor cd = toAnalyzeNext();
166 setupToAnalazeMethod(cd);
168 SSJavaLattice<String> classLattice = cd2lattice.get(cd);
169 if (classLattice != null) {
170 classLattice.removeRedundantEdges();
173 while (!toAnalyzeMethodIsEmpty()) {
174 MethodDescriptor md = toAnalyzeMethodNext();
175 if (ssjava.needTobeAnnotated(md)) {
176 SSJavaLattice<String> methodLattice = md2lattice.get(md);
177 if (methodLattice != null) {
178 methodLattice.removeRedundantEdges();
186 private void checkLattices() {
188 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
190 // current descriptors to visit in fixed-point interprocedural analysis,
192 // dependency in the call graph
193 methodDescriptorsToVisitStack.clear();
195 descriptorListToAnalyze.removeFirst();
197 Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
198 methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
200 while (!descriptorListToAnalyze.isEmpty()) {
201 MethodDescriptor md = descriptorListToAnalyze.removeFirst();
202 checkLatticesOfVirtualMethods(md);
207 private void debug_writeLatticeDotFile() {
208 // generate lattice dot file
212 while (!toAnalyzeIsEmpty()) {
213 ClassDescriptor cd = toAnalyzeNext();
215 setupToAnalazeMethod(cd);
217 SSJavaLattice<String> classLattice = cd2lattice.get(cd);
218 if (classLattice != null) {
219 ssjava.writeLatticeDotFile(cd, null, classLattice);
220 debug_printDescriptorToLocNameMapping(cd);
223 while (!toAnalyzeMethodIsEmpty()) {
224 MethodDescriptor md = toAnalyzeMethodNext();
225 if (ssjava.needTobeAnnotated(md)) {
226 SSJavaLattice<String> methodLattice = md2lattice.get(md);
227 if (methodLattice != null) {
228 ssjava.writeLatticeDotFile(cd, md, methodLattice);
229 debug_printDescriptorToLocNameMapping(md);
237 private void debug_printDescriptorToLocNameMapping(Descriptor desc) {
239 LocationInfo info = getLocationInfo(desc);
240 System.out.println("## " + desc + " ##");
241 System.out.println(info.getMapDescToInferLocation());
242 LocationInfo locInfo = getLocationInfo(desc);
243 System.out.println("mapping=" + locInfo.getMapLocSymbolToDescSet());
244 System.out.println("###################");
248 private void inferLattices() {
250 // do fixed-point analysis
252 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
254 // current descriptors to visit in fixed-point interprocedural analysis,
256 // dependency in the call graph
257 methodDescriptorsToVisitStack.clear();
259 descriptorListToAnalyze.removeFirst();
261 Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
262 methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
264 while (!descriptorListToAnalyze.isEmpty()) {
265 MethodDescriptor md = descriptorListToAnalyze.removeFirst();
266 methodDescriptorsToVisitStack.add(md);
269 // analyze scheduled methods until there are no more to visit
270 while (!methodDescriptorsToVisitStack.isEmpty()) {
271 // start to analyze leaf node
272 MethodDescriptor md = methodDescriptorsToVisitStack.pop();
274 SSJavaLattice<String> methodLattice =
275 new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM);
277 MethodLocationInfo methodInfo = new MethodLocationInfo(md);
279 System.out.println();
280 System.out.println("SSJAVA: Inferencing the lattice from " + md);
282 analyzeMethodLattice(md, methodLattice, methodInfo);
284 SSJavaLattice<String> prevMethodLattice = getMethodLattice(md);
285 MethodLocationInfo prevMethodInfo = getMethodLocationInfo(md);
287 if ((!methodLattice.equals(prevMethodLattice)) || (!methodInfo.equals(prevMethodInfo))) {
289 setMethodLattice(md, methodLattice);
290 setMethodLocInfo(md, methodInfo);
292 // results for callee changed, so enqueue dependents caller for
294 Iterator<MethodDescriptor> depsItr = ssjava.getDependents(md).iterator();
295 while (depsItr.hasNext()) {
296 MethodDescriptor methodNext = depsItr.next();
297 if (!methodDescriptorsToVisitStack.contains(methodNext)
298 && methodDescriptorToVistSet.contains(methodNext)) {
299 methodDescriptorsToVisitStack.add(methodNext);
309 private void setMethodLocInfo(MethodDescriptor md, MethodLocationInfo methodInfo) {
310 mapMethodDescToMethodLocationInfo.put(md, methodInfo);
313 private void checkLatticesOfVirtualMethods(MethodDescriptor md) {
315 if (!md.isStatic()) {
316 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
317 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
319 for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
320 MethodDescriptor mdCallee = (MethodDescriptor) iterator.next();
321 if (!md.equals(mdCallee)) {
322 checkConsistency(md, mdCallee);
330 private void checkConsistency(MethodDescriptor md1, MethodDescriptor md2) {
332 // check that two lattice have the same relations between parameters(+PC
335 MethodLocationInfo methodInfo1 = getMethodLocationInfo(md1);
337 SSJavaLattice<String> lattice1 = getMethodLattice(md1);
338 SSJavaLattice<String> lattice2 = getMethodLattice(md2);
340 Set<String> paramLocNameSet1 = methodInfo1.getParameterLocNameSet();
342 for (Iterator iterator = paramLocNameSet1.iterator(); iterator.hasNext();) {
343 String locName1 = (String) iterator.next();
344 for (Iterator iterator2 = paramLocNameSet1.iterator(); iterator2.hasNext();) {
345 String locName2 = (String) iterator2.next();
348 if (!locName1.equals(locName2)) {
350 boolean r1 = lattice1.isGreaterThan(locName1, locName2);
351 boolean r2 = lattice2.isGreaterThan(locName1, locName2);
354 throw new Error("The method " + md1 + " is not consistent with the method " + md2
355 + ".:: They have a different ordering relation between parameters " + locName1
356 + " and " + locName2 + ".");
365 private String getSymbol(int idx, FlowNode node) {
366 Descriptor desc = node.getDescTuple().get(idx);
367 return desc.getSymbol();
370 private Descriptor getDescriptor(int idx, FlowNode node) {
371 Descriptor desc = node.getDescTuple().get(idx);
375 private void analyzeMethodLattice(MethodDescriptor md, SSJavaLattice<String> methodLattice,
376 MethodLocationInfo methodInfo) {
378 // first take a look at method invocation nodes to newly added relations
380 analyzeLatticeMethodInvocationNode(md);
382 // grab the this location if the method use the 'this' reference
383 String thisLocSymbol = md.getThis().getSymbol();
384 // if (methodLattice.getKeySet().contains(thisLocSymbol)) {
385 methodInfo.setThisLocName(thisLocSymbol);
388 // visit each node of method flow graph
389 FlowGraph fg = getFlowGraph(md);
390 Set<FlowNode> nodeSet = fg.getNodeSet();
392 // for the method lattice, we need to look at the first element of
393 // NTuple<Descriptor>
394 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
395 FlowNode srcNode = (FlowNode) iterator.next();
397 Set<FlowEdge> outEdgeSet = srcNode.getOutEdgeSet();
398 for (Iterator iterator2 = outEdgeSet.iterator(); iterator2.hasNext();) {
399 FlowEdge outEdge = (FlowEdge) iterator2.next();
400 FlowNode dstNode = outEdge.getDst();
402 NTuple<Descriptor> srcNodeTuple = srcNode.getDescTuple();
403 NTuple<Descriptor> dstNodeTuple = dstNode.getDescTuple();
405 if (outEdge.getInitTuple().equals(srcNodeTuple)
406 && outEdge.getEndTuple().equals(dstNodeTuple)) {
408 if ((srcNodeTuple.size() > 1 && dstNodeTuple.size() > 1)
409 && srcNodeTuple.get(0).equals(dstNodeTuple.get(0))) {
411 // value flows between fields
412 VarDescriptor varDesc = (VarDescriptor) srcNodeTuple.get(0);
413 ClassDescriptor varClassDesc = varDesc.getType().getClassDesc();
414 extractRelationFromFieldFlows(varClassDesc, srcNode, dstNode, 1);
416 } else if (srcNodeTuple.size() == 1 || dstNodeTuple.size() == 1) {
417 // for the method lattice, we need to look at the first element of
418 // NTuple<Descriptor>
419 // in this case, take a look at connected nodes at the local level
420 addRelationToLattice(md, methodLattice, methodInfo, srcNode, dstNode);
423 if (!srcNode.getDescTuple().get(0).equals(dstNode.getDescTuple().get(0))) {
424 // in this case, take a look at connected nodes at the local level
425 addRelationToLattice(md, methodLattice, methodInfo, srcNode, dstNode);
427 Descriptor srcDesc = srcNode.getDescTuple().get(0);
428 Descriptor dstDesc = dstNode.getDescTuple().get(0);
429 recursivelyAddCompositeRelation(md, fg, methodInfo, srcNode, dstNode, srcDesc,
431 // recursiveAddRelationToLattice(1, md, srcNode, dstNode);
439 // calculate a return location
440 if (!md.getReturnType().isVoid()) {
441 Set<FlowNode> returnNodeSet = fg.getReturnNodeSet();
442 Set<String> returnVarSymbolSet = new HashSet<String>();
444 for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
445 FlowNode rtrNode = (FlowNode) iterator.next();
446 String localSymbol = rtrNode.getDescTuple().get(0).getSymbol();
447 returnVarSymbolSet.add(localSymbol);
450 String returnGLB = methodLattice.getGLB(returnVarSymbolSet);
451 if (returnGLB.equals(SSJavaAnalysis.BOTTOM)) {
452 // need to insert a new location in-between the bottom and all locations
453 // that is directly connected to the bottom
454 String returnNewLocationSymbol = "Loc" + (SSJavaLattice.seed++);
455 methodLattice.insertNewLocationAtOneLevelHigher(returnGLB, returnNewLocationSymbol);
456 methodInfo.setReturnLocName(returnNewLocationSymbol);
458 methodInfo.setReturnLocName(returnGLB);
464 private void recursiveAddRelationToLattice(int idx, MethodDescriptor md,
465 CompositeLocation srcInferLoc, CompositeLocation dstInferLoc) {
467 String srcLocSymbol = srcInferLoc.get(idx).getLocIdentifier();
468 String dstLocSymbol = dstInferLoc.get(idx).getLocIdentifier();
470 if (srcLocSymbol.equals(dstLocSymbol)) {
471 recursiveAddRelationToLattice(idx + 1, md, srcInferLoc, dstInferLoc);
474 Descriptor parentDesc = srcInferLoc.get(idx).getDescriptor();
475 LocationInfo locInfo = getLocationInfo(parentDesc);
477 addRelationHigherToLower(getLattice(parentDesc), getLocationInfo(parentDesc), srcLocSymbol,
483 private void analyzeLatticeMethodInvocationNode(MethodDescriptor mdCaller) {
485 // the transformation for a call site propagates all relations between
486 // parameters from the callee
487 // if the method is virtual, it also grab all relations from any possible
490 Set<MethodInvokeNode> setMethodInvokeNode =
491 mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
492 if (setMethodInvokeNode != null) {
494 for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
495 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
496 MethodDescriptor mdCallee = min.getMethod();
497 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
498 if (mdCallee.isStatic()) {
499 setPossibleCallees.add(mdCallee);
501 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(mdCallee));
504 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
505 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
506 propagateRelationToCaller(min, mdCaller, possibleMdCallee);
514 private void propagateRelationToCaller(MethodInvokeNode min, MethodDescriptor mdCaller,
515 MethodDescriptor possibleMdCallee) {
517 SSJavaLattice<String> calleeLattice = getMethodLattice(possibleMdCallee);
519 FlowGraph calleeFlowGraph = getFlowGraph(possibleMdCallee);
521 // find parameter node
522 Set<FlowNode> paramNodeSet = calleeFlowGraph.getParameterNodeSet();
524 for (Iterator iterator = paramNodeSet.iterator(); iterator.hasNext();) {
525 FlowNode paramFlowNode1 = (FlowNode) iterator.next();
527 for (Iterator iterator2 = paramNodeSet.iterator(); iterator2.hasNext();) {
528 FlowNode paramFlowNode2 = (FlowNode) iterator2.next();
530 String paramSymbol1 = getSymbol(0, paramFlowNode1);
531 String paramSymbol2 = getSymbol(0, paramFlowNode2);
532 // if two parameters have a relation, we need to propagate this relation
534 if (!(paramSymbol1.equals(paramSymbol2))
535 && calleeLattice.isComparable(paramSymbol1, paramSymbol2)) {
536 int higherLocIdxCallee;
537 int lowerLocIdxCallee;
538 if (calleeLattice.isGreaterThan(paramSymbol1, paramSymbol2)) {
539 higherLocIdxCallee = calleeFlowGraph.getParamIdx(paramFlowNode1.getDescTuple());
540 lowerLocIdxCallee = calleeFlowGraph.getParamIdx(paramFlowNode2.getDescTuple());
542 higherLocIdxCallee = calleeFlowGraph.getParamIdx(paramFlowNode2.getDescTuple());
543 lowerLocIdxCallee = calleeFlowGraph.getParamIdx(paramFlowNode1.getDescTuple());
546 NTuple<Descriptor> higherArg = getArgTupleByArgIdx(min, higherLocIdxCallee);
547 NTuple<Descriptor> lowerArg = getArgTupleByArgIdx(min, lowerLocIdxCallee);
549 addFlowGraphEdge(mdCaller, higherArg, lowerArg);
559 private LocationInfo getLocationInfo(Descriptor d) {
560 if (d instanceof MethodDescriptor) {
561 return getMethodLocationInfo((MethodDescriptor) d);
563 return getFieldLocationInfo((ClassDescriptor) d);
567 private MethodLocationInfo getMethodLocationInfo(MethodDescriptor md) {
569 if (!mapMethodDescToMethodLocationInfo.containsKey(md)) {
570 mapMethodDescToMethodLocationInfo.put(md, new MethodLocationInfo(md));
573 return mapMethodDescToMethodLocationInfo.get(md);
577 private LocationInfo getFieldLocationInfo(ClassDescriptor cd) {
579 if (!mapClassToLocationInfo.containsKey(cd)) {
580 mapClassToLocationInfo.put(cd, new LocationInfo(cd));
583 return mapClassToLocationInfo.get(cd);
587 private void addRelationToLattice(MethodDescriptor md, SSJavaLattice<String> methodLattice,
588 MethodLocationInfo methodInfo, FlowNode srcNode, FlowNode dstNode) {
590 System.out.println();
591 System.out.println("### addRelationToLattice src=" + srcNode + " dst=" + dstNode);
593 // add a new binary relation of dstNode < srcNode
594 FlowGraph flowGraph = getFlowGraph(md);
595 // MethodLocationInfo methodInfo = getMethodLocationInfo(md);
597 // String srcOriginSymbol = getSymbol(0, srcNode);
598 // String dstOriginSymbol = getSymbol(0, dstNode);
600 Descriptor srcDesc = getDescriptor(0, srcNode);
601 Descriptor dstDesc = getDescriptor(0, dstNode);
603 // consider a composite location case
604 boolean isSrcLocalVar = false;
605 boolean isDstLocalVar = false;
606 if (srcNode.getDescTuple().size() == 1) {
607 isSrcLocalVar = true;
610 if (dstNode.getDescTuple().size() == 1) {
611 isDstLocalVar = true;
614 boolean isAssignedCompositeLocation = false;
615 if (!methodInfo.getInferLocation(srcDesc).get(0).getLocIdentifier()
616 .equals(methodInfo.getThisLocName())) {
617 isAssignedCompositeLocation =
618 calculateCompositeLocation(flowGraph, methodLattice, methodInfo, srcNode);
621 String srcSymbol = methodInfo.getInferLocation(srcDesc).get(0).getLocIdentifier();
622 String dstSymbol = methodInfo.getInferLocation(dstDesc).get(0).getLocIdentifier();
625 if (srcNode.isParameter()) {
626 int paramIdx = flowGraph.getParamIdx(srcNode.getDescTuple());
627 methodInfo.addParameter(srcSymbol, srcDesc, paramIdx);
629 // methodInfo.addMappingOfLocNameToDescriptor(srcSymbol, srcDesc);
632 if (dstNode.isParameter()) {
633 int paramIdx = flowGraph.getParamIdx(dstNode.getDescTuple());
634 methodInfo.addParameter(dstSymbol, dstDesc, paramIdx);
636 // methodInfo.addMappingOfLocNameToDescriptor(dstSymbol, dstDesc);
639 if (!isAssignedCompositeLocation) {
640 // source does not have a composite location
641 if (!srcSymbol.equals(dstSymbol)) {
642 // add a local relation
643 if (!methodLattice.isGreaterThan(srcSymbol, dstSymbol)) {
644 // if the lattice does not have this relation, add it
645 addRelationHigherToLower(methodLattice, methodInfo, srcSymbol, dstSymbol);
646 // methodLattice.addRelationHigherToLower(srcSymbol, dstSymbol);
649 // if src and dst have the same local location...
651 recursivelyAddCompositeRelation(md, flowGraph, methodInfo, srcNode, dstNode, srcDesc,
657 // source variable has a composite location
658 if (methodInfo.getInferLocation(dstDesc).getSize() == 1) {
659 if (!srcSymbol.equals(dstSymbol)) {
660 addRelationHigherToLower(methodLattice, methodInfo, srcSymbol, dstSymbol);
669 private void recursivelyAddCompositeRelation(MethodDescriptor md, FlowGraph flowGraph,
670 MethodLocationInfo methodInfo, FlowNode srcNode, FlowNode dstNode, Descriptor srcDesc,
671 Descriptor dstDesc) {
673 CompositeLocation inferSrcLoc;
674 CompositeLocation inferDstLoc = methodInfo.getInferLocation(dstDesc);
676 if (srcNode.getDescTuple().size() > 1) {
678 inferSrcLoc = new CompositeLocation();
680 NTuple<Location> locTuple = flowGraph.getLocationTuple(srcNode);
681 for (int i = 0; i < locTuple.size(); i++) {
682 inferSrcLoc.addLocation(locTuple.get(i));
686 inferSrcLoc = methodInfo.getInferLocation(srcDesc);
689 if (dstNode.getDescTuple().size() > 1) {
691 inferDstLoc = new CompositeLocation();
693 NTuple<Location> locTuple = flowGraph.getLocationTuple(dstNode);
694 for (int i = 0; i < locTuple.size(); i++) {
695 inferDstLoc.addLocation(locTuple.get(i));
699 inferDstLoc = methodInfo.getInferLocation(dstDesc);
702 recursiveAddRelationToLattice(1, md, inferSrcLoc, inferDstLoc);
705 private void addPrefixMapping(Map<NTuple<Location>, Set<NTuple<Location>>> map,
706 NTuple<Location> prefix, NTuple<Location> element) {
708 if (!map.containsKey(prefix)) {
709 map.put(prefix, new HashSet<NTuple<Location>>());
711 map.get(prefix).add(element);
714 private boolean calculateCompositeLocation(FlowGraph flowGraph,
715 SSJavaLattice<String> methodLattice, MethodLocationInfo methodInfo, FlowNode flowNode) {
717 Descriptor localVarDesc = flowNode.getDescTuple().get(0);
719 Set<FlowNode> inNodeSet = flowGraph.getIncomingFlowNodeSet(flowNode);
720 Set<FlowNode> reachableNodeSet = flowGraph.getReachableFlowNodeSet(flowNode);
722 Map<NTuple<Location>, Set<NTuple<Location>>> mapPrefixToIncomingLocTupleSet =
723 new HashMap<NTuple<Location>, Set<NTuple<Location>>>();
725 Set<FlowNode> localInNodeSet = new HashSet<FlowNode>();
726 Set<FlowNode> localOutNodeSet = new HashSet<FlowNode>();
728 List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
730 for (Iterator iterator = inNodeSet.iterator(); iterator.hasNext();) {
731 FlowNode inNode = (FlowNode) iterator.next();
732 NTuple<Location> inTuple = flowGraph.getLocationTuple(inNode);
734 if (inTuple.size() > 1) {
735 for (int i = 1; i < inTuple.size(); i++) {
736 NTuple<Location> prefix = inTuple.subList(0, i);
737 if (!prefixList.contains(prefix)) {
738 prefixList.add(prefix);
740 addPrefixMapping(mapPrefixToIncomingLocTupleSet, prefix, inTuple);
743 localInNodeSet.add(inNode);
747 Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
748 public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
749 int s0 = arg0.size();
750 int s1 = arg1.size();
753 } else if (s0 == s1) {
762 for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
763 FlowNode reachableNode = (FlowNode) iterator2.next();
764 if (reachableNode.getDescTuple().size() == 1) {
765 localOutNodeSet.add(reachableNode);
769 // find out reachable nodes that have the longest common prefix
770 for (int i = 0; i < prefixList.size(); i++) {
771 NTuple<Location> curPrefix = prefixList.get(i);
772 Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
774 for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
775 FlowNode reachableNode = (FlowNode) iterator2.next();
776 NTuple<Location> reachLocTuple = flowGraph.getLocationTuple(reachableNode);
777 if (reachLocTuple.startsWith(curPrefix)) {
778 reachableCommonPrefixSet.add(reachLocTuple);
784 if (!reachableCommonPrefixSet.isEmpty()) {
785 // found reachable nodes that start with the prefix curPrefix
786 // need to assign a composite location
788 // first, check if there are more than one the set of locations that has
789 // the same length of the longest reachable prefix, no way to assign
790 // a composite location to the input local var
791 prefixSanityCheck(prefixList, i, flowGraph, reachableNodeSet);
793 Set<NTuple<Location>> incomingCommonPrefixSet =
794 mapPrefixToIncomingLocTupleSet.get(curPrefix);
796 int idx = curPrefix.size();
797 NTuple<Location> element = incomingCommonPrefixSet.iterator().next();
798 Descriptor desc = element.get(idx).getDescriptor();
800 SSJavaLattice<String> lattice = getLattice(desc);
801 LocationInfo locInfo = getLocationInfo(desc);
803 // CompositeLocation inferLocation =
804 // methodInfo.getInferLocation(flowNode);
805 CompositeLocation inferLocation = methodInfo.getInferLocation(localVarDesc);
807 String newlyInsertedLocName;
808 if (inferLocation.getSize() == 1) {
809 // need to replace the old local location with a new composite
812 String oldMethodLocationSymbol = inferLocation.get(0).getLocIdentifier();
814 String newLocSymbol = "Loc" + (SSJavaLattice.seed++);
815 inferLocation = new CompositeLocation();
816 for (int locIdx = 0; locIdx < curPrefix.size(); locIdx++) {
817 inferLocation.addLocation(curPrefix.get(locIdx));
819 Location fieldLoc = new Location(desc, newLocSymbol);
820 inferLocation.addLocation(fieldLoc);
823 methodInfo.mapDescriptorToLocation(localVarDesc, inferLocation);
824 methodInfo.removeMaplocalVarToLocSet(localVarDesc);
826 String newMethodLocationSymbol = curPrefix.get(0).getLocIdentifier();
828 replaceOldLocWithNewLoc(methodLattice, oldMethodLocationSymbol, newMethodLocationSymbol);
832 String localLocName = methodInfo.getInferLocation(localVarDesc).get(0).getLocIdentifier();
838 newlyInsertedLocName = inferLocation.get(inferLocation.getSize() - 1).getLocIdentifier();
840 for (Iterator iterator = incomingCommonPrefixSet.iterator(); iterator.hasNext();) {
841 NTuple<Location> tuple = (NTuple<Location>) iterator.next();
843 Location loc = tuple.get(idx);
844 String higher = locInfo.getFieldInferLocation(loc.getLocDescriptor()).getLocIdentifier();
845 System.out.println("here3");
847 addRelationHigherToLower(lattice, locInfo, higher, newlyInsertedLocName);
851 for (Iterator iterator = localInNodeSet.iterator(); iterator.hasNext();) {
852 FlowNode localNode = (FlowNode) iterator.next();
853 Descriptor localInVarDesc = localNode.getDescTuple().get(0);
854 CompositeLocation inNodeInferLoc = methodInfo.getInferLocation(localInVarDesc);
856 if (isCompositeLocation(inNodeInferLoc)) {
857 // need to make sure that newLocSymbol is lower than the infernode
858 // location in the field lattice
860 if (inNodeInferLoc.getTuple().startsWith(curPrefix)
861 && inNodeInferLoc.getSize() == (curPrefix.size() + 1)) {
862 String higher = inNodeInferLoc.get(inNodeInferLoc.getSize() - 1).getLocIdentifier();
863 if (!higher.equals(newlyInsertedLocName)) {
865 addRelationHigherToLower(lattice, locInfo, higher, newlyInsertedLocName);
868 throw new Error("Failed to generate a composite location.");
874 for (Iterator iterator = reachableCommonPrefixSet.iterator(); iterator.hasNext();) {
875 NTuple<Location> tuple = (NTuple<Location>) iterator.next();
876 Location loc = tuple.get(idx);
877 String lower = locInfo.getFieldInferLocation(loc.getLocDescriptor()).getLocIdentifier();
878 // lattice.addRelationHigherToLower(newlyInsertedLocName, lower);
880 addRelationHigherToLower(lattice, locInfo, newlyInsertedLocName, lower);
883 for (Iterator iterator = localOutNodeSet.iterator(); iterator.hasNext();) {
884 FlowNode localOutNode = (FlowNode) iterator.next();
886 Descriptor localOutDesc = localOutNode.getDescTuple().get(0);
887 // String localOutNodeSymbol =
888 // localOutNode.getDescTuple().get(0).getSymbol();
889 CompositeLocation outNodeInferLoc = methodInfo.getInferLocation(localOutDesc);
892 // .println("localOutNode=" + localOutNode + " outNodeInferLoc=" +
894 if (isCompositeLocation(outNodeInferLoc)) {
895 // need to make sure that newLocSymbol is higher than the infernode
898 if (outNodeInferLoc.getTuple().startsWith(curPrefix)
899 && outNodeInferLoc.getSize() == (curPrefix.size() + 1)) {
901 String lower = outNodeInferLoc.get(outNodeInferLoc.getSize() - 1).getLocIdentifier();
903 addRelationHigherToLower(lattice, locInfo, newlyInsertedLocName, lower);
906 throw new Error("Failed to generate a composite location.");
920 private boolean isCompositeLocation(CompositeLocation cl) {
921 return cl.getSize() > 1;
924 private boolean containsNonPrimitiveElement(Set<Descriptor> descSet) {
925 for (Iterator iterator = descSet.iterator(); iterator.hasNext();) {
926 Descriptor desc = (Descriptor) iterator.next();
928 if (desc instanceof VarDescriptor) {
929 if (!((VarDescriptor) desc).getType().isPrimitive()) {
932 } else if (desc instanceof FieldDescriptor) {
933 if (!((FieldDescriptor) desc).getType().isPrimitive()) {
942 private void addRelationHigherToLower(SSJavaLattice<String> lattice, LocationInfo locInfo,
943 String higher, String lower) {
945 Set<String> cycleElementSet = lattice.getPossibleCycleElements(higher, lower);
947 boolean hasNonPrimitiveElement = false;
948 for (Iterator iterator = cycleElementSet.iterator(); iterator.hasNext();) {
949 String cycleElementLocSymbol = (String) iterator.next();
951 Set<Descriptor> descSet = locInfo.getDescSet(cycleElementLocSymbol);
952 if (containsNonPrimitiveElement(descSet)) {
953 hasNonPrimitiveElement = true;
958 if (hasNonPrimitiveElement) {
959 // if there is non-primitive element in the cycle, no way to merge cyclic
960 // elements into the shared location
961 throw new Error("Failed to merge cyclic value flows into a shared location.");
964 if (cycleElementSet.size() > 0) {
965 String newSharedLoc = "SharedLoc" + (SSJavaLattice.seed++);
967 lattice.mergeIntoSharedLocation(cycleElementSet, newSharedLoc);
969 for (Iterator iterator = cycleElementSet.iterator(); iterator.hasNext();) {
970 String oldLocSymbol = (String) iterator.next();
971 locInfo.mergeMapping(oldLocSymbol, newSharedLoc);
975 } else if (!lattice.isGreaterThan(higher, lower)) {
976 lattice.addRelationHigherToLower(higher, lower);
980 private void replaceOldLocWithNewLoc(SSJavaLattice<String> methodLattice, String oldLocSymbol,
981 String newLocSymbol) {
983 if (methodLattice.containsKey(oldLocSymbol)) {
984 methodLattice.substituteLocation(oldLocSymbol, newLocSymbol);
989 private void prefixSanityCheck(List<NTuple<Location>> prefixList, int curIdx,
990 FlowGraph flowGraph, Set<FlowNode> reachableNodeSet) {
993 NTuple<Location> curPrefix = prefixList.get(curIdx);
995 for (int i = curIdx + 1; i < prefixList.size(); i++) {
996 NTuple<Location> prefixTuple = prefixList.get(i);
998 if (curPrefix.startsWith(prefixTuple)) {
1002 for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
1003 FlowNode reachableNode = (FlowNode) iterator2.next();
1004 NTuple<Location> reachLocTuple = flowGraph.getLocationTuple(reachableNode);
1005 if (reachLocTuple.startsWith(prefixTuple)) {
1007 throw new Error("Failed to generate a composite location");
1013 public boolean isPrimitiveLocalVariable(FlowNode node) {
1014 VarDescriptor varDesc = (VarDescriptor) node.getDescTuple().get(0);
1015 return varDesc.getType().isPrimitive();
1018 private SSJavaLattice<String> getLattice(Descriptor d) {
1019 if (d instanceof MethodDescriptor) {
1020 return getMethodLattice((MethodDescriptor) d);
1022 return getFieldLattice((ClassDescriptor) d);
1026 private SSJavaLattice<String> getMethodLattice(MethodDescriptor md) {
1027 if (!md2lattice.containsKey(md)) {
1028 md2lattice.put(md, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
1030 return md2lattice.get(md);
1033 private void setMethodLattice(MethodDescriptor md, SSJavaLattice<String> lattice) {
1034 md2lattice.put(md, lattice);
1037 private void extractRelationFromFieldFlows(ClassDescriptor cd, FlowNode srcNode,
1038 FlowNode dstNode, int idx) {
1041 if (srcNode.getDescTuple().get(idx).equals(dstNode.getDescTuple().get(idx))
1042 && srcNode.getDescTuple().size() > (idx + 1) && dstNode.getDescTuple().size() > (idx + 1)) {
1043 // value flow between fields: we don't need to add a binary relation
1046 Descriptor desc = srcNode.getDescTuple().get(idx);
1047 ClassDescriptor classDesc;
1050 classDesc = ((VarDescriptor) desc).getType().getClassDesc();
1052 classDesc = ((FieldDescriptor) desc).getType().getClassDesc();
1055 extractRelationFromFieldFlows(classDesc, srcNode, dstNode, idx + 1);
1059 Descriptor srcFieldDesc = srcNode.getDescTuple().get(idx);
1060 Descriptor dstFieldDesc = dstNode.getDescTuple().get(idx);
1062 // add a new binary relation of dstNode < srcNode
1063 SSJavaLattice<String> fieldLattice = getFieldLattice(cd);
1064 LocationInfo fieldInfo = getFieldLocationInfo(cd);
1067 String srcSymbol = fieldInfo.getFieldInferLocation(srcFieldDesc).getLocIdentifier();
1068 String dstSymbol = fieldInfo.getFieldInferLocation(dstFieldDesc).getLocIdentifier();
1070 addRelationHigherToLower(fieldLattice, fieldInfo, srcSymbol, dstSymbol);
1076 public SSJavaLattice<String> getFieldLattice(ClassDescriptor cd) {
1077 if (!cd2lattice.containsKey(cd)) {
1078 cd2lattice.put(cd, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
1080 return cd2lattice.get(cd);
1083 public void constructFlowGraph() {
1087 while (!toAnalyzeIsEmpty()) {
1088 ClassDescriptor cd = toAnalyzeNext();
1090 setupToAnalazeMethod(cd);
1091 while (!toAnalyzeMethodIsEmpty()) {
1092 MethodDescriptor md = toAnalyzeMethodNext();
1093 if (ssjava.needTobeAnnotated(md)) {
1094 if (state.SSJAVADEBUG) {
1095 System.out.println();
1096 System.out.println("SSJAVA: Constructing a flow graph: " + md);
1099 // creates a mapping from a method descriptor to virtual methods
1100 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
1101 if (md.isStatic()) {
1102 setPossibleCallees.add(md);
1104 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
1106 mapMethodDescToPossibleMethodDescSet.put(md, setPossibleCallees);
1108 // creates a mapping from a parameter descriptor to its index
1109 Map<Descriptor, Integer> mapParamDescToIdx = new HashMap<Descriptor, Integer>();
1110 int offset = md.isStatic() ? 0 : 1;
1111 for (int i = 0; i < md.numParameters(); i++) {
1112 Descriptor paramDesc = (Descriptor) md.getParameter(i);
1113 mapParamDescToIdx.put(paramDesc, new Integer(i + offset));
1116 FlowGraph fg = new FlowGraph(md, mapParamDescToIdx);
1117 mapMethodDescriptorToFlowGraph.put(md, fg);
1119 analyzeMethodBody(cd, md);
1124 _debug_printGraph();
1127 private void analyzeMethodBody(ClassDescriptor cd, MethodDescriptor md) {
1128 BlockNode bn = state.getMethodBody(md);
1129 NodeTupleSet implicitFlowTupleSet = new NodeTupleSet();
1130 analyzeFlowBlockNode(md, md.getParameterTable(), bn, implicitFlowTupleSet);
1133 private void analyzeFlowBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn,
1134 NodeTupleSet implicitFlowTupleSet) {
1136 bn.getVarTable().setParent(nametable);
1137 for (int i = 0; i < bn.size(); i++) {
1138 BlockStatementNode bsn = bn.get(i);
1139 analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
1144 private void analyzeBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
1145 BlockStatementNode bsn, NodeTupleSet implicitFlowTupleSet) {
1147 switch (bsn.kind()) {
1148 case Kind.BlockExpressionNode:
1149 analyzeBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, implicitFlowTupleSet);
1152 case Kind.DeclarationNode:
1153 analyzeFlowDeclarationNode(md, nametable, (DeclarationNode) bsn, implicitFlowTupleSet);
1156 case Kind.IfStatementNode:
1157 analyzeFlowIfStatementNode(md, nametable, (IfStatementNode) bsn, implicitFlowTupleSet);
1161 analyzeFlowLoopNode(md, nametable, (LoopNode) bsn, implicitFlowTupleSet);
1164 case Kind.ReturnNode:
1165 analyzeFlowReturnNode(md, nametable, (ReturnNode) bsn, implicitFlowTupleSet);
1168 case Kind.SubBlockNode:
1169 analyzeFlowSubBlockNode(md, nametable, (SubBlockNode) bsn, implicitFlowTupleSet);
1172 case Kind.ContinueBreakNode:
1175 case Kind.SwitchStatementNode:
1176 analyzeSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
1183 private void analyzeSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
1184 SwitchStatementNode bsn) {
1185 // TODO Auto-generated method stub
1188 private void analyzeFlowSubBlockNode(MethodDescriptor md, SymbolTable nametable,
1189 SubBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
1190 analyzeFlowBlockNode(md, nametable, sbn.getBlockNode(), implicitFlowTupleSet);
1193 private void analyzeFlowReturnNode(MethodDescriptor md, SymbolTable nametable, ReturnNode rn,
1194 NodeTupleSet implicitFlowTupleSet) {
1196 ExpressionNode returnExp = rn.getReturnExpression();
1198 NodeTupleSet nodeSet = new NodeTupleSet();
1199 analyzeFlowExpressionNode(md, nametable, returnExp, nodeSet, false);
1201 FlowGraph fg = getFlowGraph(md);
1203 // annotate the elements of the node set as the return location
1204 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1205 NTuple<Descriptor> returnDescTuple = (NTuple<Descriptor>) iterator.next();
1206 fg.setReturnFlowNode(returnDescTuple);
1207 for (Iterator iterator2 = implicitFlowTupleSet.iterator(); iterator2.hasNext();) {
1208 NTuple<Descriptor> implicitFlowDescTuple = (NTuple<Descriptor>) iterator2.next();
1209 fg.addValueFlowEdge(implicitFlowDescTuple, returnDescTuple);
1215 private void analyzeFlowLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln,
1216 NodeTupleSet implicitFlowTupleSet) {
1218 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
1220 NodeTupleSet condTupleNode = new NodeTupleSet();
1221 analyzeFlowExpressionNode(md, nametable, ln.getCondition(), condTupleNode, null,
1222 implicitFlowTupleSet, false);
1223 condTupleNode.addTupleSet(implicitFlowTupleSet);
1225 // add edges from condNodeTupleSet to all nodes of conditional nodes
1226 analyzeFlowBlockNode(md, nametable, ln.getBody(), condTupleNode);
1229 // check 'for loop' case
1230 BlockNode bn = ln.getInitializer();
1231 bn.getVarTable().setParent(nametable);
1232 for (int i = 0; i < bn.size(); i++) {
1233 BlockStatementNode bsn = bn.get(i);
1234 analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
1237 NodeTupleSet condTupleNode = new NodeTupleSet();
1238 analyzeFlowExpressionNode(md, bn.getVarTable(), ln.getCondition(), condTupleNode, null,
1239 implicitFlowTupleSet, false);
1240 condTupleNode.addTupleSet(implicitFlowTupleSet);
1242 analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(), condTupleNode);
1243 analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(), condTupleNode);
1249 private void analyzeFlowIfStatementNode(MethodDescriptor md, SymbolTable nametable,
1250 IfStatementNode isn, NodeTupleSet implicitFlowTupleSet) {
1252 NodeTupleSet condTupleNode = new NodeTupleSet();
1253 analyzeFlowExpressionNode(md, nametable, isn.getCondition(), condTupleNode, null,
1254 implicitFlowTupleSet, false);
1256 // add edges from condNodeTupleSet to all nodes of conditional nodes
1257 condTupleNode.addTupleSet(implicitFlowTupleSet);
1258 analyzeFlowBlockNode(md, nametable, isn.getTrueBlock(), condTupleNode);
1260 if (isn.getFalseBlock() != null) {
1261 analyzeFlowBlockNode(md, nametable, isn.getFalseBlock(), condTupleNode);
1266 private void analyzeFlowDeclarationNode(MethodDescriptor md, SymbolTable nametable,
1267 DeclarationNode dn, NodeTupleSet implicitFlowTupleSet) {
1269 VarDescriptor vd = dn.getVarDescriptor();
1270 NTuple<Descriptor> tupleLHS = new NTuple<Descriptor>();
1272 getFlowGraph(md).createNewFlowNode(tupleLHS);
1274 if (dn.getExpression() != null) {
1276 NodeTupleSet tupleSetRHS = new NodeTupleSet();
1277 analyzeFlowExpressionNode(md, nametable, dn.getExpression(), tupleSetRHS, null,
1278 implicitFlowTupleSet, false);
1280 // add a new flow edge from rhs to lhs
1281 for (Iterator<NTuple<Descriptor>> iter = tupleSetRHS.iterator(); iter.hasNext();) {
1282 NTuple<Descriptor> from = iter.next();
1283 addFlowGraphEdge(md, from, tupleLHS);
1290 private void analyzeBlockExpressionNode(MethodDescriptor md, SymbolTable nametable,
1291 BlockExpressionNode ben, NodeTupleSet implicitFlowTupleSet) {
1292 analyzeFlowExpressionNode(md, nametable, ben.getExpression(), null, null, implicitFlowTupleSet,
1296 private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
1297 ExpressionNode en, NodeTupleSet nodeSet, boolean isLHS) {
1298 return analyzeFlowExpressionNode(md, nametable, en, nodeSet, null, new NodeTupleSet(), isLHS);
1301 private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
1302 ExpressionNode en, NodeTupleSet nodeSet, NTuple<Descriptor> base,
1303 NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
1305 // note that expression node can create more than one flow node
1306 // nodeSet contains of flow nodes
1307 // base is always assigned to null except the case of a name node!
1309 NTuple<Descriptor> flowTuple;
1311 switch (en.kind()) {
1313 case Kind.AssignmentNode:
1314 analyzeFlowAssignmentNode(md, nametable, (AssignmentNode) en, base, implicitFlowTupleSet);
1317 case Kind.FieldAccessNode:
1319 analyzeFlowFieldAccessNode(md, nametable, (FieldAccessNode) en, nodeSet, base,
1320 implicitFlowTupleSet);
1321 nodeSet.addTuple(flowTuple);
1325 NodeTupleSet nameNodeSet = new NodeTupleSet();
1327 analyzeFlowNameNode(md, nametable, (NameNode) en, nameNodeSet, base, implicitFlowTupleSet);
1328 nodeSet.addTuple(flowTuple);
1332 analyzeFlowOpNode(md, nametable, (OpNode) en, nodeSet, implicitFlowTupleSet);
1335 case Kind.CreateObjectNode:
1336 analyzeCreateObjectNode(md, nametable, (CreateObjectNode) en);
1339 case Kind.ArrayAccessNode:
1340 analyzeFlowArrayAccessNode(md, nametable, (ArrayAccessNode) en, nodeSet, isLHS);
1343 case Kind.LiteralNode:
1344 analyzeLiteralNode(md, nametable, (LiteralNode) en);
1347 case Kind.MethodInvokeNode:
1348 analyzeFlowMethodInvokeNode(md, nametable, (MethodInvokeNode) en, implicitFlowTupleSet);
1351 case Kind.TertiaryNode:
1352 analyzeFlowTertiaryNode(md, nametable, (TertiaryNode) en, nodeSet, implicitFlowTupleSet);
1356 analyzeFlowCastNode(md, nametable, (CastNode) en, implicitFlowTupleSet);
1359 // case Kind.InstanceOfNode:
1360 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
1363 // case Kind.ArrayInitializerNode:
1364 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
1368 // case Kind.ClassTypeNode:
1369 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
1372 // case Kind.OffsetNode:
1373 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
1381 private void analyzeFlowCastNode(MethodDescriptor md, SymbolTable nametable, CastNode cn,
1382 NodeTupleSet implicitFlowTupleSet) {
1384 NodeTupleSet nodeTupleSet = new NodeTupleSet();
1385 analyzeFlowExpressionNode(md, nametable, cn.getExpression(), nodeTupleSet, false);
1389 private void analyzeFlowTertiaryNode(MethodDescriptor md, SymbolTable nametable, TertiaryNode tn,
1390 NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
1392 NodeTupleSet tertiaryTupleNode = new NodeTupleSet();
1393 analyzeFlowExpressionNode(md, nametable, tn.getCond(), tertiaryTupleNode, null,
1394 implicitFlowTupleSet, false);
1396 // add edges from tertiaryTupleNode to all nodes of conditional nodes
1397 tertiaryTupleNode.addTupleSet(implicitFlowTupleSet);
1398 analyzeFlowExpressionNode(md, nametable, tn.getTrueExpr(), tertiaryTupleNode, null,
1399 implicitFlowTupleSet, false);
1401 analyzeFlowExpressionNode(md, nametable, tn.getFalseExpr(), tertiaryTupleNode, null,
1402 implicitFlowTupleSet, false);
1404 nodeSet.addTupleSet(tertiaryTupleNode);
1408 private void addMapCallerMethodDescToMethodInvokeNodeSet(MethodDescriptor caller,
1409 MethodInvokeNode min) {
1410 Set<MethodInvokeNode> set = mapMethodDescriptorToMethodInvokeNodeSet.get(caller);
1412 set = new HashSet<MethodInvokeNode>();
1413 mapMethodDescriptorToMethodInvokeNodeSet.put(caller, set);
1418 private void analyzeFlowMethodInvokeNode(MethodDescriptor md, SymbolTable nametable,
1419 MethodInvokeNode min, NodeTupleSet implicitFlowTupleSet) {
1421 addMapCallerMethodDescToMethodInvokeNodeSet(md, min);
1423 MethodDescriptor calleeMD = min.getMethod();
1425 NameDescriptor baseName = min.getBaseName();
1426 boolean isSystemout = false;
1427 if (baseName != null) {
1428 isSystemout = baseName.getSymbol().equals("System.out");
1431 if (!ssjava.isSSJavaUtil(calleeMD.getClassDesc()) && !ssjava.isTrustMethod(calleeMD)
1432 && !calleeMD.getModifiers().isNative() && !isSystemout) {
1434 // CompositeLocation baseLocation = null;
1435 if (min.getExpression() != null) {
1437 NodeTupleSet baseNodeSet = new NodeTupleSet();
1438 analyzeFlowExpressionNode(calleeMD, nametable, min.getExpression(), baseNodeSet, null,
1439 implicitFlowTupleSet, false);
1442 if (min.getMethod().isStatic()) {
1443 // String globalLocId = ssjava.getMethodLattice(md).getGlobalLoc();
1444 // if (globalLocId == null) {
1446 // Error("Method lattice does not define global variable location at "
1447 // + generateErrorMessage(md.getClassDesc(), min));
1449 // baseLocation = new CompositeLocation(new Location(md,
1453 // String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
1454 // baseLocation = new CompositeLocation(new Location(md, thisLocId));
1459 // if (constraint != null) {
1460 // int compareResult =
1461 // CompositeLattice.compare(constraint, baseLocation, true,
1462 // generateErrorMessage(cd, min));
1463 // if (compareResult != ComparisonResult.GREATER) {
1464 // // if the current constraint is higher than method's THIS location
1465 // // no need to check constraints!
1466 // CompositeLocation calleeConstraint =
1467 // translateCallerLocToCalleeLoc(calleeMD, baseLocation, constraint);
1468 // // System.out.println("check method body for constraint:" + calleeMD +
1469 // // " calleeConstraint="
1470 // // + calleeConstraint);
1471 // checkMethodBody(calleeMD.getClassDesc(), calleeMD, calleeConstraint);
1475 analyzeFlowMethodParameters(md, nametable, min);
1477 // checkCalleeConstraints(md, nametable, min, baseLocation, constraint);
1479 // checkCallerArgumentLocationConstraints(md, nametable, min,
1480 // baseLocation, constraint);
1482 if (!min.getMethod().getReturnType().isVoid()) {
1483 // If method has a return value, compute the highest possible return
1484 // location in the caller's perspective
1485 // CompositeLocation ceilingLoc =
1486 // computeCeilingLocationForCaller(md, nametable, min, baseLocation,
1488 // return ceilingLoc;
1492 // return new CompositeLocation(Location.createTopLocation(md));
1496 private NTuple<Descriptor> getArgTupleByArgIdx(MethodInvokeNode min, int idx) {
1497 return mapMethodInvokeNodeToArgIdxMap.get(min).get(new Integer(idx));
1500 private void addArgIdxMap(MethodInvokeNode min, int idx, NTuple<Descriptor> argTuple) {
1501 Map<Integer, NTuple<Descriptor>> mapIdxToArgTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
1502 if (mapIdxToArgTuple == null) {
1503 mapIdxToArgTuple = new HashMap<Integer, NTuple<Descriptor>>();
1504 mapMethodInvokeNodeToArgIdxMap.put(min, mapIdxToArgTuple);
1506 mapIdxToArgTuple.put(new Integer(idx), argTuple);
1509 private void analyzeFlowMethodParameters(MethodDescriptor callermd, SymbolTable nametable,
1510 MethodInvokeNode min) {
1512 if (min.numArgs() > 0) {
1514 int offset = min.getMethod().isStatic() ? 0 : 1;
1516 for (int i = 0; i < min.numArgs(); i++) {
1517 ExpressionNode en = min.getArg(i);
1518 NTuple<Descriptor> argTuple =
1519 analyzeFlowExpressionNode(callermd, nametable, en, new NodeTupleSet(), false);
1521 addArgIdxMap(min, i + offset, argTuple);
1528 private void analyzeLiteralNode(MethodDescriptor md, SymbolTable nametable, LiteralNode en) {
1529 // TODO Auto-generated method stub
1533 private void analyzeFlowArrayAccessNode(MethodDescriptor md, SymbolTable nametable,
1534 ArrayAccessNode aan, NodeTupleSet nodeSet, boolean isLHS) {
1536 NodeTupleSet expNodeTupleSet = new NodeTupleSet();
1537 analyzeFlowExpressionNode(md, nametable, aan.getExpression(), expNodeTupleSet, isLHS);
1539 NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
1540 analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, isLHS);
1543 // need to create an edge from idx to array
1545 for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
1546 NTuple<Descriptor> idxTuple = idxIter.next();
1547 for (Iterator<NTuple<Descriptor>> arrIter = expNodeTupleSet.iterator(); arrIter.hasNext();) {
1548 NTuple<Descriptor> arrTuple = arrIter.next();
1549 getFlowGraph(md).addValueFlowEdge(idxTuple, arrTuple);
1553 nodeSet.addTupleSet(expNodeTupleSet);
1555 nodeSet.addTupleSet(expNodeTupleSet);
1556 nodeSet.addTupleSet(idxNodeTupleSet);
1561 private void analyzeCreateObjectNode(MethodDescriptor md, SymbolTable nametable,
1562 CreateObjectNode en) {
1563 // TODO Auto-generated method stub
1567 private void analyzeFlowOpNode(MethodDescriptor md, SymbolTable nametable, OpNode on,
1568 NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
1570 NodeTupleSet leftOpSet = new NodeTupleSet();
1571 NodeTupleSet rightOpSet = new NodeTupleSet();
1574 analyzeFlowExpressionNode(md, nametable, on.getLeft(), leftOpSet, null, implicitFlowTupleSet,
1577 if (on.getRight() != null) {
1579 analyzeFlowExpressionNode(md, nametable, on.getRight(), rightOpSet, null,
1580 implicitFlowTupleSet, false);
1583 Operation op = on.getOp();
1585 switch (op.getOp()) {
1587 case Operation.UNARYPLUS:
1588 case Operation.UNARYMINUS:
1589 case Operation.LOGIC_NOT:
1591 nodeSet.addTupleSet(leftOpSet);
1594 case Operation.LOGIC_OR:
1595 case Operation.LOGIC_AND:
1596 case Operation.COMP:
1597 case Operation.BIT_OR:
1598 case Operation.BIT_XOR:
1599 case Operation.BIT_AND:
1600 case Operation.ISAVAILABLE:
1601 case Operation.EQUAL:
1602 case Operation.NOTEQUAL:
1609 case Operation.MULT:
1612 case Operation.LEFTSHIFT:
1613 case Operation.RIGHTSHIFT:
1614 case Operation.URIGHTSHIFT:
1616 // there are two operands
1617 nodeSet.addTupleSet(leftOpSet);
1618 nodeSet.addTupleSet(rightOpSet);
1622 throw new Error(op.toString());
1626 private NTuple<Descriptor> analyzeFlowNameNode(MethodDescriptor md, SymbolTable nametable,
1627 NameNode nn, NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
1630 base = new NTuple<Descriptor>();
1633 NameDescriptor nd = nn.getName();
1635 if (nd.getBase() != null) {
1636 analyzeFlowExpressionNode(md, nametable, nn.getExpression(), nodeSet, base,
1637 implicitFlowTupleSet, false);
1639 String varname = nd.toString();
1640 if (varname.equals("this")) {
1642 base.add(md.getThis());
1646 Descriptor d = (Descriptor) nametable.get(varname);
1648 if (d instanceof VarDescriptor) {
1649 VarDescriptor vd = (VarDescriptor) d;
1651 } else if (d instanceof FieldDescriptor) {
1652 // the type of field descriptor has a location!
1653 FieldDescriptor fd = (FieldDescriptor) d;
1654 if (fd.isStatic()) {
1656 // if it is 'static final', the location has TOP since no one can
1658 // loc.addLocation(Location.createTopLocation(md));
1661 // if 'static', the location has pre-assigned global loc
1662 // MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1663 // String globalLocId = localLattice.getGlobalLoc();
1664 // if (globalLocId == null) {
1666 // Error("Global location element is not defined in the method " +
1669 // Location globalLoc = new Location(md, globalLocId);
1671 // loc.addLocation(globalLoc);
1674 // the location of field access starts from this, followed by field
1676 base.add(md.getThis());
1680 } else if (d == null) {
1681 // access static field
1682 // FieldDescriptor fd = nn.getField();addFlowGraphEdge
1684 // MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1685 // String globalLocId = localLattice.getGlobalLoc();
1686 // if (globalLocId == null) {
1688 // Error("Method lattice does not define global variable location at "
1689 // + generateErrorMessage(md.getClassDesc(), nn));
1691 // loc.addLocation(new Location(md, globalLocId));
1693 // Location fieldLoc = (Location) fd.getType().getExtension();
1694 // loc.addLocation(fieldLoc);
1701 getFlowGraph(md).createNewFlowNode(base);
1707 private NTuple<Descriptor> analyzeFlowFieldAccessNode(MethodDescriptor md, SymbolTable nametable,
1708 FieldAccessNode fan, NodeTupleSet nodeSet, NTuple<Descriptor> base,
1709 NodeTupleSet implicitFlowTupleSet) {
1711 ExpressionNode left = fan.getExpression();
1712 TypeDescriptor ltd = left.getType();
1713 FieldDescriptor fd = fan.getField();
1715 String varName = null;
1716 if (left.kind() == Kind.NameNode) {
1717 NameDescriptor nd = ((NameNode) left).getName();
1718 varName = nd.toString();
1721 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1722 // using a class name directly or access using this
1723 if (fd.isStatic() && fd.isFinal()) {
1724 // loc.addLocation(Location.createTopLocation(md));
1729 // if (left instanceof ArrayAccessNode) {
1730 // ArrayAccessNode aan = (ArrayAccessNode) left;
1731 // left = aan.getExpression();
1735 analyzeFlowExpressionNode(md, nametable, left, nodeSet, base, implicitFlowTupleSet, false);
1737 if (!left.getType().isPrimitive()) {
1739 if (fd.getSymbol().equals("length")) {
1741 // array.length access, return the location of the array
1748 getFlowGraph(md).createNewFlowNode(base);
1753 private void analyzeFlowAssignmentNode(MethodDescriptor md, SymbolTable nametable,
1754 AssignmentNode an, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
1756 // System.out.println("#an=" + an.printNode(0) + " an src=" +
1757 // an.getSrc().printNode(0) + " dst="
1758 // + an.getDest().printNode(0));
1759 NodeTupleSet nodeSetRHS = new NodeTupleSet();
1760 NodeTupleSet nodeSetLHS = new NodeTupleSet();
1762 boolean postinc = true;
1763 if (an.getOperation().getBaseOp() == null
1764 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1765 .getBaseOp().getOp() != Operation.POSTDEC)) {
1768 // if LHS is array access node, need to capture value flows between an array
1769 // and its index value
1770 analyzeFlowExpressionNode(md, nametable, an.getDest(), nodeSetLHS, null, implicitFlowTupleSet,
1774 // analyze value flows of rhs expression
1775 analyzeFlowExpressionNode(md, nametable, an.getSrc(), nodeSetRHS, null, implicitFlowTupleSet,
1778 // creates edges from RHS to LHS
1779 for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
1780 NTuple<Descriptor> fromTuple = iter.next();
1781 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
1782 NTuple<Descriptor> toTuple = iter2.next();
1783 addFlowGraphEdge(md, fromTuple, toTuple);
1787 // creates edges from implicitFlowTupleSet to LHS
1788 for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
1789 NTuple<Descriptor> fromTuple = iter.next();
1790 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
1791 NTuple<Descriptor> toTuple = iter2.next();
1792 addFlowGraphEdge(md, fromTuple, toTuple);
1798 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
1799 NTuple<Descriptor> tuple = iter2.next();
1800 addFlowGraphEdge(md, tuple, tuple);
1807 public FlowGraph getFlowGraph(MethodDescriptor md) {
1808 return mapMethodDescriptorToFlowGraph.get(md);
1811 private boolean addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
1812 NTuple<Descriptor> to) {
1814 // return true if it adds a new edge
1815 FlowGraph graph = getFlowGraph(md);
1816 graph.addValueFlowEdge(from, to);
1820 public void _debug_printGraph() {
1821 Set<MethodDescriptor> keySet = mapMethodDescriptorToFlowGraph.keySet();
1823 for (Iterator<MethodDescriptor> iterator = keySet.iterator(); iterator.hasNext();) {
1824 MethodDescriptor md = (MethodDescriptor) iterator.next();
1825 FlowGraph fg = mapMethodDescriptorToFlowGraph.get(md);
1828 } catch (IOException e) {
1829 e.printStackTrace();