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;
47 import IR.Tree.TreeNode;
49 public class LocationInference {
52 SSJavaAnalysis ssjava;
54 List<ClassDescriptor> toanalyzeList;
55 List<MethodDescriptor> toanalyzeMethodList;
56 Map<MethodDescriptor, FlowGraph> mapMethodDescriptorToFlowGraph;
58 // map a method descriptor to its set of parameter descriptors
59 Map<MethodDescriptor, Set<Descriptor>> mapMethodDescriptorToParamDescSet;
61 // keep current descriptors to visit in fixed-point interprocedural analysis,
62 private Stack<MethodDescriptor> methodDescriptorsToVisitStack;
64 // map a class descriptor to a field lattice
65 private Map<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
67 // map a method descriptor to a method lattice
68 private Map<MethodDescriptor, SSJavaLattice<String>> md2lattice;
70 // map a method descriptor to the set of method invocation nodes which are
71 // invoked by the method descriptor
72 private Map<MethodDescriptor, Set<MethodInvokeNode>> mapMethodDescriptorToMethodInvokeNodeSet;
74 private Map<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>> mapMethodInvokeNodeToArgIdxMap;
76 private Map<MethodDescriptor, MethodLocationInfo> mapMethodDescToMethodLocationInfo;
78 private Map<ClassDescriptor, LocationInfo> mapClassToLocationInfo;
80 private Map<MethodDescriptor, Set<MethodDescriptor>> mapMethodDescToPossibleMethodDescSet;
82 public static final String GLOBALLOC = "GLOBALLOC";
84 public static final String TOPLOC = "TOPLOC";
86 public static final Descriptor GLOBALDESC = new NameDescriptor(GLOBALLOC);
88 public static final Descriptor TOPDESC = new NameDescriptor(TOPLOC);
92 public LocationInference(SSJavaAnalysis ssjava, State state) {
95 this.toanalyzeList = new ArrayList<ClassDescriptor>();
96 this.toanalyzeMethodList = new ArrayList<MethodDescriptor>();
97 this.mapMethodDescriptorToFlowGraph = new HashMap<MethodDescriptor, FlowGraph>();
98 this.cd2lattice = new HashMap<ClassDescriptor, SSJavaLattice<String>>();
99 this.md2lattice = new HashMap<MethodDescriptor, SSJavaLattice<String>>();
100 this.methodDescriptorsToVisitStack = new Stack<MethodDescriptor>();
101 this.mapMethodDescriptorToMethodInvokeNodeSet =
102 new HashMap<MethodDescriptor, Set<MethodInvokeNode>>();
103 this.mapMethodInvokeNodeToArgIdxMap =
104 new HashMap<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>>();
105 this.mapMethodDescToMethodLocationInfo = new HashMap<MethodDescriptor, MethodLocationInfo>();
106 this.mapMethodDescToPossibleMethodDescSet =
107 new HashMap<MethodDescriptor, Set<MethodDescriptor>>();
108 this.mapClassToLocationInfo = new HashMap<ClassDescriptor, LocationInfo>();
111 public void setupToAnalyze() {
112 SymbolTable classtable = state.getClassSymbolTable();
113 toanalyzeList.clear();
114 toanalyzeList.addAll(classtable.getValueSet());
115 Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
116 public int compare(ClassDescriptor o1, ClassDescriptor o2) {
117 return o1.getClassName().compareToIgnoreCase(o2.getClassName());
122 public void setupToAnalazeMethod(ClassDescriptor cd) {
124 SymbolTable methodtable = cd.getMethodTable();
125 toanalyzeMethodList.clear();
126 toanalyzeMethodList.addAll(methodtable.getValueSet());
127 Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
128 public int compare(MethodDescriptor o1, MethodDescriptor o2) {
129 return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
134 public boolean toAnalyzeMethodIsEmpty() {
135 return toanalyzeMethodList.isEmpty();
138 public boolean toAnalyzeIsEmpty() {
139 return toanalyzeList.isEmpty();
142 public ClassDescriptor toAnalyzeNext() {
143 return toanalyzeList.remove(0);
146 public MethodDescriptor toAnalyzeMethodNext() {
147 return toanalyzeMethodList.remove(0);
150 public void inference() {
152 // 1) construct value flow graph
153 constructFlowGraph();
155 // 2) construct lattices
160 debug_writeLatticeDotFile();
162 // 3) check properties
167 private void simplifyLattices() {
169 // generate lattice dot file
172 while (!toAnalyzeIsEmpty()) {
173 ClassDescriptor cd = toAnalyzeNext();
175 setupToAnalazeMethod(cd);
177 SSJavaLattice<String> classLattice = cd2lattice.get(cd);
178 if (classLattice != null) {
179 classLattice.removeRedundantEdges();
182 while (!toAnalyzeMethodIsEmpty()) {
183 MethodDescriptor md = toAnalyzeMethodNext();
184 if (ssjava.needTobeAnnotated(md)) {
185 SSJavaLattice<String> methodLattice = md2lattice.get(md);
186 if (methodLattice != null) {
187 methodLattice.removeRedundantEdges();
195 private void checkLattices() {
197 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
199 // current descriptors to visit in fixed-point interprocedural analysis,
201 // dependency in the call graph
202 methodDescriptorsToVisitStack.clear();
204 descriptorListToAnalyze.removeFirst();
206 Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
207 methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
209 while (!descriptorListToAnalyze.isEmpty()) {
210 MethodDescriptor md = descriptorListToAnalyze.removeFirst();
211 checkLatticesOfVirtualMethods(md);
216 private void debug_writeLatticeDotFile() {
217 // generate lattice dot file
221 while (!toAnalyzeIsEmpty()) {
222 ClassDescriptor cd = toAnalyzeNext();
224 setupToAnalazeMethod(cd);
226 SSJavaLattice<String> classLattice = cd2lattice.get(cd);
227 if (classLattice != null) {
228 ssjava.writeLatticeDotFile(cd, null, classLattice);
229 debug_printDescriptorToLocNameMapping(cd);
232 while (!toAnalyzeMethodIsEmpty()) {
233 MethodDescriptor md = toAnalyzeMethodNext();
234 if (ssjava.needTobeAnnotated(md)) {
235 SSJavaLattice<String> methodLattice = md2lattice.get(md);
236 if (methodLattice != null) {
237 ssjava.writeLatticeDotFile(cd, md, methodLattice);
238 debug_printDescriptorToLocNameMapping(md);
246 private void debug_printDescriptorToLocNameMapping(Descriptor desc) {
248 LocationInfo info = getLocationInfo(desc);
249 System.out.println("## " + desc + " ##");
250 System.out.println(info.getMapDescToInferLocation());
251 LocationInfo locInfo = getLocationInfo(desc);
252 System.out.println("mapping=" + locInfo.getMapLocSymbolToDescSet());
253 System.out.println("###################");
257 private void inferLattices() {
259 // do fixed-point analysis
261 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
263 // current descriptors to visit in fixed-point interprocedural analysis,
265 // dependency in the call graph
266 methodDescriptorsToVisitStack.clear();
268 descriptorListToAnalyze.removeFirst();
270 Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
271 methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
273 while (!descriptorListToAnalyze.isEmpty()) {
274 MethodDescriptor md = descriptorListToAnalyze.removeFirst();
275 methodDescriptorsToVisitStack.add(md);
278 // analyze scheduled methods until there are no more to visit
279 while (!methodDescriptorsToVisitStack.isEmpty()) {
280 // start to analyze leaf node
281 MethodDescriptor md = methodDescriptorsToVisitStack.pop();
283 SSJavaLattice<String> methodLattice =
284 new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM);
286 MethodLocationInfo methodInfo = new MethodLocationInfo(md);
288 System.out.println();
289 System.out.println("SSJAVA: Inferencing the lattice from " + md);
291 analyzeMethodLattice(md, methodLattice, methodInfo);
293 SSJavaLattice<String> prevMethodLattice = getMethodLattice(md);
294 MethodLocationInfo prevMethodInfo = getMethodLocationInfo(md);
296 if ((!methodLattice.equals(prevMethodLattice)) || (!methodInfo.equals(prevMethodInfo))) {
298 setMethodLattice(md, methodLattice);
299 setMethodLocInfo(md, methodInfo);
301 // results for callee changed, so enqueue dependents caller for
303 Iterator<MethodDescriptor> depsItr = ssjava.getDependents(md).iterator();
304 while (depsItr.hasNext()) {
305 MethodDescriptor methodNext = depsItr.next();
306 if (!methodDescriptorsToVisitStack.contains(methodNext)
307 && methodDescriptorToVistSet.contains(methodNext)) {
308 methodDescriptorsToVisitStack.add(methodNext);
318 private void setMethodLocInfo(MethodDescriptor md, MethodLocationInfo methodInfo) {
319 mapMethodDescToMethodLocationInfo.put(md, methodInfo);
322 private void checkLatticesOfVirtualMethods(MethodDescriptor md) {
324 if (!md.isStatic()) {
325 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
326 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
328 for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
329 MethodDescriptor mdCallee = (MethodDescriptor) iterator.next();
330 if (!md.equals(mdCallee)) {
331 checkConsistency(md, mdCallee);
339 private void checkConsistency(MethodDescriptor md1, MethodDescriptor md2) {
341 // check that two lattice have the same relations between parameters(+PC
344 MethodLocationInfo methodInfo1 = getMethodLocationInfo(md1);
346 SSJavaLattice<String> lattice1 = getMethodLattice(md1);
347 SSJavaLattice<String> lattice2 = getMethodLattice(md2);
349 Set<String> paramLocNameSet1 = methodInfo1.getParameterLocNameSet();
351 for (Iterator iterator = paramLocNameSet1.iterator(); iterator.hasNext();) {
352 String locName1 = (String) iterator.next();
353 for (Iterator iterator2 = paramLocNameSet1.iterator(); iterator2.hasNext();) {
354 String locName2 = (String) iterator2.next();
356 if (!locName1.equals(locName2)) {
358 boolean r1 = lattice1.isGreaterThan(locName1, locName2);
359 boolean r2 = lattice2.isGreaterThan(locName1, locName2);
362 throw new Error("The method " + md1 + " is not consistent with the method " + md2
363 + ".:: They have a different ordering relation between parameters " + locName1
364 + " and " + locName2 + ".");
373 private String getSymbol(int idx, FlowNode node) {
374 Descriptor desc = node.getDescTuple().get(idx);
375 return desc.getSymbol();
378 private Descriptor getDescriptor(int idx, FlowNode node) {
379 Descriptor desc = node.getDescTuple().get(idx);
383 private void analyzeMethodLattice(MethodDescriptor md, SSJavaLattice<String> methodLattice,
384 MethodLocationInfo methodInfo) {
386 // first take a look at method invocation nodes to newly added relations
388 analyzeLatticeMethodInvocationNode(md);
390 // set the this location
391 String thisLocSymbol = md.getThis().getSymbol();
392 methodInfo.setThisLocName(thisLocSymbol);
394 // set the global location
395 methodInfo.setGlobalLocName(LocationInference.GLOBALLOC);
397 // visit each node of method flow graph
398 FlowGraph fg = getFlowGraph(md);
399 Set<FlowNode> nodeSet = fg.getNodeSet();
401 // for the method lattice, we need to look at the first element of
402 // NTuple<Descriptor>
403 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
404 FlowNode srcNode = (FlowNode) iterator.next();
406 Set<FlowEdge> outEdgeSet = srcNode.getOutEdgeSet();
407 for (Iterator iterator2 = outEdgeSet.iterator(); iterator2.hasNext();) {
408 FlowEdge outEdge = (FlowEdge) iterator2.next();
409 FlowNode dstNode = outEdge.getDst();
411 NTuple<Descriptor> srcNodeTuple = srcNode.getDescTuple();
412 NTuple<Descriptor> dstNodeTuple = dstNode.getDescTuple();
414 if (outEdge.getInitTuple().equals(srcNodeTuple)
415 && outEdge.getEndTuple().equals(dstNodeTuple)) {
417 if ((srcNodeTuple.size() > 1 && dstNodeTuple.size() > 1)
418 && srcNodeTuple.get(0).equals(dstNodeTuple.get(0))) {
420 // value flows between fields
421 VarDescriptor varDesc = (VarDescriptor) srcNodeTuple.get(0);
422 ClassDescriptor varClassDesc = varDesc.getType().getClassDesc();
423 extractRelationFromFieldFlows(varClassDesc, srcNode, dstNode, 1);
425 } else if (srcNodeTuple.size() == 1 || dstNodeTuple.size() == 1) {
426 // for the method lattice, we need to look at the first element of
427 // NTuple<Descriptor>
428 // in this case, take a look at connected nodes at the local level
429 addRelationToLattice(md, methodLattice, methodInfo, srcNode, dstNode);
432 if (!srcNode.getDescTuple().get(0).equals(dstNode.getDescTuple().get(0))) {
433 // in this case, take a look at connected nodes at the local level
434 addRelationToLattice(md, methodLattice, methodInfo, srcNode, dstNode);
436 Descriptor srcDesc = srcNode.getDescTuple().get(0);
437 Descriptor dstDesc = dstNode.getDescTuple().get(0);
438 recursivelyAddCompositeRelation(md, fg, methodInfo, srcNode, dstNode, srcDesc,
440 // recursiveAddRelationToLattice(1, md, srcNode, dstNode);
448 // calculate a return location
449 if (!md.getReturnType().isVoid()) {
450 Set<FlowNode> returnNodeSet = fg.getReturnNodeSet();
451 Set<String> returnVarSymbolSet = new HashSet<String>();
453 for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
454 FlowNode rtrNode = (FlowNode) iterator.next();
456 methodInfo.getInferLocation(rtrNode.getDescTuple().get(0)).get(0).getLocIdentifier();
457 returnVarSymbolSet.add(localSymbol);
460 String returnGLB = methodLattice.getGLB(returnVarSymbolSet);
461 if (returnGLB.equals(SSJavaAnalysis.BOTTOM)) {
462 // need to insert a new location in-between the bottom and all locations
463 // that is directly connected to the bottom
464 String returnNewLocationSymbol = "Loc" + (SSJavaLattice.seed++);
465 methodLattice.insertNewLocationAtOneLevelHigher(returnGLB, returnNewLocationSymbol);
466 methodInfo.setReturnLocName(returnNewLocationSymbol);
468 methodInfo.setReturnLocName(returnGLB);
474 private void recursiveAddRelationToLattice(int idx, MethodDescriptor md,
475 CompositeLocation srcInferLoc, CompositeLocation dstInferLoc) {
477 String srcLocSymbol = srcInferLoc.get(idx).getLocIdentifier();
478 String dstLocSymbol = dstInferLoc.get(idx).getLocIdentifier();
480 if (srcLocSymbol.equals(dstLocSymbol)) {
481 recursiveAddRelationToLattice(idx + 1, md, srcInferLoc, dstInferLoc);
484 Descriptor parentDesc = srcInferLoc.get(idx).getDescriptor();
485 LocationInfo locInfo = getLocationInfo(parentDesc);
487 addRelationHigherToLower(getLattice(parentDesc), getLocationInfo(parentDesc), srcLocSymbol,
493 private void analyzeLatticeMethodInvocationNode(MethodDescriptor mdCaller) {
495 // the transformation for a call site propagates all relations between
496 // parameters from the callee
497 // if the method is virtual, it also grab all relations from any possible
500 Set<MethodInvokeNode> setMethodInvokeNode =
501 mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
502 if (setMethodInvokeNode != null) {
504 for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
505 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
506 MethodDescriptor mdCallee = min.getMethod();
507 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
508 if (mdCallee.isStatic()) {
509 setPossibleCallees.add(mdCallee);
511 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(mdCallee));
514 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
515 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
516 propagateRelationToCaller(min, mdCaller, possibleMdCallee);
524 private void propagateRelationToCaller(MethodInvokeNode min, MethodDescriptor mdCaller,
525 MethodDescriptor possibleMdCallee) {
527 SSJavaLattice<String> calleeLattice = getMethodLattice(possibleMdCallee);
529 FlowGraph calleeFlowGraph = getFlowGraph(possibleMdCallee);
531 // find parameter node
532 Set<FlowNode> paramNodeSet = calleeFlowGraph.getParameterNodeSet();
534 for (Iterator iterator = paramNodeSet.iterator(); iterator.hasNext();) {
535 FlowNode paramFlowNode1 = (FlowNode) iterator.next();
537 for (Iterator iterator2 = paramNodeSet.iterator(); iterator2.hasNext();) {
538 FlowNode paramFlowNode2 = (FlowNode) iterator2.next();
540 String paramSymbol1 = getSymbol(0, paramFlowNode1);
541 String paramSymbol2 = getSymbol(0, paramFlowNode2);
542 // if two parameters have a relation, we need to propagate this relation
544 if (!(paramSymbol1.equals(paramSymbol2))
545 && calleeLattice.isComparable(paramSymbol1, paramSymbol2)) {
546 int higherLocIdxCallee;
547 int lowerLocIdxCallee;
548 if (calleeLattice.isGreaterThan(paramSymbol1, paramSymbol2)) {
549 higherLocIdxCallee = calleeFlowGraph.getParamIdx(paramFlowNode1.getDescTuple());
550 lowerLocIdxCallee = calleeFlowGraph.getParamIdx(paramFlowNode2.getDescTuple());
552 higherLocIdxCallee = calleeFlowGraph.getParamIdx(paramFlowNode2.getDescTuple());
553 lowerLocIdxCallee = calleeFlowGraph.getParamIdx(paramFlowNode1.getDescTuple());
556 NTuple<Descriptor> higherArg = getArgTupleByArgIdx(min, higherLocIdxCallee);
557 NTuple<Descriptor> lowerArg = getArgTupleByArgIdx(min, lowerLocIdxCallee);
559 addFlowGraphEdge(mdCaller, higherArg, lowerArg);
569 private LocationInfo getLocationInfo(Descriptor d) {
570 if (d instanceof MethodDescriptor) {
571 return getMethodLocationInfo((MethodDescriptor) d);
573 return getFieldLocationInfo((ClassDescriptor) d);
577 private MethodLocationInfo getMethodLocationInfo(MethodDescriptor md) {
579 if (!mapMethodDescToMethodLocationInfo.containsKey(md)) {
580 mapMethodDescToMethodLocationInfo.put(md, new MethodLocationInfo(md));
583 return mapMethodDescToMethodLocationInfo.get(md);
587 private LocationInfo getFieldLocationInfo(ClassDescriptor cd) {
589 if (!mapClassToLocationInfo.containsKey(cd)) {
590 mapClassToLocationInfo.put(cd, new LocationInfo(cd));
593 return mapClassToLocationInfo.get(cd);
597 private void addRelationToLattice(MethodDescriptor md, SSJavaLattice<String> methodLattice,
598 MethodLocationInfo methodInfo, FlowNode srcNode, FlowNode dstNode) {
600 System.out.println();
601 System.out.println("### addRelationToLattice src=" + srcNode + " dst=" + dstNode);
603 // add a new binary relation of dstNode < srcNode
604 FlowGraph flowGraph = getFlowGraph(md);
605 // MethodLocationInfo methodInfo = getMethodLocationInfo(md);
607 // String srcOriginSymbol = getSymbol(0, srcNode);
608 // String dstOriginSymbol = getSymbol(0, dstNode);
610 Descriptor srcDesc = getDescriptor(0, srcNode);
611 Descriptor dstDesc = getDescriptor(0, dstNode);
613 // consider a composite location case
614 boolean isSrcLocalVar = false;
615 boolean isDstLocalVar = false;
616 if (srcNode.getDescTuple().size() == 1) {
617 isSrcLocalVar = true;
620 if (dstNode.getDescTuple().size() == 1) {
621 isDstLocalVar = true;
624 boolean isAssignedCompositeLocation = false;
625 if (!methodInfo.getInferLocation(srcDesc).get(0).getLocIdentifier()
626 .equals(methodInfo.getThisLocName())) {
627 isAssignedCompositeLocation =
628 calculateCompositeLocation(flowGraph, methodLattice, methodInfo, srcNode);
631 String srcSymbol = methodInfo.getInferLocation(srcDesc).get(0).getLocIdentifier();
632 String dstSymbol = methodInfo.getInferLocation(dstDesc).get(0).getLocIdentifier();
634 if (srcNode.isParameter()) {
635 int paramIdx = flowGraph.getParamIdx(srcNode.getDescTuple());
636 methodInfo.addParameter(srcSymbol, srcDesc, paramIdx);
638 // methodInfo.addMappingOfLocNameToDescriptor(srcSymbol, srcDesc);
641 if (dstNode.isParameter()) {
642 int paramIdx = flowGraph.getParamIdx(dstNode.getDescTuple());
643 methodInfo.addParameter(dstSymbol, dstDesc, paramIdx);
645 // methodInfo.addMappingOfLocNameToDescriptor(dstSymbol, dstDesc);
648 if (!isAssignedCompositeLocation) {
649 // source does not have a composite location
650 if (!srcSymbol.equals(dstSymbol)) {
651 // add a local relation
652 if (!methodLattice.isGreaterThan(srcSymbol, dstSymbol)) {
653 // if the lattice does not have this relation, add it
654 addRelationHigherToLower(methodLattice, methodInfo, srcSymbol, dstSymbol);
655 // methodLattice.addRelationHigherToLower(srcSymbol, dstSymbol);
658 // if src and dst have the same local location...
660 recursivelyAddCompositeRelation(md, flowGraph, methodInfo, srcNode, dstNode, srcDesc,
666 // source variable has a composite location
667 if (methodInfo.getInferLocation(dstDesc).getSize() == 1) {
668 if (!srcSymbol.equals(dstSymbol)) {
669 addRelationHigherToLower(methodLattice, methodInfo, srcSymbol, dstSymbol);
677 private void recursivelyAddCompositeRelation(MethodDescriptor md, FlowGraph flowGraph,
678 MethodLocationInfo methodInfo, FlowNode srcNode, FlowNode dstNode, Descriptor srcDesc,
679 Descriptor dstDesc) {
681 CompositeLocation inferSrcLoc;
682 CompositeLocation inferDstLoc = methodInfo.getInferLocation(dstDesc);
684 if (srcNode.getDescTuple().size() > 1) {
686 inferSrcLoc = new CompositeLocation();
688 NTuple<Location> locTuple = flowGraph.getLocationTuple(srcNode);
689 for (int i = 0; i < locTuple.size(); i++) {
690 inferSrcLoc.addLocation(locTuple.get(i));
694 inferSrcLoc = methodInfo.getInferLocation(srcDesc);
697 if (dstNode.getDescTuple().size() > 1) {
699 inferDstLoc = new CompositeLocation();
701 NTuple<Location> locTuple = flowGraph.getLocationTuple(dstNode);
702 for (int i = 0; i < locTuple.size(); i++) {
703 inferDstLoc.addLocation(locTuple.get(i));
707 inferDstLoc = methodInfo.getInferLocation(dstDesc);
710 recursiveAddRelationToLattice(1, md, inferSrcLoc, inferDstLoc);
713 private void addPrefixMapping(Map<NTuple<Location>, Set<NTuple<Location>>> map,
714 NTuple<Location> prefix, NTuple<Location> element) {
716 if (!map.containsKey(prefix)) {
717 map.put(prefix, new HashSet<NTuple<Location>>());
719 map.get(prefix).add(element);
722 private boolean calculateCompositeLocation(FlowGraph flowGraph,
723 SSJavaLattice<String> methodLattice, MethodLocationInfo methodInfo, FlowNode flowNode) {
725 Descriptor localVarDesc = flowNode.getDescTuple().get(0);
727 Set<FlowNode> inNodeSet = flowGraph.getIncomingFlowNodeSet(flowNode);
728 Set<FlowNode> reachableNodeSet = flowGraph.getReachableFlowNodeSet(flowNode);
730 Map<NTuple<Location>, Set<NTuple<Location>>> mapPrefixToIncomingLocTupleSet =
731 new HashMap<NTuple<Location>, Set<NTuple<Location>>>();
733 Set<FlowNode> localInNodeSet = new HashSet<FlowNode>();
734 Set<FlowNode> localOutNodeSet = new HashSet<FlowNode>();
736 List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
738 for (Iterator iterator = inNodeSet.iterator(); iterator.hasNext();) {
739 FlowNode inNode = (FlowNode) iterator.next();
740 NTuple<Location> inTuple = flowGraph.getLocationTuple(inNode);
742 if (inTuple.size() > 1) {
743 for (int i = 1; i < inTuple.size(); i++) {
744 NTuple<Location> prefix = inTuple.subList(0, i);
745 if (!prefixList.contains(prefix)) {
746 prefixList.add(prefix);
748 addPrefixMapping(mapPrefixToIncomingLocTupleSet, prefix, inTuple);
751 localInNodeSet.add(inNode);
755 Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
756 public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
757 int s0 = arg0.size();
758 int s1 = arg1.size();
761 } else if (s0 == s1) {
769 for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
770 FlowNode reachableNode = (FlowNode) iterator2.next();
771 if (reachableNode.getDescTuple().size() == 1) {
772 localOutNodeSet.add(reachableNode);
776 // find out reachable nodes that have the longest common prefix
777 for (int i = 0; i < prefixList.size(); i++) {
778 NTuple<Location> curPrefix = prefixList.get(i);
779 Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
781 for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
782 FlowNode reachableNode = (FlowNode) iterator2.next();
783 NTuple<Location> reachLocTuple = flowGraph.getLocationTuple(reachableNode);
784 if (reachLocTuple.startsWith(curPrefix)) {
785 reachableCommonPrefixSet.add(reachLocTuple);
790 if (!reachableCommonPrefixSet.isEmpty()) {
791 // found reachable nodes that start with the prefix curPrefix
792 // need to assign a composite location
794 // first, check if there are more than one the set of locations that has
795 // the same length of the longest reachable prefix, no way to assign
796 // a composite location to the input local var
797 prefixSanityCheck(prefixList, i, flowGraph, reachableNodeSet);
799 Set<NTuple<Location>> incomingCommonPrefixSet =
800 mapPrefixToIncomingLocTupleSet.get(curPrefix);
802 int idx = curPrefix.size();
803 NTuple<Location> element = incomingCommonPrefixSet.iterator().next();
804 Descriptor desc = element.get(idx).getDescriptor();
806 SSJavaLattice<String> lattice = getLattice(desc);
807 LocationInfo locInfo = getLocationInfo(desc);
809 // CompositeLocation inferLocation =
810 // methodInfo.getInferLocation(flowNode);
811 CompositeLocation inferLocation = methodInfo.getInferLocation(localVarDesc);
813 String newlyInsertedLocName;
814 if (inferLocation.getSize() == 1) {
815 // need to replace the old local location with a new composite
818 String oldMethodLocationSymbol = inferLocation.get(0).getLocIdentifier();
820 String newLocSymbol = "Loc" + (SSJavaLattice.seed++);
821 inferLocation = new CompositeLocation();
822 for (int locIdx = 0; locIdx < curPrefix.size(); locIdx++) {
823 inferLocation.addLocation(curPrefix.get(locIdx));
825 Location fieldLoc = new Location(desc, newLocSymbol);
826 inferLocation.addLocation(fieldLoc);
828 methodInfo.mapDescriptorToLocation(localVarDesc, inferLocation);
829 methodInfo.removeMaplocalVarToLocSet(localVarDesc);
831 String newMethodLocationSymbol = curPrefix.get(0).getLocIdentifier();
833 replaceOldLocWithNewLoc(methodLattice, oldMethodLocationSymbol, newMethodLocationSymbol);
837 String localLocName = methodInfo.getInferLocation(localVarDesc).get(0).getLocIdentifier();
842 newlyInsertedLocName = inferLocation.get(inferLocation.getSize() - 1).getLocIdentifier();
844 for (Iterator iterator = incomingCommonPrefixSet.iterator(); iterator.hasNext();) {
845 NTuple<Location> tuple = (NTuple<Location>) iterator.next();
847 Location loc = tuple.get(idx);
848 String higher = locInfo.getFieldInferLocation(loc.getLocDescriptor()).getLocIdentifier();
849 System.out.println("--");
850 System.out.println("add in-flow relation:");
851 addRelationHigherToLower(lattice, locInfo, higher, newlyInsertedLocName);
853 System.out.println("end of add-inflow relation");
855 for (Iterator iterator = localInNodeSet.iterator(); iterator.hasNext();) {
856 FlowNode localNode = (FlowNode) iterator.next();
857 Descriptor localInVarDesc = localNode.getDescTuple().get(0);
858 CompositeLocation inNodeInferLoc = methodInfo.getInferLocation(localInVarDesc);
860 if (isCompositeLocation(inNodeInferLoc)) {
861 // need to make sure that newLocSymbol is lower than the infernode
862 // location in the field lattice
864 if (inNodeInferLoc.getTuple().startsWith(curPrefix)
865 && inNodeInferLoc.getSize() == (curPrefix.size() + 1)) {
866 String higher = inNodeInferLoc.get(inNodeInferLoc.getSize() - 1).getLocIdentifier();
867 if (!higher.equals(newlyInsertedLocName)) {
868 System.out.println("add localInNodeSet relation:");
869 addRelationHigherToLower(lattice, locInfo, higher, newlyInsertedLocName);
872 throw new Error("Failed to generate a composite location.");
878 for (Iterator iterator = reachableCommonPrefixSet.iterator(); iterator.hasNext();) {
879 NTuple<Location> tuple = (NTuple<Location>) iterator.next();
880 Location loc = tuple.get(idx);
881 String lower = locInfo.getFieldInferLocation(loc.getLocDescriptor()).getLocIdentifier();
882 // lattice.addRelationHigherToLower(newlyInsertedLocName, lower);
883 System.out.println("add out-flow relation:");
884 addRelationHigherToLower(lattice, locInfo, newlyInsertedLocName, lower);
886 System.out.println("end of add out-flow relation");
888 for (Iterator iterator = localOutNodeSet.iterator(); iterator.hasNext();) {
889 FlowNode localOutNode = (FlowNode) iterator.next();
891 Descriptor localOutDesc = localOutNode.getDescTuple().get(0);
892 // String localOutNodeSymbol =
893 // localOutNode.getDescTuple().get(0).getSymbol();
894 CompositeLocation outNodeInferLoc = methodInfo.getInferLocation(localOutDesc);
897 // .println("localOutNode=" + localOutNode + " outNodeInferLoc=" +
899 if (isCompositeLocation(outNodeInferLoc)) {
900 // need to make sure that newLocSymbol is higher than the infernode
903 if (outNodeInferLoc.getTuple().startsWith(curPrefix)
904 && outNodeInferLoc.getSize() == (curPrefix.size() + 1)) {
906 String lower = outNodeInferLoc.get(outNodeInferLoc.getSize() - 1).getLocIdentifier();
907 System.out.println("add outNodeInferLoc relation:");
909 addRelationHigherToLower(lattice, locInfo, newlyInsertedLocName, lower);
912 throw new Error("Failed to generate a composite location.");
926 private boolean isCompositeLocation(CompositeLocation cl) {
927 return cl.getSize() > 1;
930 private boolean containsNonPrimitiveElement(Set<Descriptor> descSet) {
931 for (Iterator iterator = descSet.iterator(); iterator.hasNext();) {
932 Descriptor desc = (Descriptor) iterator.next();
934 if (desc.equals(LocationInference.GLOBALDESC)) {
936 } else if (desc instanceof VarDescriptor) {
937 if (!((VarDescriptor) desc).getType().isPrimitive()) {
940 } else if (desc instanceof FieldDescriptor) {
941 if (!((FieldDescriptor) desc).getType().isPrimitive()) {
950 private void addRelationHigherToLower(SSJavaLattice<String> lattice, LocationInfo locInfo,
951 String higher, String lower) {
953 // if (higher.equals(lower) && lattice.isSharedLoc(higher)) {
957 Set<String> cycleElementSet = lattice.getPossibleCycleElements(higher, lower);
958 System.out.println("#Check cycle=" + lower + " < " + higher);
959 System.out.println("#cycleElementSet=" + cycleElementSet);
961 boolean hasNonPrimitiveElement = false;
962 for (Iterator iterator = cycleElementSet.iterator(); iterator.hasNext();) {
963 String cycleElementLocSymbol = (String) iterator.next();
965 Set<Descriptor> descSet = locInfo.getDescSet(cycleElementLocSymbol);
966 if (containsNonPrimitiveElement(descSet)) {
967 hasNonPrimitiveElement = true;
972 if (hasNonPrimitiveElement) {
973 // if there is non-primitive element in the cycle, no way to merge cyclic
974 // elements into the shared location
975 throw new Error("Failed to merge cyclic value flows into a shared location.");
978 if (cycleElementSet.size() > 0) {
979 String newSharedLoc = "SharedLoc" + (SSJavaLattice.seed++);
981 lattice.mergeIntoSharedLocation(cycleElementSet, newSharedLoc);
983 for (Iterator iterator = cycleElementSet.iterator(); iterator.hasNext();) {
984 String oldLocSymbol = (String) iterator.next();
985 locInfo.mergeMapping(oldLocSymbol, newSharedLoc);
988 lattice.addSharedLoc(newSharedLoc);
990 } else if (!lattice.isGreaterThan(higher, lower)) {
991 lattice.addRelationHigherToLower(higher, lower);
995 private void replaceOldLocWithNewLoc(SSJavaLattice<String> methodLattice, String oldLocSymbol,
996 String newLocSymbol) {
998 if (methodLattice.containsKey(oldLocSymbol)) {
999 methodLattice.substituteLocation(oldLocSymbol, newLocSymbol);
1004 private void prefixSanityCheck(List<NTuple<Location>> prefixList, int curIdx,
1005 FlowGraph flowGraph, Set<FlowNode> reachableNodeSet) {
1007 NTuple<Location> curPrefix = prefixList.get(curIdx);
1009 for (int i = curIdx + 1; i < prefixList.size(); i++) {
1010 NTuple<Location> prefixTuple = prefixList.get(i);
1012 if (curPrefix.startsWith(prefixTuple)) {
1016 for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
1017 FlowNode reachableNode = (FlowNode) iterator2.next();
1018 NTuple<Location> reachLocTuple = flowGraph.getLocationTuple(reachableNode);
1019 if (reachLocTuple.startsWith(prefixTuple)) {
1021 throw new Error("Failed to generate a composite location");
1027 public boolean isPrimitiveLocalVariable(FlowNode node) {
1028 VarDescriptor varDesc = (VarDescriptor) node.getDescTuple().get(0);
1029 return varDesc.getType().isPrimitive();
1032 private SSJavaLattice<String> getLattice(Descriptor d) {
1033 if (d instanceof MethodDescriptor) {
1034 return getMethodLattice((MethodDescriptor) d);
1036 return getFieldLattice((ClassDescriptor) d);
1040 private SSJavaLattice<String> getMethodLattice(MethodDescriptor md) {
1041 if (!md2lattice.containsKey(md)) {
1042 md2lattice.put(md, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
1044 return md2lattice.get(md);
1047 private void setMethodLattice(MethodDescriptor md, SSJavaLattice<String> lattice) {
1048 md2lattice.put(md, lattice);
1051 private void extractRelationFromFieldFlows(ClassDescriptor cd, FlowNode srcNode,
1052 FlowNode dstNode, int idx) {
1054 if (srcNode.getDescTuple().get(idx).equals(dstNode.getDescTuple().get(idx))
1055 && srcNode.getDescTuple().size() > (idx + 1) && dstNode.getDescTuple().size() > (idx + 1)) {
1056 // value flow between fields: we don't need to add a binary relation
1059 Descriptor desc = srcNode.getDescTuple().get(idx);
1060 ClassDescriptor classDesc;
1063 classDesc = ((VarDescriptor) desc).getType().getClassDesc();
1065 classDesc = ((FieldDescriptor) desc).getType().getClassDesc();
1068 extractRelationFromFieldFlows(classDesc, srcNode, dstNode, idx + 1);
1072 Descriptor srcFieldDesc = srcNode.getDescTuple().get(idx);
1073 Descriptor dstFieldDesc = dstNode.getDescTuple().get(idx);
1075 // add a new binary relation of dstNode < srcNode
1076 SSJavaLattice<String> fieldLattice = getFieldLattice(cd);
1077 LocationInfo fieldInfo = getFieldLocationInfo(cd);
1079 String srcSymbol = fieldInfo.getFieldInferLocation(srcFieldDesc).getLocIdentifier();
1080 String dstSymbol = fieldInfo.getFieldInferLocation(dstFieldDesc).getLocIdentifier();
1082 addRelationHigherToLower(fieldLattice, fieldInfo, srcSymbol, dstSymbol);
1088 public SSJavaLattice<String> getFieldLattice(ClassDescriptor cd) {
1089 if (!cd2lattice.containsKey(cd)) {
1090 cd2lattice.put(cd, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
1092 return cd2lattice.get(cd);
1095 public void constructFlowGraph() {
1099 while (!toAnalyzeIsEmpty()) {
1100 ClassDescriptor cd = toAnalyzeNext();
1102 setupToAnalazeMethod(cd);
1103 while (!toAnalyzeMethodIsEmpty()) {
1104 MethodDescriptor md = toAnalyzeMethodNext();
1105 if (ssjava.needTobeAnnotated(md)) {
1106 if (state.SSJAVADEBUG) {
1107 System.out.println();
1108 System.out.println("SSJAVA: Constructing a flow graph: " + md);
1111 // creates a mapping from a method descriptor to virtual methods
1112 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
1113 if (md.isStatic()) {
1114 setPossibleCallees.add(md);
1116 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
1118 mapMethodDescToPossibleMethodDescSet.put(md, setPossibleCallees);
1120 // creates a mapping from a parameter descriptor to its index
1121 Map<Descriptor, Integer> mapParamDescToIdx = new HashMap<Descriptor, Integer>();
1122 int offset = md.isStatic() ? 0 : 1;
1123 for (int i = 0; i < md.numParameters(); i++) {
1124 Descriptor paramDesc = (Descriptor) md.getParameter(i);
1125 mapParamDescToIdx.put(paramDesc, new Integer(i + offset));
1128 FlowGraph fg = new FlowGraph(md, mapParamDescToIdx);
1129 mapMethodDescriptorToFlowGraph.put(md, fg);
1131 analyzeMethodBody(cd, md);
1136 _debug_printGraph();
1139 private void analyzeMethodBody(ClassDescriptor cd, MethodDescriptor md) {
1140 BlockNode bn = state.getMethodBody(md);
1141 NodeTupleSet implicitFlowTupleSet = new NodeTupleSet();
1142 analyzeFlowBlockNode(md, md.getParameterTable(), bn, implicitFlowTupleSet);
1145 private void analyzeFlowBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn,
1146 NodeTupleSet implicitFlowTupleSet) {
1148 bn.getVarTable().setParent(nametable);
1149 for (int i = 0; i < bn.size(); i++) {
1150 BlockStatementNode bsn = bn.get(i);
1151 analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
1156 private void analyzeBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
1157 BlockStatementNode bsn, NodeTupleSet implicitFlowTupleSet) {
1159 switch (bsn.kind()) {
1160 case Kind.BlockExpressionNode:
1161 analyzeBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, implicitFlowTupleSet);
1164 case Kind.DeclarationNode:
1165 analyzeFlowDeclarationNode(md, nametable, (DeclarationNode) bsn, implicitFlowTupleSet);
1168 case Kind.IfStatementNode:
1169 analyzeFlowIfStatementNode(md, nametable, (IfStatementNode) bsn, implicitFlowTupleSet);
1173 analyzeFlowLoopNode(md, nametable, (LoopNode) bsn, implicitFlowTupleSet);
1176 case Kind.ReturnNode:
1177 analyzeFlowReturnNode(md, nametable, (ReturnNode) bsn, implicitFlowTupleSet);
1180 case Kind.SubBlockNode:
1181 analyzeFlowSubBlockNode(md, nametable, (SubBlockNode) bsn, implicitFlowTupleSet);
1184 case Kind.ContinueBreakNode:
1187 case Kind.SwitchStatementNode:
1188 analyzeSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
1195 private void analyzeSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
1196 SwitchStatementNode bsn) {
1197 // TODO Auto-generated method stub
1200 private void analyzeFlowSubBlockNode(MethodDescriptor md, SymbolTable nametable,
1201 SubBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
1202 analyzeFlowBlockNode(md, nametable, sbn.getBlockNode(), implicitFlowTupleSet);
1205 private void analyzeFlowReturnNode(MethodDescriptor md, SymbolTable nametable, ReturnNode rn,
1206 NodeTupleSet implicitFlowTupleSet) {
1208 ExpressionNode returnExp = rn.getReturnExpression();
1210 if (returnExp != null) {
1211 NodeTupleSet nodeSet = new NodeTupleSet();
1212 analyzeFlowExpressionNode(md, nametable, returnExp, nodeSet, false);
1214 FlowGraph fg = getFlowGraph(md);
1216 // annotate the elements of the node set as the return location
1217 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1218 NTuple<Descriptor> returnDescTuple = (NTuple<Descriptor>) iterator.next();
1219 fg.setReturnFlowNode(returnDescTuple);
1220 for (Iterator iterator2 = implicitFlowTupleSet.iterator(); iterator2.hasNext();) {
1221 NTuple<Descriptor> implicitFlowDescTuple = (NTuple<Descriptor>) iterator2.next();
1222 fg.addValueFlowEdge(implicitFlowDescTuple, returnDescTuple);
1229 private void analyzeFlowLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln,
1230 NodeTupleSet implicitFlowTupleSet) {
1232 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
1234 NodeTupleSet condTupleNode = new NodeTupleSet();
1235 analyzeFlowExpressionNode(md, nametable, ln.getCondition(), condTupleNode, null,
1236 implicitFlowTupleSet, false);
1237 condTupleNode.addTupleSet(implicitFlowTupleSet);
1239 // add edges from condNodeTupleSet to all nodes of conditional nodes
1240 analyzeFlowBlockNode(md, nametable, ln.getBody(), condTupleNode);
1243 // check 'for loop' case
1244 BlockNode bn = ln.getInitializer();
1245 bn.getVarTable().setParent(nametable);
1246 for (int i = 0; i < bn.size(); i++) {
1247 BlockStatementNode bsn = bn.get(i);
1248 analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
1251 NodeTupleSet condTupleNode = new NodeTupleSet();
1252 analyzeFlowExpressionNode(md, bn.getVarTable(), ln.getCondition(), condTupleNode, null,
1253 implicitFlowTupleSet, false);
1254 condTupleNode.addTupleSet(implicitFlowTupleSet);
1256 analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(), condTupleNode);
1257 analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(), condTupleNode);
1263 private void analyzeFlowIfStatementNode(MethodDescriptor md, SymbolTable nametable,
1264 IfStatementNode isn, NodeTupleSet implicitFlowTupleSet) {
1266 NodeTupleSet condTupleNode = new NodeTupleSet();
1267 analyzeFlowExpressionNode(md, nametable, isn.getCondition(), condTupleNode, null,
1268 implicitFlowTupleSet, false);
1270 // add edges from condNodeTupleSet to all nodes of conditional nodes
1271 condTupleNode.addTupleSet(implicitFlowTupleSet);
1272 analyzeFlowBlockNode(md, nametable, isn.getTrueBlock(), condTupleNode);
1274 if (isn.getFalseBlock() != null) {
1275 analyzeFlowBlockNode(md, nametable, isn.getFalseBlock(), condTupleNode);
1280 private void analyzeFlowDeclarationNode(MethodDescriptor md, SymbolTable nametable,
1281 DeclarationNode dn, NodeTupleSet implicitFlowTupleSet) {
1283 VarDescriptor vd = dn.getVarDescriptor();
1284 NTuple<Descriptor> tupleLHS = new NTuple<Descriptor>();
1286 getFlowGraph(md).createNewFlowNode(tupleLHS);
1288 if (dn.getExpression() != null) {
1290 NodeTupleSet tupleSetRHS = new NodeTupleSet();
1291 analyzeFlowExpressionNode(md, nametable, dn.getExpression(), tupleSetRHS, null,
1292 implicitFlowTupleSet, false);
1294 // add a new flow edge from rhs to lhs
1295 for (Iterator<NTuple<Descriptor>> iter = tupleSetRHS.iterator(); iter.hasNext();) {
1296 NTuple<Descriptor> from = iter.next();
1297 addFlowGraphEdge(md, from, tupleLHS);
1304 private void analyzeBlockExpressionNode(MethodDescriptor md, SymbolTable nametable,
1305 BlockExpressionNode ben, NodeTupleSet implicitFlowTupleSet) {
1306 analyzeFlowExpressionNode(md, nametable, ben.getExpression(), null, null, implicitFlowTupleSet,
1310 private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
1311 ExpressionNode en, NodeTupleSet nodeSet, boolean isLHS) {
1312 return analyzeFlowExpressionNode(md, nametable, en, nodeSet, null, new NodeTupleSet(), isLHS);
1315 private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
1316 ExpressionNode en, NodeTupleSet nodeSet, NTuple<Descriptor> base,
1317 NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
1319 // note that expression node can create more than one flow node
1320 // nodeSet contains of flow nodes
1321 // base is always assigned to null except the case of a name node!
1323 NTuple<Descriptor> flowTuple;
1325 switch (en.kind()) {
1327 case Kind.AssignmentNode:
1328 analyzeFlowAssignmentNode(md, nametable, (AssignmentNode) en, base, implicitFlowTupleSet);
1331 case Kind.FieldAccessNode:
1333 analyzeFlowFieldAccessNode(md, nametable, (FieldAccessNode) en, nodeSet, base,
1334 implicitFlowTupleSet);
1335 nodeSet.addTuple(flowTuple);
1339 NodeTupleSet nameNodeSet = new NodeTupleSet();
1341 analyzeFlowNameNode(md, nametable, (NameNode) en, nameNodeSet, base, implicitFlowTupleSet);
1342 nodeSet.addTuple(flowTuple);
1346 analyzeFlowOpNode(md, nametable, (OpNode) en, nodeSet, implicitFlowTupleSet);
1349 case Kind.CreateObjectNode:
1350 analyzeCreateObjectNode(md, nametable, (CreateObjectNode) en);
1353 case Kind.ArrayAccessNode:
1354 analyzeFlowArrayAccessNode(md, nametable, (ArrayAccessNode) en, nodeSet, isLHS);
1357 case Kind.LiteralNode:
1358 analyzeLiteralNode(md, nametable, (LiteralNode) en);
1361 case Kind.MethodInvokeNode:
1362 analyzeFlowMethodInvokeNode(md, nametable, (MethodInvokeNode) en, implicitFlowTupleSet);
1365 case Kind.TertiaryNode:
1366 analyzeFlowTertiaryNode(md, nametable, (TertiaryNode) en, nodeSet, implicitFlowTupleSet);
1370 analyzeFlowCastNode(md, nametable, (CastNode) en, implicitFlowTupleSet);
1373 // case Kind.InstanceOfNode:
1374 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
1377 // case Kind.ArrayInitializerNode:
1378 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
1382 // case Kind.ClassTypeNode:
1383 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
1386 // case Kind.OffsetNode:
1387 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
1395 private void analyzeFlowCastNode(MethodDescriptor md, SymbolTable nametable, CastNode cn,
1396 NodeTupleSet implicitFlowTupleSet) {
1398 NodeTupleSet nodeTupleSet = new NodeTupleSet();
1399 analyzeFlowExpressionNode(md, nametable, cn.getExpression(), nodeTupleSet, false);
1403 private void analyzeFlowTertiaryNode(MethodDescriptor md, SymbolTable nametable, TertiaryNode tn,
1404 NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
1406 NodeTupleSet tertiaryTupleNode = new NodeTupleSet();
1407 analyzeFlowExpressionNode(md, nametable, tn.getCond(), tertiaryTupleNode, null,
1408 implicitFlowTupleSet, false);
1410 // add edges from tertiaryTupleNode to all nodes of conditional nodes
1411 tertiaryTupleNode.addTupleSet(implicitFlowTupleSet);
1412 analyzeFlowExpressionNode(md, nametable, tn.getTrueExpr(), tertiaryTupleNode, null,
1413 implicitFlowTupleSet, false);
1415 analyzeFlowExpressionNode(md, nametable, tn.getFalseExpr(), tertiaryTupleNode, null,
1416 implicitFlowTupleSet, false);
1418 nodeSet.addTupleSet(tertiaryTupleNode);
1422 private void addMapCallerMethodDescToMethodInvokeNodeSet(MethodDescriptor caller,
1423 MethodInvokeNode min) {
1424 Set<MethodInvokeNode> set = mapMethodDescriptorToMethodInvokeNodeSet.get(caller);
1426 set = new HashSet<MethodInvokeNode>();
1427 mapMethodDescriptorToMethodInvokeNodeSet.put(caller, set);
1432 private void analyzeFlowMethodInvokeNode(MethodDescriptor md, SymbolTable nametable,
1433 MethodInvokeNode min, NodeTupleSet implicitFlowTupleSet) {
1435 addMapCallerMethodDescToMethodInvokeNodeSet(md, min);
1437 MethodDescriptor calleeMD = min.getMethod();
1439 NameDescriptor baseName = min.getBaseName();
1440 boolean isSystemout = false;
1441 if (baseName != null) {
1442 isSystemout = baseName.getSymbol().equals("System.out");
1445 if (!ssjava.isSSJavaUtil(calleeMD.getClassDesc()) && !ssjava.isTrustMethod(calleeMD)
1446 && !calleeMD.getModifiers().isNative() && !isSystemout) {
1448 // CompositeLocation baseLocation = null;
1449 if (min.getExpression() != null) {
1451 NodeTupleSet baseNodeSet = new NodeTupleSet();
1452 analyzeFlowExpressionNode(md, nametable, min.getExpression(), baseNodeSet, null,
1453 implicitFlowTupleSet, false);
1456 if (min.getMethod().isStatic()) {
1457 // String globalLocId = ssjava.getMethodLattice(md).getGlobalLoc();
1458 // if (globalLocId == null) {
1460 // Error("Method lattice does not define global variable location at "
1461 // + generateErrorMessage(md.getClassDesc(), min));
1463 // baseLocation = new CompositeLocation(new Location(md,
1467 // String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
1468 // baseLocation = new CompositeLocation(new Location(md, thisLocId));
1473 // if (constraint != null) {
1474 // int compareResult =
1475 // CompositeLattice.compare(constraint, baseLocation, true,
1476 // generateErrorMessage(cd, min));
1477 // if (compareResult != ComparisonResult.GREATER) {
1478 // // if the current constraint is higher than method's THIS location
1479 // // no need to check constraints!
1480 // CompositeLocation calleeConstraint =
1481 // translateCallerLocToCalleeLoc(calleeMD, baseLocation, constraint);
1482 // // System.out.println("check method body for constraint:" + calleeMD +
1483 // // " calleeConstraint="
1484 // // + calleeConstraint);
1485 // checkMethodBody(calleeMD.getClassDesc(), calleeMD, calleeConstraint);
1489 analyzeFlowMethodParameters(md, nametable, min);
1491 // checkCalleeConstraints(md, nametable, min, baseLocation, constraint);
1493 // checkCallerArgumentLocationConstraints(md, nametable, min,
1494 // baseLocation, constraint);
1496 if (!min.getMethod().getReturnType().isVoid()) {
1497 // If method has a return value, compute the highest possible return
1498 // location in the caller's perspective
1499 // CompositeLocation ceilingLoc =
1500 // computeCeilingLocationForCaller(md, nametable, min, baseLocation,
1502 // return ceilingLoc;
1506 // return new CompositeLocation(Location.createTopLocation(md));
1510 private NTuple<Descriptor> getArgTupleByArgIdx(MethodInvokeNode min, int idx) {
1511 return mapMethodInvokeNodeToArgIdxMap.get(min).get(new Integer(idx));
1514 private void addArgIdxMap(MethodInvokeNode min, int idx, NTuple<Descriptor> argTuple) {
1515 Map<Integer, NTuple<Descriptor>> mapIdxToArgTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
1516 if (mapIdxToArgTuple == null) {
1517 mapIdxToArgTuple = new HashMap<Integer, NTuple<Descriptor>>();
1518 mapMethodInvokeNodeToArgIdxMap.put(min, mapIdxToArgTuple);
1520 mapIdxToArgTuple.put(new Integer(idx), argTuple);
1523 private void analyzeFlowMethodParameters(MethodDescriptor callermd, SymbolTable nametable,
1524 MethodInvokeNode min) {
1526 if (min.numArgs() > 0) {
1528 int offset = min.getMethod().isStatic() ? 0 : 1;
1530 for (int i = 0; i < min.numArgs(); i++) {
1531 ExpressionNode en = min.getArg(i);
1532 NTuple<Descriptor> argTuple =
1533 analyzeFlowExpressionNode(callermd, nametable, en, new NodeTupleSet(), false);
1535 addArgIdxMap(min, i + offset, argTuple);
1542 private void analyzeLiteralNode(MethodDescriptor md, SymbolTable nametable, LiteralNode en) {
1543 // TODO Auto-generated method stub
1547 private void analyzeFlowArrayAccessNode(MethodDescriptor md, SymbolTable nametable,
1548 ArrayAccessNode aan, NodeTupleSet nodeSet, boolean isLHS) {
1550 NodeTupleSet expNodeTupleSet = new NodeTupleSet();
1551 analyzeFlowExpressionNode(md, nametable, aan.getExpression(), expNodeTupleSet, isLHS);
1553 NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
1554 analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, isLHS);
1557 // need to create an edge from idx to array
1559 for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
1560 NTuple<Descriptor> idxTuple = idxIter.next();
1561 for (Iterator<NTuple<Descriptor>> arrIter = expNodeTupleSet.iterator(); arrIter.hasNext();) {
1562 NTuple<Descriptor> arrTuple = arrIter.next();
1563 getFlowGraph(md).addValueFlowEdge(idxTuple, arrTuple);
1567 nodeSet.addTupleSet(expNodeTupleSet);
1569 nodeSet.addTupleSet(expNodeTupleSet);
1570 nodeSet.addTupleSet(idxNodeTupleSet);
1575 private void analyzeCreateObjectNode(MethodDescriptor md, SymbolTable nametable,
1576 CreateObjectNode en) {
1577 // TODO Auto-generated method stub
1581 private void analyzeFlowOpNode(MethodDescriptor md, SymbolTable nametable, OpNode on,
1582 NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
1584 NodeTupleSet leftOpSet = new NodeTupleSet();
1585 NodeTupleSet rightOpSet = new NodeTupleSet();
1588 analyzeFlowExpressionNode(md, nametable, on.getLeft(), leftOpSet, null, implicitFlowTupleSet,
1591 if (on.getRight() != null) {
1593 analyzeFlowExpressionNode(md, nametable, on.getRight(), rightOpSet, null,
1594 implicitFlowTupleSet, false);
1597 Operation op = on.getOp();
1599 switch (op.getOp()) {
1601 case Operation.UNARYPLUS:
1602 case Operation.UNARYMINUS:
1603 case Operation.LOGIC_NOT:
1605 nodeSet.addTupleSet(leftOpSet);
1608 case Operation.LOGIC_OR:
1609 case Operation.LOGIC_AND:
1610 case Operation.COMP:
1611 case Operation.BIT_OR:
1612 case Operation.BIT_XOR:
1613 case Operation.BIT_AND:
1614 case Operation.ISAVAILABLE:
1615 case Operation.EQUAL:
1616 case Operation.NOTEQUAL:
1623 case Operation.MULT:
1626 case Operation.LEFTSHIFT:
1627 case Operation.RIGHTSHIFT:
1628 case Operation.URIGHTSHIFT:
1630 // there are two operands
1631 nodeSet.addTupleSet(leftOpSet);
1632 nodeSet.addTupleSet(rightOpSet);
1636 throw new Error(op.toString());
1640 private NTuple<Descriptor> analyzeFlowNameNode(MethodDescriptor md, SymbolTable nametable,
1641 NameNode nn, NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
1644 base = new NTuple<Descriptor>();
1647 NameDescriptor nd = nn.getName();
1649 if (nd.getBase() != null) {
1650 analyzeFlowExpressionNode(md, nametable, nn.getExpression(), nodeSet, base,
1651 implicitFlowTupleSet, false);
1653 String varname = nd.toString();
1654 if (varname.equals("this")) {
1656 base.add(md.getThis());
1660 Descriptor d = (Descriptor) nametable.get(varname);
1662 if (d instanceof VarDescriptor) {
1663 VarDescriptor vd = (VarDescriptor) d;
1665 } else if (d instanceof FieldDescriptor) {
1666 // the type of field descriptor has a location!
1667 FieldDescriptor fd = (FieldDescriptor) d;
1668 if (fd.isStatic()) {
1670 // if it is 'static final', assign the default TOP LOCATION
1675 // if 'static', assign the default GLOBAL LOCATION to the first
1676 // element of the tuple
1677 base.add(GLOBALDESC);
1680 // the location of field access starts from this, followed by field
1682 base.add(md.getThis());
1686 } else if (d == null) {
1687 // access static field
1688 base.add(GLOBALDESC);
1689 // base.add(nn.getField());
1692 // FieldDescriptor fd = nn.getField();addFlowGraphEdge
1694 // MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1695 // String globalLocId = localLattice.getGlobalLoc();
1696 // if (globalLocId == null) {
1698 // Error("Method lattice does not define global variable location at "
1699 // + generateErrorMessage(md.getClassDesc(), nn));
1701 // loc.addLocation(new Location(md, globalLocId));
1703 // Location fieldLoc = (Location) fd.getType().getExtension();
1704 // loc.addLocation(fieldLoc);
1711 getFlowGraph(md).createNewFlowNode(base);
1717 private NTuple<Descriptor> analyzeFlowFieldAccessNode(MethodDescriptor md, SymbolTable nametable,
1718 FieldAccessNode fan, NodeTupleSet nodeSet, NTuple<Descriptor> base,
1719 NodeTupleSet implicitFlowTupleSet) {
1721 ExpressionNode left = fan.getExpression();
1722 TypeDescriptor ltd = left.getType();
1723 FieldDescriptor fd = fan.getField();
1725 String varName = null;
1726 if (left.kind() == Kind.NameNode) {
1727 NameDescriptor nd = ((NameNode) left).getName();
1728 varName = nd.toString();
1731 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1732 // using a class name directly or access using this
1733 if (fd.isStatic() && fd.isFinal()) {
1734 // loc.addLocation(Location.createTopLocation(md));
1739 if (left instanceof ArrayAccessNode) {
1740 ArrayAccessNode aan = (ArrayAccessNode) left;
1741 left = aan.getExpression();
1745 analyzeFlowExpressionNode(md, nametable, left, nodeSet, base, implicitFlowTupleSet, false);
1747 if (!left.getType().isPrimitive()) {
1749 if (fd.getSymbol().equals("length")) {
1750 // array.length access, just have the location of the array
1757 getFlowGraph(md).createNewFlowNode(base);
1762 private void debug_printTreeNode(TreeNode tn) {
1764 System.out.println("DEBUG: " + tn.printNode(0) + " line#=" + tn.getNumLine());
1768 private void analyzeFlowAssignmentNode(MethodDescriptor md, SymbolTable nametable,
1769 AssignmentNode an, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
1771 NodeTupleSet nodeSetRHS = new NodeTupleSet();
1772 NodeTupleSet nodeSetLHS = new NodeTupleSet();
1774 boolean postinc = true;
1775 if (an.getOperation().getBaseOp() == null
1776 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1777 .getBaseOp().getOp() != Operation.POSTDEC)) {
1780 // if LHS is array access node, need to capture value flows between an array
1781 // and its index value
1782 analyzeFlowExpressionNode(md, nametable, an.getDest(), nodeSetLHS, null, implicitFlowTupleSet,
1786 // analyze value flows of rhs expression
1787 analyzeFlowExpressionNode(md, nametable, an.getSrc(), nodeSetRHS, null, implicitFlowTupleSet,
1790 // creates edges from RHS to LHS
1791 for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
1792 NTuple<Descriptor> fromTuple = iter.next();
1793 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
1794 NTuple<Descriptor> toTuple = iter2.next();
1795 addFlowGraphEdge(md, fromTuple, toTuple);
1799 // creates edges from implicitFlowTupleSet to LHS
1800 for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
1801 NTuple<Descriptor> fromTuple = iter.next();
1802 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
1803 NTuple<Descriptor> toTuple = iter2.next();
1804 addFlowGraphEdge(md, fromTuple, toTuple);
1810 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
1811 NTuple<Descriptor> tuple = iter2.next();
1812 addFlowGraphEdge(md, tuple, tuple);
1819 public FlowGraph getFlowGraph(MethodDescriptor md) {
1820 return mapMethodDescriptorToFlowGraph.get(md);
1823 private boolean addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
1824 NTuple<Descriptor> to) {
1826 // return true if it adds a new edge
1827 FlowGraph graph = getFlowGraph(md);
1828 graph.addValueFlowEdge(from, to);
1832 public void _debug_printGraph() {
1833 Set<MethodDescriptor> keySet = mapMethodDescriptorToFlowGraph.keySet();
1835 for (Iterator<MethodDescriptor> iterator = keySet.iterator(); iterator.hasNext();) {
1836 MethodDescriptor md = (MethodDescriptor) iterator.next();
1837 FlowGraph fg = mapMethodDescriptorToFlowGraph.get(md);
1840 } catch (IOException e) {
1841 e.printStackTrace();