1 package Analysis.SSJava;
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.FileReader;
6 import java.io.FileWriter;
7 import java.io.IOException;
8 import java.util.ArrayList;
9 import java.util.Collections;
10 import java.util.Comparator;
11 import java.util.HashMap;
12 import java.util.HashSet;
13 import java.util.Iterator;
14 import java.util.LinkedList;
15 import java.util.List;
18 import java.util.Stack;
19 import java.util.Vector;
21 import IR.ClassDescriptor;
23 import IR.FieldDescriptor;
24 import IR.MethodDescriptor;
25 import IR.NameDescriptor;
28 import IR.SymbolTable;
29 import IR.TypeDescriptor;
30 import IR.VarDescriptor;
31 import IR.Tree.ArrayAccessNode;
32 import IR.Tree.AssignmentNode;
33 import IR.Tree.BlockExpressionNode;
34 import IR.Tree.BlockNode;
35 import IR.Tree.BlockStatementNode;
36 import IR.Tree.CastNode;
37 import IR.Tree.CreateObjectNode;
38 import IR.Tree.DeclarationNode;
39 import IR.Tree.ExpressionNode;
40 import IR.Tree.FieldAccessNode;
41 import IR.Tree.IfStatementNode;
43 import IR.Tree.LiteralNode;
44 import IR.Tree.LoopNode;
45 import IR.Tree.MethodInvokeNode;
46 import IR.Tree.NameNode;
47 import IR.Tree.OpNode;
48 import IR.Tree.ReturnNode;
49 import IR.Tree.SubBlockNode;
50 import IR.Tree.SwitchBlockNode;
51 import IR.Tree.SwitchStatementNode;
52 import IR.Tree.TertiaryNode;
53 import IR.Tree.TreeNode;
56 public class LocationInference {
59 SSJavaAnalysis ssjava;
61 List<ClassDescriptor> temp_toanalyzeList;
62 List<MethodDescriptor> temp_toanalyzeMethodList;
63 Map<MethodDescriptor, FlowGraph> mapMethodDescriptorToFlowGraph;
65 LinkedList<MethodDescriptor> toanalyze_methodDescList;
67 // map a method descriptor to its set of parameter descriptors
68 Map<MethodDescriptor, Set<Descriptor>> mapMethodDescriptorToParamDescSet;
70 // keep current descriptors to visit in fixed-point interprocedural analysis,
71 private Stack<MethodDescriptor> methodDescriptorsToVisitStack;
73 // map a class descriptor to a field lattice
74 private Map<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
76 // map a method descriptor to a method lattice
77 private Map<MethodDescriptor, SSJavaLattice<String>> md2lattice;
79 // map a method/class descriptor to a hierarchy graph
80 private Map<Descriptor, HierarchyGraph> mapDescriptorToHierarchyGraph;
82 // map a method/class descriptor to a skeleton hierarchy graph
83 private Map<Descriptor, HierarchyGraph> mapDescriptorToSkeletonHierarchyGraph;
85 private Map<Descriptor, HierarchyGraph> mapDescriptorToSimpleHierarchyGraph;
87 // map a method/class descriptor to a skeleton hierarchy graph with combination nodes
88 private Map<Descriptor, HierarchyGraph> mapDescriptorToCombineSkeletonHierarchyGraph;
90 // map a descriptor to a simple lattice
91 private Map<Descriptor, SSJavaLattice<String>> mapDescriptorToSimpleLattice;
93 // map a method descriptor to the set of method invocation nodes which are
94 // invoked by the method descriptor
95 private Map<MethodDescriptor, Set<MethodInvokeNode>> mapMethodDescriptorToMethodInvokeNodeSet;
97 private Map<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>> mapMethodInvokeNodeToArgIdxMap;
99 private Map<MethodInvokeNode, NTuple<Descriptor>> mapMethodInvokeNodeToBaseTuple;
101 private Map<MethodDescriptor, MethodLocationInfo> mapMethodDescToMethodLocationInfo;
103 private Map<ClassDescriptor, LocationInfo> mapClassToLocationInfo;
105 private Map<MethodDescriptor, Set<MethodDescriptor>> mapMethodToCalleeSet;
107 private Map<MethodDescriptor, Set<FlowNode>> mapMethodDescToParamNodeFlowsToReturnValue;
109 private Map<String, Vector<String>> mapFileNameToLineVector;
111 private Map<Descriptor, Integer> mapDescToDefinitionLine;
113 private Map<Descriptor, LocationSummary> mapDescToLocationSummary;
115 // maps a method descriptor to a sub global flow graph that captures all value flows caused by the
116 // set of callees reachable from the method
117 private Map<MethodDescriptor, GlobalFlowGraph> mapMethodDescriptorToSubGlobalFlowGraph;
119 private Map<MethodInvokeNode, Map<NTuple<Descriptor>, NTuple<Descriptor>>> mapMethodInvokeNodeToMapCallerArgToCalleeArg;
121 public static final String GLOBALLOC = "GLOBALLOC";
123 public static final String TOPLOC = "TOPLOC";
125 public static final String INTERLOC = "INTERLOC";
127 public static final String PCLOC = "PCLOC";
129 public static final Descriptor GLOBALDESC = new NameDescriptor(GLOBALLOC);
131 public static final Descriptor TOPDESC = new NameDescriptor(TOPLOC);
133 public static String newline = System.getProperty("line.separator");
135 LocationInfo curMethodInfo;
137 boolean debug = true;
139 private static int locSeed = 0;
141 public LocationInference(SSJavaAnalysis ssjava, State state) {
142 this.ssjava = ssjava;
144 this.temp_toanalyzeList = new ArrayList<ClassDescriptor>();
145 this.temp_toanalyzeMethodList = new ArrayList<MethodDescriptor>();
146 this.mapMethodDescriptorToFlowGraph = new HashMap<MethodDescriptor, FlowGraph>();
147 this.cd2lattice = new HashMap<ClassDescriptor, SSJavaLattice<String>>();
148 this.md2lattice = new HashMap<MethodDescriptor, SSJavaLattice<String>>();
149 this.methodDescriptorsToVisitStack = new Stack<MethodDescriptor>();
150 this.mapMethodDescriptorToMethodInvokeNodeSet =
151 new HashMap<MethodDescriptor, Set<MethodInvokeNode>>();
152 this.mapMethodInvokeNodeToArgIdxMap =
153 new HashMap<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>>();
154 this.mapMethodDescToMethodLocationInfo = new HashMap<MethodDescriptor, MethodLocationInfo>();
155 this.mapMethodToCalleeSet = new HashMap<MethodDescriptor, Set<MethodDescriptor>>();
156 this.mapClassToLocationInfo = new HashMap<ClassDescriptor, LocationInfo>();
158 this.mapFileNameToLineVector = new HashMap<String, Vector<String>>();
159 this.mapDescToDefinitionLine = new HashMap<Descriptor, Integer>();
160 this.mapMethodDescToParamNodeFlowsToReturnValue =
161 new HashMap<MethodDescriptor, Set<FlowNode>>();
163 this.mapDescriptorToHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
164 this.mapMethodInvokeNodeToBaseTuple = new HashMap<MethodInvokeNode, NTuple<Descriptor>>();
166 this.mapDescriptorToSkeletonHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
167 this.mapDescriptorToCombineSkeletonHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
168 this.mapDescriptorToSimpleHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
170 this.mapDescriptorToSimpleLattice = new HashMap<Descriptor, SSJavaLattice<String>>();
172 this.mapDescToLocationSummary = new HashMap<Descriptor, LocationSummary>();
174 this.mapMethodDescriptorToSubGlobalFlowGraph = new HashMap<MethodDescriptor, GlobalFlowGraph>();
176 this.mapMethodInvokeNodeToMapCallerArgToCalleeArg =
177 new HashMap<MethodInvokeNode, Map<NTuple<Descriptor>, NTuple<Descriptor>>>();
181 public void setupToAnalyze() {
182 SymbolTable classtable = state.getClassSymbolTable();
183 temp_toanalyzeList.clear();
184 temp_toanalyzeList.addAll(classtable.getValueSet());
185 // Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
186 // public int compare(ClassDescriptor o1, ClassDescriptor o2) {
187 // return o1.getClassName().compareToIgnoreCase(o2.getClassName());
192 public void setupToAnalazeMethod(ClassDescriptor cd) {
194 SymbolTable methodtable = cd.getMethodTable();
195 temp_toanalyzeMethodList.clear();
196 temp_toanalyzeMethodList.addAll(methodtable.getValueSet());
197 Collections.sort(temp_toanalyzeMethodList, new Comparator<MethodDescriptor>() {
198 public int compare(MethodDescriptor o1, MethodDescriptor o2) {
199 return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
204 public boolean toAnalyzeMethodIsEmpty() {
205 return temp_toanalyzeMethodList.isEmpty();
208 public boolean toAnalyzeIsEmpty() {
209 return temp_toanalyzeList.isEmpty();
212 public ClassDescriptor toAnalyzeNext() {
213 return temp_toanalyzeList.remove(0);
216 public MethodDescriptor toAnalyzeMethodNext() {
217 return temp_toanalyzeMethodList.remove(0);
220 public void inference() {
222 // 1) construct value flow graph
223 constructFlowGraph();
225 assignCompositeLocation();
227 // constructGlobalFlowGraph();
229 constructHierarchyGraph();
231 debug_writeHierarchyDotFiles();
233 // calculate RETURNLOC,PCLOC
234 calculateExtraLocations();
236 simplifyHierarchyGraph();
238 debug_writeSimpleHierarchyDotFiles();
240 constructSkeletonHierarchyGraph();
242 debug_writeSkeletonHierarchyDotFiles();
244 insertCombinationNodes();
246 debug_writeSkeletonCombinationHierarchyDotFiles();
252 debug_writeLattices();
254 updateCompositeLocationAssignments();
256 generateMethodSummary();
260 // 2) construct lattices
262 // simplifyLattices();
263 // 3) check properties
266 // calculate RETURNLOC,PCLOC
267 calculateExtraLocations();
269 debug_writeLatticeDotFile();
271 // 4) generate annotated source codes
272 generateAnnoatedCode();
276 public Map<NTuple<Descriptor>, NTuple<Descriptor>> getMapCallerArgToCalleeParam(
277 MethodInvokeNode min) {
279 if (!mapMethodInvokeNodeToMapCallerArgToCalleeArg.containsKey(min)) {
280 mapMethodInvokeNodeToMapCallerArgToCalleeArg.put(min,
281 new HashMap<NTuple<Descriptor>, NTuple<Descriptor>>());
284 return mapMethodInvokeNodeToMapCallerArgToCalleeArg.get(min);
287 public void addMapCallerArgToCalleeParam(MethodInvokeNode min, NTuple<Descriptor> callerArg,
288 NTuple<Descriptor> calleeParam) {
289 getMapCallerArgToCalleeParam(min).put(callerArg, calleeParam);
292 private void assignCompositeLocation() {
293 calculateGlobalValueFlowCompositeLocation();
294 translateCompositeLocationAssignmentToFlowGraph();
297 private void translateCompositeLocationAssignmentToFlowGraph() {
298 MethodDescriptor methodEventLoopDesc = ssjava.getMethodContainingSSJavaLoop();
299 translateCompositeLocationAssignmentToFlowGraph(methodEventLoopDesc);
303 private void updateCompositeLocationAssignments() {
305 LinkedList<MethodDescriptor> methodDescList =
306 (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
308 while (!methodDescList.isEmpty()) {
309 MethodDescriptor md = methodDescList.removeLast();
310 GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
311 FlowGraph flowGraph = getFlowGraph(md);
313 Set<FlowNode> nodeSet = flowGraph.getNodeSet();
314 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
315 FlowNode node = (FlowNode) iterator.next();
316 if (node.getCompositeLocation() != null) {
317 CompositeLocation compLoc = node.getCompositeLocation();
318 CompositeLocation updatedCompLoc = updateCompositeLocation(compLoc);
319 node.setCompositeLocation(updatedCompLoc);
321 NTuple<Descriptor> descTuple = node.getDescTuple();
322 CompositeLocation compLoc = convertToCompositeLocation(md, descTuple);
323 node.setCompositeLocation(compLoc);
331 private CompositeLocation updateCompositeLocation(CompositeLocation compLoc) {
332 CompositeLocation updatedCompLoc = new CompositeLocation();
333 for (int i = 0; i < compLoc.getSize(); i++) {
334 Location loc = compLoc.get(i);
335 String nodeIdentifier = loc.getLocIdentifier();
336 Descriptor enclosingDesc = loc.getDescriptor();
337 LocationSummary locSummary = getLocationSummary(enclosingDesc);
338 String locName = locSummary.getLocationName(nodeIdentifier);
339 Location updatedLoc = new Location(enclosingDesc, locName);
340 updatedCompLoc.addLocation(updatedLoc);
343 return updatedCompLoc;
346 private void translateCompositeLocationAssignmentToFlowGraph(MethodDescriptor mdCaller) {
348 System.out.println("\n#translateCompositeLocationAssignmentToFlowGraph=" + mdCaller);
350 // First, assign a composite location to a node in the flow graph
351 GlobalFlowGraph callerGlobalFlowGraph = getSubGlobalFlowGraph(mdCaller);
353 FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
354 Map<Location, CompositeLocation> callerMapLocToCompLoc =
355 callerGlobalFlowGraph.getMapLocationToInferCompositeLocation();
356 System.out.println("---callerMapLocToCompLoc=" + callerMapLocToCompLoc);
357 Set<Location> methodLocSet = callerMapLocToCompLoc.keySet();
358 for (Iterator iterator = methodLocSet.iterator(); iterator.hasNext();) {
359 Location methodLoc = (Location) iterator.next();
360 if (methodLoc.getDescriptor().equals(mdCaller)) {
361 CompositeLocation inferCompLoc = callerMapLocToCompLoc.get(methodLoc);
362 assignCompositeLocationToFlowGraph(callerFlowGraph, methodLoc, inferCompLoc);
366 Set<MethodInvokeNode> minSet = mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
368 Set<MethodDescriptor> calleeSet = new HashSet<MethodDescriptor>();
369 for (Iterator iterator = minSet.iterator(); iterator.hasNext();) {
370 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
371 // need to translate a composite location that is started with the base
373 if (mapMethodInvokeNodeToBaseTuple.get(min) != null) {
374 // if mapMethodInvokeNodeToBaseTuple doesn't have a mapping
375 // it means that the corresponding callee method does not cause any
377 translateMapLocationToInferCompositeLocationToCalleeGraph(callerGlobalFlowGraph, min);
379 calleeSet.add(min.getMethod());
382 for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
383 MethodDescriptor callee = (MethodDescriptor) iterator.next();
384 translateCompositeLocationAssignmentToFlowGraph(callee);
389 public void assignCompositeLocationToFlowGraph(FlowGraph flowGraph, Location loc,
390 CompositeLocation inferCompLoc) {
391 Descriptor localDesc = loc.getLocDescriptor();
393 Set<FlowNode> nodeSet = flowGraph.getNodeSet();
394 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
395 FlowNode node = (FlowNode) iterator.next();
396 if (node.getDescTuple().startsWith(localDesc)) {
397 // need to assign the inferred composite location to this node
398 CompositeLocation newCompLoc = generateCompositeLocation(node.getDescTuple(), inferCompLoc);
399 node.setCompositeLocation(newCompLoc);
400 System.out.println("SET Node=" + node + " inferCompLoc=" + newCompLoc);
405 private CompositeLocation generateCompositeLocation(NTuple<Descriptor> nodeDescTuple,
406 CompositeLocation inferCompLoc) {
408 System.out.println("generateCompositeLocation=" + nodeDescTuple + " with inferCompLoc="
411 CompositeLocation newCompLoc = new CompositeLocation();
412 for (int i = 0; i < inferCompLoc.getSize(); i++) {
413 newCompLoc.addLocation(inferCompLoc.get(i));
416 Descriptor lastDescOfPrefix = nodeDescTuple.get(0);
417 Descriptor enclosingDescriptor;
418 if (lastDescOfPrefix instanceof InterDescriptor) {
419 enclosingDescriptor = null;
421 enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
424 for (int i = 1; i < nodeDescTuple.size(); i++) {
425 Descriptor desc = nodeDescTuple.get(i);
426 Location locElement = new Location(enclosingDescriptor, desc);
427 newCompLoc.addLocation(locElement);
429 enclosingDescriptor = ((FieldDescriptor) desc).getClassDescriptor();
435 private void translateMapLocationToInferCompositeLocationToCalleeGraph(
436 GlobalFlowGraph callerGraph, MethodInvokeNode min) {
438 MethodDescriptor mdCallee = min.getMethod();
439 MethodDescriptor mdCaller = callerGraph.getMethodDescriptor();
440 Map<Location, CompositeLocation> callerMapLocToCompLoc =
441 callerGraph.getMapLocationToInferCompositeLocation();
443 FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
444 GlobalFlowGraph calleeGlobalGraph = getSubGlobalFlowGraph(mdCallee);
446 NTuple<Location> baseLocTuple =
447 translateToLocTuple(mdCaller, mapMethodInvokeNodeToBaseTuple.get(min));
449 System.out.println("\n-translate caller infer composite loc to callee=" + mdCallee
450 + " baseLocTuple=" + baseLocTuple);
451 Set<Location> keySet = callerMapLocToCompLoc.keySet();
452 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
453 Location key = (Location) iterator.next();
454 CompositeLocation callerCompLoc = callerMapLocToCompLoc.get(key);
456 if (!key.getDescriptor().equals(mdCaller)) {
457 System.out.println("--- caller key=" + key + " callerCompLoc=" + callerCompLoc);
459 // && callerCompLoc.getTuple().startsWith(baseLocTuple)) {
460 // need to translate to the callee side
463 CompositeLocation newCalleeCompLoc;
464 if (callerCompLoc.getTuple().startsWith(baseLocTuple)) {
465 System.out.println("---need to translate callerCompLoc=" + callerCompLoc
466 + " with baseTuple=" + baseLocTuple);
468 translateCompositeLocationToCallee(callerCompLoc, baseLocTuple, mdCallee);
470 calleeGlobalGraph.addMapLocationToInferCompositeLocation(key, newCalleeCompLoc);
471 System.out.println("---callee loc=" + key + " newCalleeCompLoc=" + newCalleeCompLoc);
473 // newCalleeCompLoc = callerCompLoc.clone();
479 // If the location of an argument has a composite location
480 // need to assign a proper composite location to the corresponding callee parameter
481 System.out.println("\n-translate arg composite location to callee param. min="
483 Map<Integer, NTuple<Descriptor>> mapIdxToArgTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
484 Set<Integer> idxSet = mapIdxToArgTuple.keySet();
485 for (Iterator iterator = idxSet.iterator(); iterator.hasNext();) {
486 Integer idx = (Integer) iterator.next();
488 if (idx == 0 && !min.getMethod().isStatic()) {
492 NTuple<Descriptor> argTuple = mapIdxToArgTuple.get(idx);
493 if (argTuple.size() > 0) {
494 // check if an arg tuple has been already assigned to a composite location
495 NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argTuple);
496 Location argLocalLoc = argLocTuple.get(0);
498 // if (!isPrimitiveType(argTuple)) {
499 if (callerMapLocToCompLoc.containsKey(argLocalLoc)) {
501 CompositeLocation callerCompLoc = callerMapLocToCompLoc.get(argLocalLoc);
502 for (int i = 1; i < argLocTuple.size(); i++) {
503 callerCompLoc.addLocation(argLocTuple.get(i));
506 if (callerCompLoc.getTuple().startsWith(baseLocTuple)) {
508 FlowNode calleeParamFlowNode = calleeFlowGraph.getParamFlowNode(idx);
509 NTuple<Descriptor> calleeParamDescTuple = calleeParamFlowNode.getDescTuple();
510 NTuple<Location> calleeParamLocTuple =
511 translateToLocTuple(mdCallee, calleeParamDescTuple);
513 System.out.println("---need to translate callerCompLoc=" + callerCompLoc
514 + " with baseTuple=" + baseLocTuple + " calleeParamLocTuple="
515 + calleeParamLocTuple);
517 CompositeLocation newCalleeCompLoc =
518 translateCompositeLocationToCallee(callerCompLoc, baseLocTuple, mdCallee);
520 calleeGlobalGraph.addMapLocationToInferCompositeLocation(calleeParamLocTuple.get(0),
523 System.out.println("---callee loc=" + calleeParamLocTuple.get(0)
524 + " newCalleeCompLoc=" + newCalleeCompLoc);
526 // System.out.println("###need to assign composite location to=" + calleeParamDescTuple
527 // + " with baseTuple=" + baseLocTuple);
537 private boolean isPrimitiveType(NTuple<Descriptor> argTuple) {
539 Descriptor lastDesc = argTuple.get(argTuple.size() - 1);
541 if (lastDesc instanceof FieldDescriptor) {
542 return ((FieldDescriptor) lastDesc).getType().isPrimitive();
543 } else if (lastDesc instanceof VarDescriptor) {
544 return ((VarDescriptor) lastDesc).getType().isPrimitive();
550 private CompositeLocation translateCompositeLocationToCallee(CompositeLocation callerCompLoc,
551 NTuple<Location> baseLocTuple, MethodDescriptor mdCallee) {
553 CompositeLocation newCalleeCompLoc = new CompositeLocation();
555 Location calleeThisLoc = new Location(mdCallee, mdCallee.getThis());
556 newCalleeCompLoc.addLocation(calleeThisLoc);
558 // remove the base tuple from the caller
559 // ex; In the method invoation foo.bar.methodA(), the callee will have the composite location
560 // ,which is relative to the 'this' variable, <THIS,...>
561 for (int i = baseLocTuple.size(); i < callerCompLoc.getSize(); i++) {
562 newCalleeCompLoc.addLocation(callerCompLoc.get(i));
565 return newCalleeCompLoc;
569 private void constructGlobalFlowGraph() {
571 System.out.println("");
572 LinkedList<MethodDescriptor> methodDescList =
573 (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
575 System.out.println("@@@methodDescList=" + methodDescList);
578 while (!methodDescList.isEmpty()) {
579 MethodDescriptor md = methodDescList.removeLast();
580 if (state.SSJAVADEBUG) {
581 System.out.println();
582 System.out.println("SSJAVA: Constructing a global flow graph: " + md);
584 FlowGraph flowGraph = getFlowGraph(md);
585 FlowGraph subGlobalFlowGraph = flowGraph.clone();
587 // mapMethodDescriptorToSubGlobalFlowGraph.put(md, subGlobalFlowGraph);
589 // addValueFlowsFromCalleeSubGlobalFlowGraph(md, subGlobalFlowGraph);
592 // subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
593 // } catch (IOException e) {
594 // e.printStackTrace();
596 // FlowGraph fg = new FlowGraph(md, mapParamDescToIdx);
597 // mapMethodDescriptorToFlowGraph.put(md, fg);
598 // analyzeMethodBody(md.getClassDesc(), md);
603 // DEBUG: write a global flow graph
604 MethodDescriptor mdContainingSSJavaLoop = ssjava.getMethodContainingSSJavaLoop();
605 // FlowGraph globalFlowGraph =
606 // getSubGlobalFlowGraph(mdContainingSSJavaLoop);
607 // System.out.println("GLOBAL NODE SET=" + globalFlowGraph.getNodeSet());
608 // assignCompositeLocation(globalFlowGraph);
610 // globalFlowGraph.writeGraph("_GLOBAL");
611 // } catch (IOException e) {
612 // e.printStackTrace();
614 // _debug_printGraph();
618 private void calculateGlobalValueFlowCompositeLocation() {
620 System.out.println("SSJAVA: Calculate composite locations in the global value flow graph");
621 MethodDescriptor methodDescEventLoop = ssjava.getMethodContainingSSJavaLoop();
622 GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(methodDescEventLoop);
624 Set<Location> calculatedPrefixSet = new HashSet<Location>();
626 Set<GlobalFlowNode> nodeSet = globalFlowGraph.getNodeSet();
628 next: for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
629 GlobalFlowNode node = (GlobalFlowNode) iterator.next();
631 Location prefixLoc = node.getLocTuple().get(0);
633 if (calculatedPrefixSet.contains(prefixLoc)) {
634 // the prefix loc has been already assigned to a composite location
638 calculatedPrefixSet.add(prefixLoc);
640 // Set<GlobalFlowNode> incomingNodeSet = globalFlowGraph.getIncomingNodeSet(node);
641 List<NTuple<Location>> prefixList = calculatePrefixList(globalFlowGraph, node);
643 Set<GlobalFlowNode> reachableNodeSet =
644 globalFlowGraph.getReachableNodeSetByPrefix(node.getLocTuple().get(0));
645 // Set<GlobalFlowNode> reachNodeSet = globalFlowGraph.getReachableNodeSetFrom(node);
647 // System.out.println("node=" + node + " prefixList=" + prefixList + " reachableNodeSet="
648 // + reachableNodeSet);
650 for (int i = 0; i < prefixList.size(); i++) {
651 NTuple<Location> curPrefix = prefixList.get(i);
652 Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
654 for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
655 GlobalFlowNode reachNode = (GlobalFlowNode) iterator2.next();
656 if (reachNode.getLocTuple().startsWith(curPrefix)) {
657 reachableCommonPrefixSet.add(reachNode.getLocTuple());
661 if (!reachableCommonPrefixSet.isEmpty()) {
663 MethodDescriptor curPrefixFirstElementMethodDesc =
664 (MethodDescriptor) curPrefix.get(0).getDescriptor();
666 MethodDescriptor nodePrefixLocFirstElementMethodDesc =
667 (MethodDescriptor) prefixLoc.getDescriptor();
669 if (curPrefixFirstElementMethodDesc.equals(nodePrefixLocFirstElementMethodDesc)
670 || isTransitivelyCalledFrom(nodePrefixLocFirstElementMethodDesc,
671 curPrefixFirstElementMethodDesc)) {
674 // if (!node.getLocTuple().startsWith(curPrefix.get(0))) {
676 Location curPrefixLocalLoc = curPrefix.get(0);
677 if (globalFlowGraph.mapLocationToInferCompositeLocation.containsKey(curPrefixLocalLoc)) {
678 // in this case, the local variable of the current prefix has already got a composite
680 // so we just ignore the current composite location.
682 // System.out.println("HERE WE DO NOT ASSIGN A COMPOSITE LOCATION TO =" + node
683 // + " DUE TO " + curPrefix);
688 Location targetLocalLoc = node.getLocTuple().get(0);
689 // CompositeLocation curCompLoc = globalFlowGraph.getCompositeLocation(targetLocalLoc);
690 // if ((curPrefix.size() + 1) > curCompLoc.getSize()) {
692 CompositeLocation newCompLoc = generateCompositeLocation(curPrefix);
693 System.out.println("NEED TO ASSIGN COMP LOC TO " + node + " with prefix=" + curPrefix);
694 System.out.println("- newCompLoc=" + newCompLoc);
695 globalFlowGraph.addMapLocationToInferCompositeLocation(targetLocalLoc, newCompLoc);
708 // Set<GlobalFlowNode> inNodeSet =
709 // graph.getIncomingNodeSetWithPrefix(prefix);
710 // System.out.println("inNodeSet=" + inNodeSet + " from=" + node);
713 private void assignCompositeLocation(CompositeLocation compLocPrefix, GlobalFlowNode node) {
714 CompositeLocation newCompLoc = compLocPrefix.clone();
715 NTuple<Location> locTuple = node.getLocTuple();
716 for (int i = 1; i < locTuple.size(); i++) {
717 newCompLoc.addLocation(locTuple.get(i));
719 node.setInferCompositeLocation(newCompLoc);
722 private List<NTuple<Location>> calculatePrefixList(GlobalFlowGraph graph, GlobalFlowNode node) {
724 System.out.println("\n##### calculatePrefixList node=" + node);
726 MethodDescriptor md = graph.getMethodDescriptor();
728 Set<GlobalFlowNode> incomingNodeSetPrefix =
729 graph.getIncomingNodeSetByPrefix(node.getLocTuple().get(0));
730 // System.out.println("incomingNodeSetPrefix=" + incomingNodeSetPrefix);
732 // Set<GlobalFlowNode> reachableNodeSetPrefix =
733 // graph.getReachableNodeSetByPrefix(node.getLocTuple().get(0));
734 // System.out.println("reachableNodeSetPrefix=" + reachableNodeSetPrefix);
736 List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
738 for (Iterator iterator = incomingNodeSetPrefix.iterator(); iterator.hasNext();) {
739 GlobalFlowNode inNode = (GlobalFlowNode) iterator.next();
740 NTuple<Location> inNodeTuple = inNode.getLocTuple();
742 for (int i = 1; i < inNodeTuple.size(); i++) {
743 NTuple<Location> prefix = inNodeTuple.subList(0, i);
744 if (!prefixList.contains(prefix)) {
745 prefixList.add(prefix);
750 Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
751 public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
752 int s0 = arg0.size();
753 int s1 = arg1.size();
756 } else if (s0 == s1) {
765 // List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
767 // for (Iterator iterator = incomingNodeSet.iterator(); iterator.hasNext();) {
768 // GlobalFlowNode inNode = (GlobalFlowNode) iterator.next();
769 // NTuple<Location> inNodeTuple = inNode.getLocTuple();
771 // for (int i = 1; i < inNodeTuple.size(); i++) {
772 // NTuple<Location> prefix = inNodeTuple.subList(0, i);
773 // if (!prefixList.contains(prefix)) {
774 // prefixList.add(prefix);
779 // Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
780 // public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
781 // int s0 = arg0.size();
782 // int s1 = arg1.size();
785 // } else if (s0 == s1) {
792 // return prefixList;
795 private GlobalFlowGraph constructSubGlobalFlowGraph(FlowGraph flowGraph) {
797 MethodDescriptor md = flowGraph.getMethodDescriptor();
799 GlobalFlowGraph globalGraph = new GlobalFlowGraph(md);
801 // Set<FlowNode> nodeSet = flowGraph.getNodeSet();
802 Set<FlowEdge> edgeSet = flowGraph.getEdgeSet();
804 for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
806 FlowEdge edge = (FlowEdge) iterator.next();
807 NTuple<Descriptor> srcDescTuple = edge.getInitTuple();
808 NTuple<Descriptor> dstDescTuple = edge.getEndTuple();
810 // here only keep the first element(method location) of the descriptor
812 NTuple<Location> srcLocTuple = translateToLocTuple(md, srcDescTuple);
813 // Location srcMethodLoc = srcLocTuple.get(0);
814 // Descriptor srcVarDesc = srcMethodLoc.getLocDescriptor();
815 // // if (flowGraph.isParamDesc(srcVarDesc) &&
816 // (!srcVarDesc.equals(md.getThis()))) {
817 // if (!srcVarDesc.equals(md.getThis())) {
818 // srcLocTuple = new NTuple<Location>();
819 // Location loc = new Location(md, srcVarDesc);
820 // srcLocTuple.add(loc);
823 NTuple<Location> dstLocTuple = translateToLocTuple(md, dstDescTuple);
824 // Location dstMethodLoc = dstLocTuple.get(0);
825 // Descriptor dstVarDesc = dstMethodLoc.getLocDescriptor();
826 // if (!dstVarDesc.equals(md.getThis())) {
827 // dstLocTuple = new NTuple<Location>();
828 // Location loc = new Location(md, dstVarDesc);
829 // dstLocTuple.add(loc);
832 globalGraph.addValueFlowEdge(srcLocTuple, dstLocTuple);
839 private NTuple<Location> translateToLocTuple(MethodDescriptor md, NTuple<Descriptor> descTuple) {
841 NTuple<Location> locTuple = new NTuple<Location>();
843 Descriptor enclosingDesc = md;
844 // System.out.println("md=" + md + " descTuple=" + descTuple);
845 for (int i = 0; i < descTuple.size(); i++) {
846 Descriptor desc = descTuple.get(i);
848 Location loc = new Location(enclosingDesc, desc);
851 if (desc instanceof VarDescriptor) {
852 enclosingDesc = ((VarDescriptor) desc).getType().getClassDesc();
853 } else if (desc instanceof FieldDescriptor) {
854 enclosingDesc = ((FieldDescriptor) desc).getType().getClassDesc();
856 // TODO: inter descriptor case
857 enclosingDesc = desc;
866 private void addValueFlowsFromCalleeSubGlobalFlowGraph(MethodDescriptor mdCaller,
867 GlobalFlowGraph subGlobalFlowGraph) {
869 // the transformation for a call site propagates flows through parameters
870 // if the method is virtual, it also grab all relations from any possible
873 Set<MethodInvokeNode> setMethodInvokeNode = getMethodInvokeNodeSet(mdCaller);
875 for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
876 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
877 MethodDescriptor mdCallee = min.getMethod();
878 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
879 if (mdCallee.isStatic()) {
880 setPossibleCallees.add(mdCallee);
882 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
883 // removes method descriptors that are not invoked by the caller
884 calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
885 setPossibleCallees.addAll(calleeSet);
888 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
889 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
890 propagateValueFlowsToCallerFromSubGlobalFlowGraph(min, mdCaller, possibleMdCallee);
897 private void propagateValueFlowsToCallerFromSubGlobalFlowGraph(MethodInvokeNode min,
898 MethodDescriptor mdCaller, MethodDescriptor possibleMdCallee) {
900 System.out.println("propagateValueFlowsToCallerFromSubGlobalFlowGraph=" + min.printNode(0)
901 + " by caller=" + mdCaller);
902 FlowGraph calleeFlowGraph = getFlowGraph(possibleMdCallee);
903 Map<Integer, NTuple<Descriptor>> mapIdxToArg = mapMethodInvokeNodeToArgIdxMap.get(min);
905 System.out.println("mapMethodInvokeNodeToArgIdxMap.get(min)="
906 + mapMethodInvokeNodeToArgIdxMap.get(min));
907 Set<Integer> keySet = mapIdxToArg.keySet();
908 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
909 Integer idx = (Integer) iterator.next();
910 NTuple<Descriptor> argDescTuple = mapIdxToArg.get(idx);
911 if (argDescTuple.size() > 0) {
912 NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argDescTuple);
913 NTuple<Descriptor> paramDescTuple = calleeFlowGraph.getParamFlowNode(idx).getDescTuple();
914 NTuple<Location> paramLocTuple = translateToLocTuple(possibleMdCallee, paramDescTuple);
915 addMapCallerArgToCalleeParam(min, argDescTuple, paramDescTuple);
920 NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
921 GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(possibleMdCallee);
922 Set<GlobalFlowNode> calleeNodeSet = calleeSubGlobalGraph.getNodeSet();
923 System.out.println("#calleeNodeSet=" + calleeNodeSet);
924 for (Iterator iterator = calleeNodeSet.iterator(); iterator.hasNext();) {
925 GlobalFlowNode calleeNode = (GlobalFlowNode) iterator.next();
926 addValueFlowFromCalleeNode(min, mdCaller, possibleMdCallee, calleeNode);
929 // int numParam = calleeFlowGraph.getNumParameters();
930 // for (int idx = 0; idx < numParam; idx++) {
932 // FlowNode paramNode = calleeFlowGraph.getParamFlowNode(idx);
934 // NTuple<Location> paramLocTuple =
935 // translateToLocTuple(possibleMdCallee, paramNode.getCurrentDescTuple());
937 // GlobalFlowNode globalParamNode =
938 // calleeSubGlobalGraph.getFlowNode(paramLocTuple);
940 // NTuple<Descriptor> argTuple =
941 // mapMethodInvokeNodeToArgIdxMap.get(min).get(idx);
943 // NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argTuple);
945 // System.out.println("argTupleSet=" + argLocTuple + " param=" +
947 // // here, it adds all value flows reachable from the paramNode in the
948 // callee's flow graph
950 // addValueFlowsFromCalleeParam(mdCaller, argLocTuple, baseLocTuple,
956 // // FlowGraph callerSubGlobalGraph = getSubGlobalFlowGraph(mdCaller);
957 // // FlowGraph calleeSubGlobalGraph =
958 // getSubGlobalFlowGraph(possibleMdCallee);
960 // // int numParam = calleeSubGlobalGraph.getNumParameters();
961 // // for (int idx = 0; idx < numParam; idx++) {
962 // // FlowNode paramNode = calleeSubGlobalGraph.getParamFlowNode(idx);
963 // // NTuple<Descriptor> argTuple =
964 // mapMethodInvokeNodeToArgIdxMap.get(min).get(idx);
965 // // System.out.println("argTupleSet=" + argTuple + " param=" +
967 // // // here, it adds all value flows reachable from the paramNode in the
968 // callee's flow graph
969 // // addValueFlowsFromCalleeParam(min, calleeSubGlobalGraph, paramNode,
970 // callerSubGlobalGraph,
971 // // argTuple, baseTuple);
976 private void addValueFlowFromCalleeNode(MethodInvokeNode min, MethodDescriptor mdCaller,
977 MethodDescriptor mdCallee, GlobalFlowNode calleeSrcNode) {
979 GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(mdCallee);
980 GlobalFlowGraph callerSubGlobalGraph = getSubGlobalFlowGraph(mdCaller);
982 NTuple<Location> callerSrcNodeLocTuple =
983 translateToCallerLocTuple(min, mdCallee, mdCaller, calleeSrcNode.getLocTuple());
985 if (callerSrcNodeLocTuple != null) {
986 Set<GlobalFlowNode> outNodeSet = calleeSubGlobalGraph.getOutNodeSet(calleeSrcNode);
988 for (Iterator iterator = outNodeSet.iterator(); iterator.hasNext();) {
989 GlobalFlowNode outNode = (GlobalFlowNode) iterator.next();
990 NTuple<Location> callerDstNodeLocTuple =
991 translateToCallerLocTuple(min, mdCallee, mdCaller, outNode.getLocTuple());
992 if (callerDstNodeLocTuple != null) {
993 callerSubGlobalGraph.addValueFlowEdge(callerSrcNodeLocTuple, callerDstNodeLocTuple);
1000 private NTuple<Location> translateToCallerLocTuple(MethodInvokeNode min,
1001 MethodDescriptor mdCallee, MethodDescriptor mdCaller, NTuple<Location> nodeLocTuple) {
1002 // this method will return NULL if the corresponding argument is literal
1004 // assumes that we don't need to propagate callee flows to the argument
1005 // which is literal.
1007 System.out.println("---translateToCallerLocTuple=" + min.printNode(0)
1008 + " callee nodeLocTuple=" + nodeLocTuple);
1010 FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
1012 NTuple<Descriptor> nodeDescTuple = translateToDescTuple(nodeLocTuple);
1013 if (calleeFlowGraph.isParameter(nodeDescTuple)) {
1014 int paramIdx = calleeFlowGraph.getParamIdx(nodeDescTuple);
1015 NTuple<Descriptor> argDescTuple = mapMethodInvokeNodeToArgIdxMap.get(min).get(paramIdx);
1016 // System.out.println(" mapMethodInvokeNodeToArgIdxMap.get(min)="
1017 // + mapMethodInvokeNodeToArgIdxMap.get(min));
1019 if (argDescTuple.size() == 0) {
1020 // argument is literal
1023 NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argDescTuple);
1025 NTuple<Location> callerLocTuple = new NTuple<Location>();
1027 callerLocTuple.addAll(argLocTuple);
1028 for (int i = 1; i < nodeLocTuple.size(); i++) {
1029 callerLocTuple.add(nodeLocTuple.get(i));
1031 return callerLocTuple;
1033 return nodeLocTuple.clone();
1038 private NTuple<Descriptor> translateToDescTuple(NTuple<Location> locTuple) {
1040 NTuple<Descriptor> descTuple = new NTuple<Descriptor>();
1041 for (int i = 0; i < locTuple.size(); i++) {
1042 descTuple.add(locTuple.get(i).getLocDescriptor());
1048 private void addValueFlowsFromCalleeParam(MethodDescriptor mdCaller,
1049 NTuple<Location> argLocTuple, NTuple<Location> baseLocTuple, MethodDescriptor mdCallee,
1050 GlobalFlowNode globalParamNode) {
1052 Set<GlobalFlowNode> visited = new HashSet<GlobalFlowNode>();
1053 visited.add(globalParamNode);
1054 recurAddValueFlowsFromCalleeParam(mdCaller, argLocTuple, baseLocTuple, mdCallee,
1059 private void recurAddValueFlowsFromCalleeParam(MethodDescriptor mdCaller,
1060 NTuple<Location> argLocTuple, NTuple<Location> baseLocTuple, MethodDescriptor mdCallee,
1061 GlobalFlowNode calleeCurNode) {
1063 // FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
1064 // GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(mdCallee);
1066 // NTuple<Location> curNodeLocTuple = calleeCurNode.getLocTuple();
1067 // NTuple<Descriptor> curNodeDescTuple = calleeCurNode.getDescTuple();
1068 // if (calleeFlowGraph.isParameter(curNodeDescTuple)) {
1069 // curNodeLocTuple = translateToCaller(argLocTuple, curNodeLocTuple);
1072 // Set<GlobalFlowNode> outNodeSet =
1073 // calleeSubGlobalGraph.getOutNodeSet(calleeCurNode);
1074 // for (Iterator iterator = outNodeSet.iterator(); iterator.hasNext();) {
1075 // GlobalFlowNode outNode = (GlobalFlowNode) iterator.next();
1077 // NTuple<Location> curNodeLocTuple = calleeCurNode.getLocTuple();
1078 // NTuple<Descriptor> curNodeDescTuple = calleeCurNode.getDescTuple();
1079 // if (calleeFlowGraph.isParameter(curNodeDescTuple)) {
1080 // curNodeLocTuple = translateToCaller(argLocTuple, curNodeLocTuple);
1083 // outNode.getDescTuple();
1085 // if (calleeFlowGraph.is)
1087 // if (calleeSubGlobalGraph.isParameter(srcDescTuple)) {
1088 // // destination node is started with 'parameter'
1089 // // need to translate it in terms of the caller's a node
1091 // translateToCaller(min, calleeSubGlobalGraph.getParamIdx(srcDescTuple),
1097 // Set<FlowEdge> edgeSet =
1098 // calleeSubGlobalGraph.getOutEdgeSetStartingFrom(calleeSrcNode);
1099 // for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
1100 // FlowEdge flowEdge = (FlowEdge) iterator.next();
1102 // NTuple<Descriptor> srcDescTuple = flowEdge.getInitTuple();
1103 // NTuple<Descriptor> dstDescTuple = flowEdge.getEndTuple();
1105 // FlowNode dstNode = calleeSubGlobalGraph.getFlowNode(dstDescTuple);
1107 // if (calleeSubGlobalGraph.isParameter(srcDescTuple)) {
1108 // // destination node is started with 'parameter'
1109 // // need to translate it in terms of the caller's a node
1111 // translateToCaller(min, calleeSubGlobalGraph.getParamIdx(srcDescTuple),
1115 // if (calleeSubGlobalGraph.isParameter(dstDescTuple)) {
1116 // // destination node is started with 'parameter'
1117 // // need to translate it in terms of the caller's a node
1119 // translateToCaller(min, calleeSubGlobalGraph.getParamIdx(dstDescTuple),
1123 // callerSubGlobalGraph.addValueFlowEdge(srcDescTuple, dstDescTuple);
1125 // if (!visited.contains(dstNode)) {
1126 // visited.add(dstNode);
1127 // recurAddValueFlowsFromCalleeParam(min, calleeSubGlobalGraph, dstNode,
1128 // callerSubGlobalGraph,
1129 // dstDescTuple, visited, baseTuple);
1136 private NTuple<Location> translateToCaller(NTuple<Location> argLocTuple,
1137 NTuple<Location> curNodeLocTuple) {
1139 NTuple<Location> callerLocTuple = new NTuple<Location>();
1141 callerLocTuple.addAll(argLocTuple);
1142 for (int i = 1; i < curNodeLocTuple.size(); i++) {
1143 callerLocTuple.add(curNodeLocTuple.get(i));
1146 return callerLocTuple;
1149 private void recurAddValueFlowsFromCalleeParam(MethodInvokeNode min,
1150 FlowGraph calleeSubGlobalGraph, FlowNode calleeSrcNode, FlowGraph callerSubGlobalGraph,
1151 NTuple<Descriptor> callerSrcTuple, Set<FlowNode> visited, NTuple<Descriptor> baseTuple) {
1153 MethodDescriptor mdCallee = calleeSubGlobalGraph.getMethodDescriptor();
1155 // Set<FlowEdge> edgeSet =
1156 // calleeSubGlobalGraph.getOutEdgeSet(calleeSrcNode);
1157 Set<FlowEdge> edgeSet = calleeSubGlobalGraph.getOutEdgeSetStartingFrom(calleeSrcNode);
1158 for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
1159 FlowEdge flowEdge = (FlowEdge) iterator.next();
1161 NTuple<Descriptor> srcDescTuple = flowEdge.getInitTuple();
1162 NTuple<Descriptor> dstDescTuple = flowEdge.getEndTuple();
1164 FlowNode dstNode = calleeSubGlobalGraph.getFlowNode(dstDescTuple);
1166 if (calleeSubGlobalGraph.isParameter(srcDescTuple)) {
1167 // destination node is started with 'parameter'
1168 // need to translate it in terms of the caller's a node
1170 translateToCaller(min, calleeSubGlobalGraph.getParamIdx(srcDescTuple), srcDescTuple);
1173 if (calleeSubGlobalGraph.isParameter(dstDescTuple)) {
1174 // destination node is started with 'parameter'
1175 // need to translate it in terms of the caller's a node
1177 translateToCaller(min, calleeSubGlobalGraph.getParamIdx(dstDescTuple), dstDescTuple);
1180 callerSubGlobalGraph.addValueFlowEdge(srcDescTuple, dstDescTuple);
1182 if (!visited.contains(dstNode)) {
1183 visited.add(dstNode);
1184 recurAddValueFlowsFromCalleeParam(min, calleeSubGlobalGraph, dstNode, callerSubGlobalGraph,
1185 dstDescTuple, visited, baseTuple);
1192 private NTuple<Descriptor> translateToCaller(MethodInvokeNode min, int paramIdx,
1193 NTuple<Descriptor> srcDescTuple) {
1195 NTuple<Descriptor> callerTuple = new NTuple<Descriptor>();
1197 NTuple<Descriptor> argTuple = mapMethodInvokeNodeToArgIdxMap.get(min).get(paramIdx);
1199 for (int i = 0; i < argTuple.size(); i++) {
1200 callerTuple.add(argTuple.get(i));
1203 for (int i = 1; i < srcDescTuple.size(); i++) {
1204 callerTuple.add(srcDescTuple.get(i));
1210 private NTuple<Descriptor> traslateToCalleeParamTupleToCallerArgTuple(
1211 NTuple<Descriptor> calleeInitTuple, NTuple<Descriptor> callerSrcTuple) {
1213 NTuple<Descriptor> callerInitTuple = new NTuple<Descriptor>();
1215 for (int i = 0; i < callerSrcTuple.size(); i++) {
1216 callerInitTuple.add(callerSrcTuple.get(i));
1219 for (int i = 1; i < calleeInitTuple.size(); i++) {
1220 callerInitTuple.add(calleeInitTuple.get(i));
1223 return callerInitTuple;
1226 public LocationSummary getLocationSummary(Descriptor d) {
1227 if (!mapDescToLocationSummary.containsKey(d)) {
1228 if (d instanceof MethodDescriptor) {
1229 mapDescToLocationSummary.put(d, new MethodSummary((MethodDescriptor) d));
1230 } else if (d instanceof ClassDescriptor) {
1231 mapDescToLocationSummary.put(d, new FieldSummary());
1234 return mapDescToLocationSummary.get(d);
1237 private void generateMethodSummary() {
1239 Set<MethodDescriptor> keySet = md2lattice.keySet();
1240 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1241 MethodDescriptor md = (MethodDescriptor) iterator.next();
1243 System.out.println("\nSSJAVA: generate method summary: " + md);
1245 FlowGraph flowGraph = getFlowGraph(md);
1246 MethodSummary methodSummary = getMethodSummary(md);
1248 // construct a parameter mapping that maps a parameter descriptor to an
1249 // inferred composite
1252 for (int paramIdx = 0; paramIdx < flowGraph.getNumParameters(); paramIdx++) {
1253 FlowNode flowNode = flowGraph.getParamFlowNode(paramIdx);
1254 CompositeLocation inferredCompLoc = flowNode.getCompositeLocation();
1255 // NTuple<Descriptor> descTuple = flowNode.getDescTuple();
1257 // CompositeLocation assignedCompLoc = flowNode.getCompositeLocation();
1258 // CompositeLocation inferredCompLoc;
1259 // if (assignedCompLoc != null) {
1260 // inferredCompLoc = translateCompositeLocation(assignedCompLoc);
1262 // Descriptor locDesc = descTuple.get(0);
1263 // Location loc = new Location(md, locDesc.getSymbol());
1264 // loc.setLocDescriptor(locDesc);
1265 // inferredCompLoc = new CompositeLocation(loc);
1267 System.out.println("-paramIdx=" + paramIdx + " infer=" + inferredCompLoc);
1268 System.out.println("-flowNode inferLoc=" + flowNode.getCompositeLocation());
1269 methodSummary.addMapParamIdxToInferLoc(paramIdx, inferredCompLoc);
1276 private boolean hasOrderingRelation(NTuple<Location> locTuple1, NTuple<Location> locTuple2) {
1278 int size = locTuple1.size() >= locTuple2.size() ? locTuple2.size() : locTuple1.size();
1280 for (int idx = 0; idx < size; idx++) {
1281 Location loc1 = locTuple1.get(idx);
1282 Location loc2 = locTuple2.get(idx);
1284 Descriptor desc1 = loc1.getDescriptor();
1285 Descriptor desc2 = loc2.getDescriptor();
1287 if (!desc1.equals(desc2)) {
1288 throw new Error("Fail to compare " + locTuple1 + " and " + locTuple2);
1291 Descriptor locDesc1 = loc1.getLocDescriptor();
1292 Descriptor locDesc2 = loc2.getLocDescriptor();
1294 HierarchyGraph hierarchyGraph = getHierarchyGraph(desc1);
1296 HNode node1 = hierarchyGraph.getHNode(locDesc1);
1297 HNode node2 = hierarchyGraph.getHNode(locDesc2);
1299 System.out.println("---node1=" + node1 + " node2=" + node2);
1300 System.out.println("---hierarchyGraph.getIncomingNodeSet(node2)="
1301 + hierarchyGraph.getIncomingNodeSet(node2));
1303 if (locDesc1.equals(locDesc2)) {
1305 } else if (!hierarchyGraph.getIncomingNodeSet(node2).contains(node1)
1306 && !hierarchyGraph.getIncomingNodeSet(node1).contains(node2)) {
1318 private boolean isHigherThan(NTuple<Location> locTuple1, NTuple<Location> locTuple2) {
1320 int size = locTuple1.size() >= locTuple2.size() ? locTuple2.size() : locTuple1.size();
1322 for (int idx = 0; idx < size; idx++) {
1323 Location loc1 = locTuple1.get(idx);
1324 Location loc2 = locTuple2.get(idx);
1326 Descriptor desc1 = loc1.getDescriptor();
1327 Descriptor desc2 = loc2.getDescriptor();
1329 if (!desc1.equals(desc2)) {
1330 throw new Error("Fail to compare " + locTuple1 + " and " + locTuple2);
1333 Descriptor locDesc1 = loc1.getLocDescriptor();
1334 Descriptor locDesc2 = loc2.getLocDescriptor();
1336 HierarchyGraph hierarchyGraph = getHierarchyGraph(desc1);
1338 HNode node1 = hierarchyGraph.getHNode(locDesc1);
1339 HNode node2 = hierarchyGraph.getHNode(locDesc2);
1341 System.out.println("---node1=" + node1 + " node2=" + node2);
1342 System.out.println("---hierarchyGraph.getIncomingNodeSet(node2)="
1343 + hierarchyGraph.getIncomingNodeSet(node2));
1345 if (locDesc1.equals(locDesc2)) {
1347 } else if (hierarchyGraph.getIncomingNodeSet(node2).contains(node1)) {
1358 private CompositeLocation translateCompositeLocation(CompositeLocation compLoc) {
1359 CompositeLocation newCompLoc = new CompositeLocation();
1361 // System.out.println("compLoc=" + compLoc);
1362 for (int i = 0; i < compLoc.getSize(); i++) {
1363 Location loc = compLoc.get(i);
1364 Descriptor enclosingDescriptor = loc.getDescriptor();
1365 Descriptor locDescriptor = loc.getLocDescriptor();
1367 HNode hnode = getHierarchyGraph(enclosingDescriptor).getHNode(locDescriptor);
1368 // System.out.println("-hnode=" + hnode + " from=" + locDescriptor +
1369 // " enclosingDescriptor="
1370 // + enclosingDescriptor);
1371 // System.out.println("-getLocationSummary(enclosingDescriptor)="
1372 // + getLocationSummary(enclosingDescriptor));
1373 String locName = getLocationSummary(enclosingDescriptor).getLocationName(hnode.getName());
1374 // System.out.println("-locName=" + locName);
1375 Location newLoc = new Location(enclosingDescriptor, locName);
1376 newLoc.setLocDescriptor(locDescriptor);
1377 newCompLoc.addLocation(newLoc);
1383 private void debug_writeLattices() {
1385 Set<Descriptor> keySet = mapDescriptorToSimpleLattice.keySet();
1386 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1387 Descriptor key = (Descriptor) iterator.next();
1388 SSJavaLattice<String> simpleLattice = mapDescriptorToSimpleLattice.get(key);
1389 // HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(key);
1390 HierarchyGraph scHierarchyGraph = getSkeletonCombinationHierarchyGraph(key);
1391 if (key instanceof ClassDescriptor) {
1392 writeInferredLatticeDotFile((ClassDescriptor) key, scHierarchyGraph, simpleLattice,
1394 } else if (key instanceof MethodDescriptor) {
1395 MethodDescriptor md = (MethodDescriptor) key;
1396 writeInferredLatticeDotFile(md.getClassDesc(), md, scHierarchyGraph, simpleLattice,
1400 LocationSummary ls = getLocationSummary(key);
1401 System.out.println("####LOC SUMMARY=" + key + "\n" + ls.getMapHNodeNameToLocationName());
1404 Set<ClassDescriptor> cdKeySet = cd2lattice.keySet();
1405 for (Iterator iterator = cdKeySet.iterator(); iterator.hasNext();) {
1406 ClassDescriptor cd = (ClassDescriptor) iterator.next();
1407 writeInferredLatticeDotFile((ClassDescriptor) cd, getSkeletonCombinationHierarchyGraph(cd),
1408 cd2lattice.get(cd), "");
1411 Set<MethodDescriptor> mdKeySet = md2lattice.keySet();
1412 for (Iterator iterator = mdKeySet.iterator(); iterator.hasNext();) {
1413 MethodDescriptor md = (MethodDescriptor) iterator.next();
1414 writeInferredLatticeDotFile(md.getClassDesc(), md, getSkeletonCombinationHierarchyGraph(md),
1415 md2lattice.get(md), "");
1420 private void buildLattice() {
1422 BuildLattice buildLattice = new BuildLattice(this);
1424 Set<Descriptor> keySet = mapDescriptorToCombineSkeletonHierarchyGraph.keySet();
1425 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1426 Descriptor desc = (Descriptor) iterator.next();
1428 SSJavaLattice<String> simpleLattice = buildLattice.buildLattice(desc);
1430 addMapDescToSimpleLattice(desc, simpleLattice);
1432 HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
1433 System.out.println("\n## insertIntermediateNodesToStraightLine:"
1434 + simpleHierarchyGraph.getName());
1435 SSJavaLattice<String> lattice =
1436 buildLattice.insertIntermediateNodesToStraightLine(desc, simpleLattice);
1437 lattice.removeRedundantEdges();
1439 if (desc instanceof ClassDescriptor) {
1441 cd2lattice.put((ClassDescriptor) desc, lattice);
1442 // ssjava.writeLatticeDotFile((ClassDescriptor) desc, null, lattice);
1443 } else if (desc instanceof MethodDescriptor) {
1445 md2lattice.put((MethodDescriptor) desc, lattice);
1446 MethodDescriptor md = (MethodDescriptor) desc;
1447 ClassDescriptor cd = md.getClassDesc();
1448 // ssjava.writeLatticeDotFile(cd, md, lattice);
1451 // System.out.println("\nSSJAVA: Insering Combination Nodes:" + desc);
1452 // HierarchyGraph skeletonGraph = getSkeletonHierarchyGraph(desc);
1453 // HierarchyGraph skeletonGraphWithCombinationNode =
1454 // skeletonGraph.clone();
1455 // skeletonGraphWithCombinationNode.setName(desc + "_SC");
1457 // HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
1458 // System.out.println("Identifying Combination Nodes:");
1459 // skeletonGraphWithCombinationNode.insertCombinationNodesToGraph(simpleHierarchyGraph);
1460 // skeletonGraphWithCombinationNode.simplifySkeletonCombinationHierarchyGraph();
1461 // mapDescriptorToCombineSkeletonHierarchyGraph.put(desc,
1462 // skeletonGraphWithCombinationNode);
1467 public void addMapDescToSimpleLattice(Descriptor desc, SSJavaLattice<String> lattice) {
1468 mapDescriptorToSimpleLattice.put(desc, lattice);
1471 public SSJavaLattice<String> getSimpleLattice(Descriptor desc) {
1472 return mapDescriptorToSimpleLattice.get(desc);
1475 private void simplifyHierarchyGraph() {
1476 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1477 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1478 Descriptor desc = (Descriptor) iterator.next();
1479 HierarchyGraph simpleHierarchyGraph = getHierarchyGraph(desc).clone();
1480 simpleHierarchyGraph.setName(desc + "_SIMPLE");
1481 simpleHierarchyGraph.removeRedundantEdges();
1482 // simpleHierarchyGraph.simplifyHierarchyGraph();
1483 mapDescriptorToSimpleHierarchyGraph.put(desc, simpleHierarchyGraph);
1487 private void insertCombinationNodes() {
1488 Set<Descriptor> keySet = mapDescriptorToSkeletonHierarchyGraph.keySet();
1489 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1490 Descriptor desc = (Descriptor) iterator.next();
1491 System.out.println("\nSSJAVA: Insering Combination Nodes:" + desc);
1492 HierarchyGraph skeletonGraph = getSkeletonHierarchyGraph(desc);
1493 HierarchyGraph skeletonGraphWithCombinationNode = skeletonGraph.clone();
1494 skeletonGraphWithCombinationNode.setName(desc + "_SC");
1496 HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
1497 System.out.println("Identifying Combination Nodes:");
1498 skeletonGraphWithCombinationNode.insertCombinationNodesToGraph(simpleHierarchyGraph);
1499 skeletonGraphWithCombinationNode.simplifySkeletonCombinationHierarchyGraph();
1500 mapDescriptorToCombineSkeletonHierarchyGraph.put(desc, skeletonGraphWithCombinationNode);
1504 private void constructSkeletonHierarchyGraph() {
1505 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1506 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1507 Descriptor desc = (Descriptor) iterator.next();
1508 HierarchyGraph simpleGraph = getSimpleHierarchyGraph(desc);
1509 HierarchyGraph skeletonGraph = simpleGraph.generateSkeletonGraph();
1510 skeletonGraph.setMapDescToHNode(simpleGraph.getMapDescToHNode());
1511 skeletonGraph.setMapHNodeToDescSet(simpleGraph.getMapHNodeToDescSet());
1512 skeletonGraph.simplifyHierarchyGraph();
1513 // skeletonGraph.combineRedundantNodes(false);
1514 // skeletonGraph.removeRedundantEdges();
1515 mapDescriptorToSkeletonHierarchyGraph.put(desc, skeletonGraph);
1519 private void debug_writeHierarchyDotFiles() {
1521 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1522 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1523 Descriptor desc = (Descriptor) iterator.next();
1524 getHierarchyGraph(desc).writeGraph();
1529 private void debug_writeSimpleHierarchyDotFiles() {
1531 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1532 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1533 Descriptor desc = (Descriptor) iterator.next();
1534 getHierarchyGraph(desc).writeGraph();
1535 getSimpleHierarchyGraph(desc).writeGraph();
1540 private void debug_writeSkeletonHierarchyDotFiles() {
1542 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1543 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1544 Descriptor desc = (Descriptor) iterator.next();
1545 getSkeletonHierarchyGraph(desc).writeGraph();
1550 private void debug_writeSkeletonCombinationHierarchyDotFiles() {
1552 Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
1553 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1554 Descriptor desc = (Descriptor) iterator.next();
1555 getSkeletonCombinationHierarchyGraph(desc).writeGraph();
1560 public HierarchyGraph getSimpleHierarchyGraph(Descriptor d) {
1561 return mapDescriptorToSimpleHierarchyGraph.get(d);
1564 private HierarchyGraph getSkeletonHierarchyGraph(Descriptor d) {
1565 if (!mapDescriptorToSkeletonHierarchyGraph.containsKey(d)) {
1566 mapDescriptorToSkeletonHierarchyGraph.put(d, new HierarchyGraph(d));
1568 return mapDescriptorToSkeletonHierarchyGraph.get(d);
1571 public HierarchyGraph getSkeletonCombinationHierarchyGraph(Descriptor d) {
1572 if (!mapDescriptorToCombineSkeletonHierarchyGraph.containsKey(d)) {
1573 mapDescriptorToCombineSkeletonHierarchyGraph.put(d, new HierarchyGraph(d));
1575 return mapDescriptorToCombineSkeletonHierarchyGraph.get(d);
1578 private void constructHierarchyGraph() {
1580 // do fixed-point analysis
1583 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
1585 // Collections.sort(descriptorListToAnalyze, new
1586 // Comparator<MethodDescriptor>() {
1587 // public int compare(MethodDescriptor o1, MethodDescriptor o2) {
1588 // return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
1592 // current descriptors to visit in fixed-point interprocedural analysis,
1593 // prioritized by dependency in the call graph
1594 methodDescriptorsToVisitStack.clear();
1596 Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
1597 methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
1599 while (!descriptorListToAnalyze.isEmpty()) {
1600 MethodDescriptor md = descriptorListToAnalyze.removeFirst();
1601 methodDescriptorsToVisitStack.add(md);
1604 // analyze scheduled methods until there are no more to visit
1605 while (!methodDescriptorsToVisitStack.isEmpty()) {
1606 // start to analyze leaf node
1607 MethodDescriptor md = methodDescriptorsToVisitStack.pop();
1609 HierarchyGraph hierarchyGraph = new HierarchyGraph(md);
1610 // MethodSummary methodSummary = new MethodSummary(md);
1612 // MethodLocationInfo methodInfo = new MethodLocationInfo(md);
1613 // curMethodInfo = methodInfo;
1615 System.out.println();
1616 System.out.println("SSJAVA: Construcing the hierarchy graph from " + md);
1618 constructHierarchyGraph(md, hierarchyGraph);
1620 HierarchyGraph prevHierarchyGraph = getHierarchyGraph(md);
1621 // MethodSummary prevMethodSummary = getMethodSummary(md);
1623 if (!hierarchyGraph.equals(prevHierarchyGraph)) {
1625 mapDescriptorToHierarchyGraph.put(md, hierarchyGraph);
1626 // mapDescToLocationSummary.put(md, methodSummary);
1628 // results for callee changed, so enqueue dependents caller for
1630 Iterator<MethodDescriptor> depsItr = ssjava.getDependents(md).iterator();
1631 while (depsItr.hasNext()) {
1632 MethodDescriptor methodNext = depsItr.next();
1633 if (!methodDescriptorsToVisitStack.contains(methodNext)
1634 && methodDescriptorToVistSet.contains(methodNext)) {
1635 methodDescriptorsToVisitStack.add(methodNext);
1645 private HierarchyGraph getHierarchyGraph(Descriptor d) {
1646 if (!mapDescriptorToHierarchyGraph.containsKey(d)) {
1647 mapDescriptorToHierarchyGraph.put(d, new HierarchyGraph(d));
1649 return mapDescriptorToHierarchyGraph.get(d);
1652 private void constructHierarchyGraph(MethodDescriptor md, HierarchyGraph methodGraph) {
1654 // visit each node of method flow graph
1655 FlowGraph fg = getFlowGraph(md);
1656 Set<FlowNode> nodeSet = fg.getNodeSet();
1658 Set<Descriptor> paramDescSet = fg.getMapParamDescToIdx().keySet();
1659 for (Iterator iterator = paramDescSet.iterator(); iterator.hasNext();) {
1660 Descriptor desc = (Descriptor) iterator.next();
1661 methodGraph.getHNode(desc).setSkeleton(true);
1664 // for the method lattice, we need to look at the first element of
1665 // NTuple<Descriptor>
1666 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1667 FlowNode srcNode = (FlowNode) iterator.next();
1669 Set<FlowEdge> outEdgeSet = fg.getOutEdgeSet(srcNode);
1670 for (Iterator iterator2 = outEdgeSet.iterator(); iterator2.hasNext();) {
1671 FlowEdge outEdge = (FlowEdge) iterator2.next();
1672 FlowNode dstNode = outEdge.getDst();
1674 NTuple<Descriptor> srcNodeTuple = srcNode.getDescTuple();
1675 NTuple<Descriptor> dstNodeTuple = dstNode.getDescTuple();
1677 if (outEdge.getInitTuple().equals(srcNodeTuple)
1678 && outEdge.getEndTuple().equals(dstNodeTuple)) {
1680 NTuple<Descriptor> srcCurTuple = srcNode.getCurrentDescTuple();
1681 NTuple<Descriptor> dstCurTuple = dstNode.getCurrentDescTuple();
1683 if ((srcCurTuple.size() > 1 && dstCurTuple.size() > 1)
1684 && srcCurTuple.get(0).equals(dstCurTuple.get(0))) {
1686 // value flows between fields
1687 Descriptor desc = srcCurTuple.get(0);
1688 ClassDescriptor classDesc;
1690 if (desc.equals(GLOBALDESC)) {
1691 classDesc = md.getClassDesc();
1693 VarDescriptor varDesc = (VarDescriptor) srcCurTuple.get(0);
1694 classDesc = varDesc.getType().getClassDesc();
1696 extractFlowsBetweenFields(classDesc, srcNode, dstNode, 1);
1699 // value flow between local var - local var or local var - field
1701 Descriptor srcDesc = srcCurTuple.get(0);
1702 Descriptor dstDesc = dstCurTuple.get(0);
1704 methodGraph.addEdge(srcDesc, dstDesc);
1706 if (fg.isParamDesc(srcDesc)) {
1707 methodGraph.setParamHNode(srcDesc);
1709 if (fg.isParamDesc(dstDesc)) {
1710 methodGraph.setParamHNode(dstDesc);
1721 private MethodSummary getMethodSummary(MethodDescriptor md) {
1722 if (!mapDescToLocationSummary.containsKey(md)) {
1723 mapDescToLocationSummary.put(md, new MethodSummary(md));
1725 return (MethodSummary) mapDescToLocationSummary.get(md);
1728 private void addMapClassDefinitionToLineNum(ClassDescriptor cd, String strLine, int lineNum) {
1730 String classSymbol = cd.getSymbol();
1731 int idx = classSymbol.lastIndexOf("$");
1733 classSymbol = classSymbol.substring(idx + 1);
1736 String pattern = "class " + classSymbol + " ";
1737 if (strLine.indexOf(pattern) != -1) {
1738 mapDescToDefinitionLine.put(cd, lineNum);
1742 private void addMapMethodDefinitionToLineNum(Set<MethodDescriptor> methodSet, String strLine,
1744 for (Iterator iterator = methodSet.iterator(); iterator.hasNext();) {
1745 MethodDescriptor md = (MethodDescriptor) iterator.next();
1746 String pattern = md.getMethodDeclaration();
1747 if (strLine.indexOf(pattern) != -1) {
1748 mapDescToDefinitionLine.put(md, lineNum);
1749 methodSet.remove(md);
1756 private void readOriginalSourceFiles() {
1758 SymbolTable classtable = state.getClassSymbolTable();
1760 Set<ClassDescriptor> classDescSet = new HashSet<ClassDescriptor>();
1761 classDescSet.addAll(classtable.getValueSet());
1764 // inefficient implement. it may re-visit the same file if the file
1765 // contains more than one class definitions.
1766 for (Iterator iterator = classDescSet.iterator(); iterator.hasNext();) {
1767 ClassDescriptor cd = (ClassDescriptor) iterator.next();
1769 Set<MethodDescriptor> methodSet = new HashSet<MethodDescriptor>();
1770 methodSet.addAll(cd.getMethodTable().getValueSet());
1772 String sourceFileName = cd.getSourceFileName();
1773 Vector<String> lineVec = new Vector<String>();
1775 mapFileNameToLineVector.put(sourceFileName, lineVec);
1777 BufferedReader in = new BufferedReader(new FileReader(sourceFileName));
1780 lineVec.add(""); // the index is started from 1.
1781 while ((strLine = in.readLine()) != null) {
1782 lineVec.add(lineNum, strLine);
1783 addMapClassDefinitionToLineNum(cd, strLine, lineNum);
1784 addMapMethodDefinitionToLineNum(methodSet, strLine, lineNum);
1790 } catch (IOException e) {
1791 e.printStackTrace();
1796 private String generateLatticeDefinition(Descriptor desc) {
1798 Set<String> sharedLocSet = new HashSet<String>();
1800 SSJavaLattice<String> lattice = getLattice(desc);
1801 String rtr = "@LATTICE(\"";
1803 Map<String, Set<String>> map = lattice.getTable();
1804 Set<String> keySet = map.keySet();
1805 boolean first = true;
1806 for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1807 String key = (String) iterator.next();
1808 if (!key.equals(lattice.getTopItem())) {
1809 Set<String> connectedSet = map.get(key);
1811 if (connectedSet.size() == 1) {
1812 if (connectedSet.iterator().next().equals(lattice.getBottomItem())) {
1820 if (lattice.isSharedLoc(key)) {
1821 rtr += "," + key + "*";
1826 for (Iterator iterator2 = connectedSet.iterator(); iterator2.hasNext();) {
1827 String loc = (String) iterator2.next();
1828 if (!loc.equals(lattice.getBottomItem())) {
1835 rtr += loc + "<" + key;
1836 if (lattice.isSharedLoc(key) && (!sharedLocSet.contains(key))) {
1837 rtr += "," + key + "*";
1838 sharedLocSet.add(key);
1840 if (lattice.isSharedLoc(loc) && (!sharedLocSet.contains(loc))) {
1841 rtr += "," + loc + "*";
1842 sharedLocSet.add(loc);
1852 if (desc instanceof MethodDescriptor) {
1853 TypeDescriptor returnType = ((MethodDescriptor) desc).getReturnType();
1855 MethodLocationInfo methodLocInfo = getMethodLocationInfo((MethodDescriptor) desc);
1857 if (returnType != null && (!returnType.isVoid())) {
1859 "\n@RETURNLOC(\"" + generateLocationAnnoatation(methodLocInfo.getReturnLoc()) + "\")";
1862 rtr += "\n@THISLOC(\"this\")";
1863 rtr += "\n@GLOBALLOC(\"GLOBALLOC\")";
1865 CompositeLocation pcLoc = methodLocInfo.getPCLoc();
1866 if ((pcLoc != null) && (!pcLoc.get(0).isTop())) {
1867 rtr += "\n@PCLOC(\"" + generateLocationAnnoatation(pcLoc) + "\")";
1875 private void generateAnnoatedCode() {
1877 readOriginalSourceFiles();
1880 while (!toAnalyzeIsEmpty()) {
1881 ClassDescriptor cd = toAnalyzeNext();
1883 setupToAnalazeMethod(cd);
1885 LocationInfo locInfo = mapClassToLocationInfo.get(cd);
1886 String sourceFileName = cd.getSourceFileName();
1888 if (cd.isInterface()) {
1892 int classDefLine = mapDescToDefinitionLine.get(cd);
1893 Vector<String> sourceVec = mapFileNameToLineVector.get(sourceFileName);
1895 if (locInfo == null) {
1896 locInfo = getLocationInfo(cd);
1899 for (Iterator iter = cd.getFields(); iter.hasNext();) {
1900 FieldDescriptor fieldDesc = (FieldDescriptor) iter.next();
1901 if (!(fieldDesc.isStatic() && fieldDesc.isFinal())) {
1902 String locIdentifier = locInfo.getFieldInferLocation(fieldDesc).getLocIdentifier();
1903 if (!getLattice(cd).getElementSet().contains(locIdentifier)) {
1904 getLattice(cd).put(locIdentifier);
1909 String fieldLatticeDefStr = generateLatticeDefinition(cd);
1910 String annoatedSrc = fieldLatticeDefStr + newline + sourceVec.get(classDefLine);
1911 sourceVec.set(classDefLine, annoatedSrc);
1913 // generate annotations for field declarations
1914 LocationInfo fieldLocInfo = getLocationInfo(cd);
1915 Map<Descriptor, CompositeLocation> inferLocMap = fieldLocInfo.getMapDescToInferLocation();
1917 for (Iterator iter = cd.getFields(); iter.hasNext();) {
1918 FieldDescriptor fd = (FieldDescriptor) iter.next();
1920 String locAnnotationStr;
1921 CompositeLocation inferLoc = inferLocMap.get(fd);
1923 if (inferLoc != null) {
1924 // infer loc is null if the corresponding field is static and final
1925 locAnnotationStr = "@LOC(\"" + generateLocationAnnoatation(inferLoc) + "\")";
1926 int fdLineNum = fd.getLineNum();
1927 String orgFieldDeclarationStr = sourceVec.get(fdLineNum);
1928 String fieldDeclaration = fd.toString();
1929 fieldDeclaration = fieldDeclaration.substring(0, fieldDeclaration.length() - 1);
1930 String annoatedStr = locAnnotationStr + " " + orgFieldDeclarationStr;
1931 sourceVec.set(fdLineNum, annoatedStr);
1936 while (!toAnalyzeMethodIsEmpty()) {
1937 MethodDescriptor md = toAnalyzeMethodNext();
1939 if (!ssjava.needTobeAnnotated(md)) {
1943 SSJavaLattice<String> methodLattice = md2lattice.get(md);
1944 if (methodLattice != null) {
1946 int methodDefLine = md.getLineNum();
1948 MethodLocationInfo methodLocInfo = getMethodLocationInfo(md);
1950 Map<Descriptor, CompositeLocation> methodInferLocMap =
1951 methodLocInfo.getMapDescToInferLocation();
1952 Set<Descriptor> localVarDescSet = methodInferLocMap.keySet();
1954 Set<String> localLocElementSet = methodLattice.getElementSet();
1956 for (Iterator iterator = localVarDescSet.iterator(); iterator.hasNext();) {
1957 Descriptor localVarDesc = (Descriptor) iterator.next();
1958 CompositeLocation inferLoc = methodInferLocMap.get(localVarDesc);
1960 String localLocIdentifier = inferLoc.get(0).getLocIdentifier();
1961 if (!localLocElementSet.contains(localLocIdentifier)) {
1962 methodLattice.put(localLocIdentifier);
1965 String locAnnotationStr = "@LOC(\"" + generateLocationAnnoatation(inferLoc) + "\")";
1967 if (!isParameter(md, localVarDesc)) {
1968 if (mapDescToDefinitionLine.containsKey(localVarDesc)) {
1969 int varLineNum = mapDescToDefinitionLine.get(localVarDesc);
1970 String orgSourceLine = sourceVec.get(varLineNum);
1972 orgSourceLine.indexOf(generateVarDeclaration((VarDescriptor) localVarDesc));
1974 String annoatedStr =
1975 orgSourceLine.substring(0, idx) + locAnnotationStr + " "
1976 + orgSourceLine.substring(idx);
1977 sourceVec.set(varLineNum, annoatedStr);
1980 String methodDefStr = sourceVec.get(methodDefLine);
1983 getParamLocation(methodDefStr,
1984 generateVarDeclaration((VarDescriptor) localVarDesc));
1988 String annoatedStr =
1989 methodDefStr.substring(0, idx) + locAnnotationStr + " "
1990 + methodDefStr.substring(idx);
1991 sourceVec.set(methodDefLine, annoatedStr);
1996 // check if the lattice has to have the location type for the this
1999 // boolean needToAddthisRef = hasThisReference(md);
2000 if (localLocElementSet.contains("this")) {
2001 methodLattice.put("this");
2004 String methodLatticeDefStr = generateLatticeDefinition(md);
2005 String annoatedStr = methodLatticeDefStr + newline + sourceVec.get(methodDefLine);
2006 sourceVec.set(methodDefLine, annoatedStr);
2016 private boolean hasThisReference(MethodDescriptor md) {
2018 FlowGraph fg = getFlowGraph(md);
2019 Set<FlowNode> nodeSet = fg.getNodeSet();
2020 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
2021 FlowNode flowNode = (FlowNode) iterator.next();
2022 if (flowNode.getDescTuple().get(0).equals(md.getThis())) {
2030 private int getParamLocation(String methodStr, String paramStr) {
2032 String pattern = paramStr + ",";
2034 int idx = methodStr.indexOf(pattern);
2038 pattern = paramStr + ")";
2039 return methodStr.indexOf(pattern);
2044 private String generateVarDeclaration(VarDescriptor varDesc) {
2046 TypeDescriptor td = varDesc.getType();
2047 String rtr = td.toString();
2049 for (int i = 0; i < td.getArrayCount(); i++) {
2053 rtr += " " + varDesc.getName();
2058 private String generateLocationAnnoatation(CompositeLocation loc) {
2061 Location methodLoc = loc.get(0);
2062 rtr += methodLoc.getLocIdentifier();
2064 for (int i = 1; i < loc.getSize(); i++) {
2065 Location element = loc.get(i);
2066 rtr += "," + element.getDescriptor().getSymbol() + "." + element.getLocIdentifier();
2072 private boolean isParameter(MethodDescriptor md, Descriptor localVarDesc) {
2073 return getFlowGraph(md).isParamDesc(localVarDesc);
2076 private String extractFileName(String fileName) {
2077 int idx = fileName.lastIndexOf("/");
2081 return fileName.substring(idx + 1);
2086 private void codeGen() {
2088 Set<String> originalFileNameSet = mapFileNameToLineVector.keySet();
2089 for (Iterator iterator = originalFileNameSet.iterator(); iterator.hasNext();) {
2090 String orgFileName = (String) iterator.next();
2091 String outputFileName = extractFileName(orgFileName);
2093 Vector<String> sourceVec = mapFileNameToLineVector.get(orgFileName);
2097 FileWriter fileWriter = new FileWriter("./infer/" + outputFileName);
2098 BufferedWriter out = new BufferedWriter(fileWriter);
2100 for (int i = 0; i < sourceVec.size(); i++) {
2101 out.write(sourceVec.get(i));
2105 } catch (IOException e) {
2106 e.printStackTrace();
2113 private void checkLattices() {
2115 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
2117 // current descriptors to visit in fixed-point interprocedural analysis,
2119 // dependency in the call graph
2120 methodDescriptorsToVisitStack.clear();
2122 // descriptorListToAnalyze.removeFirst();
2124 Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
2125 methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
2127 while (!descriptorListToAnalyze.isEmpty()) {
2128 MethodDescriptor md = descriptorListToAnalyze.removeFirst();
2129 checkLatticesOfVirtualMethods(md);
2134 private void debug_writeLatticeDotFile() {
2135 // generate lattice dot file
2139 while (!toAnalyzeIsEmpty()) {
2140 ClassDescriptor cd = toAnalyzeNext();
2142 setupToAnalazeMethod(cd);
2144 SSJavaLattice<String> classLattice = cd2lattice.get(cd);
2145 if (classLattice != null) {
2146 ssjava.writeLatticeDotFile(cd, null, classLattice);
2147 debug_printDescriptorToLocNameMapping(cd);
2150 while (!toAnalyzeMethodIsEmpty()) {
2151 MethodDescriptor md = toAnalyzeMethodNext();
2152 SSJavaLattice<String> methodLattice = md2lattice.get(md);
2153 if (methodLattice != null) {
2154 ssjava.writeLatticeDotFile(cd, md, methodLattice);
2155 debug_printDescriptorToLocNameMapping(md);
2162 private void debug_printDescriptorToLocNameMapping(Descriptor desc) {
2164 LocationInfo info = getLocationInfo(desc);
2165 System.out.println("## " + desc + " ##");
2166 System.out.println(info.getMapDescToInferLocation());
2167 LocationInfo locInfo = getLocationInfo(desc);
2168 System.out.println("mapping=" + locInfo.getMapLocSymbolToDescSet());
2169 System.out.println("###################");
2173 private void inferLattices() {
2176 private void calculateExtraLocations() {
2177 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
2178 for (Iterator iterator = descriptorListToAnalyze.iterator(); iterator.hasNext();) {
2179 MethodDescriptor md = (MethodDescriptor) iterator.next();
2180 calculateExtraLocations(md);
2184 private void calculateExtraLocations2() {
2185 LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
2186 for (Iterator iterator = descriptorListToAnalyze.iterator(); iterator.hasNext();) {
2187 MethodDescriptor md = (MethodDescriptor) iterator.next();
2188 calculateExtraLocations(md);
2192 private void setMethodLocInfo(MethodDescriptor md, MethodLocationInfo methodInfo) {
2193 mapMethodDescToMethodLocationInfo.put(md, methodInfo);
2196 private void checkLatticesOfVirtualMethods(MethodDescriptor md) {
2198 if (!md.isStatic()) {
2199 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
2200 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
2202 for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
2203 MethodDescriptor mdCallee = (MethodDescriptor) iterator.next();
2204 if (!md.equals(mdCallee)) {
2205 checkConsistency(md, mdCallee);
2213 private void checkConsistency(MethodDescriptor md1, MethodDescriptor md2) {
2215 // check that two lattice have the same relations between parameters(+PC
2216 // LOC, GLOBAL_LOC RETURN LOC)
2218 List<CompositeLocation> list1 = new ArrayList<CompositeLocation>();
2219 List<CompositeLocation> list2 = new ArrayList<CompositeLocation>();
2221 MethodLocationInfo locInfo1 = getMethodLocationInfo(md1);
2222 MethodLocationInfo locInfo2 = getMethodLocationInfo(md2);
2224 Map<Integer, CompositeLocation> paramMap1 = locInfo1.getMapParamIdxToInferLoc();
2225 Map<Integer, CompositeLocation> paramMap2 = locInfo2.getMapParamIdxToInferLoc();
2227 int numParam = locInfo1.getMapParamIdxToInferLoc().keySet().size();
2229 // add location types of paramters
2230 for (int idx = 0; idx < numParam; idx++) {
2231 list1.add(paramMap1.get(Integer.valueOf(idx)));
2232 list2.add(paramMap2.get(Integer.valueOf(idx)));
2235 // add program counter location
2236 list1.add(locInfo1.getPCLoc());
2237 list2.add(locInfo2.getPCLoc());
2239 if (!md1.getReturnType().isVoid()) {
2240 // add return value location
2241 CompositeLocation rtrLoc1 = getMethodLocationInfo(md1).getReturnLoc();
2242 CompositeLocation rtrLoc2 = getMethodLocationInfo(md2).getReturnLoc();
2247 // add global location type
2248 if (md1.isStatic()) {
2249 CompositeLocation globalLoc1 =
2250 new CompositeLocation(new Location(md1, locInfo1.getGlobalLocName()));
2251 CompositeLocation globalLoc2 =
2252 new CompositeLocation(new Location(md2, locInfo2.getGlobalLocName()));
2253 list1.add(globalLoc1);
2254 list2.add(globalLoc2);
2257 for (int i = 0; i < list1.size(); i++) {
2258 CompositeLocation locA1 = list1.get(i);
2259 CompositeLocation locA2 = list2.get(i);
2260 for (int k = 0; k < list1.size(); k++) {
2262 CompositeLocation locB1 = list1.get(k);
2263 CompositeLocation locB2 = list2.get(k);
2264 boolean r1 = isGreaterThan(getLattice(md1), locA1, locB1);
2266 boolean r2 = isGreaterThan(getLattice(md1), locA2, locB2);
2269 throw new Error("The method " + md1 + " is not consistent with the method " + md2
2270 + ".:: They have a different ordering relation between locations (" + locA1 + ","
2271 + locB1 + ") and (" + locA2 + "," + locB2 + ").");
2279 private String getSymbol(int idx, FlowNode node) {
2280 Descriptor desc = node.getDescTuple().get(idx);
2281 return desc.getSymbol();
2284 private Descriptor getDescriptor(int idx, FlowNode node) {
2285 Descriptor desc = node.getDescTuple().get(idx);
2289 private void calculateExtraLocations(MethodDescriptor md) {
2290 // calcualte pcloc, returnloc,...
2292 System.out.println("\nSSJAVA:Calculate extra locations: " + md);
2294 SSJavaLattice<String> methodLattice = getMethodLattice(md);
2296 MethodSummary methodSummary = getMethodSummary(md);
2298 FlowGraph fg = getFlowGraph(md);
2299 Set<FlowNode> nodeSet = fg.getNodeSet();
2301 // for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
2302 // FlowNode flowNode = (FlowNode) iterator.next();
2303 // if (flowNode.isDeclaratonNode()) {
2304 // CompositeLocation inferLoc = methodInfo.getInferLocation(flowNode.getDescTuple().get(0));
2305 // String locIdentifier = inferLoc.get(0).getLocIdentifier();
2306 // if (!methodLattice.containsKey(locIdentifier)) {
2307 // methodLattice.put(locIdentifier);
2311 MethodLocationInfo methodInfo = getMethodLocationInfo(md);
2313 Map<Integer, CompositeLocation> mapParamToLoc = methodSummary.getMapParamIdxToInferLoc();
2314 Set<Integer> paramIdxSet = mapParamToLoc.keySet();
2316 if (!ssjava.getMethodContainingSSJavaLoop().equals(md)) {
2317 // calculate the initial program counter location
2318 // PC location is higher than location types of parameters which has incoming flows.
2319 String pcLocSymbol = "PCLOC";
2321 Set<NTuple<Location>> paramLocTupleHavingInFlowSet = new HashSet<NTuple<Location>>();
2323 int numParams = fg.getNumParameters();
2324 for (int i = 0; i < numParams; i++) {
2325 FlowNode paramFlowNode = fg.getParamFlowNode(i);
2327 Descriptor prefix = paramFlowNode.getDescTuple().get(0);
2329 // if (fg.getIncomingFlowNodeSet(paramFlowNode).size() > 0) {
2330 if (fg.getIncomingNodeSetByPrefix(prefix).size() > 0) {
2331 // parameter has in-value flows
2332 NTuple<Descriptor> paramDescTuple = paramFlowNode.getCurrentDescTuple();
2333 NTuple<Location> paramLocTuple = translateToLocTuple(md, paramDescTuple);
2335 paramLocTupleHavingInFlowSet.add(paramLocTuple);
2336 // CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
2337 // paramInFlowSet.add(inferLoc);
2341 System.out.println("paramLocTupleHavingInFlowSet=" + paramLocTupleHavingInFlowSet);
2343 int numParamsWithIncomingValue = paramLocTupleHavingInFlowSet.size();
2345 if (paramLocTupleHavingInFlowSet.size() > 0
2346 && numParamsWithIncomingValue == fg.getNumParameters()) {
2347 // If the PC loc is going to be higher than all paramters, we dont' need to do anything
2349 // Generates a location in the method lattice that is higher than the
2350 // paramLocTupleHavingInFlowSet
2351 NTuple<Location> pcLocTuple = generateLocTupleHigherThan(md, paramLocTupleHavingInFlowSet);
2353 int pcLocTupleIdx = pcLocTuple.size() - 1;
2354 Location pcLoc = pcLocTuple.get(pcLocTupleIdx);
2355 Descriptor pcDesc = pcLoc.getLocDescriptor();
2356 Descriptor enclosingDesc = pcLocTuple.get(pcLocTupleIdx).getDescriptor();
2358 HierarchyGraph hierarchyGraph = getHierarchyGraph(enclosingDesc);
2359 HNode pcNode = hierarchyGraph.getHNode(pcDesc);
2360 pcNode.setSkeleton(true);
2362 for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
2363 NTuple<Location> paramLocTuple = (NTuple<Location>) iterator.next();
2364 Descriptor lowerDesc = paramLocTuple.get(pcLocTupleIdx).getLocDescriptor();
2365 hierarchyGraph.addEdge(pcDesc, lowerDesc);
2372 // calculate a return location
2373 // the return location type is lower than all parameters and location
2374 // types of return values
2375 if (!md.getReturnType().isVoid()) {
2376 // first, generate the set of return value location types that starts
2377 // with 'this' reference
2379 Set<CompositeLocation> inferFieldReturnLocSet = new HashSet<CompositeLocation>();
2381 Set<FlowNode> paramFlowNodeFlowingToReturnValueSet = getParamNodeFlowingToReturnValue(md);
2382 Set<CompositeLocation> inferParamLocSet = new HashSet<CompositeLocation>();
2383 for (Iterator iterator = paramFlowNodeFlowingToReturnValueSet.iterator(); iterator.hasNext();) {
2384 FlowNode fn = (FlowNode) iterator.next();
2385 CompositeLocation inferLoc =
2386 generateInferredCompositeLocation(methodInfo, getFlowGraph(md).getLocationTuple(fn));
2387 inferParamLocSet.add(inferLoc);
2390 Set<FlowNode> returnNodeSet = fg.getReturnNodeSet();
2392 skip: for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2393 FlowNode returnNode = (FlowNode) iterator.next();
2394 CompositeLocation inferReturnLoc =
2395 generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
2396 if (inferReturnLoc.get(0).getLocIdentifier().equals("this")) {
2397 // if the location type of the return value matches "this" reference
2398 // then, check whether this return value is equal to/lower than all
2399 // of parameters that possibly flow into the return values
2400 for (Iterator iterator2 = inferParamLocSet.iterator(); iterator2.hasNext();) {
2401 CompositeLocation paramInferLoc = (CompositeLocation) iterator2.next();
2403 if ((!paramInferLoc.equals(inferReturnLoc))
2404 && !isGreaterThan(methodLattice, paramInferLoc, inferReturnLoc)) {
2408 inferFieldReturnLocSet.add(inferReturnLoc);
2413 if (inferFieldReturnLocSet.size() > 0) {
2415 CompositeLocation returnLoc = getLowest(methodLattice, inferFieldReturnLocSet);
2416 if (returnLoc == null) {
2417 // in this case, assign <'this',bottom> to the RETURNLOC
2418 returnLoc = new CompositeLocation(new Location(md, md.getThis().getSymbol()));
2419 returnLoc.addLocation(new Location(md.getClassDesc(), getLattice(md.getClassDesc())
2422 methodInfo.setReturnLoc(returnLoc);
2425 String returnLocSymbol = "RETURNLOC";
2426 CompositeLocation returnLocInferLoc =
2427 new CompositeLocation(new Location(md, returnLocSymbol));
2428 methodInfo.setReturnLoc(returnLocInferLoc);
2430 for (Iterator iterator = paramIdxSet.iterator(); iterator.hasNext();) {
2431 Integer paramIdx = (Integer) iterator.next();
2432 CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
2433 String paramLocLocalSymbol = inferLoc.get(0).getLocIdentifier();
2434 if (!methodLattice.isGreaterThan(paramLocLocalSymbol, returnLocSymbol)) {
2436 // addRelationHigherToLower(methodLattice, methodInfo,
2437 // paramLocLocalSymbol,
2438 // returnLocSymbol);
2442 for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2443 FlowNode returnNode = (FlowNode) iterator.next();
2444 CompositeLocation inferLoc =
2445 generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
2446 if (!isGreaterThan(methodLattice, inferLoc, returnLocInferLoc)) {
2448 // addRelation(methodLattice, methodInfo, inferLoc,
2449 // returnLocInferLoc);
2458 private NTuple<Location> generateLocTupleHigherThan(MethodDescriptor md,
2459 Set<NTuple<Location>> paramLocTupleHavingInFlowSet) {
2461 System.out.println("-generateLocTupleHigherThan=" + paramLocTupleHavingInFlowSet);
2463 NTuple<Location> higherLocTuple = new NTuple<Location>();
2465 VarDescriptor thisVarDesc = md.getThis();
2466 // check if all paramter loc tuple is started with 'this' reference
2467 boolean hasParamNotStartedWithThisRef = false;
2471 Set<NTuple<Location>> paramLocTupleStartedWithThis = new HashSet<NTuple<Location>>();
2473 for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
2474 NTuple<Location> paramLocTuple = (NTuple<Location>) iterator.next();
2475 if (!paramLocTuple.get(0).getLocDescriptor().equals(thisVarDesc)) {
2476 hasParamNotStartedWithThisRef = true;
2477 } else if (paramLocTuple.size() > 1) {
2478 paramLocTupleStartedWithThis.add(paramLocTuple);
2479 if (maxSize < paramLocTuple.size()) {
2480 maxSize = paramLocTuple.size();
2485 Descriptor enclosingDesc = md;
2486 if (hasParamNotStartedWithThisRef) {
2487 // in this case, PCLOC will be the local location
2489 // all parameter is started with 'this', so PCLOC will be set relative to the composite
2490 // location started with 'this'.
2491 for (int idx = 0; idx < maxSize - 1; idx++) {
2492 Set<Descriptor> locDescSet = new HashSet<Descriptor>();
2493 Location curLoc = null;
2494 for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
2495 NTuple<Location> paramLocTuple = (NTuple<Location>) iterator.next();
2496 curLoc = paramLocTuple.get(idx);
2497 Descriptor locDesc = curLoc.getLocDescriptor();
2498 locDescSet.add(locDesc);
2500 System.out.println("locDescSet=" + locDescSet + " idx=" + idx);
2501 if (locDescSet.size() != 1) {
2504 Location newLocElement = new Location(curLoc.getDescriptor(), curLoc.getLocDescriptor());
2505 higherLocTuple.add(newLocElement);
2506 enclosingDesc = getClassTypeDescriptor(curLoc.getLocDescriptor());
2511 String pcLocIdentifier = PCLOC + (locSeed++);
2512 NameDescriptor pcLocDesc = new NameDescriptor(pcLocIdentifier);
2513 Location newLoc = new Location(enclosingDesc, pcLocDesc);
2514 higherLocTuple.add(newLoc);
2516 System.out.println("---higherLocTuple=" + higherLocTuple);
2518 return higherLocTuple;
2522 public ClassDescriptor getClassTypeDescriptor(Descriptor in) {
2524 if (in instanceof VarDescriptor) {
2525 return ((VarDescriptor) in).getType().getClassDesc();
2526 } else {/* if (desc instanceof FieldDescriptor) { */
2527 return ((FieldDescriptor) in).getType().getClassDesc();
2532 private Set<NTuple<Location>> calculateHighestLocTupleSet(
2533 Set<NTuple<Location>> paramLocTupleHavingInFlowSet) {
2535 Set<NTuple<Location>> highestSet = new HashSet<NTuple<Location>>();
2537 Iterator<NTuple<Location>> iterator = paramLocTupleHavingInFlowSet.iterator();
2538 NTuple<Location> highest = iterator.next();
2540 for (; iterator.hasNext();) {
2541 NTuple<Location> curLocTuple = (NTuple<Location>) iterator.next();
2542 if (isHigherThan(curLocTuple, highest)) {
2543 System.out.println(curLocTuple + " is greater than " + highest);
2544 highest = curLocTuple;
2548 highestSet.add(highest);
2550 MethodDescriptor md = (MethodDescriptor) highest.get(0).getDescriptor();
2551 VarDescriptor thisVarDesc = md.getThis();
2553 System.out.println("highest=" + highest);
2555 for (Iterator<NTuple<Location>> iter = paramLocTupleHavingInFlowSet.iterator(); iter.hasNext();) {
2556 NTuple<Location> curLocTuple = iter.next();
2558 if (!curLocTuple.equals(highest) && !hasOrderingRelation(highest, curLocTuple)) {
2560 System.out.println("add it to the highest set=" + curLocTuple);
2561 highestSet.add(curLocTuple);
2570 private void calculateExtraLocations2(MethodDescriptor md) {
2571 // calcualte pcloc, returnloc,...
2573 SSJavaLattice<String> methodLattice = getMethodLattice(md);
2574 MethodLocationInfo methodInfo = getMethodLocationInfo(md);
2575 FlowGraph fg = getFlowGraph(md);
2576 Set<FlowNode> nodeSet = fg.getNodeSet();
2578 for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
2579 FlowNode flowNode = (FlowNode) iterator.next();
2580 if (flowNode.isDeclaratonNode()) {
2581 CompositeLocation inferLoc = methodInfo.getInferLocation(flowNode.getDescTuple().get(0));
2582 String locIdentifier = inferLoc.get(0).getLocIdentifier();
2583 if (!methodLattice.containsKey(locIdentifier)) {
2584 methodLattice.put(locIdentifier);
2590 Map<Integer, CompositeLocation> mapParamToLoc = methodInfo.getMapParamIdxToInferLoc();
2591 Set<Integer> paramIdxSet = mapParamToLoc.keySet();
2593 if (!ssjava.getMethodContainingSSJavaLoop().equals(md)) {
2594 // calculate the initial program counter location
2595 // PC location is higher than location types of all parameters
2596 String pcLocSymbol = "PCLOC";
2598 Set<CompositeLocation> paramInFlowSet = new HashSet<CompositeLocation>();
2600 for (Iterator iterator = paramIdxSet.iterator(); iterator.hasNext();) {
2601 Integer paramIdx = (Integer) iterator.next();
2603 FlowNode paramFlowNode = fg.getParamFlowNode(paramIdx);
2605 if (fg.getIncomingFlowNodeSet(paramFlowNode).size() > 0) {
2606 // parameter has in-value flows
2607 CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
2608 paramInFlowSet.add(inferLoc);
2612 if (paramInFlowSet.size() > 0) {
2613 CompositeLocation lowestLoc = getLowest(methodLattice, paramInFlowSet);
2614 assert (lowestLoc != null);
2615 methodInfo.setPCLoc(lowestLoc);
2620 // calculate a return location
2621 // the return location type is lower than all parameters and location
2624 if (!md.getReturnType().isVoid()) {
2625 // first, generate the set of return value location types that starts
2629 Set<CompositeLocation> inferFieldReturnLocSet = new HashSet<CompositeLocation>();
2631 Set<FlowNode> paramFlowNode = getParamNodeFlowingToReturnValue(md);
2632 Set<CompositeLocation> inferParamLocSet = new HashSet<CompositeLocation>();
2633 if (paramFlowNode != null) {
2634 for (Iterator iterator = paramFlowNode.iterator(); iterator.hasNext();) {
2635 FlowNode fn = (FlowNode) iterator.next();
2636 CompositeLocation inferLoc =
2637 generateInferredCompositeLocation(methodInfo, getFlowGraph(md).getLocationTuple(fn));
2638 inferParamLocSet.add(inferLoc);
2642 Set<FlowNode> returnNodeSet = fg.getReturnNodeSet();
2644 skip: for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2645 FlowNode returnNode = (FlowNode) iterator.next();
2646 CompositeLocation inferReturnLoc =
2647 generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
2648 if (inferReturnLoc.get(0).getLocIdentifier().equals("this")) {
2649 // if the location type of the return value matches "this" reference
2650 // then, check whether this return value is equal to/lower than all
2652 // parameters that possibly flow into the return values
2653 for (Iterator iterator2 = inferParamLocSet.iterator(); iterator2.hasNext();) {
2654 CompositeLocation paramInferLoc = (CompositeLocation) iterator2.next();
2656 if ((!paramInferLoc.equals(inferReturnLoc))
2657 && !isGreaterThan(methodLattice, paramInferLoc, inferReturnLoc)) {
2661 inferFieldReturnLocSet.add(inferReturnLoc);
2666 if (inferFieldReturnLocSet.size() > 0) {
2668 CompositeLocation returnLoc = getLowest(methodLattice, inferFieldReturnLocSet);
2669 if (returnLoc == null) {
2670 // in this case, assign <'this',bottom> to the RETURNLOC
2671 returnLoc = new CompositeLocation(new Location(md, md.getThis().getSymbol()));
2672 returnLoc.addLocation(new Location(md.getClassDesc(), getLattice(md.getClassDesc())
2675 methodInfo.setReturnLoc(returnLoc);
2678 String returnLocSymbol = "RETURNLOC";
2679 CompositeLocation returnLocInferLoc =
2680 new CompositeLocation(new Location(md, returnLocSymbol));
2681 methodInfo.setReturnLoc(returnLocInferLoc);
2683 for (Iterator iterator = paramIdxSet.iterator(); iterator.hasNext();) {
2684 Integer paramIdx = (Integer) iterator.next();
2685 CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
2686 String paramLocLocalSymbol = inferLoc.get(0).getLocIdentifier();
2687 if (!methodLattice.isGreaterThan(paramLocLocalSymbol, returnLocSymbol)) {
2689 // addRelationHigherToLower(methodLattice, methodInfo,
2690 // paramLocLocalSymbol,
2691 // returnLocSymbol);
2695 for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
2696 FlowNode returnNode = (FlowNode) iterator.next();
2697 CompositeLocation inferLoc =
2698 generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
2699 if (!isGreaterThan(methodLattice, inferLoc, returnLocInferLoc)) {
2701 // addRelation(methodLattice, methodInfo, inferLoc,
2702 // returnLocInferLoc);
2711 private Set<String> getHigherLocSymbolThan(SSJavaLattice<String> lattice, String loc) {
2712 Set<String> higherLocSet = new HashSet<String>();
2714 Set<String> locSet = lattice.getTable().keySet();
2715 for (Iterator iterator = locSet.iterator(); iterator.hasNext();) {
2716 String element = (String) iterator.next();
2717 if (lattice.isGreaterThan(element, loc) && (!element.equals(lattice.getTopItem()))) {
2718 higherLocSet.add(element);
2721 return higherLocSet;
2724 private CompositeLocation getLowest(SSJavaLattice<String> methodLattice,
2725 Set<CompositeLocation> set) {
2727 CompositeLocation lowest = set.iterator().next();
2729 if (set.size() == 1) {
2733 for (Iterator iterator = set.iterator(); iterator.hasNext();) {
2734 CompositeLocation loc = (CompositeLocation) iterator.next();
2736 if ((!loc.equals(lowest)) && (!isComparable(methodLattice, lowest, loc))) {
2737 // if there is a case where composite locations are incomparable, just
2742 if ((!loc.equals(lowest)) && isGreaterThan(methodLattice, lowest, loc)) {
2749 private boolean isComparable(SSJavaLattice<String> methodLattice, CompositeLocation comp1,
2750 CompositeLocation comp2) {
2752 int size = comp1.getSize() >= comp2.getSize() ? comp2.getSize() : comp1.getSize();
2754 for (int idx = 0; idx < size; idx++) {
2755 Location loc1 = comp1.get(idx);
2756 Location loc2 = comp2.get(idx);
2758 Descriptor desc1 = loc1.getDescriptor();
2759 Descriptor desc2 = loc2.getDescriptor();
2761 if (!desc1.equals(desc2)) {
2762 throw new Error("Fail to compare " + comp1 + " and " + comp2);
2765 String symbol1 = loc1.getLocIdentifier();
2766 String symbol2 = loc2.getLocIdentifier();
2768 SSJavaLattice<String> lattice;
2770 lattice = methodLattice;
2772 lattice = getLattice(desc1);
2775 if (symbol1.equals(symbol2)) {
2777 } else if (!lattice.isComparable(symbol1, symbol2)) {
2786 private boolean isGreaterThan(SSJavaLattice<String> methodLattice, CompositeLocation comp1,
2787 CompositeLocation comp2) {
2789 int size = comp1.getSize() >= comp2.getSize() ? comp2.getSize() : comp1.getSize();
2791 for (int idx = 0; idx < size; idx++) {
2792 Location loc1 = comp1.get(idx);
2793 Location loc2 = comp2.get(idx);
2795 Descriptor desc1 = loc1.getDescriptor();
2796 Descriptor desc2 = loc2.getDescriptor();
2798 if (!desc1.equals(desc2)) {
2799 throw new Error("Fail to compare " + comp1 + " and " + comp2);
2802 String symbol1 = loc1.getLocIdentifier();
2803 String symbol2 = loc2.getLocIdentifier();
2805 SSJavaLattice<String> lattice;
2807 lattice = methodLattice;
2809 lattice = getLattice(desc1);
2812 if (symbol1.equals(symbol2)) {
2814 } else if (lattice.isGreaterThan(symbol1, symbol2)) {
2825 private void contributeCalleeFlows(MethodInvokeNode min, MethodDescriptor mdCaller,
2826 MethodDescriptor mdCallee) {
2828 System.out.println("\n##contributeCalleeFlows callee=" + mdCallee + "TO caller=" + mdCaller);
2830 getSubGlobalFlowGraph(mdCallee);
2834 private GlobalFlowGraph getSubGlobalFlowGraph(MethodDescriptor md) {
2835 return mapMethodDescriptorToSubGlobalFlowGraph.get(md);
2838 private void propagateFlowsToCallerWithNoCompositeLocation(MethodInvokeNode min,
2839 MethodDescriptor mdCaller, MethodDescriptor mdCallee) {
2841 System.out.println("\n##PROPAGATE callee=" + mdCallee + "TO caller=" + mdCaller);
2843 // if the parameter A reaches to the parameter B
2844 // then, add an edge the argument A -> the argument B to the caller's flow
2847 FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
2848 FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
2849 int numParam = calleeFlowGraph.getNumParameters();
2851 for (int i = 0; i < numParam; i++) {
2852 for (int k = 0; k < numParam; k++) {
2856 FlowNode paramNode1 = calleeFlowGraph.getParamFlowNode(i);
2857 FlowNode paramNode2 = calleeFlowGraph.getParamFlowNode(k);
2859 NTuple<Descriptor> arg1Tuple = getNodeTupleByArgIdx(min, i);
2860 NTuple<Descriptor> arg2Tuple = getNodeTupleByArgIdx(min, k);
2862 // check if the callee propagates an ordering constraints through
2865 Set<FlowNode> localReachSet = calleeFlowGraph.getLocalReachFlowNodeSetFrom(paramNode1);
2866 System.out.println("-param1=" + paramNode1 + " is higher than param2=" + paramNode2);
2867 System.out.println("-- localReachSet from param1=" + localReachSet);
2869 if (arg1Tuple.size() > 0 && arg2Tuple.size() > 0 && localReachSet.contains(paramNode2)) {
2870 // need to propagate an ordering relation s.t. arg1 is higher
2874 .println("-arg1Tuple=" + arg1Tuple + " is higher than arg2Tuple=" + arg2Tuple);
2876 // otherwise, flows between method/field locations...
2877 callerFlowGraph.addValueFlowEdge(arg1Tuple, arg2Tuple);
2878 System.out.println("arg1=" + arg1Tuple + " arg2=" + arg2Tuple);
2882 System.out.println();
2886 System.out.println("##\n");
2890 private void propagateFlowsToCaller(MethodInvokeNode min, MethodDescriptor mdCaller,
2891 MethodDescriptor mdCallee) {
2893 System.out.println("\n##PROPAGATE callee=" + mdCallee + "TO caller=" + mdCaller);
2895 // if the parameter A reaches to the parameter B
2896 // then, add an edge the argument A -> the argument B to the caller's flow
2900 // also if a parameter is a composite location and is started with "this"
2902 // need to make sure that the corresponding argument is higher than the
2903 // translated location of
2906 FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
2907 FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
2908 int numParam = calleeFlowGraph.getNumParameters();
2910 for (int i = 0; i < numParam; i++) {
2911 for (int k = 0; k < numParam; k++) {
2915 FlowNode paramNode1 = calleeFlowGraph.getParamFlowNode(i);
2916 FlowNode paramNode2 = calleeFlowGraph.getParamFlowNode(k);
2918 System.out.println("param1=" + paramNode1 + " curDescTuple="
2919 + paramNode1.getCurrentDescTuple());
2920 System.out.println("param2=" + paramNode2 + " curDescTuple="
2921 + paramNode2.getCurrentDescTuple());
2923 // TODO: deprecated method
2924 // NodeTupleSet tupleSetArg1 = getNodeTupleSetByArgIdx(min, i);
2925 // NodeTupleSet tupleSetArg2 = getNodeTupleSetByArgIdx(min, k);
2926 NodeTupleSet tupleSetArg1 = null;
2927 NodeTupleSet tupleSetArg2 = null;
2929 for (Iterator<NTuple<Descriptor>> iter1 = tupleSetArg1.iterator(); iter1.hasNext();) {
2930 NTuple<Descriptor> arg1Tuple = iter1.next();
2932 for (Iterator<NTuple<Descriptor>> iter2 = tupleSetArg2.iterator(); iter2.hasNext();) {
2933 NTuple<Descriptor> arg2Tuple = iter2.next();
2935 // check if the callee propagates an ordering constraints through
2938 Set<FlowNode> localReachSet =
2939 calleeFlowGraph.getLocalReachFlowNodeSetFrom(paramNode1);
2941 if (localReachSet.contains(paramNode2)) {
2942 // need to propagate an ordering relation s.t. arg1 is higher
2946 .println("-param1=" + paramNode1 + " is higher than param2=" + paramNode2);
2947 System.out.println("-arg1Tuple=" + arg1Tuple + " is higher than arg2Tuple="
2950 if (!min.getMethod().isStatic()) {
2951 // check if this is the case that values flow to/from the
2952 // current object reference 'this'
2954 NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
2955 Descriptor baseRef = baseTuple.get(baseTuple.size() - 1);
2957 System.out.println("paramNode1.getCurrentDescTuple()="
2958 + paramNode1.getCurrentDescTuple());
2959 // calculate the prefix of the argument
2961 if (arg2Tuple.size() == 1 && arg2Tuple.get(0).equals(baseRef)) {
2962 // in this case, the callee flow causes a caller flow to the
2963 // object whose method
2966 if (!paramNode1.getCurrentDescTuple().startsWith(mdCallee.getThis())) {
2967 // check whether ???
2969 NTuple<Descriptor> param1Prefix =
2970 calculatePrefixForParam(callerFlowGraph, calleeFlowGraph, min, arg1Tuple,
2973 if (param1Prefix != null && param1Prefix.startsWith(mdCallee.getThis())) {
2974 // in this case, we need to create a new edge
2975 // 'this.FIELD'->'this'
2976 // but we couldn't... instead we assign a new composite
2978 // with 'this' reference to the corresponding parameter
2980 CompositeLocation compLocForParam1 =
2981 generateCompositeLocation(mdCallee, param1Prefix);
2984 .println("set comp loc=" + compLocForParam1 + " to " + paramNode1);
2985 paramNode1.setCompositeLocation(compLocForParam1);
2987 // then, we need to make sure that the corresponding
2988 // argument in the caller
2989 // is required to be higher than or equal to the
2990 // translated parameter
2993 NTuple<Descriptor> translatedParamTuple =
2994 translateCompositeLocationToCaller(min, compLocForParam1);
2996 // TODO : check if the arg >= the tranlated parameter
2998 System.out.println("add a flow edge= " + arg1Tuple + "->"
2999 + translatedParamTuple);
3000 callerFlowGraph.addValueFlowEdge(arg1Tuple, translatedParamTuple);
3007 // param1 has already been assigned a composite location
3009 System.out.println("--param1 has already been assigned a composite location");
3010 CompositeLocation compLocForParam1 = paramNode1.getCompositeLocation();
3011 NTuple<Descriptor> translatedParamTuple =
3012 translateCompositeLocationToCaller(min, compLocForParam1);
3014 // TODO : check if the arg >= the tranlated parameter
3016 System.out.println("add a flow edge= " + arg1Tuple + "->"
3017 + translatedParamTuple);
3018 callerFlowGraph.addValueFlowEdge(arg1Tuple, translatedParamTuple);
3024 } else if (arg1Tuple.size() == 1 && arg1Tuple.get(0).equals(baseRef)) {
3025 // in this case, the callee flow causes a caller flow
3026 // originated from the object
3028 // method is invoked.
3030 System.out.println("###FROM CASE");
3032 if (!paramNode2.getCurrentDescTuple().startsWith(mdCallee.getThis())) {
3034 NTuple<Descriptor> param2Prefix =
3035 calculatePrefixForParam(callerFlowGraph, calleeFlowGraph, min, arg2Tuple,
3038 if (param2Prefix != null && param2Prefix.startsWith(mdCallee.getThis())) {
3039 // in this case, we need to create a new edge 'this' ->
3040 // 'this.FIELD' but we couldn't... instead we assign the
3042 // parameter a new composite location started with
3045 CompositeLocation compLocForParam2 =
3046 generateCompositeLocation(mdCallee, param2Prefix);
3048 // System.out.println("set comp loc=" + compLocForParam2
3050 // " to " + paramNode2);
3051 paramNode1.setCompositeLocation(compLocForParam2);
3059 // otherwise, flows between method/field locations...
3060 callerFlowGraph.addValueFlowEdge(arg1Tuple, arg2Tuple);
3061 System.out.println("arg1=" + arg1Tuple + " arg2=" + arg2Tuple);
3068 System.out.println();
3072 System.out.println("##\n");
3075 private NTuple<Descriptor> translateCompositeLocationToCaller(MethodInvokeNode min,
3076 CompositeLocation compLocForParam1) {
3077 NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
3079 NTuple<Descriptor> tuple = new NTuple<Descriptor>();
3081 for (int i = 0; i < baseTuple.size(); i++) {
3082 tuple.add(baseTuple.get(i));
3085 for (int i = 1; i < compLocForParam1.getSize(); i++) {
3086 Location loc = compLocForParam1.get(i);
3087 tuple.add(loc.getLocDescriptor());
3093 private CompositeLocation generateCompositeLocation(NTuple<Location> prefixLocTuple) {
3095 System.out.println("generateCompositeLocation=" + prefixLocTuple);
3097 CompositeLocation newCompLoc = new CompositeLocation();
3098 for (int i = 0; i < prefixLocTuple.size(); i++) {
3099 newCompLoc.addLocation(prefixLocTuple.get(i));
3102 Descriptor lastDescOfPrefix = prefixLocTuple.get(prefixLocTuple.size() - 1).getLocDescriptor();
3104 ClassDescriptor enclosingDescriptor;
3105 if (lastDescOfPrefix instanceof FieldDescriptor) {
3106 enclosingDescriptor = ((FieldDescriptor) lastDescOfPrefix).getType().getClassDesc();
3107 // System.out.println("enclosingDescriptor0=" + enclosingDescriptor);
3109 // var descriptor case
3110 enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
3112 // System.out.println("enclosingDescriptor=" + enclosingDescriptor);
3114 LocationDescriptor newLocDescriptor = generateNewLocationDescriptor();
3115 newLocDescriptor.setEnclosingClassDesc(enclosingDescriptor);
3117 Location newLoc = new Location(enclosingDescriptor, newLocDescriptor.getSymbol());
3118 newLoc.setLocDescriptor(newLocDescriptor);
3119 newCompLoc.addLocation(newLoc);
3121 // System.out.println("--newCompLoc=" + newCompLoc);
3125 private CompositeLocation generateCompositeLocation(MethodDescriptor md,
3126 NTuple<Descriptor> paramPrefix) {
3128 System.out.println("generateCompositeLocation=" + paramPrefix);
3130 CompositeLocation newCompLoc = convertToCompositeLocation(md, paramPrefix);
3132 Descriptor lastDescOfPrefix = paramPrefix.get(paramPrefix.size() - 1);
3133 // System.out.println("lastDescOfPrefix=" + lastDescOfPrefix + " kind="
3134 // + lastDescOfPrefix.getClass());
3135 ClassDescriptor enclosingDescriptor;
3136 if (lastDescOfPrefix instanceof FieldDescriptor) {
3137 enclosingDescriptor = ((FieldDescriptor) lastDescOfPrefix).getType().getClassDesc();
3138 // System.out.println("enclosingDescriptor0=" + enclosingDescriptor);
3140 // var descriptor case
3141 enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
3143 // System.out.println("enclosingDescriptor=" + enclosingDescriptor);
3145 LocationDescriptor newLocDescriptor = generateNewLocationDescriptor();
3146 newLocDescriptor.setEnclosingClassDesc(enclosingDescriptor);
3148 Location newLoc = new Location(enclosingDescriptor, newLocDescriptor.getSymbol());
3149 newLoc.setLocDescriptor(newLocDescriptor);
3150 newCompLoc.addLocation(newLoc);
3152 // System.out.println("--newCompLoc=" + newCompLoc);
3156 private NTuple<Descriptor> calculatePrefixForParam(FlowGraph callerFlowGraph,
3157 FlowGraph calleeFlowGraph, MethodInvokeNode min, NTuple<Descriptor> arg1Tuple,
3158 FlowNode paramNode1) {
3160 NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
3161 Descriptor baseRef = baseTuple.get(baseTuple.size() - 1);
3162 System.out.println("baseRef=" + baseRef);
3164 FlowNode flowNodeArg1 = callerFlowGraph.getFlowNode(arg1Tuple);
3165 List<NTuple<Descriptor>> callerPrefixList = calculatePrefixList(callerFlowGraph, flowNodeArg1);
3166 System.out.println("callerPrefixList=" + callerPrefixList);
3168 List<NTuple<Descriptor>> prefixList = calculatePrefixList(calleeFlowGraph, paramNode1);
3169 System.out.println("###prefixList from node=" + paramNode1 + " =" + prefixList);
3171 List<NTuple<Descriptor>> calleePrefixList =
3172 translatePrefixListToCallee(baseRef, min.getMethod(), callerPrefixList);
3174 System.out.println("calleePrefixList=" + calleePrefixList);
3176 Set<FlowNode> reachNodeSetFromParam1 = calleeFlowGraph.getReachFlowNodeSetFrom(paramNode1);
3177 System.out.println("reachNodeSetFromParam1=" + reachNodeSetFromParam1);
3179 for (int i = 0; i < calleePrefixList.size(); i++) {
3180 NTuple<Descriptor> curPrefix = calleePrefixList.get(i);
3181 Set<NTuple<Descriptor>> reachableCommonPrefixSet = new HashSet<NTuple<Descriptor>>();
3183 for (Iterator iterator2 = reachNodeSetFromParam1.iterator(); iterator2.hasNext();) {
3184 FlowNode reachNode = (FlowNode) iterator2.next();
3185 if (reachNode.getCurrentDescTuple().startsWith(curPrefix)) {
3186 reachableCommonPrefixSet.add(reachNode.getCurrentDescTuple());
3190 if (!reachableCommonPrefixSet.isEmpty()) {
3191 System.out.println("###REACHABLECOMONPREFIX=" + reachableCommonPrefixSet
3192 + " with curPreFix=" + curPrefix);
3201 private List<NTuple<Descriptor>> translatePrefixListToCallee(Descriptor baseRef,
3202 MethodDescriptor mdCallee, List<NTuple<Descriptor>> callerPrefixList) {
3204 List<NTuple<Descriptor>> calleePrefixList = new ArrayList<NTuple<Descriptor>>();
3206 for (int i = 0; i < callerPrefixList.size(); i++) {
3207 NTuple<Descriptor> prefix = callerPrefixList.get(i);
3208 if (prefix.startsWith(baseRef)) {
3209 NTuple<Descriptor> calleePrefix = new NTuple<Descriptor>();
3210 calleePrefix.add(mdCallee.getThis());
3211 for (int k = 1; k < prefix.size(); k++) {
3212 calleePrefix.add(prefix.get(k));
3214 calleePrefixList.add(calleePrefix);
3218 return calleePrefixList;
3222 private List<NTuple<Descriptor>> calculatePrefixList(FlowGraph flowGraph, FlowNode flowNode) {
3224 System.out.println("\n##### calculatePrefixList=" + flowNode);
3226 Set<FlowNode> inNodeSet = flowGraph.getIncomingFlowNodeSet(flowNode);
3227 inNodeSet.add(flowNode);
3229 System.out.println("inNodeSet=" + inNodeSet);
3231 List<NTuple<Descriptor>> prefixList = new ArrayList<NTuple<Descriptor>>();
3233 for (Iterator iterator = inNodeSet.iterator(); iterator.hasNext();) {
3234 FlowNode inNode = (FlowNode) iterator.next();
3236 NTuple<Descriptor> inNodeTuple = inNode.getCurrentDescTuple();
3238 // CompositeLocation inNodeInferredLoc =
3239 // generateInferredCompositeLocation(methodInfo, inNodeTuple);
3240 // NTuple<Location> inNodeInferredLocTuple = inNodeInferredLoc.getTuple();
3242 for (int i = 1; i < inNodeTuple.size(); i++) {
3243 NTuple<Descriptor> prefix = inNodeTuple.subList(0, i);
3244 if (!prefixList.contains(prefix)) {
3245 prefixList.add(prefix);
3250 Collections.sort(prefixList, new Comparator<NTuple<Descriptor>>() {
3251 public int compare(NTuple<Descriptor> arg0, NTuple<Descriptor> arg1) {
3252 int s0 = arg0.size();
3253 int s1 = arg1.size();
3256 } else if (s0 == s1) {
3268 public CompositeLocation convertToCompositeLocation(MethodDescriptor md, NTuple<Descriptor> tuple) {
3270 CompositeLocation compLoc = new CompositeLocation();
3272 Descriptor enclosingDescriptor = md;
3274 for (int i = 0; i < tuple.size(); i++) {
3275 Descriptor curDescriptor = tuple.get(i);
3276 Location locElement = new Location(enclosingDescriptor, curDescriptor.getSymbol());
3277 locElement.setLocDescriptor(curDescriptor);
3278 compLoc.addLocation(locElement);
3280 if (curDescriptor instanceof VarDescriptor) {
3281 enclosingDescriptor = md.getClassDesc();
3282 } else if (curDescriptor instanceof NameDescriptor) {
3283 // it is "GLOBAL LOC" case!
3284 enclosingDescriptor = GLOBALDESC;
3285 } else if (curDescriptor instanceof InterDescriptor) {
3286 enclosingDescriptor = null;
3288 enclosingDescriptor = ((FieldDescriptor) curDescriptor).getClassDescriptor();
3296 private LocationDescriptor generateNewLocationDescriptor() {
3297 return new LocationDescriptor("Loc" + (locSeed++));
3300 private int getPrefixIndex(NTuple<Descriptor> tuple1, NTuple<Descriptor> tuple2) {
3302 // return the index where the prefix shared by tuple1 and tuple2 is ended
3303 // if there is no prefix shared by both of them, return -1
3305 int minSize = tuple1.size();
3306 if (minSize > tuple2.size()) {
3307 minSize = tuple2.size();
3311 for (int i = 0; i < minSize; i++) {
3312 if (!tuple1.get(i).equals(tuple2.get(i))) {
3322 private CompositeLocation generateInferredCompositeLocation(MethodLocationInfo methodInfo,
3323 NTuple<Location> tuple) {
3325 // first, retrieve inferred location by the local var descriptor
3326 CompositeLocation inferLoc = new CompositeLocation();
3328 CompositeLocation localVarInferLoc =
3329 methodInfo.getInferLocation(tuple.get(0).getLocDescriptor());
3331 localVarInferLoc.get(0).setLocDescriptor(tuple.get(0).getLocDescriptor());
3333 for (int i = 0; i < localVarInferLoc.getSize(); i++) {
3334 inferLoc.addLocation(localVarInferLoc.get(i));
3337 for (int i = 1; i < tuple.size(); i++) {
3338 Location cur = tuple.get(i);
3339 Descriptor enclosingDesc = cur.getDescriptor();
3340 Descriptor curDesc = cur.getLocDescriptor();
3342 Location inferLocElement;
3343 if (curDesc == null) {
3344 // in this case, we have a newly generated location.
3345 inferLocElement = new Location(enclosingDesc, cur.getLocIdentifier());
3347 String fieldLocSymbol =
3348 getLocationInfo(enclosingDesc).getInferLocation(curDesc).get(0).getLocIdentifier();
3349 inferLocElement = new Location(enclosingDesc, fieldLocSymbol);
3350 inferLocElement.setLocDescriptor(curDesc);
3353 inferLoc.addLocation(inferLocElement);
3357 assert (inferLoc.get(0).getLocDescriptor().getSymbol() == inferLoc.get(0).getLocIdentifier());
3361 public LocationInfo getLocationInfo(Descriptor d) {
3362 if (d instanceof MethodDescriptor) {
3363 return getMethodLocationInfo((MethodDescriptor) d);
3365 return getFieldLocationInfo((ClassDescriptor) d);
3369 private MethodLocationInfo getMethodLocationInfo(MethodDescriptor md) {
3371 if (!mapMethodDescToMethodLocationInfo.containsKey(md)) {
3372 mapMethodDescToMethodLocationInfo.put(md, new MethodLocationInfo(md));
3375 return mapMethodDescToMethodLocationInfo.get(md);
3379 private LocationInfo getFieldLocationInfo(ClassDescriptor cd) {
3381 if (!mapClassToLocationInfo.containsKey(cd)) {
3382 mapClassToLocationInfo.put(cd, new LocationInfo(cd));
3385 return mapClassToLocationInfo.get(cd);
3389 private void addPrefixMapping(Map<NTuple<Location>, Set<NTuple<Location>>> map,
3390 NTuple<Location> prefix, NTuple<Location> element) {
3392 if (!map.containsKey(prefix)) {
3393 map.put(prefix, new HashSet<NTuple<Location>>());
3395 map.get(prefix).add(element);
3398 private boolean containsNonPrimitiveElement(Set<Descriptor> descSet) {
3399 for (Iterator iterator = descSet.iterator(); iterator.hasNext();) {
3400 Descriptor desc = (Descriptor) iterator.next();
3402 if (desc.equals(LocationInference.GLOBALDESC)) {
3404 } else if (desc instanceof VarDescriptor) {
3405 if (!((VarDescriptor) desc).getType().isPrimitive()) {
3408 } else if (desc instanceof FieldDescriptor) {
3409 if (!((FieldDescriptor) desc).getType().isPrimitive()) {
3418 private SSJavaLattice<String> getLattice(Descriptor d) {
3419 if (d instanceof MethodDescriptor) {
3420 return getMethodLattice((MethodDescriptor) d);
3422 return getFieldLattice((ClassDescriptor) d);
3426 private SSJavaLattice<String> getMethodLattice(MethodDescriptor md) {
3427 if (!md2lattice.containsKey(md)) {
3428 md2lattice.put(md, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
3430 return md2lattice.get(md);
3433 private void setMethodLattice(MethodDescriptor md, SSJavaLattice<String> lattice) {
3434 md2lattice.put(md, lattice);
3437 private void extractFlowsBetweenFields(ClassDescriptor cd, FlowNode srcNode, FlowNode dstNode,
3440 NTuple<Descriptor> srcCurTuple = srcNode.getCurrentDescTuple();
3441 NTuple<Descriptor> dstCurTuple = dstNode.getCurrentDescTuple();
3443 if (srcCurTuple.get(idx).equals(dstCurTuple.get(idx)) && srcCurTuple.size() > (idx + 1)
3444 && dstCurTuple.size() > (idx + 1)) {
3445 // value flow between fields: we don't need to add a binary relation
3448 Descriptor desc = srcCurTuple.get(idx);
3449 ClassDescriptor classDesc;
3452 classDesc = ((VarDescriptor) desc).getType().getClassDesc();
3454 if (desc instanceof FieldDescriptor) {
3455 classDesc = ((FieldDescriptor) desc).getType().getClassDesc();
3457 // this case is that the local variable has a composite location assignment
3458 // the following element after the composite location to the local variable
3459 // has the enclosing descriptor of the local variable
3460 Descriptor localDesc = srcNode.getDescTuple().get(0);
3461 classDesc = ((VarDescriptor) localDesc).getType().getClassDesc();
3464 extractFlowsBetweenFields(classDesc, srcNode, dstNode, idx + 1);
3468 Descriptor srcFieldDesc = srcCurTuple.get(idx);
3469 Descriptor dstFieldDesc = dstCurTuple.get(idx);
3472 getHierarchyGraph(cd).addEdge(srcFieldDesc, dstFieldDesc);
3478 public SSJavaLattice<String> getFieldLattice(ClassDescriptor cd) {
3479 if (!cd2lattice.containsKey(cd)) {
3480 cd2lattice.put(cd, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
3482 return cd2lattice.get(cd);
3485 public LinkedList<MethodDescriptor> computeMethodList() {
3487 Set<MethodDescriptor> toSort = new HashSet<MethodDescriptor>();
3491 Set<MethodDescriptor> visited = new HashSet<MethodDescriptor>();
3492 Set<MethodDescriptor> reachableCallee = new HashSet<MethodDescriptor>();
3494 while (!toAnalyzeIsEmpty()) {
3495 ClassDescriptor cd = toAnalyzeNext();
3497 setupToAnalazeMethod(cd);
3498 temp_toanalyzeMethodList.removeAll(visited);
3500 while (!toAnalyzeMethodIsEmpty()) {
3501 MethodDescriptor md = toAnalyzeMethodNext();
3502 if ((!visited.contains(md))
3503 && (ssjava.needTobeAnnotated(md) || reachableCallee.contains(md))) {
3505 // creates a mapping from a method descriptor to virtual methods
3506 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3507 if (md.isStatic()) {
3508 setPossibleCallees.add(md);
3510 setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
3513 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getCalleeSet(md);
3514 Set<MethodDescriptor> needToAnalyzeCalleeSet = new HashSet<MethodDescriptor>();
3516 for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
3517 MethodDescriptor calleemd = (MethodDescriptor) iterator.next();
3518 if ((!ssjava.isTrustMethod(calleemd))
3519 && (!ssjava.isSSJavaUtil(calleemd.getClassDesc()))) {
3520 if (!visited.contains(calleemd)) {
3521 temp_toanalyzeMethodList.add(calleemd);
3523 reachableCallee.add(calleemd);
3524 needToAnalyzeCalleeSet.add(calleemd);
3528 mapMethodToCalleeSet.put(md, needToAnalyzeCalleeSet);
3537 return ssjava.topologicalSort(toSort);
3541 public boolean isTransitivelyCalledFrom(MethodDescriptor callee, MethodDescriptor caller) {
3542 // if the callee is transitively invoked from the caller
3545 int callerIdx = toanalyze_methodDescList.indexOf(caller);
3546 int calleeIdx = toanalyze_methodDescList.indexOf(callee);
3548 if (callerIdx < calleeIdx) {
3556 public void constructFlowGraph() {
3558 System.out.println("");
3559 toanalyze_methodDescList = computeMethodList();
3561 LinkedList<MethodDescriptor> methodDescList =
3562 (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
3564 System.out.println("@@@methodDescList=" + methodDescList);
3567 while (!methodDescList.isEmpty()) {
3568 MethodDescriptor md = methodDescList.removeLast();
3569 if (state.SSJAVADEBUG) {
3570 System.out.println();
3571 System.out.println("SSJAVA: Constructing a flow graph: " + md);
3573 // creates a mapping from a parameter descriptor to its index
3574 Map<Descriptor, Integer> mapParamDescToIdx = new HashMap<Descriptor, Integer>();
3576 if (!md.isStatic()) {
3578 mapParamDescToIdx.put(md.getThis(), 0);
3581 for (int i = 0; i < md.numParameters(); i++) {
3582 Descriptor paramDesc = (Descriptor) md.getParameter(i);
3583 mapParamDescToIdx.put(paramDesc, new Integer(i + offset));
3586 FlowGraph fg = new FlowGraph(md, mapParamDescToIdx);
3587 mapMethodDescriptorToFlowGraph.put(md, fg);
3589 analyzeMethodBody(md.getClassDesc(), md);
3591 // System.out.println("##constructSubGlobalFlowGraph");
3592 // GlobalFlowGraph subGlobalFlowGraph = constructSubGlobalFlowGraph(fg);
3593 // mapMethodDescriptorToSubGlobalFlowGraph.put(md, subGlobalFlowGraph);
3596 // System.out.println("##addValueFlowsFromCalleeSubGlobalFlowGraph");
3597 // addValueFlowsFromCalleeSubGlobalFlowGraph(md, subGlobalFlowGraph);
3598 // subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
3600 // propagateFlowsFromCalleesWithNoCompositeLocation(md);
3604 // _debug_printGraph();
3606 methodDescList = (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
3608 while (!methodDescList.isEmpty()) {
3609 MethodDescriptor md = methodDescList.removeLast();
3610 if (state.SSJAVADEBUG) {
3611 System.out.println();
3612 System.out.println("SSJAVA: Constructing a flow graph2: " + md);
3614 System.out.println("##constructSubGlobalFlowGraph");
3615 GlobalFlowGraph subGlobalFlowGraph = constructSubGlobalFlowGraph(getFlowGraph(md));
3616 mapMethodDescriptorToSubGlobalFlowGraph.put(md, subGlobalFlowGraph);
3619 System.out.println("##addValueFlowsFromCalleeSubGlobalFlowGraph");
3620 addValueFlowsFromCalleeSubGlobalFlowGraph(md, subGlobalFlowGraph);
3621 subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
3623 propagateFlowsFromCalleesWithNoCompositeLocation(md);
3630 private Set<MethodInvokeNode> getMethodInvokeNodeSet(MethodDescriptor md) {
3631 if (!mapMethodDescriptorToMethodInvokeNodeSet.containsKey(md)) {
3632 mapMethodDescriptorToMethodInvokeNodeSet.put(md, new HashSet<MethodInvokeNode>());
3634 return mapMethodDescriptorToMethodInvokeNodeSet.get(md);
3637 private void constructSubGlobalFlowGraph(MethodDescriptor md) {
3639 FlowGraph flowGraph = getFlowGraph(md);
3641 Set<MethodInvokeNode> setMethodInvokeNode = getMethodInvokeNodeSet(md);
3643 for (Iterator<MethodInvokeNode> iter = setMethodInvokeNode.iterator(); iter.hasNext();) {
3644 MethodInvokeNode min = iter.next();
3645 propagateFlowsFromMethodInvokeNode(md, min);
3650 private void propagateFlowsFromMethodInvokeNode(MethodDescriptor mdCaller, MethodInvokeNode min) {
3651 // the transformation for a call site propagates flows through parameters
3652 // if the method is virtual, it also grab all relations from any possible
3655 MethodDescriptor mdCallee = min.getMethod();
3656 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3657 if (mdCallee.isStatic()) {
3658 setPossibleCallees.add(mdCallee);
3660 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
3661 // removes method descriptors that are not invoked by the caller
3662 calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
3663 setPossibleCallees.addAll(calleeSet);
3666 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
3667 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
3668 contributeCalleeFlows(min, mdCaller, possibleMdCallee);
3673 private void assignCompositeLocation(MethodDescriptor md) {
3675 FlowGraph flowGraph = getFlowGraph(md);
3677 Set<FlowNode> nodeSet = flowGraph.getNodeSet();
3679 next: for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
3680 FlowNode flowNode = (FlowNode) iterator.next();
3682 // assign a composite location only to the local variable
3683 if (flowNode.getCurrentDescTuple().size() == 1) {
3685 List<NTuple<Descriptor>> prefixList = calculatePrefixList(flowGraph, flowNode);
3686 Set<FlowNode> reachSet = flowGraph.getReachFlowNodeSetFrom(flowNode);
3688 for (int i = 0; i < prefixList.size(); i++) {
3689 NTuple<Descriptor> curPrefix = prefixList.get(i);
3690 Set<NTuple<Descriptor>> reachableCommonPrefixSet = new HashSet<NTuple<Descriptor>>();
3692 for (Iterator iterator2 = reachSet.iterator(); iterator2.hasNext();) {
3693 FlowNode reachNode = (FlowNode) iterator2.next();
3694 if (reachNode.getCurrentDescTuple().startsWith(curPrefix)) {
3695 reachableCommonPrefixSet.add(reachNode.getCurrentDescTuple());
3699 if (!reachableCommonPrefixSet.isEmpty()) {
3700 System.out.println("NEED TO ASSIGN COMP LOC TO " + flowNode + " with prefix="
3702 CompositeLocation newCompLoc = generateCompositeLocation(md, curPrefix);
3703 flowNode.setCompositeLocation(newCompLoc);
3714 private void propagateFlowsFromCalleesWithNoCompositeLocation(MethodDescriptor mdCaller) {
3716 // the transformation for a call site propagates flows through parameters
3717 // if the method is virtual, it also grab all relations from any possible
3720 Set<MethodInvokeNode> setMethodInvokeNode =
3721 mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
3723 if (setMethodInvokeNode != null) {
3725 for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
3726 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
3727 MethodDescriptor mdCallee = min.getMethod();
3728 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3729 if (mdCallee.isStatic()) {
3730 setPossibleCallees.add(mdCallee);
3732 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
3733 // removes method descriptors that are not invoked by the caller
3734 calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
3735 setPossibleCallees.addAll(calleeSet);
3738 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
3739 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
3740 propagateFlowsToCallerWithNoCompositeLocation(min, mdCaller, possibleMdCallee);
3748 private void propagateFlowsFromCallees(MethodDescriptor mdCaller) {
3750 // the transformation for a call site propagates flows through parameters
3751 // if the method is virtual, it also grab all relations from any possible
3754 Set<MethodInvokeNode> setMethodInvokeNode =
3755 mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
3757 if (setMethodInvokeNode != null) {
3759 for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
3760 MethodInvokeNode min = (MethodInvokeNode) iterator.next();
3761 MethodDescriptor mdCallee = min.getMethod();
3762 Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3763 if (mdCallee.isStatic()) {
3764 setPossibleCallees.add(mdCallee);
3766 Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
3767 // removes method descriptors that are not invoked by the caller
3768 calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
3769 setPossibleCallees.addAll(calleeSet);
3772 for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
3773 MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
3774 propagateFlowsToCaller(min, mdCaller, possibleMdCallee);
3782 private void analyzeMethodBody(ClassDescriptor cd, MethodDescriptor md) {
3783 BlockNode bn = state.getMethodBody(md);
3784 NodeTupleSet implicitFlowTupleSet = new NodeTupleSet();
3785 analyzeFlowBlockNode(md, md.getParameterTable(), bn, implicitFlowTupleSet);
3788 private void analyzeFlowBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn,
3789 NodeTupleSet implicitFlowTupleSet) {
3791 bn.getVarTable().setParent(nametable);
3792 for (int i = 0; i < bn.size(); i++) {
3793 BlockStatementNode bsn = bn.get(i);
3794 analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
3799 private void analyzeBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
3800 BlockStatementNode bsn, NodeTupleSet implicitFlowTupleSet) {
3802 switch (bsn.kind()) {
3803 case Kind.BlockExpressionNode:
3804 analyzeBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, implicitFlowTupleSet);
3807 case Kind.DeclarationNode:
3808 analyzeFlowDeclarationNode(md, nametable, (DeclarationNode) bsn, implicitFlowTupleSet);
3811 case Kind.IfStatementNode:
3812 analyzeFlowIfStatementNode(md, nametable, (IfStatementNode) bsn, implicitFlowTupleSet);
3816 analyzeFlowLoopNode(md, nametable, (LoopNode) bsn, implicitFlowTupleSet);
3819 case Kind.ReturnNode:
3820 analyzeFlowReturnNode(md, nametable, (ReturnNode) bsn, implicitFlowTupleSet);
3823 case Kind.SubBlockNode:
3824 analyzeFlowSubBlockNode(md, nametable, (SubBlockNode) bsn, implicitFlowTupleSet);
3827 case Kind.ContinueBreakNode:
3830 case Kind.SwitchStatementNode:
3831 analyzeSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, implicitFlowTupleSet);
3838 private void analyzeSwitchBlockNode(MethodDescriptor md, SymbolTable nametable,
3839 SwitchBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
3841 analyzeFlowBlockNode(md, nametable, sbn.getSwitchBlockStatement(), implicitFlowTupleSet);
3845 private void analyzeSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
3846 SwitchStatementNode ssn, NodeTupleSet implicitFlowTupleSet) {
3848 NodeTupleSet condTupleNode = new NodeTupleSet();
3849 analyzeFlowExpressionNode(md, nametable, ssn.getCondition(), condTupleNode, null,
3850 implicitFlowTupleSet, false);
3852 NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
3854 newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
3855 newImplicitTupleSet.addTupleSet(condTupleNode);
3857 if (newImplicitTupleSet.size() > 1) {
3858 // need to create an intermediate node for the GLB of conditional
3859 // locations & implicit flows
3860 NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
3861 for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter.hasNext();) {
3862 NTuple<Descriptor> tuple = idxIter.next();
3863 addFlowGraphEdge(md, tuple, interTuple);
3865 newImplicitTupleSet.clear();
3866 newImplicitTupleSet.addTuple(interTuple);
3869 BlockNode sbn = ssn.getSwitchBody();
3870 for (int i = 0; i < sbn.size(); i++) {
3871 analyzeSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), newImplicitTupleSet);
3876 private void analyzeFlowSubBlockNode(MethodDescriptor md, SymbolTable nametable,
3877 SubBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
3878 analyzeFlowBlockNode(md, nametable, sbn.getBlockNode(), implicitFlowTupleSet);
3881 private void analyzeFlowReturnNode(MethodDescriptor md, SymbolTable nametable, ReturnNode rn,
3882 NodeTupleSet implicitFlowTupleSet) {
3884 ExpressionNode returnExp = rn.getReturnExpression();
3886 if (returnExp != null) {
3887 NodeTupleSet nodeSet = new NodeTupleSet();
3888 // if a return expression returns a literal value, nodeSet is empty
3889 analyzeFlowExpressionNode(md, nametable, returnExp, nodeSet, false);
3890 FlowGraph fg = getFlowGraph(md);
3892 // if (implicitFlowTupleSet.size() == 1
3894 // fg.getFlowNode(implicitFlowTupleSet.iterator().next()).isIntermediate())
3897 // // since there is already an intermediate node for the GLB of implicit
3899 // // we don't need to create another intermediate node.
3900 // // just re-use the intermediate node for implicit flows.
3902 // FlowNode meetNode =
3903 // fg.getFlowNode(implicitFlowTupleSet.iterator().next());
3905 // for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
3906 // NTuple<Descriptor> returnNodeTuple = (NTuple<Descriptor>)
3908 // fg.addValueFlowEdge(returnNodeTuple, meetNode.getDescTuple());
3913 NodeTupleSet currentFlowTupleSet = new NodeTupleSet();
3915 // add tuples from return node
3916 currentFlowTupleSet.addTupleSet(nodeSet);
3918 // add tuples corresponding to the current implicit flows
3919 currentFlowTupleSet.addTupleSet(implicitFlowTupleSet);
3921 if (currentFlowTupleSet.size() > 1) {
3922 FlowNode meetNode = fg.createIntermediateNode();
3923 for (Iterator iterator = currentFlowTupleSet.iterator(); iterator.hasNext();) {
3924 NTuple<Descriptor> currentFlowTuple = (NTuple<Descriptor>) iterator.next();
3925 fg.addValueFlowEdge(currentFlowTuple, meetNode.getDescTuple());
3927 fg.addReturnFlowNode(meetNode.getDescTuple());
3928 } else if (currentFlowTupleSet.size() == 1) {
3929 NTuple<Descriptor> tuple = currentFlowTupleSet.iterator().next();
3930 fg.addReturnFlowNode(tuple);
3937 private void analyzeFlowLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln,
3938 NodeTupleSet implicitFlowTupleSet) {
3940 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
3942 NodeTupleSet condTupleNode = new NodeTupleSet();
3943 analyzeFlowExpressionNode(md, nametable, ln.getCondition(), condTupleNode, null,
3944 implicitFlowTupleSet, false);
3946 NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
3948 newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
3949 newImplicitTupleSet.addTupleSet(condTupleNode);
3951 if (newImplicitTupleSet.size() > 1) {
3952 // need to create an intermediate node for the GLB of conditional
3953 // locations & implicit flows
3954 NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
3955 for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter
3957 NTuple<Descriptor> tuple = idxIter.next();
3958 addFlowGraphEdge(md, tuple, interTuple);
3960 newImplicitTupleSet.clear();
3961 newImplicitTupleSet.addTuple(interTuple);
3966 // System.out.println("condTupleNode="+condTupleNode);
3967 // NTuple<Descriptor> interTuple =
3968 // getFlowGraph(md).createIntermediateNode().getDescTuple();
3970 // for (Iterator<NTuple<Descriptor>> idxIter = condTupleNode.iterator();
3971 // idxIter.hasNext();) {
3972 // NTuple<Descriptor> tuple = idxIter.next();
3973 // addFlowGraphEdge(md, tuple, interTuple);
3976 // for (Iterator<NTuple<Descriptor>> idxIter =
3977 // implicitFlowTupleSet.iterator(); idxIter
3979 // NTuple<Descriptor> tuple = idxIter.next();
3980 // addFlowGraphEdge(md, tuple, interTuple);
3983 // NodeTupleSet newImplicitSet = new NodeTupleSet();
3984 // newImplicitSet.addTuple(interTuple);
3985 analyzeFlowBlockNode(md, nametable, ln.getBody(), newImplicitTupleSet);
3988 // condTupleNode.addTupleSet(implicitFlowTupleSet);
3990 // add edges from condNodeTupleSet to all nodes of conditional nodes
3991 // analyzeFlowBlockNode(md, nametable, ln.getBody(), condTupleNode);
3994 // check 'for loop' case
3995 BlockNode bn = ln.getInitializer();
3996 bn.getVarTable().setParent(nametable);
3997 for (int i = 0; i < bn.size(); i++) {
3998 BlockStatementNode bsn = bn.get(i);
3999 analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
4002 NodeTupleSet condTupleNode = new NodeTupleSet();
4003 analyzeFlowExpressionNode(md, bn.getVarTable(), ln.getCondition(), condTupleNode, null,
4004 implicitFlowTupleSet, false);
4007 NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4009 for (Iterator<NTuple<Descriptor>> idxIter = condTupleNode.iterator(); idxIter.hasNext();) {
4010 NTuple<Descriptor> tuple = idxIter.next();
4011 addFlowGraphEdge(md, tuple, interTuple);
4014 for (Iterator<NTuple<Descriptor>> idxIter = implicitFlowTupleSet.iterator(); idxIter
4016 NTuple<Descriptor> tuple = idxIter.next();
4017 addFlowGraphEdge(md, tuple, interTuple);
4020 NodeTupleSet newImplicitSet = new NodeTupleSet();
4021 newImplicitSet.addTuple(interTuple);
4022 analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(), newImplicitSet);
4023 analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(), newImplicitSet);
4026 // condTupleNode.addTupleSet(implicitFlowTupleSet);
4028 // analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(),
4030 // analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(),
4037 private void analyzeFlowIfStatementNode(MethodDescriptor md, SymbolTable nametable,
4038 IfStatementNode isn, NodeTupleSet implicitFlowTupleSet) {
4040 System.out.println("analyzeFlowIfStatementNode=" + isn.printNode(0));
4042 NodeTupleSet condTupleNode = new NodeTupleSet();
4043 analyzeFlowExpressionNode(md, nametable, isn.getCondition(), condTupleNode, null,
4044 implicitFlowTupleSet, false);
4046 NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
4048 newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
4049 newImplicitTupleSet.addTupleSet(condTupleNode);
4051 System.out.println("condTupleNode=" + condTupleNode);
4052 System.out.println("implicitFlowTupleSet=" + implicitFlowTupleSet);
4053 System.out.println("newImplicitTupleSet=" + newImplicitTupleSet);
4055 if (newImplicitTupleSet.size() > 1) {
4057 // need to create an intermediate node for the GLB of conditional locations & implicit flows
4058 NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4059 for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter.hasNext();) {
4060 NTuple<Descriptor> tuple = idxIter.next();
4061 addFlowGraphEdge(md, tuple, interTuple);
4063 newImplicitTupleSet.clear();
4064 newImplicitTupleSet.addTuple(interTuple);
4067 analyzeFlowBlockNode(md, nametable, isn.getTrueBlock(), newImplicitTupleSet);
4069 if (isn.getFalseBlock() != null) {
4070 analyzeFlowBlockNode(md, nametable, isn.getFalseBlock(), newImplicitTupleSet);
4075 private void analyzeFlowDeclarationNode(MethodDescriptor md, SymbolTable nametable,
4076 DeclarationNode dn, NodeTupleSet implicitFlowTupleSet) {
4078 VarDescriptor vd = dn.getVarDescriptor();
4079 mapDescToDefinitionLine.put(vd, dn.getNumLine());
4080 NTuple<Descriptor> tupleLHS = new NTuple<Descriptor>();
4082 FlowNode fn = getFlowGraph(md).createNewFlowNode(tupleLHS);
4083 fn.setDeclarationNode();
4085 if (dn.getExpression() != null) {
4087 NodeTupleSet nodeSetRHS = new NodeTupleSet();
4088 analyzeFlowExpressionNode(md, nametable, dn.getExpression(), nodeSetRHS, null,
4089 implicitFlowTupleSet, false);
4091 // creates edges from RHS to LHS
4092 NTuple<Descriptor> interTuple = null;
4093 if (nodeSetRHS.size() > 1) {
4094 interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4097 for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
4098 NTuple<Descriptor> fromTuple = iter.next();
4099 addFlowGraphEdge(md, fromTuple, interTuple, tupleLHS);
4102 // creates edges from implicitFlowTupleSet to LHS
4103 for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
4104 NTuple<Descriptor> implicitTuple = iter.next();
4105 addFlowGraphEdge(md, implicitTuple, tupleLHS);
4112 private void analyzeBlockExpressionNode(MethodDescriptor md, SymbolTable nametable,
4113 BlockExpressionNode ben, NodeTupleSet implicitFlowTupleSet) {
4114 analyzeFlowExpressionNode(md, nametable, ben.getExpression(), null, null, implicitFlowTupleSet,
4118 private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
4119 ExpressionNode en, NodeTupleSet nodeSet, boolean isLHS) {
4120 return analyzeFlowExpressionNode(md, nametable, en, nodeSet, null, new NodeTupleSet(), isLHS);
4123 private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
4124 ExpressionNode en, NodeTupleSet nodeSet, NTuple<Descriptor> base,
4125 NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
4127 // note that expression node can create more than one flow node
4128 // nodeSet contains of flow nodes
4129 // base is always assigned to null except the case of a name node!
4131 NTuple<Descriptor> flowTuple;
4133 switch (en.kind()) {
4135 case Kind.AssignmentNode:
4136 analyzeFlowAssignmentNode(md, nametable, (AssignmentNode) en, nodeSet, base,
4137 implicitFlowTupleSet);
4140 case Kind.FieldAccessNode:
4142 analyzeFlowFieldAccessNode(md, nametable, (FieldAccessNode) en, nodeSet, base,
4143 implicitFlowTupleSet, isLHS);
4144 if (flowTuple != null) {
4145 nodeSet.addTuple(flowTuple);
4150 NodeTupleSet nameNodeSet = new NodeTupleSet();
4152 analyzeFlowNameNode(md, nametable, (NameNode) en, nameNodeSet, base, implicitFlowTupleSet);
4153 if (flowTuple != null) {
4154 nodeSet.addTuple(flowTuple);
4159 analyzeFlowOpNode(md, nametable, (OpNode) en, nodeSet, implicitFlowTupleSet);
4162 case Kind.CreateObjectNode:
4163 analyzeCreateObjectNode(md, nametable, (CreateObjectNode) en);
4166 case Kind.ArrayAccessNode:
4167 analyzeFlowArrayAccessNode(md, nametable, (ArrayAccessNode) en, nodeSet, isLHS);
4170 case Kind.LiteralNode:
4171 analyzeLiteralNode(md, nametable, (LiteralNode) en);
4174 case Kind.MethodInvokeNode:
4175 analyzeFlowMethodInvokeNode(md, nametable, (MethodInvokeNode) en, nodeSet,
4176 implicitFlowTupleSet);
4179 case Kind.TertiaryNode:
4180 analyzeFlowTertiaryNode(md, nametable, (TertiaryNode) en, nodeSet, implicitFlowTupleSet);
4184 analyzeFlowCastNode(md, nametable, (CastNode) en, nodeSet, base, implicitFlowTupleSet);
4186 // case Kind.InstanceOfNode:
4187 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
4190 // case Kind.ArrayInitializerNode:
4191 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
4195 // case Kind.ClassTypeNode:
4196 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
4199 // case Kind.OffsetNode:
4200 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
4208 private void analyzeFlowCastNode(MethodDescriptor md, SymbolTable nametable, CastNode cn,
4209 NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
4211 analyzeFlowExpressionNode(md, nametable, cn.getExpression(), nodeSet, base,
4212 implicitFlowTupleSet, false);
4216 private void analyzeFlowTertiaryNode(MethodDescriptor md, SymbolTable nametable, TertiaryNode tn,
4217 NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
4219 NodeTupleSet tertiaryTupleNode = new NodeTupleSet();
4220 analyzeFlowExpressionNode(md, nametable, tn.getCond(), tertiaryTupleNode, null,
4221 implicitFlowTupleSet, false);
4223 // add edges from tertiaryTupleNode to all nodes of conditional nodes
4224 tertiaryTupleNode.addTupleSet(implicitFlowTupleSet);
4225 analyzeFlowExpressionNode(md, nametable, tn.getTrueExpr(), tertiaryTupleNode, null,
4226 implicitFlowTupleSet, false);
4228 analyzeFlowExpressionNode(md, nametable, tn.getFalseExpr(), tertiaryTupleNode, null,
4229 implicitFlowTupleSet, false);
4231 nodeSet.addTupleSet(tertiaryTupleNode);
4235 private void addMapCallerMethodDescToMethodInvokeNodeSet(MethodDescriptor caller,
4236 MethodInvokeNode min) {
4237 Set<MethodInvokeNode> set = mapMethodDescriptorToMethodInvokeNodeSet.get(caller);
4239 set = new HashSet<MethodInvokeNode>();
4240 mapMethodDescriptorToMethodInvokeNodeSet.put(caller, set);
4245 private void addParamNodeFlowingToReturnValue(MethodDescriptor md, FlowNode fn) {
4247 if (!mapMethodDescToParamNodeFlowsToReturnValue.containsKey(md)) {
4248 mapMethodDescToParamNodeFlowsToReturnValue.put(md, new HashSet<FlowNode>());
4250 mapMethodDescToParamNodeFlowsToReturnValue.get(md).add(fn);
4253 private Set<FlowNode> getParamNodeFlowingToReturnValue(MethodDescriptor md) {
4255 if (!mapMethodDescToParamNodeFlowsToReturnValue.containsKey(md)) {
4256 mapMethodDescToParamNodeFlowsToReturnValue.put(md, new HashSet<FlowNode>());
4259 return mapMethodDescToParamNodeFlowsToReturnValue.get(md);
4262 private void analyzeFlowMethodInvokeNode(MethodDescriptor md, SymbolTable nametable,
4263 MethodInvokeNode min, NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
4265 System.out.println("analyzeFlowMethodInvokeNode=" + min.printNode(0));
4267 mapMethodInvokeNodeToArgIdxMap.put(min, new HashMap<Integer, NTuple<Descriptor>>());
4269 if (nodeSet == null) {
4270 nodeSet = new NodeTupleSet();
4273 MethodDescriptor calleeMethodDesc = min.getMethod();
4275 NameDescriptor baseName = min.getBaseName();
4276 boolean isSystemout = false;
4277 if (baseName != null) {
4278 isSystemout = baseName.getSymbol().equals("System.out");
4281 if (!ssjava.isSSJavaUtil(calleeMethodDesc.getClassDesc())
4282 && !ssjava.isTrustMethod(calleeMethodDesc) && !isSystemout) {
4284 addMapCallerMethodDescToMethodInvokeNodeSet(md, min);
4286 FlowGraph calleeFlowGraph = getFlowGraph(calleeMethodDesc);
4287 Set<FlowNode> calleeReturnSet = calleeFlowGraph.getReturnNodeSet();
4289 if (min.getExpression() != null) {
4291 NodeTupleSet baseNodeSet = new NodeTupleSet();
4292 analyzeFlowExpressionNode(md, nametable, min.getExpression(), baseNodeSet, null,
4293 implicitFlowTupleSet, false);
4295 assert (baseNodeSet.size() == 1);
4296 NTuple<Descriptor> baseTuple = baseNodeSet.iterator().next();
4297 mapMethodInvokeNodeToBaseTuple.put(min, baseTuple);
4299 if (!min.getMethod().isStatic()) {
4300 addArgIdxMap(min, 0, baseTuple);
4302 for (Iterator iterator = calleeReturnSet.iterator(); iterator.hasNext();) {
4303 FlowNode returnNode = (FlowNode) iterator.next();
4304 NTuple<Descriptor> returnDescTuple = returnNode.getDescTuple();
4305 if (returnDescTuple.startsWith(calleeMethodDesc.getThis())) {
4306 // the location type of the return value is started with 'this'
4308 NTuple<Descriptor> inFlowTuple = new NTuple<Descriptor>(baseTuple.getList());
4309 inFlowTuple.addAll(returnDescTuple.subList(1, returnDescTuple.size()));
4310 nodeSet.addTuple(inFlowTuple);
4313 Set<FlowNode> inFlowSet = calleeFlowGraph.getIncomingFlowNodeSet(returnNode);
4314 System.out.println("inFlowSet=" + inFlowSet + " from retrunNode=" + returnNode);
4315 for (Iterator iterator2 = inFlowSet.iterator(); iterator2.hasNext();) {
4316 FlowNode inFlowNode = (FlowNode) iterator2.next();
4317 if (inFlowNode.getDescTuple().startsWith(calleeMethodDesc.getThis())) {
4318 nodeSet.addTupleSet(baseNodeSet);
4327 // analyze parameter flows
4329 if (min.numArgs() > 0) {
4332 if (min.getMethod().isStatic()) {
4338 for (int i = 0; i < min.numArgs(); i++) {
4339 ExpressionNode en = min.getArg(i);
4340 int idx = i + offset;
4341 NodeTupleSet argTupleSet = new NodeTupleSet();
4342 analyzeFlowExpressionNode(md, nametable, en, argTupleSet, false);
4343 // if argument is liternal node, argTuple is set to NULL
4345 NTuple<Descriptor> argTuple = new NTuple<Descriptor>();
4346 System.out.println("-argTupleSet=" + argTupleSet + " from en=" + en.printNode(0));
4347 if (argTupleSet.size() > 1) {
4348 NTuple<Descriptor> interTuple =
4349 getFlowGraph(md).createIntermediateNode().getDescTuple();
4350 for (Iterator<NTuple<Descriptor>> idxIter = argTupleSet.iterator(); idxIter.hasNext();) {
4351 NTuple<Descriptor> tuple = idxIter.next();
4352 addFlowGraphEdge(md, tuple, interTuple);
4354 argTuple = interTuple;
4355 } else if (argTupleSet.size() == 1) {
4356 argTuple = argTupleSet.iterator().next();
4358 argTuple = new NTuple<Descriptor>();
4361 addArgIdxMap(min, idx, argTuple);
4363 FlowNode paramNode = calleeFlowGraph.getParamFlowNode(idx);
4364 if (hasInFlowTo(calleeFlowGraph, paramNode, calleeReturnSet)
4365 || calleeMethodDesc.getModifiers().isNative()) {
4366 addParamNodeFlowingToReturnValue(calleeMethodDesc, paramNode);
4367 nodeSet.addTupleSet(argTupleSet);
4373 // propagateFlowsFromCallee(min, md, min.getMethod());
4375 System.out.println("min nodeSet=" + nodeSet);
4380 private boolean hasInFlowTo(FlowGraph fg, FlowNode inNode, Set<FlowNode> nodeSet) {
4381 // return true if inNode has in-flows to nodeSet
4383 // Set<FlowNode> reachableSet = fg.getReachFlowNodeSetFrom(inNode);
4384 Set<FlowNode> reachableSet = fg.getReachableSetFrom(inNode.getDescTuple());
4385 System.out.println("inNode=" + inNode + " reachalbeSet=" + reachableSet);
4387 for (Iterator iterator = reachableSet.iterator(); iterator.hasNext();) {
4388 FlowNode fn = (FlowNode) iterator.next();
4389 if (nodeSet.contains(fn)) {
4396 private NTuple<Descriptor> getNodeTupleByArgIdx(MethodInvokeNode min, int idx) {
4397 return mapMethodInvokeNodeToArgIdxMap.get(min).get(new Integer(idx));
4400 private void addArgIdxMap(MethodInvokeNode min, int idx, NTuple<Descriptor> argTuple /*
4404 Map<Integer, NTuple<Descriptor>> mapIdxToTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
4405 if (mapIdxToTuple == null) {
4406 mapIdxToTuple = new HashMap<Integer, NTuple<Descriptor>>();
4407 mapMethodInvokeNodeToArgIdxMap.put(min, mapIdxToTuple);
4409 mapIdxToTuple.put(new Integer(idx), argTuple);
4412 private void analyzeLiteralNode(MethodDescriptor md, SymbolTable nametable, LiteralNode en) {
4416 private void analyzeFlowArrayAccessNode(MethodDescriptor md, SymbolTable nametable,
4417 ArrayAccessNode aan, NodeTupleSet nodeSet, boolean isLHS) {
4419 NodeTupleSet expNodeTupleSet = new NodeTupleSet();
4420 NTuple<Descriptor> base =
4421 analyzeFlowExpressionNode(md, nametable, aan.getExpression(), expNodeTupleSet, isLHS);
4423 NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
4424 analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, isLHS);
4427 // need to create an edge from idx to array
4428 for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
4429 NTuple<Descriptor> idxTuple = idxIter.next();
4430 for (Iterator<NTuple<Descriptor>> arrIter = expNodeTupleSet.iterator(); arrIter.hasNext();) {
4431 NTuple<Descriptor> arrTuple = arrIter.next();
4432 getFlowGraph(md).addValueFlowEdge(idxTuple, arrTuple);
4436 nodeSet.addTupleSet(expNodeTupleSet);
4438 nodeSet.addTupleSet(expNodeTupleSet);
4439 nodeSet.addTupleSet(idxNodeTupleSet);
4443 private void analyzeCreateObjectNode(MethodDescriptor md, SymbolTable nametable,
4444 CreateObjectNode en) {
4445 // TODO Auto-generated method stub
4449 private void analyzeFlowOpNode(MethodDescriptor md, SymbolTable nametable, OpNode on,
4450 NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
4452 NodeTupleSet leftOpSet = new NodeTupleSet();
4453 NodeTupleSet rightOpSet = new NodeTupleSet();
4456 analyzeFlowExpressionNode(md, nametable, on.getLeft(), leftOpSet, null, implicitFlowTupleSet,
4459 if (on.getRight() != null) {
4461 analyzeFlowExpressionNode(md, nametable, on.getRight(), rightOpSet, null,
4462 implicitFlowTupleSet, false);
4465 Operation op = on.getOp();
4467 switch (op.getOp()) {
4469 case Operation.UNARYPLUS:
4470 case Operation.UNARYMINUS:
4471 case Operation.LOGIC_NOT:
4473 nodeSet.addTupleSet(leftOpSet);
4476 case Operation.LOGIC_OR:
4477 case Operation.LOGIC_AND:
4478 case Operation.COMP:
4479 case Operation.BIT_OR:
4480 case Operation.BIT_XOR:
4481 case Operation.BIT_AND:
4482 case Operation.ISAVAILABLE:
4483 case Operation.EQUAL:
4484 case Operation.NOTEQUAL:
4491 case Operation.MULT:
4494 case Operation.LEFTSHIFT:
4495 case Operation.RIGHTSHIFT:
4496 case Operation.URIGHTSHIFT:
4498 // there are two operands
4499 nodeSet.addTupleSet(leftOpSet);
4500 nodeSet.addTupleSet(rightOpSet);
4504 throw new Error(op.toString());
4509 private NTuple<Descriptor> analyzeFlowNameNode(MethodDescriptor md, SymbolTable nametable,
4510 NameNode nn, NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
4512 // System.out.println("analyzeFlowNameNode=" + nn.printNode(0));
4515 base = new NTuple<Descriptor>();
4518 NameDescriptor nd = nn.getName();
4520 if (nd.getBase() != null) {
4522 analyzeFlowExpressionNode(md, nametable, nn.getExpression(), nodeSet, base,
4523 implicitFlowTupleSet, false);
4525 // base node has the top location
4529 String varname = nd.toString();
4530 if (varname.equals("this")) {
4532 base.add(md.getThis());
4536 Descriptor d = (Descriptor) nametable.get(varname);
4538 if (d instanceof VarDescriptor) {
4539 VarDescriptor vd = (VarDescriptor) d;
4541 } else if (d instanceof FieldDescriptor) {
4542 // the type of field descriptor has a location!
4543 FieldDescriptor fd = (FieldDescriptor) d;
4544 if (fd.isStatic()) {
4546 // if it is 'static final', no need to have flow node for the TOP
4550 // if 'static', assign the default GLOBAL LOCATION to the first
4551 // element of the tuple
4552 base.add(GLOBALDESC);
4555 // the location of field access starts from this, followed by field
4557 base.add(md.getThis());
4561 } else if (d == null) {
4562 // access static field
4563 base.add(GLOBALDESC);
4564 base.add(nn.getField());
4567 // FieldDescriptor fd = nn.getField();addFlowGraphEdge
4569 // MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
4570 // String globalLocId = localLattice.getGlobalLoc();
4571 // if (globalLocId == null) {
4573 // Error("Method lattice does not define global variable location at "
4574 // + generateErrorMessage(md.getClassDesc(), nn));
4576 // loc.addLocation(new Location(md, globalLocId));
4578 // Location fieldLoc = (Location) fd.getType().getExtension();
4579 // loc.addLocation(fieldLoc);
4585 getFlowGraph(md).createNewFlowNode(base);
4591 private NTuple<Descriptor> analyzeFlowFieldAccessNode(MethodDescriptor md, SymbolTable nametable,
4592 FieldAccessNode fan, NodeTupleSet nodeSet, NTuple<Descriptor> base,
4593 NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
4595 ExpressionNode left = fan.getExpression();
4596 TypeDescriptor ltd = left.getType();
4597 FieldDescriptor fd = fan.getField();
4599 String varName = null;
4600 if (left.kind() == Kind.NameNode) {
4601 NameDescriptor nd = ((NameNode) left).getName();
4602 varName = nd.toString();
4605 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
4606 // using a class name directly or access using this
4607 if (fd.isStatic() && fd.isFinal()) {
4612 NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
4614 if (left instanceof ArrayAccessNode) {
4616 ArrayAccessNode aan = (ArrayAccessNode) left;
4617 left = aan.getExpression();
4618 analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, base,
4619 implicitFlowTupleSet, isLHS);
4621 nodeSet.addTupleSet(idxNodeTupleSet);
4624 analyzeFlowExpressionNode(md, nametable, left, nodeSet, base, implicitFlowTupleSet, isLHS);
4627 // in this case, field is TOP location
4631 NTuple<Descriptor> flowFieldTuple = new NTuple<Descriptor>(base.toList());
4633 if (!left.getType().isPrimitive()) {
4635 if (!fd.getSymbol().equals("length")) {
4636 // array.length access, just have the location of the array
4637 flowFieldTuple.add(fd);
4638 nodeSet.removeTuple(base);
4642 getFlowGraph(md).createNewFlowNode(flowFieldTuple);
4645 for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
4646 NTuple<Descriptor> idxTuple = idxIter.next();
4647 getFlowGraph(md).addValueFlowEdge(idxTuple, flowFieldTuple);
4650 return flowFieldTuple;
4656 private void debug_printTreeNode(TreeNode tn) {
4658 System.out.println("DEBUG: " + tn.printNode(0) + " line#=" + tn.getNumLine());
4662 private void analyzeFlowAssignmentNode(MethodDescriptor md, SymbolTable nametable,
4663 AssignmentNode an, NodeTupleSet nodeSet, NTuple<Descriptor> base,
4664 NodeTupleSet implicitFlowTupleSet) {
4666 NodeTupleSet nodeSetRHS = new NodeTupleSet();
4667 NodeTupleSet nodeSetLHS = new NodeTupleSet();
4669 boolean postinc = true;
4670 if (an.getOperation().getBaseOp() == null
4671 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
4672 .getBaseOp().getOp() != Operation.POSTDEC)) {
4675 // if LHS is array access node, need to capture value flows between an array
4676 // and its index value
4677 analyzeFlowExpressionNode(md, nametable, an.getDest(), nodeSetLHS, null, implicitFlowTupleSet,
4681 // analyze value flows of rhs expression
4682 analyzeFlowExpressionNode(md, nametable, an.getSrc(), nodeSetRHS, null, implicitFlowTupleSet,
4685 // System.out.println("-analyzeFlowAssignmentNode=" + an.printNode(0));
4686 // System.out.println("-nodeSetLHS=" + nodeSetLHS);
4687 // System.out.println("-nodeSetRHS=" + nodeSetRHS);
4688 // System.out.println("-implicitFlowTupleSet=" + implicitFlowTupleSet);
4689 // System.out.println("-");
4691 if (an.getOperation().getOp() >= 2 && an.getOperation().getOp() <= 12) {
4692 // if assignment contains OP+EQ operator, creates edges from LHS to LHS
4694 for (Iterator<NTuple<Descriptor>> iter = nodeSetLHS.iterator(); iter.hasNext();) {
4695 NTuple<Descriptor> fromTuple = iter.next();
4696 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4697 NTuple<Descriptor> toTuple = iter2.next();
4698 addFlowGraphEdge(md, fromTuple, toTuple);
4703 // creates edges from RHS to LHS
4704 NTuple<Descriptor> interTuple = null;
4705 if (nodeSetRHS.size() > 1) {
4706 interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
4709 for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
4710 NTuple<Descriptor> fromTuple = iter.next();
4711 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4712 NTuple<Descriptor> toTuple = iter2.next();
4713 addFlowGraphEdge(md, fromTuple, interTuple, toTuple);
4717 // creates edges from implicitFlowTupleSet to LHS
4718 for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
4719 NTuple<Descriptor> fromTuple = iter.next();
4720 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4721 NTuple<Descriptor> toTuple = iter2.next();
4722 addFlowGraphEdge(md, fromTuple, toTuple);
4729 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4730 NTuple<Descriptor> tuple = iter2.next();
4731 addFlowGraphEdge(md, tuple, tuple);
4734 // creates edges from implicitFlowTupleSet to LHS
4735 for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
4736 NTuple<Descriptor> fromTuple = iter.next();
4737 for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
4738 NTuple<Descriptor> toTuple = iter2.next();
4739 addFlowGraphEdge(md, fromTuple, toTuple);
4745 if (nodeSet != null) {
4746 nodeSet.addTupleSet(nodeSetLHS);
4750 public FlowGraph getFlowGraph(MethodDescriptor md) {
4751 return mapMethodDescriptorToFlowGraph.get(md);
4754 private boolean addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
4755 NTuple<Descriptor> to) {
4756 FlowGraph graph = getFlowGraph(md);
4757 graph.addValueFlowEdge(from, to);
4761 private void addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
4762 NTuple<Descriptor> inter, NTuple<Descriptor> to) {
4764 FlowGraph graph = getFlowGraph(md);
4766 if (inter != null) {
4767 graph.addValueFlowEdge(from, inter);
4768 graph.addValueFlowEdge(inter, to);
4770 graph.addValueFlowEdge(from, to);
4775 public void writeInferredLatticeDotFile(ClassDescriptor cd, HierarchyGraph simpleHierarchyGraph,
4776 SSJavaLattice<String> locOrder, String nameSuffix) {
4777 writeInferredLatticeDotFile(cd, null, simpleHierarchyGraph, locOrder, nameSuffix);
4780 public void writeInferredLatticeDotFile(ClassDescriptor cd, MethodDescriptor md,
4781 HierarchyGraph simpleHierarchyGraph, SSJavaLattice<String> locOrder, String nameSuffix) {
4783 String fileName = "lattice_";
4786 cd.getSymbol().replaceAll("[\\W_]", "") + "_" + md.toString().replaceAll("[\\W_]", "");
4788 fileName += cd.getSymbol().replaceAll("[\\W_]", "");
4791 fileName += nameSuffix;
4793 Set<Pair<String, String>> pairSet = locOrder.getOrderingPairSet();
4795 Set<String> addedLocSet = new HashSet<String>();
4797 if (pairSet.size() > 0) {
4799 BufferedWriter bw = new BufferedWriter(new FileWriter(fileName + ".dot"));
4801 bw.write("digraph " + fileName + " {\n");
4803 for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
4804 // pair is in the form of <higher, lower>
4805 Pair<String, String> pair = (Pair<String, String>) iterator.next();
4807 String highLocId = pair.getFirst();
4808 String lowLocId = pair.getSecond();
4810 if (!addedLocSet.contains(highLocId)) {
4811 addedLocSet.add(highLocId);
4812 drawNode(bw, locOrder, simpleHierarchyGraph, highLocId);
4815 if (!addedLocSet.contains(lowLocId)) {
4816 addedLocSet.add(lowLocId);
4817 drawNode(bw, locOrder, simpleHierarchyGraph, lowLocId);
4820 bw.write(highLocId + " -> " + lowLocId + ";\n");
4825 } catch (IOException e) {
4826 e.printStackTrace();
4833 private String convertMergeSetToString(HierarchyGraph graph, Set<HNode> mergeSet) {
4835 for (Iterator iterator = mergeSet.iterator(); iterator.hasNext();) {
4836 HNode merged = (HNode) iterator.next();
4837 if (merged.isMergeNode()) {
4838 str += convertMergeSetToString(graph, graph.getMapHNodetoMergeSet().get(merged));
4840 str += " " + merged.getName();
4846 private void drawNode(BufferedWriter bw, SSJavaLattice<String> lattice, HierarchyGraph graph,
4847 String locName) throws IOException {
4849 HNode node = graph.getHNode(locName);
4856 if (lattice.isSharedLoc(locName)) {
4857 prettyStr = locName + "*";
4859 prettyStr = locName;
4862 if (node.isMergeNode()) {
4863 Set<HNode> mergeSet = graph.getMapHNodetoMergeSet().get(node);
4864 prettyStr += ":" + convertMergeSetToString(graph, mergeSet);
4866 bw.write(locName + " [label=\"" + prettyStr + "\"]" + ";\n");
4869 public void _debug_printGraph() {
4870 Set<MethodDescriptor> keySet = mapMethodDescriptorToFlowGraph.keySet();
4872 for (Iterator<MethodDescriptor> iterator = keySet.iterator(); iterator.hasNext();) {
4873 MethodDescriptor md = (MethodDescriptor) iterator.next();
4874 FlowGraph fg = mapMethodDescriptorToFlowGraph.get(md);
4877 } catch (IOException e) {
4878 e.printStackTrace();
4886 class CyclicFlowException extends Exception {
4890 class InterDescriptor extends Descriptor {
4892 public InterDescriptor(String name) {