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
149 debug_writeLatticeDotFile();
151 // 3) check properties
156 private void checkLattices() {
158 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
160 // current descriptors to visit in fixed-point interprocedural analysis,
162 // dependency in the call graph
163 methodDescriptorsToVisitStack.clear();
165 descriptorListToAnalyze.removeFirst();
167 Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
168 methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
170 while (!descriptorListToAnalyze.isEmpty()) {
171 MethodDescriptor md = descriptorListToAnalyze.removeFirst();
172 checkLatticesOfVirtualMethods(md);
177 private void debug_writeLatticeDotFile() {
178 // generate lattice dot file
182 while (!toAnalyzeIsEmpty()) {
183 ClassDescriptor cd = toAnalyzeNext();
185 setupToAnalazeMethod(cd);
187 SSJavaLattice<String> classLattice = cd2lattice.get(cd);
188 if (classLattice != null) {
189 ssjava.writeLatticeDotFile(cd, null, classLattice);
192 while (!toAnalyzeMethodIsEmpty()) {
193 MethodDescriptor md = toAnalyzeMethodNext();
194 if (ssjava.needTobeAnnotated(md)) {
195 SSJavaLattice<String> methodLattice = md2lattice.get(md);
196 if (methodLattice != null) {
197 ssjava.writeLatticeDotFile(cd, md, methodLattice);
205 private void inferLattices() {
207 // do fixed-point analysis
209 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
211 // current descriptors to visit in fixed-point interprocedural analysis,
213 // dependency in the call graph
214 methodDescriptorsToVisitStack.clear();
216 descriptorListToAnalyze.removeFirst();
218 Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
219 methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
221 while (!descriptorListToAnalyze.isEmpty()) {
222 MethodDescriptor md = descriptorListToAnalyze.removeFirst();
223 methodDescriptorsToVisitStack.add(md);
226 // analyze scheduled methods until there are no more to visit
227 while (!methodDescriptorsToVisitStack.isEmpty()) {
228 // start to analyze leaf node
229 MethodDescriptor md = methodDescriptorsToVisitStack.pop();
231 SSJavaLattice<String> methodLattice =
232 new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM);
234 System.out.println();
235 System.out.println("SSJAVA: Inferencing the lattice from " + md);
237 analyzeMethodLattice(md, methodLattice);
239 SSJavaLattice<String> prevMethodLattice = getMethodLattice(md);
241 if (!methodLattice.equals(prevMethodLattice)) {
243 setMethodLattice(md, methodLattice);
245 // results for callee changed, so enqueue dependents caller for
247 Iterator<MethodDescriptor> depsItr = ssjava.getDependents(md).iterator();
248 while (depsItr.hasNext()) {
249 MethodDescriptor methodNext = depsItr.next();
250 if (!methodDescriptorsToVisitStack.contains(methodNext)
251 && methodDescriptorToVistSet.contains(methodNext)) {
252 methodDescriptorsToVisitStack.add(methodNext);
262 private void checkLatticesOfVirtualMethods(MethodDescriptor md) {
264 if (!md.isStatic()) {
265 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
266 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
268 for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
269 MethodDescriptor mdCallee = (MethodDescriptor) iterator.next();
270 if (!md.equals(mdCallee)) {
271 checkConsistency(md, mdCallee);
279 private void checkConsistency(MethodDescriptor md1, MethodDescriptor md2) {
281 // check that two lattice have the same relations between parameters(+PC
284 MethodLocationInfo methodInfo1 = getMethodLocationInfo(md1);
286 SSJavaLattice<String> lattice1 = getMethodLattice(md1);
287 SSJavaLattice<String> lattice2 = getMethodLattice(md2);
289 Set<String> paramLocNameSet1 = methodInfo1.getParameterLocNameSet();
291 for (Iterator iterator = paramLocNameSet1.iterator(); iterator.hasNext();) {
292 String locName1 = (String) iterator.next();
293 for (Iterator iterator2 = paramLocNameSet1.iterator(); iterator2.hasNext();) {
294 String locName2 = (String) iterator2.next();
296 // System.out.println("COMPARE " + locName1 + " - " + locName2 + " "
297 // + lattice1.isGreaterThan(locName1, locName2) + "-"
298 // + lattice2.isGreaterThan(locName1, locName2));
300 if (!locName1.equals(locName2)) {
302 boolean r1 = lattice1.isGreaterThan(locName1, locName2);
303 boolean r2 = lattice2.isGreaterThan(locName1, locName2);
306 throw new Error("The method " + md1 + " is not consistent with the method " + md2
307 + ".:: They have a different ordering relation between parameters " + locName1
308 + " and " + locName2 + ".");
317 private String getSymbol(int idx, FlowNode node) {
318 Descriptor desc = node.getDescTuple().get(idx);
319 return desc.getSymbol();
322 private Descriptor getDescriptor(int idx, FlowNode node) {
323 Descriptor desc = node.getDescTuple().get(idx);
327 private void analyzeMethodLattice(MethodDescriptor md, SSJavaLattice<String> methodLattice) {
329 MethodLocationInfo methodInfo = getMethodLocationInfo(md);
331 // first take a look at method invocation nodes to newly added relations
333 analyzeLatticeMethodInvocationNode(md);
335 // visit each node of method flow graph
336 FlowGraph fg = getFlowGraph(md);
337 Set<FlowNode> nodeSet = fg.getNodeSet();
339 // for the method lattice, we need to look at the first element of
340 // NTuple<Descriptor>
341 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
342 FlowNode srcNode = (FlowNode) iterator.next();
344 Set<FlowEdge> outEdgeSet = srcNode.getOutEdgeSet();
345 for (Iterator iterator2 = outEdgeSet.iterator(); iterator2.hasNext();) {
346 FlowEdge outEdge = (FlowEdge) iterator2.next();
347 FlowNode dstNode = outEdge.getDst();
349 NTuple<Descriptor> srcNodeTuple = srcNode.getDescTuple();
350 NTuple<Descriptor> dstNodeTuple = dstNode.getDescTuple();
352 if (outEdge.getInitTuple().equals(srcNodeTuple)
353 && outEdge.getEndTuple().equals(dstNodeTuple)) {
355 if ((srcNodeTuple.size() > 1 && dstNodeTuple.size() > 1)
356 && srcNodeTuple.get(0).equals(dstNodeTuple.get(0))) {
358 // value flows between fields
359 VarDescriptor varDesc = (VarDescriptor) srcNodeTuple.get(0);
360 ClassDescriptor varClassDesc = varDesc.getType().getClassDesc();
361 extractRelationFromFieldFlows(varClassDesc, srcNode, dstNode, 1);
364 // for the method lattice, we need to look at the first element of
365 // NTuple<Descriptor>
366 if (srcNodeTuple.size() == 1 || dstNodeTuple.size() == 1) {
367 // in this case, take a look at connected nodes at the local level
368 addRelationToLattice(md, methodLattice, srcNode, dstNode);
376 // grab the this location if the method use the 'this' reference
377 String thisLocSymbol = md.getThis().getSymbol();
378 if (methodLattice.getKeySet().contains(thisLocSymbol)) {
379 methodInfo.setThisLocName(thisLocSymbol);
382 // calculate a return location
383 if (!md.getReturnType().isVoid()) {
384 Set<FlowNode> returnNodeSet = fg.getReturnNodeSet();
385 Set<String> returnVarSymbolSet = new HashSet<String>();
387 for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
388 FlowNode rtrNode = (FlowNode) iterator.next();
389 String localSymbol = rtrNode.getDescTuple().get(0).getSymbol();
390 returnVarSymbolSet.add(localSymbol);
393 String returnGLB = methodLattice.getGLB(returnVarSymbolSet);
394 if (returnGLB.equals(SSJavaAnalysis.BOTTOM)) {
395 // need to insert a new location in-between the bottom and all locations
396 // that is directly connected to the bottom
397 String returnNewLocationSymbol = "Loc" + (SSJavaLattice.seed++);
398 methodLattice.insertNewLocationAtOneLevelHigher(returnGLB, returnNewLocationSymbol);
399 methodInfo.setReturnLocName(returnNewLocationSymbol);
401 methodInfo.setReturnLocName(returnGLB);
407 private void analyzeLatticeMethodInvocationNode(MethodDescriptor mdCaller) {
409 // the transformation for a call site propagates all relations between
410 // parameters from the callee
411 // if the method is virtual, it also grab all relations from any possible
414 Set<MethodInvokeNode> setMethodInvokeNode =
415 mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
416 if (setMethodInvokeNode != null) {
418 for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
419 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
420 MethodDescriptor mdCallee = min.getMethod();
421 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
422 if (mdCallee.isStatic()) {
423 setPossibleCallees.add(mdCallee);
425 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(mdCallee));
428 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
429 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
430 propagateRelationToCaller(min, mdCaller, possibleMdCallee);
438 private void propagateRelationToCaller(MethodInvokeNode min, MethodDescriptor mdCaller,
439 MethodDescriptor possibleMdCallee) {
441 SSJavaLattice<String> calleeLattice = getMethodLattice(possibleMdCallee);
443 FlowGraph calleeFlowGraph = getFlowGraph(possibleMdCallee);
445 // find parameter node
446 Set<FlowNode> paramNodeSet = calleeFlowGraph.getParameterNodeSet();
448 for (Iterator iterator = paramNodeSet.iterator(); iterator.hasNext();) {
449 FlowNode paramFlowNode1 = (FlowNode) iterator.next();
451 for (Iterator iterator2 = paramNodeSet.iterator(); iterator2.hasNext();) {
452 FlowNode paramFlowNode2 = (FlowNode) iterator2.next();
454 String paramSymbol1 = getSymbol(0, paramFlowNode1);
455 String paramSymbol2 = getSymbol(0, paramFlowNode2);
456 // if two parameters have a relation, we need to propagate this relation
458 if (!(paramSymbol1.equals(paramSymbol2))
459 && calleeLattice.isComparable(paramSymbol1, paramSymbol2)) {
460 int higherLocIdxCallee;
461 int lowerLocIdxCallee;
462 if (calleeLattice.isGreaterThan(paramSymbol1, paramSymbol2)) {
463 higherLocIdxCallee = calleeFlowGraph.getParamIdx(paramFlowNode1.getDescTuple());
464 lowerLocIdxCallee = calleeFlowGraph.getParamIdx(paramFlowNode2.getDescTuple());
466 higherLocIdxCallee = calleeFlowGraph.getParamIdx(paramFlowNode2.getDescTuple());
467 lowerLocIdxCallee = calleeFlowGraph.getParamIdx(paramFlowNode1.getDescTuple());
470 NTuple<Descriptor> higherArg = getArgTupleByArgIdx(min, higherLocIdxCallee);
471 NTuple<Descriptor> lowerArg = getArgTupleByArgIdx(min, lowerLocIdxCallee);
473 addFlowGraphEdge(mdCaller, higherArg, lowerArg);
483 private LocationInfo getLocationInfo(Descriptor d) {
484 if (d instanceof MethodDescriptor) {
485 return getMethodLocationInfo((MethodDescriptor) d);
487 return getFieldLocationInfo((ClassDescriptor) d);
491 private MethodLocationInfo getMethodLocationInfo(MethodDescriptor md) {
493 if (!mapMethodDescToMethodLocationInfo.containsKey(md)) {
494 mapMethodDescToMethodLocationInfo.put(md, new MethodLocationInfo(md));
497 return mapMethodDescToMethodLocationInfo.get(md);
501 private LocationInfo getFieldLocationInfo(ClassDescriptor cd) {
503 if (!mapClassToLocationInfo.containsKey(cd)) {
504 mapClassToLocationInfo.put(cd, new LocationInfo(cd));
507 return mapClassToLocationInfo.get(cd);
511 private void addRelationToLattice(MethodDescriptor md, SSJavaLattice<String> methodLattice,
512 FlowNode srcNode, FlowNode dstNode) {
514 System.out.println("### addRelationToLattice src=" + srcNode + " dst=" + dstNode);
516 // add a new binary relation of dstNode < srcNode
517 FlowGraph flowGraph = getFlowGraph(md);
518 MethodLocationInfo methodInfo = getMethodLocationInfo(md);
520 String srcOriginSymbol = getSymbol(0, srcNode);
521 String dstOriginSymbol = getSymbol(0, dstNode);
523 Descriptor srcDesc = getDescriptor(0, srcNode);
524 Descriptor dstDesc = getDescriptor(0, dstNode);
526 String srcSymbol = methodInfo.getLocName(srcOriginSymbol);
527 String dstSymbol = methodInfo.getLocName(dstOriginSymbol);
529 if (srcNode.isParameter()) {
530 int paramIdx = flowGraph.getParamIdx(srcNode.getDescTuple());
531 methodInfo.addParameter(srcSymbol, srcDesc, paramIdx);
533 methodInfo.addMappingOfLocNameToDescriptor(srcSymbol, srcDesc);
536 if (dstNode.isParameter()) {
537 int paramIdx = flowGraph.getParamIdx(dstNode.getDescTuple());
538 methodInfo.addParameter(dstSymbol, dstDesc, paramIdx);
540 methodInfo.addMappingOfLocNameToDescriptor(dstSymbol, dstDesc);
543 // consider a composite location case
545 boolean isSrcLocalVar = false;
546 boolean isDstLocalVar = false;
547 if (srcNode.getDescTuple().size() == 1) {
548 isSrcLocalVar = true;
551 if (dstNode.getDescTuple().size() == 1) {
552 isDstLocalVar = true;
555 boolean isAssignedCompositeLocation = false;
556 if (isSrcLocalVar && isDstLocalVar) {
557 // both src and dst are local var
559 // CompositeLocation inferSrc=methodInfo.getInferLocation(srcNode);
560 // CompositeLocation inferDst=methodInfo.getInferLocation(dstNode);
561 // if( (inferSrc!=null && inferSrc.getSize()>1) || (inferDst!=null &&
562 // inferDst.getSize()>1)){
563 // isAssignedCompositeLocation = true;
567 isAssignedCompositeLocation =
568 calculateCompositeLocationForLocalVar(flowGraph, methodLattice, methodInfo, srcNode);
569 calculateCompositeLocationForLocalVar(flowGraph, methodLattice, methodInfo, dstNode);
571 } else if (isSrcLocalVar) {
573 isAssignedCompositeLocation =
574 calculateCompositeLocationForLocalVar(flowGraph, methodLattice, methodInfo, srcNode);
575 } else if (isDstLocalVar) {
577 isAssignedCompositeLocation =
578 calculateCompositeLocationForLocalVar(flowGraph, methodLattice, methodInfo, dstNode);
581 if (!isAssignedCompositeLocation) {
582 if (!methodLattice.isGreaterThan(srcSymbol, dstSymbol)) {
583 // if the lattice does not have this relation, add it
584 methodLattice.addRelationHigherToLower(srcSymbol, dstSymbol);
588 // Set<String> cycleElementSet =
589 // methodLattice.getPossibleCycleElements(srcSymbol, dstSymbol);
591 // System.out.println("### POSSIBLE CYCLE ELEMENT SET=" + cycleElementSet);
592 // boolean hasNonPrimitiveElement = false;
593 // for (Iterator iterator = cycleElementSet.iterator(); iterator.hasNext();)
595 // String cycleElementSymbol = (String) iterator.next();
596 // Set<Descriptor> flowNodeSet =
597 // methodInfo.getFlowNodeSet(cycleElementSymbol);
598 // for (Iterator iterator2 = flowNodeSet.iterator(); iterator2.hasNext();) {
599 // Descriptor desc = (Descriptor) iterator2.next();
600 // if (!isPrimitiveTypeDescriptor(desc)) {
601 // hasNonPrimitiveElement = true;
604 // .println("flowNode=" + desc + " is primitive?=" +
605 // isPrimitiveTypeDescriptor(desc));
609 // if (hasNonPrimitiveElement) {
610 // // if there is non-primitive element in the cycle, no way to merge cyclic
611 // // elements into the shared location
612 // System.out.println("Failed to merge cyclic value flows into a shared location.");
614 // // try to assign more fine-grind composite location to the source or the
616 // System.out.println("SRC=" + srcSymbol + " DST=" + dstSymbol);
617 // System.out.println("### SRCNODE=" + srcNode + " DSTNODE=" + dstNode);
619 // FlowNode targetNode;
620 // if (isPrimitiveLocalVariable(srcNode)) {
621 // targetNode = srcNode;
623 // targetNode = dstNode;
626 // calculateMoreFineGrainedLocation(md, methodLattice, targetNode);
631 // if (cycleElementSet.size() > 0) {
632 // String newSharedLoc = "SharedLoc" + (SSJavaLattice.seed++);
633 // methodLattice.mergeIntoSharedLocation(cycleElementSet, newSharedLoc);
635 // for (Iterator iterator = cycleElementSet.iterator(); iterator.hasNext();)
637 // String locName = (String) iterator.next();
638 // methodInfo.mapDescSymbolToLocName(locName, newSharedLoc);
641 // } else if (!methodLattice.isGreaterThan(srcSymbol, dstSymbol)) {
642 // // if the lattice does not have this relation, add it
643 // methodLattice.addRelationHigherToLower(srcSymbol, dstSymbol);
646 // System.out.println("methodLattice=" + methodLattice.getKeySet());
650 private void addPrefixMapping(Map<NTuple<Location>, Set<NTuple<Location>>> map,
651 NTuple<Location> prefix, NTuple<Location> element) {
653 if (!map.containsKey(prefix)) {
654 map.put(prefix, new HashSet<NTuple<Location>>());
656 map.get(prefix).add(element);
660 private NTuple<Location> getLocationTuple(MethodLocationInfo methodInfo, FlowGraph flowGraph,
663 NTuple<Location> locTuple;
664 CompositeLocation inferLoc = methodInfo.getInferLocation(flowNode);
665 if (inferLoc != null) {
666 // the flow node has already been assigned to the location
667 locTuple = new NTuple<Location>();
668 NTuple<Location> inferLocTuple = inferLoc.getTuple();
669 for (int i = 0; i < inferLocTuple.size(); i++) {
670 locTuple.add(inferLocTuple.get(i));
673 locTuple = flowGraph.getLocationTuple(flowNode);
679 private boolean calculateCompositeLocationForLocalVar(FlowGraph flowGraph,
680 SSJavaLattice<String> methodLattice, MethodLocationInfo methodInfo, FlowNode flowNode) {
682 Set<FlowNode> inNodeSet = flowGraph.getIncomingFlowNodeSet(flowNode);
683 Set<FlowNode> reachableNodeSet = flowGraph.getReachableFlowNodeSet(flowNode);
685 Map<NTuple<Location>, Set<NTuple<Location>>> mapPrefixToIncomingLocTupleSet =
686 new HashMap<NTuple<Location>, Set<NTuple<Location>>>();
688 List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
690 for (Iterator iterator = inNodeSet.iterator(); iterator.hasNext();) {
691 FlowNode inNode = (FlowNode) iterator.next();
692 NTuple<Location> inTuple = getLocationTuple(methodInfo, flowGraph, inNode);
694 if (inTuple.size() > 1) {
695 for (int i = 1; i < inTuple.size(); i++) {
696 NTuple<Location> prefix = inTuple.subList(0, i);
697 if (!prefixList.contains(prefix)) {
698 prefixList.add(prefix);
700 addPrefixMapping(mapPrefixToIncomingLocTupleSet, prefix, inTuple);
705 Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
706 public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
707 int s0 = arg0.size();
708 int s1 = arg1.size();
711 } else if (s0 == s1) {
719 // find out reachable nodes that have the longest common prefix
720 for (int i = 0; i < prefixList.size(); i++) {
721 NTuple<Location> curPrefix = prefixList.get(i);
722 Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
724 for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
725 FlowNode reachableNode = (FlowNode) iterator2.next();
726 NTuple<Location> reachLocTuple = flowGraph.getLocationTuple(reachableNode);
727 if (reachLocTuple.startsWith(curPrefix)) {
728 reachableCommonPrefixSet.add(reachLocTuple);
732 if (!reachableCommonPrefixSet.isEmpty()) {
733 Set<NTuple<Location>> incomingCommonPrefixSet =
734 mapPrefixToIncomingLocTupleSet.get(curPrefix);
736 int idx = curPrefix.size();
737 NTuple<Location> element = incomingCommonPrefixSet.iterator().next();
738 Descriptor desc = element.get(idx).getDescriptor();
740 SSJavaLattice<String> lattice = getLattice(desc);
741 LocationInfo locInfo = getLocationInfo(desc);
743 CompositeLocation inferNode = methodInfo.getInferLocation(flowNode);
745 if (inferNode != null) {
748 String newLocSymbol = "Loc" + (SSJavaLattice.seed++);
749 inferNode = new CompositeLocation();
750 for (int locIdx = 0; locIdx < curPrefix.size(); locIdx++) {
751 inferNode.addLocation(curPrefix.get(locIdx));
753 inferNode.addLocation(new Location(desc, newLocSymbol));
754 methodInfo.mapFlowNodeToInferLocation(flowNode, inferNode);
755 if (flowNode.getDescTuple().size() == 1) {
756 // local variable case
757 modifyLocalLatticeAccrodingToNewlyAddedCompositeLocation(methodLattice, methodInfo,
758 inferNode, flowNode);
762 nodeSymbol = inferNode.get(inferNode.getSize() - 1).getLocIdentifier();
764 for (Iterator iterator = incomingCommonPrefixSet.iterator(); iterator.hasNext();) {
765 NTuple<Location> tuple = (NTuple<Location>) iterator.next();
766 Location loc = tuple.get(idx);
767 String higher = locInfo.getLocName(loc.getLocIdentifier());
768 lattice.addRelationHigherToLower(higher, nodeSymbol);
771 for (Iterator iterator = reachableCommonPrefixSet.iterator(); iterator.hasNext();) {
772 NTuple<Location> tuple = (NTuple<Location>) iterator.next();
773 Location loc = tuple.get(idx);
774 String lower = locInfo.getLocName(loc.getLocIdentifier());
775 lattice.addRelationHigherToLower(nodeSymbol, lower);
787 private void modifyLocalLatticeAccrodingToNewlyAddedCompositeLocation(
788 SSJavaLattice<String> methodLattice, MethodLocationInfo methodInfo,
789 CompositeLocation inferNode, FlowNode flowNode) {
791 Location localLocation = inferNode.get(0);
792 String newLocName = methodInfo.getLocName(localLocation.getLocIdentifier());
793 String oldLocName = methodInfo.getLocName(flowNode.getDescTuple().get(0).getSymbol());
795 methodInfo.mapDescSymbolToLocName(oldLocName, newLocName);
796 methodLattice.substituteLocation(oldLocName, newLocName);
800 public boolean isPrimitiveLocalVariable(FlowNode node) {
801 VarDescriptor varDesc = (VarDescriptor) node.getDescTuple().get(0);
802 return varDesc.getType().isPrimitive();
805 private SSJavaLattice<String> getLattice(Descriptor d) {
806 if (d instanceof MethodDescriptor) {
807 return getMethodLattice((MethodDescriptor) d);
809 return getFieldLattice((ClassDescriptor) d);
813 private SSJavaLattice<String> getMethodLattice(MethodDescriptor md) {
814 if (!md2lattice.containsKey(md)) {
815 md2lattice.put(md, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
817 return md2lattice.get(md);
820 private void setMethodLattice(MethodDescriptor md, SSJavaLattice<String> lattice) {
821 md2lattice.put(md, lattice);
824 private void extractRelationFromFieldFlows(ClassDescriptor cd, FlowNode srcNode,
825 FlowNode dstNode, int idx) {
827 if (srcNode.getDescTuple().get(idx).equals(dstNode.getDescTuple().get(idx))
828 && srcNode.getDescTuple().size() > (idx + 1) && dstNode.getDescTuple().size() > (idx + 1)) {
829 // value flow between fields: we don't need to add a binary relation
832 Descriptor desc = srcNode.getDescTuple().get(idx);
833 ClassDescriptor classDesc;
836 classDesc = ((VarDescriptor) desc).getType().getClassDesc();
838 classDesc = ((FieldDescriptor) desc).getType().getClassDesc();
841 extractRelationFromFieldFlows(classDesc, srcNode, dstNode, idx + 1);
845 Descriptor srcFieldDesc = srcNode.getDescTuple().get(idx);
846 Descriptor dstFieldDesc = dstNode.getDescTuple().get(idx);
848 // add a new binary relation of dstNode < srcNode
849 SSJavaLattice<String> fieldLattice = getFieldLattice(cd);
851 String srcOriginalSymbol = srcFieldDesc.getSymbol();
852 String dstOriginalSymbol = dstFieldDesc.getSymbol();
854 LocationInfo fieldInfo = getFieldLocationInfo(cd);
856 String srcSymbol = fieldInfo.getLocName(srcOriginalSymbol);
857 String dstSymbol = fieldInfo.getLocName(dstOriginalSymbol);
859 Set<String> cycleElementSet = fieldLattice.getPossibleCycleElements(srcSymbol, dstSymbol);
861 if (cycleElementSet.size() > 0) {
862 String newSharedLoc = "SharedLoc" + (SSJavaLattice.seed++);
863 fieldLattice.mergeIntoSharedLocation(cycleElementSet, newSharedLoc);
865 for (Iterator iterator = cycleElementSet.iterator(); iterator.hasNext();) {
866 String locName = (String) iterator.next();
867 fieldInfo.mapDescSymbolToLocName(locName, newSharedLoc);
870 } else if (!fieldLattice.isGreaterThan(srcSymbol, dstSymbol)) {
871 // if the lattice does not have this relation, add it
872 fieldLattice.addRelationHigherToLower(srcSymbol, dstSymbol);
879 public SSJavaLattice<String> getFieldLattice(ClassDescriptor cd) {
880 if (!cd2lattice.containsKey(cd)) {
881 cd2lattice.put(cd, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
883 return cd2lattice.get(cd);
886 public void constructFlowGraph() {
890 while (!toAnalyzeIsEmpty()) {
891 ClassDescriptor cd = toAnalyzeNext();
893 setupToAnalazeMethod(cd);
894 while (!toAnalyzeMethodIsEmpty()) {
895 MethodDescriptor md = toAnalyzeMethodNext();
896 if (ssjava.needTobeAnnotated(md)) {
897 if (state.SSJAVADEBUG) {
898 System.out.println();
899 System.out.println("SSJAVA: Constructing a flow graph: " + md);
902 // creates a mapping from a method descriptor to virtual methods
903 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
905 setPossibleCallees.add(md);
907 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
909 mapMethodDescToPossibleMethodDescSet.put(md, setPossibleCallees);
911 // creates a mapping from a parameter descriptor to its index
912 Map<Descriptor, Integer> mapParamDescToIdx = new HashMap<Descriptor, Integer>();
913 int offset = md.isStatic() ? 0 : 1;
914 for (int i = 0; i < md.numParameters(); i++) {
915 Descriptor paramDesc = (Descriptor) md.getParameter(i);
916 mapParamDescToIdx.put(paramDesc, new Integer(i + offset));
919 FlowGraph fg = new FlowGraph(md, mapParamDescToIdx);
920 mapMethodDescriptorToFlowGraph.put(md, fg);
922 analyzeMethodBody(cd, md);
930 private void analyzeMethodBody(ClassDescriptor cd, MethodDescriptor md) {
931 BlockNode bn = state.getMethodBody(md);
932 NodeTupleSet implicitFlowTupleSet = new NodeTupleSet();
933 analyzeFlowBlockNode(md, md.getParameterTable(), bn, implicitFlowTupleSet);
936 private void analyzeFlowBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn,
937 NodeTupleSet implicitFlowTupleSet) {
939 bn.getVarTable().setParent(nametable);
940 for (int i = 0; i < bn.size(); i++) {
941 BlockStatementNode bsn = bn.get(i);
942 analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
947 private void analyzeBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
948 BlockStatementNode bsn, NodeTupleSet implicitFlowTupleSet) {
950 switch (bsn.kind()) {
951 case Kind.BlockExpressionNode:
952 analyzeBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, implicitFlowTupleSet);
955 case Kind.DeclarationNode:
956 analyzeFlowDeclarationNode(md, nametable, (DeclarationNode) bsn, implicitFlowTupleSet);
959 case Kind.IfStatementNode:
960 analyzeFlowIfStatementNode(md, nametable, (IfStatementNode) bsn, implicitFlowTupleSet);
964 analyzeFlowLoopNode(md, nametable, (LoopNode) bsn, implicitFlowTupleSet);
967 case Kind.ReturnNode:
968 analyzeFlowReturnNode(md, nametable, (ReturnNode) bsn, implicitFlowTupleSet);
971 case Kind.SubBlockNode:
972 analyzeFlowSubBlockNode(md, nametable, (SubBlockNode) bsn, implicitFlowTupleSet);
975 case Kind.ContinueBreakNode:
978 case Kind.SwitchStatementNode:
979 analyzeSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
986 private void analyzeSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
987 SwitchStatementNode bsn) {
988 // TODO Auto-generated method stub
991 private void analyzeFlowSubBlockNode(MethodDescriptor md, SymbolTable nametable,
992 SubBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
993 analyzeFlowBlockNode(md, nametable, sbn.getBlockNode(), implicitFlowTupleSet);
996 private void analyzeFlowReturnNode(MethodDescriptor md, SymbolTable nametable, ReturnNode rn,
997 NodeTupleSet implicitFlowTupleSet) {
999 ExpressionNode returnExp = rn.getReturnExpression();
1001 NodeTupleSet nodeSet = new NodeTupleSet();
1002 analyzeFlowExpressionNode(md, nametable, returnExp, nodeSet, false);
1004 FlowGraph fg = getFlowGraph(md);
1006 // annotate the elements of the node set as the return location
1007 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1008 NTuple<Descriptor> returnDescTuple = (NTuple<Descriptor>) iterator.next();
1009 fg.setReturnFlowNode(returnDescTuple);
1010 for (Iterator iterator2 = implicitFlowTupleSet.iterator(); iterator2.hasNext();) {
1011 NTuple<Descriptor> implicitFlowDescTuple = (NTuple<Descriptor>) iterator2.next();
1012 fg.addValueFlowEdge(implicitFlowDescTuple, returnDescTuple);
1018 private void analyzeFlowLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln,
1019 NodeTupleSet implicitFlowTupleSet) {
1021 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
1023 NodeTupleSet condTupleNode = new NodeTupleSet();
1024 analyzeFlowExpressionNode(md, nametable, ln.getCondition(), condTupleNode, null,
1025 implicitFlowTupleSet, false);
1026 condTupleNode.addTupleSet(implicitFlowTupleSet);
1028 // add edges from condNodeTupleSet to all nodes of conditional nodes
1029 analyzeFlowBlockNode(md, nametable, ln.getBody(), condTupleNode);
1032 // check 'for loop' case
1033 BlockNode bn = ln.getInitializer();
1034 analyzeFlowBlockNode(md, bn.getVarTable(), bn, implicitFlowTupleSet);
1035 bn.getVarTable().setParent(nametable);
1037 NodeTupleSet condTupleNode = new NodeTupleSet();
1038 analyzeFlowExpressionNode(md, bn.getVarTable(), ln.getCondition(), condTupleNode, null,
1039 implicitFlowTupleSet, false);
1040 condTupleNode.addTupleSet(implicitFlowTupleSet);
1042 analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(), condTupleNode);
1043 analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(), condTupleNode);
1049 private void analyzeFlowIfStatementNode(MethodDescriptor md, SymbolTable nametable,
1050 IfStatementNode isn, NodeTupleSet implicitFlowTupleSet) {
1052 NodeTupleSet condTupleNode = new NodeTupleSet();
1053 analyzeFlowExpressionNode(md, nametable, isn.getCondition(), condTupleNode, null,
1054 implicitFlowTupleSet, false);
1056 // add edges from condNodeTupleSet to all nodes of conditional nodes
1057 condTupleNode.addTupleSet(implicitFlowTupleSet);
1058 analyzeFlowBlockNode(md, nametable, isn.getTrueBlock(), condTupleNode);
1060 if (isn.getFalseBlock() != null) {
1061 analyzeFlowBlockNode(md, nametable, isn.getFalseBlock(), condTupleNode);
1066 private void analyzeFlowDeclarationNode(MethodDescriptor md, SymbolTable nametable,
1067 DeclarationNode dn, NodeTupleSet implicitFlowTupleSet) {
1069 VarDescriptor vd = dn.getVarDescriptor();
1070 NTuple<Descriptor> tupleLHS = new NTuple<Descriptor>();
1072 getFlowGraph(md).createNewFlowNode(tupleLHS);
1074 if (dn.getExpression() != null) {
1076 NodeTupleSet tupleSetRHS = new NodeTupleSet();
1077 analyzeFlowExpressionNode(md, nametable, dn.getExpression(), tupleSetRHS, null,
1078 implicitFlowTupleSet, false);
1080 // add a new flow edge from rhs to lhs
1081 for (Iterator<NTuple<Descriptor>> iter = tupleSetRHS.iterator(); iter.hasNext();) {
1082 NTuple<Descriptor> from = iter.next();
1083 addFlowGraphEdge(md, from, tupleLHS);
1090 private void analyzeBlockExpressionNode(MethodDescriptor md, SymbolTable nametable,
1091 BlockExpressionNode ben, NodeTupleSet implicitFlowTupleSet) {
1092 analyzeFlowExpressionNode(md, nametable, ben.getExpression(), null, null, implicitFlowTupleSet,
1096 private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
1097 ExpressionNode en, NodeTupleSet nodeSet, boolean isLHS) {
1098 return analyzeFlowExpressionNode(md, nametable, en, nodeSet, null, new NodeTupleSet(), isLHS);
1101 private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
1102 ExpressionNode en, NodeTupleSet nodeSet, NTuple<Descriptor> base,
1103 NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
1105 // note that expression node can create more than one flow node
1106 // nodeSet contains of flow nodes
1107 // base is always assigned to null except the case of a name node!
1109 NTuple<Descriptor> flowTuple;
1111 switch (en.kind()) {
1113 case Kind.AssignmentNode:
1114 analyzeFlowAssignmentNode(md, nametable, (AssignmentNode) en, base, implicitFlowTupleSet);
1117 case Kind.FieldAccessNode:
1119 analyzeFlowFieldAccessNode(md, nametable, (FieldAccessNode) en, nodeSet, base,
1120 implicitFlowTupleSet);
1121 nodeSet.addTuple(flowTuple);
1125 NodeTupleSet nameNodeSet = new NodeTupleSet();
1127 analyzeFlowNameNode(md, nametable, (NameNode) en, nameNodeSet, base, implicitFlowTupleSet);
1128 nodeSet.addTuple(flowTuple);
1132 analyzeFlowOpNode(md, nametable, (OpNode) en, nodeSet, implicitFlowTupleSet);
1135 case Kind.CreateObjectNode:
1136 analyzeCreateObjectNode(md, nametable, (CreateObjectNode) en);
1139 case Kind.ArrayAccessNode:
1140 analyzeFlowArrayAccessNode(md, nametable, (ArrayAccessNode) en, nodeSet, isLHS);
1143 case Kind.LiteralNode:
1144 analyzeLiteralNode(md, nametable, (LiteralNode) en);
1147 case Kind.MethodInvokeNode:
1148 analyzeFlowMethodInvokeNode(md, nametable, (MethodInvokeNode) en, implicitFlowTupleSet);
1151 case Kind.TertiaryNode:
1152 analyzeFlowTertiaryNode(md, nametable, (TertiaryNode) en, nodeSet, implicitFlowTupleSet);
1156 analyzeFlowCastNode(md, nametable, (CastNode) en, implicitFlowTupleSet);
1159 // case Kind.InstanceOfNode:
1160 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
1163 // case Kind.ArrayInitializerNode:
1164 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
1168 // case Kind.ClassTypeNode:
1169 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
1172 // case Kind.OffsetNode:
1173 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
1181 private void analyzeFlowCastNode(MethodDescriptor md, SymbolTable nametable, CastNode cn,
1182 NodeTupleSet implicitFlowTupleSet) {
1184 NodeTupleSet nodeTupleSet = new NodeTupleSet();
1185 analyzeFlowExpressionNode(md, nametable, cn.getExpression(), nodeTupleSet, false);
1189 private void analyzeFlowTertiaryNode(MethodDescriptor md, SymbolTable nametable, TertiaryNode tn,
1190 NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
1192 NodeTupleSet tertiaryTupleNode = new NodeTupleSet();
1193 analyzeFlowExpressionNode(md, nametable, tn.getCond(), tertiaryTupleNode, null,
1194 implicitFlowTupleSet, false);
1196 // add edges from tertiaryTupleNode to all nodes of conditional nodes
1197 tertiaryTupleNode.addTupleSet(implicitFlowTupleSet);
1198 analyzeFlowExpressionNode(md, nametable, tn.getTrueExpr(), tertiaryTupleNode, null,
1199 implicitFlowTupleSet, false);
1201 analyzeFlowExpressionNode(md, nametable, tn.getFalseExpr(), tertiaryTupleNode, null,
1202 implicitFlowTupleSet, false);
1204 nodeSet.addTupleSet(tertiaryTupleNode);
1208 private void addMapCallerMethodDescToMethodInvokeNodeSet(MethodDescriptor caller,
1209 MethodInvokeNode min) {
1210 Set<MethodInvokeNode> set = mapMethodDescriptorToMethodInvokeNodeSet.get(caller);
1212 set = new HashSet<MethodInvokeNode>();
1213 mapMethodDescriptorToMethodInvokeNodeSet.put(caller, set);
1218 private void analyzeFlowMethodInvokeNode(MethodDescriptor md, SymbolTable nametable,
1219 MethodInvokeNode min, NodeTupleSet implicitFlowTupleSet) {
1221 addMapCallerMethodDescToMethodInvokeNodeSet(md, min);
1223 MethodDescriptor calleeMD = min.getMethod();
1225 NameDescriptor baseName = min.getBaseName();
1226 boolean isSystemout = false;
1227 if (baseName != null) {
1228 isSystemout = baseName.getSymbol().equals("System.out");
1231 if (!ssjava.isSSJavaUtil(calleeMD.getClassDesc()) && !ssjava.isTrustMethod(calleeMD)
1232 && !calleeMD.getModifiers().isNative() && !isSystemout) {
1234 // CompositeLocation baseLocation = null;
1235 if (min.getExpression() != null) {
1237 NodeTupleSet baseNodeSet = new NodeTupleSet();
1238 analyzeFlowExpressionNode(calleeMD, nametable, min.getExpression(), baseNodeSet, null,
1239 implicitFlowTupleSet, false);
1242 if (min.getMethod().isStatic()) {
1243 // String globalLocId = ssjava.getMethodLattice(md).getGlobalLoc();
1244 // if (globalLocId == null) {
1246 // Error("Method lattice does not define global variable location at "
1247 // + generateErrorMessage(md.getClassDesc(), min));
1249 // baseLocation = new CompositeLocation(new Location(md,
1253 // String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
1254 // baseLocation = new CompositeLocation(new Location(md, thisLocId));
1259 // if (constraint != null) {
1260 // int compareResult =
1261 // CompositeLattice.compare(constraint, baseLocation, true,
1262 // generateErrorMessage(cd, min));
1263 // if (compareResult != ComparisonResult.GREATER) {
1264 // // if the current constraint is higher than method's THIS location
1265 // // no need to check constraints!
1266 // CompositeLocation calleeConstraint =
1267 // translateCallerLocToCalleeLoc(calleeMD, baseLocation, constraint);
1268 // // System.out.println("check method body for constraint:" + calleeMD +
1269 // // " calleeConstraint="
1270 // // + calleeConstraint);
1271 // checkMethodBody(calleeMD.getClassDesc(), calleeMD, calleeConstraint);
1275 analyzeFlowMethodParameters(md, nametable, min);
1277 // checkCalleeConstraints(md, nametable, min, baseLocation, constraint);
1279 // checkCallerArgumentLocationConstraints(md, nametable, min,
1280 // baseLocation, constraint);
1282 if (!min.getMethod().getReturnType().isVoid()) {
1283 // If method has a return value, compute the highest possible return
1284 // location in the caller's perspective
1285 // CompositeLocation ceilingLoc =
1286 // computeCeilingLocationForCaller(md, nametable, min, baseLocation,
1288 // return ceilingLoc;
1292 // return new CompositeLocation(Location.createTopLocation(md));
1296 private NTuple<Descriptor> getArgTupleByArgIdx(MethodInvokeNode min, int idx) {
1297 return mapMethodInvokeNodeToArgIdxMap.get(min).get(new Integer(idx));
1300 private void addArgIdxMap(MethodInvokeNode min, int idx, NTuple<Descriptor> argTuple) {
1301 Map<Integer, NTuple<Descriptor>> mapIdxToArgTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
1302 if (mapIdxToArgTuple == null) {
1303 mapIdxToArgTuple = new HashMap<Integer, NTuple<Descriptor>>();
1304 mapMethodInvokeNodeToArgIdxMap.put(min, mapIdxToArgTuple);
1306 mapIdxToArgTuple.put(new Integer(idx), argTuple);
1309 private void analyzeFlowMethodParameters(MethodDescriptor callermd, SymbolTable nametable,
1310 MethodInvokeNode min) {
1312 if (min.numArgs() > 0) {
1314 int offset = min.getMethod().isStatic() ? 0 : 1;
1316 for (int i = 0; i < min.numArgs(); i++) {
1317 ExpressionNode en = min.getArg(i);
1318 NTuple<Descriptor> argTuple =
1319 analyzeFlowExpressionNode(callermd, nametable, en, new NodeTupleSet(), false);
1321 addArgIdxMap(min, i + offset, argTuple);
1328 private void analyzeLiteralNode(MethodDescriptor md, SymbolTable nametable, LiteralNode en) {
1329 // TODO Auto-generated method stub
1333 private void analyzeFlowArrayAccessNode(MethodDescriptor md, SymbolTable nametable,
1334 ArrayAccessNode aan, NodeTupleSet nodeSet, boolean isLHS) {
1336 NodeTupleSet expNodeTupleSet = new NodeTupleSet();
1337 analyzeFlowExpressionNode(md, nametable, aan.getExpression(), expNodeTupleSet, isLHS);
1339 NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
1340 analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, isLHS);
1343 // need to create an edge from idx to array
1345 for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
1346 NTuple<Descriptor> idxTuple = idxIter.next();
1347 for (Iterator<NTuple<Descriptor>> arrIter = expNodeTupleSet.iterator(); arrIter.hasNext();) {
1348 NTuple<Descriptor> arrTuple = arrIter.next();
1349 getFlowGraph(md).addValueFlowEdge(idxTuple, arrTuple);
1353 nodeSet.addTupleSet(expNodeTupleSet);
1355 nodeSet.addTupleSet(expNodeTupleSet);
1356 nodeSet.addTupleSet(idxNodeTupleSet);
1361 private void analyzeCreateObjectNode(MethodDescriptor md, SymbolTable nametable,
1362 CreateObjectNode en) {
1363 // TODO Auto-generated method stub
1367 private void analyzeFlowOpNode(MethodDescriptor md, SymbolTable nametable, OpNode on,
1368 NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
1370 NodeTupleSet leftOpSet = new NodeTupleSet();
1371 NodeTupleSet rightOpSet = new NodeTupleSet();
1374 analyzeFlowExpressionNode(md, nametable, on.getLeft(), leftOpSet, null, implicitFlowTupleSet,
1377 if (on.getRight() != null) {
1379 analyzeFlowExpressionNode(md, nametable, on.getRight(), rightOpSet, null,
1380 implicitFlowTupleSet, false);
1383 Operation op = on.getOp();
1385 switch (op.getOp()) {
1387 case Operation.UNARYPLUS:
1388 case Operation.UNARYMINUS:
1389 case Operation.LOGIC_NOT:
1391 nodeSet.addTupleSet(leftOpSet);
1394 case Operation.LOGIC_OR:
1395 case Operation.LOGIC_AND:
1396 case Operation.COMP:
1397 case Operation.BIT_OR:
1398 case Operation.BIT_XOR:
1399 case Operation.BIT_AND:
1400 case Operation.ISAVAILABLE:
1401 case Operation.EQUAL:
1402 case Operation.NOTEQUAL:
1409 case Operation.MULT:
1412 case Operation.LEFTSHIFT:
1413 case Operation.RIGHTSHIFT:
1414 case Operation.URIGHTSHIFT:
1416 // there are two operands
1417 nodeSet.addTupleSet(leftOpSet);
1418 nodeSet.addTupleSet(rightOpSet);
1422 throw new Error(op.toString());
1426 private NTuple<Descriptor> analyzeFlowNameNode(MethodDescriptor md, SymbolTable nametable,
1427 NameNode nn, NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
1430 base = new NTuple<Descriptor>();
1433 NameDescriptor nd = nn.getName();
1435 if (nd.getBase() != null) {
1436 analyzeFlowExpressionNode(md, nametable, nn.getExpression(), nodeSet, base,
1437 implicitFlowTupleSet, false);
1439 String varname = nd.toString();
1440 if (varname.equals("this")) {
1442 base.add(md.getThis());
1446 Descriptor d = (Descriptor) nametable.get(varname);
1448 if (d instanceof VarDescriptor) {
1449 VarDescriptor vd = (VarDescriptor) d;
1451 } else if (d instanceof FieldDescriptor) {
1452 // the type of field descriptor has a location!
1453 FieldDescriptor fd = (FieldDescriptor) d;
1454 if (fd.isStatic()) {
1456 // if it is 'static final', the location has TOP since no one can
1458 // loc.addLocation(Location.createTopLocation(md));
1461 // if 'static', the location has pre-assigned global loc
1462 // MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1463 // String globalLocId = localLattice.getGlobalLoc();
1464 // if (globalLocId == null) {
1466 // Error("Global location element is not defined in the method " +
1469 // Location globalLoc = new Location(md, globalLocId);
1471 // loc.addLocation(globalLoc);
1474 // the location of field access starts from this, followed by field
1476 base.add(md.getThis());
1480 } else if (d == null) {
1481 // access static field
1482 // FieldDescriptor fd = nn.getField();addFlowGraphEdge
1484 // MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1485 // String globalLocId = localLattice.getGlobalLoc();
1486 // if (globalLocId == null) {
1488 // Error("Method lattice does not define global variable location at "
1489 // + generateErrorMessage(md.getClassDesc(), nn));
1491 // loc.addLocation(new Location(md, globalLocId));
1493 // Location fieldLoc = (Location) fd.getType().getExtension();
1494 // loc.addLocation(fieldLoc);
1501 getFlowGraph(md).createNewFlowNode(base);
1507 private NTuple<Descriptor> analyzeFlowFieldAccessNode(MethodDescriptor md, SymbolTable nametable,
1508 FieldAccessNode fan, NodeTupleSet nodeSet, NTuple<Descriptor> base,
1509 NodeTupleSet implicitFlowTupleSet) {
1511 ExpressionNode left = fan.getExpression();
1512 TypeDescriptor ltd = left.getType();
1513 FieldDescriptor fd = fan.getField();
1515 String varName = null;
1516 if (left.kind() == Kind.NameNode) {
1517 NameDescriptor nd = ((NameNode) left).getName();
1518 varName = nd.toString();
1521 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1522 // using a class name directly or access using this
1523 if (fd.isStatic() && fd.isFinal()) {
1524 // loc.addLocation(Location.createTopLocation(md));
1529 // if (left instanceof ArrayAccessNode) {
1530 // ArrayAccessNode aan = (ArrayAccessNode) left;
1531 // left = aan.getExpression();
1535 analyzeFlowExpressionNode(md, nametable, left, nodeSet, base, implicitFlowTupleSet, false);
1537 if (!left.getType().isPrimitive()) {
1539 if (fd.getSymbol().equals("length")) {
1541 // array.length access, return the location of the array
1548 getFlowGraph(md).createNewFlowNode(base);
1553 private void analyzeFlowAssignmentNode(MethodDescriptor md, SymbolTable nametable,
1554 AssignmentNode an, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
1556 NodeTupleSet nodeSetRHS = new NodeTupleSet();
1557 NodeTupleSet nodeSetLHS = new NodeTupleSet();
1559 boolean postinc = true;
1560 if (an.getOperation().getBaseOp() == null
1561 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1562 .getBaseOp().getOp() != Operation.POSTDEC)) {
1566 // if LHS is array access node, need to capture value flows between an array
1567 // and its index value
1568 analyzeFlowExpressionNode(md, nametable, an.getDest(), nodeSetLHS, null, implicitFlowTupleSet,
1572 // analyze value flows of rhs expression
1573 analyzeFlowExpressionNode(md, nametable, an.getSrc(), nodeSetRHS, null, implicitFlowTupleSet,
1576 // creates edges from RHS to LHS
1577 for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
1578 NTuple<Descriptor> fromTuple = iter.next();
1579 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
1580 NTuple<Descriptor> toTuple = iter2.next();
1581 addFlowGraphEdge(md, fromTuple, toTuple);
1585 // creates edges from implicitFlowTupleSet to LHS
1586 for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
1587 NTuple<Descriptor> fromTuple = iter.next();
1588 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
1589 NTuple<Descriptor> toTuple = iter2.next();
1590 addFlowGraphEdge(md, fromTuple, toTuple);
1596 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
1597 NTuple<Descriptor> tuple = iter2.next();
1598 addFlowGraphEdge(md, tuple, tuple);
1605 public FlowGraph getFlowGraph(MethodDescriptor md) {
1606 return mapMethodDescriptorToFlowGraph.get(md);
1609 private boolean addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
1610 NTuple<Descriptor> to) {
1612 // return true if it adds a new edge
1613 FlowGraph graph = getFlowGraph(md);
1614 graph.addValueFlowEdge(from, to);
1618 public void _debug_printGraph() {
1619 Set<MethodDescriptor> keySet = mapMethodDescriptorToFlowGraph.keySet();
1621 for (Iterator<MethodDescriptor> iterator = keySet.iterator(); iterator.hasNext();) {
1622 MethodDescriptor md = (MethodDescriptor) iterator.next();
1623 FlowGraph fg = mapMethodDescriptorToFlowGraph.get(md);
1626 } catch (IOException e) {
1627 e.printStackTrace();